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 <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = 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 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const struct got_error *
713 get_signer_id(char **signer_id, struct got_repository *repo,
714 struct got_worktree *worktree)
716 const char *got_signer_id = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 *signer_id = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 if (got_signer_id) {
738 *signer_id = strdup(got_signer_id);
739 if (*signer_id == NULL)
740 return got_error_from_errno("strdup");
742 return NULL;
745 static const struct got_error *
746 get_gitconfig_path(char **gitconfig_path)
748 const char *homedir = getenv("HOME");
750 *gitconfig_path = NULL;
751 if (homedir) {
752 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
753 return got_error_from_errno("asprintf");
756 return NULL;
759 static const struct got_error *
760 cmd_import(int argc, char *argv[])
762 const struct got_error *error = NULL;
763 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
764 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
765 const char *branch_name = NULL;
766 char *id_str = NULL, *logmsg_path = NULL;
767 char refname[PATH_MAX] = "refs/heads/";
768 struct got_repository *repo = NULL;
769 struct got_reference *branch_ref = NULL, *head_ref = NULL;
770 struct got_object_id *new_commit_id = NULL;
771 int ch, n = 0;
772 struct got_pathlist_head ignores;
773 struct got_pathlist_entry *pe;
774 int preserve_logmsg = 0;
775 int *pack_fds = NULL;
777 TAILQ_INIT(&ignores);
779 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
780 switch (ch) {
781 case 'b':
782 branch_name = optarg;
783 break;
784 case 'I':
785 if (optarg[0] == '\0')
786 break;
787 error = got_pathlist_insert(&pe, &ignores, optarg,
788 NULL);
789 if (error)
790 goto done;
791 break;
792 case 'm':
793 logmsg = strdup(optarg);
794 if (logmsg == NULL) {
795 error = got_error_from_errno("strdup");
796 goto done;
798 break;
799 case 'r':
800 repo_path = realpath(optarg, NULL);
801 if (repo_path == NULL) {
802 error = got_error_from_errno2("realpath",
803 optarg);
804 goto done;
806 break;
807 default:
808 usage_import();
809 /* NOTREACHED */
813 argc -= optind;
814 argv += optind;
816 #ifndef PROFILE
817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
818 "unveil",
819 NULL) == -1)
820 err(1, "pledge");
821 #endif
822 if (argc != 1)
823 usage_import();
825 if (repo_path == NULL) {
826 repo_path = getcwd(NULL, 0);
827 if (repo_path == NULL)
828 return got_error_from_errno("getcwd");
830 got_path_strip_trailing_slashes(repo_path);
831 error = get_gitconfig_path(&gitconfig_path);
832 if (error)
833 goto done;
834 error = got_repo_pack_fds_open(&pack_fds);
835 if (error != NULL)
836 goto done;
837 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
838 if (error)
839 goto done;
841 error = get_author(&author, repo, NULL);
842 if (error)
843 return error;
845 /*
846 * Don't let the user create a branch name with a leading '-'.
847 * While technically a valid reference name, this case is usually
848 * an unintended typo.
849 */
850 if (branch_name && branch_name[0] == '-')
851 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
854 if (error && error->code != GOT_ERR_NOT_REF)
855 goto done;
857 if (branch_name)
858 n = strlcat(refname, branch_name, sizeof(refname));
859 else if (head_ref && got_ref_is_symbolic(head_ref))
860 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
861 sizeof(refname));
862 else
863 n = strlcat(refname, "main", sizeof(refname));
864 if (n >= sizeof(refname)) {
865 error = got_error(GOT_ERR_NO_SPACE);
866 goto done;
869 error = got_ref_open(&branch_ref, repo, refname, 0);
870 if (error) {
871 if (error->code != GOT_ERR_NOT_REF)
872 goto done;
873 } else {
874 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
875 "import target branch already exists");
876 goto done;
879 path_dir = realpath(argv[0], NULL);
880 if (path_dir == NULL) {
881 error = got_error_from_errno2("realpath", argv[0]);
882 goto done;
884 got_path_strip_trailing_slashes(path_dir);
886 /*
887 * unveil(2) traverses exec(2); if an editor is used we have
888 * to apply unveil after the log message has been written.
889 */
890 if (logmsg == NULL || strlen(logmsg) == 0) {
891 error = get_editor(&editor);
892 if (error)
893 goto done;
894 free(logmsg);
895 error = collect_import_msg(&logmsg, &logmsg_path, editor,
896 path_dir, refname);
897 if (error) {
898 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
899 logmsg_path != NULL)
900 preserve_logmsg = 1;
901 goto done;
905 if (unveil(path_dir, "r") != 0) {
906 error = got_error_from_errno2("unveil", path_dir);
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_repo_import(&new_commit_id, path_dir, logmsg,
920 author, &ignores, repo, import_progress, NULL);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_write(branch_ref, repo);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_object_id_str(&id_str, new_commit_id);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
949 if (error) {
950 if (error->code != GOT_ERR_NOT_REF) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
957 branch_ref);
958 if (error) {
959 if (logmsg_path)
960 preserve_logmsg = 1;
961 goto done;
964 error = got_ref_write(head_ref, repo);
965 if (error) {
966 if (logmsg_path)
967 preserve_logmsg = 1;
968 goto done;
972 printf("Created branch %s with commit %s\n",
973 got_ref_get_name(branch_ref), id_str);
974 done:
975 if (pack_fds) {
976 const struct got_error *pack_err =
977 got_repo_pack_fds_close(pack_fds);
978 if (error == NULL)
979 error = pack_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 break;
1582 case 'l':
1583 list_refs_only = 1;
1584 break;
1585 case 'm':
1586 mirror_references = 1;
1587 break;
1588 case 'q':
1589 verbosity = -1;
1590 break;
1591 case 'R':
1592 error = got_pathlist_append(&wanted_refs,
1593 optarg, NULL);
1594 if (error)
1595 return error;
1596 break;
1597 case 'v':
1598 if (verbosity < 0)
1599 verbosity = 0;
1600 else if (verbosity < 3)
1601 verbosity++;
1602 break;
1603 default:
1604 usage_clone();
1605 break;
1608 argc -= optind;
1609 argv += optind;
1611 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('a', 'b');
1613 if (list_refs_only) {
1614 if (!TAILQ_EMPTY(&wanted_branches))
1615 option_conflict('l', 'b');
1616 if (fetch_all_branches)
1617 option_conflict('l', 'a');
1618 if (mirror_references)
1619 option_conflict('l', 'm');
1620 if (!TAILQ_EMPTY(&wanted_refs))
1621 option_conflict('l', 'R');
1624 uri = argv[0];
1626 if (argc == 1)
1627 dirname = NULL;
1628 else if (argc == 2)
1629 dirname = argv[1];
1630 else
1631 usage_clone();
1633 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1634 &repo_name, uri);
1635 if (error)
1636 goto done;
1638 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1639 host, port ? ":" : "", port ? port : "",
1640 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1641 error = got_error_from_errno("asprintf");
1642 goto done;
1645 if (strcmp(proto, "git") == 0) {
1646 #ifndef PROFILE
1647 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1648 "sendfd dns inet unveil", NULL) == -1)
1649 err(1, "pledge");
1650 #endif
1651 } else if (strcmp(proto, "git+ssh") == 0 ||
1652 strcmp(proto, "ssh") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
1658 } else if (strcmp(proto, "http") == 0 ||
1659 strcmp(proto, "git+http") == 0) {
1660 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1661 goto done;
1662 } else {
1663 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1664 goto done;
1666 if (dirname == NULL) {
1667 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1668 error = got_error_from_errno("asprintf");
1669 goto done;
1671 repo_path = default_destdir;
1672 } else
1673 repo_path = dirname;
1675 if (!list_refs_only) {
1676 error = got_path_mkdir(repo_path);
1677 if (error &&
1678 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1679 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1680 goto done;
1681 if (!got_path_dir_is_empty(repo_path)) {
1682 error = got_error_path(repo_path,
1683 GOT_ERR_DIR_NOT_EMPTY);
1684 goto done;
1688 error = got_dial_apply_unveil(proto);
1689 if (error)
1690 goto done;
1692 error = apply_unveil(repo_path, 0, NULL);
1693 if (error)
1694 goto done;
1696 if (verbosity >= 0)
1697 printf("Connecting to %s\n", git_url);
1699 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1700 server_path, verbosity);
1701 if (error)
1702 goto done;
1704 if (!list_refs_only) {
1705 error = got_repo_init(repo_path, NULL);
1706 if (error)
1707 goto done;
1708 error = got_repo_pack_fds_open(&pack_fds);
1709 if (error != NULL)
1710 goto done;
1711 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1712 if (error)
1713 goto done;
1716 fpa.last_scaled_size[0] = '\0';
1717 fpa.last_p_indexed = -1;
1718 fpa.last_p_resolved = -1;
1719 fpa.verbosity = verbosity;
1720 fpa.create_configs = 1;
1721 fpa.configs_created = 0;
1722 fpa.repo = repo;
1723 fpa.config_info.symrefs = &symrefs;
1724 fpa.config_info.wanted_branches = &wanted_branches;
1725 fpa.config_info.wanted_refs = &wanted_refs;
1726 fpa.config_info.proto = proto;
1727 fpa.config_info.host = host;
1728 fpa.config_info.port = port;
1729 fpa.config_info.remote_repo_path = server_path;
1730 fpa.config_info.git_url = git_url;
1731 fpa.config_info.fetch_all_branches = fetch_all_branches;
1732 fpa.config_info.mirror_references = mirror_references;
1733 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1734 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1735 fetch_all_branches, &wanted_branches, &wanted_refs,
1736 list_refs_only, verbosity, fetchfd, repo,
1737 fetch_progress, &fpa);
1738 if (error)
1739 goto done;
1741 if (list_refs_only) {
1742 error = list_remote_refs(&symrefs, &refs);
1743 goto done;
1746 if (pack_hash == NULL) {
1747 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1748 "server sent an empty pack file");
1749 goto done;
1751 error = got_object_id_str(&id_str, pack_hash);
1752 if (error)
1753 goto done;
1754 if (verbosity >= 0)
1755 printf("\nFetched %s.pack\n", id_str);
1756 free(id_str);
1758 /* Set up references provided with the pack file. */
1759 TAILQ_FOREACH(pe, &refs, entry) {
1760 const char *refname = pe->path;
1761 struct got_object_id *id = pe->data;
1762 char *remote_refname;
1764 if (is_wanted_ref(&wanted_refs, refname) &&
1765 !mirror_references) {
1766 error = create_wanted_ref(refname, id,
1767 GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 verbosity - 1, repo);
1769 if (error)
1770 goto done;
1771 continue;
1774 error = create_ref(refname, id, verbosity - 1, repo);
1775 if (error)
1776 goto done;
1778 if (mirror_references)
1779 continue;
1781 if (strncmp("refs/heads/", refname, 11) != 0)
1782 continue;
1784 if (asprintf(&remote_refname,
1785 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1786 refname + 11) == -1) {
1787 error = got_error_from_errno("asprintf");
1788 goto done;
1790 error = create_ref(remote_refname, id, verbosity - 1, repo);
1791 free(remote_refname);
1792 if (error)
1793 goto done;
1796 /* Set the HEAD reference if the server provided one. */
1797 TAILQ_FOREACH(pe, &symrefs, entry) {
1798 struct got_reference *target_ref;
1799 const char *refname = pe->path;
1800 const char *target = pe->data;
1801 char *remote_refname = NULL, *remote_target = NULL;
1803 if (strcmp(refname, GOT_REF_HEAD) != 0)
1804 continue;
1806 error = got_ref_open(&target_ref, repo, target, 0);
1807 if (error) {
1808 if (error->code == GOT_ERR_NOT_REF) {
1809 error = NULL;
1810 continue;
1812 goto done;
1815 error = create_symref(refname, target_ref, verbosity, repo);
1816 got_ref_close(target_ref);
1817 if (error)
1818 goto done;
1820 if (mirror_references)
1821 continue;
1823 if (strncmp("refs/heads/", target, 11) != 0)
1824 continue;
1826 if (asprintf(&remote_refname,
1827 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1828 refname) == -1) {
1829 error = got_error_from_errno("asprintf");
1830 goto done;
1832 if (asprintf(&remote_target,
1833 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1834 target + 11) == -1) {
1835 error = got_error_from_errno("asprintf");
1836 free(remote_refname);
1837 goto done;
1839 error = got_ref_open(&target_ref, repo, remote_target, 0);
1840 if (error) {
1841 free(remote_refname);
1842 free(remote_target);
1843 if (error->code == GOT_ERR_NOT_REF) {
1844 error = NULL;
1845 continue;
1847 goto done;
1849 error = create_symref(remote_refname, target_ref,
1850 verbosity - 1, repo);
1851 free(remote_refname);
1852 free(remote_target);
1853 got_ref_close(target_ref);
1854 if (error)
1855 goto done;
1857 if (pe == NULL) {
1859 * We failed to set the HEAD reference. If we asked for
1860 * a set of wanted branches use the first of one of those
1861 * which could be fetched instead.
1863 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1864 const char *target = pe->path;
1865 struct got_reference *target_ref;
1867 error = got_ref_open(&target_ref, repo, target, 0);
1868 if (error) {
1869 if (error->code == GOT_ERR_NOT_REF) {
1870 error = NULL;
1871 continue;
1873 goto done;
1876 error = create_symref(GOT_REF_HEAD, target_ref,
1877 verbosity, repo);
1878 got_ref_close(target_ref);
1879 if (error)
1880 goto done;
1881 break;
1884 if (!fpa.configs_created && pe != NULL) {
1885 error = create_config_files(fpa.config_info.proto,
1886 fpa.config_info.host, fpa.config_info.port,
1887 fpa.config_info.remote_repo_path,
1888 fpa.config_info.git_url,
1889 fpa.config_info.fetch_all_branches,
1890 fpa.config_info.mirror_references,
1891 fpa.config_info.symrefs,
1892 fpa.config_info.wanted_branches,
1893 fpa.config_info.wanted_refs, fpa.repo);
1894 if (error)
1895 goto done;
1899 if (verbosity >= 0)
1900 printf("Created %s repository '%s'\n",
1901 mirror_references ? "mirrored" : "cloned", repo_path);
1902 done:
1903 if (pack_fds) {
1904 const struct got_error *pack_err =
1905 got_repo_pack_fds_close(pack_fds);
1906 if (error == NULL)
1907 error = pack_err;
1909 if (fetchpid > 0) {
1910 if (kill(fetchpid, SIGTERM) == -1)
1911 error = got_error_from_errno("kill");
1912 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1913 error = got_error_from_errno("waitpid");
1915 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1916 error = got_error_from_errno("close");
1917 if (repo) {
1918 const struct got_error *close_err = got_repo_close(repo);
1919 if (error == NULL)
1920 error = close_err;
1922 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1923 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1924 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1925 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1926 free(pack_hash);
1927 free(proto);
1928 free(host);
1929 free(port);
1930 free(server_path);
1931 free(repo_name);
1932 free(default_destdir);
1933 free(git_url);
1934 return error;
1937 static const struct got_error *
1938 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1939 int replace_tags, int verbosity, struct got_repository *repo)
1941 const struct got_error *err = NULL;
1942 char *new_id_str = NULL;
1943 struct got_object_id *old_id = NULL;
1945 err = got_object_id_str(&new_id_str, new_id);
1946 if (err)
1947 goto done;
1949 if (!replace_tags &&
1950 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1951 err = got_ref_resolve(&old_id, repo, ref);
1952 if (err)
1953 goto done;
1954 if (got_object_id_cmp(old_id, new_id) == 0)
1955 goto done;
1956 if (verbosity >= 0) {
1957 printf("Rejecting update of existing tag %s: %s\n",
1958 got_ref_get_name(ref), new_id_str);
1960 goto done;
1963 if (got_ref_is_symbolic(ref)) {
1964 if (verbosity >= 0) {
1965 printf("Replacing reference %s: %s\n",
1966 got_ref_get_name(ref),
1967 got_ref_get_symref_target(ref));
1969 err = got_ref_change_symref_to_ref(ref, new_id);
1970 if (err)
1971 goto done;
1972 err = got_ref_write(ref, repo);
1973 if (err)
1974 goto done;
1975 } else {
1976 err = got_ref_resolve(&old_id, repo, ref);
1977 if (err)
1978 goto done;
1979 if (got_object_id_cmp(old_id, new_id) == 0)
1980 goto done;
1982 err = got_ref_change_ref(ref, new_id);
1983 if (err)
1984 goto done;
1985 err = got_ref_write(ref, repo);
1986 if (err)
1987 goto done;
1990 if (verbosity >= 0)
1991 printf("Updated %s: %s\n", got_ref_get_name(ref),
1992 new_id_str);
1993 done:
1994 free(old_id);
1995 free(new_id_str);
1996 return err;
1999 static const struct got_error *
2000 update_symref(const char *refname, struct got_reference *target_ref,
2001 int verbosity, struct got_repository *repo)
2003 const struct got_error *err = NULL, *unlock_err;
2004 struct got_reference *symref;
2005 int symref_is_locked = 0;
2007 err = got_ref_open(&symref, repo, refname, 1);
2008 if (err) {
2009 if (err->code != GOT_ERR_NOT_REF)
2010 return err;
2011 err = got_ref_alloc_symref(&symref, refname, target_ref);
2012 if (err)
2013 goto done;
2015 err = got_ref_write(symref, repo);
2016 if (err)
2017 goto done;
2019 if (verbosity >= 0)
2020 printf("Created reference %s: %s\n",
2021 got_ref_get_name(symref),
2022 got_ref_get_symref_target(symref));
2023 } else {
2024 symref_is_locked = 1;
2026 if (strcmp(got_ref_get_symref_target(symref),
2027 got_ref_get_name(target_ref)) == 0)
2028 goto done;
2030 err = got_ref_change_symref(symref,
2031 got_ref_get_name(target_ref));
2032 if (err)
2033 goto done;
2035 err = got_ref_write(symref, repo);
2036 if (err)
2037 goto done;
2039 if (verbosity >= 0)
2040 printf("Updated %s: %s\n", got_ref_get_name(symref),
2041 got_ref_get_symref_target(symref));
2044 done:
2045 if (symref_is_locked) {
2046 unlock_err = got_ref_unlock(symref);
2047 if (unlock_err && err == NULL)
2048 err = unlock_err;
2050 got_ref_close(symref);
2051 return err;
2054 __dead static void
2055 usage_fetch(void)
2057 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2058 "[-R reference] [-r repository-path] [remote-repository]\n",
2059 getprogname());
2060 exit(1);
2063 static const struct got_error *
2064 delete_missing_ref(struct got_reference *ref,
2065 int verbosity, struct got_repository *repo)
2067 const struct got_error *err = NULL;
2068 struct got_object_id *id = NULL;
2069 char *id_str = NULL;
2071 if (got_ref_is_symbolic(ref)) {
2072 err = got_ref_delete(ref, repo);
2073 if (err)
2074 return err;
2075 if (verbosity >= 0) {
2076 printf("Deleted %s: %s\n",
2077 got_ref_get_name(ref),
2078 got_ref_get_symref_target(ref));
2080 } else {
2081 err = got_ref_resolve(&id, repo, ref);
2082 if (err)
2083 return err;
2084 err = got_object_id_str(&id_str, id);
2085 if (err)
2086 goto done;
2088 err = got_ref_delete(ref, repo);
2089 if (err)
2090 goto done;
2091 if (verbosity >= 0) {
2092 printf("Deleted %s: %s\n",
2093 got_ref_get_name(ref), id_str);
2096 done:
2097 free(id);
2098 free(id_str);
2099 return NULL;
2102 static const struct got_error *
2103 delete_missing_refs(struct got_pathlist_head *their_refs,
2104 struct got_pathlist_head *their_symrefs,
2105 const struct got_remote_repo *remote,
2106 int verbosity, struct got_repository *repo)
2108 const struct got_error *err = NULL, *unlock_err;
2109 struct got_reflist_head my_refs;
2110 struct got_reflist_entry *re;
2111 struct got_pathlist_entry *pe;
2112 char *remote_namespace = NULL;
2113 char *local_refname = NULL;
2115 TAILQ_INIT(&my_refs);
2117 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2118 == -1)
2119 return got_error_from_errno("asprintf");
2121 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2122 if (err)
2123 goto done;
2125 TAILQ_FOREACH(re, &my_refs, entry) {
2126 const char *refname = got_ref_get_name(re->ref);
2127 const char *their_refname;
2129 if (remote->mirror_references) {
2130 their_refname = refname;
2131 } else {
2132 if (strncmp(refname, remote_namespace,
2133 strlen(remote_namespace)) == 0) {
2134 if (strcmp(refname + strlen(remote_namespace),
2135 GOT_REF_HEAD) == 0)
2136 continue;
2137 if (asprintf(&local_refname, "refs/heads/%s",
2138 refname + strlen(remote_namespace)) == -1) {
2139 err = got_error_from_errno("asprintf");
2140 goto done;
2142 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2143 continue;
2145 their_refname = local_refname;
2148 TAILQ_FOREACH(pe, their_refs, entry) {
2149 if (strcmp(their_refname, pe->path) == 0)
2150 break;
2152 if (pe != NULL)
2153 continue;
2155 TAILQ_FOREACH(pe, their_symrefs, entry) {
2156 if (strcmp(their_refname, pe->path) == 0)
2157 break;
2159 if (pe != NULL)
2160 continue;
2162 err = delete_missing_ref(re->ref, verbosity, repo);
2163 if (err)
2164 break;
2166 if (local_refname) {
2167 struct got_reference *ref;
2168 err = got_ref_open(&ref, repo, local_refname, 1);
2169 if (err) {
2170 if (err->code != GOT_ERR_NOT_REF)
2171 break;
2172 free(local_refname);
2173 local_refname = NULL;
2174 continue;
2176 err = delete_missing_ref(ref, verbosity, repo);
2177 if (err)
2178 break;
2179 unlock_err = got_ref_unlock(ref);
2180 got_ref_close(ref);
2181 if (unlock_err && err == NULL) {
2182 err = unlock_err;
2183 break;
2186 free(local_refname);
2187 local_refname = NULL;
2190 done:
2191 got_ref_list_free(&my_refs);
2192 free(remote_namespace);
2193 free(local_refname);
2194 return err;
2197 static const struct got_error *
2198 update_wanted_ref(const char *refname, struct got_object_id *id,
2199 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2201 const struct got_error *err, *unlock_err;
2202 char *remote_refname;
2203 struct got_reference *ref;
2205 if (strncmp("refs/", refname, 5) == 0)
2206 refname += 5;
2208 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2209 remote_repo_name, refname) == -1)
2210 return got_error_from_errno("asprintf");
2212 err = got_ref_open(&ref, repo, remote_refname, 1);
2213 if (err) {
2214 if (err->code != GOT_ERR_NOT_REF)
2215 goto done;
2216 err = create_ref(remote_refname, id, verbosity, repo);
2217 } else {
2218 err = update_ref(ref, id, 0, verbosity, repo);
2219 unlock_err = got_ref_unlock(ref);
2220 if (unlock_err && err == NULL)
2221 err = unlock_err;
2222 got_ref_close(ref);
2224 done:
2225 free(remote_refname);
2226 return err;
2229 static const struct got_error *
2230 delete_ref(struct got_repository *repo, struct got_reference *ref)
2232 const struct got_error *err = NULL;
2233 struct got_object_id *id = NULL;
2234 char *id_str = NULL;
2235 const char *target;
2237 if (got_ref_is_symbolic(ref)) {
2238 target = got_ref_get_symref_target(ref);
2239 } else {
2240 err = got_ref_resolve(&id, repo, ref);
2241 if (err)
2242 goto done;
2243 err = got_object_id_str(&id_str, id);
2244 if (err)
2245 goto done;
2246 target = id_str;
2249 err = got_ref_delete(ref, repo);
2250 if (err)
2251 goto done;
2253 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2254 done:
2255 free(id);
2256 free(id_str);
2257 return err;
2260 static const struct got_error *
2261 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2263 const struct got_error *err = NULL;
2264 struct got_reflist_head refs;
2265 struct got_reflist_entry *re;
2266 char *prefix;
2268 TAILQ_INIT(&refs);
2270 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2271 err = got_error_from_errno("asprintf");
2272 goto done;
2274 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2275 if (err)
2276 goto done;
2278 TAILQ_FOREACH(re, &refs, entry)
2279 delete_ref(repo, re->ref);
2280 done:
2281 got_ref_list_free(&refs);
2282 return err;
2285 static const struct got_error *
2286 cmd_fetch(int argc, char *argv[])
2288 const struct got_error *error = NULL, *unlock_err;
2289 char *cwd = NULL, *repo_path = NULL;
2290 const char *remote_name;
2291 char *proto = NULL, *host = NULL, *port = NULL;
2292 char *repo_name = NULL, *server_path = NULL;
2293 const struct got_remote_repo *remotes, *remote = NULL;
2294 int nremotes;
2295 char *id_str = NULL;
2296 struct got_repository *repo = NULL;
2297 struct got_worktree *worktree = NULL;
2298 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2299 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2300 struct got_pathlist_entry *pe;
2301 struct got_object_id *pack_hash = NULL;
2302 int i, ch, fetchfd = -1, fetchstatus;
2303 pid_t fetchpid = -1;
2304 struct got_fetch_progress_arg fpa;
2305 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2306 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2307 int *pack_fds = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&wanted_branches);
2312 TAILQ_INIT(&wanted_refs);
2314 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2315 switch (ch) {
2316 case 'a':
2317 fetch_all_branches = 1;
2318 break;
2319 case 'b':
2320 error = got_pathlist_append(&wanted_branches,
2321 optarg, NULL);
2322 if (error)
2323 return error;
2324 break;
2325 case 'd':
2326 delete_refs = 1;
2327 break;
2328 case 'l':
2329 list_refs_only = 1;
2330 break;
2331 case 'q':
2332 verbosity = -1;
2333 break;
2334 case 'R':
2335 error = got_pathlist_append(&wanted_refs,
2336 optarg, NULL);
2337 if (error)
2338 return error;
2339 break;
2340 case 'r':
2341 repo_path = realpath(optarg, NULL);
2342 if (repo_path == NULL)
2343 return got_error_from_errno2("realpath",
2344 optarg);
2345 got_path_strip_trailing_slashes(repo_path);
2346 break;
2347 case 't':
2348 replace_tags = 1;
2349 break;
2350 case 'v':
2351 if (verbosity < 0)
2352 verbosity = 0;
2353 else if (verbosity < 3)
2354 verbosity++;
2355 break;
2356 case 'X':
2357 delete_remote = 1;
2358 break;
2359 default:
2360 usage_fetch();
2361 break;
2364 argc -= optind;
2365 argv += optind;
2367 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2368 option_conflict('a', 'b');
2369 if (list_refs_only) {
2370 if (!TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('l', 'b');
2372 if (fetch_all_branches)
2373 option_conflict('l', 'a');
2374 if (delete_refs)
2375 option_conflict('l', 'd');
2376 if (delete_remote)
2377 option_conflict('l', 'X');
2379 if (delete_remote) {
2380 if (fetch_all_branches)
2381 option_conflict('X', 'a');
2382 if (!TAILQ_EMPTY(&wanted_branches))
2383 option_conflict('X', 'b');
2384 if (delete_refs)
2385 option_conflict('X', 'd');
2386 if (replace_tags)
2387 option_conflict('X', 't');
2388 if (!TAILQ_EMPTY(&wanted_refs))
2389 option_conflict('X', 'R');
2392 if (argc == 0) {
2393 if (delete_remote)
2394 errx(1, "-X option requires a remote name");
2395 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2396 } else if (argc == 1)
2397 remote_name = argv[0];
2398 else
2399 usage_fetch();
2401 cwd = getcwd(NULL, 0);
2402 if (cwd == NULL) {
2403 error = got_error_from_errno("getcwd");
2404 goto done;
2407 error = got_repo_pack_fds_open(&pack_fds);
2408 if (error != NULL)
2409 goto done;
2411 if (repo_path == NULL) {
2412 error = got_worktree_open(&worktree, cwd);
2413 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2414 goto done;
2415 else
2416 error = NULL;
2417 if (worktree) {
2418 repo_path =
2419 strdup(got_worktree_get_repo_path(worktree));
2420 if (repo_path == NULL)
2421 error = got_error_from_errno("strdup");
2422 if (error)
2423 goto done;
2424 } else {
2425 repo_path = strdup(cwd);
2426 if (repo_path == NULL) {
2427 error = got_error_from_errno("strdup");
2428 goto done;
2433 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2434 if (error)
2435 goto done;
2437 if (delete_remote) {
2438 error = delete_refs_for_remote(repo, remote_name);
2439 goto done; /* nothing else to do */
2442 if (worktree) {
2443 worktree_conf = got_worktree_get_gotconfig(worktree);
2444 if (worktree_conf) {
2445 got_gotconfig_get_remotes(&nremotes, &remotes,
2446 worktree_conf);
2447 for (i = 0; i < nremotes; i++) {
2448 if (strcmp(remotes[i].name, remote_name) == 0) {
2449 remote = &remotes[i];
2450 break;
2455 if (remote == NULL) {
2456 repo_conf = got_repo_get_gotconfig(repo);
2457 if (repo_conf) {
2458 got_gotconfig_get_remotes(&nremotes, &remotes,
2459 repo_conf);
2460 for (i = 0; i < nremotes; i++) {
2461 if (strcmp(remotes[i].name, remote_name) == 0) {
2462 remote = &remotes[i];
2463 break;
2468 if (remote == NULL) {
2469 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2470 for (i = 0; i < nremotes; i++) {
2471 if (strcmp(remotes[i].name, remote_name) == 0) {
2472 remote = &remotes[i];
2473 break;
2477 if (remote == NULL) {
2478 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2479 goto done;
2482 if (TAILQ_EMPTY(&wanted_branches)) {
2483 if (!fetch_all_branches)
2484 fetch_all_branches = remote->fetch_all_branches;
2485 for (i = 0; i < remote->nfetch_branches; i++) {
2486 error = got_pathlist_append(&wanted_branches,
2487 remote->fetch_branches[i], NULL);
2488 if (error)
2489 goto done;
2492 if (TAILQ_EMPTY(&wanted_refs)) {
2493 for (i = 0; i < remote->nfetch_refs; i++) {
2494 error = got_pathlist_append(&wanted_refs,
2495 remote->fetch_refs[i], NULL);
2496 if (error)
2497 goto done;
2501 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2502 &repo_name, remote->fetch_url);
2503 if (error)
2504 goto done;
2506 if (strcmp(proto, "git") == 0) {
2507 #ifndef PROFILE
2508 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2509 "sendfd dns inet unveil", NULL) == -1)
2510 err(1, "pledge");
2511 #endif
2512 } else if (strcmp(proto, "git+ssh") == 0 ||
2513 strcmp(proto, "ssh") == 0) {
2514 #ifndef PROFILE
2515 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2516 "sendfd unveil", NULL) == -1)
2517 err(1, "pledge");
2518 #endif
2519 } else if (strcmp(proto, "http") == 0 ||
2520 strcmp(proto, "git+http") == 0) {
2521 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2522 goto done;
2523 } else {
2524 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2525 goto done;
2528 error = got_dial_apply_unveil(proto);
2529 if (error)
2530 goto done;
2532 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2533 if (error)
2534 goto done;
2536 if (verbosity >= 0) {
2537 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2538 remote->name, proto, host,
2539 port ? ":" : "", port ? port : "",
2540 *server_path == '/' ? "" : "/", server_path);
2543 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2544 server_path, verbosity);
2545 if (error)
2546 goto done;
2548 fpa.last_scaled_size[0] = '\0';
2549 fpa.last_p_indexed = -1;
2550 fpa.last_p_resolved = -1;
2551 fpa.verbosity = verbosity;
2552 fpa.repo = repo;
2553 fpa.create_configs = 0;
2554 fpa.configs_created = 0;
2555 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2556 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2557 remote->mirror_references, fetch_all_branches, &wanted_branches,
2558 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2559 fetch_progress, &fpa);
2560 if (error)
2561 goto done;
2563 if (list_refs_only) {
2564 error = list_remote_refs(&symrefs, &refs);
2565 goto done;
2568 if (pack_hash == NULL) {
2569 if (verbosity >= 0)
2570 printf("Already up-to-date\n");
2571 } else if (verbosity >= 0) {
2572 error = got_object_id_str(&id_str, pack_hash);
2573 if (error)
2574 goto done;
2575 printf("\nFetched %s.pack\n", id_str);
2576 free(id_str);
2577 id_str = NULL;
2580 /* Update references provided with the pack file. */
2581 TAILQ_FOREACH(pe, &refs, entry) {
2582 const char *refname = pe->path;
2583 struct got_object_id *id = pe->data;
2584 struct got_reference *ref;
2585 char *remote_refname;
2587 if (is_wanted_ref(&wanted_refs, refname) &&
2588 !remote->mirror_references) {
2589 error = update_wanted_ref(refname, id,
2590 remote->name, verbosity, repo);
2591 if (error)
2592 goto done;
2593 continue;
2596 if (remote->mirror_references ||
2597 strncmp("refs/tags/", refname, 10) == 0) {
2598 error = got_ref_open(&ref, repo, refname, 1);
2599 if (error) {
2600 if (error->code != GOT_ERR_NOT_REF)
2601 goto done;
2602 error = create_ref(refname, id, verbosity,
2603 repo);
2604 if (error)
2605 goto done;
2606 } else {
2607 error = update_ref(ref, id, replace_tags,
2608 verbosity, repo);
2609 unlock_err = got_ref_unlock(ref);
2610 if (unlock_err && error == NULL)
2611 error = unlock_err;
2612 got_ref_close(ref);
2613 if (error)
2614 goto done;
2616 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2617 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2618 remote_name, refname + 11) == -1) {
2619 error = got_error_from_errno("asprintf");
2620 goto done;
2623 error = got_ref_open(&ref, repo, remote_refname, 1);
2624 if (error) {
2625 if (error->code != GOT_ERR_NOT_REF)
2626 goto done;
2627 error = create_ref(remote_refname, id,
2628 verbosity, repo);
2629 if (error)
2630 goto done;
2631 } else {
2632 error = update_ref(ref, id, replace_tags,
2633 verbosity, repo);
2634 unlock_err = got_ref_unlock(ref);
2635 if (unlock_err && error == NULL)
2636 error = unlock_err;
2637 got_ref_close(ref);
2638 if (error)
2639 goto done;
2642 /* Also create a local branch if none exists yet. */
2643 error = got_ref_open(&ref, repo, refname, 1);
2644 if (error) {
2645 if (error->code != GOT_ERR_NOT_REF)
2646 goto done;
2647 error = create_ref(refname, id, verbosity,
2648 repo);
2649 if (error)
2650 goto done;
2651 } else {
2652 unlock_err = got_ref_unlock(ref);
2653 if (unlock_err && error == NULL)
2654 error = unlock_err;
2655 got_ref_close(ref);
2659 if (delete_refs) {
2660 error = delete_missing_refs(&refs, &symrefs, remote,
2661 verbosity, repo);
2662 if (error)
2663 goto done;
2666 if (!remote->mirror_references) {
2667 /* Update remote HEAD reference if the server provided one. */
2668 TAILQ_FOREACH(pe, &symrefs, entry) {
2669 struct got_reference *target_ref;
2670 const char *refname = pe->path;
2671 const char *target = pe->data;
2672 char *remote_refname = NULL, *remote_target = NULL;
2674 if (strcmp(refname, GOT_REF_HEAD) != 0)
2675 continue;
2677 if (strncmp("refs/heads/", target, 11) != 0)
2678 continue;
2680 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2681 remote->name, refname) == -1) {
2682 error = got_error_from_errno("asprintf");
2683 goto done;
2685 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2686 remote->name, target + 11) == -1) {
2687 error = got_error_from_errno("asprintf");
2688 free(remote_refname);
2689 goto done;
2692 error = got_ref_open(&target_ref, repo, remote_target,
2693 0);
2694 if (error) {
2695 free(remote_refname);
2696 free(remote_target);
2697 if (error->code == GOT_ERR_NOT_REF) {
2698 error = NULL;
2699 continue;
2701 goto done;
2703 error = update_symref(remote_refname, target_ref,
2704 verbosity, repo);
2705 free(remote_refname);
2706 free(remote_target);
2707 got_ref_close(target_ref);
2708 if (error)
2709 goto done;
2712 done:
2713 if (fetchpid > 0) {
2714 if (kill(fetchpid, SIGTERM) == -1)
2715 error = got_error_from_errno("kill");
2716 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2717 error = got_error_from_errno("waitpid");
2719 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2720 error = got_error_from_errno("close");
2721 if (repo) {
2722 const struct got_error *close_err = got_repo_close(repo);
2723 if (error == NULL)
2724 error = close_err;
2726 if (worktree)
2727 got_worktree_close(worktree);
2728 if (pack_fds) {
2729 const struct got_error *pack_err =
2730 got_repo_pack_fds_close(pack_fds);
2731 if (error == NULL)
2732 error = pack_err;
2734 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2735 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2736 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2737 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2738 free(id_str);
2739 free(cwd);
2740 free(repo_path);
2741 free(pack_hash);
2742 free(proto);
2743 free(host);
2744 free(port);
2745 free(server_path);
2746 free(repo_name);
2747 return error;
2751 __dead static void
2752 usage_checkout(void)
2754 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2755 "[-p path-prefix] repository-path [work-tree-path]\n",
2756 getprogname());
2757 exit(1);
2760 static void
2761 show_worktree_base_ref_warning(void)
2763 fprintf(stderr, "%s: warning: could not create a reference "
2764 "to the work tree's base commit; the commit could be "
2765 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2766 "repository writable and running 'got update' will prevent this\n",
2767 getprogname());
2770 struct got_checkout_progress_arg {
2771 const char *worktree_path;
2772 int had_base_commit_ref_error;
2773 int verbosity;
2776 static const struct got_error *
2777 checkout_progress(void *arg, unsigned char status, const char *path)
2779 struct got_checkout_progress_arg *a = arg;
2781 /* Base commit bump happens silently. */
2782 if (status == GOT_STATUS_BUMP_BASE)
2783 return NULL;
2785 if (status == GOT_STATUS_BASE_REF_ERR) {
2786 a->had_base_commit_ref_error = 1;
2787 return NULL;
2790 while (path[0] == '/')
2791 path++;
2793 if (a->verbosity >= 0)
2794 printf("%c %s/%s\n", status, a->worktree_path, path);
2796 return NULL;
2799 static const struct got_error *
2800 check_cancelled(void *arg)
2802 if (sigint_received || sigpipe_received)
2803 return got_error(GOT_ERR_CANCELLED);
2804 return NULL;
2807 static const struct got_error *
2808 check_linear_ancestry(struct got_object_id *commit_id,
2809 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2810 struct got_repository *repo)
2812 const struct got_error *err = NULL;
2813 struct got_object_id *yca_id;
2815 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2816 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2817 if (err)
2818 return err;
2820 if (yca_id == NULL)
2821 return got_error(GOT_ERR_ANCESTRY);
2824 * Require a straight line of history between the target commit
2825 * and the work tree's base commit.
2827 * Non-linear situations such as this require a rebase:
2829 * (commit) D F (base_commit)
2830 * \ /
2831 * C E
2832 * \ /
2833 * B (yca)
2834 * |
2835 * A
2837 * 'got update' only handles linear cases:
2838 * Update forwards in time: A (base/yca) - B - C - D (commit)
2839 * Update backwards in time: D (base) - C - B - A (commit/yca)
2841 if (allow_forwards_in_time_only) {
2842 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2843 return got_error(GOT_ERR_ANCESTRY);
2844 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2845 got_object_id_cmp(base_commit_id, yca_id) != 0)
2846 return got_error(GOT_ERR_ANCESTRY);
2848 free(yca_id);
2849 return NULL;
2852 static const struct got_error *
2853 check_same_branch(struct got_object_id *commit_id,
2854 struct got_reference *head_ref, struct got_object_id *yca_id,
2855 struct got_repository *repo)
2857 const struct got_error *err = NULL;
2858 struct got_commit_graph *graph = NULL;
2859 struct got_object_id *head_commit_id = NULL;
2860 int is_same_branch = 0;
2862 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2863 if (err)
2864 goto done;
2866 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2867 is_same_branch = 1;
2868 goto done;
2870 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2871 is_same_branch = 1;
2872 goto done;
2875 err = got_commit_graph_open(&graph, "/", 1);
2876 if (err)
2877 goto done;
2879 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2880 check_cancelled, NULL);
2881 if (err)
2882 goto done;
2884 for (;;) {
2885 struct got_object_id id;
2887 err = got_commit_graph_iter_next(&id, graph, repo,
2888 check_cancelled, NULL);
2889 if (err) {
2890 if (err->code == GOT_ERR_ITER_COMPLETED)
2891 err = NULL;
2892 break;
2895 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2896 break;
2897 if (got_object_id_cmp(&id, commit_id) == 0) {
2898 is_same_branch = 1;
2899 break;
2902 done:
2903 if (graph)
2904 got_commit_graph_close(graph);
2905 free(head_commit_id);
2906 if (!err && !is_same_branch)
2907 err = got_error(GOT_ERR_ANCESTRY);
2908 return err;
2911 static const struct got_error *
2912 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2914 static char msg[512];
2915 const char *branch_name;
2917 if (got_ref_is_symbolic(ref))
2918 branch_name = got_ref_get_symref_target(ref);
2919 else
2920 branch_name = got_ref_get_name(ref);
2922 if (strncmp("refs/heads/", branch_name, 11) == 0)
2923 branch_name += 11;
2925 snprintf(msg, sizeof(msg),
2926 "target commit is not contained in branch '%s'; "
2927 "the branch to use must be specified with -b; "
2928 "if necessary a new branch can be created for "
2929 "this commit with 'got branch -c %s BRANCH_NAME'",
2930 branch_name, commit_id_str);
2932 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2935 static const struct got_error *
2936 cmd_checkout(int argc, char *argv[])
2938 const struct got_error *error = NULL;
2939 struct got_repository *repo = NULL;
2940 struct got_reference *head_ref = NULL, *ref = NULL;
2941 struct got_worktree *worktree = NULL;
2942 char *repo_path = NULL;
2943 char *worktree_path = NULL;
2944 const char *path_prefix = "";
2945 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2946 char *commit_id_str = NULL;
2947 struct got_object_id *commit_id = NULL;
2948 char *cwd = NULL;
2949 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2950 struct got_pathlist_head paths;
2951 struct got_checkout_progress_arg cpa;
2952 int *pack_fds = NULL;
2954 TAILQ_INIT(&paths);
2956 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2957 switch (ch) {
2958 case 'b':
2959 branch_name = optarg;
2960 break;
2961 case 'c':
2962 commit_id_str = strdup(optarg);
2963 if (commit_id_str == NULL)
2964 return got_error_from_errno("strdup");
2965 break;
2966 case 'E':
2967 allow_nonempty = 1;
2968 break;
2969 case 'p':
2970 path_prefix = optarg;
2971 break;
2972 case 'q':
2973 verbosity = -1;
2974 break;
2975 default:
2976 usage_checkout();
2977 /* NOTREACHED */
2981 argc -= optind;
2982 argv += optind;
2984 #ifndef PROFILE
2985 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2986 "unveil", NULL) == -1)
2987 err(1, "pledge");
2988 #endif
2989 if (argc == 1) {
2990 char *base, *dotgit;
2991 const char *path;
2992 repo_path = realpath(argv[0], NULL);
2993 if (repo_path == NULL)
2994 return got_error_from_errno2("realpath", argv[0]);
2995 cwd = getcwd(NULL, 0);
2996 if (cwd == NULL) {
2997 error = got_error_from_errno("getcwd");
2998 goto done;
3000 if (path_prefix[0])
3001 path = path_prefix;
3002 else
3003 path = repo_path;
3004 error = got_path_basename(&base, path);
3005 if (error)
3006 goto done;
3007 dotgit = strstr(base, ".git");
3008 if (dotgit)
3009 *dotgit = '\0';
3010 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3011 error = got_error_from_errno("asprintf");
3012 free(base);
3013 goto done;
3015 free(base);
3016 } else if (argc == 2) {
3017 repo_path = realpath(argv[0], NULL);
3018 if (repo_path == NULL) {
3019 error = got_error_from_errno2("realpath", argv[0]);
3020 goto done;
3022 worktree_path = realpath(argv[1], NULL);
3023 if (worktree_path == NULL) {
3024 if (errno != ENOENT) {
3025 error = got_error_from_errno2("realpath",
3026 argv[1]);
3027 goto done;
3029 worktree_path = strdup(argv[1]);
3030 if (worktree_path == NULL) {
3031 error = got_error_from_errno("strdup");
3032 goto done;
3035 } else
3036 usage_checkout();
3038 got_path_strip_trailing_slashes(repo_path);
3039 got_path_strip_trailing_slashes(worktree_path);
3041 error = got_repo_pack_fds_open(&pack_fds);
3042 if (error != NULL)
3043 goto done;
3045 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3046 if (error != NULL)
3047 goto done;
3049 /* Pre-create work tree path for unveil(2) */
3050 error = got_path_mkdir(worktree_path);
3051 if (error) {
3052 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3053 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3054 goto done;
3055 if (!allow_nonempty &&
3056 !got_path_dir_is_empty(worktree_path)) {
3057 error = got_error_path(worktree_path,
3058 GOT_ERR_DIR_NOT_EMPTY);
3059 goto done;
3063 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3064 if (error)
3065 goto done;
3067 error = got_ref_open(&head_ref, repo, branch_name, 0);
3068 if (error != NULL)
3069 goto done;
3071 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3072 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3073 goto done;
3075 error = got_worktree_open(&worktree, worktree_path);
3076 if (error != NULL)
3077 goto done;
3079 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3080 path_prefix);
3081 if (error != NULL)
3082 goto done;
3083 if (!same_path_prefix) {
3084 error = got_error(GOT_ERR_PATH_PREFIX);
3085 goto done;
3088 if (commit_id_str) {
3089 struct got_reflist_head refs;
3090 TAILQ_INIT(&refs);
3091 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3092 NULL);
3093 if (error)
3094 goto done;
3095 error = got_repo_match_object_id(&commit_id, NULL,
3096 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3097 got_ref_list_free(&refs);
3098 if (error)
3099 goto done;
3100 error = check_linear_ancestry(commit_id,
3101 got_worktree_get_base_commit_id(worktree), 0, repo);
3102 if (error != NULL) {
3103 if (error->code == GOT_ERR_ANCESTRY) {
3104 error = checkout_ancestry_error(
3105 head_ref, commit_id_str);
3107 goto done;
3109 error = check_same_branch(commit_id, head_ref, NULL, repo);
3110 if (error) {
3111 if (error->code == GOT_ERR_ANCESTRY) {
3112 error = checkout_ancestry_error(
3113 head_ref, commit_id_str);
3115 goto done;
3117 error = got_worktree_set_base_commit_id(worktree, repo,
3118 commit_id);
3119 if (error)
3120 goto done;
3121 /* Expand potentially abbreviated commit ID string. */
3122 free(commit_id_str);
3123 error = got_object_id_str(&commit_id_str, commit_id);
3124 if (error)
3125 goto done;
3126 } else {
3127 commit_id = got_object_id_dup(
3128 got_worktree_get_base_commit_id(worktree));
3129 if (commit_id == NULL) {
3130 error = got_error_from_errno("got_object_id_dup");
3131 goto done;
3133 error = got_object_id_str(&commit_id_str, commit_id);
3134 if (error)
3135 goto done;
3138 error = got_pathlist_append(&paths, "", NULL);
3139 if (error)
3140 goto done;
3141 cpa.worktree_path = worktree_path;
3142 cpa.had_base_commit_ref_error = 0;
3143 cpa.verbosity = verbosity;
3144 error = got_worktree_checkout_files(worktree, &paths, repo,
3145 checkout_progress, &cpa, check_cancelled, NULL);
3146 if (error != NULL)
3147 goto done;
3149 if (got_ref_is_symbolic(head_ref)) {
3150 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3151 if (error)
3152 goto done;
3153 refname = got_ref_get_name(ref);
3154 } else
3155 refname = got_ref_get_name(head_ref);
3156 printf("Checked out %s: %s\n", refname, commit_id_str);
3157 printf("Now shut up and hack\n");
3158 if (cpa.had_base_commit_ref_error)
3159 show_worktree_base_ref_warning();
3160 done:
3161 if (pack_fds) {
3162 const struct got_error *pack_err =
3163 got_repo_pack_fds_close(pack_fds);
3164 if (error == NULL)
3165 error = pack_err;
3167 if (head_ref)
3168 got_ref_close(head_ref);
3169 if (ref)
3170 got_ref_close(ref);
3171 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3172 free(commit_id_str);
3173 free(commit_id);
3174 free(repo_path);
3175 free(worktree_path);
3176 free(cwd);
3177 return error;
3180 struct got_update_progress_arg {
3181 int did_something;
3182 int conflicts;
3183 int obstructed;
3184 int not_updated;
3185 int missing;
3186 int not_deleted;
3187 int unversioned;
3188 int verbosity;
3191 static void
3192 print_update_progress_stats(struct got_update_progress_arg *upa)
3194 if (!upa->did_something)
3195 return;
3197 if (upa->conflicts > 0)
3198 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3199 if (upa->obstructed > 0)
3200 printf("File paths obstructed by a non-regular file: %d\n",
3201 upa->obstructed);
3202 if (upa->not_updated > 0)
3203 printf("Files not updated because of existing merge "
3204 "conflicts: %d\n", upa->not_updated);
3208 * The meaning of some status codes differs between merge-style operations and
3209 * update operations. For example, the ! status code means "file was missing"
3210 * if changes were merged into the work tree, and "missing file was restored"
3211 * if the work tree was updated. This function should be used by any operation
3212 * which merges changes into the work tree without updating the work tree.
3214 static void
3215 print_merge_progress_stats(struct got_update_progress_arg *upa)
3217 if (!upa->did_something)
3218 return;
3220 if (upa->conflicts > 0)
3221 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3222 if (upa->obstructed > 0)
3223 printf("File paths obstructed by a non-regular file: %d\n",
3224 upa->obstructed);
3225 if (upa->missing > 0)
3226 printf("Files which had incoming changes but could not be "
3227 "found in the work tree: %d\n", upa->missing);
3228 if (upa->not_deleted > 0)
3229 printf("Files not deleted due to differences in deleted "
3230 "content: %d\n", upa->not_deleted);
3231 if (upa->unversioned > 0)
3232 printf("Files not merged because an unversioned file was "
3233 "found in the work tree: %d\n", upa->unversioned);
3236 __dead static void
3237 usage_update(void)
3239 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3240 "[path ...]\n", getprogname());
3241 exit(1);
3244 static const struct got_error *
3245 update_progress(void *arg, unsigned char status, const char *path)
3247 struct got_update_progress_arg *upa = arg;
3249 if (status == GOT_STATUS_EXISTS ||
3250 status == GOT_STATUS_BASE_REF_ERR)
3251 return NULL;
3253 upa->did_something = 1;
3255 /* Base commit bump happens silently. */
3256 if (status == GOT_STATUS_BUMP_BASE)
3257 return NULL;
3259 if (status == GOT_STATUS_CONFLICT)
3260 upa->conflicts++;
3261 if (status == GOT_STATUS_OBSTRUCTED)
3262 upa->obstructed++;
3263 if (status == GOT_STATUS_CANNOT_UPDATE)
3264 upa->not_updated++;
3265 if (status == GOT_STATUS_MISSING)
3266 upa->missing++;
3267 if (status == GOT_STATUS_CANNOT_DELETE)
3268 upa->not_deleted++;
3269 if (status == GOT_STATUS_UNVERSIONED)
3270 upa->unversioned++;
3272 while (path[0] == '/')
3273 path++;
3274 if (upa->verbosity >= 0)
3275 printf("%c %s\n", status, path);
3277 return NULL;
3280 static const struct got_error *
3281 switch_head_ref(struct got_reference *head_ref,
3282 struct got_object_id *commit_id, struct got_worktree *worktree,
3283 struct got_repository *repo)
3285 const struct got_error *err = NULL;
3286 char *base_id_str;
3287 int ref_has_moved = 0;
3289 /* Trivial case: switching between two different references. */
3290 if (strcmp(got_ref_get_name(head_ref),
3291 got_worktree_get_head_ref_name(worktree)) != 0) {
3292 printf("Switching work tree from %s to %s\n",
3293 got_worktree_get_head_ref_name(worktree),
3294 got_ref_get_name(head_ref));
3295 return got_worktree_set_head_ref(worktree, head_ref);
3298 err = check_linear_ancestry(commit_id,
3299 got_worktree_get_base_commit_id(worktree), 0, repo);
3300 if (err) {
3301 if (err->code != GOT_ERR_ANCESTRY)
3302 return err;
3303 ref_has_moved = 1;
3305 if (!ref_has_moved)
3306 return NULL;
3308 /* Switching to a rebased branch with the same reference name. */
3309 err = got_object_id_str(&base_id_str,
3310 got_worktree_get_base_commit_id(worktree));
3311 if (err)
3312 return err;
3313 printf("Reference %s now points at a different branch\n",
3314 got_worktree_get_head_ref_name(worktree));
3315 printf("Switching work tree from %s to %s\n", base_id_str,
3316 got_worktree_get_head_ref_name(worktree));
3317 return NULL;
3320 static const struct got_error *
3321 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3323 const struct got_error *err;
3324 int in_progress;
3326 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3327 if (err)
3328 return err;
3329 if (in_progress)
3330 return got_error(GOT_ERR_REBASING);
3332 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3333 if (err)
3334 return err;
3335 if (in_progress)
3336 return got_error(GOT_ERR_HISTEDIT_BUSY);
3338 return NULL;
3341 static const struct got_error *
3342 check_merge_in_progress(struct got_worktree *worktree,
3343 struct got_repository *repo)
3345 const struct got_error *err;
3346 int in_progress;
3348 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3349 if (err)
3350 return err;
3351 if (in_progress)
3352 return got_error(GOT_ERR_MERGE_BUSY);
3354 return NULL;
3357 static const struct got_error *
3358 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3359 char *argv[], struct got_worktree *worktree)
3361 const struct got_error *err = NULL;
3362 char *path;
3363 struct got_pathlist_entry *new;
3364 int i;
3366 if (argc == 0) {
3367 path = strdup("");
3368 if (path == NULL)
3369 return got_error_from_errno("strdup");
3370 return got_pathlist_append(paths, path, NULL);
3373 for (i = 0; i < argc; i++) {
3374 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3375 if (err)
3376 break;
3377 err = got_pathlist_insert(&new, paths, path, NULL);
3378 if (err || new == NULL /* duplicate */) {
3379 free(path);
3380 if (err)
3381 break;
3385 return err;
3388 static const struct got_error *
3389 wrap_not_worktree_error(const struct got_error *orig_err,
3390 const char *cmdname, const char *path)
3392 const struct got_error *err;
3393 struct got_repository *repo;
3394 static char msg[512];
3395 int *pack_fds = NULL;
3397 err = got_repo_pack_fds_open(&pack_fds);
3398 if (err)
3399 return err;
3401 err = got_repo_open(&repo, path, NULL, pack_fds);
3402 if (err)
3403 return orig_err;
3405 snprintf(msg, sizeof(msg),
3406 "'got %s' needs a work tree in addition to a git repository\n"
3407 "Work trees can be checked out from this Git repository with "
3408 "'got checkout'.\n"
3409 "The got(1) manual page contains more information.", cmdname);
3410 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3411 got_repo_close(repo);
3412 if (pack_fds) {
3413 const struct got_error *pack_err =
3414 got_repo_pack_fds_close(pack_fds);
3415 if (err == NULL)
3416 err = pack_err;
3418 return err;
3421 static const struct got_error *
3422 cmd_update(int argc, char *argv[])
3424 const struct got_error *error = NULL;
3425 struct got_repository *repo = NULL;
3426 struct got_worktree *worktree = NULL;
3427 char *worktree_path = NULL;
3428 struct got_object_id *commit_id = NULL;
3429 char *commit_id_str = NULL;
3430 const char *branch_name = NULL;
3431 struct got_reference *head_ref = NULL;
3432 struct got_pathlist_head paths;
3433 struct got_pathlist_entry *pe;
3434 int ch, verbosity = 0;
3435 struct got_update_progress_arg upa;
3436 int *pack_fds = NULL;
3438 TAILQ_INIT(&paths);
3440 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3441 switch (ch) {
3442 case 'b':
3443 branch_name = optarg;
3444 break;
3445 case 'c':
3446 commit_id_str = strdup(optarg);
3447 if (commit_id_str == NULL)
3448 return got_error_from_errno("strdup");
3449 break;
3450 case 'q':
3451 verbosity = -1;
3452 break;
3453 default:
3454 usage_update();
3455 /* NOTREACHED */
3459 argc -= optind;
3460 argv += optind;
3462 #ifndef PROFILE
3463 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3464 "unveil", NULL) == -1)
3465 err(1, "pledge");
3466 #endif
3467 worktree_path = getcwd(NULL, 0);
3468 if (worktree_path == NULL) {
3469 error = got_error_from_errno("getcwd");
3470 goto done;
3473 error = got_repo_pack_fds_open(&pack_fds);
3474 if (error != NULL)
3475 goto done;
3477 error = got_worktree_open(&worktree, worktree_path);
3478 if (error) {
3479 if (error->code == GOT_ERR_NOT_WORKTREE)
3480 error = wrap_not_worktree_error(error, "update",
3481 worktree_path);
3482 goto done;
3485 error = check_rebase_or_histedit_in_progress(worktree);
3486 if (error)
3487 goto done;
3489 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3490 NULL, pack_fds);
3491 if (error != NULL)
3492 goto done;
3494 error = apply_unveil(got_repo_get_path(repo), 0,
3495 got_worktree_get_root_path(worktree));
3496 if (error)
3497 goto done;
3499 error = check_merge_in_progress(worktree, repo);
3500 if (error)
3501 goto done;
3503 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3504 if (error)
3505 goto done;
3507 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3508 got_worktree_get_head_ref_name(worktree), 0);
3509 if (error != NULL)
3510 goto done;
3511 if (commit_id_str == NULL) {
3512 error = got_ref_resolve(&commit_id, repo, head_ref);
3513 if (error != NULL)
3514 goto done;
3515 error = got_object_id_str(&commit_id_str, commit_id);
3516 if (error != NULL)
3517 goto done;
3518 } else {
3519 struct got_reflist_head refs;
3520 TAILQ_INIT(&refs);
3521 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3522 NULL);
3523 if (error)
3524 goto done;
3525 error = got_repo_match_object_id(&commit_id, NULL,
3526 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3527 got_ref_list_free(&refs);
3528 free(commit_id_str);
3529 commit_id_str = NULL;
3530 if (error)
3531 goto done;
3532 error = got_object_id_str(&commit_id_str, commit_id);
3533 if (error)
3534 goto done;
3537 if (branch_name) {
3538 struct got_object_id *head_commit_id;
3539 TAILQ_FOREACH(pe, &paths, entry) {
3540 if (pe->path_len == 0)
3541 continue;
3542 error = got_error_msg(GOT_ERR_BAD_PATH,
3543 "switching between branches requires that "
3544 "the entire work tree gets updated");
3545 goto done;
3547 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3548 if (error)
3549 goto done;
3550 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3551 repo);
3552 free(head_commit_id);
3553 if (error != NULL)
3554 goto done;
3555 error = check_same_branch(commit_id, head_ref, NULL, repo);
3556 if (error)
3557 goto done;
3558 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3559 if (error)
3560 goto done;
3561 } else {
3562 error = check_linear_ancestry(commit_id,
3563 got_worktree_get_base_commit_id(worktree), 0, repo);
3564 if (error != NULL) {
3565 if (error->code == GOT_ERR_ANCESTRY)
3566 error = got_error(GOT_ERR_BRANCH_MOVED);
3567 goto done;
3569 error = check_same_branch(commit_id, head_ref, NULL, repo);
3570 if (error)
3571 goto done;
3574 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3575 commit_id) != 0) {
3576 error = got_worktree_set_base_commit_id(worktree, repo,
3577 commit_id);
3578 if (error)
3579 goto done;
3582 memset(&upa, 0, sizeof(upa));
3583 upa.verbosity = verbosity;
3584 error = got_worktree_checkout_files(worktree, &paths, repo,
3585 update_progress, &upa, check_cancelled, NULL);
3586 if (error != NULL)
3587 goto done;
3589 if (upa.did_something) {
3590 printf("Updated to %s: %s\n",
3591 got_worktree_get_head_ref_name(worktree), commit_id_str);
3592 } else
3593 printf("Already up-to-date\n");
3595 print_update_progress_stats(&upa);
3596 done:
3597 if (pack_fds) {
3598 const struct got_error *pack_err =
3599 got_repo_pack_fds_close(pack_fds);
3600 if (error == NULL)
3601 error = pack_err;
3603 free(worktree_path);
3604 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3605 free(commit_id);
3606 free(commit_id_str);
3607 return error;
3610 static const struct got_error *
3611 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3612 const char *path, int diff_context, int ignore_whitespace,
3613 int force_text_diff, int show_diffstat, struct got_repository *repo,
3614 FILE *outfile)
3616 const struct got_error *err = NULL;
3617 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3618 FILE *f1 = NULL, *f2 = NULL;
3619 int fd1 = -1, fd2 = -1;
3621 fd1 = got_opentempfd();
3622 if (fd1 == -1)
3623 return got_error_from_errno("got_opentempfd");
3624 fd2 = got_opentempfd();
3625 if (fd2 == -1) {
3626 err = got_error_from_errno("got_opentempfd");
3627 goto done;
3630 if (blob_id1) {
3631 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3632 fd1);
3633 if (err)
3634 goto done;
3637 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3638 if (err)
3639 goto done;
3641 f1 = got_opentemp();
3642 if (f1 == NULL) {
3643 err = got_error_from_errno("got_opentemp");
3644 goto done;
3646 f2 = got_opentemp();
3647 if (f2 == NULL) {
3648 err = got_error_from_errno("got_opentemp");
3649 goto done;
3652 while (path[0] == '/')
3653 path++;
3654 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3655 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3656 force_text_diff, show_diffstat, NULL, outfile);
3657 done:
3658 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3659 err = got_error_from_errno("close");
3660 if (blob1)
3661 got_object_blob_close(blob1);
3662 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3663 err = got_error_from_errno("close");
3664 got_object_blob_close(blob2);
3665 if (f1 && fclose(f1) == EOF && err == NULL)
3666 err = got_error_from_errno("fclose");
3667 if (f2 && fclose(f2) == EOF && err == NULL)
3668 err = got_error_from_errno("fclose");
3669 return err;
3672 static const struct got_error *
3673 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3674 const char *path, int diff_context, int ignore_whitespace,
3675 int force_text_diff, struct got_repository *repo, FILE *outfile)
3677 const struct got_error *err = NULL;
3678 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3679 struct got_diff_blob_output_unidiff_arg arg;
3680 FILE *f1 = NULL, *f2 = NULL;
3681 int fd1 = -1, fd2 = -1;
3683 if (tree_id1) {
3684 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3685 if (err)
3686 goto done;
3687 fd1 = got_opentempfd();
3688 if (fd1 == -1) {
3689 err = got_error_from_errno("got_opentempfd");
3690 goto done;
3694 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3695 if (err)
3696 goto done;
3698 f1 = got_opentemp();
3699 if (f1 == NULL) {
3700 err = got_error_from_errno("got_opentemp");
3701 goto done;
3704 f2 = got_opentemp();
3705 if (f2 == NULL) {
3706 err = got_error_from_errno("got_opentemp");
3707 goto done;
3709 fd2 = got_opentempfd();
3710 if (fd2 == -1) {
3711 err = got_error_from_errno("got_opentempfd");
3712 goto done;
3714 arg.diff_context = diff_context;
3715 arg.ignore_whitespace = ignore_whitespace;
3716 arg.force_text_diff = force_text_diff;
3717 arg.show_diffstat = 0;
3718 arg.diffstat = NULL;
3719 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3720 arg.outfile = outfile;
3721 arg.lines = NULL;
3722 arg.nlines = 0;
3723 while (path[0] == '/')
3724 path++;
3725 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3726 got_diff_blob_output_unidiff, &arg, 1);
3727 done:
3728 if (tree1)
3729 got_object_tree_close(tree1);
3730 if (tree2)
3731 got_object_tree_close(tree2);
3732 if (f1 && fclose(f1) == EOF && err == NULL)
3733 err = got_error_from_errno("fclose");
3734 if (f2 && fclose(f2) == EOF && err == NULL)
3735 err = got_error_from_errno("fclose");
3736 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3737 err = got_error_from_errno("close");
3738 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3739 err = got_error_from_errno("close");
3740 return err;
3743 static const struct got_error *
3744 get_changed_paths(struct got_pathlist_head *paths,
3745 struct got_commit_object *commit, struct got_repository *repo,
3746 struct got_diffstat_cb_arg *dsa)
3748 const struct got_error *err = NULL;
3749 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3750 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3751 struct got_object_qid *qid;
3752 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3753 FILE *f1 = NULL, *f2 = NULL;
3754 int fd1 = -1, fd2 = -1;
3756 if (dsa) {
3757 cb = got_diff_tree_compute_diffstat;
3759 f1 = got_opentemp();
3760 if (f1 == NULL) {
3761 err = got_error_from_errno("got_opentemp");
3762 goto done;
3764 f2 = got_opentemp();
3765 if (f2 == NULL) {
3766 err = got_error_from_errno("got_opentemp");
3767 goto done;
3769 fd1 = got_opentempfd();
3770 if (fd1 == -1) {
3771 err = got_error_from_errno("got_opentempfd");
3772 goto done;
3774 fd2 = got_opentempfd();
3775 if (fd2 == -1) {
3776 err = got_error_from_errno("got_opentempfd");
3777 goto done;
3781 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3782 if (qid != NULL) {
3783 struct got_commit_object *pcommit;
3784 err = got_object_open_as_commit(&pcommit, repo,
3785 &qid->id);
3786 if (err)
3787 return err;
3789 tree_id1 = got_object_id_dup(
3790 got_object_commit_get_tree_id(pcommit));
3791 if (tree_id1 == NULL) {
3792 got_object_commit_close(pcommit);
3793 return got_error_from_errno("got_object_id_dup");
3795 got_object_commit_close(pcommit);
3799 if (tree_id1) {
3800 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3801 if (err)
3802 goto done;
3805 tree_id2 = got_object_commit_get_tree_id(commit);
3806 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3807 if (err)
3808 goto done;
3810 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3811 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3812 done:
3813 if (tree1)
3814 got_object_tree_close(tree1);
3815 if (tree2)
3816 got_object_tree_close(tree2);
3817 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3818 err = got_error_from_errno("close");
3819 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3820 err = got_error_from_errno("close");
3821 if (f1 && fclose(f1) == EOF && err == NULL)
3822 err = got_error_from_errno("fclose");
3823 if (f2 && fclose(f2) == EOF && err == NULL)
3824 err = got_error_from_errno("fclose");
3825 free(tree_id1);
3826 return err;
3829 static const struct got_error *
3830 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3831 const char *path, int diff_context, struct got_repository *repo,
3832 FILE *outfile)
3834 const struct got_error *err = NULL;
3835 struct got_commit_object *pcommit = NULL;
3836 char *id_str1 = NULL, *id_str2 = NULL;
3837 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3838 struct got_object_qid *qid;
3840 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3841 if (qid != NULL) {
3842 err = got_object_open_as_commit(&pcommit, repo,
3843 &qid->id);
3844 if (err)
3845 return err;
3846 err = got_object_id_str(&id_str1, &qid->id);
3847 if (err)
3848 goto done;
3851 err = got_object_id_str(&id_str2, id);
3852 if (err)
3853 goto done;
3855 if (path && path[0] != '\0') {
3856 int obj_type;
3857 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3858 if (err)
3859 goto done;
3860 if (pcommit) {
3861 err = got_object_id_by_path(&obj_id1, repo,
3862 pcommit, path);
3863 if (err) {
3864 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3865 free(obj_id2);
3866 goto done;
3870 err = got_object_get_type(&obj_type, repo, obj_id2);
3871 if (err) {
3872 free(obj_id2);
3873 goto done;
3875 fprintf(outfile,
3876 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3877 fprintf(outfile, "commit - %s\n",
3878 id_str1 ? id_str1 : "/dev/null");
3879 fprintf(outfile, "commit + %s\n", id_str2);
3880 switch (obj_type) {
3881 case GOT_OBJ_TYPE_BLOB:
3882 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3883 0, 0, 0, repo, outfile);
3884 break;
3885 case GOT_OBJ_TYPE_TREE:
3886 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3887 0, 0, repo, outfile);
3888 break;
3889 default:
3890 err = got_error(GOT_ERR_OBJ_TYPE);
3891 break;
3893 free(obj_id1);
3894 free(obj_id2);
3895 } else {
3896 obj_id2 = got_object_commit_get_tree_id(commit);
3897 if (pcommit)
3898 obj_id1 = got_object_commit_get_tree_id(pcommit);
3899 fprintf(outfile,
3900 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3901 fprintf(outfile, "commit - %s\n",
3902 id_str1 ? id_str1 : "/dev/null");
3903 fprintf(outfile, "commit + %s\n", id_str2);
3904 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3905 repo, outfile);
3907 done:
3908 free(id_str1);
3909 free(id_str2);
3910 if (pcommit)
3911 got_object_commit_close(pcommit);
3912 return err;
3915 static char *
3916 get_datestr(time_t *time, char *datebuf)
3918 struct tm mytm, *tm;
3919 char *p, *s;
3921 tm = gmtime_r(time, &mytm);
3922 if (tm == NULL)
3923 return NULL;
3924 s = asctime_r(tm, datebuf);
3925 if (s == NULL)
3926 return NULL;
3927 p = strchr(s, '\n');
3928 if (p)
3929 *p = '\0';
3930 return s;
3933 static const struct got_error *
3934 match_commit(int *have_match, struct got_object_id *id,
3935 struct got_commit_object *commit, regex_t *regex)
3937 const struct got_error *err = NULL;
3938 regmatch_t regmatch;
3939 char *id_str = NULL, *logmsg = NULL;
3941 *have_match = 0;
3943 err = got_object_id_str(&id_str, id);
3944 if (err)
3945 return err;
3947 err = got_object_commit_get_logmsg(&logmsg, commit);
3948 if (err)
3949 goto done;
3951 if (regexec(regex, got_object_commit_get_author(commit), 1,
3952 &regmatch, 0) == 0 ||
3953 regexec(regex, got_object_commit_get_committer(commit), 1,
3954 &regmatch, 0) == 0 ||
3955 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3956 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3957 *have_match = 1;
3958 done:
3959 free(id_str);
3960 free(logmsg);
3961 return err;
3964 static void
3965 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3966 regex_t *regex)
3968 regmatch_t regmatch;
3969 struct got_pathlist_entry *pe;
3971 *have_match = 0;
3973 TAILQ_FOREACH(pe, changed_paths, entry) {
3974 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3975 *have_match = 1;
3976 break;
3981 static const struct got_error *
3982 match_patch(int *have_match, struct got_commit_object *commit,
3983 struct got_object_id *id, const char *path, int diff_context,
3984 struct got_repository *repo, regex_t *regex, FILE *f)
3986 const struct got_error *err = NULL;
3987 char *line = NULL;
3988 size_t linesize = 0;
3989 regmatch_t regmatch;
3991 *have_match = 0;
3993 err = got_opentemp_truncate(f);
3994 if (err)
3995 return err;
3997 err = print_patch(commit, id, path, diff_context, repo, f);
3998 if (err)
3999 goto done;
4001 if (fseeko(f, 0L, SEEK_SET) == -1) {
4002 err = got_error_from_errno("fseeko");
4003 goto done;
4006 while (getline(&line, &linesize, f) != -1) {
4007 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4008 *have_match = 1;
4009 break;
4012 done:
4013 free(line);
4014 return err;
4017 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4019 static const struct got_error*
4020 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4021 struct got_object_id *id, struct got_repository *repo,
4022 int local_only)
4024 static const struct got_error *err = NULL;
4025 struct got_reflist_entry *re;
4026 char *s;
4027 const char *name;
4029 *refs_str = NULL;
4031 TAILQ_FOREACH(re, refs, entry) {
4032 struct got_tag_object *tag = NULL;
4033 struct got_object_id *ref_id;
4034 int cmp;
4036 name = got_ref_get_name(re->ref);
4037 if (strcmp(name, GOT_REF_HEAD) == 0)
4038 continue;
4039 if (strncmp(name, "refs/", 5) == 0)
4040 name += 5;
4041 if (strncmp(name, "got/", 4) == 0)
4042 continue;
4043 if (strncmp(name, "heads/", 6) == 0)
4044 name += 6;
4045 if (strncmp(name, "remotes/", 8) == 0) {
4046 if (local_only)
4047 continue;
4048 name += 8;
4049 s = strstr(name, "/" GOT_REF_HEAD);
4050 if (s != NULL && s[strlen(s)] == '\0')
4051 continue;
4053 err = got_ref_resolve(&ref_id, repo, re->ref);
4054 if (err)
4055 break;
4056 if (strncmp(name, "tags/", 5) == 0) {
4057 err = got_object_open_as_tag(&tag, repo, ref_id);
4058 if (err) {
4059 if (err->code != GOT_ERR_OBJ_TYPE) {
4060 free(ref_id);
4061 break;
4063 /* Ref points at something other than a tag. */
4064 err = NULL;
4065 tag = NULL;
4068 cmp = got_object_id_cmp(tag ?
4069 got_object_tag_get_object_id(tag) : ref_id, id);
4070 free(ref_id);
4071 if (tag)
4072 got_object_tag_close(tag);
4073 if (cmp != 0)
4074 continue;
4075 s = *refs_str;
4076 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4077 s ? ", " : "", name) == -1) {
4078 err = got_error_from_errno("asprintf");
4079 free(s);
4080 *refs_str = NULL;
4081 break;
4083 free(s);
4086 return err;
4089 static const struct got_error *
4090 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4091 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4093 const struct got_error *err = NULL;
4094 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4095 char *comma, *s, *nl;
4096 struct got_reflist_head *refs;
4097 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4098 struct tm tm;
4099 time_t committer_time;
4101 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4102 if (refs) {
4103 err = build_refs_str(&ref_str, refs, id, repo, 1);
4104 if (err)
4105 return err;
4107 /* Display the first matching ref only. */
4108 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4109 *comma = '\0';
4112 if (ref_str == NULL) {
4113 err = got_object_id_str(&id_str, id);
4114 if (err)
4115 return err;
4118 committer_time = got_object_commit_get_committer_time(commit);
4119 if (gmtime_r(&committer_time, &tm) == NULL) {
4120 err = got_error_from_errno("gmtime_r");
4121 goto done;
4123 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4124 err = got_error(GOT_ERR_NO_SPACE);
4125 goto done;
4128 err = got_object_commit_get_logmsg(&logmsg0, commit);
4129 if (err)
4130 goto done;
4132 s = logmsg0;
4133 while (isspace((unsigned char)s[0]))
4134 s++;
4136 nl = strchr(s, '\n');
4137 if (nl) {
4138 *nl = '\0';
4141 if (ref_str)
4142 printf("%s%-7s %s\n", datebuf, ref_str, s);
4143 else
4144 printf("%s%.7s %s\n", datebuf, id_str, s);
4146 if (fflush(stdout) != 0 && err == NULL)
4147 err = got_error_from_errno("fflush");
4148 done:
4149 free(id_str);
4150 free(ref_str);
4151 free(logmsg0);
4152 return err;
4155 static const struct got_error *
4156 print_diffstat(struct got_diffstat_cb_arg *dsa, struct got_pathlist_head *paths,
4157 const char *header)
4159 struct got_pathlist_entry *pe;
4161 if (header != NULL)
4162 printf("%s\n", header);
4164 TAILQ_FOREACH(pe, paths, entry) {
4165 struct got_diff_changed_path *cp = pe->data;
4166 int pad = dsa->max_path_len - pe->path_len + 1;
4168 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4169 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4171 printf("\n%d file%s changed, %d insertions(+), %d deletions(-)\n\n",
4172 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins, dsa->del);
4174 if (fflush(stdout) != 0)
4175 return got_error_from_errno("fflush");
4177 return NULL;
4180 static const struct got_error *
4181 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4182 struct got_repository *repo, const char *path,
4183 struct got_pathlist_head *changed_paths, struct got_diffstat_cb_arg *dsa,
4184 int show_patch, int diff_context,
4185 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4187 const struct got_error *err = NULL;
4188 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4189 char datebuf[26];
4190 time_t committer_time;
4191 const char *author, *committer;
4192 char *refs_str = NULL;
4194 err = got_object_id_str(&id_str, id);
4195 if (err)
4196 return err;
4198 if (custom_refs_str == NULL) {
4199 struct got_reflist_head *refs;
4200 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4201 if (refs) {
4202 err = build_refs_str(&refs_str, refs, id, repo, 0);
4203 if (err)
4204 goto done;
4208 printf(GOT_COMMIT_SEP_STR);
4209 if (custom_refs_str)
4210 printf("commit %s (%s)\n", id_str, custom_refs_str);
4211 else
4212 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4213 refs_str ? refs_str : "", refs_str ? ")" : "");
4214 free(id_str);
4215 id_str = NULL;
4216 free(refs_str);
4217 refs_str = NULL;
4218 printf("from: %s\n", got_object_commit_get_author(commit));
4219 author = got_object_commit_get_author(commit);
4220 committer = got_object_commit_get_committer(commit);
4221 if (strcmp(author, committer) != 0)
4222 printf("via: %s\n", committer);
4223 committer_time = got_object_commit_get_committer_time(commit);
4224 datestr = get_datestr(&committer_time, datebuf);
4225 if (datestr)
4226 printf("date: %s UTC\n", datestr);
4227 if (got_object_commit_get_nparents(commit) > 1) {
4228 const struct got_object_id_queue *parent_ids;
4229 struct got_object_qid *qid;
4230 int n = 1;
4231 parent_ids = got_object_commit_get_parent_ids(commit);
4232 STAILQ_FOREACH(qid, parent_ids, entry) {
4233 err = got_object_id_str(&id_str, &qid->id);
4234 if (err)
4235 goto done;
4236 printf("parent %d: %s\n", n++, id_str);
4237 free(id_str);
4238 id_str = NULL;
4242 err = got_object_commit_get_logmsg(&logmsg0, commit);
4243 if (err)
4244 goto done;
4246 logmsg = logmsg0;
4247 do {
4248 line = strsep(&logmsg, "\n");
4249 if (line)
4250 printf(" %s\n", line);
4251 } while (line);
4252 free(logmsg0);
4254 if (dsa && changed_paths) {
4255 err = print_diffstat(dsa, changed_paths, NULL);
4256 if (err)
4257 goto done;
4258 } else if (changed_paths) {
4259 struct got_pathlist_entry *pe;
4261 TAILQ_FOREACH(pe, changed_paths, entry) {
4262 struct got_diff_changed_path *cp = pe->data;
4264 printf(" %c %s\n", cp->status, pe->path);
4266 printf("\n");
4268 if (show_patch) {
4269 err = print_patch(commit, id, path, diff_context, repo, stdout);
4270 if (err == 0)
4271 printf("\n");
4274 if (fflush(stdout) != 0 && err == NULL)
4275 err = got_error_from_errno("fflush");
4276 done:
4277 free(id_str);
4278 free(refs_str);
4279 return err;
4282 static const struct got_error *
4283 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4284 struct got_repository *repo, const char *path, int show_changed_paths,
4285 int show_diffstat, int show_patch, const char *search_pattern,
4286 int diff_context, int limit, int log_branches, int reverse_display_order,
4287 struct got_reflist_object_id_map *refs_idmap, int one_line,
4288 FILE *tmpfile)
4290 const struct got_error *err;
4291 struct got_commit_graph *graph;
4292 regex_t regex;
4293 int have_match;
4294 struct got_object_id_queue reversed_commits;
4295 struct got_object_qid *qid;
4296 struct got_commit_object *commit;
4297 struct got_pathlist_head changed_paths;
4299 STAILQ_INIT(&reversed_commits);
4300 TAILQ_INIT(&changed_paths);
4302 if (search_pattern && regcomp(&regex, search_pattern,
4303 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4304 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4306 err = got_commit_graph_open(&graph, path, !log_branches);
4307 if (err)
4308 return err;
4309 err = got_commit_graph_iter_start(graph, root_id, repo,
4310 check_cancelled, NULL);
4311 if (err)
4312 goto done;
4313 for (;;) {
4314 struct got_object_id id;
4315 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4316 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4318 if (sigint_received || sigpipe_received)
4319 break;
4321 err = got_commit_graph_iter_next(&id, graph, repo,
4322 check_cancelled, NULL);
4323 if (err) {
4324 if (err->code == GOT_ERR_ITER_COMPLETED)
4325 err = NULL;
4326 break;
4329 err = got_object_open_as_commit(&commit, repo, &id);
4330 if (err)
4331 break;
4333 if ((show_changed_paths || show_diffstat) &&
4334 !reverse_display_order) {
4335 err = get_changed_paths(&changed_paths, commit, repo,
4336 show_diffstat ? &dsa : NULL);
4337 if (err)
4338 break;
4341 if (search_pattern) {
4342 err = match_commit(&have_match, &id, commit, &regex);
4343 if (err) {
4344 got_object_commit_close(commit);
4345 break;
4347 if (have_match == 0 && show_changed_paths)
4348 match_changed_paths(&have_match,
4349 &changed_paths, &regex);
4350 if (have_match == 0 && show_patch) {
4351 err = match_patch(&have_match, commit, &id,
4352 path, diff_context, repo, &regex,
4353 tmpfile);
4354 if (err)
4355 break;
4357 if (have_match == 0) {
4358 got_object_commit_close(commit);
4359 got_pathlist_free(&changed_paths,
4360 GOT_PATHLIST_FREE_ALL);
4361 continue;
4365 if (reverse_display_order) {
4366 err = got_object_qid_alloc(&qid, &id);
4367 if (err)
4368 break;
4369 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4370 got_object_commit_close(commit);
4371 } else {
4372 if (one_line)
4373 err = print_commit_oneline(commit, &id,
4374 repo, refs_idmap);
4375 else
4376 err = print_commit(commit, &id, repo, path,
4377 (show_changed_paths || show_diffstat) ?
4378 &changed_paths : NULL,
4379 show_diffstat ? &dsa : NULL, show_patch,
4380 diff_context, refs_idmap, NULL);
4381 got_object_commit_close(commit);
4382 if (err)
4383 break;
4385 if ((limit && --limit == 0) ||
4386 (end_id && got_object_id_cmp(&id, end_id) == 0))
4387 break;
4389 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4391 if (reverse_display_order) {
4392 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4393 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4394 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4396 err = got_object_open_as_commit(&commit, repo,
4397 &qid->id);
4398 if (err)
4399 break;
4400 if (show_changed_paths || show_diffstat) {
4401 err = get_changed_paths(&changed_paths,
4402 commit, repo, show_diffstat ? &dsa : NULL);
4403 if (err)
4404 break;
4406 if (one_line)
4407 err = print_commit_oneline(commit, &qid->id,
4408 repo, refs_idmap);
4409 else
4410 err = print_commit(commit, &qid->id, repo, path,
4411 (show_changed_paths || show_diffstat) ?
4412 &changed_paths : NULL,
4413 show_diffstat ? &dsa : NULL, show_patch,
4414 diff_context, refs_idmap, NULL);
4415 got_object_commit_close(commit);
4416 if (err)
4417 break;
4418 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4421 done:
4422 while (!STAILQ_EMPTY(&reversed_commits)) {
4423 qid = STAILQ_FIRST(&reversed_commits);
4424 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4425 got_object_qid_free(qid);
4427 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4428 if (search_pattern)
4429 regfree(&regex);
4430 got_commit_graph_close(graph);
4431 return err;
4434 __dead static void
4435 usage_log(void)
4437 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4438 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4439 "[path]\n", getprogname());
4440 exit(1);
4443 static int
4444 get_default_log_limit(void)
4446 const char *got_default_log_limit;
4447 long long n;
4448 const char *errstr;
4450 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4451 if (got_default_log_limit == NULL)
4452 return 0;
4453 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4454 if (errstr != NULL)
4455 return 0;
4456 return n;
4459 static const struct got_error *
4460 cmd_log(int argc, char *argv[])
4462 const struct got_error *error;
4463 struct got_repository *repo = NULL;
4464 struct got_worktree *worktree = NULL;
4465 struct got_object_id *start_id = NULL, *end_id = NULL;
4466 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4467 const char *start_commit = NULL, *end_commit = NULL;
4468 const char *search_pattern = NULL;
4469 int diff_context = -1, ch;
4470 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4471 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4472 const char *errstr;
4473 struct got_reflist_head refs;
4474 struct got_reflist_object_id_map *refs_idmap = NULL;
4475 FILE *tmpfile = NULL;
4476 int *pack_fds = NULL;
4478 TAILQ_INIT(&refs);
4480 #ifndef PROFILE
4481 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4482 NULL)
4483 == -1)
4484 err(1, "pledge");
4485 #endif
4487 limit = get_default_log_limit();
4489 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4490 switch (ch) {
4491 case 'b':
4492 log_branches = 1;
4493 break;
4494 case 'C':
4495 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4496 &errstr);
4497 if (errstr != NULL)
4498 errx(1, "number of context lines is %s: %s",
4499 errstr, optarg);
4500 break;
4501 case 'c':
4502 start_commit = optarg;
4503 break;
4504 case 'd':
4505 show_diffstat = 1;
4506 break;
4507 case 'l':
4508 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4509 if (errstr != NULL)
4510 errx(1, "number of commits is %s: %s",
4511 errstr, optarg);
4512 break;
4513 case 'P':
4514 show_changed_paths = 1;
4515 break;
4516 case 'p':
4517 show_patch = 1;
4518 break;
4519 case 'R':
4520 reverse_display_order = 1;
4521 break;
4522 case 'r':
4523 repo_path = realpath(optarg, NULL);
4524 if (repo_path == NULL)
4525 return got_error_from_errno2("realpath",
4526 optarg);
4527 got_path_strip_trailing_slashes(repo_path);
4528 break;
4529 case 'S':
4530 search_pattern = optarg;
4531 break;
4532 case 's':
4533 one_line = 1;
4534 break;
4535 case 'x':
4536 end_commit = optarg;
4537 break;
4538 default:
4539 usage_log();
4540 /* NOTREACHED */
4544 argc -= optind;
4545 argv += optind;
4547 if (diff_context == -1)
4548 diff_context = 3;
4549 else if (!show_patch)
4550 errx(1, "-C requires -p");
4552 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4553 errx(1, "cannot use -s with -d, -p or -P");
4555 cwd = getcwd(NULL, 0);
4556 if (cwd == NULL) {
4557 error = got_error_from_errno("getcwd");
4558 goto done;
4561 error = got_repo_pack_fds_open(&pack_fds);
4562 if (error != NULL)
4563 goto done;
4565 if (repo_path == NULL) {
4566 error = got_worktree_open(&worktree, cwd);
4567 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4568 goto done;
4569 error = NULL;
4572 if (argc == 1) {
4573 if (worktree) {
4574 error = got_worktree_resolve_path(&path, worktree,
4575 argv[0]);
4576 if (error)
4577 goto done;
4578 } else {
4579 path = strdup(argv[0]);
4580 if (path == NULL) {
4581 error = got_error_from_errno("strdup");
4582 goto done;
4585 } else if (argc != 0)
4586 usage_log();
4588 if (repo_path == NULL) {
4589 repo_path = worktree ?
4590 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4592 if (repo_path == NULL) {
4593 error = got_error_from_errno("strdup");
4594 goto done;
4597 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4598 if (error != NULL)
4599 goto done;
4601 error = apply_unveil(got_repo_get_path(repo), 1,
4602 worktree ? got_worktree_get_root_path(worktree) : NULL);
4603 if (error)
4604 goto done;
4606 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4607 if (error)
4608 goto done;
4610 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4611 if (error)
4612 goto done;
4614 if (start_commit == NULL) {
4615 struct got_reference *head_ref;
4616 struct got_commit_object *commit = NULL;
4617 error = got_ref_open(&head_ref, repo,
4618 worktree ? got_worktree_get_head_ref_name(worktree)
4619 : GOT_REF_HEAD, 0);
4620 if (error != NULL)
4621 goto done;
4622 error = got_ref_resolve(&start_id, repo, head_ref);
4623 got_ref_close(head_ref);
4624 if (error != NULL)
4625 goto done;
4626 error = got_object_open_as_commit(&commit, repo,
4627 start_id);
4628 if (error != NULL)
4629 goto done;
4630 got_object_commit_close(commit);
4631 } else {
4632 error = got_repo_match_object_id(&start_id, NULL,
4633 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4634 if (error != NULL)
4635 goto done;
4637 if (end_commit != NULL) {
4638 error = got_repo_match_object_id(&end_id, NULL,
4639 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4640 if (error != NULL)
4641 goto done;
4644 if (worktree) {
4646 * If a path was specified on the command line it was resolved
4647 * to a path in the work tree above. Prepend the work tree's
4648 * path prefix to obtain the corresponding in-repository path.
4650 if (path) {
4651 const char *prefix;
4652 prefix = got_worktree_get_path_prefix(worktree);
4653 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4654 (path[0] != '\0') ? "/" : "", path) == -1) {
4655 error = got_error_from_errno("asprintf");
4656 goto done;
4659 } else
4660 error = got_repo_map_path(&in_repo_path, repo,
4661 path ? path : "");
4662 if (error != NULL)
4663 goto done;
4664 if (in_repo_path) {
4665 free(path);
4666 path = in_repo_path;
4669 if (worktree) {
4670 /* Release work tree lock. */
4671 got_worktree_close(worktree);
4672 worktree = NULL;
4675 if (search_pattern && show_patch) {
4676 tmpfile = got_opentemp();
4677 if (tmpfile == NULL) {
4678 error = got_error_from_errno("got_opentemp");
4679 goto done;
4683 error = print_commits(start_id, end_id, repo, path ? path : "",
4684 show_changed_paths, show_diffstat, show_patch, search_pattern,
4685 diff_context, limit, log_branches, reverse_display_order,
4686 refs_idmap, one_line, tmpfile);
4687 done:
4688 free(path);
4689 free(repo_path);
4690 free(cwd);
4691 if (worktree)
4692 got_worktree_close(worktree);
4693 if (repo) {
4694 const struct got_error *close_err = got_repo_close(repo);
4695 if (error == NULL)
4696 error = close_err;
4698 if (pack_fds) {
4699 const struct got_error *pack_err =
4700 got_repo_pack_fds_close(pack_fds);
4701 if (error == NULL)
4702 error = pack_err;
4704 if (refs_idmap)
4705 got_reflist_object_id_map_free(refs_idmap);
4706 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4707 error = got_error_from_errno("fclose");
4708 got_ref_list_free(&refs);
4709 return error;
4712 __dead static void
4713 usage_diff(void)
4715 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4716 "[-r repository-path] [object1 object2 | path ...]\n",
4717 getprogname());
4718 exit(1);
4721 struct print_diff_arg {
4722 struct got_repository *repo;
4723 struct got_worktree *worktree;
4724 struct got_diffstat_cb_arg *diffstat;
4725 int diff_context;
4726 const char *id_str;
4727 int header_shown;
4728 int diff_staged;
4729 enum got_diff_algorithm diff_algo;
4730 int ignore_whitespace;
4731 int force_text_diff;
4732 int show_diffstat;
4733 FILE *f1;
4734 FILE *f2;
4735 FILE *outfile;
4739 * Create a file which contains the target path of a symlink so we can feed
4740 * it as content to the diff engine.
4742 static const struct got_error *
4743 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4744 const char *abspath)
4746 const struct got_error *err = NULL;
4747 char target_path[PATH_MAX];
4748 ssize_t target_len, outlen;
4750 *fd = -1;
4752 if (dirfd != -1) {
4753 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4754 if (target_len == -1)
4755 return got_error_from_errno2("readlinkat", abspath);
4756 } else {
4757 target_len = readlink(abspath, target_path, PATH_MAX);
4758 if (target_len == -1)
4759 return got_error_from_errno2("readlink", abspath);
4762 *fd = got_opentempfd();
4763 if (*fd == -1)
4764 return got_error_from_errno("got_opentempfd");
4766 outlen = write(*fd, target_path, target_len);
4767 if (outlen == -1) {
4768 err = got_error_from_errno("got_opentempfd");
4769 goto done;
4772 if (lseek(*fd, 0, SEEK_SET) == -1) {
4773 err = got_error_from_errno2("lseek", abspath);
4774 goto done;
4776 done:
4777 if (err) {
4778 close(*fd);
4779 *fd = -1;
4781 return err;
4784 static const struct got_error *
4785 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4786 const char *path, struct got_object_id *blob_id,
4787 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4788 int dirfd, const char *de_name)
4790 struct print_diff_arg *a = arg;
4791 const struct got_error *err = NULL;
4792 struct got_blob_object *blob1 = NULL;
4793 int fd = -1, fd1 = -1, fd2 = -1;
4794 FILE *f2 = NULL;
4795 char *abspath = NULL, *label1 = NULL;
4796 struct stat sb;
4797 off_t size1 = 0;
4798 int f2_exists = 0;
4800 memset(&sb, 0, sizeof(sb));
4802 if (a->diff_staged) {
4803 if (staged_status != GOT_STATUS_MODIFY &&
4804 staged_status != GOT_STATUS_ADD &&
4805 staged_status != GOT_STATUS_DELETE)
4806 return NULL;
4807 } else {
4808 if (staged_status == GOT_STATUS_DELETE)
4809 return NULL;
4810 if (status == GOT_STATUS_NONEXISTENT)
4811 return got_error_set_errno(ENOENT, path);
4812 if (status != GOT_STATUS_MODIFY &&
4813 status != GOT_STATUS_ADD &&
4814 status != GOT_STATUS_DELETE &&
4815 status != GOT_STATUS_CONFLICT)
4816 return NULL;
4819 err = got_opentemp_truncate(a->f1);
4820 if (err)
4821 return got_error_from_errno("got_opentemp_truncate");
4822 err = got_opentemp_truncate(a->f2);
4823 if (err)
4824 return got_error_from_errno("got_opentemp_truncate");
4826 if (!a->header_shown) {
4827 if (fprintf(a->outfile, "diff %s%s\n",
4828 a->diff_staged ? "-s " : "",
4829 got_worktree_get_root_path(a->worktree)) < 0) {
4830 err = got_error_from_errno("fprintf");
4831 goto done;
4833 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4834 err = got_error_from_errno("fprintf");
4835 goto done;
4837 if (fprintf(a->outfile, "path + %s%s\n",
4838 got_worktree_get_root_path(a->worktree),
4839 a->diff_staged ? " (staged changes)" : "") < 0) {
4840 err = got_error_from_errno("fprintf");
4841 goto done;
4843 a->header_shown = 1;
4846 if (a->diff_staged) {
4847 const char *label1 = NULL, *label2 = NULL;
4848 switch (staged_status) {
4849 case GOT_STATUS_MODIFY:
4850 label1 = path;
4851 label2 = path;
4852 break;
4853 case GOT_STATUS_ADD:
4854 label2 = path;
4855 break;
4856 case GOT_STATUS_DELETE:
4857 label1 = path;
4858 break;
4859 default:
4860 return got_error(GOT_ERR_FILE_STATUS);
4862 fd1 = got_opentempfd();
4863 if (fd1 == -1) {
4864 err = got_error_from_errno("got_opentempfd");
4865 goto done;
4867 fd2 = got_opentempfd();
4868 if (fd2 == -1) {
4869 err = got_error_from_errno("got_opentempfd");
4870 goto done;
4872 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4873 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4874 a->diff_algo, a->diff_context, a->ignore_whitespace,
4875 a->force_text_diff, a->show_diffstat, a->diffstat, a->repo,
4876 a->outfile);
4877 goto done;
4880 fd1 = got_opentempfd();
4881 if (fd1 == -1) {
4882 err = got_error_from_errno("got_opentempfd");
4883 goto done;
4886 if (staged_status == GOT_STATUS_ADD ||
4887 staged_status == GOT_STATUS_MODIFY) {
4888 char *id_str;
4889 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4890 8192, fd1);
4891 if (err)
4892 goto done;
4893 err = got_object_id_str(&id_str, staged_blob_id);
4894 if (err)
4895 goto done;
4896 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4897 err = got_error_from_errno("asprintf");
4898 free(id_str);
4899 goto done;
4901 free(id_str);
4902 } else if (status != GOT_STATUS_ADD) {
4903 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4904 fd1);
4905 if (err)
4906 goto done;
4909 if (status != GOT_STATUS_DELETE) {
4910 if (asprintf(&abspath, "%s/%s",
4911 got_worktree_get_root_path(a->worktree), path) == -1) {
4912 err = got_error_from_errno("asprintf");
4913 goto done;
4916 if (dirfd != -1) {
4917 fd = openat(dirfd, de_name,
4918 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4919 if (fd == -1) {
4920 if (!got_err_open_nofollow_on_symlink()) {
4921 err = got_error_from_errno2("openat",
4922 abspath);
4923 goto done;
4925 err = get_symlink_target_file(&fd, dirfd,
4926 de_name, abspath);
4927 if (err)
4928 goto done;
4930 } else {
4931 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4932 if (fd == -1) {
4933 if (!got_err_open_nofollow_on_symlink()) {
4934 err = got_error_from_errno2("open",
4935 abspath);
4936 goto done;
4938 err = get_symlink_target_file(&fd, dirfd,
4939 de_name, abspath);
4940 if (err)
4941 goto done;
4944 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4945 err = got_error_from_errno2("fstatat", abspath);
4946 goto done;
4948 f2 = fdopen(fd, "r");
4949 if (f2 == NULL) {
4950 err = got_error_from_errno2("fdopen", abspath);
4951 goto done;
4953 fd = -1;
4954 f2_exists = 1;
4957 if (blob1) {
4958 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4959 a->f1, blob1);
4960 if (err)
4961 goto done;
4964 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4965 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4966 a->ignore_whitespace, a->force_text_diff, a->show_diffstat,
4967 a->diffstat, a->outfile);
4968 done:
4969 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4970 err = got_error_from_errno("close");
4971 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4972 err = got_error_from_errno("close");
4973 if (blob1)
4974 got_object_blob_close(blob1);
4975 if (fd != -1 && close(fd) == -1 && err == NULL)
4976 err = got_error_from_errno("close");
4977 if (f2 && fclose(f2) == EOF && err == NULL)
4978 err = got_error_from_errno("fclose");
4979 free(abspath);
4980 return err;
4983 static const struct got_error *
4984 printfile(FILE *f)
4986 char buf[8192];
4987 size_t r;
4989 if (fseeko(f, 0L, SEEK_SET) == -1)
4990 return got_error_from_errno("fseek");
4992 for (;;) {
4993 r = fread(buf, 1, sizeof(buf), f);
4994 if (r == 0) {
4995 if (ferror(f))
4996 return got_error_from_errno("fread");
4997 if (feof(f))
4998 break;
5000 if (fwrite(buf, 1, r, stdout) != r)
5001 return got_ferror(stdout, GOT_ERR_IO);
5004 return NULL;
5007 static const struct got_error *
5008 cmd_diff(int argc, char *argv[])
5010 const struct got_error *error;
5011 struct got_repository *repo = NULL;
5012 struct got_worktree *worktree = NULL;
5013 char *cwd = NULL, *repo_path = NULL;
5014 const char *commit_args[2] = { NULL, NULL };
5015 int ncommit_args = 0;
5016 struct got_object_id *ids[2] = { NULL, NULL };
5017 char *labels[2] = { NULL, NULL };
5018 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5019 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5020 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5021 const char *errstr;
5022 struct got_reflist_head refs;
5023 struct got_pathlist_head diffstat_paths, paths;
5024 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5025 int fd1 = -1, fd2 = -1;
5026 int *pack_fds = NULL;
5027 struct got_diffstat_cb_arg dsa;
5029 memset(&dsa, 0, sizeof(dsa));
5031 TAILQ_INIT(&refs);
5032 TAILQ_INIT(&paths);
5033 TAILQ_INIT(&diffstat_paths);
5035 #ifndef PROFILE
5036 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5037 NULL) == -1)
5038 err(1, "pledge");
5039 #endif
5041 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5042 switch (ch) {
5043 case 'a':
5044 force_text_diff = 1;
5045 break;
5046 case 'C':
5047 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5048 &errstr);
5049 if (errstr != NULL)
5050 errx(1, "number of context lines is %s: %s",
5051 errstr, optarg);
5052 break;
5053 case 'c':
5054 if (ncommit_args >= 2)
5055 errx(1, "too many -c options used");
5056 commit_args[ncommit_args++] = optarg;
5057 break;
5058 case 'd':
5059 show_diffstat = 1;
5060 break;
5061 case 'P':
5062 force_path = 1;
5063 break;
5064 case 'r':
5065 repo_path = realpath(optarg, NULL);
5066 if (repo_path == NULL)
5067 return got_error_from_errno2("realpath",
5068 optarg);
5069 got_path_strip_trailing_slashes(repo_path);
5070 rflag = 1;
5071 break;
5072 case 's':
5073 diff_staged = 1;
5074 break;
5075 case 'w':
5076 ignore_whitespace = 1;
5077 break;
5078 default:
5079 usage_diff();
5080 /* NOTREACHED */
5084 argc -= optind;
5085 argv += optind;
5087 cwd = getcwd(NULL, 0);
5088 if (cwd == NULL) {
5089 error = got_error_from_errno("getcwd");
5090 goto done;
5093 error = got_repo_pack_fds_open(&pack_fds);
5094 if (error != NULL)
5095 goto done;
5097 if (repo_path == NULL) {
5098 error = got_worktree_open(&worktree, cwd);
5099 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5100 goto done;
5101 else
5102 error = NULL;
5103 if (worktree) {
5104 repo_path =
5105 strdup(got_worktree_get_repo_path(worktree));
5106 if (repo_path == NULL) {
5107 error = got_error_from_errno("strdup");
5108 goto done;
5110 } else {
5111 repo_path = strdup(cwd);
5112 if (repo_path == NULL) {
5113 error = got_error_from_errno("strdup");
5114 goto done;
5119 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5120 free(repo_path);
5121 if (error != NULL)
5122 goto done;
5124 if (show_diffstat) {
5125 dsa.paths = &diffstat_paths;
5126 dsa.force_text = force_text_diff;
5127 dsa.ignore_ws = ignore_whitespace;
5128 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5131 if (rflag || worktree == NULL || ncommit_args > 0) {
5132 if (force_path) {
5133 error = got_error_msg(GOT_ERR_NOT_IMPL,
5134 "-P option can only be used when diffing "
5135 "a work tree");
5136 goto done;
5138 if (diff_staged) {
5139 error = got_error_msg(GOT_ERR_NOT_IMPL,
5140 "-s option can only be used when diffing "
5141 "a work tree");
5142 goto done;
5146 error = apply_unveil(got_repo_get_path(repo), 1,
5147 worktree ? got_worktree_get_root_path(worktree) : NULL);
5148 if (error)
5149 goto done;
5151 if ((!force_path && argc == 2) || ncommit_args > 0) {
5152 int obj_type = (ncommit_args > 0 ?
5153 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5154 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5155 NULL);
5156 if (error)
5157 goto done;
5158 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5159 const char *arg;
5160 if (ncommit_args > 0)
5161 arg = commit_args[i];
5162 else
5163 arg = argv[i];
5164 error = got_repo_match_object_id(&ids[i], &labels[i],
5165 arg, obj_type, &refs, repo);
5166 if (error) {
5167 if (error->code != GOT_ERR_NOT_REF &&
5168 error->code != GOT_ERR_NO_OBJ)
5169 goto done;
5170 if (ncommit_args > 0)
5171 goto done;
5172 error = NULL;
5173 break;
5178 f1 = got_opentemp();
5179 if (f1 == NULL) {
5180 error = got_error_from_errno("got_opentemp");
5181 goto done;
5184 f2 = got_opentemp();
5185 if (f2 == NULL) {
5186 error = got_error_from_errno("got_opentemp");
5187 goto done;
5190 outfile = got_opentemp();
5191 if (outfile == NULL) {
5192 error = got_error_from_errno("got_opentemp");
5193 goto done;
5196 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5197 struct print_diff_arg arg;
5198 char *id_str;
5200 if (worktree == NULL) {
5201 if (argc == 2 && ids[0] == NULL) {
5202 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5203 goto done;
5204 } else if (argc == 2 && ids[1] == NULL) {
5205 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5206 goto done;
5207 } else if (argc > 0) {
5208 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5209 "%s", "specified paths cannot be resolved");
5210 goto done;
5211 } else {
5212 error = got_error(GOT_ERR_NOT_WORKTREE);
5213 goto done;
5217 error = get_worktree_paths_from_argv(&paths, argc, argv,
5218 worktree);
5219 if (error)
5220 goto done;
5222 error = got_object_id_str(&id_str,
5223 got_worktree_get_base_commit_id(worktree));
5224 if (error)
5225 goto done;
5226 arg.repo = repo;
5227 arg.worktree = worktree;
5228 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5229 arg.diff_context = diff_context;
5230 arg.id_str = id_str;
5231 arg.header_shown = 0;
5232 arg.diff_staged = diff_staged;
5233 arg.ignore_whitespace = ignore_whitespace;
5234 arg.force_text_diff = force_text_diff;
5235 arg.show_diffstat = show_diffstat;
5236 arg.diffstat = &dsa;
5237 arg.f1 = f1;
5238 arg.f2 = f2;
5239 arg.outfile = outfile;
5241 error = got_worktree_status(worktree, &paths, repo, 0,
5242 print_diff, &arg, check_cancelled, NULL);
5243 free(id_str);
5244 if (error)
5245 goto done;
5247 if (show_diffstat && dsa.nfiles > 0) {
5248 char *header;
5250 if (asprintf(&header, "diffstat %s%s",
5251 diff_staged ? "-s " : "",
5252 got_worktree_get_root_path(worktree)) == -1)
5253 goto done;
5255 error = print_diffstat(&dsa, &diffstat_paths, header);
5256 free(header);
5257 if (error)
5258 goto done;
5261 error = printfile(outfile);
5262 goto done;
5265 if (ncommit_args == 1) {
5266 struct got_commit_object *commit;
5267 error = got_object_open_as_commit(&commit, repo, ids[0]);
5268 if (error)
5269 goto done;
5271 labels[1] = labels[0];
5272 ids[1] = ids[0];
5273 if (got_object_commit_get_nparents(commit) > 0) {
5274 const struct got_object_id_queue *pids;
5275 struct got_object_qid *pid;
5276 pids = got_object_commit_get_parent_ids(commit);
5277 pid = STAILQ_FIRST(pids);
5278 ids[0] = got_object_id_dup(&pid->id);
5279 if (ids[0] == NULL) {
5280 error = got_error_from_errno(
5281 "got_object_id_dup");
5282 got_object_commit_close(commit);
5283 goto done;
5285 error = got_object_id_str(&labels[0], ids[0]);
5286 if (error) {
5287 got_object_commit_close(commit);
5288 goto done;
5290 } else {
5291 ids[0] = NULL;
5292 labels[0] = strdup("/dev/null");
5293 if (labels[0] == NULL) {
5294 error = got_error_from_errno("strdup");
5295 got_object_commit_close(commit);
5296 goto done;
5300 got_object_commit_close(commit);
5303 if (ncommit_args == 0 && argc > 2) {
5304 error = got_error_msg(GOT_ERR_BAD_PATH,
5305 "path arguments cannot be used when diffing two objects");
5306 goto done;
5309 if (ids[0]) {
5310 error = got_object_get_type(&type1, repo, ids[0]);
5311 if (error)
5312 goto done;
5315 error = got_object_get_type(&type2, repo, ids[1]);
5316 if (error)
5317 goto done;
5318 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5319 error = got_error(GOT_ERR_OBJ_TYPE);
5320 goto done;
5322 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5323 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5324 "path arguments cannot be used when diffing blobs");
5325 goto done;
5328 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5329 char *in_repo_path;
5330 struct got_pathlist_entry *new;
5331 if (worktree) {
5332 const char *prefix;
5333 char *p;
5334 error = got_worktree_resolve_path(&p, worktree,
5335 argv[i]);
5336 if (error)
5337 goto done;
5338 prefix = got_worktree_get_path_prefix(worktree);
5339 while (prefix[0] == '/')
5340 prefix++;
5341 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5342 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5343 p) == -1) {
5344 error = got_error_from_errno("asprintf");
5345 free(p);
5346 goto done;
5348 free(p);
5349 } else {
5350 char *mapped_path, *s;
5351 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5352 if (error)
5353 goto done;
5354 s = mapped_path;
5355 while (s[0] == '/')
5356 s++;
5357 in_repo_path = strdup(s);
5358 if (in_repo_path == NULL) {
5359 error = got_error_from_errno("asprintf");
5360 free(mapped_path);
5361 goto done;
5363 free(mapped_path);
5366 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5367 if (error || new == NULL /* duplicate */)
5368 free(in_repo_path);
5369 if (error)
5370 goto done;
5373 if (worktree) {
5374 /* Release work tree lock. */
5375 got_worktree_close(worktree);
5376 worktree = NULL;
5379 fd1 = got_opentempfd();
5380 if (fd1 == -1) {
5381 error = got_error_from_errno("got_opentempfd");
5382 goto done;
5385 fd2 = got_opentempfd();
5386 if (fd2 == -1) {
5387 error = got_error_from_errno("got_opentempfd");
5388 goto done;
5391 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5392 case GOT_OBJ_TYPE_BLOB:
5393 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5394 fd1, fd2, ids[0], ids[1], NULL, NULL,
5395 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5396 ignore_whitespace, force_text_diff, show_diffstat,
5397 show_diffstat ? &dsa : NULL, repo, outfile);
5398 break;
5399 case GOT_OBJ_TYPE_TREE:
5400 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5401 ids[0], ids[1], &paths, "", "",
5402 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5403 ignore_whitespace, force_text_diff, show_diffstat,
5404 show_diffstat ? &dsa : NULL, repo, outfile);
5405 break;
5406 case GOT_OBJ_TYPE_COMMIT:
5407 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5408 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5409 fd1, fd2, ids[0], ids[1], &paths,
5410 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5411 ignore_whitespace, force_text_diff, show_diffstat,
5412 show_diffstat ? &dsa : NULL, repo, outfile);
5413 break;
5414 default:
5415 error = got_error(GOT_ERR_OBJ_TYPE);
5417 if (error)
5418 goto done;
5420 if (show_diffstat && dsa.nfiles > 0) {
5421 char *header = NULL;
5423 if (asprintf(&header, "diffstat %s %s",
5424 labels[0], labels[1]) == -1)
5425 goto done;
5427 error = print_diffstat(&dsa, &diffstat_paths, header);
5428 free(header);
5429 if (error)
5430 goto done;
5433 error = printfile(outfile);
5435 done:
5436 free(labels[0]);
5437 free(labels[1]);
5438 free(ids[0]);
5439 free(ids[1]);
5440 if (worktree)
5441 got_worktree_close(worktree);
5442 if (repo) {
5443 const struct got_error *close_err = got_repo_close(repo);
5444 if (error == NULL)
5445 error = close_err;
5447 if (pack_fds) {
5448 const struct got_error *pack_err =
5449 got_repo_pack_fds_close(pack_fds);
5450 if (error == NULL)
5451 error = pack_err;
5453 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5454 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5455 got_ref_list_free(&refs);
5456 if (outfile && fclose(outfile) == EOF && error == NULL)
5457 error = got_error_from_errno("fclose");
5458 if (f1 && fclose(f1) == EOF && error == NULL)
5459 error = got_error_from_errno("fclose");
5460 if (f2 && fclose(f2) == EOF && error == NULL)
5461 error = got_error_from_errno("fclose");
5462 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5463 error = got_error_from_errno("close");
5464 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5465 error = got_error_from_errno("close");
5466 return error;
5469 __dead static void
5470 usage_blame(void)
5472 fprintf(stderr,
5473 "usage: %s blame [-c commit] [-r repository-path] path\n",
5474 getprogname());
5475 exit(1);
5478 struct blame_line {
5479 int annotated;
5480 char *id_str;
5481 char *committer;
5482 char datebuf[11]; /* YYYY-MM-DD + NUL */
5485 struct blame_cb_args {
5486 struct blame_line *lines;
5487 int nlines;
5488 int nlines_prec;
5489 int lineno_cur;
5490 off_t *line_offsets;
5491 FILE *f;
5492 struct got_repository *repo;
5495 static const struct got_error *
5496 blame_cb(void *arg, int nlines, int lineno,
5497 struct got_commit_object *commit, struct got_object_id *id)
5499 const struct got_error *err = NULL;
5500 struct blame_cb_args *a = arg;
5501 struct blame_line *bline;
5502 char *line = NULL;
5503 size_t linesize = 0;
5504 off_t offset;
5505 struct tm tm;
5506 time_t committer_time;
5508 if (nlines != a->nlines ||
5509 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5510 return got_error(GOT_ERR_RANGE);
5512 if (sigint_received)
5513 return got_error(GOT_ERR_ITER_COMPLETED);
5515 if (lineno == -1)
5516 return NULL; /* no change in this commit */
5518 /* Annotate this line. */
5519 bline = &a->lines[lineno - 1];
5520 if (bline->annotated)
5521 return NULL;
5522 err = got_object_id_str(&bline->id_str, id);
5523 if (err)
5524 return err;
5526 bline->committer = strdup(got_object_commit_get_committer(commit));
5527 if (bline->committer == NULL) {
5528 err = got_error_from_errno("strdup");
5529 goto done;
5532 committer_time = got_object_commit_get_committer_time(commit);
5533 if (gmtime_r(&committer_time, &tm) == NULL)
5534 return got_error_from_errno("gmtime_r");
5535 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5536 &tm) == 0) {
5537 err = got_error(GOT_ERR_NO_SPACE);
5538 goto done;
5540 bline->annotated = 1;
5542 /* Print lines annotated so far. */
5543 bline = &a->lines[a->lineno_cur - 1];
5544 if (!bline->annotated)
5545 goto done;
5547 offset = a->line_offsets[a->lineno_cur - 1];
5548 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5549 err = got_error_from_errno("fseeko");
5550 goto done;
5553 while (a->lineno_cur <= a->nlines && bline->annotated) {
5554 char *smallerthan, *at, *nl, *committer;
5555 size_t len;
5557 if (getline(&line, &linesize, a->f) == -1) {
5558 if (ferror(a->f))
5559 err = got_error_from_errno("getline");
5560 break;
5563 committer = bline->committer;
5564 smallerthan = strchr(committer, '<');
5565 if (smallerthan && smallerthan[1] != '\0')
5566 committer = smallerthan + 1;
5567 at = strchr(committer, '@');
5568 if (at)
5569 *at = '\0';
5570 len = strlen(committer);
5571 if (len >= 9)
5572 committer[8] = '\0';
5574 nl = strchr(line, '\n');
5575 if (nl)
5576 *nl = '\0';
5577 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5578 bline->id_str, bline->datebuf, committer, line);
5580 a->lineno_cur++;
5581 bline = &a->lines[a->lineno_cur - 1];
5583 done:
5584 free(line);
5585 return err;
5588 static const struct got_error *
5589 cmd_blame(int argc, char *argv[])
5591 const struct got_error *error;
5592 struct got_repository *repo = NULL;
5593 struct got_worktree *worktree = NULL;
5594 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5595 char *link_target = NULL;
5596 struct got_object_id *obj_id = NULL;
5597 struct got_object_id *commit_id = NULL;
5598 struct got_commit_object *commit = NULL;
5599 struct got_blob_object *blob = NULL;
5600 char *commit_id_str = NULL;
5601 struct blame_cb_args bca;
5602 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5603 off_t filesize;
5604 int *pack_fds = NULL;
5605 FILE *f1 = NULL, *f2 = NULL;
5607 fd1 = got_opentempfd();
5608 if (fd1 == -1)
5609 return got_error_from_errno("got_opentempfd");
5611 memset(&bca, 0, sizeof(bca));
5613 #ifndef PROFILE
5614 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5615 NULL) == -1)
5616 err(1, "pledge");
5617 #endif
5619 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5620 switch (ch) {
5621 case 'c':
5622 commit_id_str = optarg;
5623 break;
5624 case 'r':
5625 repo_path = realpath(optarg, NULL);
5626 if (repo_path == NULL)
5627 return got_error_from_errno2("realpath",
5628 optarg);
5629 got_path_strip_trailing_slashes(repo_path);
5630 break;
5631 default:
5632 usage_blame();
5633 /* NOTREACHED */
5637 argc -= optind;
5638 argv += optind;
5640 if (argc == 1)
5641 path = argv[0];
5642 else
5643 usage_blame();
5645 cwd = getcwd(NULL, 0);
5646 if (cwd == NULL) {
5647 error = got_error_from_errno("getcwd");
5648 goto done;
5651 error = got_repo_pack_fds_open(&pack_fds);
5652 if (error != NULL)
5653 goto done;
5655 if (repo_path == NULL) {
5656 error = got_worktree_open(&worktree, cwd);
5657 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5658 goto done;
5659 else
5660 error = NULL;
5661 if (worktree) {
5662 repo_path =
5663 strdup(got_worktree_get_repo_path(worktree));
5664 if (repo_path == NULL) {
5665 error = got_error_from_errno("strdup");
5666 if (error)
5667 goto done;
5669 } else {
5670 repo_path = strdup(cwd);
5671 if (repo_path == NULL) {
5672 error = got_error_from_errno("strdup");
5673 goto done;
5678 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5679 if (error != NULL)
5680 goto done;
5682 if (worktree) {
5683 const char *prefix = got_worktree_get_path_prefix(worktree);
5684 char *p;
5686 error = got_worktree_resolve_path(&p, worktree, path);
5687 if (error)
5688 goto done;
5689 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5690 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5691 p) == -1) {
5692 error = got_error_from_errno("asprintf");
5693 free(p);
5694 goto done;
5696 free(p);
5697 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5698 } else {
5699 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5700 if (error)
5701 goto done;
5702 error = got_repo_map_path(&in_repo_path, repo, path);
5704 if (error)
5705 goto done;
5707 if (commit_id_str == NULL) {
5708 struct got_reference *head_ref;
5709 error = got_ref_open(&head_ref, repo, worktree ?
5710 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5711 if (error != NULL)
5712 goto done;
5713 error = got_ref_resolve(&commit_id, repo, head_ref);
5714 got_ref_close(head_ref);
5715 if (error != NULL)
5716 goto done;
5717 } else {
5718 struct got_reflist_head refs;
5719 TAILQ_INIT(&refs);
5720 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5721 NULL);
5722 if (error)
5723 goto done;
5724 error = got_repo_match_object_id(&commit_id, NULL,
5725 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5726 got_ref_list_free(&refs);
5727 if (error)
5728 goto done;
5731 if (worktree) {
5732 /* Release work tree lock. */
5733 got_worktree_close(worktree);
5734 worktree = NULL;
5737 error = got_object_open_as_commit(&commit, repo, commit_id);
5738 if (error)
5739 goto done;
5741 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5742 commit, repo);
5743 if (error)
5744 goto done;
5746 error = got_object_id_by_path(&obj_id, repo, commit,
5747 link_target ? link_target : in_repo_path);
5748 if (error)
5749 goto done;
5751 error = got_object_get_type(&obj_type, repo, obj_id);
5752 if (error)
5753 goto done;
5755 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5756 error = got_error_path(link_target ? link_target : in_repo_path,
5757 GOT_ERR_OBJ_TYPE);
5758 goto done;
5761 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5762 if (error)
5763 goto done;
5764 bca.f = got_opentemp();
5765 if (bca.f == NULL) {
5766 error = got_error_from_errno("got_opentemp");
5767 goto done;
5769 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5770 &bca.line_offsets, bca.f, blob);
5771 if (error || bca.nlines == 0)
5772 goto done;
5774 /* Don't include \n at EOF in the blame line count. */
5775 if (bca.line_offsets[bca.nlines - 1] == filesize)
5776 bca.nlines--;
5778 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5779 if (bca.lines == NULL) {
5780 error = got_error_from_errno("calloc");
5781 goto done;
5783 bca.lineno_cur = 1;
5784 bca.nlines_prec = 0;
5785 i = bca.nlines;
5786 while (i > 0) {
5787 i /= 10;
5788 bca.nlines_prec++;
5790 bca.repo = repo;
5792 fd2 = got_opentempfd();
5793 if (fd2 == -1) {
5794 error = got_error_from_errno("got_opentempfd");
5795 goto done;
5797 fd3 = got_opentempfd();
5798 if (fd3 == -1) {
5799 error = got_error_from_errno("got_opentempfd");
5800 goto done;
5802 f1 = got_opentemp();
5803 if (f1 == NULL) {
5804 error = got_error_from_errno("got_opentemp");
5805 goto done;
5807 f2 = got_opentemp();
5808 if (f2 == NULL) {
5809 error = got_error_from_errno("got_opentemp");
5810 goto done;
5812 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5813 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5814 check_cancelled, NULL, fd2, fd3, f1, f2);
5815 done:
5816 free(in_repo_path);
5817 free(link_target);
5818 free(repo_path);
5819 free(cwd);
5820 free(commit_id);
5821 free(obj_id);
5822 if (commit)
5823 got_object_commit_close(commit);
5825 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5826 error = got_error_from_errno("close");
5827 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5828 error = got_error_from_errno("close");
5829 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5830 error = got_error_from_errno("close");
5831 if (f1 && fclose(f1) == EOF && error == NULL)
5832 error = got_error_from_errno("fclose");
5833 if (f2 && fclose(f2) == EOF && error == NULL)
5834 error = got_error_from_errno("fclose");
5836 if (blob)
5837 got_object_blob_close(blob);
5838 if (worktree)
5839 got_worktree_close(worktree);
5840 if (repo) {
5841 const struct got_error *close_err = got_repo_close(repo);
5842 if (error == NULL)
5843 error = close_err;
5845 if (pack_fds) {
5846 const struct got_error *pack_err =
5847 got_repo_pack_fds_close(pack_fds);
5848 if (error == NULL)
5849 error = pack_err;
5851 if (bca.lines) {
5852 for (i = 0; i < bca.nlines; i++) {
5853 struct blame_line *bline = &bca.lines[i];
5854 free(bline->id_str);
5855 free(bline->committer);
5857 free(bca.lines);
5859 free(bca.line_offsets);
5860 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5861 error = got_error_from_errno("fclose");
5862 return error;
5865 __dead static void
5866 usage_tree(void)
5868 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5869 "[path]\n", getprogname());
5870 exit(1);
5873 static const struct got_error *
5874 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5875 const char *root_path, struct got_repository *repo)
5877 const struct got_error *err = NULL;
5878 int is_root_path = (strcmp(path, root_path) == 0);
5879 const char *modestr = "";
5880 mode_t mode = got_tree_entry_get_mode(te);
5881 char *link_target = NULL;
5883 path += strlen(root_path);
5884 while (path[0] == '/')
5885 path++;
5887 if (got_object_tree_entry_is_submodule(te))
5888 modestr = "$";
5889 else if (S_ISLNK(mode)) {
5890 int i;
5892 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5893 if (err)
5894 return err;
5895 for (i = 0; i < strlen(link_target); i++) {
5896 if (!isprint((unsigned char)link_target[i]))
5897 link_target[i] = '?';
5900 modestr = "@";
5902 else if (S_ISDIR(mode))
5903 modestr = "/";
5904 else if (mode & S_IXUSR)
5905 modestr = "*";
5907 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5908 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5909 link_target ? " -> ": "", link_target ? link_target : "");
5911 free(link_target);
5912 return NULL;
5915 static const struct got_error *
5916 print_tree(const char *path, struct got_commit_object *commit,
5917 int show_ids, int recurse, const char *root_path,
5918 struct got_repository *repo)
5920 const struct got_error *err = NULL;
5921 struct got_object_id *tree_id = NULL;
5922 struct got_tree_object *tree = NULL;
5923 int nentries, i;
5925 err = got_object_id_by_path(&tree_id, repo, commit, path);
5926 if (err)
5927 goto done;
5929 err = got_object_open_as_tree(&tree, repo, tree_id);
5930 if (err)
5931 goto done;
5932 nentries = got_object_tree_get_nentries(tree);
5933 for (i = 0; i < nentries; i++) {
5934 struct got_tree_entry *te;
5935 char *id = NULL;
5937 if (sigint_received || sigpipe_received)
5938 break;
5940 te = got_object_tree_get_entry(tree, i);
5941 if (show_ids) {
5942 char *id_str;
5943 err = got_object_id_str(&id_str,
5944 got_tree_entry_get_id(te));
5945 if (err)
5946 goto done;
5947 if (asprintf(&id, "%s ", id_str) == -1) {
5948 err = got_error_from_errno("asprintf");
5949 free(id_str);
5950 goto done;
5952 free(id_str);
5954 err = print_entry(te, id, path, root_path, repo);
5955 free(id);
5956 if (err)
5957 goto done;
5959 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5960 char *child_path;
5961 if (asprintf(&child_path, "%s%s%s", path,
5962 path[0] == '/' && path[1] == '\0' ? "" : "/",
5963 got_tree_entry_get_name(te)) == -1) {
5964 err = got_error_from_errno("asprintf");
5965 goto done;
5967 err = print_tree(child_path, commit, show_ids, 1,
5968 root_path, repo);
5969 free(child_path);
5970 if (err)
5971 goto done;
5974 done:
5975 if (tree)
5976 got_object_tree_close(tree);
5977 free(tree_id);
5978 return err;
5981 static const struct got_error *
5982 cmd_tree(int argc, char *argv[])
5984 const struct got_error *error;
5985 struct got_repository *repo = NULL;
5986 struct got_worktree *worktree = NULL;
5987 const char *path, *refname = NULL;
5988 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5989 struct got_object_id *commit_id = NULL;
5990 struct got_commit_object *commit = NULL;
5991 char *commit_id_str = NULL;
5992 int show_ids = 0, recurse = 0;
5993 int ch;
5994 int *pack_fds = NULL;
5996 #ifndef PROFILE
5997 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5998 NULL) == -1)
5999 err(1, "pledge");
6000 #endif
6002 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6003 switch (ch) {
6004 case 'c':
6005 commit_id_str = optarg;
6006 break;
6007 case 'i':
6008 show_ids = 1;
6009 break;
6010 case 'R':
6011 recurse = 1;
6012 break;
6013 case 'r':
6014 repo_path = realpath(optarg, NULL);
6015 if (repo_path == NULL)
6016 return got_error_from_errno2("realpath",
6017 optarg);
6018 got_path_strip_trailing_slashes(repo_path);
6019 break;
6020 default:
6021 usage_tree();
6022 /* NOTREACHED */
6026 argc -= optind;
6027 argv += optind;
6029 if (argc == 1)
6030 path = argv[0];
6031 else if (argc > 1)
6032 usage_tree();
6033 else
6034 path = NULL;
6036 cwd = getcwd(NULL, 0);
6037 if (cwd == NULL) {
6038 error = got_error_from_errno("getcwd");
6039 goto done;
6042 error = got_repo_pack_fds_open(&pack_fds);
6043 if (error != NULL)
6044 goto done;
6046 if (repo_path == NULL) {
6047 error = got_worktree_open(&worktree, cwd);
6048 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6049 goto done;
6050 else
6051 error = NULL;
6052 if (worktree) {
6053 repo_path =
6054 strdup(got_worktree_get_repo_path(worktree));
6055 if (repo_path == NULL)
6056 error = got_error_from_errno("strdup");
6057 if (error)
6058 goto done;
6059 } else {
6060 repo_path = strdup(cwd);
6061 if (repo_path == NULL) {
6062 error = got_error_from_errno("strdup");
6063 goto done;
6068 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6069 if (error != NULL)
6070 goto done;
6072 if (worktree) {
6073 const char *prefix = got_worktree_get_path_prefix(worktree);
6074 char *p;
6076 if (path == NULL)
6077 path = "";
6078 error = got_worktree_resolve_path(&p, worktree, path);
6079 if (error)
6080 goto done;
6081 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6082 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6083 p) == -1) {
6084 error = got_error_from_errno("asprintf");
6085 free(p);
6086 goto done;
6088 free(p);
6089 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6090 if (error)
6091 goto done;
6092 } else {
6093 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6094 if (error)
6095 goto done;
6096 if (path == NULL)
6097 path = "/";
6098 error = got_repo_map_path(&in_repo_path, repo, path);
6099 if (error != NULL)
6100 goto done;
6103 if (commit_id_str == NULL) {
6104 struct got_reference *head_ref;
6105 if (worktree)
6106 refname = got_worktree_get_head_ref_name(worktree);
6107 else
6108 refname = GOT_REF_HEAD;
6109 error = got_ref_open(&head_ref, repo, refname, 0);
6110 if (error != NULL)
6111 goto done;
6112 error = got_ref_resolve(&commit_id, repo, head_ref);
6113 got_ref_close(head_ref);
6114 if (error != NULL)
6115 goto done;
6116 } else {
6117 struct got_reflist_head refs;
6118 TAILQ_INIT(&refs);
6119 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6120 NULL);
6121 if (error)
6122 goto done;
6123 error = got_repo_match_object_id(&commit_id, NULL,
6124 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6125 got_ref_list_free(&refs);
6126 if (error)
6127 goto done;
6130 if (worktree) {
6131 /* Release work tree lock. */
6132 got_worktree_close(worktree);
6133 worktree = NULL;
6136 error = got_object_open_as_commit(&commit, repo, commit_id);
6137 if (error)
6138 goto done;
6140 error = print_tree(in_repo_path, commit, show_ids, recurse,
6141 in_repo_path, repo);
6142 done:
6143 free(in_repo_path);
6144 free(repo_path);
6145 free(cwd);
6146 free(commit_id);
6147 if (commit)
6148 got_object_commit_close(commit);
6149 if (worktree)
6150 got_worktree_close(worktree);
6151 if (repo) {
6152 const struct got_error *close_err = got_repo_close(repo);
6153 if (error == NULL)
6154 error = close_err;
6156 if (pack_fds) {
6157 const struct got_error *pack_err =
6158 got_repo_pack_fds_close(pack_fds);
6159 if (error == NULL)
6160 error = pack_err;
6162 return error;
6165 __dead static void
6166 usage_status(void)
6168 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6169 "[-s status-codes] [path ...]\n", getprogname());
6170 exit(1);
6173 struct got_status_arg {
6174 char *status_codes;
6175 int suppress;
6178 static const struct got_error *
6179 print_status(void *arg, unsigned char status, unsigned char staged_status,
6180 const char *path, struct got_object_id *blob_id,
6181 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6182 int dirfd, const char *de_name)
6184 struct got_status_arg *st = arg;
6186 if (status == staged_status && (status == GOT_STATUS_DELETE))
6187 status = GOT_STATUS_NO_CHANGE;
6188 if (st != NULL && st->status_codes) {
6189 size_t ncodes = strlen(st->status_codes);
6190 int i, j = 0;
6192 for (i = 0; i < ncodes ; i++) {
6193 if (st->suppress) {
6194 if (status == st->status_codes[i] ||
6195 staged_status == st->status_codes[i]) {
6196 j++;
6197 continue;
6199 } else {
6200 if (status == st->status_codes[i] ||
6201 staged_status == st->status_codes[i])
6202 break;
6206 if (st->suppress && j == 0)
6207 goto print;
6209 if (i == ncodes)
6210 return NULL;
6212 print:
6213 printf("%c%c %s\n", status, staged_status, path);
6214 return NULL;
6217 static const struct got_error *
6218 cmd_status(int argc, char *argv[])
6220 const struct got_error *error = NULL;
6221 struct got_repository *repo = NULL;
6222 struct got_worktree *worktree = NULL;
6223 struct got_status_arg st;
6224 char *cwd = NULL;
6225 struct got_pathlist_head paths;
6226 int ch, i, no_ignores = 0;
6227 int *pack_fds = NULL;
6229 TAILQ_INIT(&paths);
6231 memset(&st, 0, sizeof(st));
6232 st.status_codes = NULL;
6233 st.suppress = 0;
6235 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6236 switch (ch) {
6237 case 'I':
6238 no_ignores = 1;
6239 break;
6240 case 'S':
6241 if (st.status_codes != NULL && st.suppress == 0)
6242 option_conflict('S', 's');
6243 st.suppress = 1;
6244 /* fallthrough */
6245 case 's':
6246 for (i = 0; i < strlen(optarg); i++) {
6247 switch (optarg[i]) {
6248 case GOT_STATUS_MODIFY:
6249 case GOT_STATUS_ADD:
6250 case GOT_STATUS_DELETE:
6251 case GOT_STATUS_CONFLICT:
6252 case GOT_STATUS_MISSING:
6253 case GOT_STATUS_OBSTRUCTED:
6254 case GOT_STATUS_UNVERSIONED:
6255 case GOT_STATUS_MODE_CHANGE:
6256 case GOT_STATUS_NONEXISTENT:
6257 break;
6258 default:
6259 errx(1, "invalid status code '%c'",
6260 optarg[i]);
6263 if (ch == 's' && st.suppress)
6264 option_conflict('s', 'S');
6265 st.status_codes = optarg;
6266 break;
6267 default:
6268 usage_status();
6269 /* NOTREACHED */
6273 argc -= optind;
6274 argv += optind;
6276 #ifndef PROFILE
6277 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6278 NULL) == -1)
6279 err(1, "pledge");
6280 #endif
6281 cwd = getcwd(NULL, 0);
6282 if (cwd == NULL) {
6283 error = got_error_from_errno("getcwd");
6284 goto done;
6287 error = got_repo_pack_fds_open(&pack_fds);
6288 if (error != NULL)
6289 goto done;
6291 error = got_worktree_open(&worktree, cwd);
6292 if (error) {
6293 if (error->code == GOT_ERR_NOT_WORKTREE)
6294 error = wrap_not_worktree_error(error, "status", cwd);
6295 goto done;
6298 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6299 NULL, pack_fds);
6300 if (error != NULL)
6301 goto done;
6303 error = apply_unveil(got_repo_get_path(repo), 1,
6304 got_worktree_get_root_path(worktree));
6305 if (error)
6306 goto done;
6308 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6309 if (error)
6310 goto done;
6312 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6313 print_status, &st, check_cancelled, NULL);
6314 done:
6315 if (pack_fds) {
6316 const struct got_error *pack_err =
6317 got_repo_pack_fds_close(pack_fds);
6318 if (error == NULL)
6319 error = pack_err;
6322 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6323 free(cwd);
6324 return error;
6327 __dead static void
6328 usage_ref(void)
6330 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6331 "[-s reference] [name]\n", getprogname());
6332 exit(1);
6335 static const struct got_error *
6336 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6338 static const struct got_error *err = NULL;
6339 struct got_reflist_head refs;
6340 struct got_reflist_entry *re;
6342 TAILQ_INIT(&refs);
6343 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6344 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6345 repo);
6346 if (err)
6347 return err;
6349 TAILQ_FOREACH(re, &refs, entry) {
6350 char *refstr;
6351 refstr = got_ref_to_str(re->ref);
6352 if (refstr == NULL) {
6353 err = got_error_from_errno("got_ref_to_str");
6354 break;
6356 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6357 free(refstr);
6360 got_ref_list_free(&refs);
6361 return err;
6364 static const struct got_error *
6365 delete_ref_by_name(struct got_repository *repo, const char *refname)
6367 const struct got_error *err;
6368 struct got_reference *ref;
6370 err = got_ref_open(&ref, repo, refname, 0);
6371 if (err)
6372 return err;
6374 err = delete_ref(repo, ref);
6375 got_ref_close(ref);
6376 return err;
6379 static const struct got_error *
6380 add_ref(struct got_repository *repo, const char *refname, const char *target)
6382 const struct got_error *err = NULL;
6383 struct got_object_id *id = NULL;
6384 struct got_reference *ref = NULL;
6385 struct got_reflist_head refs;
6388 * Don't let the user create a reference name with a leading '-'.
6389 * While technically a valid reference name, this case is usually
6390 * an unintended typo.
6392 if (refname[0] == '-')
6393 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6395 TAILQ_INIT(&refs);
6396 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6397 if (err)
6398 goto done;
6399 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6400 &refs, repo);
6401 got_ref_list_free(&refs);
6402 if (err)
6403 goto done;
6405 err = got_ref_alloc(&ref, refname, id);
6406 if (err)
6407 goto done;
6409 err = got_ref_write(ref, repo);
6410 done:
6411 if (ref)
6412 got_ref_close(ref);
6413 free(id);
6414 return err;
6417 static const struct got_error *
6418 add_symref(struct got_repository *repo, const char *refname, const char *target)
6420 const struct got_error *err = NULL;
6421 struct got_reference *ref = NULL;
6422 struct got_reference *target_ref = NULL;
6425 * Don't let the user create a reference name with a leading '-'.
6426 * While technically a valid reference name, this case is usually
6427 * an unintended typo.
6429 if (refname[0] == '-')
6430 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6432 err = got_ref_open(&target_ref, repo, target, 0);
6433 if (err)
6434 return err;
6436 err = got_ref_alloc_symref(&ref, refname, target_ref);
6437 if (err)
6438 goto done;
6440 err = got_ref_write(ref, repo);
6441 done:
6442 if (target_ref)
6443 got_ref_close(target_ref);
6444 if (ref)
6445 got_ref_close(ref);
6446 return err;
6449 static const struct got_error *
6450 cmd_ref(int argc, char *argv[])
6452 const struct got_error *error = NULL;
6453 struct got_repository *repo = NULL;
6454 struct got_worktree *worktree = NULL;
6455 char *cwd = NULL, *repo_path = NULL;
6456 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6457 const char *obj_arg = NULL, *symref_target= NULL;
6458 char *refname = NULL;
6459 int *pack_fds = NULL;
6461 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6462 switch (ch) {
6463 case 'c':
6464 obj_arg = optarg;
6465 break;
6466 case 'd':
6467 do_delete = 1;
6468 break;
6469 case 'l':
6470 do_list = 1;
6471 break;
6472 case 'r':
6473 repo_path = realpath(optarg, NULL);
6474 if (repo_path == NULL)
6475 return got_error_from_errno2("realpath",
6476 optarg);
6477 got_path_strip_trailing_slashes(repo_path);
6478 break;
6479 case 's':
6480 symref_target = optarg;
6481 break;
6482 case 't':
6483 sort_by_time = 1;
6484 break;
6485 default:
6486 usage_ref();
6487 /* NOTREACHED */
6491 if (obj_arg && do_list)
6492 option_conflict('c', 'l');
6493 if (obj_arg && do_delete)
6494 option_conflict('c', 'd');
6495 if (obj_arg && symref_target)
6496 option_conflict('c', 's');
6497 if (symref_target && do_delete)
6498 option_conflict('s', 'd');
6499 if (symref_target && do_list)
6500 option_conflict('s', 'l');
6501 if (do_delete && do_list)
6502 option_conflict('d', 'l');
6503 if (sort_by_time && !do_list)
6504 errx(1, "-t option requires -l option");
6506 argc -= optind;
6507 argv += optind;
6509 if (do_list) {
6510 if (argc != 0 && argc != 1)
6511 usage_ref();
6512 if (argc == 1) {
6513 refname = strdup(argv[0]);
6514 if (refname == NULL) {
6515 error = got_error_from_errno("strdup");
6516 goto done;
6519 } else {
6520 if (argc != 1)
6521 usage_ref();
6522 refname = strdup(argv[0]);
6523 if (refname == NULL) {
6524 error = got_error_from_errno("strdup");
6525 goto done;
6529 if (refname)
6530 got_path_strip_trailing_slashes(refname);
6532 #ifndef PROFILE
6533 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6534 "sendfd unveil", NULL) == -1)
6535 err(1, "pledge");
6536 #endif
6537 cwd = getcwd(NULL, 0);
6538 if (cwd == NULL) {
6539 error = got_error_from_errno("getcwd");
6540 goto done;
6543 error = got_repo_pack_fds_open(&pack_fds);
6544 if (error != NULL)
6545 goto done;
6547 if (repo_path == NULL) {
6548 error = got_worktree_open(&worktree, cwd);
6549 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6550 goto done;
6551 else
6552 error = NULL;
6553 if (worktree) {
6554 repo_path =
6555 strdup(got_worktree_get_repo_path(worktree));
6556 if (repo_path == NULL)
6557 error = got_error_from_errno("strdup");
6558 if (error)
6559 goto done;
6560 } else {
6561 repo_path = strdup(cwd);
6562 if (repo_path == NULL) {
6563 error = got_error_from_errno("strdup");
6564 goto done;
6569 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6570 if (error != NULL)
6571 goto done;
6573 #ifndef PROFILE
6574 if (do_list) {
6575 /* Remove "cpath" promise. */
6576 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6577 NULL) == -1)
6578 err(1, "pledge");
6580 #endif
6582 error = apply_unveil(got_repo_get_path(repo), do_list,
6583 worktree ? got_worktree_get_root_path(worktree) : NULL);
6584 if (error)
6585 goto done;
6587 if (do_list)
6588 error = list_refs(repo, refname, sort_by_time);
6589 else if (do_delete)
6590 error = delete_ref_by_name(repo, refname);
6591 else if (symref_target)
6592 error = add_symref(repo, refname, symref_target);
6593 else {
6594 if (obj_arg == NULL)
6595 usage_ref();
6596 error = add_ref(repo, refname, obj_arg);
6598 done:
6599 free(refname);
6600 if (repo) {
6601 const struct got_error *close_err = got_repo_close(repo);
6602 if (error == NULL)
6603 error = close_err;
6605 if (worktree)
6606 got_worktree_close(worktree);
6607 if (pack_fds) {
6608 const struct got_error *pack_err =
6609 got_repo_pack_fds_close(pack_fds);
6610 if (error == NULL)
6611 error = pack_err;
6613 free(cwd);
6614 free(repo_path);
6615 return error;
6618 __dead static void
6619 usage_branch(void)
6621 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6622 "[-r repository-path] [name]\n", getprogname());
6623 exit(1);
6626 static const struct got_error *
6627 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6628 struct got_reference *ref)
6630 const struct got_error *err = NULL;
6631 const char *refname, *marker = " ";
6632 char *refstr;
6634 refname = got_ref_get_name(ref);
6635 if (worktree && strcmp(refname,
6636 got_worktree_get_head_ref_name(worktree)) == 0) {
6637 struct got_object_id *id = NULL;
6639 err = got_ref_resolve(&id, repo, ref);
6640 if (err)
6641 return err;
6642 if (got_object_id_cmp(id,
6643 got_worktree_get_base_commit_id(worktree)) == 0)
6644 marker = "* ";
6645 else
6646 marker = "~ ";
6647 free(id);
6650 if (strncmp(refname, "refs/heads/", 11) == 0)
6651 refname += 11;
6652 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6653 refname += 18;
6654 if (strncmp(refname, "refs/remotes/", 13) == 0)
6655 refname += 13;
6657 refstr = got_ref_to_str(ref);
6658 if (refstr == NULL)
6659 return got_error_from_errno("got_ref_to_str");
6661 printf("%s%s: %s\n", marker, refname, refstr);
6662 free(refstr);
6663 return NULL;
6666 static const struct got_error *
6667 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6669 const char *refname;
6671 if (worktree == NULL)
6672 return got_error(GOT_ERR_NOT_WORKTREE);
6674 refname = got_worktree_get_head_ref_name(worktree);
6676 if (strncmp(refname, "refs/heads/", 11) == 0)
6677 refname += 11;
6678 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6679 refname += 18;
6681 printf("%s\n", refname);
6683 return NULL;
6686 static const struct got_error *
6687 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6688 int sort_by_time)
6690 static const struct got_error *err = NULL;
6691 struct got_reflist_head refs;
6692 struct got_reflist_entry *re;
6693 struct got_reference *temp_ref = NULL;
6694 int rebase_in_progress, histedit_in_progress;
6696 TAILQ_INIT(&refs);
6698 if (worktree) {
6699 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6700 worktree);
6701 if (err)
6702 return err;
6704 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6705 worktree);
6706 if (err)
6707 return err;
6709 if (rebase_in_progress || histedit_in_progress) {
6710 err = got_ref_open(&temp_ref, repo,
6711 got_worktree_get_head_ref_name(worktree), 0);
6712 if (err)
6713 return err;
6714 list_branch(repo, worktree, temp_ref);
6715 got_ref_close(temp_ref);
6719 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6720 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6721 repo);
6722 if (err)
6723 return err;
6725 TAILQ_FOREACH(re, &refs, entry)
6726 list_branch(repo, worktree, re->ref);
6728 got_ref_list_free(&refs);
6730 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6731 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6732 repo);
6733 if (err)
6734 return err;
6736 TAILQ_FOREACH(re, &refs, entry)
6737 list_branch(repo, worktree, re->ref);
6739 got_ref_list_free(&refs);
6741 return NULL;
6744 static const struct got_error *
6745 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6746 const char *branch_name)
6748 const struct got_error *err = NULL;
6749 struct got_reference *ref = NULL;
6750 char *refname, *remote_refname = NULL;
6752 if (strncmp(branch_name, "refs/", 5) == 0)
6753 branch_name += 5;
6754 if (strncmp(branch_name, "heads/", 6) == 0)
6755 branch_name += 6;
6756 else if (strncmp(branch_name, "remotes/", 8) == 0)
6757 branch_name += 8;
6759 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6760 return got_error_from_errno("asprintf");
6762 if (asprintf(&remote_refname, "refs/remotes/%s",
6763 branch_name) == -1) {
6764 err = got_error_from_errno("asprintf");
6765 goto done;
6768 err = got_ref_open(&ref, repo, refname, 0);
6769 if (err) {
6770 const struct got_error *err2;
6771 if (err->code != GOT_ERR_NOT_REF)
6772 goto done;
6774 * Keep 'err' intact such that if neither branch exists
6775 * we report "refs/heads" rather than "refs/remotes" in
6776 * our error message.
6778 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6779 if (err2)
6780 goto done;
6781 err = NULL;
6784 if (worktree &&
6785 strcmp(got_worktree_get_head_ref_name(worktree),
6786 got_ref_get_name(ref)) == 0) {
6787 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6788 "will not delete this work tree's current branch");
6789 goto done;
6792 err = delete_ref(repo, ref);
6793 done:
6794 if (ref)
6795 got_ref_close(ref);
6796 free(refname);
6797 free(remote_refname);
6798 return err;
6801 static const struct got_error *
6802 add_branch(struct got_repository *repo, const char *branch_name,
6803 struct got_object_id *base_commit_id)
6805 const struct got_error *err = NULL;
6806 struct got_reference *ref = NULL;
6807 char *refname = NULL;
6810 * Don't let the user create a branch name with a leading '-'.
6811 * While technically a valid reference name, this case is usually
6812 * an unintended typo.
6814 if (branch_name[0] == '-')
6815 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6817 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6818 branch_name += 11;
6820 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6821 err = got_error_from_errno("asprintf");
6822 goto done;
6825 err = got_ref_open(&ref, repo, refname, 0);
6826 if (err == NULL) {
6827 err = got_error(GOT_ERR_BRANCH_EXISTS);
6828 goto done;
6829 } else if (err->code != GOT_ERR_NOT_REF)
6830 goto done;
6832 err = got_ref_alloc(&ref, refname, base_commit_id);
6833 if (err)
6834 goto done;
6836 err = got_ref_write(ref, repo);
6837 done:
6838 if (ref)
6839 got_ref_close(ref);
6840 free(refname);
6841 return err;
6844 static const struct got_error *
6845 cmd_branch(int argc, char *argv[])
6847 const struct got_error *error = NULL;
6848 struct got_repository *repo = NULL;
6849 struct got_worktree *worktree = NULL;
6850 char *cwd = NULL, *repo_path = NULL;
6851 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6852 const char *delref = NULL, *commit_id_arg = NULL;
6853 struct got_reference *ref = NULL;
6854 struct got_pathlist_head paths;
6855 struct got_object_id *commit_id = NULL;
6856 char *commit_id_str = NULL;
6857 int *pack_fds = NULL;
6859 TAILQ_INIT(&paths);
6861 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6862 switch (ch) {
6863 case 'c':
6864 commit_id_arg = optarg;
6865 break;
6866 case 'd':
6867 delref = optarg;
6868 break;
6869 case 'l':
6870 do_list = 1;
6871 break;
6872 case 'n':
6873 do_update = 0;
6874 break;
6875 case 'r':
6876 repo_path = realpath(optarg, NULL);
6877 if (repo_path == NULL)
6878 return got_error_from_errno2("realpath",
6879 optarg);
6880 got_path_strip_trailing_slashes(repo_path);
6881 break;
6882 case 't':
6883 sort_by_time = 1;
6884 break;
6885 default:
6886 usage_branch();
6887 /* NOTREACHED */
6891 if (do_list && delref)
6892 option_conflict('l', 'd');
6893 if (sort_by_time && !do_list)
6894 errx(1, "-t option requires -l option");
6896 argc -= optind;
6897 argv += optind;
6899 if (!do_list && !delref && argc == 0)
6900 do_show = 1;
6902 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6903 errx(1, "-c option can only be used when creating a branch");
6905 if (do_list || delref) {
6906 if (argc > 0)
6907 usage_branch();
6908 } else if (!do_show && argc != 1)
6909 usage_branch();
6911 #ifndef PROFILE
6912 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6913 "sendfd unveil", NULL) == -1)
6914 err(1, "pledge");
6915 #endif
6916 cwd = getcwd(NULL, 0);
6917 if (cwd == NULL) {
6918 error = got_error_from_errno("getcwd");
6919 goto done;
6922 error = got_repo_pack_fds_open(&pack_fds);
6923 if (error != NULL)
6924 goto done;
6926 if (repo_path == NULL) {
6927 error = got_worktree_open(&worktree, cwd);
6928 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6929 goto done;
6930 else
6931 error = NULL;
6932 if (worktree) {
6933 repo_path =
6934 strdup(got_worktree_get_repo_path(worktree));
6935 if (repo_path == NULL)
6936 error = got_error_from_errno("strdup");
6937 if (error)
6938 goto done;
6939 } else {
6940 repo_path = strdup(cwd);
6941 if (repo_path == NULL) {
6942 error = got_error_from_errno("strdup");
6943 goto done;
6948 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6949 if (error != NULL)
6950 goto done;
6952 #ifndef PROFILE
6953 if (do_list || do_show) {
6954 /* Remove "cpath" promise. */
6955 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6956 NULL) == -1)
6957 err(1, "pledge");
6959 #endif
6961 error = apply_unveil(got_repo_get_path(repo), do_list,
6962 worktree ? got_worktree_get_root_path(worktree) : NULL);
6963 if (error)
6964 goto done;
6966 if (do_show)
6967 error = show_current_branch(repo, worktree);
6968 else if (do_list)
6969 error = list_branches(repo, worktree, sort_by_time);
6970 else if (delref)
6971 error = delete_branch(repo, worktree, delref);
6972 else {
6973 struct got_reflist_head refs;
6974 TAILQ_INIT(&refs);
6975 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6976 NULL);
6977 if (error)
6978 goto done;
6979 if (commit_id_arg == NULL)
6980 commit_id_arg = worktree ?
6981 got_worktree_get_head_ref_name(worktree) :
6982 GOT_REF_HEAD;
6983 error = got_repo_match_object_id(&commit_id, NULL,
6984 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6985 got_ref_list_free(&refs);
6986 if (error)
6987 goto done;
6988 error = add_branch(repo, argv[0], commit_id);
6989 if (error)
6990 goto done;
6991 if (worktree && do_update) {
6992 struct got_update_progress_arg upa;
6993 char *branch_refname = NULL;
6995 error = got_object_id_str(&commit_id_str, commit_id);
6996 if (error)
6997 goto done;
6998 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6999 worktree);
7000 if (error)
7001 goto done;
7002 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7003 == -1) {
7004 error = got_error_from_errno("asprintf");
7005 goto done;
7007 error = got_ref_open(&ref, repo, branch_refname, 0);
7008 free(branch_refname);
7009 if (error)
7010 goto done;
7011 error = switch_head_ref(ref, commit_id, worktree,
7012 repo);
7013 if (error)
7014 goto done;
7015 error = got_worktree_set_base_commit_id(worktree, repo,
7016 commit_id);
7017 if (error)
7018 goto done;
7019 memset(&upa, 0, sizeof(upa));
7020 error = got_worktree_checkout_files(worktree, &paths,
7021 repo, update_progress, &upa, check_cancelled,
7022 NULL);
7023 if (error)
7024 goto done;
7025 if (upa.did_something) {
7026 printf("Updated to %s: %s\n",
7027 got_worktree_get_head_ref_name(worktree),
7028 commit_id_str);
7030 print_update_progress_stats(&upa);
7033 done:
7034 if (ref)
7035 got_ref_close(ref);
7036 if (repo) {
7037 const struct got_error *close_err = got_repo_close(repo);
7038 if (error == NULL)
7039 error = close_err;
7041 if (worktree)
7042 got_worktree_close(worktree);
7043 if (pack_fds) {
7044 const struct got_error *pack_err =
7045 got_repo_pack_fds_close(pack_fds);
7046 if (error == NULL)
7047 error = pack_err;
7049 free(cwd);
7050 free(repo_path);
7051 free(commit_id);
7052 free(commit_id_str);
7053 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7054 return error;
7058 __dead static void
7059 usage_tag(void)
7061 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7062 "[-r repository-path] [-s signer-id] name\n", getprogname());
7063 exit(1);
7066 #if 0
7067 static const struct got_error *
7068 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7070 const struct got_error *err = NULL;
7071 struct got_reflist_entry *re, *se, *new;
7072 struct got_object_id *re_id, *se_id;
7073 struct got_tag_object *re_tag, *se_tag;
7074 time_t re_time, se_time;
7076 STAILQ_FOREACH(re, tags, entry) {
7077 se = STAILQ_FIRST(sorted);
7078 if (se == NULL) {
7079 err = got_reflist_entry_dup(&new, re);
7080 if (err)
7081 return err;
7082 STAILQ_INSERT_HEAD(sorted, new, entry);
7083 continue;
7084 } else {
7085 err = got_ref_resolve(&re_id, repo, re->ref);
7086 if (err)
7087 break;
7088 err = got_object_open_as_tag(&re_tag, repo, re_id);
7089 free(re_id);
7090 if (err)
7091 break;
7092 re_time = got_object_tag_get_tagger_time(re_tag);
7093 got_object_tag_close(re_tag);
7096 while (se) {
7097 err = got_ref_resolve(&se_id, repo, re->ref);
7098 if (err)
7099 break;
7100 err = got_object_open_as_tag(&se_tag, repo, se_id);
7101 free(se_id);
7102 if (err)
7103 break;
7104 se_time = got_object_tag_get_tagger_time(se_tag);
7105 got_object_tag_close(se_tag);
7107 if (se_time > re_time) {
7108 err = got_reflist_entry_dup(&new, re);
7109 if (err)
7110 return err;
7111 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7112 break;
7114 se = STAILQ_NEXT(se, entry);
7115 continue;
7118 done:
7119 return err;
7121 #endif
7123 static const struct got_error *
7124 get_tag_refname(char **refname, const char *tag_name)
7126 const struct got_error *err;
7128 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7129 *refname = strdup(tag_name);
7130 if (*refname == NULL)
7131 return got_error_from_errno("strdup");
7132 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7133 err = got_error_from_errno("asprintf");
7134 *refname = NULL;
7135 return err;
7138 return NULL;
7141 static const struct got_error *
7142 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7143 const char *allowed_signers, const char *revoked_signers, int verbosity)
7145 static const struct got_error *err = NULL;
7146 struct got_reflist_head refs;
7147 struct got_reflist_entry *re;
7148 char *wanted_refname = NULL;
7149 int bad_sigs = 0;
7151 TAILQ_INIT(&refs);
7153 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7154 if (err)
7155 return err;
7157 if (tag_name) {
7158 struct got_reference *ref;
7159 err = get_tag_refname(&wanted_refname, tag_name);
7160 if (err)
7161 goto done;
7162 /* Wanted tag reference should exist. */
7163 err = got_ref_open(&ref, repo, wanted_refname, 0);
7164 if (err)
7165 goto done;
7166 got_ref_close(ref);
7169 TAILQ_FOREACH(re, &refs, entry) {
7170 const char *refname;
7171 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7172 char datebuf[26];
7173 const char *tagger, *ssh_sig = NULL;
7174 char *sig_msg = NULL;
7175 time_t tagger_time;
7176 struct got_object_id *id;
7177 struct got_tag_object *tag;
7178 struct got_commit_object *commit = NULL;
7180 refname = got_ref_get_name(re->ref);
7181 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7182 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7183 continue;
7184 refname += 10;
7185 refstr = got_ref_to_str(re->ref);
7186 if (refstr == NULL) {
7187 err = got_error_from_errno("got_ref_to_str");
7188 break;
7191 err = got_ref_resolve(&id, repo, re->ref);
7192 if (err)
7193 break;
7194 err = got_object_open_as_tag(&tag, repo, id);
7195 if (err) {
7196 if (err->code != GOT_ERR_OBJ_TYPE) {
7197 free(id);
7198 break;
7200 /* "lightweight" tag */
7201 err = got_object_open_as_commit(&commit, repo, id);
7202 if (err) {
7203 free(id);
7204 break;
7206 tagger = got_object_commit_get_committer(commit);
7207 tagger_time =
7208 got_object_commit_get_committer_time(commit);
7209 err = got_object_id_str(&id_str, id);
7210 free(id);
7211 if (err)
7212 break;
7213 } else {
7214 free(id);
7215 tagger = got_object_tag_get_tagger(tag);
7216 tagger_time = got_object_tag_get_tagger_time(tag);
7217 err = got_object_id_str(&id_str,
7218 got_object_tag_get_object_id(tag));
7219 if (err)
7220 break;
7223 if (tag && verify_tags) {
7224 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7225 got_object_tag_get_message(tag));
7226 if (ssh_sig && allowed_signers == NULL) {
7227 err = got_error_msg(
7228 GOT_ERR_VERIFY_TAG_SIGNATURE,
7229 "SSH signature verification requires "
7230 "setting allowed_signers in "
7231 "got.conf(5)");
7232 break;
7236 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7237 free(refstr);
7238 printf("from: %s\n", tagger);
7239 datestr = get_datestr(&tagger_time, datebuf);
7240 if (datestr)
7241 printf("date: %s UTC\n", datestr);
7242 if (commit)
7243 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7244 else {
7245 switch (got_object_tag_get_object_type(tag)) {
7246 case GOT_OBJ_TYPE_BLOB:
7247 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7248 id_str);
7249 break;
7250 case GOT_OBJ_TYPE_TREE:
7251 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7252 id_str);
7253 break;
7254 case GOT_OBJ_TYPE_COMMIT:
7255 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7256 id_str);
7257 break;
7258 case GOT_OBJ_TYPE_TAG:
7259 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7260 id_str);
7261 break;
7262 default:
7263 break;
7266 free(id_str);
7268 if (ssh_sig) {
7269 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7270 allowed_signers, revoked_signers, verbosity);
7271 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7272 bad_sigs = 1;
7273 else if (err)
7274 break;
7275 printf("signature: %s", sig_msg);
7276 free(sig_msg);
7277 sig_msg = NULL;
7280 if (commit) {
7281 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7282 if (err)
7283 break;
7284 got_object_commit_close(commit);
7285 } else {
7286 tagmsg0 = strdup(got_object_tag_get_message(tag));
7287 got_object_tag_close(tag);
7288 if (tagmsg0 == NULL) {
7289 err = got_error_from_errno("strdup");
7290 break;
7294 tagmsg = tagmsg0;
7295 do {
7296 line = strsep(&tagmsg, "\n");
7297 if (line)
7298 printf(" %s\n", line);
7299 } while (line);
7300 free(tagmsg0);
7302 done:
7303 got_ref_list_free(&refs);
7304 free(wanted_refname);
7306 if (err == NULL && bad_sigs)
7307 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7308 return err;
7311 static const struct got_error *
7312 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7313 const char *tag_name, const char *repo_path)
7315 const struct got_error *err = NULL;
7316 char *template = NULL, *initial_content = NULL;
7317 char *editor = NULL;
7318 int initial_content_len;
7319 int fd = -1;
7321 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7322 err = got_error_from_errno("asprintf");
7323 goto done;
7326 initial_content_len = asprintf(&initial_content,
7327 "\n# tagging commit %s as %s\n",
7328 commit_id_str, tag_name);
7329 if (initial_content_len == -1) {
7330 err = got_error_from_errno("asprintf");
7331 goto done;
7334 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7335 if (err)
7336 goto done;
7338 if (write(fd, initial_content, initial_content_len) == -1) {
7339 err = got_error_from_errno2("write", *tagmsg_path);
7340 goto done;
7343 err = get_editor(&editor);
7344 if (err)
7345 goto done;
7346 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7347 initial_content_len, 1);
7348 done:
7349 free(initial_content);
7350 free(template);
7351 free(editor);
7353 if (fd != -1 && close(fd) == -1 && err == NULL)
7354 err = got_error_from_errno2("close", *tagmsg_path);
7356 if (err) {
7357 free(*tagmsg);
7358 *tagmsg = NULL;
7360 return err;
7363 static const struct got_error *
7364 add_tag(struct got_repository *repo, const char *tagger,
7365 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7366 const char *signer_id, int verbosity)
7368 const struct got_error *err = NULL;
7369 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7370 char *label = NULL, *commit_id_str = NULL;
7371 struct got_reference *ref = NULL;
7372 char *refname = NULL, *tagmsg = NULL;
7373 char *tagmsg_path = NULL, *tag_id_str = NULL;
7374 int preserve_tagmsg = 0;
7375 struct got_reflist_head refs;
7377 TAILQ_INIT(&refs);
7380 * Don't let the user create a tag name with a leading '-'.
7381 * While technically a valid reference name, this case is usually
7382 * an unintended typo.
7384 if (tag_name[0] == '-')
7385 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7387 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7388 if (err)
7389 goto done;
7391 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7392 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7393 if (err)
7394 goto done;
7396 err = got_object_id_str(&commit_id_str, commit_id);
7397 if (err)
7398 goto done;
7400 err = get_tag_refname(&refname, tag_name);
7401 if (err)
7402 goto done;
7403 if (strncmp("refs/tags/", tag_name, 10) == 0)
7404 tag_name += 10;
7406 err = got_ref_open(&ref, repo, refname, 0);
7407 if (err == NULL) {
7408 err = got_error(GOT_ERR_TAG_EXISTS);
7409 goto done;
7410 } else if (err->code != GOT_ERR_NOT_REF)
7411 goto done;
7413 if (tagmsg_arg == NULL) {
7414 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7415 tag_name, got_repo_get_path(repo));
7416 if (err) {
7417 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7418 tagmsg_path != NULL)
7419 preserve_tagmsg = 1;
7420 goto done;
7422 /* Editor is done; we can now apply unveil(2) */
7423 err = got_sigs_apply_unveil();
7424 if (err)
7425 goto done;
7426 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7427 if (err)
7428 goto done;
7431 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7432 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7433 verbosity);
7434 if (err) {
7435 if (tagmsg_path)
7436 preserve_tagmsg = 1;
7437 goto done;
7440 err = got_ref_alloc(&ref, refname, tag_id);
7441 if (err) {
7442 if (tagmsg_path)
7443 preserve_tagmsg = 1;
7444 goto done;
7447 err = got_ref_write(ref, repo);
7448 if (err) {
7449 if (tagmsg_path)
7450 preserve_tagmsg = 1;
7451 goto done;
7454 err = got_object_id_str(&tag_id_str, tag_id);
7455 if (err) {
7456 if (tagmsg_path)
7457 preserve_tagmsg = 1;
7458 goto done;
7460 printf("Created tag %s\n", tag_id_str);
7461 done:
7462 if (preserve_tagmsg) {
7463 fprintf(stderr, "%s: tag message preserved in %s\n",
7464 getprogname(), tagmsg_path);
7465 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7466 err = got_error_from_errno2("unlink", tagmsg_path);
7467 free(tag_id_str);
7468 if (ref)
7469 got_ref_close(ref);
7470 free(commit_id);
7471 free(commit_id_str);
7472 free(refname);
7473 free(tagmsg);
7474 free(tagmsg_path);
7475 got_ref_list_free(&refs);
7476 return err;
7479 static const struct got_error *
7480 cmd_tag(int argc, char *argv[])
7482 const struct got_error *error = NULL;
7483 struct got_repository *repo = NULL;
7484 struct got_worktree *worktree = NULL;
7485 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7486 char *gitconfig_path = NULL, *tagger = NULL;
7487 char *allowed_signers = NULL, *revoked_signers = NULL;
7488 char *signer_id = NULL;
7489 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7490 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7491 int *pack_fds = NULL;
7493 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7494 switch (ch) {
7495 case 'c':
7496 commit_id_arg = optarg;
7497 break;
7498 case 'l':
7499 do_list = 1;
7500 break;
7501 case 'm':
7502 tagmsg = optarg;
7503 break;
7504 case 'r':
7505 repo_path = realpath(optarg, NULL);
7506 if (repo_path == NULL) {
7507 error = got_error_from_errno2("realpath",
7508 optarg);
7509 goto done;
7511 got_path_strip_trailing_slashes(repo_path);
7512 break;
7513 case 's':
7514 signer_id = strdup(optarg);
7515 if (signer_id == NULL) {
7516 error = got_error_from_errno("strdup");
7517 goto done;
7519 break;
7520 case 'V':
7521 verify_tags = 1;
7522 break;
7523 case 'v':
7524 if (verbosity < 0)
7525 verbosity = 0;
7526 else if (verbosity < 3)
7527 verbosity++;
7528 break;
7529 default:
7530 usage_tag();
7531 /* NOTREACHED */
7535 argc -= optind;
7536 argv += optind;
7538 if (do_list || verify_tags) {
7539 if (commit_id_arg != NULL)
7540 errx(1,
7541 "-c option can only be used when creating a tag");
7542 if (tagmsg) {
7543 if (do_list)
7544 option_conflict('l', 'm');
7545 else
7546 option_conflict('V', 'm');
7548 if (signer_id) {
7549 if (do_list)
7550 option_conflict('l', 's');
7551 else
7552 option_conflict('V', 's');
7554 if (argc > 1)
7555 usage_tag();
7556 } else if (argc != 1)
7557 usage_tag();
7559 if (argc == 1)
7560 tag_name = argv[0];
7562 #ifndef PROFILE
7563 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7564 "sendfd unveil", NULL) == -1)
7565 err(1, "pledge");
7566 #endif
7567 cwd = getcwd(NULL, 0);
7568 if (cwd == NULL) {
7569 error = got_error_from_errno("getcwd");
7570 goto done;
7573 error = got_repo_pack_fds_open(&pack_fds);
7574 if (error != NULL)
7575 goto done;
7577 if (repo_path == NULL) {
7578 error = got_worktree_open(&worktree, cwd);
7579 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7580 goto done;
7581 else
7582 error = NULL;
7583 if (worktree) {
7584 repo_path =
7585 strdup(got_worktree_get_repo_path(worktree));
7586 if (repo_path == NULL)
7587 error = got_error_from_errno("strdup");
7588 if (error)
7589 goto done;
7590 } else {
7591 repo_path = strdup(cwd);
7592 if (repo_path == NULL) {
7593 error = got_error_from_errno("strdup");
7594 goto done;
7599 if (do_list || verify_tags) {
7600 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7601 if (error != NULL)
7602 goto done;
7603 error = get_allowed_signers(&allowed_signers, repo, worktree);
7604 if (error)
7605 goto done;
7606 error = get_revoked_signers(&revoked_signers, repo, worktree);
7607 if (error)
7608 goto done;
7609 if (worktree) {
7610 /* Release work tree lock. */
7611 got_worktree_close(worktree);
7612 worktree = NULL;
7616 * Remove "cpath" promise unless needed for signature tmpfile
7617 * creation.
7619 if (verify_tags)
7620 got_sigs_apply_unveil();
7621 else {
7622 #ifndef PROFILE
7623 if (pledge("stdio rpath wpath flock proc exec sendfd "
7624 "unveil", NULL) == -1)
7625 err(1, "pledge");
7626 #endif
7628 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7629 if (error)
7630 goto done;
7631 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7632 revoked_signers, verbosity);
7633 } else {
7634 error = get_gitconfig_path(&gitconfig_path);
7635 if (error)
7636 goto done;
7637 error = got_repo_open(&repo, repo_path, gitconfig_path,
7638 pack_fds);
7639 if (error != NULL)
7640 goto done;
7642 error = get_author(&tagger, repo, worktree);
7643 if (error)
7644 goto done;
7645 if (signer_id == NULL) {
7646 error = get_signer_id(&signer_id, repo, worktree);
7647 if (error)
7648 goto done;
7651 if (tagmsg) {
7652 if (signer_id) {
7653 error = got_sigs_apply_unveil();
7654 if (error)
7655 goto done;
7657 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7658 if (error)
7659 goto done;
7662 if (commit_id_arg == NULL) {
7663 struct got_reference *head_ref;
7664 struct got_object_id *commit_id;
7665 error = got_ref_open(&head_ref, repo,
7666 worktree ? got_worktree_get_head_ref_name(worktree)
7667 : GOT_REF_HEAD, 0);
7668 if (error)
7669 goto done;
7670 error = got_ref_resolve(&commit_id, repo, head_ref);
7671 got_ref_close(head_ref);
7672 if (error)
7673 goto done;
7674 error = got_object_id_str(&commit_id_str, commit_id);
7675 free(commit_id);
7676 if (error)
7677 goto done;
7680 if (worktree) {
7681 /* Release work tree lock. */
7682 got_worktree_close(worktree);
7683 worktree = NULL;
7686 error = add_tag(repo, tagger, tag_name,
7687 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7688 signer_id, verbosity);
7690 done:
7691 if (repo) {
7692 const struct got_error *close_err = got_repo_close(repo);
7693 if (error == NULL)
7694 error = close_err;
7696 if (worktree)
7697 got_worktree_close(worktree);
7698 if (pack_fds) {
7699 const struct got_error *pack_err =
7700 got_repo_pack_fds_close(pack_fds);
7701 if (error == NULL)
7702 error = pack_err;
7704 free(cwd);
7705 free(repo_path);
7706 free(gitconfig_path);
7707 free(commit_id_str);
7708 free(tagger);
7709 free(allowed_signers);
7710 free(revoked_signers);
7711 free(signer_id);
7712 return error;
7715 __dead static void
7716 usage_add(void)
7718 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7719 exit(1);
7722 static const struct got_error *
7723 add_progress(void *arg, unsigned char status, const char *path)
7725 while (path[0] == '/')
7726 path++;
7727 printf("%c %s\n", status, path);
7728 return NULL;
7731 static const struct got_error *
7732 cmd_add(int argc, char *argv[])
7734 const struct got_error *error = NULL;
7735 struct got_repository *repo = NULL;
7736 struct got_worktree *worktree = NULL;
7737 char *cwd = NULL;
7738 struct got_pathlist_head paths;
7739 struct got_pathlist_entry *pe;
7740 int ch, can_recurse = 0, no_ignores = 0;
7741 int *pack_fds = NULL;
7743 TAILQ_INIT(&paths);
7745 while ((ch = getopt(argc, argv, "IR")) != -1) {
7746 switch (ch) {
7747 case 'I':
7748 no_ignores = 1;
7749 break;
7750 case 'R':
7751 can_recurse = 1;
7752 break;
7753 default:
7754 usage_add();
7755 /* NOTREACHED */
7759 argc -= optind;
7760 argv += optind;
7762 #ifndef PROFILE
7763 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7764 NULL) == -1)
7765 err(1, "pledge");
7766 #endif
7767 if (argc < 1)
7768 usage_add();
7770 cwd = getcwd(NULL, 0);
7771 if (cwd == NULL) {
7772 error = got_error_from_errno("getcwd");
7773 goto done;
7776 error = got_repo_pack_fds_open(&pack_fds);
7777 if (error != NULL)
7778 goto done;
7780 error = got_worktree_open(&worktree, cwd);
7781 if (error) {
7782 if (error->code == GOT_ERR_NOT_WORKTREE)
7783 error = wrap_not_worktree_error(error, "add", cwd);
7784 goto done;
7787 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7788 NULL, pack_fds);
7789 if (error != NULL)
7790 goto done;
7792 error = apply_unveil(got_repo_get_path(repo), 1,
7793 got_worktree_get_root_path(worktree));
7794 if (error)
7795 goto done;
7797 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7798 if (error)
7799 goto done;
7801 if (!can_recurse) {
7802 char *ondisk_path;
7803 struct stat sb;
7804 TAILQ_FOREACH(pe, &paths, entry) {
7805 if (asprintf(&ondisk_path, "%s/%s",
7806 got_worktree_get_root_path(worktree),
7807 pe->path) == -1) {
7808 error = got_error_from_errno("asprintf");
7809 goto done;
7811 if (lstat(ondisk_path, &sb) == -1) {
7812 if (errno == ENOENT) {
7813 free(ondisk_path);
7814 continue;
7816 error = got_error_from_errno2("lstat",
7817 ondisk_path);
7818 free(ondisk_path);
7819 goto done;
7821 free(ondisk_path);
7822 if (S_ISDIR(sb.st_mode)) {
7823 error = got_error_msg(GOT_ERR_BAD_PATH,
7824 "adding directories requires -R option");
7825 goto done;
7830 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7831 NULL, repo, no_ignores);
7832 done:
7833 if (repo) {
7834 const struct got_error *close_err = got_repo_close(repo);
7835 if (error == NULL)
7836 error = close_err;
7838 if (worktree)
7839 got_worktree_close(worktree);
7840 if (pack_fds) {
7841 const struct got_error *pack_err =
7842 got_repo_pack_fds_close(pack_fds);
7843 if (error == NULL)
7844 error = pack_err;
7846 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7847 free(cwd);
7848 return error;
7851 __dead static void
7852 usage_remove(void)
7854 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7855 getprogname());
7856 exit(1);
7859 static const struct got_error *
7860 print_remove_status(void *arg, unsigned char status,
7861 unsigned char staged_status, const char *path)
7863 while (path[0] == '/')
7864 path++;
7865 if (status == GOT_STATUS_NONEXISTENT)
7866 return NULL;
7867 if (status == staged_status && (status == GOT_STATUS_DELETE))
7868 status = GOT_STATUS_NO_CHANGE;
7869 printf("%c%c %s\n", status, staged_status, path);
7870 return NULL;
7873 static const struct got_error *
7874 cmd_remove(int argc, char *argv[])
7876 const struct got_error *error = NULL;
7877 struct got_worktree *worktree = NULL;
7878 struct got_repository *repo = NULL;
7879 const char *status_codes = NULL;
7880 char *cwd = NULL;
7881 struct got_pathlist_head paths;
7882 struct got_pathlist_entry *pe;
7883 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7884 int ignore_missing_paths = 0;
7885 int *pack_fds = NULL;
7887 TAILQ_INIT(&paths);
7889 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7890 switch (ch) {
7891 case 'f':
7892 delete_local_mods = 1;
7893 ignore_missing_paths = 1;
7894 break;
7895 case 'k':
7896 keep_on_disk = 1;
7897 break;
7898 case 'R':
7899 can_recurse = 1;
7900 break;
7901 case 's':
7902 for (i = 0; i < strlen(optarg); i++) {
7903 switch (optarg[i]) {
7904 case GOT_STATUS_MODIFY:
7905 delete_local_mods = 1;
7906 break;
7907 case GOT_STATUS_MISSING:
7908 ignore_missing_paths = 1;
7909 break;
7910 default:
7911 errx(1, "invalid status code '%c'",
7912 optarg[i]);
7915 status_codes = optarg;
7916 break;
7917 default:
7918 usage_remove();
7919 /* NOTREACHED */
7923 argc -= optind;
7924 argv += optind;
7926 #ifndef PROFILE
7927 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7928 NULL) == -1)
7929 err(1, "pledge");
7930 #endif
7931 if (argc < 1)
7932 usage_remove();
7934 cwd = getcwd(NULL, 0);
7935 if (cwd == NULL) {
7936 error = got_error_from_errno("getcwd");
7937 goto done;
7940 error = got_repo_pack_fds_open(&pack_fds);
7941 if (error != NULL)
7942 goto done;
7944 error = got_worktree_open(&worktree, cwd);
7945 if (error) {
7946 if (error->code == GOT_ERR_NOT_WORKTREE)
7947 error = wrap_not_worktree_error(error, "remove", cwd);
7948 goto done;
7951 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7952 NULL, pack_fds);
7953 if (error)
7954 goto done;
7956 error = apply_unveil(got_repo_get_path(repo), 1,
7957 got_worktree_get_root_path(worktree));
7958 if (error)
7959 goto done;
7961 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7962 if (error)
7963 goto done;
7965 if (!can_recurse) {
7966 char *ondisk_path;
7967 struct stat sb;
7968 TAILQ_FOREACH(pe, &paths, entry) {
7969 if (asprintf(&ondisk_path, "%s/%s",
7970 got_worktree_get_root_path(worktree),
7971 pe->path) == -1) {
7972 error = got_error_from_errno("asprintf");
7973 goto done;
7975 if (lstat(ondisk_path, &sb) == -1) {
7976 if (errno == ENOENT) {
7977 free(ondisk_path);
7978 continue;
7980 error = got_error_from_errno2("lstat",
7981 ondisk_path);
7982 free(ondisk_path);
7983 goto done;
7985 free(ondisk_path);
7986 if (S_ISDIR(sb.st_mode)) {
7987 error = got_error_msg(GOT_ERR_BAD_PATH,
7988 "removing directories requires -R option");
7989 goto done;
7994 error = got_worktree_schedule_delete(worktree, &paths,
7995 delete_local_mods, status_codes, print_remove_status, NULL,
7996 repo, keep_on_disk, ignore_missing_paths);
7997 done:
7998 if (repo) {
7999 const struct got_error *close_err = got_repo_close(repo);
8000 if (error == NULL)
8001 error = close_err;
8003 if (worktree)
8004 got_worktree_close(worktree);
8005 if (pack_fds) {
8006 const struct got_error *pack_err =
8007 got_repo_pack_fds_close(pack_fds);
8008 if (error == NULL)
8009 error = pack_err;
8011 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8012 free(cwd);
8013 return error;
8016 __dead static void
8017 usage_patch(void)
8019 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8020 "[patchfile]\n", getprogname());
8021 exit(1);
8024 static const struct got_error *
8025 patch_from_stdin(int *patchfd)
8027 const struct got_error *err = NULL;
8028 ssize_t r;
8029 char buf[BUFSIZ];
8030 sig_t sighup, sigint, sigquit;
8032 *patchfd = got_opentempfd();
8033 if (*patchfd == -1)
8034 return got_error_from_errno("got_opentempfd");
8036 sighup = signal(SIGHUP, SIG_DFL);
8037 sigint = signal(SIGINT, SIG_DFL);
8038 sigquit = signal(SIGQUIT, SIG_DFL);
8040 for (;;) {
8041 r = read(0, buf, sizeof(buf));
8042 if (r == -1) {
8043 err = got_error_from_errno("read");
8044 break;
8046 if (r == 0)
8047 break;
8048 if (write(*patchfd, buf, r) == -1) {
8049 err = got_error_from_errno("write");
8050 break;
8054 signal(SIGHUP, sighup);
8055 signal(SIGINT, sigint);
8056 signal(SIGQUIT, sigquit);
8058 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8059 err = got_error_from_errno("lseek");
8061 if (err != NULL) {
8062 close(*patchfd);
8063 *patchfd = -1;
8066 return err;
8069 static const struct got_error *
8070 patch_progress(void *arg, const char *old, const char *new,
8071 unsigned char status, const struct got_error *error, int old_from,
8072 int old_lines, int new_from, int new_lines, int offset,
8073 int ws_mangled, const struct got_error *hunk_err)
8075 const char *path = new == NULL ? old : new;
8077 while (*path == '/')
8078 path++;
8080 if (status != 0)
8081 printf("%c %s\n", status, path);
8083 if (error != NULL)
8084 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8086 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8087 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8088 old_lines, new_from, new_lines);
8089 if (hunk_err != NULL)
8090 printf("%s\n", hunk_err->msg);
8091 else if (offset != 0)
8092 printf("applied with offset %d\n", offset);
8093 else
8094 printf("hunk contains mangled whitespace\n");
8097 return NULL;
8100 static const struct got_error *
8101 cmd_patch(int argc, char *argv[])
8103 const struct got_error *error = NULL, *close_error = NULL;
8104 struct got_worktree *worktree = NULL;
8105 struct got_repository *repo = NULL;
8106 struct got_reflist_head refs;
8107 struct got_object_id *commit_id = NULL;
8108 const char *commit_id_str = NULL;
8109 struct stat sb;
8110 const char *errstr;
8111 char *cwd = NULL;
8112 int ch, nop = 0, strip = -1, reverse = 0;
8113 int patchfd;
8114 int *pack_fds = NULL;
8116 TAILQ_INIT(&refs);
8118 #ifndef PROFILE
8119 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8120 "unveil", NULL) == -1)
8121 err(1, "pledge");
8122 #endif
8124 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8125 switch (ch) {
8126 case 'c':
8127 commit_id_str = optarg;
8128 break;
8129 case 'n':
8130 nop = 1;
8131 break;
8132 case 'p':
8133 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8134 if (errstr != NULL)
8135 errx(1, "pathname strip count is %s: %s",
8136 errstr, optarg);
8137 break;
8138 case 'R':
8139 reverse = 1;
8140 break;
8141 default:
8142 usage_patch();
8143 /* NOTREACHED */
8147 argc -= optind;
8148 argv += optind;
8150 if (argc == 0) {
8151 error = patch_from_stdin(&patchfd);
8152 if (error)
8153 return error;
8154 } else if (argc == 1) {
8155 patchfd = open(argv[0], O_RDONLY);
8156 if (patchfd == -1) {
8157 error = got_error_from_errno2("open", argv[0]);
8158 return error;
8160 if (fstat(patchfd, &sb) == -1) {
8161 error = got_error_from_errno2("fstat", argv[0]);
8162 goto done;
8164 if (!S_ISREG(sb.st_mode)) {
8165 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8166 goto done;
8168 } else
8169 usage_patch();
8171 if ((cwd = getcwd(NULL, 0)) == NULL) {
8172 error = got_error_from_errno("getcwd");
8173 goto done;
8176 error = got_repo_pack_fds_open(&pack_fds);
8177 if (error != NULL)
8178 goto done;
8180 error = got_worktree_open(&worktree, cwd);
8181 if (error != NULL)
8182 goto done;
8184 const char *repo_path = got_worktree_get_repo_path(worktree);
8185 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8186 if (error != NULL)
8187 goto done;
8189 error = apply_unveil(got_repo_get_path(repo), 0,
8190 got_worktree_get_root_path(worktree));
8191 if (error != NULL)
8192 goto done;
8194 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8195 if (error)
8196 goto done;
8198 if (commit_id_str != NULL) {
8199 error = got_repo_match_object_id(&commit_id, NULL,
8200 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8201 if (error)
8202 goto done;
8205 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8206 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8208 done:
8209 got_ref_list_free(&refs);
8210 free(commit_id);
8211 if (repo) {
8212 close_error = got_repo_close(repo);
8213 if (error == NULL)
8214 error = close_error;
8216 if (worktree != NULL) {
8217 close_error = got_worktree_close(worktree);
8218 if (error == NULL)
8219 error = close_error;
8221 if (pack_fds) {
8222 const struct got_error *pack_err =
8223 got_repo_pack_fds_close(pack_fds);
8224 if (error == NULL)
8225 error = pack_err;
8227 free(cwd);
8228 return error;
8231 __dead static void
8232 usage_revert(void)
8234 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8235 getprogname());
8236 exit(1);
8239 static const struct got_error *
8240 revert_progress(void *arg, unsigned char status, const char *path)
8242 if (status == GOT_STATUS_UNVERSIONED)
8243 return NULL;
8245 while (path[0] == '/')
8246 path++;
8247 printf("%c %s\n", status, path);
8248 return NULL;
8251 struct choose_patch_arg {
8252 FILE *patch_script_file;
8253 const char *action;
8256 static const struct got_error *
8257 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8258 int nchanges, const char *action)
8260 const struct got_error *err;
8261 char *line = NULL;
8262 size_t linesize = 0;
8263 ssize_t linelen;
8265 switch (status) {
8266 case GOT_STATUS_ADD:
8267 printf("A %s\n%s this addition? [y/n] ", path, action);
8268 break;
8269 case GOT_STATUS_DELETE:
8270 printf("D %s\n%s this deletion? [y/n] ", path, action);
8271 break;
8272 case GOT_STATUS_MODIFY:
8273 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8274 return got_error_from_errno("fseek");
8275 printf(GOT_COMMIT_SEP_STR);
8276 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8277 printf("%s", line);
8278 if (linelen == -1 && ferror(patch_file)) {
8279 err = got_error_from_errno("getline");
8280 free(line);
8281 return err;
8283 free(line);
8284 printf(GOT_COMMIT_SEP_STR);
8285 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8286 path, n, nchanges, action);
8287 break;
8288 default:
8289 return got_error_path(path, GOT_ERR_FILE_STATUS);
8292 fflush(stdout);
8293 return NULL;
8296 static const struct got_error *
8297 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8298 FILE *patch_file, int n, int nchanges)
8300 const struct got_error *err = NULL;
8301 char *line = NULL;
8302 size_t linesize = 0;
8303 ssize_t linelen;
8304 int resp = ' ';
8305 struct choose_patch_arg *a = arg;
8307 *choice = GOT_PATCH_CHOICE_NONE;
8309 if (a->patch_script_file) {
8310 char *nl;
8311 err = show_change(status, path, patch_file, n, nchanges,
8312 a->action);
8313 if (err)
8314 return err;
8315 linelen = getline(&line, &linesize, a->patch_script_file);
8316 if (linelen == -1) {
8317 if (ferror(a->patch_script_file))
8318 return got_error_from_errno("getline");
8319 return NULL;
8321 nl = strchr(line, '\n');
8322 if (nl)
8323 *nl = '\0';
8324 if (strcmp(line, "y") == 0) {
8325 *choice = GOT_PATCH_CHOICE_YES;
8326 printf("y\n");
8327 } else if (strcmp(line, "n") == 0) {
8328 *choice = GOT_PATCH_CHOICE_NO;
8329 printf("n\n");
8330 } else if (strcmp(line, "q") == 0 &&
8331 status == GOT_STATUS_MODIFY) {
8332 *choice = GOT_PATCH_CHOICE_QUIT;
8333 printf("q\n");
8334 } else
8335 printf("invalid response '%s'\n", line);
8336 free(line);
8337 return NULL;
8340 while (resp != 'y' && resp != 'n' && resp != 'q') {
8341 err = show_change(status, path, patch_file, n, nchanges,
8342 a->action);
8343 if (err)
8344 return err;
8345 resp = getchar();
8346 if (resp == '\n')
8347 resp = getchar();
8348 if (status == GOT_STATUS_MODIFY) {
8349 if (resp != 'y' && resp != 'n' && resp != 'q') {
8350 printf("invalid response '%c'\n", resp);
8351 resp = ' ';
8353 } else if (resp != 'y' && resp != 'n') {
8354 printf("invalid response '%c'\n", resp);
8355 resp = ' ';
8359 if (resp == 'y')
8360 *choice = GOT_PATCH_CHOICE_YES;
8361 else if (resp == 'n')
8362 *choice = GOT_PATCH_CHOICE_NO;
8363 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8364 *choice = GOT_PATCH_CHOICE_QUIT;
8366 return NULL;
8369 static const struct got_error *
8370 cmd_revert(int argc, char *argv[])
8372 const struct got_error *error = NULL;
8373 struct got_worktree *worktree = NULL;
8374 struct got_repository *repo = NULL;
8375 char *cwd = NULL, *path = NULL;
8376 struct got_pathlist_head paths;
8377 struct got_pathlist_entry *pe;
8378 int ch, can_recurse = 0, pflag = 0;
8379 FILE *patch_script_file = NULL;
8380 const char *patch_script_path = NULL;
8381 struct choose_patch_arg cpa;
8382 int *pack_fds = NULL;
8384 TAILQ_INIT(&paths);
8386 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8387 switch (ch) {
8388 case 'F':
8389 patch_script_path = optarg;
8390 break;
8391 case 'p':
8392 pflag = 1;
8393 break;
8394 case 'R':
8395 can_recurse = 1;
8396 break;
8397 default:
8398 usage_revert();
8399 /* NOTREACHED */
8403 argc -= optind;
8404 argv += optind;
8406 #ifndef PROFILE
8407 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8408 "unveil", NULL) == -1)
8409 err(1, "pledge");
8410 #endif
8411 if (argc < 1)
8412 usage_revert();
8413 if (patch_script_path && !pflag)
8414 errx(1, "-F option can only be used together with -p option");
8416 cwd = getcwd(NULL, 0);
8417 if (cwd == NULL) {
8418 error = got_error_from_errno("getcwd");
8419 goto done;
8422 error = got_repo_pack_fds_open(&pack_fds);
8423 if (error != NULL)
8424 goto done;
8426 error = got_worktree_open(&worktree, cwd);
8427 if (error) {
8428 if (error->code == GOT_ERR_NOT_WORKTREE)
8429 error = wrap_not_worktree_error(error, "revert", cwd);
8430 goto done;
8433 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8434 NULL, pack_fds);
8435 if (error != NULL)
8436 goto done;
8438 if (patch_script_path) {
8439 patch_script_file = fopen(patch_script_path, "re");
8440 if (patch_script_file == NULL) {
8441 error = got_error_from_errno2("fopen",
8442 patch_script_path);
8443 goto done;
8446 error = apply_unveil(got_repo_get_path(repo), 1,
8447 got_worktree_get_root_path(worktree));
8448 if (error)
8449 goto done;
8451 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8452 if (error)
8453 goto done;
8455 if (!can_recurse) {
8456 char *ondisk_path;
8457 struct stat sb;
8458 TAILQ_FOREACH(pe, &paths, entry) {
8459 if (asprintf(&ondisk_path, "%s/%s",
8460 got_worktree_get_root_path(worktree),
8461 pe->path) == -1) {
8462 error = got_error_from_errno("asprintf");
8463 goto done;
8465 if (lstat(ondisk_path, &sb) == -1) {
8466 if (errno == ENOENT) {
8467 free(ondisk_path);
8468 continue;
8470 error = got_error_from_errno2("lstat",
8471 ondisk_path);
8472 free(ondisk_path);
8473 goto done;
8475 free(ondisk_path);
8476 if (S_ISDIR(sb.st_mode)) {
8477 error = got_error_msg(GOT_ERR_BAD_PATH,
8478 "reverting directories requires -R option");
8479 goto done;
8484 cpa.patch_script_file = patch_script_file;
8485 cpa.action = "revert";
8486 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8487 pflag ? choose_patch : NULL, &cpa, repo);
8488 done:
8489 if (patch_script_file && fclose(patch_script_file) == EOF &&
8490 error == NULL)
8491 error = got_error_from_errno2("fclose", patch_script_path);
8492 if (repo) {
8493 const struct got_error *close_err = got_repo_close(repo);
8494 if (error == NULL)
8495 error = close_err;
8497 if (worktree)
8498 got_worktree_close(worktree);
8499 if (pack_fds) {
8500 const struct got_error *pack_err =
8501 got_repo_pack_fds_close(pack_fds);
8502 if (error == NULL)
8503 error = pack_err;
8505 free(path);
8506 free(cwd);
8507 return error;
8510 __dead static void
8511 usage_commit(void)
8513 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8514 "[-m message] [path ...]\n", getprogname());
8515 exit(1);
8518 struct collect_commit_logmsg_arg {
8519 const char *cmdline_log;
8520 const char *prepared_log;
8521 int non_interactive;
8522 const char *editor;
8523 const char *worktree_path;
8524 const char *branch_name;
8525 const char *repo_path;
8526 char *logmsg_path;
8530 static const struct got_error *
8531 read_prepared_logmsg(char **logmsg, const char *path)
8533 const struct got_error *err = NULL;
8534 FILE *f = NULL;
8535 struct stat sb;
8536 size_t r;
8538 *logmsg = NULL;
8539 memset(&sb, 0, sizeof(sb));
8541 f = fopen(path, "re");
8542 if (f == NULL)
8543 return got_error_from_errno2("fopen", path);
8545 if (fstat(fileno(f), &sb) == -1) {
8546 err = got_error_from_errno2("fstat", path);
8547 goto done;
8549 if (sb.st_size == 0) {
8550 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8551 goto done;
8554 *logmsg = malloc(sb.st_size + 1);
8555 if (*logmsg == NULL) {
8556 err = got_error_from_errno("malloc");
8557 goto done;
8560 r = fread(*logmsg, 1, sb.st_size, f);
8561 if (r != sb.st_size) {
8562 if (ferror(f))
8563 err = got_error_from_errno2("fread", path);
8564 else
8565 err = got_error(GOT_ERR_IO);
8566 goto done;
8568 (*logmsg)[sb.st_size] = '\0';
8569 done:
8570 if (fclose(f) == EOF && err == NULL)
8571 err = got_error_from_errno2("fclose", path);
8572 if (err) {
8573 free(*logmsg);
8574 *logmsg = NULL;
8576 return err;
8579 static const struct got_error *
8580 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8581 const char *diff_path, char **logmsg, void *arg)
8583 char *initial_content = NULL;
8584 struct got_pathlist_entry *pe;
8585 const struct got_error *err = NULL;
8586 char *template = NULL;
8587 struct collect_commit_logmsg_arg *a = arg;
8588 int initial_content_len;
8589 int fd = -1;
8590 size_t len;
8592 /* if a message was specified on the command line, just use it */
8593 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8594 len = strlen(a->cmdline_log) + 1;
8595 *logmsg = malloc(len + 1);
8596 if (*logmsg == NULL)
8597 return got_error_from_errno("malloc");
8598 strlcpy(*logmsg, a->cmdline_log, len);
8599 return NULL;
8600 } else if (a->prepared_log != NULL && a->non_interactive)
8601 return read_prepared_logmsg(logmsg, a->prepared_log);
8603 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8604 return got_error_from_errno("asprintf");
8606 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8607 if (err)
8608 goto done;
8610 if (a->prepared_log) {
8611 char *msg;
8612 err = read_prepared_logmsg(&msg, a->prepared_log);
8613 if (err)
8614 goto done;
8615 if (write(fd, msg, strlen(msg)) == -1) {
8616 err = got_error_from_errno2("write", a->logmsg_path);
8617 free(msg);
8618 goto done;
8620 free(msg);
8623 initial_content_len = asprintf(&initial_content,
8624 "\n# changes to be committed on branch %s:\n",
8625 a->branch_name);
8626 if (initial_content_len == -1) {
8627 err = got_error_from_errno("asprintf");
8628 goto done;
8631 if (write(fd, initial_content, initial_content_len) == -1) {
8632 err = got_error_from_errno2("write", a->logmsg_path);
8633 goto done;
8636 TAILQ_FOREACH(pe, commitable_paths, entry) {
8637 struct got_commitable *ct = pe->data;
8638 dprintf(fd, "# %c %s\n",
8639 got_commitable_get_status(ct),
8640 got_commitable_get_path(ct));
8643 if (diff_path) {
8644 dprintf(fd, "# detailed changes can be viewed in %s\n",
8645 diff_path);
8648 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8649 initial_content_len, a->prepared_log ? 0 : 1);
8650 done:
8651 free(initial_content);
8652 free(template);
8654 if (fd != -1 && close(fd) == -1 && err == NULL)
8655 err = got_error_from_errno2("close", a->logmsg_path);
8657 /* Editor is done; we can now apply unveil(2) */
8658 if (err == NULL)
8659 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8660 if (err) {
8661 free(*logmsg);
8662 *logmsg = NULL;
8664 return err;
8667 static const struct got_error *
8668 cmd_commit(int argc, char *argv[])
8670 const struct got_error *error = NULL;
8671 struct got_worktree *worktree = NULL;
8672 struct got_repository *repo = NULL;
8673 char *cwd = NULL, *id_str = NULL;
8674 struct got_object_id *id = NULL;
8675 const char *logmsg = NULL;
8676 char *prepared_logmsg = NULL;
8677 struct collect_commit_logmsg_arg cl_arg;
8678 const char *author = NULL;
8679 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8680 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8681 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8682 int show_diff = 1;
8683 struct got_pathlist_head paths;
8684 int *pack_fds = NULL;
8686 TAILQ_INIT(&paths);
8687 cl_arg.logmsg_path = NULL;
8689 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8690 switch (ch) {
8691 case 'A':
8692 author = optarg;
8693 error = valid_author(author);
8694 if (error)
8695 return error;
8696 break;
8697 case 'F':
8698 if (logmsg != NULL)
8699 option_conflict('F', 'm');
8700 prepared_logmsg = realpath(optarg, NULL);
8701 if (prepared_logmsg == NULL)
8702 return got_error_from_errno2("realpath",
8703 optarg);
8704 break;
8705 case 'm':
8706 if (prepared_logmsg)
8707 option_conflict('m', 'F');
8708 logmsg = optarg;
8709 break;
8710 case 'N':
8711 non_interactive = 1;
8712 break;
8713 case 'n':
8714 show_diff = 0;
8715 break;
8716 case 'S':
8717 allow_bad_symlinks = 1;
8718 break;
8719 default:
8720 usage_commit();
8721 /* NOTREACHED */
8725 argc -= optind;
8726 argv += optind;
8728 #ifndef PROFILE
8729 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8730 "unveil", NULL) == -1)
8731 err(1, "pledge");
8732 #endif
8733 cwd = getcwd(NULL, 0);
8734 if (cwd == NULL) {
8735 error = got_error_from_errno("getcwd");
8736 goto done;
8739 error = got_repo_pack_fds_open(&pack_fds);
8740 if (error != NULL)
8741 goto done;
8743 error = got_worktree_open(&worktree, cwd);
8744 if (error) {
8745 if (error->code == GOT_ERR_NOT_WORKTREE)
8746 error = wrap_not_worktree_error(error, "commit", cwd);
8747 goto done;
8750 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8751 if (error)
8752 goto done;
8753 if (rebase_in_progress) {
8754 error = got_error(GOT_ERR_REBASING);
8755 goto done;
8758 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8759 worktree);
8760 if (error)
8761 goto done;
8763 error = get_gitconfig_path(&gitconfig_path);
8764 if (error)
8765 goto done;
8766 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8767 gitconfig_path, pack_fds);
8768 if (error != NULL)
8769 goto done;
8771 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8772 if (error)
8773 goto done;
8774 if (merge_in_progress) {
8775 error = got_error(GOT_ERR_MERGE_BUSY);
8776 goto done;
8779 error = get_author(&committer, repo, worktree);
8780 if (error)
8781 goto done;
8783 if (author != NULL && !strcmp(committer, author)) {
8784 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8785 goto done;
8788 if (author == NULL)
8789 author = committer;
8792 * unveil(2) traverses exec(2); if an editor is used we have
8793 * to apply unveil after the log message has been written.
8795 if (logmsg == NULL || strlen(logmsg) == 0)
8796 error = get_editor(&editor);
8797 else
8798 error = apply_unveil(got_repo_get_path(repo), 0,
8799 got_worktree_get_root_path(worktree));
8800 if (error)
8801 goto done;
8803 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8804 if (error)
8805 goto done;
8807 cl_arg.editor = editor;
8808 cl_arg.cmdline_log = logmsg;
8809 cl_arg.prepared_log = prepared_logmsg;
8810 cl_arg.non_interactive = non_interactive;
8811 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8812 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8813 if (!histedit_in_progress) {
8814 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8815 error = got_error(GOT_ERR_COMMIT_BRANCH);
8816 goto done;
8818 cl_arg.branch_name += 11;
8820 cl_arg.repo_path = got_repo_get_path(repo);
8821 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8822 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8823 print_status, NULL, repo);
8824 if (error) {
8825 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8826 cl_arg.logmsg_path != NULL)
8827 preserve_logmsg = 1;
8828 goto done;
8831 error = got_object_id_str(&id_str, id);
8832 if (error)
8833 goto done;
8834 printf("Created commit %s\n", id_str);
8835 done:
8836 if (preserve_logmsg) {
8837 fprintf(stderr, "%s: log message preserved in %s\n",
8838 getprogname(), cl_arg.logmsg_path);
8839 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8840 error == NULL)
8841 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8842 free(cl_arg.logmsg_path);
8843 if (repo) {
8844 const struct got_error *close_err = got_repo_close(repo);
8845 if (error == NULL)
8846 error = close_err;
8848 if (worktree)
8849 got_worktree_close(worktree);
8850 if (pack_fds) {
8851 const struct got_error *pack_err =
8852 got_repo_pack_fds_close(pack_fds);
8853 if (error == NULL)
8854 error = pack_err;
8856 free(cwd);
8857 free(id_str);
8858 free(gitconfig_path);
8859 free(editor);
8860 free(committer);
8861 free(prepared_logmsg);
8862 return error;
8865 __dead static void
8866 usage_send(void)
8868 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8869 "[-r repository-path] [-t tag] [remote-repository]\n",
8870 getprogname());
8871 exit(1);
8874 static void
8875 print_load_info(int print_colored, int print_found, int print_trees,
8876 int ncolored, int nfound, int ntrees)
8878 if (print_colored) {
8879 printf("%d commit%s colored", ncolored,
8880 ncolored == 1 ? "" : "s");
8882 if (print_found) {
8883 printf("%s%d object%s found",
8884 ncolored > 0 ? "; " : "",
8885 nfound, nfound == 1 ? "" : "s");
8887 if (print_trees) {
8888 printf("; %d tree%s scanned", ntrees,
8889 ntrees == 1 ? "" : "s");
8893 struct got_send_progress_arg {
8894 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8895 int verbosity;
8896 int last_ncolored;
8897 int last_nfound;
8898 int last_ntrees;
8899 int loading_done;
8900 int last_ncommits;
8901 int last_nobj_total;
8902 int last_p_deltify;
8903 int last_p_written;
8904 int last_p_sent;
8905 int printed_something;
8906 int sent_something;
8907 struct got_pathlist_head *delete_branches;
8910 static const struct got_error *
8911 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8912 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8913 int nobj_written, off_t bytes_sent, const char *refname,
8914 const char *errmsg, int success)
8916 struct got_send_progress_arg *a = arg;
8917 char scaled_packsize[FMT_SCALED_STRSIZE];
8918 char scaled_sent[FMT_SCALED_STRSIZE];
8919 int p_deltify = 0, p_written = 0, p_sent = 0;
8920 int print_colored = 0, print_found = 0, print_trees = 0;
8921 int print_searching = 0, print_total = 0;
8922 int print_deltify = 0, print_written = 0, print_sent = 0;
8924 if (a->verbosity < 0)
8925 return NULL;
8927 if (refname) {
8928 const char *status = success ? "accepted" : "rejected";
8930 if (success) {
8931 struct got_pathlist_entry *pe;
8932 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8933 const char *branchname = pe->path;
8934 if (got_path_cmp(branchname, refname,
8935 strlen(branchname), strlen(refname)) == 0) {
8936 status = "deleted";
8937 a->sent_something = 1;
8938 break;
8943 if (a->printed_something)
8944 putchar('\n');
8945 printf("Server has %s %s", status, refname);
8946 if (errmsg)
8947 printf(": %s", errmsg);
8948 a->printed_something = 1;
8949 return NULL;
8952 if (a->last_ncolored != ncolored) {
8953 print_colored = 1;
8954 a->last_ncolored = ncolored;
8957 if (a->last_nfound != nfound) {
8958 print_colored = 1;
8959 print_found = 1;
8960 a->last_nfound = nfound;
8963 if (a->last_ntrees != ntrees) {
8964 print_colored = 1;
8965 print_found = 1;
8966 print_trees = 1;
8967 a->last_ntrees = ntrees;
8970 if ((print_colored || print_found || print_trees) &&
8971 !a->loading_done) {
8972 printf("\r");
8973 print_load_info(print_colored, print_found, print_trees,
8974 ncolored, nfound, ntrees);
8975 a->printed_something = 1;
8976 fflush(stdout);
8977 return NULL;
8978 } else if (!a->loading_done) {
8979 printf("\r");
8980 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8981 printf("\n");
8982 a->loading_done = 1;
8985 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8986 return got_error_from_errno("fmt_scaled");
8987 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8988 return got_error_from_errno("fmt_scaled");
8990 if (a->last_ncommits != ncommits) {
8991 print_searching = 1;
8992 a->last_ncommits = ncommits;
8995 if (a->last_nobj_total != nobj_total) {
8996 print_searching = 1;
8997 print_total = 1;
8998 a->last_nobj_total = nobj_total;
9001 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9002 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9003 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9004 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9005 return got_error(GOT_ERR_NO_SPACE);
9008 if (nobj_deltify > 0 || nobj_written > 0) {
9009 if (nobj_deltify > 0) {
9010 p_deltify = (nobj_deltify * 100) / nobj_total;
9011 if (p_deltify != a->last_p_deltify) {
9012 a->last_p_deltify = p_deltify;
9013 print_searching = 1;
9014 print_total = 1;
9015 print_deltify = 1;
9018 if (nobj_written > 0) {
9019 p_written = (nobj_written * 100) / nobj_total;
9020 if (p_written != a->last_p_written) {
9021 a->last_p_written = p_written;
9022 print_searching = 1;
9023 print_total = 1;
9024 print_deltify = 1;
9025 print_written = 1;
9030 if (bytes_sent > 0) {
9031 p_sent = (bytes_sent * 100) / packfile_size;
9032 if (p_sent != a->last_p_sent) {
9033 a->last_p_sent = p_sent;
9034 print_searching = 1;
9035 print_total = 1;
9036 print_deltify = 1;
9037 print_written = 1;
9038 print_sent = 1;
9040 a->sent_something = 1;
9043 if (print_searching || print_total || print_deltify || print_written ||
9044 print_sent)
9045 printf("\r");
9046 if (print_searching)
9047 printf("packing %d reference%s", ncommits,
9048 ncommits == 1 ? "" : "s");
9049 if (print_total)
9050 printf("; %d object%s", nobj_total,
9051 nobj_total == 1 ? "" : "s");
9052 if (print_deltify)
9053 printf("; deltify: %d%%", p_deltify);
9054 if (print_sent)
9055 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9056 scaled_packsize, p_sent);
9057 else if (print_written)
9058 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9059 scaled_packsize, p_written);
9060 if (print_searching || print_total || print_deltify ||
9061 print_written || print_sent) {
9062 a->printed_something = 1;
9063 fflush(stdout);
9065 return NULL;
9068 static const struct got_error *
9069 cmd_send(int argc, char *argv[])
9071 const struct got_error *error = NULL;
9072 char *cwd = NULL, *repo_path = NULL;
9073 const char *remote_name;
9074 char *proto = NULL, *host = NULL, *port = NULL;
9075 char *repo_name = NULL, *server_path = NULL;
9076 const struct got_remote_repo *remotes, *remote = NULL;
9077 int nremotes, nbranches = 0, ndelete_branches = 0;
9078 struct got_repository *repo = NULL;
9079 struct got_worktree *worktree = NULL;
9080 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9081 struct got_pathlist_head branches;
9082 struct got_pathlist_head tags;
9083 struct got_reflist_head all_branches;
9084 struct got_reflist_head all_tags;
9085 struct got_pathlist_head delete_args;
9086 struct got_pathlist_head delete_branches;
9087 struct got_reflist_entry *re;
9088 struct got_pathlist_entry *pe;
9089 int i, ch, sendfd = -1, sendstatus;
9090 pid_t sendpid = -1;
9091 struct got_send_progress_arg spa;
9092 int verbosity = 0, overwrite_refs = 0;
9093 int send_all_branches = 0, send_all_tags = 0;
9094 struct got_reference *ref = NULL;
9095 int *pack_fds = NULL;
9097 TAILQ_INIT(&branches);
9098 TAILQ_INIT(&tags);
9099 TAILQ_INIT(&all_branches);
9100 TAILQ_INIT(&all_tags);
9101 TAILQ_INIT(&delete_args);
9102 TAILQ_INIT(&delete_branches);
9104 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9105 switch (ch) {
9106 case 'a':
9107 send_all_branches = 1;
9108 break;
9109 case 'b':
9110 error = got_pathlist_append(&branches, optarg, NULL);
9111 if (error)
9112 return error;
9113 nbranches++;
9114 break;
9115 case 'd':
9116 error = got_pathlist_append(&delete_args, optarg, NULL);
9117 if (error)
9118 return error;
9119 break;
9120 case 'f':
9121 overwrite_refs = 1;
9122 break;
9123 case 'q':
9124 verbosity = -1;
9125 break;
9126 case 'r':
9127 repo_path = realpath(optarg, NULL);
9128 if (repo_path == NULL)
9129 return got_error_from_errno2("realpath",
9130 optarg);
9131 got_path_strip_trailing_slashes(repo_path);
9132 break;
9133 case 'T':
9134 send_all_tags = 1;
9135 break;
9136 case 't':
9137 error = got_pathlist_append(&tags, optarg, NULL);
9138 if (error)
9139 return error;
9140 break;
9141 case 'v':
9142 if (verbosity < 0)
9143 verbosity = 0;
9144 else if (verbosity < 3)
9145 verbosity++;
9146 break;
9147 default:
9148 usage_send();
9149 /* NOTREACHED */
9152 argc -= optind;
9153 argv += optind;
9155 if (send_all_branches && !TAILQ_EMPTY(&branches))
9156 option_conflict('a', 'b');
9157 if (send_all_tags && !TAILQ_EMPTY(&tags))
9158 option_conflict('T', 't');
9161 if (argc == 0)
9162 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9163 else if (argc == 1)
9164 remote_name = argv[0];
9165 else
9166 usage_send();
9168 cwd = getcwd(NULL, 0);
9169 if (cwd == NULL) {
9170 error = got_error_from_errno("getcwd");
9171 goto done;
9174 error = got_repo_pack_fds_open(&pack_fds);
9175 if (error != NULL)
9176 goto done;
9178 if (repo_path == NULL) {
9179 error = got_worktree_open(&worktree, cwd);
9180 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9181 goto done;
9182 else
9183 error = NULL;
9184 if (worktree) {
9185 repo_path =
9186 strdup(got_worktree_get_repo_path(worktree));
9187 if (repo_path == NULL)
9188 error = got_error_from_errno("strdup");
9189 if (error)
9190 goto done;
9191 } else {
9192 repo_path = strdup(cwd);
9193 if (repo_path == NULL) {
9194 error = got_error_from_errno("strdup");
9195 goto done;
9200 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9201 if (error)
9202 goto done;
9204 if (worktree) {
9205 worktree_conf = got_worktree_get_gotconfig(worktree);
9206 if (worktree_conf) {
9207 got_gotconfig_get_remotes(&nremotes, &remotes,
9208 worktree_conf);
9209 for (i = 0; i < nremotes; i++) {
9210 if (strcmp(remotes[i].name, remote_name) == 0) {
9211 remote = &remotes[i];
9212 break;
9217 if (remote == NULL) {
9218 repo_conf = got_repo_get_gotconfig(repo);
9219 if (repo_conf) {
9220 got_gotconfig_get_remotes(&nremotes, &remotes,
9221 repo_conf);
9222 for (i = 0; i < nremotes; i++) {
9223 if (strcmp(remotes[i].name, remote_name) == 0) {
9224 remote = &remotes[i];
9225 break;
9230 if (remote == NULL) {
9231 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9232 for (i = 0; i < nremotes; i++) {
9233 if (strcmp(remotes[i].name, remote_name) == 0) {
9234 remote = &remotes[i];
9235 break;
9239 if (remote == NULL) {
9240 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9241 goto done;
9244 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9245 &repo_name, remote->send_url);
9246 if (error)
9247 goto done;
9249 if (strcmp(proto, "git") == 0) {
9250 #ifndef PROFILE
9251 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9252 "sendfd dns inet unveil", NULL) == -1)
9253 err(1, "pledge");
9254 #endif
9255 } else if (strcmp(proto, "git+ssh") == 0 ||
9256 strcmp(proto, "ssh") == 0) {
9257 #ifndef PROFILE
9258 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9259 "sendfd unveil", NULL) == -1)
9260 err(1, "pledge");
9261 #endif
9262 } else if (strcmp(proto, "http") == 0 ||
9263 strcmp(proto, "git+http") == 0) {
9264 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9265 goto done;
9266 } else {
9267 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9268 goto done;
9271 error = got_dial_apply_unveil(proto);
9272 if (error)
9273 goto done;
9275 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9276 if (error)
9277 goto done;
9279 if (send_all_branches) {
9280 error = got_ref_list(&all_branches, repo, "refs/heads",
9281 got_ref_cmp_by_name, NULL);
9282 if (error)
9283 goto done;
9284 TAILQ_FOREACH(re, &all_branches, entry) {
9285 const char *branchname = got_ref_get_name(re->ref);
9286 error = got_pathlist_append(&branches,
9287 branchname, NULL);
9288 if (error)
9289 goto done;
9290 nbranches++;
9292 } else if (nbranches == 0) {
9293 for (i = 0; i < remote->nsend_branches; i++) {
9294 error = got_pathlist_append(&branches,
9295 remote->send_branches[i], NULL);
9296 if (error)
9297 goto done;
9301 if (send_all_tags) {
9302 error = got_ref_list(&all_tags, repo, "refs/tags",
9303 got_ref_cmp_by_name, NULL);
9304 if (error)
9305 goto done;
9306 TAILQ_FOREACH(re, &all_tags, entry) {
9307 const char *tagname = got_ref_get_name(re->ref);
9308 error = got_pathlist_append(&tags,
9309 tagname, NULL);
9310 if (error)
9311 goto done;
9316 * To prevent accidents only branches in refs/heads/ can be deleted
9317 * with 'got send -d'.
9318 * Deleting anything else requires local repository access or Git.
9320 TAILQ_FOREACH(pe, &delete_args, entry) {
9321 const char *branchname = pe->path;
9322 char *s;
9323 struct got_pathlist_entry *new;
9324 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9325 s = strdup(branchname);
9326 if (s == NULL) {
9327 error = got_error_from_errno("strdup");
9328 goto done;
9330 } else {
9331 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9332 error = got_error_from_errno("asprintf");
9333 goto done;
9336 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9337 if (error || new == NULL /* duplicate */)
9338 free(s);
9339 if (error)
9340 goto done;
9341 ndelete_branches++;
9344 if (nbranches == 0 && ndelete_branches == 0) {
9345 struct got_reference *head_ref;
9346 if (worktree)
9347 error = got_ref_open(&head_ref, repo,
9348 got_worktree_get_head_ref_name(worktree), 0);
9349 else
9350 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9351 if (error)
9352 goto done;
9353 if (got_ref_is_symbolic(head_ref)) {
9354 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9355 got_ref_close(head_ref);
9356 if (error)
9357 goto done;
9358 } else
9359 ref = head_ref;
9360 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9361 NULL);
9362 if (error)
9363 goto done;
9364 nbranches++;
9367 if (verbosity >= 0) {
9368 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9369 remote->name, proto, host,
9370 port ? ":" : "", port ? port : "",
9371 *server_path == '/' ? "" : "/", server_path);
9374 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9375 server_path, verbosity);
9376 if (error)
9377 goto done;
9379 memset(&spa, 0, sizeof(spa));
9380 spa.last_scaled_packsize[0] = '\0';
9381 spa.last_p_deltify = -1;
9382 spa.last_p_written = -1;
9383 spa.verbosity = verbosity;
9384 spa.delete_branches = &delete_branches;
9385 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9386 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9387 check_cancelled, NULL);
9388 if (spa.printed_something)
9389 putchar('\n');
9390 if (error)
9391 goto done;
9392 if (!spa.sent_something && verbosity >= 0)
9393 printf("Already up-to-date\n");
9394 done:
9395 if (sendpid > 0) {
9396 if (kill(sendpid, SIGTERM) == -1)
9397 error = got_error_from_errno("kill");
9398 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9399 error = got_error_from_errno("waitpid");
9401 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9402 error = got_error_from_errno("close");
9403 if (repo) {
9404 const struct got_error *close_err = got_repo_close(repo);
9405 if (error == NULL)
9406 error = close_err;
9408 if (worktree)
9409 got_worktree_close(worktree);
9410 if (pack_fds) {
9411 const struct got_error *pack_err =
9412 got_repo_pack_fds_close(pack_fds);
9413 if (error == NULL)
9414 error = pack_err;
9416 if (ref)
9417 got_ref_close(ref);
9418 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9419 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9420 got_ref_list_free(&all_branches);
9421 got_ref_list_free(&all_tags);
9422 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9423 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9424 free(cwd);
9425 free(repo_path);
9426 free(proto);
9427 free(host);
9428 free(port);
9429 free(server_path);
9430 free(repo_name);
9431 return error;
9434 __dead static void
9435 usage_cherrypick(void)
9437 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9438 exit(1);
9441 static const struct got_error *
9442 cmd_cherrypick(int argc, char *argv[])
9444 const struct got_error *error = NULL;
9445 struct got_worktree *worktree = NULL;
9446 struct got_repository *repo = NULL;
9447 char *cwd = NULL, *commit_id_str = NULL;
9448 struct got_object_id *commit_id = NULL;
9449 struct got_commit_object *commit = NULL;
9450 struct got_object_qid *pid;
9451 int ch;
9452 struct got_update_progress_arg upa;
9453 int *pack_fds = NULL;
9455 while ((ch = getopt(argc, argv, "")) != -1) {
9456 switch (ch) {
9457 default:
9458 usage_cherrypick();
9459 /* NOTREACHED */
9463 argc -= optind;
9464 argv += optind;
9466 #ifndef PROFILE
9467 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9468 "unveil", NULL) == -1)
9469 err(1, "pledge");
9470 #endif
9471 if (argc != 1)
9472 usage_cherrypick();
9474 cwd = getcwd(NULL, 0);
9475 if (cwd == NULL) {
9476 error = got_error_from_errno("getcwd");
9477 goto done;
9480 error = got_repo_pack_fds_open(&pack_fds);
9481 if (error != NULL)
9482 goto done;
9484 error = got_worktree_open(&worktree, cwd);
9485 if (error) {
9486 if (error->code == GOT_ERR_NOT_WORKTREE)
9487 error = wrap_not_worktree_error(error, "cherrypick",
9488 cwd);
9489 goto done;
9492 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9493 NULL, pack_fds);
9494 if (error != NULL)
9495 goto done;
9497 error = apply_unveil(got_repo_get_path(repo), 0,
9498 got_worktree_get_root_path(worktree));
9499 if (error)
9500 goto done;
9502 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9503 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9504 if (error)
9505 goto done;
9506 error = got_object_id_str(&commit_id_str, commit_id);
9507 if (error)
9508 goto done;
9510 error = got_object_open_as_commit(&commit, repo, commit_id);
9511 if (error)
9512 goto done;
9513 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9514 memset(&upa, 0, sizeof(upa));
9515 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9516 commit_id, repo, update_progress, &upa, check_cancelled,
9517 NULL);
9518 if (error != NULL)
9519 goto done;
9521 if (upa.did_something)
9522 printf("Merged commit %s\n", commit_id_str);
9523 print_merge_progress_stats(&upa);
9524 done:
9525 if (commit)
9526 got_object_commit_close(commit);
9527 free(commit_id_str);
9528 if (worktree)
9529 got_worktree_close(worktree);
9530 if (repo) {
9531 const struct got_error *close_err = got_repo_close(repo);
9532 if (error == NULL)
9533 error = close_err;
9535 if (pack_fds) {
9536 const struct got_error *pack_err =
9537 got_repo_pack_fds_close(pack_fds);
9538 if (error == NULL)
9539 error = pack_err;
9542 return error;
9545 __dead static void
9546 usage_backout(void)
9548 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9549 exit(1);
9552 static const struct got_error *
9553 cmd_backout(int argc, char *argv[])
9555 const struct got_error *error = NULL;
9556 struct got_worktree *worktree = NULL;
9557 struct got_repository *repo = NULL;
9558 char *cwd = NULL, *commit_id_str = NULL;
9559 struct got_object_id *commit_id = NULL;
9560 struct got_commit_object *commit = NULL;
9561 struct got_object_qid *pid;
9562 int ch;
9563 struct got_update_progress_arg upa;
9564 int *pack_fds = NULL;
9566 while ((ch = getopt(argc, argv, "")) != -1) {
9567 switch (ch) {
9568 default:
9569 usage_backout();
9570 /* NOTREACHED */
9574 argc -= optind;
9575 argv += optind;
9577 #ifndef PROFILE
9578 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9579 "unveil", NULL) == -1)
9580 err(1, "pledge");
9581 #endif
9582 if (argc != 1)
9583 usage_backout();
9585 cwd = getcwd(NULL, 0);
9586 if (cwd == NULL) {
9587 error = got_error_from_errno("getcwd");
9588 goto done;
9591 error = got_repo_pack_fds_open(&pack_fds);
9592 if (error != NULL)
9593 goto done;
9595 error = got_worktree_open(&worktree, cwd);
9596 if (error) {
9597 if (error->code == GOT_ERR_NOT_WORKTREE)
9598 error = wrap_not_worktree_error(error, "backout", cwd);
9599 goto done;
9602 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9603 NULL, pack_fds);
9604 if (error != NULL)
9605 goto done;
9607 error = apply_unveil(got_repo_get_path(repo), 0,
9608 got_worktree_get_root_path(worktree));
9609 if (error)
9610 goto done;
9612 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9613 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9614 if (error)
9615 goto done;
9616 error = got_object_id_str(&commit_id_str, commit_id);
9617 if (error)
9618 goto done;
9620 error = got_object_open_as_commit(&commit, repo, commit_id);
9621 if (error)
9622 goto done;
9623 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9624 if (pid == NULL) {
9625 error = got_error(GOT_ERR_ROOT_COMMIT);
9626 goto done;
9629 memset(&upa, 0, sizeof(upa));
9630 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9631 repo, update_progress, &upa, check_cancelled, NULL);
9632 if (error != NULL)
9633 goto done;
9635 if (upa.did_something)
9636 printf("Backed out commit %s\n", commit_id_str);
9637 print_merge_progress_stats(&upa);
9638 done:
9639 if (commit)
9640 got_object_commit_close(commit);
9641 free(commit_id_str);
9642 if (worktree)
9643 got_worktree_close(worktree);
9644 if (repo) {
9645 const struct got_error *close_err = got_repo_close(repo);
9646 if (error == NULL)
9647 error = close_err;
9649 if (pack_fds) {
9650 const struct got_error *pack_err =
9651 got_repo_pack_fds_close(pack_fds);
9652 if (error == NULL)
9653 error = pack_err;
9655 return error;
9658 __dead static void
9659 usage_rebase(void)
9661 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9662 exit(1);
9665 static void
9666 trim_logmsg(char *logmsg, int limit)
9668 char *nl;
9669 size_t len;
9671 len = strlen(logmsg);
9672 if (len > limit)
9673 len = limit;
9674 logmsg[len] = '\0';
9675 nl = strchr(logmsg, '\n');
9676 if (nl)
9677 *nl = '\0';
9680 static const struct got_error *
9681 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9683 const struct got_error *err;
9684 char *logmsg0 = NULL;
9685 const char *s;
9687 err = got_object_commit_get_logmsg(&logmsg0, commit);
9688 if (err)
9689 return err;
9691 s = logmsg0;
9692 while (isspace((unsigned char)s[0]))
9693 s++;
9695 *logmsg = strdup(s);
9696 if (*logmsg == NULL) {
9697 err = got_error_from_errno("strdup");
9698 goto done;
9701 trim_logmsg(*logmsg, limit);
9702 done:
9703 free(logmsg0);
9704 return err;
9707 static const struct got_error *
9708 show_rebase_merge_conflict(struct got_object_id *id,
9709 struct got_repository *repo)
9711 const struct got_error *err;
9712 struct got_commit_object *commit = NULL;
9713 char *id_str = NULL, *logmsg = NULL;
9715 err = got_object_open_as_commit(&commit, repo, id);
9716 if (err)
9717 return err;
9719 err = got_object_id_str(&id_str, id);
9720 if (err)
9721 goto done;
9723 id_str[12] = '\0';
9725 err = get_short_logmsg(&logmsg, 42, commit);
9726 if (err)
9727 goto done;
9729 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9730 done:
9731 free(id_str);
9732 got_object_commit_close(commit);
9733 free(logmsg);
9734 return err;
9737 static const struct got_error *
9738 show_rebase_progress(struct got_commit_object *commit,
9739 struct got_object_id *old_id, struct got_object_id *new_id)
9741 const struct got_error *err;
9742 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9744 err = got_object_id_str(&old_id_str, old_id);
9745 if (err)
9746 goto done;
9748 if (new_id) {
9749 err = got_object_id_str(&new_id_str, new_id);
9750 if (err)
9751 goto done;
9754 old_id_str[12] = '\0';
9755 if (new_id_str)
9756 new_id_str[12] = '\0';
9758 err = get_short_logmsg(&logmsg, 42, commit);
9759 if (err)
9760 goto done;
9762 printf("%s -> %s: %s\n", old_id_str,
9763 new_id_str ? new_id_str : "no-op change", logmsg);
9764 done:
9765 free(old_id_str);
9766 free(new_id_str);
9767 free(logmsg);
9768 return err;
9771 static const struct got_error *
9772 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9773 struct got_reference *branch, struct got_reference *new_base_branch,
9774 struct got_reference *tmp_branch, struct got_repository *repo,
9775 int create_backup)
9777 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9778 return got_worktree_rebase_complete(worktree, fileindex,
9779 new_base_branch, tmp_branch, branch, repo, create_backup);
9782 static const struct got_error *
9783 rebase_commit(struct got_pathlist_head *merged_paths,
9784 struct got_worktree *worktree, struct got_fileindex *fileindex,
9785 struct got_reference *tmp_branch, const char *committer,
9786 struct got_object_id *commit_id, struct got_repository *repo)
9788 const struct got_error *error;
9789 struct got_commit_object *commit;
9790 struct got_object_id *new_commit_id;
9792 error = got_object_open_as_commit(&commit, repo, commit_id);
9793 if (error)
9794 return error;
9796 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9797 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9798 repo);
9799 if (error) {
9800 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9801 goto done;
9802 error = show_rebase_progress(commit, commit_id, NULL);
9803 } else {
9804 error = show_rebase_progress(commit, commit_id, new_commit_id);
9805 free(new_commit_id);
9807 done:
9808 got_object_commit_close(commit);
9809 return error;
9812 struct check_path_prefix_arg {
9813 const char *path_prefix;
9814 size_t len;
9815 int errcode;
9818 static const struct got_error *
9819 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9820 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9821 struct got_object_id *id1, struct got_object_id *id2,
9822 const char *path1, const char *path2,
9823 mode_t mode1, mode_t mode2, struct got_repository *repo)
9825 struct check_path_prefix_arg *a = arg;
9827 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9828 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9829 return got_error(a->errcode);
9831 return NULL;
9834 static const struct got_error *
9835 check_path_prefix(struct got_object_id *parent_id,
9836 struct got_object_id *commit_id, const char *path_prefix,
9837 int errcode, struct got_repository *repo)
9839 const struct got_error *err;
9840 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9841 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9842 struct check_path_prefix_arg cpp_arg;
9844 if (got_path_is_root_dir(path_prefix))
9845 return NULL;
9847 err = got_object_open_as_commit(&commit, repo, commit_id);
9848 if (err)
9849 goto done;
9851 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9852 if (err)
9853 goto done;
9855 err = got_object_open_as_tree(&tree1, repo,
9856 got_object_commit_get_tree_id(parent_commit));
9857 if (err)
9858 goto done;
9860 err = got_object_open_as_tree(&tree2, repo,
9861 got_object_commit_get_tree_id(commit));
9862 if (err)
9863 goto done;
9865 cpp_arg.path_prefix = path_prefix;
9866 while (cpp_arg.path_prefix[0] == '/')
9867 cpp_arg.path_prefix++;
9868 cpp_arg.len = strlen(cpp_arg.path_prefix);
9869 cpp_arg.errcode = errcode;
9870 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9871 check_path_prefix_in_diff, &cpp_arg, 0);
9872 done:
9873 if (tree1)
9874 got_object_tree_close(tree1);
9875 if (tree2)
9876 got_object_tree_close(tree2);
9877 if (commit)
9878 got_object_commit_close(commit);
9879 if (parent_commit)
9880 got_object_commit_close(parent_commit);
9881 return err;
9884 static const struct got_error *
9885 collect_commits(struct got_object_id_queue *commits,
9886 struct got_object_id *initial_commit_id,
9887 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9888 const char *path_prefix, int path_prefix_errcode,
9889 struct got_repository *repo)
9891 const struct got_error *err = NULL;
9892 struct got_commit_graph *graph = NULL;
9893 struct got_object_id parent_id, commit_id;
9894 struct got_object_qid *qid;
9896 err = got_commit_graph_open(&graph, "/", 1);
9897 if (err)
9898 return err;
9900 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9901 check_cancelled, NULL);
9902 if (err)
9903 goto done;
9905 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9906 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9907 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9908 check_cancelled, NULL);
9909 if (err) {
9910 if (err->code == GOT_ERR_ITER_COMPLETED) {
9911 err = got_error_msg(GOT_ERR_ANCESTRY,
9912 "ran out of commits to rebase before "
9913 "youngest common ancestor commit has "
9914 "been reached?!?");
9916 goto done;
9917 } else {
9918 err = check_path_prefix(&parent_id, &commit_id,
9919 path_prefix, path_prefix_errcode, repo);
9920 if (err)
9921 goto done;
9923 err = got_object_qid_alloc(&qid, &commit_id);
9924 if (err)
9925 goto done;
9926 STAILQ_INSERT_HEAD(commits, qid, entry);
9928 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9931 done:
9932 got_commit_graph_close(graph);
9933 return err;
9936 static const struct got_error *
9937 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9939 const struct got_error *err = NULL;
9940 time_t committer_time;
9941 struct tm tm;
9942 char datebuf[11]; /* YYYY-MM-DD + NUL */
9943 char *author0 = NULL, *author, *smallerthan;
9944 char *logmsg0 = NULL, *logmsg, *newline;
9946 committer_time = got_object_commit_get_committer_time(commit);
9947 if (gmtime_r(&committer_time, &tm) == NULL)
9948 return got_error_from_errno("gmtime_r");
9949 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9950 return got_error(GOT_ERR_NO_SPACE);
9952 author0 = strdup(got_object_commit_get_author(commit));
9953 if (author0 == NULL)
9954 return got_error_from_errno("strdup");
9955 author = author0;
9956 smallerthan = strchr(author, '<');
9957 if (smallerthan && smallerthan[1] != '\0')
9958 author = smallerthan + 1;
9959 author[strcspn(author, "@>")] = '\0';
9961 err = got_object_commit_get_logmsg(&logmsg0, commit);
9962 if (err)
9963 goto done;
9964 logmsg = logmsg0;
9965 while (*logmsg == '\n')
9966 logmsg++;
9967 newline = strchr(logmsg, '\n');
9968 if (newline)
9969 *newline = '\0';
9971 if (asprintf(brief_str, "%s %s %s",
9972 datebuf, author, logmsg) == -1)
9973 err = got_error_from_errno("asprintf");
9974 done:
9975 free(author0);
9976 free(logmsg0);
9977 return err;
9980 static const struct got_error *
9981 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9982 struct got_repository *repo)
9984 const struct got_error *err;
9985 char *id_str;
9987 err = got_object_id_str(&id_str, id);
9988 if (err)
9989 return err;
9991 err = got_ref_delete(ref, repo);
9992 if (err)
9993 goto done;
9995 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9996 done:
9997 free(id_str);
9998 return err;
10001 static const struct got_error *
10002 print_backup_ref(const char *branch_name, const char *new_id_str,
10003 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10004 struct got_reflist_object_id_map *refs_idmap,
10005 struct got_repository *repo)
10007 const struct got_error *err = NULL;
10008 struct got_reflist_head *refs;
10009 char *refs_str = NULL;
10010 struct got_object_id *new_commit_id = NULL;
10011 struct got_commit_object *new_commit = NULL;
10012 char *new_commit_brief_str = NULL;
10013 struct got_object_id *yca_id = NULL;
10014 struct got_commit_object *yca_commit = NULL;
10015 char *yca_id_str = NULL, *yca_brief_str = NULL;
10016 char *custom_refs_str;
10018 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10019 return got_error_from_errno("asprintf");
10021 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10022 0, 0, refs_idmap, custom_refs_str);
10023 if (err)
10024 goto done;
10026 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10027 if (err)
10028 goto done;
10030 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10031 if (refs) {
10032 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10033 if (err)
10034 goto done;
10037 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10038 if (err)
10039 goto done;
10041 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10042 if (err)
10043 goto done;
10045 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10046 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10047 if (err)
10048 goto done;
10050 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10051 refs_str ? " (" : "", refs_str ? refs_str : "",
10052 refs_str ? ")" : "", new_commit_brief_str);
10053 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10054 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10055 free(refs_str);
10056 refs_str = NULL;
10058 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10059 if (err)
10060 goto done;
10062 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10063 if (err)
10064 goto done;
10066 err = got_object_id_str(&yca_id_str, yca_id);
10067 if (err)
10068 goto done;
10070 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10071 if (refs) {
10072 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10073 if (err)
10074 goto done;
10076 printf("history forked at %s%s%s%s\n %s\n",
10077 yca_id_str,
10078 refs_str ? " (" : "", refs_str ? refs_str : "",
10079 refs_str ? ")" : "", yca_brief_str);
10081 done:
10082 free(custom_refs_str);
10083 free(new_commit_id);
10084 free(refs_str);
10085 free(yca_id);
10086 free(yca_id_str);
10087 free(yca_brief_str);
10088 if (new_commit)
10089 got_object_commit_close(new_commit);
10090 if (yca_commit)
10091 got_object_commit_close(yca_commit);
10093 return NULL;
10096 static const struct got_error *
10097 process_backup_refs(const char *backup_ref_prefix,
10098 const char *wanted_branch_name,
10099 int delete, struct got_repository *repo)
10101 const struct got_error *err;
10102 struct got_reflist_head refs, backup_refs;
10103 struct got_reflist_entry *re;
10104 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10105 struct got_object_id *old_commit_id = NULL;
10106 char *branch_name = NULL;
10107 struct got_commit_object *old_commit = NULL;
10108 struct got_reflist_object_id_map *refs_idmap = NULL;
10109 int wanted_branch_found = 0;
10111 TAILQ_INIT(&refs);
10112 TAILQ_INIT(&backup_refs);
10114 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10115 if (err)
10116 return err;
10118 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10119 if (err)
10120 goto done;
10122 if (wanted_branch_name) {
10123 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10124 wanted_branch_name += 11;
10127 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10128 got_ref_cmp_by_commit_timestamp_descending, repo);
10129 if (err)
10130 goto done;
10132 TAILQ_FOREACH(re, &backup_refs, entry) {
10133 const char *refname = got_ref_get_name(re->ref);
10134 char *slash;
10136 err = check_cancelled(NULL);
10137 if (err)
10138 break;
10140 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10141 if (err)
10142 break;
10144 err = got_object_open_as_commit(&old_commit, repo,
10145 old_commit_id);
10146 if (err)
10147 break;
10149 if (strncmp(backup_ref_prefix, refname,
10150 backup_ref_prefix_len) == 0)
10151 refname += backup_ref_prefix_len;
10153 while (refname[0] == '/')
10154 refname++;
10156 branch_name = strdup(refname);
10157 if (branch_name == NULL) {
10158 err = got_error_from_errno("strdup");
10159 break;
10161 slash = strrchr(branch_name, '/');
10162 if (slash) {
10163 *slash = '\0';
10164 refname += strlen(branch_name) + 1;
10167 if (wanted_branch_name == NULL ||
10168 strcmp(wanted_branch_name, branch_name) == 0) {
10169 wanted_branch_found = 1;
10170 if (delete) {
10171 err = delete_backup_ref(re->ref,
10172 old_commit_id, repo);
10173 } else {
10174 err = print_backup_ref(branch_name, refname,
10175 old_commit_id, old_commit, refs_idmap,
10176 repo);
10178 if (err)
10179 break;
10182 free(old_commit_id);
10183 old_commit_id = NULL;
10184 free(branch_name);
10185 branch_name = NULL;
10186 got_object_commit_close(old_commit);
10187 old_commit = NULL;
10190 if (wanted_branch_name && !wanted_branch_found) {
10191 err = got_error_fmt(GOT_ERR_NOT_REF,
10192 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10194 done:
10195 if (refs_idmap)
10196 got_reflist_object_id_map_free(refs_idmap);
10197 got_ref_list_free(&refs);
10198 got_ref_list_free(&backup_refs);
10199 free(old_commit_id);
10200 free(branch_name);
10201 if (old_commit)
10202 got_object_commit_close(old_commit);
10203 return err;
10206 static const struct got_error *
10207 abort_progress(void *arg, unsigned char status, const char *path)
10210 * Unversioned files should not clutter progress output when
10211 * an operation is aborted.
10213 if (status == GOT_STATUS_UNVERSIONED)
10214 return NULL;
10216 return update_progress(arg, status, path);
10219 static const struct got_error *
10220 cmd_rebase(int argc, char *argv[])
10222 const struct got_error *error = NULL;
10223 struct got_worktree *worktree = NULL;
10224 struct got_repository *repo = NULL;
10225 struct got_fileindex *fileindex = NULL;
10226 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10227 struct got_reference *branch = NULL;
10228 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10229 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10230 struct got_object_id *resume_commit_id = NULL;
10231 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10232 struct got_object_id *head_commit_id = NULL;
10233 struct got_reference *head_ref = NULL;
10234 struct got_commit_object *commit = NULL;
10235 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10236 int histedit_in_progress = 0, merge_in_progress = 0;
10237 int create_backup = 1, list_backups = 0, delete_backups = 0;
10238 struct got_object_id_queue commits;
10239 struct got_pathlist_head merged_paths;
10240 const struct got_object_id_queue *parent_ids;
10241 struct got_object_qid *qid, *pid;
10242 struct got_update_progress_arg upa;
10243 int *pack_fds = NULL;
10245 STAILQ_INIT(&commits);
10246 TAILQ_INIT(&merged_paths);
10247 memset(&upa, 0, sizeof(upa));
10249 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10250 switch (ch) {
10251 case 'a':
10252 abort_rebase = 1;
10253 break;
10254 case 'c':
10255 continue_rebase = 1;
10256 break;
10257 case 'l':
10258 list_backups = 1;
10259 break;
10260 case 'X':
10261 delete_backups = 1;
10262 break;
10263 default:
10264 usage_rebase();
10265 /* NOTREACHED */
10269 argc -= optind;
10270 argv += optind;
10272 #ifndef PROFILE
10273 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10274 "unveil", NULL) == -1)
10275 err(1, "pledge");
10276 #endif
10277 if (list_backups) {
10278 if (abort_rebase)
10279 option_conflict('l', 'a');
10280 if (continue_rebase)
10281 option_conflict('l', 'c');
10282 if (delete_backups)
10283 option_conflict('l', 'X');
10284 if (argc != 0 && argc != 1)
10285 usage_rebase();
10286 } else if (delete_backups) {
10287 if (abort_rebase)
10288 option_conflict('X', 'a');
10289 if (continue_rebase)
10290 option_conflict('X', 'c');
10291 if (list_backups)
10292 option_conflict('l', 'X');
10293 if (argc != 0 && argc != 1)
10294 usage_rebase();
10295 } else {
10296 if (abort_rebase && continue_rebase)
10297 usage_rebase();
10298 else if (abort_rebase || continue_rebase) {
10299 if (argc != 0)
10300 usage_rebase();
10301 } else if (argc != 1)
10302 usage_rebase();
10305 cwd = getcwd(NULL, 0);
10306 if (cwd == NULL) {
10307 error = got_error_from_errno("getcwd");
10308 goto done;
10311 error = got_repo_pack_fds_open(&pack_fds);
10312 if (error != NULL)
10313 goto done;
10315 error = got_worktree_open(&worktree, cwd);
10316 if (error) {
10317 if (list_backups || delete_backups) {
10318 if (error->code != GOT_ERR_NOT_WORKTREE)
10319 goto done;
10320 } else {
10321 if (error->code == GOT_ERR_NOT_WORKTREE)
10322 error = wrap_not_worktree_error(error,
10323 "rebase", cwd);
10324 goto done;
10328 error = get_gitconfig_path(&gitconfig_path);
10329 if (error)
10330 goto done;
10331 error = got_repo_open(&repo,
10332 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10333 gitconfig_path, pack_fds);
10334 if (error != NULL)
10335 goto done;
10337 error = get_author(&committer, repo, worktree);
10338 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10339 goto done;
10341 error = apply_unveil(got_repo_get_path(repo), 0,
10342 worktree ? got_worktree_get_root_path(worktree) : NULL);
10343 if (error)
10344 goto done;
10346 if (list_backups || delete_backups) {
10347 error = process_backup_refs(
10348 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10349 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10350 goto done; /* nothing else to do */
10353 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10354 worktree);
10355 if (error)
10356 goto done;
10357 if (histedit_in_progress) {
10358 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10359 goto done;
10362 error = got_worktree_merge_in_progress(&merge_in_progress,
10363 worktree, repo);
10364 if (error)
10365 goto done;
10366 if (merge_in_progress) {
10367 error = got_error(GOT_ERR_MERGE_BUSY);
10368 goto done;
10371 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10372 if (error)
10373 goto done;
10375 if (abort_rebase) {
10376 if (!rebase_in_progress) {
10377 error = got_error(GOT_ERR_NOT_REBASING);
10378 goto done;
10380 error = got_worktree_rebase_continue(&resume_commit_id,
10381 &new_base_branch, &tmp_branch, &branch, &fileindex,
10382 worktree, repo);
10383 if (error)
10384 goto done;
10385 printf("Switching work tree to %s\n",
10386 got_ref_get_symref_target(new_base_branch));
10387 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10388 new_base_branch, abort_progress, &upa);
10389 if (error)
10390 goto done;
10391 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10392 print_merge_progress_stats(&upa);
10393 goto done; /* nothing else to do */
10396 if (continue_rebase) {
10397 if (!rebase_in_progress) {
10398 error = got_error(GOT_ERR_NOT_REBASING);
10399 goto done;
10401 error = got_worktree_rebase_continue(&resume_commit_id,
10402 &new_base_branch, &tmp_branch, &branch, &fileindex,
10403 worktree, repo);
10404 if (error)
10405 goto done;
10407 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10408 committer, resume_commit_id, repo);
10409 if (error)
10410 goto done;
10412 yca_id = got_object_id_dup(resume_commit_id);
10413 if (yca_id == NULL) {
10414 error = got_error_from_errno("got_object_id_dup");
10415 goto done;
10417 } else {
10418 error = got_ref_open(&branch, repo, argv[0], 0);
10419 if (error != NULL)
10420 goto done;
10421 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10422 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10423 "will not rebase a branch which lives outside "
10424 "the \"refs/heads/\" reference namespace");
10425 goto done;
10429 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10430 if (error)
10431 goto done;
10433 if (!continue_rebase) {
10434 struct got_object_id *base_commit_id;
10436 error = got_ref_open(&head_ref, repo,
10437 got_worktree_get_head_ref_name(worktree), 0);
10438 if (error)
10439 goto done;
10440 error = got_ref_resolve(&head_commit_id, repo, head_ref);
10441 if (error)
10442 goto done;
10443 base_commit_id = got_worktree_get_base_commit_id(worktree);
10444 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
10445 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
10446 goto done;
10449 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10450 base_commit_id, branch_head_commit_id, 1, repo,
10451 check_cancelled, NULL);
10452 if (error)
10453 goto done;
10454 if (yca_id == NULL) {
10455 error = got_error_msg(GOT_ERR_ANCESTRY,
10456 "specified branch shares no common ancestry "
10457 "with work tree's branch");
10458 goto done;
10461 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10462 if (error) {
10463 if (error->code != GOT_ERR_ANCESTRY)
10464 goto done;
10465 error = NULL;
10466 } else {
10467 struct got_pathlist_head paths;
10468 printf("%s is already based on %s\n",
10469 got_ref_get_name(branch),
10470 got_worktree_get_head_ref_name(worktree));
10471 error = switch_head_ref(branch, branch_head_commit_id,
10472 worktree, repo);
10473 if (error)
10474 goto done;
10475 error = got_worktree_set_base_commit_id(worktree, repo,
10476 branch_head_commit_id);
10477 if (error)
10478 goto done;
10479 TAILQ_INIT(&paths);
10480 error = got_pathlist_append(&paths, "", NULL);
10481 if (error)
10482 goto done;
10483 error = got_worktree_checkout_files(worktree,
10484 &paths, repo, update_progress, &upa,
10485 check_cancelled, NULL);
10486 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
10487 if (error)
10488 goto done;
10489 if (upa.did_something) {
10490 char *id_str;
10491 error = got_object_id_str(&id_str,
10492 branch_head_commit_id);
10493 if (error)
10494 goto done;
10495 printf("Updated to %s: %s\n",
10496 got_worktree_get_head_ref_name(worktree),
10497 id_str);
10498 free(id_str);
10499 } else
10500 printf("Already up-to-date\n");
10501 print_update_progress_stats(&upa);
10502 goto done;
10506 commit_id = branch_head_commit_id;
10507 error = got_object_open_as_commit(&commit, repo, commit_id);
10508 if (error)
10509 goto done;
10511 parent_ids = got_object_commit_get_parent_ids(commit);
10512 pid = STAILQ_FIRST(parent_ids);
10513 if (pid == NULL) {
10514 error = got_error(GOT_ERR_EMPTY_REBASE);
10515 goto done;
10517 error = collect_commits(&commits, commit_id, &pid->id,
10518 yca_id, got_worktree_get_path_prefix(worktree),
10519 GOT_ERR_REBASE_PATH, repo);
10520 got_object_commit_close(commit);
10521 commit = NULL;
10522 if (error)
10523 goto done;
10525 if (!continue_rebase) {
10526 error = got_worktree_rebase_prepare(&new_base_branch,
10527 &tmp_branch, &fileindex, worktree, branch, repo);
10528 if (error)
10529 goto done;
10532 if (STAILQ_EMPTY(&commits)) {
10533 if (continue_rebase) {
10534 error = rebase_complete(worktree, fileindex,
10535 branch, new_base_branch, tmp_branch, repo,
10536 create_backup);
10537 goto done;
10538 } else {
10539 /* Fast-forward the reference of the branch. */
10540 struct got_object_id *new_head_commit_id;
10541 char *id_str;
10542 error = got_ref_resolve(&new_head_commit_id, repo,
10543 new_base_branch);
10544 if (error)
10545 goto done;
10546 error = got_object_id_str(&id_str, new_head_commit_id);
10547 if (error)
10548 goto done;
10549 printf("Forwarding %s to commit %s\n",
10550 got_ref_get_name(branch), id_str);
10551 free(id_str);
10552 error = got_ref_change_ref(branch,
10553 new_head_commit_id);
10554 if (error)
10555 goto done;
10556 /* No backup needed since objects did not change. */
10557 create_backup = 0;
10561 pid = NULL;
10562 STAILQ_FOREACH(qid, &commits, entry) {
10564 commit_id = &qid->id;
10565 parent_id = pid ? &pid->id : yca_id;
10566 pid = qid;
10568 memset(&upa, 0, sizeof(upa));
10569 error = got_worktree_rebase_merge_files(&merged_paths,
10570 worktree, fileindex, parent_id, commit_id, repo,
10571 update_progress, &upa, check_cancelled, NULL);
10572 if (error)
10573 goto done;
10575 print_merge_progress_stats(&upa);
10576 if (upa.conflicts > 0 || upa.missing > 0 ||
10577 upa.not_deleted > 0 || upa.unversioned > 0) {
10578 if (upa.conflicts > 0) {
10579 error = show_rebase_merge_conflict(&qid->id,
10580 repo);
10581 if (error)
10582 goto done;
10584 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10585 break;
10588 error = rebase_commit(&merged_paths, worktree, fileindex,
10589 tmp_branch, committer, commit_id, repo);
10590 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10591 if (error)
10592 goto done;
10595 if (upa.conflicts > 0 || upa.missing > 0 ||
10596 upa.not_deleted > 0 || upa.unversioned > 0) {
10597 error = got_worktree_rebase_postpone(worktree, fileindex);
10598 if (error)
10599 goto done;
10600 if (upa.conflicts > 0 && upa.missing == 0 &&
10601 upa.not_deleted == 0 && upa.unversioned == 0) {
10602 error = got_error_msg(GOT_ERR_CONFLICTS,
10603 "conflicts must be resolved before rebasing "
10604 "can continue");
10605 } else if (upa.conflicts > 0) {
10606 error = got_error_msg(GOT_ERR_CONFLICTS,
10607 "conflicts must be resolved before rebasing "
10608 "can continue; changes destined for some "
10609 "files were not yet merged and should be "
10610 "merged manually if required before the "
10611 "rebase operation is continued");
10612 } else {
10613 error = got_error_msg(GOT_ERR_CONFLICTS,
10614 "changes destined for some files were not "
10615 "yet merged and should be merged manually "
10616 "if required before the rebase operation "
10617 "is continued");
10619 } else
10620 error = rebase_complete(worktree, fileindex, branch,
10621 new_base_branch, tmp_branch, repo, create_backup);
10622 done:
10623 free(cwd);
10624 free(committer);
10625 free(gitconfig_path);
10626 got_object_id_queue_free(&commits);
10627 free(branch_head_commit_id);
10628 free(resume_commit_id);
10629 free(head_commit_id);
10630 free(yca_id);
10631 if (commit)
10632 got_object_commit_close(commit);
10633 if (branch)
10634 got_ref_close(branch);
10635 if (new_base_branch)
10636 got_ref_close(new_base_branch);
10637 if (tmp_branch)
10638 got_ref_close(tmp_branch);
10639 if (head_ref)
10640 got_ref_close(head_ref);
10641 if (worktree)
10642 got_worktree_close(worktree);
10643 if (repo) {
10644 const struct got_error *close_err = got_repo_close(repo);
10645 if (error == NULL)
10646 error = close_err;
10648 if (pack_fds) {
10649 const struct got_error *pack_err =
10650 got_repo_pack_fds_close(pack_fds);
10651 if (error == NULL)
10652 error = pack_err;
10654 return error;
10657 __dead static void
10658 usage_histedit(void)
10660 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10661 "[branch]\n", getprogname());
10662 exit(1);
10665 #define GOT_HISTEDIT_PICK 'p'
10666 #define GOT_HISTEDIT_EDIT 'e'
10667 #define GOT_HISTEDIT_FOLD 'f'
10668 #define GOT_HISTEDIT_DROP 'd'
10669 #define GOT_HISTEDIT_MESG 'm'
10671 static const struct got_histedit_cmd {
10672 unsigned char code;
10673 const char *name;
10674 const char *desc;
10675 } got_histedit_cmds[] = {
10676 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10677 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10678 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10679 "be used" },
10680 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10681 { GOT_HISTEDIT_MESG, "mesg",
10682 "single-line log message for commit above (open editor if empty)" },
10685 struct got_histedit_list_entry {
10686 TAILQ_ENTRY(got_histedit_list_entry) entry;
10687 struct got_object_id *commit_id;
10688 const struct got_histedit_cmd *cmd;
10689 char *logmsg;
10691 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10693 static const struct got_error *
10694 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10695 FILE *f, struct got_repository *repo)
10697 const struct got_error *err = NULL;
10698 char *logmsg = NULL, *id_str = NULL;
10699 struct got_commit_object *commit = NULL;
10700 int n;
10702 err = got_object_open_as_commit(&commit, repo, commit_id);
10703 if (err)
10704 goto done;
10706 err = get_short_logmsg(&logmsg, 34, commit);
10707 if (err)
10708 goto done;
10710 err = got_object_id_str(&id_str, commit_id);
10711 if (err)
10712 goto done;
10714 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10715 if (n < 0)
10716 err = got_ferror(f, GOT_ERR_IO);
10717 done:
10718 if (commit)
10719 got_object_commit_close(commit);
10720 free(id_str);
10721 free(logmsg);
10722 return err;
10725 static const struct got_error *
10726 histedit_write_commit_list(struct got_object_id_queue *commits,
10727 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10728 struct got_repository *repo)
10730 const struct got_error *err = NULL;
10731 struct got_object_qid *qid;
10732 const char *histedit_cmd = NULL;
10734 if (STAILQ_EMPTY(commits))
10735 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10737 STAILQ_FOREACH(qid, commits, entry) {
10738 histedit_cmd = got_histedit_cmds[0].name;
10739 if (edit_only)
10740 histedit_cmd = "edit";
10741 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10742 histedit_cmd = "fold";
10743 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10744 if (err)
10745 break;
10746 if (edit_logmsg_only) {
10747 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10748 if (n < 0) {
10749 err = got_ferror(f, GOT_ERR_IO);
10750 break;
10755 return err;
10758 static const struct got_error *
10759 write_cmd_list(FILE *f, const char *branch_name,
10760 struct got_object_id_queue *commits)
10762 const struct got_error *err = NULL;
10763 size_t i;
10764 int n;
10765 char *id_str;
10766 struct got_object_qid *qid;
10768 qid = STAILQ_FIRST(commits);
10769 err = got_object_id_str(&id_str, &qid->id);
10770 if (err)
10771 return err;
10773 n = fprintf(f,
10774 "# Editing the history of branch '%s' starting at\n"
10775 "# commit %s\n"
10776 "# Commits will be processed in order from top to "
10777 "bottom of this file.\n", branch_name, id_str);
10778 if (n < 0) {
10779 err = got_ferror(f, GOT_ERR_IO);
10780 goto done;
10783 n = fprintf(f, "# Available histedit commands:\n");
10784 if (n < 0) {
10785 err = got_ferror(f, GOT_ERR_IO);
10786 goto done;
10789 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10790 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10791 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10792 cmd->desc);
10793 if (n < 0) {
10794 err = got_ferror(f, GOT_ERR_IO);
10795 break;
10798 done:
10799 free(id_str);
10800 return err;
10803 static const struct got_error *
10804 histedit_syntax_error(int lineno)
10806 static char msg[42];
10807 int ret;
10809 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10810 lineno);
10811 if (ret < 0 || (size_t)ret >= sizeof(msg))
10812 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10814 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10817 static const struct got_error *
10818 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10819 char *logmsg, struct got_repository *repo)
10821 const struct got_error *err;
10822 struct got_commit_object *folded_commit = NULL;
10823 char *id_str, *folded_logmsg = NULL;
10825 err = got_object_id_str(&id_str, hle->commit_id);
10826 if (err)
10827 return err;
10829 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10830 if (err)
10831 goto done;
10833 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10834 if (err)
10835 goto done;
10836 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10837 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10838 folded_logmsg) == -1) {
10839 err = got_error_from_errno("asprintf");
10841 done:
10842 if (folded_commit)
10843 got_object_commit_close(folded_commit);
10844 free(id_str);
10845 free(folded_logmsg);
10846 return err;
10849 static struct got_histedit_list_entry *
10850 get_folded_commits(struct got_histedit_list_entry *hle)
10852 struct got_histedit_list_entry *prev, *folded = NULL;
10854 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10855 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10856 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10857 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10858 folded = prev;
10859 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10862 return folded;
10865 static const struct got_error *
10866 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10867 struct got_repository *repo)
10869 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10870 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10871 const struct got_error *err = NULL;
10872 struct got_commit_object *commit = NULL;
10873 int logmsg_len;
10874 int fd;
10875 struct got_histedit_list_entry *folded = NULL;
10877 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10878 if (err)
10879 return err;
10881 folded = get_folded_commits(hle);
10882 if (folded) {
10883 while (folded != hle) {
10884 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10885 folded = TAILQ_NEXT(folded, entry);
10886 continue;
10888 err = append_folded_commit_msg(&new_msg, folded,
10889 logmsg, repo);
10890 if (err)
10891 goto done;
10892 free(logmsg);
10893 logmsg = new_msg;
10894 folded = TAILQ_NEXT(folded, entry);
10898 err = got_object_id_str(&id_str, hle->commit_id);
10899 if (err)
10900 goto done;
10901 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10902 if (err)
10903 goto done;
10904 logmsg_len = asprintf(&new_msg,
10905 "%s\n# original log message of commit %s: %s",
10906 logmsg ? logmsg : "", id_str, orig_logmsg);
10907 if (logmsg_len == -1) {
10908 err = got_error_from_errno("asprintf");
10909 goto done;
10911 free(logmsg);
10912 logmsg = new_msg;
10914 err = got_object_id_str(&id_str, hle->commit_id);
10915 if (err)
10916 goto done;
10918 err = got_opentemp_named_fd(&logmsg_path, &fd,
10919 GOT_TMPDIR_STR "/got-logmsg", "");
10920 if (err)
10921 goto done;
10923 write(fd, logmsg, logmsg_len);
10924 close(fd);
10926 err = get_editor(&editor);
10927 if (err)
10928 goto done;
10930 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10931 logmsg_len, 0);
10932 if (err) {
10933 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10934 goto done;
10935 err = NULL;
10936 hle->logmsg = strdup(new_msg);
10937 if (hle->logmsg == NULL)
10938 err = got_error_from_errno("strdup");
10940 done:
10941 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10942 err = got_error_from_errno2("unlink", logmsg_path);
10943 free(logmsg_path);
10944 free(logmsg);
10945 free(orig_logmsg);
10946 free(editor);
10947 if (commit)
10948 got_object_commit_close(commit);
10949 return err;
10952 static const struct got_error *
10953 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10954 FILE *f, struct got_repository *repo)
10956 const struct got_error *err = NULL;
10957 char *line = NULL, *p, *end;
10958 size_t i, size;
10959 ssize_t len;
10960 int lineno = 0, lastcmd = -1;
10961 const struct got_histedit_cmd *cmd;
10962 struct got_object_id *commit_id = NULL;
10963 struct got_histedit_list_entry *hle = NULL;
10965 for (;;) {
10966 len = getline(&line, &size, f);
10967 if (len == -1) {
10968 const struct got_error *getline_err;
10969 if (feof(f))
10970 break;
10971 getline_err = got_error_from_errno("getline");
10972 err = got_ferror(f, getline_err->code);
10973 break;
10975 lineno++;
10976 p = line;
10977 while (isspace((unsigned char)p[0]))
10978 p++;
10979 if (p[0] == '#' || p[0] == '\0') {
10980 free(line);
10981 line = NULL;
10982 continue;
10984 cmd = NULL;
10985 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10986 cmd = &got_histedit_cmds[i];
10987 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10988 isspace((unsigned char)p[strlen(cmd->name)])) {
10989 p += strlen(cmd->name);
10990 break;
10992 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10993 p++;
10994 break;
10997 if (i == nitems(got_histedit_cmds)) {
10998 err = histedit_syntax_error(lineno);
10999 break;
11001 while (isspace((unsigned char)p[0]))
11002 p++;
11003 if (cmd->code == GOT_HISTEDIT_MESG) {
11004 if (lastcmd != GOT_HISTEDIT_PICK &&
11005 lastcmd != GOT_HISTEDIT_EDIT) {
11006 err = got_error(GOT_ERR_HISTEDIT_CMD);
11007 break;
11009 if (p[0] == '\0') {
11010 err = histedit_edit_logmsg(hle, repo);
11011 if (err)
11012 break;
11013 } else {
11014 hle->logmsg = strdup(p);
11015 if (hle->logmsg == NULL) {
11016 err = got_error_from_errno("strdup");
11017 break;
11020 free(line);
11021 line = NULL;
11022 lastcmd = cmd->code;
11023 continue;
11024 } else {
11025 end = p;
11026 while (end[0] && !isspace((unsigned char)end[0]))
11027 end++;
11028 *end = '\0';
11030 err = got_object_resolve_id_str(&commit_id, repo, p);
11031 if (err) {
11032 /* override error code */
11033 err = histedit_syntax_error(lineno);
11034 break;
11037 hle = malloc(sizeof(*hle));
11038 if (hle == NULL) {
11039 err = got_error_from_errno("malloc");
11040 break;
11042 hle->cmd = cmd;
11043 hle->commit_id = commit_id;
11044 hle->logmsg = NULL;
11045 commit_id = NULL;
11046 free(line);
11047 line = NULL;
11048 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11049 lastcmd = cmd->code;
11052 free(line);
11053 free(commit_id);
11054 return err;
11057 static const struct got_error *
11058 histedit_check_script(struct got_histedit_list *histedit_cmds,
11059 struct got_object_id_queue *commits, struct got_repository *repo)
11061 const struct got_error *err = NULL;
11062 struct got_object_qid *qid;
11063 struct got_histedit_list_entry *hle;
11064 static char msg[92];
11065 char *id_str;
11067 if (TAILQ_EMPTY(histedit_cmds))
11068 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11069 "histedit script contains no commands");
11070 if (STAILQ_EMPTY(commits))
11071 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11073 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11074 struct got_histedit_list_entry *hle2;
11075 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11076 if (hle == hle2)
11077 continue;
11078 if (got_object_id_cmp(hle->commit_id,
11079 hle2->commit_id) != 0)
11080 continue;
11081 err = got_object_id_str(&id_str, hle->commit_id);
11082 if (err)
11083 return err;
11084 snprintf(msg, sizeof(msg), "commit %s is listed "
11085 "more than once in histedit script", id_str);
11086 free(id_str);
11087 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11091 STAILQ_FOREACH(qid, commits, entry) {
11092 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11093 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11094 break;
11096 if (hle == NULL) {
11097 err = got_object_id_str(&id_str, &qid->id);
11098 if (err)
11099 return err;
11100 snprintf(msg, sizeof(msg),
11101 "commit %s missing from histedit script", id_str);
11102 free(id_str);
11103 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11107 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11108 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11109 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11110 "last commit in histedit script cannot be folded");
11112 return NULL;
11115 static const struct got_error *
11116 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11117 const char *path, struct got_object_id_queue *commits,
11118 struct got_repository *repo)
11120 const struct got_error *err = NULL;
11121 char *editor;
11122 FILE *f = NULL;
11124 err = get_editor(&editor);
11125 if (err)
11126 return err;
11128 if (spawn_editor(editor, path) == -1) {
11129 err = got_error_from_errno("failed spawning editor");
11130 goto done;
11133 f = fopen(path, "re");
11134 if (f == NULL) {
11135 err = got_error_from_errno("fopen");
11136 goto done;
11138 err = histedit_parse_list(histedit_cmds, f, repo);
11139 if (err)
11140 goto done;
11142 err = histedit_check_script(histedit_cmds, commits, repo);
11143 done:
11144 if (f && fclose(f) == EOF && err == NULL)
11145 err = got_error_from_errno("fclose");
11146 free(editor);
11147 return err;
11150 static const struct got_error *
11151 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11152 struct got_object_id_queue *, const char *, const char *,
11153 struct got_repository *);
11155 static const struct got_error *
11156 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11157 struct got_object_id_queue *commits, const char *branch_name,
11158 int edit_logmsg_only, int fold_only, int edit_only,
11159 struct got_repository *repo)
11161 const struct got_error *err;
11162 FILE *f = NULL;
11163 char *path = NULL;
11165 err = got_opentemp_named(&path, &f, "got-histedit", "");
11166 if (err)
11167 return err;
11169 err = write_cmd_list(f, branch_name, commits);
11170 if (err)
11171 goto done;
11173 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11174 fold_only, edit_only, repo);
11175 if (err)
11176 goto done;
11178 if (edit_logmsg_only || fold_only || edit_only) {
11179 rewind(f);
11180 err = histedit_parse_list(histedit_cmds, f, repo);
11181 } else {
11182 if (fclose(f) == EOF) {
11183 err = got_error_from_errno("fclose");
11184 goto done;
11186 f = NULL;
11187 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11188 if (err) {
11189 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11190 err->code != GOT_ERR_HISTEDIT_CMD)
11191 goto done;
11192 err = histedit_edit_list_retry(histedit_cmds, err,
11193 commits, path, branch_name, repo);
11196 done:
11197 if (f && fclose(f) == EOF && err == NULL)
11198 err = got_error_from_errno("fclose");
11199 if (path && unlink(path) != 0 && err == NULL)
11200 err = got_error_from_errno2("unlink", path);
11201 free(path);
11202 return err;
11205 static const struct got_error *
11206 histedit_save_list(struct got_histedit_list *histedit_cmds,
11207 struct got_worktree *worktree, struct got_repository *repo)
11209 const struct got_error *err = NULL;
11210 char *path = NULL;
11211 FILE *f = NULL;
11212 struct got_histedit_list_entry *hle;
11213 struct got_commit_object *commit = NULL;
11215 err = got_worktree_get_histedit_script_path(&path, worktree);
11216 if (err)
11217 return err;
11219 f = fopen(path, "we");
11220 if (f == NULL) {
11221 err = got_error_from_errno2("fopen", path);
11222 goto done;
11224 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11225 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11226 repo);
11227 if (err)
11228 break;
11230 if (hle->logmsg) {
11231 int n = fprintf(f, "%c %s\n",
11232 GOT_HISTEDIT_MESG, hle->logmsg);
11233 if (n < 0) {
11234 err = got_ferror(f, GOT_ERR_IO);
11235 break;
11239 done:
11240 if (f && fclose(f) == EOF && err == NULL)
11241 err = got_error_from_errno("fclose");
11242 free(path);
11243 if (commit)
11244 got_object_commit_close(commit);
11245 return err;
11248 static void
11249 histedit_free_list(struct got_histedit_list *histedit_cmds)
11251 struct got_histedit_list_entry *hle;
11253 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11254 TAILQ_REMOVE(histedit_cmds, hle, entry);
11255 free(hle);
11259 static const struct got_error *
11260 histedit_load_list(struct got_histedit_list *histedit_cmds,
11261 const char *path, struct got_repository *repo)
11263 const struct got_error *err = NULL;
11264 FILE *f = NULL;
11266 f = fopen(path, "re");
11267 if (f == NULL) {
11268 err = got_error_from_errno2("fopen", path);
11269 goto done;
11272 err = histedit_parse_list(histedit_cmds, f, repo);
11273 done:
11274 if (f && fclose(f) == EOF && err == NULL)
11275 err = got_error_from_errno("fclose");
11276 return err;
11279 static const struct got_error *
11280 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11281 const struct got_error *edit_err, struct got_object_id_queue *commits,
11282 const char *path, const char *branch_name, struct got_repository *repo)
11284 const struct got_error *err = NULL, *prev_err = edit_err;
11285 int resp = ' ';
11287 while (resp != 'c' && resp != 'r' && resp != 'a') {
11288 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11289 "or (a)bort: ", getprogname(), prev_err->msg);
11290 resp = getchar();
11291 if (resp == '\n')
11292 resp = getchar();
11293 if (resp == 'c') {
11294 histedit_free_list(histedit_cmds);
11295 err = histedit_run_editor(histedit_cmds, path, commits,
11296 repo);
11297 if (err) {
11298 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11299 err->code != GOT_ERR_HISTEDIT_CMD)
11300 break;
11301 prev_err = err;
11302 resp = ' ';
11303 continue;
11305 break;
11306 } else if (resp == 'r') {
11307 histedit_free_list(histedit_cmds);
11308 err = histedit_edit_script(histedit_cmds,
11309 commits, branch_name, 0, 0, 0, repo);
11310 if (err) {
11311 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11312 err->code != GOT_ERR_HISTEDIT_CMD)
11313 break;
11314 prev_err = err;
11315 resp = ' ';
11316 continue;
11318 break;
11319 } else if (resp == 'a') {
11320 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11321 break;
11322 } else
11323 printf("invalid response '%c'\n", resp);
11326 return err;
11329 static const struct got_error *
11330 histedit_complete(struct got_worktree *worktree,
11331 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11332 struct got_reference *branch, struct got_repository *repo)
11334 printf("Switching work tree to %s\n",
11335 got_ref_get_symref_target(branch));
11336 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11337 branch, repo);
11340 static const struct got_error *
11341 show_histedit_progress(struct got_commit_object *commit,
11342 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11344 const struct got_error *err;
11345 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11347 err = got_object_id_str(&old_id_str, hle->commit_id);
11348 if (err)
11349 goto done;
11351 if (new_id) {
11352 err = got_object_id_str(&new_id_str, new_id);
11353 if (err)
11354 goto done;
11357 old_id_str[12] = '\0';
11358 if (new_id_str)
11359 new_id_str[12] = '\0';
11361 if (hle->logmsg) {
11362 logmsg = strdup(hle->logmsg);
11363 if (logmsg == NULL) {
11364 err = got_error_from_errno("strdup");
11365 goto done;
11367 trim_logmsg(logmsg, 42);
11368 } else {
11369 err = get_short_logmsg(&logmsg, 42, commit);
11370 if (err)
11371 goto done;
11374 switch (hle->cmd->code) {
11375 case GOT_HISTEDIT_PICK:
11376 case GOT_HISTEDIT_EDIT:
11377 printf("%s -> %s: %s\n", old_id_str,
11378 new_id_str ? new_id_str : "no-op change", logmsg);
11379 break;
11380 case GOT_HISTEDIT_DROP:
11381 case GOT_HISTEDIT_FOLD:
11382 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11383 logmsg);
11384 break;
11385 default:
11386 break;
11388 done:
11389 free(old_id_str);
11390 free(new_id_str);
11391 return err;
11394 static const struct got_error *
11395 histedit_commit(struct got_pathlist_head *merged_paths,
11396 struct got_worktree *worktree, struct got_fileindex *fileindex,
11397 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11398 const char *committer, struct got_repository *repo)
11400 const struct got_error *err;
11401 struct got_commit_object *commit;
11402 struct got_object_id *new_commit_id;
11404 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11405 && hle->logmsg == NULL) {
11406 err = histedit_edit_logmsg(hle, repo);
11407 if (err)
11408 return err;
11411 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11412 if (err)
11413 return err;
11415 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11416 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11417 hle->logmsg, repo);
11418 if (err) {
11419 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11420 goto done;
11421 err = show_histedit_progress(commit, hle, NULL);
11422 } else {
11423 err = show_histedit_progress(commit, hle, new_commit_id);
11424 free(new_commit_id);
11426 done:
11427 got_object_commit_close(commit);
11428 return err;
11431 static const struct got_error *
11432 histedit_skip_commit(struct got_histedit_list_entry *hle,
11433 struct got_worktree *worktree, struct got_repository *repo)
11435 const struct got_error *error;
11436 struct got_commit_object *commit;
11438 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11439 repo);
11440 if (error)
11441 return error;
11443 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11444 if (error)
11445 return error;
11447 error = show_histedit_progress(commit, hle, NULL);
11448 got_object_commit_close(commit);
11449 return error;
11452 static const struct got_error *
11453 check_local_changes(void *arg, unsigned char status,
11454 unsigned char staged_status, const char *path,
11455 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11456 struct got_object_id *commit_id, int dirfd, const char *de_name)
11458 int *have_local_changes = arg;
11460 switch (status) {
11461 case GOT_STATUS_ADD:
11462 case GOT_STATUS_DELETE:
11463 case GOT_STATUS_MODIFY:
11464 case GOT_STATUS_CONFLICT:
11465 *have_local_changes = 1;
11466 return got_error(GOT_ERR_CANCELLED);
11467 default:
11468 break;
11471 switch (staged_status) {
11472 case GOT_STATUS_ADD:
11473 case GOT_STATUS_DELETE:
11474 case GOT_STATUS_MODIFY:
11475 *have_local_changes = 1;
11476 return got_error(GOT_ERR_CANCELLED);
11477 default:
11478 break;
11481 return NULL;
11484 static const struct got_error *
11485 cmd_histedit(int argc, char *argv[])
11487 const struct got_error *error = NULL;
11488 struct got_worktree *worktree = NULL;
11489 struct got_fileindex *fileindex = NULL;
11490 struct got_repository *repo = NULL;
11491 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11492 struct got_reference *branch = NULL;
11493 struct got_reference *tmp_branch = NULL;
11494 struct got_object_id *resume_commit_id = NULL;
11495 struct got_object_id *base_commit_id = NULL;
11496 struct got_object_id *head_commit_id = NULL;
11497 struct got_commit_object *commit = NULL;
11498 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11499 struct got_update_progress_arg upa;
11500 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11501 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11502 int list_backups = 0, delete_backups = 0;
11503 const char *edit_script_path = NULL;
11504 struct got_object_id_queue commits;
11505 struct got_pathlist_head merged_paths;
11506 const struct got_object_id_queue *parent_ids;
11507 struct got_object_qid *pid;
11508 struct got_histedit_list histedit_cmds;
11509 struct got_histedit_list_entry *hle;
11510 int *pack_fds = NULL;
11512 STAILQ_INIT(&commits);
11513 TAILQ_INIT(&histedit_cmds);
11514 TAILQ_INIT(&merged_paths);
11515 memset(&upa, 0, sizeof(upa));
11517 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11518 switch (ch) {
11519 case 'a':
11520 abort_edit = 1;
11521 break;
11522 case 'c':
11523 continue_edit = 1;
11524 break;
11525 case 'e':
11526 edit_only = 1;
11527 break;
11528 case 'F':
11529 edit_script_path = optarg;
11530 break;
11531 case 'f':
11532 fold_only = 1;
11533 break;
11534 case 'l':
11535 list_backups = 1;
11536 break;
11537 case 'm':
11538 edit_logmsg_only = 1;
11539 break;
11540 case 'X':
11541 delete_backups = 1;
11542 break;
11543 default:
11544 usage_histedit();
11545 /* NOTREACHED */
11549 argc -= optind;
11550 argv += optind;
11552 #ifndef PROFILE
11553 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11554 "unveil", NULL) == -1)
11555 err(1, "pledge");
11556 #endif
11557 if (abort_edit && continue_edit)
11558 option_conflict('a', 'c');
11559 if (edit_script_path && edit_logmsg_only)
11560 option_conflict('F', 'm');
11561 if (abort_edit && edit_logmsg_only)
11562 option_conflict('a', 'm');
11563 if (continue_edit && edit_logmsg_only)
11564 option_conflict('c', 'm');
11565 if (abort_edit && fold_only)
11566 option_conflict('a', 'f');
11567 if (continue_edit && fold_only)
11568 option_conflict('c', 'f');
11569 if (fold_only && edit_logmsg_only)
11570 option_conflict('f', 'm');
11571 if (edit_script_path && fold_only)
11572 option_conflict('F', 'f');
11573 if (abort_edit && edit_only)
11574 option_conflict('a', 'e');
11575 if (continue_edit && edit_only)
11576 option_conflict('c', 'e');
11577 if (edit_only && edit_logmsg_only)
11578 option_conflict('e', 'm');
11579 if (edit_script_path && edit_only)
11580 option_conflict('F', 'e');
11581 if (list_backups) {
11582 if (abort_edit)
11583 option_conflict('l', 'a');
11584 if (continue_edit)
11585 option_conflict('l', 'c');
11586 if (edit_script_path)
11587 option_conflict('l', 'F');
11588 if (edit_logmsg_only)
11589 option_conflict('l', 'm');
11590 if (fold_only)
11591 option_conflict('l', 'f');
11592 if (edit_only)
11593 option_conflict('l', 'e');
11594 if (delete_backups)
11595 option_conflict('l', 'X');
11596 if (argc != 0 && argc != 1)
11597 usage_histedit();
11598 } else if (delete_backups) {
11599 if (abort_edit)
11600 option_conflict('X', 'a');
11601 if (continue_edit)
11602 option_conflict('X', 'c');
11603 if (edit_script_path)
11604 option_conflict('X', 'F');
11605 if (edit_logmsg_only)
11606 option_conflict('X', 'm');
11607 if (fold_only)
11608 option_conflict('X', 'f');
11609 if (edit_only)
11610 option_conflict('X', 'e');
11611 if (list_backups)
11612 option_conflict('X', 'l');
11613 if (argc != 0 && argc != 1)
11614 usage_histedit();
11615 } else if (argc != 0)
11616 usage_histedit();
11619 * This command cannot apply unveil(2) in all cases because the
11620 * user may choose to run an editor to edit the histedit script
11621 * and to edit individual commit log messages.
11622 * unveil(2) traverses exec(2); if an editor is used we have to
11623 * apply unveil after edit script and log messages have been written.
11624 * XXX TODO: Make use of unveil(2) where possible.
11627 cwd = getcwd(NULL, 0);
11628 if (cwd == NULL) {
11629 error = got_error_from_errno("getcwd");
11630 goto done;
11633 error = got_repo_pack_fds_open(&pack_fds);
11634 if (error != NULL)
11635 goto done;
11637 error = got_worktree_open(&worktree, cwd);
11638 if (error) {
11639 if (list_backups || delete_backups) {
11640 if (error->code != GOT_ERR_NOT_WORKTREE)
11641 goto done;
11642 } else {
11643 if (error->code == GOT_ERR_NOT_WORKTREE)
11644 error = wrap_not_worktree_error(error,
11645 "histedit", cwd);
11646 goto done;
11650 if (list_backups || delete_backups) {
11651 error = got_repo_open(&repo,
11652 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11653 NULL, pack_fds);
11654 if (error != NULL)
11655 goto done;
11656 error = apply_unveil(got_repo_get_path(repo), 0,
11657 worktree ? got_worktree_get_root_path(worktree) : NULL);
11658 if (error)
11659 goto done;
11660 error = process_backup_refs(
11661 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11662 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11663 goto done; /* nothing else to do */
11666 error = get_gitconfig_path(&gitconfig_path);
11667 if (error)
11668 goto done;
11669 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11670 gitconfig_path, pack_fds);
11671 if (error != NULL)
11672 goto done;
11674 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11675 if (error)
11676 goto done;
11677 if (rebase_in_progress) {
11678 error = got_error(GOT_ERR_REBASING);
11679 goto done;
11682 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11683 repo);
11684 if (error)
11685 goto done;
11686 if (merge_in_progress) {
11687 error = got_error(GOT_ERR_MERGE_BUSY);
11688 goto done;
11691 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11692 if (error)
11693 goto done;
11695 if (edit_in_progress && edit_logmsg_only) {
11696 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11697 "histedit operation is in progress in this "
11698 "work tree and must be continued or aborted "
11699 "before the -m option can be used");
11700 goto done;
11702 if (edit_in_progress && fold_only) {
11703 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11704 "histedit operation is in progress in this "
11705 "work tree and must be continued or aborted "
11706 "before the -f option can be used");
11707 goto done;
11709 if (edit_in_progress && edit_only) {
11710 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11711 "histedit operation is in progress in this "
11712 "work tree and must be continued or aborted "
11713 "before the -e option can be used");
11714 goto done;
11717 if (edit_in_progress && abort_edit) {
11718 error = got_worktree_histedit_continue(&resume_commit_id,
11719 &tmp_branch, &branch, &base_commit_id, &fileindex,
11720 worktree, repo);
11721 if (error)
11722 goto done;
11723 printf("Switching work tree to %s\n",
11724 got_ref_get_symref_target(branch));
11725 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11726 branch, base_commit_id, abort_progress, &upa);
11727 if (error)
11728 goto done;
11729 printf("Histedit of %s aborted\n",
11730 got_ref_get_symref_target(branch));
11731 print_merge_progress_stats(&upa);
11732 goto done; /* nothing else to do */
11733 } else if (abort_edit) {
11734 error = got_error(GOT_ERR_NOT_HISTEDIT);
11735 goto done;
11738 error = get_author(&committer, repo, worktree);
11739 if (error)
11740 goto done;
11742 if (continue_edit) {
11743 char *path;
11745 if (!edit_in_progress) {
11746 error = got_error(GOT_ERR_NOT_HISTEDIT);
11747 goto done;
11750 error = got_worktree_get_histedit_script_path(&path, worktree);
11751 if (error)
11752 goto done;
11754 error = histedit_load_list(&histedit_cmds, path, repo);
11755 free(path);
11756 if (error)
11757 goto done;
11759 error = got_worktree_histedit_continue(&resume_commit_id,
11760 &tmp_branch, &branch, &base_commit_id, &fileindex,
11761 worktree, repo);
11762 if (error)
11763 goto done;
11765 error = got_ref_resolve(&head_commit_id, repo, branch);
11766 if (error)
11767 goto done;
11769 error = got_object_open_as_commit(&commit, repo,
11770 head_commit_id);
11771 if (error)
11772 goto done;
11773 parent_ids = got_object_commit_get_parent_ids(commit);
11774 pid = STAILQ_FIRST(parent_ids);
11775 if (pid == NULL) {
11776 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11777 goto done;
11779 error = collect_commits(&commits, head_commit_id, &pid->id,
11780 base_commit_id, got_worktree_get_path_prefix(worktree),
11781 GOT_ERR_HISTEDIT_PATH, repo);
11782 got_object_commit_close(commit);
11783 commit = NULL;
11784 if (error)
11785 goto done;
11786 } else {
11787 if (edit_in_progress) {
11788 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11789 goto done;
11792 error = got_ref_open(&branch, repo,
11793 got_worktree_get_head_ref_name(worktree), 0);
11794 if (error != NULL)
11795 goto done;
11797 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11798 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11799 "will not edit commit history of a branch outside "
11800 "the \"refs/heads/\" reference namespace");
11801 goto done;
11804 error = got_ref_resolve(&head_commit_id, repo, branch);
11805 got_ref_close(branch);
11806 branch = NULL;
11807 if (error)
11808 goto done;
11810 error = got_object_open_as_commit(&commit, repo,
11811 head_commit_id);
11812 if (error)
11813 goto done;
11814 parent_ids = got_object_commit_get_parent_ids(commit);
11815 pid = STAILQ_FIRST(parent_ids);
11816 if (pid == NULL) {
11817 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11818 goto done;
11820 error = collect_commits(&commits, head_commit_id, &pid->id,
11821 got_worktree_get_base_commit_id(worktree),
11822 got_worktree_get_path_prefix(worktree),
11823 GOT_ERR_HISTEDIT_PATH, repo);
11824 got_object_commit_close(commit);
11825 commit = NULL;
11826 if (error)
11827 goto done;
11829 if (STAILQ_EMPTY(&commits)) {
11830 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11831 goto done;
11834 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11835 &base_commit_id, &fileindex, worktree, repo);
11836 if (error)
11837 goto done;
11839 if (edit_script_path) {
11840 error = histedit_load_list(&histedit_cmds,
11841 edit_script_path, repo);
11842 if (error) {
11843 got_worktree_histedit_abort(worktree, fileindex,
11844 repo, branch, base_commit_id,
11845 abort_progress, &upa);
11846 print_merge_progress_stats(&upa);
11847 goto done;
11849 } else {
11850 const char *branch_name;
11851 branch_name = got_ref_get_symref_target(branch);
11852 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11853 branch_name += 11;
11854 error = histedit_edit_script(&histedit_cmds, &commits,
11855 branch_name, edit_logmsg_only, fold_only,
11856 edit_only, repo);
11857 if (error) {
11858 got_worktree_histedit_abort(worktree, fileindex,
11859 repo, branch, base_commit_id,
11860 abort_progress, &upa);
11861 print_merge_progress_stats(&upa);
11862 goto done;
11867 error = histedit_save_list(&histedit_cmds, worktree,
11868 repo);
11869 if (error) {
11870 got_worktree_histedit_abort(worktree, fileindex,
11871 repo, branch, base_commit_id,
11872 abort_progress, &upa);
11873 print_merge_progress_stats(&upa);
11874 goto done;
11879 error = histedit_check_script(&histedit_cmds, &commits, repo);
11880 if (error)
11881 goto done;
11883 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11884 if (resume_commit_id) {
11885 if (got_object_id_cmp(hle->commit_id,
11886 resume_commit_id) != 0)
11887 continue;
11889 resume_commit_id = NULL;
11890 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11891 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11892 error = histedit_skip_commit(hle, worktree,
11893 repo);
11894 if (error)
11895 goto done;
11896 } else {
11897 struct got_pathlist_head paths;
11898 int have_changes = 0;
11900 TAILQ_INIT(&paths);
11901 error = got_pathlist_append(&paths, "", NULL);
11902 if (error)
11903 goto done;
11904 error = got_worktree_status(worktree, &paths,
11905 repo, 0, check_local_changes, &have_changes,
11906 check_cancelled, NULL);
11907 got_pathlist_free(&paths,
11908 GOT_PATHLIST_FREE_NONE);
11909 if (error) {
11910 if (error->code != GOT_ERR_CANCELLED)
11911 goto done;
11912 if (sigint_received || sigpipe_received)
11913 goto done;
11915 if (have_changes) {
11916 error = histedit_commit(NULL, worktree,
11917 fileindex, tmp_branch, hle,
11918 committer, repo);
11919 if (error)
11920 goto done;
11921 } else {
11922 error = got_object_open_as_commit(
11923 &commit, repo, hle->commit_id);
11924 if (error)
11925 goto done;
11926 error = show_histedit_progress(commit,
11927 hle, NULL);
11928 got_object_commit_close(commit);
11929 commit = NULL;
11930 if (error)
11931 goto done;
11934 continue;
11937 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11938 error = histedit_skip_commit(hle, worktree, repo);
11939 if (error)
11940 goto done;
11941 continue;
11944 error = got_object_open_as_commit(&commit, repo,
11945 hle->commit_id);
11946 if (error)
11947 goto done;
11948 parent_ids = got_object_commit_get_parent_ids(commit);
11949 pid = STAILQ_FIRST(parent_ids);
11951 error = got_worktree_histedit_merge_files(&merged_paths,
11952 worktree, fileindex, &pid->id, hle->commit_id, repo,
11953 update_progress, &upa, check_cancelled, NULL);
11954 if (error)
11955 goto done;
11956 got_object_commit_close(commit);
11957 commit = NULL;
11959 print_merge_progress_stats(&upa);
11960 if (upa.conflicts > 0 || upa.missing > 0 ||
11961 upa.not_deleted > 0 || upa.unversioned > 0) {
11962 if (upa.conflicts > 0) {
11963 error = show_rebase_merge_conflict(
11964 hle->commit_id, repo);
11965 if (error)
11966 goto done;
11968 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11969 break;
11972 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11973 char *id_str;
11974 error = got_object_id_str(&id_str, hle->commit_id);
11975 if (error)
11976 goto done;
11977 printf("Stopping histedit for amending commit %s\n",
11978 id_str);
11979 free(id_str);
11980 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11981 error = got_worktree_histedit_postpone(worktree,
11982 fileindex);
11983 goto done;
11986 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11987 error = histedit_skip_commit(hle, worktree, repo);
11988 if (error)
11989 goto done;
11990 continue;
11993 error = histedit_commit(&merged_paths, worktree, fileindex,
11994 tmp_branch, hle, committer, repo);
11995 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11996 if (error)
11997 goto done;
12000 if (upa.conflicts > 0 || upa.missing > 0 ||
12001 upa.not_deleted > 0 || upa.unversioned > 0) {
12002 error = got_worktree_histedit_postpone(worktree, fileindex);
12003 if (error)
12004 goto done;
12005 if (upa.conflicts > 0 && upa.missing == 0 &&
12006 upa.not_deleted == 0 && upa.unversioned == 0) {
12007 error = got_error_msg(GOT_ERR_CONFLICTS,
12008 "conflicts must be resolved before histedit "
12009 "can continue");
12010 } else if (upa.conflicts > 0) {
12011 error = got_error_msg(GOT_ERR_CONFLICTS,
12012 "conflicts must be resolved before histedit "
12013 "can continue; changes destined for some "
12014 "files were not yet merged and should be "
12015 "merged manually if required before the "
12016 "histedit operation is continued");
12017 } else {
12018 error = got_error_msg(GOT_ERR_CONFLICTS,
12019 "changes destined for some files were not "
12020 "yet merged and should be merged manually "
12021 "if required before the histedit operation "
12022 "is continued");
12024 } else
12025 error = histedit_complete(worktree, fileindex, tmp_branch,
12026 branch, repo);
12027 done:
12028 free(cwd);
12029 free(committer);
12030 free(gitconfig_path);
12031 got_object_id_queue_free(&commits);
12032 histedit_free_list(&histedit_cmds);
12033 free(head_commit_id);
12034 free(base_commit_id);
12035 free(resume_commit_id);
12036 if (commit)
12037 got_object_commit_close(commit);
12038 if (branch)
12039 got_ref_close(branch);
12040 if (tmp_branch)
12041 got_ref_close(tmp_branch);
12042 if (worktree)
12043 got_worktree_close(worktree);
12044 if (repo) {
12045 const struct got_error *close_err = got_repo_close(repo);
12046 if (error == NULL)
12047 error = close_err;
12049 if (pack_fds) {
12050 const struct got_error *pack_err =
12051 got_repo_pack_fds_close(pack_fds);
12052 if (error == NULL)
12053 error = pack_err;
12055 return error;
12058 __dead static void
12059 usage_integrate(void)
12061 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12062 exit(1);
12065 static const struct got_error *
12066 cmd_integrate(int argc, char *argv[])
12068 const struct got_error *error = NULL;
12069 struct got_repository *repo = NULL;
12070 struct got_worktree *worktree = NULL;
12071 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12072 const char *branch_arg = NULL;
12073 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12074 struct got_fileindex *fileindex = NULL;
12075 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12076 int ch;
12077 struct got_update_progress_arg upa;
12078 int *pack_fds = NULL;
12080 while ((ch = getopt(argc, argv, "")) != -1) {
12081 switch (ch) {
12082 default:
12083 usage_integrate();
12084 /* NOTREACHED */
12088 argc -= optind;
12089 argv += optind;
12091 if (argc != 1)
12092 usage_integrate();
12093 branch_arg = argv[0];
12094 #ifndef PROFILE
12095 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12096 "unveil", NULL) == -1)
12097 err(1, "pledge");
12098 #endif
12099 cwd = getcwd(NULL, 0);
12100 if (cwd == NULL) {
12101 error = got_error_from_errno("getcwd");
12102 goto done;
12105 error = got_repo_pack_fds_open(&pack_fds);
12106 if (error != NULL)
12107 goto done;
12109 error = got_worktree_open(&worktree, cwd);
12110 if (error) {
12111 if (error->code == GOT_ERR_NOT_WORKTREE)
12112 error = wrap_not_worktree_error(error, "integrate",
12113 cwd);
12114 goto done;
12117 error = check_rebase_or_histedit_in_progress(worktree);
12118 if (error)
12119 goto done;
12121 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12122 NULL, pack_fds);
12123 if (error != NULL)
12124 goto done;
12126 error = apply_unveil(got_repo_get_path(repo), 0,
12127 got_worktree_get_root_path(worktree));
12128 if (error)
12129 goto done;
12131 error = check_merge_in_progress(worktree, repo);
12132 if (error)
12133 goto done;
12135 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12136 error = got_error_from_errno("asprintf");
12137 goto done;
12140 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12141 &base_branch_ref, worktree, refname, repo);
12142 if (error)
12143 goto done;
12145 refname = strdup(got_ref_get_name(branch_ref));
12146 if (refname == NULL) {
12147 error = got_error_from_errno("strdup");
12148 got_worktree_integrate_abort(worktree, fileindex, repo,
12149 branch_ref, base_branch_ref);
12150 goto done;
12152 base_refname = strdup(got_ref_get_name(base_branch_ref));
12153 if (base_refname == NULL) {
12154 error = got_error_from_errno("strdup");
12155 got_worktree_integrate_abort(worktree, fileindex, repo,
12156 branch_ref, base_branch_ref);
12157 goto done;
12159 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12160 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12161 got_worktree_integrate_abort(worktree, fileindex, repo,
12162 branch_ref, base_branch_ref);
12163 goto done;
12166 error = got_ref_resolve(&commit_id, repo, branch_ref);
12167 if (error)
12168 goto done;
12170 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12171 if (error)
12172 goto done;
12174 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12175 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12176 "specified branch has already been integrated");
12177 got_worktree_integrate_abort(worktree, fileindex, repo,
12178 branch_ref, base_branch_ref);
12179 goto done;
12182 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12183 if (error) {
12184 if (error->code == GOT_ERR_ANCESTRY)
12185 error = got_error(GOT_ERR_REBASE_REQUIRED);
12186 got_worktree_integrate_abort(worktree, fileindex, repo,
12187 branch_ref, base_branch_ref);
12188 goto done;
12191 memset(&upa, 0, sizeof(upa));
12192 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12193 branch_ref, base_branch_ref, update_progress, &upa,
12194 check_cancelled, NULL);
12195 if (error)
12196 goto done;
12198 printf("Integrated %s into %s\n", refname, base_refname);
12199 print_update_progress_stats(&upa);
12200 done:
12201 if (repo) {
12202 const struct got_error *close_err = got_repo_close(repo);
12203 if (error == NULL)
12204 error = close_err;
12206 if (worktree)
12207 got_worktree_close(worktree);
12208 if (pack_fds) {
12209 const struct got_error *pack_err =
12210 got_repo_pack_fds_close(pack_fds);
12211 if (error == NULL)
12212 error = pack_err;
12214 free(cwd);
12215 free(base_commit_id);
12216 free(commit_id);
12217 free(refname);
12218 free(base_refname);
12219 return error;
12222 __dead static void
12223 usage_merge(void)
12225 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12226 exit(1);
12229 static const struct got_error *
12230 cmd_merge(int argc, char *argv[])
12232 const struct got_error *error = NULL;
12233 struct got_worktree *worktree = NULL;
12234 struct got_repository *repo = NULL;
12235 struct got_fileindex *fileindex = NULL;
12236 char *cwd = NULL, *id_str = NULL, *author = NULL;
12237 struct got_reference *branch = NULL, *wt_branch = NULL;
12238 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12239 struct got_object_id *wt_branch_tip = NULL;
12240 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12241 int interrupt_merge = 0;
12242 struct got_update_progress_arg upa;
12243 struct got_object_id *merge_commit_id = NULL;
12244 char *branch_name = NULL;
12245 int *pack_fds = NULL;
12247 memset(&upa, 0, sizeof(upa));
12249 while ((ch = getopt(argc, argv, "acn")) != -1) {
12250 switch (ch) {
12251 case 'a':
12252 abort_merge = 1;
12253 break;
12254 case 'c':
12255 continue_merge = 1;
12256 break;
12257 case 'n':
12258 interrupt_merge = 1;
12259 break;
12260 default:
12261 usage_rebase();
12262 /* NOTREACHED */
12266 argc -= optind;
12267 argv += optind;
12269 #ifndef PROFILE
12270 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12271 "unveil", NULL) == -1)
12272 err(1, "pledge");
12273 #endif
12275 if (abort_merge && continue_merge)
12276 option_conflict('a', 'c');
12277 if (abort_merge || continue_merge) {
12278 if (argc != 0)
12279 usage_merge();
12280 } else if (argc != 1)
12281 usage_merge();
12283 cwd = getcwd(NULL, 0);
12284 if (cwd == NULL) {
12285 error = got_error_from_errno("getcwd");
12286 goto done;
12289 error = got_repo_pack_fds_open(&pack_fds);
12290 if (error != NULL)
12291 goto done;
12293 error = got_worktree_open(&worktree, cwd);
12294 if (error) {
12295 if (error->code == GOT_ERR_NOT_WORKTREE)
12296 error = wrap_not_worktree_error(error,
12297 "merge", cwd);
12298 goto done;
12301 error = got_repo_open(&repo,
12302 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12303 pack_fds);
12304 if (error != NULL)
12305 goto done;
12307 error = apply_unveil(got_repo_get_path(repo), 0,
12308 worktree ? got_worktree_get_root_path(worktree) : NULL);
12309 if (error)
12310 goto done;
12312 error = check_rebase_or_histedit_in_progress(worktree);
12313 if (error)
12314 goto done;
12316 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12317 repo);
12318 if (error)
12319 goto done;
12321 if (abort_merge) {
12322 if (!merge_in_progress) {
12323 error = got_error(GOT_ERR_NOT_MERGING);
12324 goto done;
12326 error = got_worktree_merge_continue(&branch_name,
12327 &branch_tip, &fileindex, worktree, repo);
12328 if (error)
12329 goto done;
12330 error = got_worktree_merge_abort(worktree, fileindex, repo,
12331 abort_progress, &upa);
12332 if (error)
12333 goto done;
12334 printf("Merge of %s aborted\n", branch_name);
12335 goto done; /* nothing else to do */
12338 error = get_author(&author, repo, worktree);
12339 if (error)
12340 goto done;
12342 if (continue_merge) {
12343 if (!merge_in_progress) {
12344 error = got_error(GOT_ERR_NOT_MERGING);
12345 goto done;
12347 error = got_worktree_merge_continue(&branch_name,
12348 &branch_tip, &fileindex, worktree, repo);
12349 if (error)
12350 goto done;
12351 } else {
12352 error = got_ref_open(&branch, repo, argv[0], 0);
12353 if (error != NULL)
12354 goto done;
12355 branch_name = strdup(got_ref_get_name(branch));
12356 if (branch_name == NULL) {
12357 error = got_error_from_errno("strdup");
12358 goto done;
12360 error = got_ref_resolve(&branch_tip, repo, branch);
12361 if (error)
12362 goto done;
12365 error = got_ref_open(&wt_branch, repo,
12366 got_worktree_get_head_ref_name(worktree), 0);
12367 if (error)
12368 goto done;
12369 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12370 if (error)
12371 goto done;
12372 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12373 wt_branch_tip, branch_tip, 0, repo,
12374 check_cancelled, NULL);
12375 if (error && error->code != GOT_ERR_ANCESTRY)
12376 goto done;
12378 if (!continue_merge) {
12379 error = check_path_prefix(wt_branch_tip, branch_tip,
12380 got_worktree_get_path_prefix(worktree),
12381 GOT_ERR_MERGE_PATH, repo);
12382 if (error)
12383 goto done;
12384 if (yca_id) {
12385 error = check_same_branch(wt_branch_tip, branch,
12386 yca_id, repo);
12387 if (error) {
12388 if (error->code != GOT_ERR_ANCESTRY)
12389 goto done;
12390 error = NULL;
12391 } else {
12392 static char msg[512];
12393 snprintf(msg, sizeof(msg),
12394 "cannot create a merge commit because "
12395 "%s is based on %s; %s can be integrated "
12396 "with 'got integrate' instead", branch_name,
12397 got_worktree_get_head_ref_name(worktree),
12398 branch_name);
12399 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12400 goto done;
12403 error = got_worktree_merge_prepare(&fileindex, worktree,
12404 branch, repo);
12405 if (error)
12406 goto done;
12408 error = got_worktree_merge_branch(worktree, fileindex,
12409 yca_id, branch_tip, repo, update_progress, &upa,
12410 check_cancelled, NULL);
12411 if (error)
12412 goto done;
12413 print_merge_progress_stats(&upa);
12414 if (!upa.did_something) {
12415 error = got_worktree_merge_abort(worktree, fileindex,
12416 repo, abort_progress, &upa);
12417 if (error)
12418 goto done;
12419 printf("Already up-to-date\n");
12420 goto done;
12424 if (interrupt_merge) {
12425 error = got_worktree_merge_postpone(worktree, fileindex);
12426 if (error)
12427 goto done;
12428 printf("Merge of %s interrupted on request\n", branch_name);
12429 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12430 upa.not_deleted > 0 || upa.unversioned > 0) {
12431 error = got_worktree_merge_postpone(worktree, fileindex);
12432 if (error)
12433 goto done;
12434 if (upa.conflicts > 0 && upa.missing == 0 &&
12435 upa.not_deleted == 0 && upa.unversioned == 0) {
12436 error = got_error_msg(GOT_ERR_CONFLICTS,
12437 "conflicts must be resolved before merging "
12438 "can continue");
12439 } else if (upa.conflicts > 0) {
12440 error = got_error_msg(GOT_ERR_CONFLICTS,
12441 "conflicts must be resolved before merging "
12442 "can continue; changes destined for some "
12443 "files were not yet merged and "
12444 "should be merged manually if required before the "
12445 "merge operation is continued");
12446 } else {
12447 error = got_error_msg(GOT_ERR_CONFLICTS,
12448 "changes destined for some "
12449 "files were not yet merged and should be "
12450 "merged manually if required before the "
12451 "merge operation is continued");
12453 goto done;
12454 } else {
12455 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12456 fileindex, author, NULL, 1, branch_tip, branch_name,
12457 repo, continue_merge ? print_status : NULL, NULL);
12458 if (error)
12459 goto done;
12460 error = got_worktree_merge_complete(worktree, fileindex, repo);
12461 if (error)
12462 goto done;
12463 error = got_object_id_str(&id_str, merge_commit_id);
12464 if (error)
12465 goto done;
12466 printf("Merged %s into %s: %s\n", branch_name,
12467 got_worktree_get_head_ref_name(worktree),
12468 id_str);
12471 done:
12472 free(id_str);
12473 free(merge_commit_id);
12474 free(author);
12475 free(branch_tip);
12476 free(branch_name);
12477 free(yca_id);
12478 if (branch)
12479 got_ref_close(branch);
12480 if (wt_branch)
12481 got_ref_close(wt_branch);
12482 if (worktree)
12483 got_worktree_close(worktree);
12484 if (repo) {
12485 const struct got_error *close_err = got_repo_close(repo);
12486 if (error == NULL)
12487 error = close_err;
12489 if (pack_fds) {
12490 const struct got_error *pack_err =
12491 got_repo_pack_fds_close(pack_fds);
12492 if (error == NULL)
12493 error = pack_err;
12495 return error;
12498 __dead static void
12499 usage_stage(void)
12501 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12502 "[path ...]\n", getprogname());
12503 exit(1);
12506 static const struct got_error *
12507 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12508 const char *path, struct got_object_id *blob_id,
12509 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12510 int dirfd, const char *de_name)
12512 const struct got_error *err = NULL;
12513 char *id_str = NULL;
12515 if (staged_status != GOT_STATUS_ADD &&
12516 staged_status != GOT_STATUS_MODIFY &&
12517 staged_status != GOT_STATUS_DELETE)
12518 return NULL;
12520 if (staged_status == GOT_STATUS_ADD ||
12521 staged_status == GOT_STATUS_MODIFY)
12522 err = got_object_id_str(&id_str, staged_blob_id);
12523 else
12524 err = got_object_id_str(&id_str, blob_id);
12525 if (err)
12526 return err;
12528 printf("%s %c %s\n", id_str, staged_status, path);
12529 free(id_str);
12530 return NULL;
12533 static const struct got_error *
12534 cmd_stage(int argc, char *argv[])
12536 const struct got_error *error = NULL;
12537 struct got_repository *repo = NULL;
12538 struct got_worktree *worktree = NULL;
12539 char *cwd = NULL;
12540 struct got_pathlist_head paths;
12541 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12542 FILE *patch_script_file = NULL;
12543 const char *patch_script_path = NULL;
12544 struct choose_patch_arg cpa;
12545 int *pack_fds = NULL;
12547 TAILQ_INIT(&paths);
12549 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12550 switch (ch) {
12551 case 'F':
12552 patch_script_path = optarg;
12553 break;
12554 case 'l':
12555 list_stage = 1;
12556 break;
12557 case 'p':
12558 pflag = 1;
12559 break;
12560 case 'S':
12561 allow_bad_symlinks = 1;
12562 break;
12563 default:
12564 usage_stage();
12565 /* NOTREACHED */
12569 argc -= optind;
12570 argv += optind;
12572 #ifndef PROFILE
12573 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12574 "unveil", NULL) == -1)
12575 err(1, "pledge");
12576 #endif
12577 if (list_stage && (pflag || patch_script_path))
12578 errx(1, "-l option cannot be used with other options");
12579 if (patch_script_path && !pflag)
12580 errx(1, "-F option can only be used together with -p option");
12582 cwd = getcwd(NULL, 0);
12583 if (cwd == NULL) {
12584 error = got_error_from_errno("getcwd");
12585 goto done;
12588 error = got_repo_pack_fds_open(&pack_fds);
12589 if (error != NULL)
12590 goto done;
12592 error = got_worktree_open(&worktree, cwd);
12593 if (error) {
12594 if (error->code == GOT_ERR_NOT_WORKTREE)
12595 error = wrap_not_worktree_error(error, "stage", cwd);
12596 goto done;
12599 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12600 NULL, pack_fds);
12601 if (error != NULL)
12602 goto done;
12604 if (patch_script_path) {
12605 patch_script_file = fopen(patch_script_path, "re");
12606 if (patch_script_file == NULL) {
12607 error = got_error_from_errno2("fopen",
12608 patch_script_path);
12609 goto done;
12612 error = apply_unveil(got_repo_get_path(repo), 0,
12613 got_worktree_get_root_path(worktree));
12614 if (error)
12615 goto done;
12617 error = check_merge_in_progress(worktree, repo);
12618 if (error)
12619 goto done;
12621 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12622 if (error)
12623 goto done;
12625 if (list_stage)
12626 error = got_worktree_status(worktree, &paths, repo, 0,
12627 print_stage, NULL, check_cancelled, NULL);
12628 else {
12629 cpa.patch_script_file = patch_script_file;
12630 cpa.action = "stage";
12631 error = got_worktree_stage(worktree, &paths,
12632 pflag ? NULL : print_status, NULL,
12633 pflag ? choose_patch : NULL, &cpa,
12634 allow_bad_symlinks, repo);
12636 done:
12637 if (patch_script_file && fclose(patch_script_file) == EOF &&
12638 error == NULL)
12639 error = got_error_from_errno2("fclose", patch_script_path);
12640 if (repo) {
12641 const struct got_error *close_err = got_repo_close(repo);
12642 if (error == NULL)
12643 error = close_err;
12645 if (worktree)
12646 got_worktree_close(worktree);
12647 if (pack_fds) {
12648 const struct got_error *pack_err =
12649 got_repo_pack_fds_close(pack_fds);
12650 if (error == NULL)
12651 error = pack_err;
12653 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12654 free(cwd);
12655 return error;
12658 __dead static void
12659 usage_unstage(void)
12661 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12662 "[path ...]\n", getprogname());
12663 exit(1);
12667 static const struct got_error *
12668 cmd_unstage(int argc, char *argv[])
12670 const struct got_error *error = NULL;
12671 struct got_repository *repo = NULL;
12672 struct got_worktree *worktree = NULL;
12673 char *cwd = NULL;
12674 struct got_pathlist_head paths;
12675 int ch, pflag = 0;
12676 struct got_update_progress_arg upa;
12677 FILE *patch_script_file = NULL;
12678 const char *patch_script_path = NULL;
12679 struct choose_patch_arg cpa;
12680 int *pack_fds = NULL;
12682 TAILQ_INIT(&paths);
12684 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12685 switch (ch) {
12686 case 'F':
12687 patch_script_path = optarg;
12688 break;
12689 case 'p':
12690 pflag = 1;
12691 break;
12692 default:
12693 usage_unstage();
12694 /* NOTREACHED */
12698 argc -= optind;
12699 argv += optind;
12701 #ifndef PROFILE
12702 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12703 "unveil", NULL) == -1)
12704 err(1, "pledge");
12705 #endif
12706 if (patch_script_path && !pflag)
12707 errx(1, "-F option can only be used together with -p option");
12709 cwd = getcwd(NULL, 0);
12710 if (cwd == NULL) {
12711 error = got_error_from_errno("getcwd");
12712 goto done;
12715 error = got_repo_pack_fds_open(&pack_fds);
12716 if (error != NULL)
12717 goto done;
12719 error = got_worktree_open(&worktree, cwd);
12720 if (error) {
12721 if (error->code == GOT_ERR_NOT_WORKTREE)
12722 error = wrap_not_worktree_error(error, "unstage", cwd);
12723 goto done;
12726 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12727 NULL, pack_fds);
12728 if (error != NULL)
12729 goto done;
12731 if (patch_script_path) {
12732 patch_script_file = fopen(patch_script_path, "re");
12733 if (patch_script_file == NULL) {
12734 error = got_error_from_errno2("fopen",
12735 patch_script_path);
12736 goto done;
12740 error = apply_unveil(got_repo_get_path(repo), 0,
12741 got_worktree_get_root_path(worktree));
12742 if (error)
12743 goto done;
12745 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12746 if (error)
12747 goto done;
12749 cpa.patch_script_file = patch_script_file;
12750 cpa.action = "unstage";
12751 memset(&upa, 0, sizeof(upa));
12752 error = got_worktree_unstage(worktree, &paths, update_progress,
12753 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12754 if (!error)
12755 print_merge_progress_stats(&upa);
12756 done:
12757 if (patch_script_file && fclose(patch_script_file) == EOF &&
12758 error == NULL)
12759 error = got_error_from_errno2("fclose", patch_script_path);
12760 if (repo) {
12761 const struct got_error *close_err = got_repo_close(repo);
12762 if (error == NULL)
12763 error = close_err;
12765 if (worktree)
12766 got_worktree_close(worktree);
12767 if (pack_fds) {
12768 const struct got_error *pack_err =
12769 got_repo_pack_fds_close(pack_fds);
12770 if (error == NULL)
12771 error = pack_err;
12773 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12774 free(cwd);
12775 return error;
12778 __dead static void
12779 usage_cat(void)
12781 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12782 "arg ...\n", getprogname());
12783 exit(1);
12786 static const struct got_error *
12787 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12789 const struct got_error *err;
12790 struct got_blob_object *blob;
12791 int fd = -1;
12793 fd = got_opentempfd();
12794 if (fd == -1)
12795 return got_error_from_errno("got_opentempfd");
12797 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12798 if (err)
12799 goto done;
12801 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12802 done:
12803 if (fd != -1 && close(fd) == -1 && err == NULL)
12804 err = got_error_from_errno("close");
12805 if (blob)
12806 got_object_blob_close(blob);
12807 return err;
12810 static const struct got_error *
12811 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12813 const struct got_error *err;
12814 struct got_tree_object *tree;
12815 int nentries, i;
12817 err = got_object_open_as_tree(&tree, repo, id);
12818 if (err)
12819 return err;
12821 nentries = got_object_tree_get_nentries(tree);
12822 for (i = 0; i < nentries; i++) {
12823 struct got_tree_entry *te;
12824 char *id_str;
12825 if (sigint_received || sigpipe_received)
12826 break;
12827 te = got_object_tree_get_entry(tree, i);
12828 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12829 if (err)
12830 break;
12831 fprintf(outfile, "%s %.7o %s\n", id_str,
12832 got_tree_entry_get_mode(te),
12833 got_tree_entry_get_name(te));
12834 free(id_str);
12837 got_object_tree_close(tree);
12838 return err;
12841 static const struct got_error *
12842 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12844 const struct got_error *err;
12845 struct got_commit_object *commit;
12846 const struct got_object_id_queue *parent_ids;
12847 struct got_object_qid *pid;
12848 char *id_str = NULL;
12849 const char *logmsg = NULL;
12850 char gmtoff[6];
12852 err = got_object_open_as_commit(&commit, repo, id);
12853 if (err)
12854 return err;
12856 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12857 if (err)
12858 goto done;
12860 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12861 parent_ids = got_object_commit_get_parent_ids(commit);
12862 fprintf(outfile, "numparents %d\n",
12863 got_object_commit_get_nparents(commit));
12864 STAILQ_FOREACH(pid, parent_ids, entry) {
12865 char *pid_str;
12866 err = got_object_id_str(&pid_str, &pid->id);
12867 if (err)
12868 goto done;
12869 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12870 free(pid_str);
12872 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12873 got_object_commit_get_author_gmtoff(commit));
12874 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12875 got_object_commit_get_author(commit),
12876 (long long)got_object_commit_get_author_time(commit),
12877 gmtoff);
12879 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12880 got_object_commit_get_committer_gmtoff(commit));
12881 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12882 got_object_commit_get_committer(commit),
12883 (long long)got_object_commit_get_committer_time(commit),
12884 gmtoff);
12886 logmsg = got_object_commit_get_logmsg_raw(commit);
12887 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12888 fprintf(outfile, "%s", logmsg);
12889 done:
12890 free(id_str);
12891 got_object_commit_close(commit);
12892 return err;
12895 static const struct got_error *
12896 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12898 const struct got_error *err;
12899 struct got_tag_object *tag;
12900 char *id_str = NULL;
12901 const char *tagmsg = NULL;
12902 char gmtoff[6];
12904 err = got_object_open_as_tag(&tag, repo, id);
12905 if (err)
12906 return err;
12908 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12909 if (err)
12910 goto done;
12912 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12914 switch (got_object_tag_get_object_type(tag)) {
12915 case GOT_OBJ_TYPE_BLOB:
12916 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12917 GOT_OBJ_LABEL_BLOB);
12918 break;
12919 case GOT_OBJ_TYPE_TREE:
12920 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12921 GOT_OBJ_LABEL_TREE);
12922 break;
12923 case GOT_OBJ_TYPE_COMMIT:
12924 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12925 GOT_OBJ_LABEL_COMMIT);
12926 break;
12927 case GOT_OBJ_TYPE_TAG:
12928 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12929 GOT_OBJ_LABEL_TAG);
12930 break;
12931 default:
12932 break;
12935 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12936 got_object_tag_get_name(tag));
12938 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12939 got_object_tag_get_tagger_gmtoff(tag));
12940 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12941 got_object_tag_get_tagger(tag),
12942 (long long)got_object_tag_get_tagger_time(tag),
12943 gmtoff);
12945 tagmsg = got_object_tag_get_message(tag);
12946 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12947 fprintf(outfile, "%s", tagmsg);
12948 done:
12949 free(id_str);
12950 got_object_tag_close(tag);
12951 return err;
12954 static const struct got_error *
12955 cmd_cat(int argc, char *argv[])
12957 const struct got_error *error;
12958 struct got_repository *repo = NULL;
12959 struct got_worktree *worktree = NULL;
12960 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12961 const char *commit_id_str = NULL;
12962 struct got_object_id *id = NULL, *commit_id = NULL;
12963 struct got_commit_object *commit = NULL;
12964 int ch, obj_type, i, force_path = 0;
12965 struct got_reflist_head refs;
12966 int *pack_fds = NULL;
12968 TAILQ_INIT(&refs);
12970 #ifndef PROFILE
12971 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12972 NULL) == -1)
12973 err(1, "pledge");
12974 #endif
12976 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12977 switch (ch) {
12978 case 'c':
12979 commit_id_str = optarg;
12980 break;
12981 case 'P':
12982 force_path = 1;
12983 break;
12984 case 'r':
12985 repo_path = realpath(optarg, NULL);
12986 if (repo_path == NULL)
12987 return got_error_from_errno2("realpath",
12988 optarg);
12989 got_path_strip_trailing_slashes(repo_path);
12990 break;
12991 default:
12992 usage_cat();
12993 /* NOTREACHED */
12997 argc -= optind;
12998 argv += optind;
13000 cwd = getcwd(NULL, 0);
13001 if (cwd == NULL) {
13002 error = got_error_from_errno("getcwd");
13003 goto done;
13006 error = got_repo_pack_fds_open(&pack_fds);
13007 if (error != NULL)
13008 goto done;
13010 if (repo_path == NULL) {
13011 error = got_worktree_open(&worktree, cwd);
13012 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13013 goto done;
13014 if (worktree) {
13015 repo_path = strdup(
13016 got_worktree_get_repo_path(worktree));
13017 if (repo_path == NULL) {
13018 error = got_error_from_errno("strdup");
13019 goto done;
13022 /* Release work tree lock. */
13023 got_worktree_close(worktree);
13024 worktree = NULL;
13028 if (repo_path == NULL) {
13029 repo_path = strdup(cwd);
13030 if (repo_path == NULL)
13031 return got_error_from_errno("strdup");
13034 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13035 free(repo_path);
13036 if (error != NULL)
13037 goto done;
13039 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13040 if (error)
13041 goto done;
13043 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13044 if (error)
13045 goto done;
13047 if (commit_id_str == NULL)
13048 commit_id_str = GOT_REF_HEAD;
13049 error = got_repo_match_object_id(&commit_id, NULL,
13050 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13051 if (error)
13052 goto done;
13054 error = got_object_open_as_commit(&commit, repo, commit_id);
13055 if (error)
13056 goto done;
13058 for (i = 0; i < argc; i++) {
13059 if (force_path) {
13060 error = got_object_id_by_path(&id, repo, commit,
13061 argv[i]);
13062 if (error)
13063 break;
13064 } else {
13065 error = got_repo_match_object_id(&id, &label, argv[i],
13066 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13067 repo);
13068 if (error) {
13069 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13070 error->code != GOT_ERR_NOT_REF)
13071 break;
13072 error = got_object_id_by_path(&id, repo,
13073 commit, argv[i]);
13074 if (error)
13075 break;
13079 error = got_object_get_type(&obj_type, repo, id);
13080 if (error)
13081 break;
13083 switch (obj_type) {
13084 case GOT_OBJ_TYPE_BLOB:
13085 error = cat_blob(id, repo, stdout);
13086 break;
13087 case GOT_OBJ_TYPE_TREE:
13088 error = cat_tree(id, repo, stdout);
13089 break;
13090 case GOT_OBJ_TYPE_COMMIT:
13091 error = cat_commit(id, repo, stdout);
13092 break;
13093 case GOT_OBJ_TYPE_TAG:
13094 error = cat_tag(id, repo, stdout);
13095 break;
13096 default:
13097 error = got_error(GOT_ERR_OBJ_TYPE);
13098 break;
13100 if (error)
13101 break;
13102 free(label);
13103 label = NULL;
13104 free(id);
13105 id = NULL;
13107 done:
13108 free(label);
13109 free(id);
13110 free(commit_id);
13111 if (commit)
13112 got_object_commit_close(commit);
13113 if (worktree)
13114 got_worktree_close(worktree);
13115 if (repo) {
13116 const struct got_error *close_err = got_repo_close(repo);
13117 if (error == NULL)
13118 error = close_err;
13120 if (pack_fds) {
13121 const struct got_error *pack_err =
13122 got_repo_pack_fds_close(pack_fds);
13123 if (error == NULL)
13124 error = pack_err;
13127 got_ref_list_free(&refs);
13128 return error;
13131 __dead static void
13132 usage_info(void)
13134 fprintf(stderr, "usage: %s info [path ...]\n",
13135 getprogname());
13136 exit(1);
13139 static const struct got_error *
13140 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13141 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13142 struct got_object_id *commit_id)
13144 const struct got_error *err = NULL;
13145 char *id_str = NULL;
13146 char datebuf[128];
13147 struct tm mytm, *tm;
13148 struct got_pathlist_head *paths = arg;
13149 struct got_pathlist_entry *pe;
13152 * Clear error indication from any of the path arguments which
13153 * would cause this file index entry to be displayed.
13155 TAILQ_FOREACH(pe, paths, entry) {
13156 if (got_path_cmp(path, pe->path, strlen(path),
13157 pe->path_len) == 0 ||
13158 got_path_is_child(path, pe->path, pe->path_len))
13159 pe->data = NULL; /* no error */
13162 printf(GOT_COMMIT_SEP_STR);
13163 if (S_ISLNK(mode))
13164 printf("symlink: %s\n", path);
13165 else if (S_ISREG(mode)) {
13166 printf("file: %s\n", path);
13167 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13168 } else if (S_ISDIR(mode))
13169 printf("directory: %s\n", path);
13170 else
13171 printf("something: %s\n", path);
13173 tm = localtime_r(&mtime, &mytm);
13174 if (tm == NULL)
13175 return NULL;
13176 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13177 return got_error(GOT_ERR_NO_SPACE);
13178 printf("timestamp: %s\n", datebuf);
13180 if (blob_id) {
13181 err = got_object_id_str(&id_str, blob_id);
13182 if (err)
13183 return err;
13184 printf("based on blob: %s\n", id_str);
13185 free(id_str);
13188 if (staged_blob_id) {
13189 err = got_object_id_str(&id_str, staged_blob_id);
13190 if (err)
13191 return err;
13192 printf("based on staged blob: %s\n", id_str);
13193 free(id_str);
13196 if (commit_id) {
13197 err = got_object_id_str(&id_str, commit_id);
13198 if (err)
13199 return err;
13200 printf("based on commit: %s\n", id_str);
13201 free(id_str);
13204 return NULL;
13207 static const struct got_error *
13208 cmd_info(int argc, char *argv[])
13210 const struct got_error *error = NULL;
13211 struct got_worktree *worktree = NULL;
13212 char *cwd = NULL, *id_str = NULL;
13213 struct got_pathlist_head paths;
13214 char *uuidstr = NULL;
13215 int ch, show_files = 0;
13217 TAILQ_INIT(&paths);
13219 while ((ch = getopt(argc, argv, "")) != -1) {
13220 switch (ch) {
13221 default:
13222 usage_info();
13223 /* NOTREACHED */
13227 argc -= optind;
13228 argv += optind;
13230 #ifndef PROFILE
13231 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13232 NULL) == -1)
13233 err(1, "pledge");
13234 #endif
13235 cwd = getcwd(NULL, 0);
13236 if (cwd == NULL) {
13237 error = got_error_from_errno("getcwd");
13238 goto done;
13241 error = got_worktree_open(&worktree, cwd);
13242 if (error) {
13243 if (error->code == GOT_ERR_NOT_WORKTREE)
13244 error = wrap_not_worktree_error(error, "info", cwd);
13245 goto done;
13248 #ifndef PROFILE
13249 /* Remove "wpath cpath proc exec sendfd" promises. */
13250 if (pledge("stdio rpath flock unveil", NULL) == -1)
13251 err(1, "pledge");
13252 #endif
13253 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13254 if (error)
13255 goto done;
13257 if (argc >= 1) {
13258 error = get_worktree_paths_from_argv(&paths, argc, argv,
13259 worktree);
13260 if (error)
13261 goto done;
13262 show_files = 1;
13265 error = got_object_id_str(&id_str,
13266 got_worktree_get_base_commit_id(worktree));
13267 if (error)
13268 goto done;
13270 error = got_worktree_get_uuid(&uuidstr, worktree);
13271 if (error)
13272 goto done;
13274 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13275 printf("work tree base commit: %s\n", id_str);
13276 printf("work tree path prefix: %s\n",
13277 got_worktree_get_path_prefix(worktree));
13278 printf("work tree branch reference: %s\n",
13279 got_worktree_get_head_ref_name(worktree));
13280 printf("work tree UUID: %s\n", uuidstr);
13281 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13283 if (show_files) {
13284 struct got_pathlist_entry *pe;
13285 TAILQ_FOREACH(pe, &paths, entry) {
13286 if (pe->path_len == 0)
13287 continue;
13289 * Assume this path will fail. This will be corrected
13290 * in print_path_info() in case the path does suceeed.
13292 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13294 error = got_worktree_path_info(worktree, &paths,
13295 print_path_info, &paths, check_cancelled, NULL);
13296 if (error)
13297 goto done;
13298 TAILQ_FOREACH(pe, &paths, entry) {
13299 if (pe->data != NULL) {
13300 const struct got_error *perr;
13302 perr = pe->data;
13303 error = got_error_fmt(perr->code, "%s",
13304 pe->path);
13305 break;
13309 done:
13310 if (worktree)
13311 got_worktree_close(worktree);
13312 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13313 free(cwd);
13314 free(id_str);
13315 free(uuidstr);
13316 return error;