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 insertion%s(+), %d deletion%s(-)\n\n",
4172 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4173 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4175 if (fflush(stdout) != 0)
4176 return got_error_from_errno("fflush");
4178 return NULL;
4181 static const struct got_error *
4182 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4183 struct got_repository *repo, const char *path,
4184 struct got_pathlist_head *changed_paths, struct got_diffstat_cb_arg *dsa,
4185 int show_patch, int diff_context,
4186 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4188 const struct got_error *err = NULL;
4189 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4190 char datebuf[26];
4191 time_t committer_time;
4192 const char *author, *committer;
4193 char *refs_str = NULL;
4195 err = got_object_id_str(&id_str, id);
4196 if (err)
4197 return err;
4199 if (custom_refs_str == NULL) {
4200 struct got_reflist_head *refs;
4201 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4202 if (refs) {
4203 err = build_refs_str(&refs_str, refs, id, repo, 0);
4204 if (err)
4205 goto done;
4209 printf(GOT_COMMIT_SEP_STR);
4210 if (custom_refs_str)
4211 printf("commit %s (%s)\n", id_str, custom_refs_str);
4212 else
4213 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4214 refs_str ? refs_str : "", refs_str ? ")" : "");
4215 free(id_str);
4216 id_str = NULL;
4217 free(refs_str);
4218 refs_str = NULL;
4219 printf("from: %s\n", got_object_commit_get_author(commit));
4220 author = got_object_commit_get_author(commit);
4221 committer = got_object_commit_get_committer(commit);
4222 if (strcmp(author, committer) != 0)
4223 printf("via: %s\n", committer);
4224 committer_time = got_object_commit_get_committer_time(commit);
4225 datestr = get_datestr(&committer_time, datebuf);
4226 if (datestr)
4227 printf("date: %s UTC\n", datestr);
4228 if (got_object_commit_get_nparents(commit) > 1) {
4229 const struct got_object_id_queue *parent_ids;
4230 struct got_object_qid *qid;
4231 int n = 1;
4232 parent_ids = got_object_commit_get_parent_ids(commit);
4233 STAILQ_FOREACH(qid, parent_ids, entry) {
4234 err = got_object_id_str(&id_str, &qid->id);
4235 if (err)
4236 goto done;
4237 printf("parent %d: %s\n", n++, id_str);
4238 free(id_str);
4239 id_str = NULL;
4243 err = got_object_commit_get_logmsg(&logmsg0, commit);
4244 if (err)
4245 goto done;
4247 logmsg = logmsg0;
4248 do {
4249 line = strsep(&logmsg, "\n");
4250 if (line)
4251 printf(" %s\n", line);
4252 } while (line);
4253 free(logmsg0);
4255 if (dsa && changed_paths) {
4256 err = print_diffstat(dsa, changed_paths, NULL);
4257 if (err)
4258 goto done;
4259 } else if (changed_paths) {
4260 struct got_pathlist_entry *pe;
4262 TAILQ_FOREACH(pe, changed_paths, entry) {
4263 struct got_diff_changed_path *cp = pe->data;
4265 printf(" %c %s\n", cp->status, pe->path);
4267 printf("\n");
4269 if (show_patch) {
4270 err = print_patch(commit, id, path, diff_context, repo, stdout);
4271 if (err == 0)
4272 printf("\n");
4275 if (fflush(stdout) != 0 && err == NULL)
4276 err = got_error_from_errno("fflush");
4277 done:
4278 free(id_str);
4279 free(refs_str);
4280 return err;
4283 static const struct got_error *
4284 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4285 struct got_repository *repo, const char *path, int show_changed_paths,
4286 int show_diffstat, int show_patch, const char *search_pattern,
4287 int diff_context, int limit, int log_branches, int reverse_display_order,
4288 struct got_reflist_object_id_map *refs_idmap, int one_line,
4289 FILE *tmpfile)
4291 const struct got_error *err;
4292 struct got_commit_graph *graph;
4293 regex_t regex;
4294 int have_match;
4295 struct got_object_id_queue reversed_commits;
4296 struct got_object_qid *qid;
4297 struct got_commit_object *commit;
4298 struct got_pathlist_head changed_paths;
4300 STAILQ_INIT(&reversed_commits);
4301 TAILQ_INIT(&changed_paths);
4303 if (search_pattern && regcomp(&regex, search_pattern,
4304 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4305 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4307 err = got_commit_graph_open(&graph, path, !log_branches);
4308 if (err)
4309 return err;
4310 err = got_commit_graph_iter_start(graph, root_id, repo,
4311 check_cancelled, NULL);
4312 if (err)
4313 goto done;
4314 for (;;) {
4315 struct got_object_id id;
4316 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4317 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4319 if (sigint_received || sigpipe_received)
4320 break;
4322 err = got_commit_graph_iter_next(&id, graph, repo,
4323 check_cancelled, NULL);
4324 if (err) {
4325 if (err->code == GOT_ERR_ITER_COMPLETED)
4326 err = NULL;
4327 break;
4330 err = got_object_open_as_commit(&commit, repo, &id);
4331 if (err)
4332 break;
4334 if ((show_changed_paths || show_diffstat) &&
4335 !reverse_display_order) {
4336 err = get_changed_paths(&changed_paths, commit, repo,
4337 show_diffstat ? &dsa : NULL);
4338 if (err)
4339 break;
4342 if (search_pattern) {
4343 err = match_commit(&have_match, &id, commit, &regex);
4344 if (err) {
4345 got_object_commit_close(commit);
4346 break;
4348 if (have_match == 0 && show_changed_paths)
4349 match_changed_paths(&have_match,
4350 &changed_paths, &regex);
4351 if (have_match == 0 && show_patch) {
4352 err = match_patch(&have_match, commit, &id,
4353 path, diff_context, repo, &regex,
4354 tmpfile);
4355 if (err)
4356 break;
4358 if (have_match == 0) {
4359 got_object_commit_close(commit);
4360 got_pathlist_free(&changed_paths,
4361 GOT_PATHLIST_FREE_ALL);
4362 continue;
4366 if (reverse_display_order) {
4367 err = got_object_qid_alloc(&qid, &id);
4368 if (err)
4369 break;
4370 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4371 got_object_commit_close(commit);
4372 } else {
4373 if (one_line)
4374 err = print_commit_oneline(commit, &id,
4375 repo, refs_idmap);
4376 else
4377 err = print_commit(commit, &id, repo, path,
4378 (show_changed_paths || show_diffstat) ?
4379 &changed_paths : NULL,
4380 show_diffstat ? &dsa : NULL, show_patch,
4381 diff_context, refs_idmap, NULL);
4382 got_object_commit_close(commit);
4383 if (err)
4384 break;
4386 if ((limit && --limit == 0) ||
4387 (end_id && got_object_id_cmp(&id, end_id) == 0))
4388 break;
4390 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4392 if (reverse_display_order) {
4393 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4394 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4395 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4397 err = got_object_open_as_commit(&commit, repo,
4398 &qid->id);
4399 if (err)
4400 break;
4401 if (show_changed_paths || show_diffstat) {
4402 err = get_changed_paths(&changed_paths,
4403 commit, repo, show_diffstat ? &dsa : NULL);
4404 if (err)
4405 break;
4407 if (one_line)
4408 err = print_commit_oneline(commit, &qid->id,
4409 repo, refs_idmap);
4410 else
4411 err = print_commit(commit, &qid->id, repo, path,
4412 (show_changed_paths || show_diffstat) ?
4413 &changed_paths : NULL,
4414 show_diffstat ? &dsa : NULL, show_patch,
4415 diff_context, refs_idmap, NULL);
4416 got_object_commit_close(commit);
4417 if (err)
4418 break;
4419 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4422 done:
4423 while (!STAILQ_EMPTY(&reversed_commits)) {
4424 qid = STAILQ_FIRST(&reversed_commits);
4425 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4426 got_object_qid_free(qid);
4428 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4429 if (search_pattern)
4430 regfree(&regex);
4431 got_commit_graph_close(graph);
4432 return err;
4435 __dead static void
4436 usage_log(void)
4438 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4439 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4440 "[path]\n", getprogname());
4441 exit(1);
4444 static int
4445 get_default_log_limit(void)
4447 const char *got_default_log_limit;
4448 long long n;
4449 const char *errstr;
4451 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4452 if (got_default_log_limit == NULL)
4453 return 0;
4454 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4455 if (errstr != NULL)
4456 return 0;
4457 return n;
4460 static const struct got_error *
4461 cmd_log(int argc, char *argv[])
4463 const struct got_error *error;
4464 struct got_repository *repo = NULL;
4465 struct got_worktree *worktree = NULL;
4466 struct got_object_id *start_id = NULL, *end_id = NULL;
4467 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4468 const char *start_commit = NULL, *end_commit = NULL;
4469 const char *search_pattern = NULL;
4470 int diff_context = -1, ch;
4471 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4472 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4473 const char *errstr;
4474 struct got_reflist_head refs;
4475 struct got_reflist_object_id_map *refs_idmap = NULL;
4476 FILE *tmpfile = NULL;
4477 int *pack_fds = NULL;
4479 TAILQ_INIT(&refs);
4481 #ifndef PROFILE
4482 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4483 NULL)
4484 == -1)
4485 err(1, "pledge");
4486 #endif
4488 limit = get_default_log_limit();
4490 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4491 switch (ch) {
4492 case 'b':
4493 log_branches = 1;
4494 break;
4495 case 'C':
4496 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4497 &errstr);
4498 if (errstr != NULL)
4499 errx(1, "number of context lines is %s: %s",
4500 errstr, optarg);
4501 break;
4502 case 'c':
4503 start_commit = optarg;
4504 break;
4505 case 'd':
4506 show_diffstat = 1;
4507 break;
4508 case 'l':
4509 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4510 if (errstr != NULL)
4511 errx(1, "number of commits is %s: %s",
4512 errstr, optarg);
4513 break;
4514 case 'P':
4515 show_changed_paths = 1;
4516 break;
4517 case 'p':
4518 show_patch = 1;
4519 break;
4520 case 'R':
4521 reverse_display_order = 1;
4522 break;
4523 case 'r':
4524 repo_path = realpath(optarg, NULL);
4525 if (repo_path == NULL)
4526 return got_error_from_errno2("realpath",
4527 optarg);
4528 got_path_strip_trailing_slashes(repo_path);
4529 break;
4530 case 'S':
4531 search_pattern = optarg;
4532 break;
4533 case 's':
4534 one_line = 1;
4535 break;
4536 case 'x':
4537 end_commit = optarg;
4538 break;
4539 default:
4540 usage_log();
4541 /* NOTREACHED */
4545 argc -= optind;
4546 argv += optind;
4548 if (diff_context == -1)
4549 diff_context = 3;
4550 else if (!show_patch)
4551 errx(1, "-C requires -p");
4553 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4554 errx(1, "cannot use -s with -d, -p or -P");
4556 cwd = getcwd(NULL, 0);
4557 if (cwd == NULL) {
4558 error = got_error_from_errno("getcwd");
4559 goto done;
4562 error = got_repo_pack_fds_open(&pack_fds);
4563 if (error != NULL)
4564 goto done;
4566 if (repo_path == NULL) {
4567 error = got_worktree_open(&worktree, cwd);
4568 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4569 goto done;
4570 error = NULL;
4573 if (argc == 1) {
4574 if (worktree) {
4575 error = got_worktree_resolve_path(&path, worktree,
4576 argv[0]);
4577 if (error)
4578 goto done;
4579 } else {
4580 path = strdup(argv[0]);
4581 if (path == NULL) {
4582 error = got_error_from_errno("strdup");
4583 goto done;
4586 } else if (argc != 0)
4587 usage_log();
4589 if (repo_path == NULL) {
4590 repo_path = worktree ?
4591 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4593 if (repo_path == NULL) {
4594 error = got_error_from_errno("strdup");
4595 goto done;
4598 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4599 if (error != NULL)
4600 goto done;
4602 error = apply_unveil(got_repo_get_path(repo), 1,
4603 worktree ? got_worktree_get_root_path(worktree) : NULL);
4604 if (error)
4605 goto done;
4607 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4608 if (error)
4609 goto done;
4611 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4612 if (error)
4613 goto done;
4615 if (start_commit == NULL) {
4616 struct got_reference *head_ref;
4617 struct got_commit_object *commit = NULL;
4618 error = got_ref_open(&head_ref, repo,
4619 worktree ? got_worktree_get_head_ref_name(worktree)
4620 : GOT_REF_HEAD, 0);
4621 if (error != NULL)
4622 goto done;
4623 error = got_ref_resolve(&start_id, repo, head_ref);
4624 got_ref_close(head_ref);
4625 if (error != NULL)
4626 goto done;
4627 error = got_object_open_as_commit(&commit, repo,
4628 start_id);
4629 if (error != NULL)
4630 goto done;
4631 got_object_commit_close(commit);
4632 } else {
4633 error = got_repo_match_object_id(&start_id, NULL,
4634 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4635 if (error != NULL)
4636 goto done;
4638 if (end_commit != NULL) {
4639 error = got_repo_match_object_id(&end_id, NULL,
4640 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4641 if (error != NULL)
4642 goto done;
4645 if (worktree) {
4647 * If a path was specified on the command line it was resolved
4648 * to a path in the work tree above. Prepend the work tree's
4649 * path prefix to obtain the corresponding in-repository path.
4651 if (path) {
4652 const char *prefix;
4653 prefix = got_worktree_get_path_prefix(worktree);
4654 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4655 (path[0] != '\0') ? "/" : "", path) == -1) {
4656 error = got_error_from_errno("asprintf");
4657 goto done;
4660 } else
4661 error = got_repo_map_path(&in_repo_path, repo,
4662 path ? path : "");
4663 if (error != NULL)
4664 goto done;
4665 if (in_repo_path) {
4666 free(path);
4667 path = in_repo_path;
4670 if (worktree) {
4671 /* Release work tree lock. */
4672 got_worktree_close(worktree);
4673 worktree = NULL;
4676 if (search_pattern && show_patch) {
4677 tmpfile = got_opentemp();
4678 if (tmpfile == NULL) {
4679 error = got_error_from_errno("got_opentemp");
4680 goto done;
4684 error = print_commits(start_id, end_id, repo, path ? path : "",
4685 show_changed_paths, show_diffstat, show_patch, search_pattern,
4686 diff_context, limit, log_branches, reverse_display_order,
4687 refs_idmap, one_line, tmpfile);
4688 done:
4689 free(path);
4690 free(repo_path);
4691 free(cwd);
4692 if (worktree)
4693 got_worktree_close(worktree);
4694 if (repo) {
4695 const struct got_error *close_err = got_repo_close(repo);
4696 if (error == NULL)
4697 error = close_err;
4699 if (pack_fds) {
4700 const struct got_error *pack_err =
4701 got_repo_pack_fds_close(pack_fds);
4702 if (error == NULL)
4703 error = pack_err;
4705 if (refs_idmap)
4706 got_reflist_object_id_map_free(refs_idmap);
4707 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4708 error = got_error_from_errno("fclose");
4709 got_ref_list_free(&refs);
4710 return error;
4713 __dead static void
4714 usage_diff(void)
4716 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4717 "[-r repository-path] [object1 object2 | path ...]\n",
4718 getprogname());
4719 exit(1);
4722 struct print_diff_arg {
4723 struct got_repository *repo;
4724 struct got_worktree *worktree;
4725 struct got_diffstat_cb_arg *diffstat;
4726 int diff_context;
4727 const char *id_str;
4728 int header_shown;
4729 int diff_staged;
4730 enum got_diff_algorithm diff_algo;
4731 int ignore_whitespace;
4732 int force_text_diff;
4733 int show_diffstat;
4734 FILE *f1;
4735 FILE *f2;
4736 FILE *outfile;
4740 * Create a file which contains the target path of a symlink so we can feed
4741 * it as content to the diff engine.
4743 static const struct got_error *
4744 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4745 const char *abspath)
4747 const struct got_error *err = NULL;
4748 char target_path[PATH_MAX];
4749 ssize_t target_len, outlen;
4751 *fd = -1;
4753 if (dirfd != -1) {
4754 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4755 if (target_len == -1)
4756 return got_error_from_errno2("readlinkat", abspath);
4757 } else {
4758 target_len = readlink(abspath, target_path, PATH_MAX);
4759 if (target_len == -1)
4760 return got_error_from_errno2("readlink", abspath);
4763 *fd = got_opentempfd();
4764 if (*fd == -1)
4765 return got_error_from_errno("got_opentempfd");
4767 outlen = write(*fd, target_path, target_len);
4768 if (outlen == -1) {
4769 err = got_error_from_errno("got_opentempfd");
4770 goto done;
4773 if (lseek(*fd, 0, SEEK_SET) == -1) {
4774 err = got_error_from_errno2("lseek", abspath);
4775 goto done;
4777 done:
4778 if (err) {
4779 close(*fd);
4780 *fd = -1;
4782 return err;
4785 static const struct got_error *
4786 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4787 const char *path, struct got_object_id *blob_id,
4788 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4789 int dirfd, const char *de_name)
4791 struct print_diff_arg *a = arg;
4792 const struct got_error *err = NULL;
4793 struct got_blob_object *blob1 = NULL;
4794 int fd = -1, fd1 = -1, fd2 = -1;
4795 FILE *f2 = NULL;
4796 char *abspath = NULL, *label1 = NULL;
4797 struct stat sb;
4798 off_t size1 = 0;
4799 int f2_exists = 0;
4801 memset(&sb, 0, sizeof(sb));
4803 if (a->diff_staged) {
4804 if (staged_status != GOT_STATUS_MODIFY &&
4805 staged_status != GOT_STATUS_ADD &&
4806 staged_status != GOT_STATUS_DELETE)
4807 return NULL;
4808 } else {
4809 if (staged_status == GOT_STATUS_DELETE)
4810 return NULL;
4811 if (status == GOT_STATUS_NONEXISTENT)
4812 return got_error_set_errno(ENOENT, path);
4813 if (status != GOT_STATUS_MODIFY &&
4814 status != GOT_STATUS_ADD &&
4815 status != GOT_STATUS_DELETE &&
4816 status != GOT_STATUS_CONFLICT)
4817 return NULL;
4820 err = got_opentemp_truncate(a->f1);
4821 if (err)
4822 return got_error_from_errno("got_opentemp_truncate");
4823 err = got_opentemp_truncate(a->f2);
4824 if (err)
4825 return got_error_from_errno("got_opentemp_truncate");
4827 if (!a->header_shown) {
4828 if (fprintf(a->outfile, "diff %s%s\n",
4829 a->diff_staged ? "-s " : "",
4830 got_worktree_get_root_path(a->worktree)) < 0) {
4831 err = got_error_from_errno("fprintf");
4832 goto done;
4834 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4835 err = got_error_from_errno("fprintf");
4836 goto done;
4838 if (fprintf(a->outfile, "path + %s%s\n",
4839 got_worktree_get_root_path(a->worktree),
4840 a->diff_staged ? " (staged changes)" : "") < 0) {
4841 err = got_error_from_errno("fprintf");
4842 goto done;
4844 a->header_shown = 1;
4847 if (a->diff_staged) {
4848 const char *label1 = NULL, *label2 = NULL;
4849 switch (staged_status) {
4850 case GOT_STATUS_MODIFY:
4851 label1 = path;
4852 label2 = path;
4853 break;
4854 case GOT_STATUS_ADD:
4855 label2 = path;
4856 break;
4857 case GOT_STATUS_DELETE:
4858 label1 = path;
4859 break;
4860 default:
4861 return got_error(GOT_ERR_FILE_STATUS);
4863 fd1 = got_opentempfd();
4864 if (fd1 == -1) {
4865 err = got_error_from_errno("got_opentempfd");
4866 goto done;
4868 fd2 = got_opentempfd();
4869 if (fd2 == -1) {
4870 err = got_error_from_errno("got_opentempfd");
4871 goto done;
4873 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4874 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4875 a->diff_algo, a->diff_context, a->ignore_whitespace,
4876 a->force_text_diff, a->show_diffstat, a->diffstat, a->repo,
4877 a->outfile);
4878 goto done;
4881 fd1 = got_opentempfd();
4882 if (fd1 == -1) {
4883 err = got_error_from_errno("got_opentempfd");
4884 goto done;
4887 if (staged_status == GOT_STATUS_ADD ||
4888 staged_status == GOT_STATUS_MODIFY) {
4889 char *id_str;
4890 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4891 8192, fd1);
4892 if (err)
4893 goto done;
4894 err = got_object_id_str(&id_str, staged_blob_id);
4895 if (err)
4896 goto done;
4897 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4898 err = got_error_from_errno("asprintf");
4899 free(id_str);
4900 goto done;
4902 free(id_str);
4903 } else if (status != GOT_STATUS_ADD) {
4904 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4905 fd1);
4906 if (err)
4907 goto done;
4910 if (status != GOT_STATUS_DELETE) {
4911 if (asprintf(&abspath, "%s/%s",
4912 got_worktree_get_root_path(a->worktree), path) == -1) {
4913 err = got_error_from_errno("asprintf");
4914 goto done;
4917 if (dirfd != -1) {
4918 fd = openat(dirfd, de_name,
4919 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4920 if (fd == -1) {
4921 if (!got_err_open_nofollow_on_symlink()) {
4922 err = got_error_from_errno2("openat",
4923 abspath);
4924 goto done;
4926 err = get_symlink_target_file(&fd, dirfd,
4927 de_name, abspath);
4928 if (err)
4929 goto done;
4931 } else {
4932 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4933 if (fd == -1) {
4934 if (!got_err_open_nofollow_on_symlink()) {
4935 err = got_error_from_errno2("open",
4936 abspath);
4937 goto done;
4939 err = get_symlink_target_file(&fd, dirfd,
4940 de_name, abspath);
4941 if (err)
4942 goto done;
4945 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4946 err = got_error_from_errno2("fstatat", abspath);
4947 goto done;
4949 f2 = fdopen(fd, "r");
4950 if (f2 == NULL) {
4951 err = got_error_from_errno2("fdopen", abspath);
4952 goto done;
4954 fd = -1;
4955 f2_exists = 1;
4958 if (blob1) {
4959 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4960 a->f1, blob1);
4961 if (err)
4962 goto done;
4965 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4966 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4967 a->ignore_whitespace, a->force_text_diff, a->show_diffstat,
4968 a->diffstat, a->outfile);
4969 done:
4970 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4971 err = got_error_from_errno("close");
4972 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4973 err = got_error_from_errno("close");
4974 if (blob1)
4975 got_object_blob_close(blob1);
4976 if (fd != -1 && close(fd) == -1 && err == NULL)
4977 err = got_error_from_errno("close");
4978 if (f2 && fclose(f2) == EOF && err == NULL)
4979 err = got_error_from_errno("fclose");
4980 free(abspath);
4981 return err;
4984 static const struct got_error *
4985 printfile(FILE *f)
4987 char buf[8192];
4988 size_t r;
4990 if (fseeko(f, 0L, SEEK_SET) == -1)
4991 return got_error_from_errno("fseek");
4993 for (;;) {
4994 r = fread(buf, 1, sizeof(buf), f);
4995 if (r == 0) {
4996 if (ferror(f))
4997 return got_error_from_errno("fread");
4998 if (feof(f))
4999 break;
5001 if (fwrite(buf, 1, r, stdout) != r)
5002 return got_ferror(stdout, GOT_ERR_IO);
5005 return NULL;
5008 static const struct got_error *
5009 cmd_diff(int argc, char *argv[])
5011 const struct got_error *error;
5012 struct got_repository *repo = NULL;
5013 struct got_worktree *worktree = NULL;
5014 char *cwd = NULL, *repo_path = NULL;
5015 const char *commit_args[2] = { NULL, NULL };
5016 int ncommit_args = 0;
5017 struct got_object_id *ids[2] = { NULL, NULL };
5018 char *labels[2] = { NULL, NULL };
5019 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5020 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5021 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5022 const char *errstr;
5023 struct got_reflist_head refs;
5024 struct got_pathlist_head diffstat_paths, paths;
5025 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5026 int fd1 = -1, fd2 = -1;
5027 int *pack_fds = NULL;
5028 struct got_diffstat_cb_arg dsa;
5030 memset(&dsa, 0, sizeof(dsa));
5032 TAILQ_INIT(&refs);
5033 TAILQ_INIT(&paths);
5034 TAILQ_INIT(&diffstat_paths);
5036 #ifndef PROFILE
5037 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5038 NULL) == -1)
5039 err(1, "pledge");
5040 #endif
5042 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5043 switch (ch) {
5044 case 'a':
5045 force_text_diff = 1;
5046 break;
5047 case 'C':
5048 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5049 &errstr);
5050 if (errstr != NULL)
5051 errx(1, "number of context lines is %s: %s",
5052 errstr, optarg);
5053 break;
5054 case 'c':
5055 if (ncommit_args >= 2)
5056 errx(1, "too many -c options used");
5057 commit_args[ncommit_args++] = optarg;
5058 break;
5059 case 'd':
5060 show_diffstat = 1;
5061 break;
5062 case 'P':
5063 force_path = 1;
5064 break;
5065 case 'r':
5066 repo_path = realpath(optarg, NULL);
5067 if (repo_path == NULL)
5068 return got_error_from_errno2("realpath",
5069 optarg);
5070 got_path_strip_trailing_slashes(repo_path);
5071 rflag = 1;
5072 break;
5073 case 's':
5074 diff_staged = 1;
5075 break;
5076 case 'w':
5077 ignore_whitespace = 1;
5078 break;
5079 default:
5080 usage_diff();
5081 /* NOTREACHED */
5085 argc -= optind;
5086 argv += optind;
5088 cwd = getcwd(NULL, 0);
5089 if (cwd == NULL) {
5090 error = got_error_from_errno("getcwd");
5091 goto done;
5094 error = got_repo_pack_fds_open(&pack_fds);
5095 if (error != NULL)
5096 goto done;
5098 if (repo_path == NULL) {
5099 error = got_worktree_open(&worktree, cwd);
5100 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5101 goto done;
5102 else
5103 error = NULL;
5104 if (worktree) {
5105 repo_path =
5106 strdup(got_worktree_get_repo_path(worktree));
5107 if (repo_path == NULL) {
5108 error = got_error_from_errno("strdup");
5109 goto done;
5111 } else {
5112 repo_path = strdup(cwd);
5113 if (repo_path == NULL) {
5114 error = got_error_from_errno("strdup");
5115 goto done;
5120 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5121 free(repo_path);
5122 if (error != NULL)
5123 goto done;
5125 if (show_diffstat) {
5126 dsa.paths = &diffstat_paths;
5127 dsa.force_text = force_text_diff;
5128 dsa.ignore_ws = ignore_whitespace;
5129 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5132 if (rflag || worktree == NULL || ncommit_args > 0) {
5133 if (force_path) {
5134 error = got_error_msg(GOT_ERR_NOT_IMPL,
5135 "-P option can only be used when diffing "
5136 "a work tree");
5137 goto done;
5139 if (diff_staged) {
5140 error = got_error_msg(GOT_ERR_NOT_IMPL,
5141 "-s option can only be used when diffing "
5142 "a work tree");
5143 goto done;
5147 error = apply_unveil(got_repo_get_path(repo), 1,
5148 worktree ? got_worktree_get_root_path(worktree) : NULL);
5149 if (error)
5150 goto done;
5152 if ((!force_path && argc == 2) || ncommit_args > 0) {
5153 int obj_type = (ncommit_args > 0 ?
5154 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5155 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5156 NULL);
5157 if (error)
5158 goto done;
5159 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5160 const char *arg;
5161 if (ncommit_args > 0)
5162 arg = commit_args[i];
5163 else
5164 arg = argv[i];
5165 error = got_repo_match_object_id(&ids[i], &labels[i],
5166 arg, obj_type, &refs, repo);
5167 if (error) {
5168 if (error->code != GOT_ERR_NOT_REF &&
5169 error->code != GOT_ERR_NO_OBJ)
5170 goto done;
5171 if (ncommit_args > 0)
5172 goto done;
5173 error = NULL;
5174 break;
5179 f1 = got_opentemp();
5180 if (f1 == NULL) {
5181 error = got_error_from_errno("got_opentemp");
5182 goto done;
5185 f2 = got_opentemp();
5186 if (f2 == NULL) {
5187 error = got_error_from_errno("got_opentemp");
5188 goto done;
5191 outfile = got_opentemp();
5192 if (outfile == NULL) {
5193 error = got_error_from_errno("got_opentemp");
5194 goto done;
5197 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5198 struct print_diff_arg arg;
5199 char *id_str;
5201 if (worktree == NULL) {
5202 if (argc == 2 && ids[0] == NULL) {
5203 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5204 goto done;
5205 } else if (argc == 2 && ids[1] == NULL) {
5206 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5207 goto done;
5208 } else if (argc > 0) {
5209 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5210 "%s", "specified paths cannot be resolved");
5211 goto done;
5212 } else {
5213 error = got_error(GOT_ERR_NOT_WORKTREE);
5214 goto done;
5218 error = get_worktree_paths_from_argv(&paths, argc, argv,
5219 worktree);
5220 if (error)
5221 goto done;
5223 error = got_object_id_str(&id_str,
5224 got_worktree_get_base_commit_id(worktree));
5225 if (error)
5226 goto done;
5227 arg.repo = repo;
5228 arg.worktree = worktree;
5229 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5230 arg.diff_context = diff_context;
5231 arg.id_str = id_str;
5232 arg.header_shown = 0;
5233 arg.diff_staged = diff_staged;
5234 arg.ignore_whitespace = ignore_whitespace;
5235 arg.force_text_diff = force_text_diff;
5236 arg.show_diffstat = show_diffstat;
5237 arg.diffstat = &dsa;
5238 arg.f1 = f1;
5239 arg.f2 = f2;
5240 arg.outfile = outfile;
5242 error = got_worktree_status(worktree, &paths, repo, 0,
5243 print_diff, &arg, check_cancelled, NULL);
5244 free(id_str);
5245 if (error)
5246 goto done;
5248 if (show_diffstat && dsa.nfiles > 0) {
5249 char *header;
5251 if (asprintf(&header, "diffstat %s%s",
5252 diff_staged ? "-s " : "",
5253 got_worktree_get_root_path(worktree)) == -1) {
5254 error = got_error_from_errno("asprintf");
5255 goto done;
5258 error = print_diffstat(&dsa, &diffstat_paths, header);
5259 free(header);
5260 if (error)
5261 goto done;
5264 error = printfile(outfile);
5265 goto done;
5268 if (ncommit_args == 1) {
5269 struct got_commit_object *commit;
5270 error = got_object_open_as_commit(&commit, repo, ids[0]);
5271 if (error)
5272 goto done;
5274 labels[1] = labels[0];
5275 ids[1] = ids[0];
5276 if (got_object_commit_get_nparents(commit) > 0) {
5277 const struct got_object_id_queue *pids;
5278 struct got_object_qid *pid;
5279 pids = got_object_commit_get_parent_ids(commit);
5280 pid = STAILQ_FIRST(pids);
5281 ids[0] = got_object_id_dup(&pid->id);
5282 if (ids[0] == NULL) {
5283 error = got_error_from_errno(
5284 "got_object_id_dup");
5285 got_object_commit_close(commit);
5286 goto done;
5288 error = got_object_id_str(&labels[0], ids[0]);
5289 if (error) {
5290 got_object_commit_close(commit);
5291 goto done;
5293 } else {
5294 ids[0] = NULL;
5295 labels[0] = strdup("/dev/null");
5296 if (labels[0] == NULL) {
5297 error = got_error_from_errno("strdup");
5298 got_object_commit_close(commit);
5299 goto done;
5303 got_object_commit_close(commit);
5306 if (ncommit_args == 0 && argc > 2) {
5307 error = got_error_msg(GOT_ERR_BAD_PATH,
5308 "path arguments cannot be used when diffing two objects");
5309 goto done;
5312 if (ids[0]) {
5313 error = got_object_get_type(&type1, repo, ids[0]);
5314 if (error)
5315 goto done;
5318 error = got_object_get_type(&type2, repo, ids[1]);
5319 if (error)
5320 goto done;
5321 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5322 error = got_error(GOT_ERR_OBJ_TYPE);
5323 goto done;
5325 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5326 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5327 "path arguments cannot be used when diffing blobs");
5328 goto done;
5331 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5332 char *in_repo_path;
5333 struct got_pathlist_entry *new;
5334 if (worktree) {
5335 const char *prefix;
5336 char *p;
5337 error = got_worktree_resolve_path(&p, worktree,
5338 argv[i]);
5339 if (error)
5340 goto done;
5341 prefix = got_worktree_get_path_prefix(worktree);
5342 while (prefix[0] == '/')
5343 prefix++;
5344 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5345 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5346 p) == -1) {
5347 error = got_error_from_errno("asprintf");
5348 free(p);
5349 goto done;
5351 free(p);
5352 } else {
5353 char *mapped_path, *s;
5354 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5355 if (error)
5356 goto done;
5357 s = mapped_path;
5358 while (s[0] == '/')
5359 s++;
5360 in_repo_path = strdup(s);
5361 if (in_repo_path == NULL) {
5362 error = got_error_from_errno("asprintf");
5363 free(mapped_path);
5364 goto done;
5366 free(mapped_path);
5369 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5370 if (error || new == NULL /* duplicate */)
5371 free(in_repo_path);
5372 if (error)
5373 goto done;
5376 if (worktree) {
5377 /* Release work tree lock. */
5378 got_worktree_close(worktree);
5379 worktree = NULL;
5382 fd1 = got_opentempfd();
5383 if (fd1 == -1) {
5384 error = got_error_from_errno("got_opentempfd");
5385 goto done;
5388 fd2 = got_opentempfd();
5389 if (fd2 == -1) {
5390 error = got_error_from_errno("got_opentempfd");
5391 goto done;
5394 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5395 case GOT_OBJ_TYPE_BLOB:
5396 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5397 fd1, fd2, ids[0], ids[1], NULL, NULL,
5398 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5399 ignore_whitespace, force_text_diff, show_diffstat,
5400 show_diffstat ? &dsa : NULL, repo, outfile);
5401 break;
5402 case GOT_OBJ_TYPE_TREE:
5403 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5404 ids[0], ids[1], &paths, "", "",
5405 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5406 ignore_whitespace, force_text_diff, show_diffstat,
5407 show_diffstat ? &dsa : NULL, repo, outfile);
5408 break;
5409 case GOT_OBJ_TYPE_COMMIT:
5410 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5411 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5412 fd1, fd2, ids[0], ids[1], &paths,
5413 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5414 ignore_whitespace, force_text_diff, show_diffstat,
5415 show_diffstat ? &dsa : NULL, repo, outfile);
5416 break;
5417 default:
5418 error = got_error(GOT_ERR_OBJ_TYPE);
5420 if (error)
5421 goto done;
5423 if (show_diffstat && dsa.nfiles > 0) {
5424 char *header = NULL;
5426 if (asprintf(&header, "diffstat %s %s",
5427 labels[0], labels[1]) == -1) {
5428 error = got_error_from_errno("asprintf");
5429 goto done;
5432 error = print_diffstat(&dsa, &diffstat_paths, header);
5433 free(header);
5434 if (error)
5435 goto done;
5438 error = printfile(outfile);
5440 done:
5441 free(labels[0]);
5442 free(labels[1]);
5443 free(ids[0]);
5444 free(ids[1]);
5445 if (worktree)
5446 got_worktree_close(worktree);
5447 if (repo) {
5448 const struct got_error *close_err = got_repo_close(repo);
5449 if (error == NULL)
5450 error = close_err;
5452 if (pack_fds) {
5453 const struct got_error *pack_err =
5454 got_repo_pack_fds_close(pack_fds);
5455 if (error == NULL)
5456 error = pack_err;
5458 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5459 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5460 got_ref_list_free(&refs);
5461 if (outfile && fclose(outfile) == EOF && error == NULL)
5462 error = got_error_from_errno("fclose");
5463 if (f1 && fclose(f1) == EOF && error == NULL)
5464 error = got_error_from_errno("fclose");
5465 if (f2 && fclose(f2) == EOF && error == NULL)
5466 error = got_error_from_errno("fclose");
5467 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5468 error = got_error_from_errno("close");
5469 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5470 error = got_error_from_errno("close");
5471 return error;
5474 __dead static void
5475 usage_blame(void)
5477 fprintf(stderr,
5478 "usage: %s blame [-c commit] [-r repository-path] path\n",
5479 getprogname());
5480 exit(1);
5483 struct blame_line {
5484 int annotated;
5485 char *id_str;
5486 char *committer;
5487 char datebuf[11]; /* YYYY-MM-DD + NUL */
5490 struct blame_cb_args {
5491 struct blame_line *lines;
5492 int nlines;
5493 int nlines_prec;
5494 int lineno_cur;
5495 off_t *line_offsets;
5496 FILE *f;
5497 struct got_repository *repo;
5500 static const struct got_error *
5501 blame_cb(void *arg, int nlines, int lineno,
5502 struct got_commit_object *commit, struct got_object_id *id)
5504 const struct got_error *err = NULL;
5505 struct blame_cb_args *a = arg;
5506 struct blame_line *bline;
5507 char *line = NULL;
5508 size_t linesize = 0;
5509 off_t offset;
5510 struct tm tm;
5511 time_t committer_time;
5513 if (nlines != a->nlines ||
5514 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5515 return got_error(GOT_ERR_RANGE);
5517 if (sigint_received)
5518 return got_error(GOT_ERR_ITER_COMPLETED);
5520 if (lineno == -1)
5521 return NULL; /* no change in this commit */
5523 /* Annotate this line. */
5524 bline = &a->lines[lineno - 1];
5525 if (bline->annotated)
5526 return NULL;
5527 err = got_object_id_str(&bline->id_str, id);
5528 if (err)
5529 return err;
5531 bline->committer = strdup(got_object_commit_get_committer(commit));
5532 if (bline->committer == NULL) {
5533 err = got_error_from_errno("strdup");
5534 goto done;
5537 committer_time = got_object_commit_get_committer_time(commit);
5538 if (gmtime_r(&committer_time, &tm) == NULL)
5539 return got_error_from_errno("gmtime_r");
5540 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5541 &tm) == 0) {
5542 err = got_error(GOT_ERR_NO_SPACE);
5543 goto done;
5545 bline->annotated = 1;
5547 /* Print lines annotated so far. */
5548 bline = &a->lines[a->lineno_cur - 1];
5549 if (!bline->annotated)
5550 goto done;
5552 offset = a->line_offsets[a->lineno_cur - 1];
5553 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5554 err = got_error_from_errno("fseeko");
5555 goto done;
5558 while (a->lineno_cur <= a->nlines && bline->annotated) {
5559 char *smallerthan, *at, *nl, *committer;
5560 size_t len;
5562 if (getline(&line, &linesize, a->f) == -1) {
5563 if (ferror(a->f))
5564 err = got_error_from_errno("getline");
5565 break;
5568 committer = bline->committer;
5569 smallerthan = strchr(committer, '<');
5570 if (smallerthan && smallerthan[1] != '\0')
5571 committer = smallerthan + 1;
5572 at = strchr(committer, '@');
5573 if (at)
5574 *at = '\0';
5575 len = strlen(committer);
5576 if (len >= 9)
5577 committer[8] = '\0';
5579 nl = strchr(line, '\n');
5580 if (nl)
5581 *nl = '\0';
5582 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5583 bline->id_str, bline->datebuf, committer, line);
5585 a->lineno_cur++;
5586 bline = &a->lines[a->lineno_cur - 1];
5588 done:
5589 free(line);
5590 return err;
5593 static const struct got_error *
5594 cmd_blame(int argc, char *argv[])
5596 const struct got_error *error;
5597 struct got_repository *repo = NULL;
5598 struct got_worktree *worktree = NULL;
5599 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5600 char *link_target = NULL;
5601 struct got_object_id *obj_id = NULL;
5602 struct got_object_id *commit_id = NULL;
5603 struct got_commit_object *commit = NULL;
5604 struct got_blob_object *blob = NULL;
5605 char *commit_id_str = NULL;
5606 struct blame_cb_args bca;
5607 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5608 off_t filesize;
5609 int *pack_fds = NULL;
5610 FILE *f1 = NULL, *f2 = NULL;
5612 fd1 = got_opentempfd();
5613 if (fd1 == -1)
5614 return got_error_from_errno("got_opentempfd");
5616 memset(&bca, 0, sizeof(bca));
5618 #ifndef PROFILE
5619 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5620 NULL) == -1)
5621 err(1, "pledge");
5622 #endif
5624 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5625 switch (ch) {
5626 case 'c':
5627 commit_id_str = optarg;
5628 break;
5629 case 'r':
5630 repo_path = realpath(optarg, NULL);
5631 if (repo_path == NULL)
5632 return got_error_from_errno2("realpath",
5633 optarg);
5634 got_path_strip_trailing_slashes(repo_path);
5635 break;
5636 default:
5637 usage_blame();
5638 /* NOTREACHED */
5642 argc -= optind;
5643 argv += optind;
5645 if (argc == 1)
5646 path = argv[0];
5647 else
5648 usage_blame();
5650 cwd = getcwd(NULL, 0);
5651 if (cwd == NULL) {
5652 error = got_error_from_errno("getcwd");
5653 goto done;
5656 error = got_repo_pack_fds_open(&pack_fds);
5657 if (error != NULL)
5658 goto done;
5660 if (repo_path == NULL) {
5661 error = got_worktree_open(&worktree, cwd);
5662 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5663 goto done;
5664 else
5665 error = NULL;
5666 if (worktree) {
5667 repo_path =
5668 strdup(got_worktree_get_repo_path(worktree));
5669 if (repo_path == NULL) {
5670 error = got_error_from_errno("strdup");
5671 if (error)
5672 goto done;
5674 } else {
5675 repo_path = strdup(cwd);
5676 if (repo_path == NULL) {
5677 error = got_error_from_errno("strdup");
5678 goto done;
5683 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5684 if (error != NULL)
5685 goto done;
5687 if (worktree) {
5688 const char *prefix = got_worktree_get_path_prefix(worktree);
5689 char *p;
5691 error = got_worktree_resolve_path(&p, worktree, path);
5692 if (error)
5693 goto done;
5694 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5695 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5696 p) == -1) {
5697 error = got_error_from_errno("asprintf");
5698 free(p);
5699 goto done;
5701 free(p);
5702 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5703 } else {
5704 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5705 if (error)
5706 goto done;
5707 error = got_repo_map_path(&in_repo_path, repo, path);
5709 if (error)
5710 goto done;
5712 if (commit_id_str == NULL) {
5713 struct got_reference *head_ref;
5714 error = got_ref_open(&head_ref, repo, worktree ?
5715 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5716 if (error != NULL)
5717 goto done;
5718 error = got_ref_resolve(&commit_id, repo, head_ref);
5719 got_ref_close(head_ref);
5720 if (error != NULL)
5721 goto done;
5722 } else {
5723 struct got_reflist_head refs;
5724 TAILQ_INIT(&refs);
5725 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5726 NULL);
5727 if (error)
5728 goto done;
5729 error = got_repo_match_object_id(&commit_id, NULL,
5730 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5731 got_ref_list_free(&refs);
5732 if (error)
5733 goto done;
5736 if (worktree) {
5737 /* Release work tree lock. */
5738 got_worktree_close(worktree);
5739 worktree = NULL;
5742 error = got_object_open_as_commit(&commit, repo, commit_id);
5743 if (error)
5744 goto done;
5746 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5747 commit, repo);
5748 if (error)
5749 goto done;
5751 error = got_object_id_by_path(&obj_id, repo, commit,
5752 link_target ? link_target : in_repo_path);
5753 if (error)
5754 goto done;
5756 error = got_object_get_type(&obj_type, repo, obj_id);
5757 if (error)
5758 goto done;
5760 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5761 error = got_error_path(link_target ? link_target : in_repo_path,
5762 GOT_ERR_OBJ_TYPE);
5763 goto done;
5766 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5767 if (error)
5768 goto done;
5769 bca.f = got_opentemp();
5770 if (bca.f == NULL) {
5771 error = got_error_from_errno("got_opentemp");
5772 goto done;
5774 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5775 &bca.line_offsets, bca.f, blob);
5776 if (error || bca.nlines == 0)
5777 goto done;
5779 /* Don't include \n at EOF in the blame line count. */
5780 if (bca.line_offsets[bca.nlines - 1] == filesize)
5781 bca.nlines--;
5783 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5784 if (bca.lines == NULL) {
5785 error = got_error_from_errno("calloc");
5786 goto done;
5788 bca.lineno_cur = 1;
5789 bca.nlines_prec = 0;
5790 i = bca.nlines;
5791 while (i > 0) {
5792 i /= 10;
5793 bca.nlines_prec++;
5795 bca.repo = repo;
5797 fd2 = got_opentempfd();
5798 if (fd2 == -1) {
5799 error = got_error_from_errno("got_opentempfd");
5800 goto done;
5802 fd3 = got_opentempfd();
5803 if (fd3 == -1) {
5804 error = got_error_from_errno("got_opentempfd");
5805 goto done;
5807 f1 = got_opentemp();
5808 if (f1 == NULL) {
5809 error = got_error_from_errno("got_opentemp");
5810 goto done;
5812 f2 = got_opentemp();
5813 if (f2 == NULL) {
5814 error = got_error_from_errno("got_opentemp");
5815 goto done;
5817 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5818 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5819 check_cancelled, NULL, fd2, fd3, f1, f2);
5820 done:
5821 free(in_repo_path);
5822 free(link_target);
5823 free(repo_path);
5824 free(cwd);
5825 free(commit_id);
5826 free(obj_id);
5827 if (commit)
5828 got_object_commit_close(commit);
5830 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5831 error = got_error_from_errno("close");
5832 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5833 error = got_error_from_errno("close");
5834 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5835 error = got_error_from_errno("close");
5836 if (f1 && fclose(f1) == EOF && error == NULL)
5837 error = got_error_from_errno("fclose");
5838 if (f2 && fclose(f2) == EOF && error == NULL)
5839 error = got_error_from_errno("fclose");
5841 if (blob)
5842 got_object_blob_close(blob);
5843 if (worktree)
5844 got_worktree_close(worktree);
5845 if (repo) {
5846 const struct got_error *close_err = got_repo_close(repo);
5847 if (error == NULL)
5848 error = close_err;
5850 if (pack_fds) {
5851 const struct got_error *pack_err =
5852 got_repo_pack_fds_close(pack_fds);
5853 if (error == NULL)
5854 error = pack_err;
5856 if (bca.lines) {
5857 for (i = 0; i < bca.nlines; i++) {
5858 struct blame_line *bline = &bca.lines[i];
5859 free(bline->id_str);
5860 free(bline->committer);
5862 free(bca.lines);
5864 free(bca.line_offsets);
5865 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5866 error = got_error_from_errno("fclose");
5867 return error;
5870 __dead static void
5871 usage_tree(void)
5873 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5874 "[path]\n", getprogname());
5875 exit(1);
5878 static const struct got_error *
5879 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5880 const char *root_path, struct got_repository *repo)
5882 const struct got_error *err = NULL;
5883 int is_root_path = (strcmp(path, root_path) == 0);
5884 const char *modestr = "";
5885 mode_t mode = got_tree_entry_get_mode(te);
5886 char *link_target = NULL;
5888 path += strlen(root_path);
5889 while (path[0] == '/')
5890 path++;
5892 if (got_object_tree_entry_is_submodule(te))
5893 modestr = "$";
5894 else if (S_ISLNK(mode)) {
5895 int i;
5897 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5898 if (err)
5899 return err;
5900 for (i = 0; i < strlen(link_target); i++) {
5901 if (!isprint((unsigned char)link_target[i]))
5902 link_target[i] = '?';
5905 modestr = "@";
5907 else if (S_ISDIR(mode))
5908 modestr = "/";
5909 else if (mode & S_IXUSR)
5910 modestr = "*";
5912 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5913 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5914 link_target ? " -> ": "", link_target ? link_target : "");
5916 free(link_target);
5917 return NULL;
5920 static const struct got_error *
5921 print_tree(const char *path, struct got_commit_object *commit,
5922 int show_ids, int recurse, const char *root_path,
5923 struct got_repository *repo)
5925 const struct got_error *err = NULL;
5926 struct got_object_id *tree_id = NULL;
5927 struct got_tree_object *tree = NULL;
5928 int nentries, i;
5930 err = got_object_id_by_path(&tree_id, repo, commit, path);
5931 if (err)
5932 goto done;
5934 err = got_object_open_as_tree(&tree, repo, tree_id);
5935 if (err)
5936 goto done;
5937 nentries = got_object_tree_get_nentries(tree);
5938 for (i = 0; i < nentries; i++) {
5939 struct got_tree_entry *te;
5940 char *id = NULL;
5942 if (sigint_received || sigpipe_received)
5943 break;
5945 te = got_object_tree_get_entry(tree, i);
5946 if (show_ids) {
5947 char *id_str;
5948 err = got_object_id_str(&id_str,
5949 got_tree_entry_get_id(te));
5950 if (err)
5951 goto done;
5952 if (asprintf(&id, "%s ", id_str) == -1) {
5953 err = got_error_from_errno("asprintf");
5954 free(id_str);
5955 goto done;
5957 free(id_str);
5959 err = print_entry(te, id, path, root_path, repo);
5960 free(id);
5961 if (err)
5962 goto done;
5964 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5965 char *child_path;
5966 if (asprintf(&child_path, "%s%s%s", path,
5967 path[0] == '/' && path[1] == '\0' ? "" : "/",
5968 got_tree_entry_get_name(te)) == -1) {
5969 err = got_error_from_errno("asprintf");
5970 goto done;
5972 err = print_tree(child_path, commit, show_ids, 1,
5973 root_path, repo);
5974 free(child_path);
5975 if (err)
5976 goto done;
5979 done:
5980 if (tree)
5981 got_object_tree_close(tree);
5982 free(tree_id);
5983 return err;
5986 static const struct got_error *
5987 cmd_tree(int argc, char *argv[])
5989 const struct got_error *error;
5990 struct got_repository *repo = NULL;
5991 struct got_worktree *worktree = NULL;
5992 const char *path, *refname = NULL;
5993 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5994 struct got_object_id *commit_id = NULL;
5995 struct got_commit_object *commit = NULL;
5996 char *commit_id_str = NULL;
5997 int show_ids = 0, recurse = 0;
5998 int ch;
5999 int *pack_fds = NULL;
6001 #ifndef PROFILE
6002 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6003 NULL) == -1)
6004 err(1, "pledge");
6005 #endif
6007 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6008 switch (ch) {
6009 case 'c':
6010 commit_id_str = optarg;
6011 break;
6012 case 'i':
6013 show_ids = 1;
6014 break;
6015 case 'R':
6016 recurse = 1;
6017 break;
6018 case 'r':
6019 repo_path = realpath(optarg, NULL);
6020 if (repo_path == NULL)
6021 return got_error_from_errno2("realpath",
6022 optarg);
6023 got_path_strip_trailing_slashes(repo_path);
6024 break;
6025 default:
6026 usage_tree();
6027 /* NOTREACHED */
6031 argc -= optind;
6032 argv += optind;
6034 if (argc == 1)
6035 path = argv[0];
6036 else if (argc > 1)
6037 usage_tree();
6038 else
6039 path = NULL;
6041 cwd = getcwd(NULL, 0);
6042 if (cwd == NULL) {
6043 error = got_error_from_errno("getcwd");
6044 goto done;
6047 error = got_repo_pack_fds_open(&pack_fds);
6048 if (error != NULL)
6049 goto done;
6051 if (repo_path == NULL) {
6052 error = got_worktree_open(&worktree, cwd);
6053 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6054 goto done;
6055 else
6056 error = NULL;
6057 if (worktree) {
6058 repo_path =
6059 strdup(got_worktree_get_repo_path(worktree));
6060 if (repo_path == NULL)
6061 error = got_error_from_errno("strdup");
6062 if (error)
6063 goto done;
6064 } else {
6065 repo_path = strdup(cwd);
6066 if (repo_path == NULL) {
6067 error = got_error_from_errno("strdup");
6068 goto done;
6073 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6074 if (error != NULL)
6075 goto done;
6077 if (worktree) {
6078 const char *prefix = got_worktree_get_path_prefix(worktree);
6079 char *p;
6081 if (path == NULL)
6082 path = "";
6083 error = got_worktree_resolve_path(&p, worktree, path);
6084 if (error)
6085 goto done;
6086 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6087 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6088 p) == -1) {
6089 error = got_error_from_errno("asprintf");
6090 free(p);
6091 goto done;
6093 free(p);
6094 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6095 if (error)
6096 goto done;
6097 } else {
6098 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6099 if (error)
6100 goto done;
6101 if (path == NULL)
6102 path = "/";
6103 error = got_repo_map_path(&in_repo_path, repo, path);
6104 if (error != NULL)
6105 goto done;
6108 if (commit_id_str == NULL) {
6109 struct got_reference *head_ref;
6110 if (worktree)
6111 refname = got_worktree_get_head_ref_name(worktree);
6112 else
6113 refname = GOT_REF_HEAD;
6114 error = got_ref_open(&head_ref, repo, refname, 0);
6115 if (error != NULL)
6116 goto done;
6117 error = got_ref_resolve(&commit_id, repo, head_ref);
6118 got_ref_close(head_ref);
6119 if (error != NULL)
6120 goto done;
6121 } else {
6122 struct got_reflist_head refs;
6123 TAILQ_INIT(&refs);
6124 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6125 NULL);
6126 if (error)
6127 goto done;
6128 error = got_repo_match_object_id(&commit_id, NULL,
6129 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6130 got_ref_list_free(&refs);
6131 if (error)
6132 goto done;
6135 if (worktree) {
6136 /* Release work tree lock. */
6137 got_worktree_close(worktree);
6138 worktree = NULL;
6141 error = got_object_open_as_commit(&commit, repo, commit_id);
6142 if (error)
6143 goto done;
6145 error = print_tree(in_repo_path, commit, show_ids, recurse,
6146 in_repo_path, repo);
6147 done:
6148 free(in_repo_path);
6149 free(repo_path);
6150 free(cwd);
6151 free(commit_id);
6152 if (commit)
6153 got_object_commit_close(commit);
6154 if (worktree)
6155 got_worktree_close(worktree);
6156 if (repo) {
6157 const struct got_error *close_err = got_repo_close(repo);
6158 if (error == NULL)
6159 error = close_err;
6161 if (pack_fds) {
6162 const struct got_error *pack_err =
6163 got_repo_pack_fds_close(pack_fds);
6164 if (error == NULL)
6165 error = pack_err;
6167 return error;
6170 __dead static void
6171 usage_status(void)
6173 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6174 "[-s status-codes] [path ...]\n", getprogname());
6175 exit(1);
6178 struct got_status_arg {
6179 char *status_codes;
6180 int suppress;
6183 static const struct got_error *
6184 print_status(void *arg, unsigned char status, unsigned char staged_status,
6185 const char *path, struct got_object_id *blob_id,
6186 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6187 int dirfd, const char *de_name)
6189 struct got_status_arg *st = arg;
6191 if (status == staged_status && (status == GOT_STATUS_DELETE))
6192 status = GOT_STATUS_NO_CHANGE;
6193 if (st != NULL && st->status_codes) {
6194 size_t ncodes = strlen(st->status_codes);
6195 int i, j = 0;
6197 for (i = 0; i < ncodes ; i++) {
6198 if (st->suppress) {
6199 if (status == st->status_codes[i] ||
6200 staged_status == st->status_codes[i]) {
6201 j++;
6202 continue;
6204 } else {
6205 if (status == st->status_codes[i] ||
6206 staged_status == st->status_codes[i])
6207 break;
6211 if (st->suppress && j == 0)
6212 goto print;
6214 if (i == ncodes)
6215 return NULL;
6217 print:
6218 printf("%c%c %s\n", status, staged_status, path);
6219 return NULL;
6222 static const struct got_error *
6223 cmd_status(int argc, char *argv[])
6225 const struct got_error *error = NULL;
6226 struct got_repository *repo = NULL;
6227 struct got_worktree *worktree = NULL;
6228 struct got_status_arg st;
6229 char *cwd = NULL;
6230 struct got_pathlist_head paths;
6231 int ch, i, no_ignores = 0;
6232 int *pack_fds = NULL;
6234 TAILQ_INIT(&paths);
6236 memset(&st, 0, sizeof(st));
6237 st.status_codes = NULL;
6238 st.suppress = 0;
6240 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6241 switch (ch) {
6242 case 'I':
6243 no_ignores = 1;
6244 break;
6245 case 'S':
6246 if (st.status_codes != NULL && st.suppress == 0)
6247 option_conflict('S', 's');
6248 st.suppress = 1;
6249 /* fallthrough */
6250 case 's':
6251 for (i = 0; i < strlen(optarg); i++) {
6252 switch (optarg[i]) {
6253 case GOT_STATUS_MODIFY:
6254 case GOT_STATUS_ADD:
6255 case GOT_STATUS_DELETE:
6256 case GOT_STATUS_CONFLICT:
6257 case GOT_STATUS_MISSING:
6258 case GOT_STATUS_OBSTRUCTED:
6259 case GOT_STATUS_UNVERSIONED:
6260 case GOT_STATUS_MODE_CHANGE:
6261 case GOT_STATUS_NONEXISTENT:
6262 break;
6263 default:
6264 errx(1, "invalid status code '%c'",
6265 optarg[i]);
6268 if (ch == 's' && st.suppress)
6269 option_conflict('s', 'S');
6270 st.status_codes = optarg;
6271 break;
6272 default:
6273 usage_status();
6274 /* NOTREACHED */
6278 argc -= optind;
6279 argv += optind;
6281 #ifndef PROFILE
6282 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6283 NULL) == -1)
6284 err(1, "pledge");
6285 #endif
6286 cwd = getcwd(NULL, 0);
6287 if (cwd == NULL) {
6288 error = got_error_from_errno("getcwd");
6289 goto done;
6292 error = got_repo_pack_fds_open(&pack_fds);
6293 if (error != NULL)
6294 goto done;
6296 error = got_worktree_open(&worktree, cwd);
6297 if (error) {
6298 if (error->code == GOT_ERR_NOT_WORKTREE)
6299 error = wrap_not_worktree_error(error, "status", cwd);
6300 goto done;
6303 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6304 NULL, pack_fds);
6305 if (error != NULL)
6306 goto done;
6308 error = apply_unveil(got_repo_get_path(repo), 1,
6309 got_worktree_get_root_path(worktree));
6310 if (error)
6311 goto done;
6313 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6314 if (error)
6315 goto done;
6317 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6318 print_status, &st, check_cancelled, NULL);
6319 done:
6320 if (pack_fds) {
6321 const struct got_error *pack_err =
6322 got_repo_pack_fds_close(pack_fds);
6323 if (error == NULL)
6324 error = pack_err;
6327 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6328 free(cwd);
6329 return error;
6332 __dead static void
6333 usage_ref(void)
6335 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6336 "[-s reference] [name]\n", getprogname());
6337 exit(1);
6340 static const struct got_error *
6341 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6343 static const struct got_error *err = NULL;
6344 struct got_reflist_head refs;
6345 struct got_reflist_entry *re;
6347 TAILQ_INIT(&refs);
6348 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6349 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6350 repo);
6351 if (err)
6352 return err;
6354 TAILQ_FOREACH(re, &refs, entry) {
6355 char *refstr;
6356 refstr = got_ref_to_str(re->ref);
6357 if (refstr == NULL) {
6358 err = got_error_from_errno("got_ref_to_str");
6359 break;
6361 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6362 free(refstr);
6365 got_ref_list_free(&refs);
6366 return err;
6369 static const struct got_error *
6370 delete_ref_by_name(struct got_repository *repo, const char *refname)
6372 const struct got_error *err;
6373 struct got_reference *ref;
6375 err = got_ref_open(&ref, repo, refname, 0);
6376 if (err)
6377 return err;
6379 err = delete_ref(repo, ref);
6380 got_ref_close(ref);
6381 return err;
6384 static const struct got_error *
6385 add_ref(struct got_repository *repo, const char *refname, const char *target)
6387 const struct got_error *err = NULL;
6388 struct got_object_id *id = NULL;
6389 struct got_reference *ref = NULL;
6390 struct got_reflist_head refs;
6393 * Don't let the user create a reference name with a leading '-'.
6394 * While technically a valid reference name, this case is usually
6395 * an unintended typo.
6397 if (refname[0] == '-')
6398 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6400 TAILQ_INIT(&refs);
6401 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6402 if (err)
6403 goto done;
6404 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6405 &refs, repo);
6406 got_ref_list_free(&refs);
6407 if (err)
6408 goto done;
6410 err = got_ref_alloc(&ref, refname, id);
6411 if (err)
6412 goto done;
6414 err = got_ref_write(ref, repo);
6415 done:
6416 if (ref)
6417 got_ref_close(ref);
6418 free(id);
6419 return err;
6422 static const struct got_error *
6423 add_symref(struct got_repository *repo, const char *refname, const char *target)
6425 const struct got_error *err = NULL;
6426 struct got_reference *ref = NULL;
6427 struct got_reference *target_ref = NULL;
6430 * Don't let the user create a reference name with a leading '-'.
6431 * While technically a valid reference name, this case is usually
6432 * an unintended typo.
6434 if (refname[0] == '-')
6435 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6437 err = got_ref_open(&target_ref, repo, target, 0);
6438 if (err)
6439 return err;
6441 err = got_ref_alloc_symref(&ref, refname, target_ref);
6442 if (err)
6443 goto done;
6445 err = got_ref_write(ref, repo);
6446 done:
6447 if (target_ref)
6448 got_ref_close(target_ref);
6449 if (ref)
6450 got_ref_close(ref);
6451 return err;
6454 static const struct got_error *
6455 cmd_ref(int argc, char *argv[])
6457 const struct got_error *error = NULL;
6458 struct got_repository *repo = NULL;
6459 struct got_worktree *worktree = NULL;
6460 char *cwd = NULL, *repo_path = NULL;
6461 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6462 const char *obj_arg = NULL, *symref_target= NULL;
6463 char *refname = NULL;
6464 int *pack_fds = NULL;
6466 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6467 switch (ch) {
6468 case 'c':
6469 obj_arg = optarg;
6470 break;
6471 case 'd':
6472 do_delete = 1;
6473 break;
6474 case 'l':
6475 do_list = 1;
6476 break;
6477 case 'r':
6478 repo_path = realpath(optarg, NULL);
6479 if (repo_path == NULL)
6480 return got_error_from_errno2("realpath",
6481 optarg);
6482 got_path_strip_trailing_slashes(repo_path);
6483 break;
6484 case 's':
6485 symref_target = optarg;
6486 break;
6487 case 't':
6488 sort_by_time = 1;
6489 break;
6490 default:
6491 usage_ref();
6492 /* NOTREACHED */
6496 if (obj_arg && do_list)
6497 option_conflict('c', 'l');
6498 if (obj_arg && do_delete)
6499 option_conflict('c', 'd');
6500 if (obj_arg && symref_target)
6501 option_conflict('c', 's');
6502 if (symref_target && do_delete)
6503 option_conflict('s', 'd');
6504 if (symref_target && do_list)
6505 option_conflict('s', 'l');
6506 if (do_delete && do_list)
6507 option_conflict('d', 'l');
6508 if (sort_by_time && !do_list)
6509 errx(1, "-t option requires -l option");
6511 argc -= optind;
6512 argv += optind;
6514 if (do_list) {
6515 if (argc != 0 && argc != 1)
6516 usage_ref();
6517 if (argc == 1) {
6518 refname = strdup(argv[0]);
6519 if (refname == NULL) {
6520 error = got_error_from_errno("strdup");
6521 goto done;
6524 } else {
6525 if (argc != 1)
6526 usage_ref();
6527 refname = strdup(argv[0]);
6528 if (refname == NULL) {
6529 error = got_error_from_errno("strdup");
6530 goto done;
6534 if (refname)
6535 got_path_strip_trailing_slashes(refname);
6537 #ifndef PROFILE
6538 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6539 "sendfd unveil", NULL) == -1)
6540 err(1, "pledge");
6541 #endif
6542 cwd = getcwd(NULL, 0);
6543 if (cwd == NULL) {
6544 error = got_error_from_errno("getcwd");
6545 goto done;
6548 error = got_repo_pack_fds_open(&pack_fds);
6549 if (error != NULL)
6550 goto done;
6552 if (repo_path == NULL) {
6553 error = got_worktree_open(&worktree, cwd);
6554 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6555 goto done;
6556 else
6557 error = NULL;
6558 if (worktree) {
6559 repo_path =
6560 strdup(got_worktree_get_repo_path(worktree));
6561 if (repo_path == NULL)
6562 error = got_error_from_errno("strdup");
6563 if (error)
6564 goto done;
6565 } else {
6566 repo_path = strdup(cwd);
6567 if (repo_path == NULL) {
6568 error = got_error_from_errno("strdup");
6569 goto done;
6574 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6575 if (error != NULL)
6576 goto done;
6578 #ifndef PROFILE
6579 if (do_list) {
6580 /* Remove "cpath" promise. */
6581 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6582 NULL) == -1)
6583 err(1, "pledge");
6585 #endif
6587 error = apply_unveil(got_repo_get_path(repo), do_list,
6588 worktree ? got_worktree_get_root_path(worktree) : NULL);
6589 if (error)
6590 goto done;
6592 if (do_list)
6593 error = list_refs(repo, refname, sort_by_time);
6594 else if (do_delete)
6595 error = delete_ref_by_name(repo, refname);
6596 else if (symref_target)
6597 error = add_symref(repo, refname, symref_target);
6598 else {
6599 if (obj_arg == NULL)
6600 usage_ref();
6601 error = add_ref(repo, refname, obj_arg);
6603 done:
6604 free(refname);
6605 if (repo) {
6606 const struct got_error *close_err = got_repo_close(repo);
6607 if (error == NULL)
6608 error = close_err;
6610 if (worktree)
6611 got_worktree_close(worktree);
6612 if (pack_fds) {
6613 const struct got_error *pack_err =
6614 got_repo_pack_fds_close(pack_fds);
6615 if (error == NULL)
6616 error = pack_err;
6618 free(cwd);
6619 free(repo_path);
6620 return error;
6623 __dead static void
6624 usage_branch(void)
6626 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6627 "[-r repository-path] [name]\n", getprogname());
6628 exit(1);
6631 static const struct got_error *
6632 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6633 struct got_reference *ref)
6635 const struct got_error *err = NULL;
6636 const char *refname, *marker = " ";
6637 char *refstr;
6639 refname = got_ref_get_name(ref);
6640 if (worktree && strcmp(refname,
6641 got_worktree_get_head_ref_name(worktree)) == 0) {
6642 struct got_object_id *id = NULL;
6644 err = got_ref_resolve(&id, repo, ref);
6645 if (err)
6646 return err;
6647 if (got_object_id_cmp(id,
6648 got_worktree_get_base_commit_id(worktree)) == 0)
6649 marker = "* ";
6650 else
6651 marker = "~ ";
6652 free(id);
6655 if (strncmp(refname, "refs/heads/", 11) == 0)
6656 refname += 11;
6657 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6658 refname += 18;
6659 if (strncmp(refname, "refs/remotes/", 13) == 0)
6660 refname += 13;
6662 refstr = got_ref_to_str(ref);
6663 if (refstr == NULL)
6664 return got_error_from_errno("got_ref_to_str");
6666 printf("%s%s: %s\n", marker, refname, refstr);
6667 free(refstr);
6668 return NULL;
6671 static const struct got_error *
6672 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6674 const char *refname;
6676 if (worktree == NULL)
6677 return got_error(GOT_ERR_NOT_WORKTREE);
6679 refname = got_worktree_get_head_ref_name(worktree);
6681 if (strncmp(refname, "refs/heads/", 11) == 0)
6682 refname += 11;
6683 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6684 refname += 18;
6686 printf("%s\n", refname);
6688 return NULL;
6691 static const struct got_error *
6692 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6693 int sort_by_time)
6695 static const struct got_error *err = NULL;
6696 struct got_reflist_head refs;
6697 struct got_reflist_entry *re;
6698 struct got_reference *temp_ref = NULL;
6699 int rebase_in_progress, histedit_in_progress;
6701 TAILQ_INIT(&refs);
6703 if (worktree) {
6704 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6705 worktree);
6706 if (err)
6707 return err;
6709 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6710 worktree);
6711 if (err)
6712 return err;
6714 if (rebase_in_progress || histedit_in_progress) {
6715 err = got_ref_open(&temp_ref, repo,
6716 got_worktree_get_head_ref_name(worktree), 0);
6717 if (err)
6718 return err;
6719 list_branch(repo, worktree, temp_ref);
6720 got_ref_close(temp_ref);
6724 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6725 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6726 repo);
6727 if (err)
6728 return err;
6730 TAILQ_FOREACH(re, &refs, entry)
6731 list_branch(repo, worktree, re->ref);
6733 got_ref_list_free(&refs);
6735 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6736 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6737 repo);
6738 if (err)
6739 return err;
6741 TAILQ_FOREACH(re, &refs, entry)
6742 list_branch(repo, worktree, re->ref);
6744 got_ref_list_free(&refs);
6746 return NULL;
6749 static const struct got_error *
6750 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6751 const char *branch_name)
6753 const struct got_error *err = NULL;
6754 struct got_reference *ref = NULL;
6755 char *refname, *remote_refname = NULL;
6757 if (strncmp(branch_name, "refs/", 5) == 0)
6758 branch_name += 5;
6759 if (strncmp(branch_name, "heads/", 6) == 0)
6760 branch_name += 6;
6761 else if (strncmp(branch_name, "remotes/", 8) == 0)
6762 branch_name += 8;
6764 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6765 return got_error_from_errno("asprintf");
6767 if (asprintf(&remote_refname, "refs/remotes/%s",
6768 branch_name) == -1) {
6769 err = got_error_from_errno("asprintf");
6770 goto done;
6773 err = got_ref_open(&ref, repo, refname, 0);
6774 if (err) {
6775 const struct got_error *err2;
6776 if (err->code != GOT_ERR_NOT_REF)
6777 goto done;
6779 * Keep 'err' intact such that if neither branch exists
6780 * we report "refs/heads" rather than "refs/remotes" in
6781 * our error message.
6783 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6784 if (err2)
6785 goto done;
6786 err = NULL;
6789 if (worktree &&
6790 strcmp(got_worktree_get_head_ref_name(worktree),
6791 got_ref_get_name(ref)) == 0) {
6792 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6793 "will not delete this work tree's current branch");
6794 goto done;
6797 err = delete_ref(repo, ref);
6798 done:
6799 if (ref)
6800 got_ref_close(ref);
6801 free(refname);
6802 free(remote_refname);
6803 return err;
6806 static const struct got_error *
6807 add_branch(struct got_repository *repo, const char *branch_name,
6808 struct got_object_id *base_commit_id)
6810 const struct got_error *err = NULL;
6811 struct got_reference *ref = NULL;
6812 char *refname = NULL;
6815 * Don't let the user create a branch name with a leading '-'.
6816 * While technically a valid reference name, this case is usually
6817 * an unintended typo.
6819 if (branch_name[0] == '-')
6820 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6822 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6823 branch_name += 11;
6825 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6826 err = got_error_from_errno("asprintf");
6827 goto done;
6830 err = got_ref_open(&ref, repo, refname, 0);
6831 if (err == NULL) {
6832 err = got_error(GOT_ERR_BRANCH_EXISTS);
6833 goto done;
6834 } else if (err->code != GOT_ERR_NOT_REF)
6835 goto done;
6837 err = got_ref_alloc(&ref, refname, base_commit_id);
6838 if (err)
6839 goto done;
6841 err = got_ref_write(ref, repo);
6842 done:
6843 if (ref)
6844 got_ref_close(ref);
6845 free(refname);
6846 return err;
6849 static const struct got_error *
6850 cmd_branch(int argc, char *argv[])
6852 const struct got_error *error = NULL;
6853 struct got_repository *repo = NULL;
6854 struct got_worktree *worktree = NULL;
6855 char *cwd = NULL, *repo_path = NULL;
6856 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6857 const char *delref = NULL, *commit_id_arg = NULL;
6858 struct got_reference *ref = NULL;
6859 struct got_pathlist_head paths;
6860 struct got_object_id *commit_id = NULL;
6861 char *commit_id_str = NULL;
6862 int *pack_fds = NULL;
6864 TAILQ_INIT(&paths);
6866 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6867 switch (ch) {
6868 case 'c':
6869 commit_id_arg = optarg;
6870 break;
6871 case 'd':
6872 delref = optarg;
6873 break;
6874 case 'l':
6875 do_list = 1;
6876 break;
6877 case 'n':
6878 do_update = 0;
6879 break;
6880 case 'r':
6881 repo_path = realpath(optarg, NULL);
6882 if (repo_path == NULL)
6883 return got_error_from_errno2("realpath",
6884 optarg);
6885 got_path_strip_trailing_slashes(repo_path);
6886 break;
6887 case 't':
6888 sort_by_time = 1;
6889 break;
6890 default:
6891 usage_branch();
6892 /* NOTREACHED */
6896 if (do_list && delref)
6897 option_conflict('l', 'd');
6898 if (sort_by_time && !do_list)
6899 errx(1, "-t option requires -l option");
6901 argc -= optind;
6902 argv += optind;
6904 if (!do_list && !delref && argc == 0)
6905 do_show = 1;
6907 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6908 errx(1, "-c option can only be used when creating a branch");
6910 if (do_list || delref) {
6911 if (argc > 0)
6912 usage_branch();
6913 } else if (!do_show && argc != 1)
6914 usage_branch();
6916 #ifndef PROFILE
6917 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6918 "sendfd unveil", NULL) == -1)
6919 err(1, "pledge");
6920 #endif
6921 cwd = getcwd(NULL, 0);
6922 if (cwd == NULL) {
6923 error = got_error_from_errno("getcwd");
6924 goto done;
6927 error = got_repo_pack_fds_open(&pack_fds);
6928 if (error != NULL)
6929 goto done;
6931 if (repo_path == NULL) {
6932 error = got_worktree_open(&worktree, cwd);
6933 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6934 goto done;
6935 else
6936 error = NULL;
6937 if (worktree) {
6938 repo_path =
6939 strdup(got_worktree_get_repo_path(worktree));
6940 if (repo_path == NULL)
6941 error = got_error_from_errno("strdup");
6942 if (error)
6943 goto done;
6944 } else {
6945 repo_path = strdup(cwd);
6946 if (repo_path == NULL) {
6947 error = got_error_from_errno("strdup");
6948 goto done;
6953 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6954 if (error != NULL)
6955 goto done;
6957 #ifndef PROFILE
6958 if (do_list || do_show) {
6959 /* Remove "cpath" promise. */
6960 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6961 NULL) == -1)
6962 err(1, "pledge");
6964 #endif
6966 error = apply_unveil(got_repo_get_path(repo), do_list,
6967 worktree ? got_worktree_get_root_path(worktree) : NULL);
6968 if (error)
6969 goto done;
6971 if (do_show)
6972 error = show_current_branch(repo, worktree);
6973 else if (do_list)
6974 error = list_branches(repo, worktree, sort_by_time);
6975 else if (delref)
6976 error = delete_branch(repo, worktree, delref);
6977 else {
6978 struct got_reflist_head refs;
6979 TAILQ_INIT(&refs);
6980 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6981 NULL);
6982 if (error)
6983 goto done;
6984 if (commit_id_arg == NULL)
6985 commit_id_arg = worktree ?
6986 got_worktree_get_head_ref_name(worktree) :
6987 GOT_REF_HEAD;
6988 error = got_repo_match_object_id(&commit_id, NULL,
6989 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6990 got_ref_list_free(&refs);
6991 if (error)
6992 goto done;
6993 error = add_branch(repo, argv[0], commit_id);
6994 if (error)
6995 goto done;
6996 if (worktree && do_update) {
6997 struct got_update_progress_arg upa;
6998 char *branch_refname = NULL;
7000 error = got_object_id_str(&commit_id_str, commit_id);
7001 if (error)
7002 goto done;
7003 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7004 worktree);
7005 if (error)
7006 goto done;
7007 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7008 == -1) {
7009 error = got_error_from_errno("asprintf");
7010 goto done;
7012 error = got_ref_open(&ref, repo, branch_refname, 0);
7013 free(branch_refname);
7014 if (error)
7015 goto done;
7016 error = switch_head_ref(ref, commit_id, worktree,
7017 repo);
7018 if (error)
7019 goto done;
7020 error = got_worktree_set_base_commit_id(worktree, repo,
7021 commit_id);
7022 if (error)
7023 goto done;
7024 memset(&upa, 0, sizeof(upa));
7025 error = got_worktree_checkout_files(worktree, &paths,
7026 repo, update_progress, &upa, check_cancelled,
7027 NULL);
7028 if (error)
7029 goto done;
7030 if (upa.did_something) {
7031 printf("Updated to %s: %s\n",
7032 got_worktree_get_head_ref_name(worktree),
7033 commit_id_str);
7035 print_update_progress_stats(&upa);
7038 done:
7039 if (ref)
7040 got_ref_close(ref);
7041 if (repo) {
7042 const struct got_error *close_err = got_repo_close(repo);
7043 if (error == NULL)
7044 error = close_err;
7046 if (worktree)
7047 got_worktree_close(worktree);
7048 if (pack_fds) {
7049 const struct got_error *pack_err =
7050 got_repo_pack_fds_close(pack_fds);
7051 if (error == NULL)
7052 error = pack_err;
7054 free(cwd);
7055 free(repo_path);
7056 free(commit_id);
7057 free(commit_id_str);
7058 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7059 return error;
7063 __dead static void
7064 usage_tag(void)
7066 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7067 "[-r repository-path] [-s signer-id] name\n", getprogname());
7068 exit(1);
7071 #if 0
7072 static const struct got_error *
7073 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7075 const struct got_error *err = NULL;
7076 struct got_reflist_entry *re, *se, *new;
7077 struct got_object_id *re_id, *se_id;
7078 struct got_tag_object *re_tag, *se_tag;
7079 time_t re_time, se_time;
7081 STAILQ_FOREACH(re, tags, entry) {
7082 se = STAILQ_FIRST(sorted);
7083 if (se == NULL) {
7084 err = got_reflist_entry_dup(&new, re);
7085 if (err)
7086 return err;
7087 STAILQ_INSERT_HEAD(sorted, new, entry);
7088 continue;
7089 } else {
7090 err = got_ref_resolve(&re_id, repo, re->ref);
7091 if (err)
7092 break;
7093 err = got_object_open_as_tag(&re_tag, repo, re_id);
7094 free(re_id);
7095 if (err)
7096 break;
7097 re_time = got_object_tag_get_tagger_time(re_tag);
7098 got_object_tag_close(re_tag);
7101 while (se) {
7102 err = got_ref_resolve(&se_id, repo, re->ref);
7103 if (err)
7104 break;
7105 err = got_object_open_as_tag(&se_tag, repo, se_id);
7106 free(se_id);
7107 if (err)
7108 break;
7109 se_time = got_object_tag_get_tagger_time(se_tag);
7110 got_object_tag_close(se_tag);
7112 if (se_time > re_time) {
7113 err = got_reflist_entry_dup(&new, re);
7114 if (err)
7115 return err;
7116 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7117 break;
7119 se = STAILQ_NEXT(se, entry);
7120 continue;
7123 done:
7124 return err;
7126 #endif
7128 static const struct got_error *
7129 get_tag_refname(char **refname, const char *tag_name)
7131 const struct got_error *err;
7133 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7134 *refname = strdup(tag_name);
7135 if (*refname == NULL)
7136 return got_error_from_errno("strdup");
7137 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7138 err = got_error_from_errno("asprintf");
7139 *refname = NULL;
7140 return err;
7143 return NULL;
7146 static const struct got_error *
7147 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7148 const char *allowed_signers, const char *revoked_signers, int verbosity)
7150 static const struct got_error *err = NULL;
7151 struct got_reflist_head refs;
7152 struct got_reflist_entry *re;
7153 char *wanted_refname = NULL;
7154 int bad_sigs = 0;
7156 TAILQ_INIT(&refs);
7158 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7159 if (err)
7160 return err;
7162 if (tag_name) {
7163 struct got_reference *ref;
7164 err = get_tag_refname(&wanted_refname, tag_name);
7165 if (err)
7166 goto done;
7167 /* Wanted tag reference should exist. */
7168 err = got_ref_open(&ref, repo, wanted_refname, 0);
7169 if (err)
7170 goto done;
7171 got_ref_close(ref);
7174 TAILQ_FOREACH(re, &refs, entry) {
7175 const char *refname;
7176 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7177 char datebuf[26];
7178 const char *tagger, *ssh_sig = NULL;
7179 char *sig_msg = NULL;
7180 time_t tagger_time;
7181 struct got_object_id *id;
7182 struct got_tag_object *tag;
7183 struct got_commit_object *commit = NULL;
7185 refname = got_ref_get_name(re->ref);
7186 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7187 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7188 continue;
7189 refname += 10;
7190 refstr = got_ref_to_str(re->ref);
7191 if (refstr == NULL) {
7192 err = got_error_from_errno("got_ref_to_str");
7193 break;
7196 err = got_ref_resolve(&id, repo, re->ref);
7197 if (err)
7198 break;
7199 err = got_object_open_as_tag(&tag, repo, id);
7200 if (err) {
7201 if (err->code != GOT_ERR_OBJ_TYPE) {
7202 free(id);
7203 break;
7205 /* "lightweight" tag */
7206 err = got_object_open_as_commit(&commit, repo, id);
7207 if (err) {
7208 free(id);
7209 break;
7211 tagger = got_object_commit_get_committer(commit);
7212 tagger_time =
7213 got_object_commit_get_committer_time(commit);
7214 err = got_object_id_str(&id_str, id);
7215 free(id);
7216 if (err)
7217 break;
7218 } else {
7219 free(id);
7220 tagger = got_object_tag_get_tagger(tag);
7221 tagger_time = got_object_tag_get_tagger_time(tag);
7222 err = got_object_id_str(&id_str,
7223 got_object_tag_get_object_id(tag));
7224 if (err)
7225 break;
7228 if (tag && verify_tags) {
7229 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7230 got_object_tag_get_message(tag));
7231 if (ssh_sig && allowed_signers == NULL) {
7232 err = got_error_msg(
7233 GOT_ERR_VERIFY_TAG_SIGNATURE,
7234 "SSH signature verification requires "
7235 "setting allowed_signers in "
7236 "got.conf(5)");
7237 break;
7241 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7242 free(refstr);
7243 printf("from: %s\n", tagger);
7244 datestr = get_datestr(&tagger_time, datebuf);
7245 if (datestr)
7246 printf("date: %s UTC\n", datestr);
7247 if (commit)
7248 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7249 else {
7250 switch (got_object_tag_get_object_type(tag)) {
7251 case GOT_OBJ_TYPE_BLOB:
7252 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7253 id_str);
7254 break;
7255 case GOT_OBJ_TYPE_TREE:
7256 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7257 id_str);
7258 break;
7259 case GOT_OBJ_TYPE_COMMIT:
7260 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7261 id_str);
7262 break;
7263 case GOT_OBJ_TYPE_TAG:
7264 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7265 id_str);
7266 break;
7267 default:
7268 break;
7271 free(id_str);
7273 if (ssh_sig) {
7274 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7275 allowed_signers, revoked_signers, verbosity);
7276 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7277 bad_sigs = 1;
7278 else if (err)
7279 break;
7280 printf("signature: %s", sig_msg);
7281 free(sig_msg);
7282 sig_msg = NULL;
7285 if (commit) {
7286 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7287 if (err)
7288 break;
7289 got_object_commit_close(commit);
7290 } else {
7291 tagmsg0 = strdup(got_object_tag_get_message(tag));
7292 got_object_tag_close(tag);
7293 if (tagmsg0 == NULL) {
7294 err = got_error_from_errno("strdup");
7295 break;
7299 tagmsg = tagmsg0;
7300 do {
7301 line = strsep(&tagmsg, "\n");
7302 if (line)
7303 printf(" %s\n", line);
7304 } while (line);
7305 free(tagmsg0);
7307 done:
7308 got_ref_list_free(&refs);
7309 free(wanted_refname);
7311 if (err == NULL && bad_sigs)
7312 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7313 return err;
7316 static const struct got_error *
7317 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7318 const char *tag_name, const char *repo_path)
7320 const struct got_error *err = NULL;
7321 char *template = NULL, *initial_content = NULL;
7322 char *editor = NULL;
7323 int initial_content_len;
7324 int fd = -1;
7326 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7327 err = got_error_from_errno("asprintf");
7328 goto done;
7331 initial_content_len = asprintf(&initial_content,
7332 "\n# tagging commit %s as %s\n",
7333 commit_id_str, tag_name);
7334 if (initial_content_len == -1) {
7335 err = got_error_from_errno("asprintf");
7336 goto done;
7339 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7340 if (err)
7341 goto done;
7343 if (write(fd, initial_content, initial_content_len) == -1) {
7344 err = got_error_from_errno2("write", *tagmsg_path);
7345 goto done;
7348 err = get_editor(&editor);
7349 if (err)
7350 goto done;
7351 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7352 initial_content_len, 1);
7353 done:
7354 free(initial_content);
7355 free(template);
7356 free(editor);
7358 if (fd != -1 && close(fd) == -1 && err == NULL)
7359 err = got_error_from_errno2("close", *tagmsg_path);
7361 if (err) {
7362 free(*tagmsg);
7363 *tagmsg = NULL;
7365 return err;
7368 static const struct got_error *
7369 add_tag(struct got_repository *repo, const char *tagger,
7370 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7371 const char *signer_id, int verbosity)
7373 const struct got_error *err = NULL;
7374 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7375 char *label = NULL, *commit_id_str = NULL;
7376 struct got_reference *ref = NULL;
7377 char *refname = NULL, *tagmsg = NULL;
7378 char *tagmsg_path = NULL, *tag_id_str = NULL;
7379 int preserve_tagmsg = 0;
7380 struct got_reflist_head refs;
7382 TAILQ_INIT(&refs);
7385 * Don't let the user create a tag name with a leading '-'.
7386 * While technically a valid reference name, this case is usually
7387 * an unintended typo.
7389 if (tag_name[0] == '-')
7390 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7392 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7393 if (err)
7394 goto done;
7396 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7397 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7398 if (err)
7399 goto done;
7401 err = got_object_id_str(&commit_id_str, commit_id);
7402 if (err)
7403 goto done;
7405 err = get_tag_refname(&refname, tag_name);
7406 if (err)
7407 goto done;
7408 if (strncmp("refs/tags/", tag_name, 10) == 0)
7409 tag_name += 10;
7411 err = got_ref_open(&ref, repo, refname, 0);
7412 if (err == NULL) {
7413 err = got_error(GOT_ERR_TAG_EXISTS);
7414 goto done;
7415 } else if (err->code != GOT_ERR_NOT_REF)
7416 goto done;
7418 if (tagmsg_arg == NULL) {
7419 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7420 tag_name, got_repo_get_path(repo));
7421 if (err) {
7422 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7423 tagmsg_path != NULL)
7424 preserve_tagmsg = 1;
7425 goto done;
7427 /* Editor is done; we can now apply unveil(2) */
7428 err = got_sigs_apply_unveil();
7429 if (err)
7430 goto done;
7431 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7432 if (err)
7433 goto done;
7436 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7437 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7438 verbosity);
7439 if (err) {
7440 if (tagmsg_path)
7441 preserve_tagmsg = 1;
7442 goto done;
7445 err = got_ref_alloc(&ref, refname, tag_id);
7446 if (err) {
7447 if (tagmsg_path)
7448 preserve_tagmsg = 1;
7449 goto done;
7452 err = got_ref_write(ref, repo);
7453 if (err) {
7454 if (tagmsg_path)
7455 preserve_tagmsg = 1;
7456 goto done;
7459 err = got_object_id_str(&tag_id_str, tag_id);
7460 if (err) {
7461 if (tagmsg_path)
7462 preserve_tagmsg = 1;
7463 goto done;
7465 printf("Created tag %s\n", tag_id_str);
7466 done:
7467 if (preserve_tagmsg) {
7468 fprintf(stderr, "%s: tag message preserved in %s\n",
7469 getprogname(), tagmsg_path);
7470 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7471 err = got_error_from_errno2("unlink", tagmsg_path);
7472 free(tag_id_str);
7473 if (ref)
7474 got_ref_close(ref);
7475 free(commit_id);
7476 free(commit_id_str);
7477 free(refname);
7478 free(tagmsg);
7479 free(tagmsg_path);
7480 got_ref_list_free(&refs);
7481 return err;
7484 static const struct got_error *
7485 cmd_tag(int argc, char *argv[])
7487 const struct got_error *error = NULL;
7488 struct got_repository *repo = NULL;
7489 struct got_worktree *worktree = NULL;
7490 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7491 char *gitconfig_path = NULL, *tagger = NULL;
7492 char *allowed_signers = NULL, *revoked_signers = NULL;
7493 char *signer_id = NULL;
7494 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7495 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7496 int *pack_fds = NULL;
7498 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7499 switch (ch) {
7500 case 'c':
7501 commit_id_arg = optarg;
7502 break;
7503 case 'l':
7504 do_list = 1;
7505 break;
7506 case 'm':
7507 tagmsg = optarg;
7508 break;
7509 case 'r':
7510 repo_path = realpath(optarg, NULL);
7511 if (repo_path == NULL) {
7512 error = got_error_from_errno2("realpath",
7513 optarg);
7514 goto done;
7516 got_path_strip_trailing_slashes(repo_path);
7517 break;
7518 case 's':
7519 signer_id = strdup(optarg);
7520 if (signer_id == NULL) {
7521 error = got_error_from_errno("strdup");
7522 goto done;
7524 break;
7525 case 'V':
7526 verify_tags = 1;
7527 break;
7528 case 'v':
7529 if (verbosity < 0)
7530 verbosity = 0;
7531 else if (verbosity < 3)
7532 verbosity++;
7533 break;
7534 default:
7535 usage_tag();
7536 /* NOTREACHED */
7540 argc -= optind;
7541 argv += optind;
7543 if (do_list || verify_tags) {
7544 if (commit_id_arg != NULL)
7545 errx(1,
7546 "-c option can only be used when creating a tag");
7547 if (tagmsg) {
7548 if (do_list)
7549 option_conflict('l', 'm');
7550 else
7551 option_conflict('V', 'm');
7553 if (signer_id) {
7554 if (do_list)
7555 option_conflict('l', 's');
7556 else
7557 option_conflict('V', 's');
7559 if (argc > 1)
7560 usage_tag();
7561 } else if (argc != 1)
7562 usage_tag();
7564 if (argc == 1)
7565 tag_name = argv[0];
7567 #ifndef PROFILE
7568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7569 "sendfd unveil", NULL) == -1)
7570 err(1, "pledge");
7571 #endif
7572 cwd = getcwd(NULL, 0);
7573 if (cwd == NULL) {
7574 error = got_error_from_errno("getcwd");
7575 goto done;
7578 error = got_repo_pack_fds_open(&pack_fds);
7579 if (error != NULL)
7580 goto done;
7582 if (repo_path == NULL) {
7583 error = got_worktree_open(&worktree, cwd);
7584 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7585 goto done;
7586 else
7587 error = NULL;
7588 if (worktree) {
7589 repo_path =
7590 strdup(got_worktree_get_repo_path(worktree));
7591 if (repo_path == NULL)
7592 error = got_error_from_errno("strdup");
7593 if (error)
7594 goto done;
7595 } else {
7596 repo_path = strdup(cwd);
7597 if (repo_path == NULL) {
7598 error = got_error_from_errno("strdup");
7599 goto done;
7604 if (do_list || verify_tags) {
7605 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7606 if (error != NULL)
7607 goto done;
7608 error = get_allowed_signers(&allowed_signers, repo, worktree);
7609 if (error)
7610 goto done;
7611 error = get_revoked_signers(&revoked_signers, repo, worktree);
7612 if (error)
7613 goto done;
7614 if (worktree) {
7615 /* Release work tree lock. */
7616 got_worktree_close(worktree);
7617 worktree = NULL;
7621 * Remove "cpath" promise unless needed for signature tmpfile
7622 * creation.
7624 if (verify_tags)
7625 got_sigs_apply_unveil();
7626 else {
7627 #ifndef PROFILE
7628 if (pledge("stdio rpath wpath flock proc exec sendfd "
7629 "unveil", NULL) == -1)
7630 err(1, "pledge");
7631 #endif
7633 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7634 if (error)
7635 goto done;
7636 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7637 revoked_signers, verbosity);
7638 } else {
7639 error = get_gitconfig_path(&gitconfig_path);
7640 if (error)
7641 goto done;
7642 error = got_repo_open(&repo, repo_path, gitconfig_path,
7643 pack_fds);
7644 if (error != NULL)
7645 goto done;
7647 error = get_author(&tagger, repo, worktree);
7648 if (error)
7649 goto done;
7650 if (signer_id == NULL) {
7651 error = get_signer_id(&signer_id, repo, worktree);
7652 if (error)
7653 goto done;
7656 if (tagmsg) {
7657 if (signer_id) {
7658 error = got_sigs_apply_unveil();
7659 if (error)
7660 goto done;
7662 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7663 if (error)
7664 goto done;
7667 if (commit_id_arg == NULL) {
7668 struct got_reference *head_ref;
7669 struct got_object_id *commit_id;
7670 error = got_ref_open(&head_ref, repo,
7671 worktree ? got_worktree_get_head_ref_name(worktree)
7672 : GOT_REF_HEAD, 0);
7673 if (error)
7674 goto done;
7675 error = got_ref_resolve(&commit_id, repo, head_ref);
7676 got_ref_close(head_ref);
7677 if (error)
7678 goto done;
7679 error = got_object_id_str(&commit_id_str, commit_id);
7680 free(commit_id);
7681 if (error)
7682 goto done;
7685 if (worktree) {
7686 /* Release work tree lock. */
7687 got_worktree_close(worktree);
7688 worktree = NULL;
7691 error = add_tag(repo, tagger, tag_name,
7692 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7693 signer_id, verbosity);
7695 done:
7696 if (repo) {
7697 const struct got_error *close_err = got_repo_close(repo);
7698 if (error == NULL)
7699 error = close_err;
7701 if (worktree)
7702 got_worktree_close(worktree);
7703 if (pack_fds) {
7704 const struct got_error *pack_err =
7705 got_repo_pack_fds_close(pack_fds);
7706 if (error == NULL)
7707 error = pack_err;
7709 free(cwd);
7710 free(repo_path);
7711 free(gitconfig_path);
7712 free(commit_id_str);
7713 free(tagger);
7714 free(allowed_signers);
7715 free(revoked_signers);
7716 free(signer_id);
7717 return error;
7720 __dead static void
7721 usage_add(void)
7723 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7724 exit(1);
7727 static const struct got_error *
7728 add_progress(void *arg, unsigned char status, const char *path)
7730 while (path[0] == '/')
7731 path++;
7732 printf("%c %s\n", status, path);
7733 return NULL;
7736 static const struct got_error *
7737 cmd_add(int argc, char *argv[])
7739 const struct got_error *error = NULL;
7740 struct got_repository *repo = NULL;
7741 struct got_worktree *worktree = NULL;
7742 char *cwd = NULL;
7743 struct got_pathlist_head paths;
7744 struct got_pathlist_entry *pe;
7745 int ch, can_recurse = 0, no_ignores = 0;
7746 int *pack_fds = NULL;
7748 TAILQ_INIT(&paths);
7750 while ((ch = getopt(argc, argv, "IR")) != -1) {
7751 switch (ch) {
7752 case 'I':
7753 no_ignores = 1;
7754 break;
7755 case 'R':
7756 can_recurse = 1;
7757 break;
7758 default:
7759 usage_add();
7760 /* NOTREACHED */
7764 argc -= optind;
7765 argv += optind;
7767 #ifndef PROFILE
7768 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7769 NULL) == -1)
7770 err(1, "pledge");
7771 #endif
7772 if (argc < 1)
7773 usage_add();
7775 cwd = getcwd(NULL, 0);
7776 if (cwd == NULL) {
7777 error = got_error_from_errno("getcwd");
7778 goto done;
7781 error = got_repo_pack_fds_open(&pack_fds);
7782 if (error != NULL)
7783 goto done;
7785 error = got_worktree_open(&worktree, cwd);
7786 if (error) {
7787 if (error->code == GOT_ERR_NOT_WORKTREE)
7788 error = wrap_not_worktree_error(error, "add", cwd);
7789 goto done;
7792 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7793 NULL, pack_fds);
7794 if (error != NULL)
7795 goto done;
7797 error = apply_unveil(got_repo_get_path(repo), 1,
7798 got_worktree_get_root_path(worktree));
7799 if (error)
7800 goto done;
7802 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7803 if (error)
7804 goto done;
7806 if (!can_recurse) {
7807 char *ondisk_path;
7808 struct stat sb;
7809 TAILQ_FOREACH(pe, &paths, entry) {
7810 if (asprintf(&ondisk_path, "%s/%s",
7811 got_worktree_get_root_path(worktree),
7812 pe->path) == -1) {
7813 error = got_error_from_errno("asprintf");
7814 goto done;
7816 if (lstat(ondisk_path, &sb) == -1) {
7817 if (errno == ENOENT) {
7818 free(ondisk_path);
7819 continue;
7821 error = got_error_from_errno2("lstat",
7822 ondisk_path);
7823 free(ondisk_path);
7824 goto done;
7826 free(ondisk_path);
7827 if (S_ISDIR(sb.st_mode)) {
7828 error = got_error_msg(GOT_ERR_BAD_PATH,
7829 "adding directories requires -R option");
7830 goto done;
7835 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7836 NULL, repo, no_ignores);
7837 done:
7838 if (repo) {
7839 const struct got_error *close_err = got_repo_close(repo);
7840 if (error == NULL)
7841 error = close_err;
7843 if (worktree)
7844 got_worktree_close(worktree);
7845 if (pack_fds) {
7846 const struct got_error *pack_err =
7847 got_repo_pack_fds_close(pack_fds);
7848 if (error == NULL)
7849 error = pack_err;
7851 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7852 free(cwd);
7853 return error;
7856 __dead static void
7857 usage_remove(void)
7859 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7860 getprogname());
7861 exit(1);
7864 static const struct got_error *
7865 print_remove_status(void *arg, unsigned char status,
7866 unsigned char staged_status, const char *path)
7868 while (path[0] == '/')
7869 path++;
7870 if (status == GOT_STATUS_NONEXISTENT)
7871 return NULL;
7872 if (status == staged_status && (status == GOT_STATUS_DELETE))
7873 status = GOT_STATUS_NO_CHANGE;
7874 printf("%c%c %s\n", status, staged_status, path);
7875 return NULL;
7878 static const struct got_error *
7879 cmd_remove(int argc, char *argv[])
7881 const struct got_error *error = NULL;
7882 struct got_worktree *worktree = NULL;
7883 struct got_repository *repo = NULL;
7884 const char *status_codes = NULL;
7885 char *cwd = NULL;
7886 struct got_pathlist_head paths;
7887 struct got_pathlist_entry *pe;
7888 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7889 int ignore_missing_paths = 0;
7890 int *pack_fds = NULL;
7892 TAILQ_INIT(&paths);
7894 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7895 switch (ch) {
7896 case 'f':
7897 delete_local_mods = 1;
7898 ignore_missing_paths = 1;
7899 break;
7900 case 'k':
7901 keep_on_disk = 1;
7902 break;
7903 case 'R':
7904 can_recurse = 1;
7905 break;
7906 case 's':
7907 for (i = 0; i < strlen(optarg); i++) {
7908 switch (optarg[i]) {
7909 case GOT_STATUS_MODIFY:
7910 delete_local_mods = 1;
7911 break;
7912 case GOT_STATUS_MISSING:
7913 ignore_missing_paths = 1;
7914 break;
7915 default:
7916 errx(1, "invalid status code '%c'",
7917 optarg[i]);
7920 status_codes = optarg;
7921 break;
7922 default:
7923 usage_remove();
7924 /* NOTREACHED */
7928 argc -= optind;
7929 argv += optind;
7931 #ifndef PROFILE
7932 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7933 NULL) == -1)
7934 err(1, "pledge");
7935 #endif
7936 if (argc < 1)
7937 usage_remove();
7939 cwd = getcwd(NULL, 0);
7940 if (cwd == NULL) {
7941 error = got_error_from_errno("getcwd");
7942 goto done;
7945 error = got_repo_pack_fds_open(&pack_fds);
7946 if (error != NULL)
7947 goto done;
7949 error = got_worktree_open(&worktree, cwd);
7950 if (error) {
7951 if (error->code == GOT_ERR_NOT_WORKTREE)
7952 error = wrap_not_worktree_error(error, "remove", cwd);
7953 goto done;
7956 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7957 NULL, pack_fds);
7958 if (error)
7959 goto done;
7961 error = apply_unveil(got_repo_get_path(repo), 1,
7962 got_worktree_get_root_path(worktree));
7963 if (error)
7964 goto done;
7966 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7967 if (error)
7968 goto done;
7970 if (!can_recurse) {
7971 char *ondisk_path;
7972 struct stat sb;
7973 TAILQ_FOREACH(pe, &paths, entry) {
7974 if (asprintf(&ondisk_path, "%s/%s",
7975 got_worktree_get_root_path(worktree),
7976 pe->path) == -1) {
7977 error = got_error_from_errno("asprintf");
7978 goto done;
7980 if (lstat(ondisk_path, &sb) == -1) {
7981 if (errno == ENOENT) {
7982 free(ondisk_path);
7983 continue;
7985 error = got_error_from_errno2("lstat",
7986 ondisk_path);
7987 free(ondisk_path);
7988 goto done;
7990 free(ondisk_path);
7991 if (S_ISDIR(sb.st_mode)) {
7992 error = got_error_msg(GOT_ERR_BAD_PATH,
7993 "removing directories requires -R option");
7994 goto done;
7999 error = got_worktree_schedule_delete(worktree, &paths,
8000 delete_local_mods, status_codes, print_remove_status, NULL,
8001 repo, keep_on_disk, ignore_missing_paths);
8002 done:
8003 if (repo) {
8004 const struct got_error *close_err = got_repo_close(repo);
8005 if (error == NULL)
8006 error = close_err;
8008 if (worktree)
8009 got_worktree_close(worktree);
8010 if (pack_fds) {
8011 const struct got_error *pack_err =
8012 got_repo_pack_fds_close(pack_fds);
8013 if (error == NULL)
8014 error = pack_err;
8016 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8017 free(cwd);
8018 return error;
8021 __dead static void
8022 usage_patch(void)
8024 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8025 "[patchfile]\n", getprogname());
8026 exit(1);
8029 static const struct got_error *
8030 patch_from_stdin(int *patchfd)
8032 const struct got_error *err = NULL;
8033 ssize_t r;
8034 char buf[BUFSIZ];
8035 sig_t sighup, sigint, sigquit;
8037 *patchfd = got_opentempfd();
8038 if (*patchfd == -1)
8039 return got_error_from_errno("got_opentempfd");
8041 sighup = signal(SIGHUP, SIG_DFL);
8042 sigint = signal(SIGINT, SIG_DFL);
8043 sigquit = signal(SIGQUIT, SIG_DFL);
8045 for (;;) {
8046 r = read(0, buf, sizeof(buf));
8047 if (r == -1) {
8048 err = got_error_from_errno("read");
8049 break;
8051 if (r == 0)
8052 break;
8053 if (write(*patchfd, buf, r) == -1) {
8054 err = got_error_from_errno("write");
8055 break;
8059 signal(SIGHUP, sighup);
8060 signal(SIGINT, sigint);
8061 signal(SIGQUIT, sigquit);
8063 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8064 err = got_error_from_errno("lseek");
8066 if (err != NULL) {
8067 close(*patchfd);
8068 *patchfd = -1;
8071 return err;
8074 static const struct got_error *
8075 patch_progress(void *arg, const char *old, const char *new,
8076 unsigned char status, const struct got_error *error, int old_from,
8077 int old_lines, int new_from, int new_lines, int offset,
8078 int ws_mangled, const struct got_error *hunk_err)
8080 const char *path = new == NULL ? old : new;
8082 while (*path == '/')
8083 path++;
8085 if (status != 0)
8086 printf("%c %s\n", status, path);
8088 if (error != NULL)
8089 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8091 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8092 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8093 old_lines, new_from, new_lines);
8094 if (hunk_err != NULL)
8095 printf("%s\n", hunk_err->msg);
8096 else if (offset != 0)
8097 printf("applied with offset %d\n", offset);
8098 else
8099 printf("hunk contains mangled whitespace\n");
8102 return NULL;
8105 static const struct got_error *
8106 cmd_patch(int argc, char *argv[])
8108 const struct got_error *error = NULL, *close_error = NULL;
8109 struct got_worktree *worktree = NULL;
8110 struct got_repository *repo = NULL;
8111 struct got_reflist_head refs;
8112 struct got_object_id *commit_id = NULL;
8113 const char *commit_id_str = NULL;
8114 struct stat sb;
8115 const char *errstr;
8116 char *cwd = NULL;
8117 int ch, nop = 0, strip = -1, reverse = 0;
8118 int patchfd;
8119 int *pack_fds = NULL;
8121 TAILQ_INIT(&refs);
8123 #ifndef PROFILE
8124 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8125 "unveil", NULL) == -1)
8126 err(1, "pledge");
8127 #endif
8129 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8130 switch (ch) {
8131 case 'c':
8132 commit_id_str = optarg;
8133 break;
8134 case 'n':
8135 nop = 1;
8136 break;
8137 case 'p':
8138 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8139 if (errstr != NULL)
8140 errx(1, "pathname strip count is %s: %s",
8141 errstr, optarg);
8142 break;
8143 case 'R':
8144 reverse = 1;
8145 break;
8146 default:
8147 usage_patch();
8148 /* NOTREACHED */
8152 argc -= optind;
8153 argv += optind;
8155 if (argc == 0) {
8156 error = patch_from_stdin(&patchfd);
8157 if (error)
8158 return error;
8159 } else if (argc == 1) {
8160 patchfd = open(argv[0], O_RDONLY);
8161 if (patchfd == -1) {
8162 error = got_error_from_errno2("open", argv[0]);
8163 return error;
8165 if (fstat(patchfd, &sb) == -1) {
8166 error = got_error_from_errno2("fstat", argv[0]);
8167 goto done;
8169 if (!S_ISREG(sb.st_mode)) {
8170 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8171 goto done;
8173 } else
8174 usage_patch();
8176 if ((cwd = getcwd(NULL, 0)) == NULL) {
8177 error = got_error_from_errno("getcwd");
8178 goto done;
8181 error = got_repo_pack_fds_open(&pack_fds);
8182 if (error != NULL)
8183 goto done;
8185 error = got_worktree_open(&worktree, cwd);
8186 if (error != NULL)
8187 goto done;
8189 const char *repo_path = got_worktree_get_repo_path(worktree);
8190 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8191 if (error != NULL)
8192 goto done;
8194 error = apply_unveil(got_repo_get_path(repo), 0,
8195 got_worktree_get_root_path(worktree));
8196 if (error != NULL)
8197 goto done;
8199 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8200 if (error)
8201 goto done;
8203 if (commit_id_str != NULL) {
8204 error = got_repo_match_object_id(&commit_id, NULL,
8205 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8206 if (error)
8207 goto done;
8210 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8211 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8213 done:
8214 got_ref_list_free(&refs);
8215 free(commit_id);
8216 if (repo) {
8217 close_error = got_repo_close(repo);
8218 if (error == NULL)
8219 error = close_error;
8221 if (worktree != NULL) {
8222 close_error = got_worktree_close(worktree);
8223 if (error == NULL)
8224 error = close_error;
8226 if (pack_fds) {
8227 const struct got_error *pack_err =
8228 got_repo_pack_fds_close(pack_fds);
8229 if (error == NULL)
8230 error = pack_err;
8232 free(cwd);
8233 return error;
8236 __dead static void
8237 usage_revert(void)
8239 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8240 getprogname());
8241 exit(1);
8244 static const struct got_error *
8245 revert_progress(void *arg, unsigned char status, const char *path)
8247 if (status == GOT_STATUS_UNVERSIONED)
8248 return NULL;
8250 while (path[0] == '/')
8251 path++;
8252 printf("%c %s\n", status, path);
8253 return NULL;
8256 struct choose_patch_arg {
8257 FILE *patch_script_file;
8258 const char *action;
8261 static const struct got_error *
8262 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8263 int nchanges, const char *action)
8265 const struct got_error *err;
8266 char *line = NULL;
8267 size_t linesize = 0;
8268 ssize_t linelen;
8270 switch (status) {
8271 case GOT_STATUS_ADD:
8272 printf("A %s\n%s this addition? [y/n] ", path, action);
8273 break;
8274 case GOT_STATUS_DELETE:
8275 printf("D %s\n%s this deletion? [y/n] ", path, action);
8276 break;
8277 case GOT_STATUS_MODIFY:
8278 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8279 return got_error_from_errno("fseek");
8280 printf(GOT_COMMIT_SEP_STR);
8281 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8282 printf("%s", line);
8283 if (linelen == -1 && ferror(patch_file)) {
8284 err = got_error_from_errno("getline");
8285 free(line);
8286 return err;
8288 free(line);
8289 printf(GOT_COMMIT_SEP_STR);
8290 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8291 path, n, nchanges, action);
8292 break;
8293 default:
8294 return got_error_path(path, GOT_ERR_FILE_STATUS);
8297 fflush(stdout);
8298 return NULL;
8301 static const struct got_error *
8302 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8303 FILE *patch_file, int n, int nchanges)
8305 const struct got_error *err = NULL;
8306 char *line = NULL;
8307 size_t linesize = 0;
8308 ssize_t linelen;
8309 int resp = ' ';
8310 struct choose_patch_arg *a = arg;
8312 *choice = GOT_PATCH_CHOICE_NONE;
8314 if (a->patch_script_file) {
8315 char *nl;
8316 err = show_change(status, path, patch_file, n, nchanges,
8317 a->action);
8318 if (err)
8319 return err;
8320 linelen = getline(&line, &linesize, a->patch_script_file);
8321 if (linelen == -1) {
8322 if (ferror(a->patch_script_file))
8323 return got_error_from_errno("getline");
8324 return NULL;
8326 nl = strchr(line, '\n');
8327 if (nl)
8328 *nl = '\0';
8329 if (strcmp(line, "y") == 0) {
8330 *choice = GOT_PATCH_CHOICE_YES;
8331 printf("y\n");
8332 } else if (strcmp(line, "n") == 0) {
8333 *choice = GOT_PATCH_CHOICE_NO;
8334 printf("n\n");
8335 } else if (strcmp(line, "q") == 0 &&
8336 status == GOT_STATUS_MODIFY) {
8337 *choice = GOT_PATCH_CHOICE_QUIT;
8338 printf("q\n");
8339 } else
8340 printf("invalid response '%s'\n", line);
8341 free(line);
8342 return NULL;
8345 while (resp != 'y' && resp != 'n' && resp != 'q') {
8346 err = show_change(status, path, patch_file, n, nchanges,
8347 a->action);
8348 if (err)
8349 return err;
8350 resp = getchar();
8351 if (resp == '\n')
8352 resp = getchar();
8353 if (status == GOT_STATUS_MODIFY) {
8354 if (resp != 'y' && resp != 'n' && resp != 'q') {
8355 printf("invalid response '%c'\n", resp);
8356 resp = ' ';
8358 } else if (resp != 'y' && resp != 'n') {
8359 printf("invalid response '%c'\n", resp);
8360 resp = ' ';
8364 if (resp == 'y')
8365 *choice = GOT_PATCH_CHOICE_YES;
8366 else if (resp == 'n')
8367 *choice = GOT_PATCH_CHOICE_NO;
8368 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8369 *choice = GOT_PATCH_CHOICE_QUIT;
8371 return NULL;
8374 static const struct got_error *
8375 cmd_revert(int argc, char *argv[])
8377 const struct got_error *error = NULL;
8378 struct got_worktree *worktree = NULL;
8379 struct got_repository *repo = NULL;
8380 char *cwd = NULL, *path = NULL;
8381 struct got_pathlist_head paths;
8382 struct got_pathlist_entry *pe;
8383 int ch, can_recurse = 0, pflag = 0;
8384 FILE *patch_script_file = NULL;
8385 const char *patch_script_path = NULL;
8386 struct choose_patch_arg cpa;
8387 int *pack_fds = NULL;
8389 TAILQ_INIT(&paths);
8391 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8392 switch (ch) {
8393 case 'F':
8394 patch_script_path = optarg;
8395 break;
8396 case 'p':
8397 pflag = 1;
8398 break;
8399 case 'R':
8400 can_recurse = 1;
8401 break;
8402 default:
8403 usage_revert();
8404 /* NOTREACHED */
8408 argc -= optind;
8409 argv += optind;
8411 #ifndef PROFILE
8412 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8413 "unveil", NULL) == -1)
8414 err(1, "pledge");
8415 #endif
8416 if (argc < 1)
8417 usage_revert();
8418 if (patch_script_path && !pflag)
8419 errx(1, "-F option can only be used together with -p option");
8421 cwd = getcwd(NULL, 0);
8422 if (cwd == NULL) {
8423 error = got_error_from_errno("getcwd");
8424 goto done;
8427 error = got_repo_pack_fds_open(&pack_fds);
8428 if (error != NULL)
8429 goto done;
8431 error = got_worktree_open(&worktree, cwd);
8432 if (error) {
8433 if (error->code == GOT_ERR_NOT_WORKTREE)
8434 error = wrap_not_worktree_error(error, "revert", cwd);
8435 goto done;
8438 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8439 NULL, pack_fds);
8440 if (error != NULL)
8441 goto done;
8443 if (patch_script_path) {
8444 patch_script_file = fopen(patch_script_path, "re");
8445 if (patch_script_file == NULL) {
8446 error = got_error_from_errno2("fopen",
8447 patch_script_path);
8448 goto done;
8451 error = apply_unveil(got_repo_get_path(repo), 1,
8452 got_worktree_get_root_path(worktree));
8453 if (error)
8454 goto done;
8456 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8457 if (error)
8458 goto done;
8460 if (!can_recurse) {
8461 char *ondisk_path;
8462 struct stat sb;
8463 TAILQ_FOREACH(pe, &paths, entry) {
8464 if (asprintf(&ondisk_path, "%s/%s",
8465 got_worktree_get_root_path(worktree),
8466 pe->path) == -1) {
8467 error = got_error_from_errno("asprintf");
8468 goto done;
8470 if (lstat(ondisk_path, &sb) == -1) {
8471 if (errno == ENOENT) {
8472 free(ondisk_path);
8473 continue;
8475 error = got_error_from_errno2("lstat",
8476 ondisk_path);
8477 free(ondisk_path);
8478 goto done;
8480 free(ondisk_path);
8481 if (S_ISDIR(sb.st_mode)) {
8482 error = got_error_msg(GOT_ERR_BAD_PATH,
8483 "reverting directories requires -R option");
8484 goto done;
8489 cpa.patch_script_file = patch_script_file;
8490 cpa.action = "revert";
8491 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8492 pflag ? choose_patch : NULL, &cpa, repo);
8493 done:
8494 if (patch_script_file && fclose(patch_script_file) == EOF &&
8495 error == NULL)
8496 error = got_error_from_errno2("fclose", patch_script_path);
8497 if (repo) {
8498 const struct got_error *close_err = got_repo_close(repo);
8499 if (error == NULL)
8500 error = close_err;
8502 if (worktree)
8503 got_worktree_close(worktree);
8504 if (pack_fds) {
8505 const struct got_error *pack_err =
8506 got_repo_pack_fds_close(pack_fds);
8507 if (error == NULL)
8508 error = pack_err;
8510 free(path);
8511 free(cwd);
8512 return error;
8515 __dead static void
8516 usage_commit(void)
8518 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8519 "[-m message] [path ...]\n", getprogname());
8520 exit(1);
8523 struct collect_commit_logmsg_arg {
8524 const char *cmdline_log;
8525 const char *prepared_log;
8526 int non_interactive;
8527 const char *editor;
8528 const char *worktree_path;
8529 const char *branch_name;
8530 const char *repo_path;
8531 char *logmsg_path;
8535 static const struct got_error *
8536 read_prepared_logmsg(char **logmsg, const char *path)
8538 const struct got_error *err = NULL;
8539 FILE *f = NULL;
8540 struct stat sb;
8541 size_t r;
8543 *logmsg = NULL;
8544 memset(&sb, 0, sizeof(sb));
8546 f = fopen(path, "re");
8547 if (f == NULL)
8548 return got_error_from_errno2("fopen", path);
8550 if (fstat(fileno(f), &sb) == -1) {
8551 err = got_error_from_errno2("fstat", path);
8552 goto done;
8554 if (sb.st_size == 0) {
8555 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8556 goto done;
8559 *logmsg = malloc(sb.st_size + 1);
8560 if (*logmsg == NULL) {
8561 err = got_error_from_errno("malloc");
8562 goto done;
8565 r = fread(*logmsg, 1, sb.st_size, f);
8566 if (r != sb.st_size) {
8567 if (ferror(f))
8568 err = got_error_from_errno2("fread", path);
8569 else
8570 err = got_error(GOT_ERR_IO);
8571 goto done;
8573 (*logmsg)[sb.st_size] = '\0';
8574 done:
8575 if (fclose(f) == EOF && err == NULL)
8576 err = got_error_from_errno2("fclose", path);
8577 if (err) {
8578 free(*logmsg);
8579 *logmsg = NULL;
8581 return err;
8584 static const struct got_error *
8585 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8586 const char *diff_path, char **logmsg, void *arg)
8588 char *initial_content = NULL;
8589 struct got_pathlist_entry *pe;
8590 const struct got_error *err = NULL;
8591 char *template = NULL;
8592 struct collect_commit_logmsg_arg *a = arg;
8593 int initial_content_len;
8594 int fd = -1;
8595 size_t len;
8597 /* if a message was specified on the command line, just use it */
8598 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8599 len = strlen(a->cmdline_log) + 1;
8600 *logmsg = malloc(len + 1);
8601 if (*logmsg == NULL)
8602 return got_error_from_errno("malloc");
8603 strlcpy(*logmsg, a->cmdline_log, len);
8604 return NULL;
8605 } else if (a->prepared_log != NULL && a->non_interactive)
8606 return read_prepared_logmsg(logmsg, a->prepared_log);
8608 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8609 return got_error_from_errno("asprintf");
8611 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8612 if (err)
8613 goto done;
8615 if (a->prepared_log) {
8616 char *msg;
8617 err = read_prepared_logmsg(&msg, a->prepared_log);
8618 if (err)
8619 goto done;
8620 if (write(fd, msg, strlen(msg)) == -1) {
8621 err = got_error_from_errno2("write", a->logmsg_path);
8622 free(msg);
8623 goto done;
8625 free(msg);
8628 initial_content_len = asprintf(&initial_content,
8629 "\n# changes to be committed on branch %s:\n",
8630 a->branch_name);
8631 if (initial_content_len == -1) {
8632 err = got_error_from_errno("asprintf");
8633 goto done;
8636 if (write(fd, initial_content, initial_content_len) == -1) {
8637 err = got_error_from_errno2("write", a->logmsg_path);
8638 goto done;
8641 TAILQ_FOREACH(pe, commitable_paths, entry) {
8642 struct got_commitable *ct = pe->data;
8643 dprintf(fd, "# %c %s\n",
8644 got_commitable_get_status(ct),
8645 got_commitable_get_path(ct));
8648 if (diff_path) {
8649 dprintf(fd, "# detailed changes can be viewed in %s\n",
8650 diff_path);
8653 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8654 initial_content_len, a->prepared_log ? 0 : 1);
8655 done:
8656 free(initial_content);
8657 free(template);
8659 if (fd != -1 && close(fd) == -1 && err == NULL)
8660 err = got_error_from_errno2("close", a->logmsg_path);
8662 /* Editor is done; we can now apply unveil(2) */
8663 if (err == NULL)
8664 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8665 if (err) {
8666 free(*logmsg);
8667 *logmsg = NULL;
8669 return err;
8672 static const struct got_error *
8673 cmd_commit(int argc, char *argv[])
8675 const struct got_error *error = NULL;
8676 struct got_worktree *worktree = NULL;
8677 struct got_repository *repo = NULL;
8678 char *cwd = NULL, *id_str = NULL;
8679 struct got_object_id *id = NULL;
8680 const char *logmsg = NULL;
8681 char *prepared_logmsg = NULL;
8682 struct collect_commit_logmsg_arg cl_arg;
8683 const char *author = NULL;
8684 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8685 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8686 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8687 int show_diff = 1;
8688 struct got_pathlist_head paths;
8689 int *pack_fds = NULL;
8691 TAILQ_INIT(&paths);
8692 cl_arg.logmsg_path = NULL;
8694 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8695 switch (ch) {
8696 case 'A':
8697 author = optarg;
8698 error = valid_author(author);
8699 if (error)
8700 return error;
8701 break;
8702 case 'F':
8703 if (logmsg != NULL)
8704 option_conflict('F', 'm');
8705 prepared_logmsg = realpath(optarg, NULL);
8706 if (prepared_logmsg == NULL)
8707 return got_error_from_errno2("realpath",
8708 optarg);
8709 break;
8710 case 'm':
8711 if (prepared_logmsg)
8712 option_conflict('m', 'F');
8713 logmsg = optarg;
8714 break;
8715 case 'N':
8716 non_interactive = 1;
8717 break;
8718 case 'n':
8719 show_diff = 0;
8720 break;
8721 case 'S':
8722 allow_bad_symlinks = 1;
8723 break;
8724 default:
8725 usage_commit();
8726 /* NOTREACHED */
8730 argc -= optind;
8731 argv += optind;
8733 #ifndef PROFILE
8734 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8735 "unveil", NULL) == -1)
8736 err(1, "pledge");
8737 #endif
8738 cwd = getcwd(NULL, 0);
8739 if (cwd == NULL) {
8740 error = got_error_from_errno("getcwd");
8741 goto done;
8744 error = got_repo_pack_fds_open(&pack_fds);
8745 if (error != NULL)
8746 goto done;
8748 error = got_worktree_open(&worktree, cwd);
8749 if (error) {
8750 if (error->code == GOT_ERR_NOT_WORKTREE)
8751 error = wrap_not_worktree_error(error, "commit", cwd);
8752 goto done;
8755 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8756 if (error)
8757 goto done;
8758 if (rebase_in_progress) {
8759 error = got_error(GOT_ERR_REBASING);
8760 goto done;
8763 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8764 worktree);
8765 if (error)
8766 goto done;
8768 error = get_gitconfig_path(&gitconfig_path);
8769 if (error)
8770 goto done;
8771 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8772 gitconfig_path, pack_fds);
8773 if (error != NULL)
8774 goto done;
8776 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8777 if (error)
8778 goto done;
8779 if (merge_in_progress) {
8780 error = got_error(GOT_ERR_MERGE_BUSY);
8781 goto done;
8784 error = get_author(&committer, repo, worktree);
8785 if (error)
8786 goto done;
8788 if (author != NULL && !strcmp(committer, author)) {
8789 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8790 goto done;
8793 if (author == NULL)
8794 author = committer;
8797 * unveil(2) traverses exec(2); if an editor is used we have
8798 * to apply unveil after the log message has been written.
8800 if (logmsg == NULL || strlen(logmsg) == 0)
8801 error = get_editor(&editor);
8802 else
8803 error = apply_unveil(got_repo_get_path(repo), 0,
8804 got_worktree_get_root_path(worktree));
8805 if (error)
8806 goto done;
8808 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8809 if (error)
8810 goto done;
8812 cl_arg.editor = editor;
8813 cl_arg.cmdline_log = logmsg;
8814 cl_arg.prepared_log = prepared_logmsg;
8815 cl_arg.non_interactive = non_interactive;
8816 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8817 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8818 if (!histedit_in_progress) {
8819 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8820 error = got_error(GOT_ERR_COMMIT_BRANCH);
8821 goto done;
8823 cl_arg.branch_name += 11;
8825 cl_arg.repo_path = got_repo_get_path(repo);
8826 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8827 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8828 print_status, NULL, repo);
8829 if (error) {
8830 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8831 cl_arg.logmsg_path != NULL)
8832 preserve_logmsg = 1;
8833 goto done;
8836 error = got_object_id_str(&id_str, id);
8837 if (error)
8838 goto done;
8839 printf("Created commit %s\n", id_str);
8840 done:
8841 if (preserve_logmsg) {
8842 fprintf(stderr, "%s: log message preserved in %s\n",
8843 getprogname(), cl_arg.logmsg_path);
8844 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8845 error == NULL)
8846 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8847 free(cl_arg.logmsg_path);
8848 if (repo) {
8849 const struct got_error *close_err = got_repo_close(repo);
8850 if (error == NULL)
8851 error = close_err;
8853 if (worktree)
8854 got_worktree_close(worktree);
8855 if (pack_fds) {
8856 const struct got_error *pack_err =
8857 got_repo_pack_fds_close(pack_fds);
8858 if (error == NULL)
8859 error = pack_err;
8861 free(cwd);
8862 free(id_str);
8863 free(gitconfig_path);
8864 free(editor);
8865 free(committer);
8866 free(prepared_logmsg);
8867 return error;
8870 __dead static void
8871 usage_send(void)
8873 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8874 "[-r repository-path] [-t tag] [remote-repository]\n",
8875 getprogname());
8876 exit(1);
8879 static void
8880 print_load_info(int print_colored, int print_found, int print_trees,
8881 int ncolored, int nfound, int ntrees)
8883 if (print_colored) {
8884 printf("%d commit%s colored", ncolored,
8885 ncolored == 1 ? "" : "s");
8887 if (print_found) {
8888 printf("%s%d object%s found",
8889 ncolored > 0 ? "; " : "",
8890 nfound, nfound == 1 ? "" : "s");
8892 if (print_trees) {
8893 printf("; %d tree%s scanned", ntrees,
8894 ntrees == 1 ? "" : "s");
8898 struct got_send_progress_arg {
8899 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8900 int verbosity;
8901 int last_ncolored;
8902 int last_nfound;
8903 int last_ntrees;
8904 int loading_done;
8905 int last_ncommits;
8906 int last_nobj_total;
8907 int last_p_deltify;
8908 int last_p_written;
8909 int last_p_sent;
8910 int printed_something;
8911 int sent_something;
8912 struct got_pathlist_head *delete_branches;
8915 static const struct got_error *
8916 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8917 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8918 int nobj_written, off_t bytes_sent, const char *refname,
8919 const char *errmsg, int success)
8921 struct got_send_progress_arg *a = arg;
8922 char scaled_packsize[FMT_SCALED_STRSIZE];
8923 char scaled_sent[FMT_SCALED_STRSIZE];
8924 int p_deltify = 0, p_written = 0, p_sent = 0;
8925 int print_colored = 0, print_found = 0, print_trees = 0;
8926 int print_searching = 0, print_total = 0;
8927 int print_deltify = 0, print_written = 0, print_sent = 0;
8929 if (a->verbosity < 0)
8930 return NULL;
8932 if (refname) {
8933 const char *status = success ? "accepted" : "rejected";
8935 if (success) {
8936 struct got_pathlist_entry *pe;
8937 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8938 const char *branchname = pe->path;
8939 if (got_path_cmp(branchname, refname,
8940 strlen(branchname), strlen(refname)) == 0) {
8941 status = "deleted";
8942 a->sent_something = 1;
8943 break;
8948 if (a->printed_something)
8949 putchar('\n');
8950 printf("Server has %s %s", status, refname);
8951 if (errmsg)
8952 printf(": %s", errmsg);
8953 a->printed_something = 1;
8954 return NULL;
8957 if (a->last_ncolored != ncolored) {
8958 print_colored = 1;
8959 a->last_ncolored = ncolored;
8962 if (a->last_nfound != nfound) {
8963 print_colored = 1;
8964 print_found = 1;
8965 a->last_nfound = nfound;
8968 if (a->last_ntrees != ntrees) {
8969 print_colored = 1;
8970 print_found = 1;
8971 print_trees = 1;
8972 a->last_ntrees = ntrees;
8975 if ((print_colored || print_found || print_trees) &&
8976 !a->loading_done) {
8977 printf("\r");
8978 print_load_info(print_colored, print_found, print_trees,
8979 ncolored, nfound, ntrees);
8980 a->printed_something = 1;
8981 fflush(stdout);
8982 return NULL;
8983 } else if (!a->loading_done) {
8984 printf("\r");
8985 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8986 printf("\n");
8987 a->loading_done = 1;
8990 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8991 return got_error_from_errno("fmt_scaled");
8992 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8993 return got_error_from_errno("fmt_scaled");
8995 if (a->last_ncommits != ncommits) {
8996 print_searching = 1;
8997 a->last_ncommits = ncommits;
9000 if (a->last_nobj_total != nobj_total) {
9001 print_searching = 1;
9002 print_total = 1;
9003 a->last_nobj_total = nobj_total;
9006 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9007 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9008 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9009 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9010 return got_error(GOT_ERR_NO_SPACE);
9013 if (nobj_deltify > 0 || nobj_written > 0) {
9014 if (nobj_deltify > 0) {
9015 p_deltify = (nobj_deltify * 100) / nobj_total;
9016 if (p_deltify != a->last_p_deltify) {
9017 a->last_p_deltify = p_deltify;
9018 print_searching = 1;
9019 print_total = 1;
9020 print_deltify = 1;
9023 if (nobj_written > 0) {
9024 p_written = (nobj_written * 100) / nobj_total;
9025 if (p_written != a->last_p_written) {
9026 a->last_p_written = p_written;
9027 print_searching = 1;
9028 print_total = 1;
9029 print_deltify = 1;
9030 print_written = 1;
9035 if (bytes_sent > 0) {
9036 p_sent = (bytes_sent * 100) / packfile_size;
9037 if (p_sent != a->last_p_sent) {
9038 a->last_p_sent = p_sent;
9039 print_searching = 1;
9040 print_total = 1;
9041 print_deltify = 1;
9042 print_written = 1;
9043 print_sent = 1;
9045 a->sent_something = 1;
9048 if (print_searching || print_total || print_deltify || print_written ||
9049 print_sent)
9050 printf("\r");
9051 if (print_searching)
9052 printf("packing %d reference%s", ncommits,
9053 ncommits == 1 ? "" : "s");
9054 if (print_total)
9055 printf("; %d object%s", nobj_total,
9056 nobj_total == 1 ? "" : "s");
9057 if (print_deltify)
9058 printf("; deltify: %d%%", p_deltify);
9059 if (print_sent)
9060 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9061 scaled_packsize, p_sent);
9062 else if (print_written)
9063 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9064 scaled_packsize, p_written);
9065 if (print_searching || print_total || print_deltify ||
9066 print_written || print_sent) {
9067 a->printed_something = 1;
9068 fflush(stdout);
9070 return NULL;
9073 static const struct got_error *
9074 cmd_send(int argc, char *argv[])
9076 const struct got_error *error = NULL;
9077 char *cwd = NULL, *repo_path = NULL;
9078 const char *remote_name;
9079 char *proto = NULL, *host = NULL, *port = NULL;
9080 char *repo_name = NULL, *server_path = NULL;
9081 const struct got_remote_repo *remotes, *remote = NULL;
9082 int nremotes, nbranches = 0, ndelete_branches = 0;
9083 struct got_repository *repo = NULL;
9084 struct got_worktree *worktree = NULL;
9085 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9086 struct got_pathlist_head branches;
9087 struct got_pathlist_head tags;
9088 struct got_reflist_head all_branches;
9089 struct got_reflist_head all_tags;
9090 struct got_pathlist_head delete_args;
9091 struct got_pathlist_head delete_branches;
9092 struct got_reflist_entry *re;
9093 struct got_pathlist_entry *pe;
9094 int i, ch, sendfd = -1, sendstatus;
9095 pid_t sendpid = -1;
9096 struct got_send_progress_arg spa;
9097 int verbosity = 0, overwrite_refs = 0;
9098 int send_all_branches = 0, send_all_tags = 0;
9099 struct got_reference *ref = NULL;
9100 int *pack_fds = NULL;
9102 TAILQ_INIT(&branches);
9103 TAILQ_INIT(&tags);
9104 TAILQ_INIT(&all_branches);
9105 TAILQ_INIT(&all_tags);
9106 TAILQ_INIT(&delete_args);
9107 TAILQ_INIT(&delete_branches);
9109 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9110 switch (ch) {
9111 case 'a':
9112 send_all_branches = 1;
9113 break;
9114 case 'b':
9115 error = got_pathlist_append(&branches, optarg, NULL);
9116 if (error)
9117 return error;
9118 nbranches++;
9119 break;
9120 case 'd':
9121 error = got_pathlist_append(&delete_args, optarg, NULL);
9122 if (error)
9123 return error;
9124 break;
9125 case 'f':
9126 overwrite_refs = 1;
9127 break;
9128 case 'q':
9129 verbosity = -1;
9130 break;
9131 case 'r':
9132 repo_path = realpath(optarg, NULL);
9133 if (repo_path == NULL)
9134 return got_error_from_errno2("realpath",
9135 optarg);
9136 got_path_strip_trailing_slashes(repo_path);
9137 break;
9138 case 'T':
9139 send_all_tags = 1;
9140 break;
9141 case 't':
9142 error = got_pathlist_append(&tags, optarg, NULL);
9143 if (error)
9144 return error;
9145 break;
9146 case 'v':
9147 if (verbosity < 0)
9148 verbosity = 0;
9149 else if (verbosity < 3)
9150 verbosity++;
9151 break;
9152 default:
9153 usage_send();
9154 /* NOTREACHED */
9157 argc -= optind;
9158 argv += optind;
9160 if (send_all_branches && !TAILQ_EMPTY(&branches))
9161 option_conflict('a', 'b');
9162 if (send_all_tags && !TAILQ_EMPTY(&tags))
9163 option_conflict('T', 't');
9166 if (argc == 0)
9167 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9168 else if (argc == 1)
9169 remote_name = argv[0];
9170 else
9171 usage_send();
9173 cwd = getcwd(NULL, 0);
9174 if (cwd == NULL) {
9175 error = got_error_from_errno("getcwd");
9176 goto done;
9179 error = got_repo_pack_fds_open(&pack_fds);
9180 if (error != NULL)
9181 goto done;
9183 if (repo_path == NULL) {
9184 error = got_worktree_open(&worktree, cwd);
9185 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9186 goto done;
9187 else
9188 error = NULL;
9189 if (worktree) {
9190 repo_path =
9191 strdup(got_worktree_get_repo_path(worktree));
9192 if (repo_path == NULL)
9193 error = got_error_from_errno("strdup");
9194 if (error)
9195 goto done;
9196 } else {
9197 repo_path = strdup(cwd);
9198 if (repo_path == NULL) {
9199 error = got_error_from_errno("strdup");
9200 goto done;
9205 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9206 if (error)
9207 goto done;
9209 if (worktree) {
9210 worktree_conf = got_worktree_get_gotconfig(worktree);
9211 if (worktree_conf) {
9212 got_gotconfig_get_remotes(&nremotes, &remotes,
9213 worktree_conf);
9214 for (i = 0; i < nremotes; i++) {
9215 if (strcmp(remotes[i].name, remote_name) == 0) {
9216 remote = &remotes[i];
9217 break;
9222 if (remote == NULL) {
9223 repo_conf = got_repo_get_gotconfig(repo);
9224 if (repo_conf) {
9225 got_gotconfig_get_remotes(&nremotes, &remotes,
9226 repo_conf);
9227 for (i = 0; i < nremotes; i++) {
9228 if (strcmp(remotes[i].name, remote_name) == 0) {
9229 remote = &remotes[i];
9230 break;
9235 if (remote == NULL) {
9236 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9237 for (i = 0; i < nremotes; i++) {
9238 if (strcmp(remotes[i].name, remote_name) == 0) {
9239 remote = &remotes[i];
9240 break;
9244 if (remote == NULL) {
9245 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9246 goto done;
9249 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9250 &repo_name, remote->send_url);
9251 if (error)
9252 goto done;
9254 if (strcmp(proto, "git") == 0) {
9255 #ifndef PROFILE
9256 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9257 "sendfd dns inet unveil", NULL) == -1)
9258 err(1, "pledge");
9259 #endif
9260 } else if (strcmp(proto, "git+ssh") == 0 ||
9261 strcmp(proto, "ssh") == 0) {
9262 #ifndef PROFILE
9263 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9264 "sendfd unveil", NULL) == -1)
9265 err(1, "pledge");
9266 #endif
9267 } else if (strcmp(proto, "http") == 0 ||
9268 strcmp(proto, "git+http") == 0) {
9269 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9270 goto done;
9271 } else {
9272 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9273 goto done;
9276 error = got_dial_apply_unveil(proto);
9277 if (error)
9278 goto done;
9280 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9281 if (error)
9282 goto done;
9284 if (send_all_branches) {
9285 error = got_ref_list(&all_branches, repo, "refs/heads",
9286 got_ref_cmp_by_name, NULL);
9287 if (error)
9288 goto done;
9289 TAILQ_FOREACH(re, &all_branches, entry) {
9290 const char *branchname = got_ref_get_name(re->ref);
9291 error = got_pathlist_append(&branches,
9292 branchname, NULL);
9293 if (error)
9294 goto done;
9295 nbranches++;
9297 } else if (nbranches == 0) {
9298 for (i = 0; i < remote->nsend_branches; i++) {
9299 error = got_pathlist_append(&branches,
9300 remote->send_branches[i], NULL);
9301 if (error)
9302 goto done;
9306 if (send_all_tags) {
9307 error = got_ref_list(&all_tags, repo, "refs/tags",
9308 got_ref_cmp_by_name, NULL);
9309 if (error)
9310 goto done;
9311 TAILQ_FOREACH(re, &all_tags, entry) {
9312 const char *tagname = got_ref_get_name(re->ref);
9313 error = got_pathlist_append(&tags,
9314 tagname, NULL);
9315 if (error)
9316 goto done;
9321 * To prevent accidents only branches in refs/heads/ can be deleted
9322 * with 'got send -d'.
9323 * Deleting anything else requires local repository access or Git.
9325 TAILQ_FOREACH(pe, &delete_args, entry) {
9326 const char *branchname = pe->path;
9327 char *s;
9328 struct got_pathlist_entry *new;
9329 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9330 s = strdup(branchname);
9331 if (s == NULL) {
9332 error = got_error_from_errno("strdup");
9333 goto done;
9335 } else {
9336 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9337 error = got_error_from_errno("asprintf");
9338 goto done;
9341 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9342 if (error || new == NULL /* duplicate */)
9343 free(s);
9344 if (error)
9345 goto done;
9346 ndelete_branches++;
9349 if (nbranches == 0 && ndelete_branches == 0) {
9350 struct got_reference *head_ref;
9351 if (worktree)
9352 error = got_ref_open(&head_ref, repo,
9353 got_worktree_get_head_ref_name(worktree), 0);
9354 else
9355 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9356 if (error)
9357 goto done;
9358 if (got_ref_is_symbolic(head_ref)) {
9359 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9360 got_ref_close(head_ref);
9361 if (error)
9362 goto done;
9363 } else
9364 ref = head_ref;
9365 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9366 NULL);
9367 if (error)
9368 goto done;
9369 nbranches++;
9372 if (verbosity >= 0) {
9373 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9374 remote->name, proto, host,
9375 port ? ":" : "", port ? port : "",
9376 *server_path == '/' ? "" : "/", server_path);
9379 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9380 server_path, verbosity);
9381 if (error)
9382 goto done;
9384 memset(&spa, 0, sizeof(spa));
9385 spa.last_scaled_packsize[0] = '\0';
9386 spa.last_p_deltify = -1;
9387 spa.last_p_written = -1;
9388 spa.verbosity = verbosity;
9389 spa.delete_branches = &delete_branches;
9390 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9391 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9392 check_cancelled, NULL);
9393 if (spa.printed_something)
9394 putchar('\n');
9395 if (error)
9396 goto done;
9397 if (!spa.sent_something && verbosity >= 0)
9398 printf("Already up-to-date\n");
9399 done:
9400 if (sendpid > 0) {
9401 if (kill(sendpid, SIGTERM) == -1)
9402 error = got_error_from_errno("kill");
9403 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9404 error = got_error_from_errno("waitpid");
9406 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9407 error = got_error_from_errno("close");
9408 if (repo) {
9409 const struct got_error *close_err = got_repo_close(repo);
9410 if (error == NULL)
9411 error = close_err;
9413 if (worktree)
9414 got_worktree_close(worktree);
9415 if (pack_fds) {
9416 const struct got_error *pack_err =
9417 got_repo_pack_fds_close(pack_fds);
9418 if (error == NULL)
9419 error = pack_err;
9421 if (ref)
9422 got_ref_close(ref);
9423 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9424 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9425 got_ref_list_free(&all_branches);
9426 got_ref_list_free(&all_tags);
9427 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9428 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9429 free(cwd);
9430 free(repo_path);
9431 free(proto);
9432 free(host);
9433 free(port);
9434 free(server_path);
9435 free(repo_name);
9436 return error;
9439 __dead static void
9440 usage_cherrypick(void)
9442 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9443 exit(1);
9446 static const struct got_error *
9447 cmd_cherrypick(int argc, char *argv[])
9449 const struct got_error *error = NULL;
9450 struct got_worktree *worktree = NULL;
9451 struct got_repository *repo = NULL;
9452 char *cwd = NULL, *commit_id_str = NULL;
9453 struct got_object_id *commit_id = NULL;
9454 struct got_commit_object *commit = NULL;
9455 struct got_object_qid *pid;
9456 int ch;
9457 struct got_update_progress_arg upa;
9458 int *pack_fds = NULL;
9460 while ((ch = getopt(argc, argv, "")) != -1) {
9461 switch (ch) {
9462 default:
9463 usage_cherrypick();
9464 /* NOTREACHED */
9468 argc -= optind;
9469 argv += optind;
9471 #ifndef PROFILE
9472 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9473 "unveil", NULL) == -1)
9474 err(1, "pledge");
9475 #endif
9476 if (argc != 1)
9477 usage_cherrypick();
9479 cwd = getcwd(NULL, 0);
9480 if (cwd == NULL) {
9481 error = got_error_from_errno("getcwd");
9482 goto done;
9485 error = got_repo_pack_fds_open(&pack_fds);
9486 if (error != NULL)
9487 goto done;
9489 error = got_worktree_open(&worktree, cwd);
9490 if (error) {
9491 if (error->code == GOT_ERR_NOT_WORKTREE)
9492 error = wrap_not_worktree_error(error, "cherrypick",
9493 cwd);
9494 goto done;
9497 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9498 NULL, pack_fds);
9499 if (error != NULL)
9500 goto done;
9502 error = apply_unveil(got_repo_get_path(repo), 0,
9503 got_worktree_get_root_path(worktree));
9504 if (error)
9505 goto done;
9507 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9508 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9509 if (error)
9510 goto done;
9511 error = got_object_id_str(&commit_id_str, commit_id);
9512 if (error)
9513 goto done;
9515 error = got_object_open_as_commit(&commit, repo, commit_id);
9516 if (error)
9517 goto done;
9518 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9519 memset(&upa, 0, sizeof(upa));
9520 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9521 commit_id, repo, update_progress, &upa, check_cancelled,
9522 NULL);
9523 if (error != NULL)
9524 goto done;
9526 if (upa.did_something)
9527 printf("Merged commit %s\n", commit_id_str);
9528 print_merge_progress_stats(&upa);
9529 done:
9530 if (commit)
9531 got_object_commit_close(commit);
9532 free(commit_id_str);
9533 if (worktree)
9534 got_worktree_close(worktree);
9535 if (repo) {
9536 const struct got_error *close_err = got_repo_close(repo);
9537 if (error == NULL)
9538 error = close_err;
9540 if (pack_fds) {
9541 const struct got_error *pack_err =
9542 got_repo_pack_fds_close(pack_fds);
9543 if (error == NULL)
9544 error = pack_err;
9547 return error;
9550 __dead static void
9551 usage_backout(void)
9553 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9554 exit(1);
9557 static const struct got_error *
9558 cmd_backout(int argc, char *argv[])
9560 const struct got_error *error = NULL;
9561 struct got_worktree *worktree = NULL;
9562 struct got_repository *repo = NULL;
9563 char *cwd = NULL, *commit_id_str = NULL;
9564 struct got_object_id *commit_id = NULL;
9565 struct got_commit_object *commit = NULL;
9566 struct got_object_qid *pid;
9567 int ch;
9568 struct got_update_progress_arg upa;
9569 int *pack_fds = NULL;
9571 while ((ch = getopt(argc, argv, "")) != -1) {
9572 switch (ch) {
9573 default:
9574 usage_backout();
9575 /* NOTREACHED */
9579 argc -= optind;
9580 argv += optind;
9582 #ifndef PROFILE
9583 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9584 "unveil", NULL) == -1)
9585 err(1, "pledge");
9586 #endif
9587 if (argc != 1)
9588 usage_backout();
9590 cwd = getcwd(NULL, 0);
9591 if (cwd == NULL) {
9592 error = got_error_from_errno("getcwd");
9593 goto done;
9596 error = got_repo_pack_fds_open(&pack_fds);
9597 if (error != NULL)
9598 goto done;
9600 error = got_worktree_open(&worktree, cwd);
9601 if (error) {
9602 if (error->code == GOT_ERR_NOT_WORKTREE)
9603 error = wrap_not_worktree_error(error, "backout", cwd);
9604 goto done;
9607 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9608 NULL, pack_fds);
9609 if (error != NULL)
9610 goto done;
9612 error = apply_unveil(got_repo_get_path(repo), 0,
9613 got_worktree_get_root_path(worktree));
9614 if (error)
9615 goto done;
9617 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9618 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9619 if (error)
9620 goto done;
9621 error = got_object_id_str(&commit_id_str, commit_id);
9622 if (error)
9623 goto done;
9625 error = got_object_open_as_commit(&commit, repo, commit_id);
9626 if (error)
9627 goto done;
9628 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9629 if (pid == NULL) {
9630 error = got_error(GOT_ERR_ROOT_COMMIT);
9631 goto done;
9634 memset(&upa, 0, sizeof(upa));
9635 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9636 repo, update_progress, &upa, check_cancelled, NULL);
9637 if (error != NULL)
9638 goto done;
9640 if (upa.did_something)
9641 printf("Backed out commit %s\n", commit_id_str);
9642 print_merge_progress_stats(&upa);
9643 done:
9644 if (commit)
9645 got_object_commit_close(commit);
9646 free(commit_id_str);
9647 if (worktree)
9648 got_worktree_close(worktree);
9649 if (repo) {
9650 const struct got_error *close_err = got_repo_close(repo);
9651 if (error == NULL)
9652 error = close_err;
9654 if (pack_fds) {
9655 const struct got_error *pack_err =
9656 got_repo_pack_fds_close(pack_fds);
9657 if (error == NULL)
9658 error = pack_err;
9660 return error;
9663 __dead static void
9664 usage_rebase(void)
9666 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9667 exit(1);
9670 static void
9671 trim_logmsg(char *logmsg, int limit)
9673 char *nl;
9674 size_t len;
9676 len = strlen(logmsg);
9677 if (len > limit)
9678 len = limit;
9679 logmsg[len] = '\0';
9680 nl = strchr(logmsg, '\n');
9681 if (nl)
9682 *nl = '\0';
9685 static const struct got_error *
9686 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9688 const struct got_error *err;
9689 char *logmsg0 = NULL;
9690 const char *s;
9692 err = got_object_commit_get_logmsg(&logmsg0, commit);
9693 if (err)
9694 return err;
9696 s = logmsg0;
9697 while (isspace((unsigned char)s[0]))
9698 s++;
9700 *logmsg = strdup(s);
9701 if (*logmsg == NULL) {
9702 err = got_error_from_errno("strdup");
9703 goto done;
9706 trim_logmsg(*logmsg, limit);
9707 done:
9708 free(logmsg0);
9709 return err;
9712 static const struct got_error *
9713 show_rebase_merge_conflict(struct got_object_id *id,
9714 struct got_repository *repo)
9716 const struct got_error *err;
9717 struct got_commit_object *commit = NULL;
9718 char *id_str = NULL, *logmsg = NULL;
9720 err = got_object_open_as_commit(&commit, repo, id);
9721 if (err)
9722 return err;
9724 err = got_object_id_str(&id_str, id);
9725 if (err)
9726 goto done;
9728 id_str[12] = '\0';
9730 err = get_short_logmsg(&logmsg, 42, commit);
9731 if (err)
9732 goto done;
9734 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9735 done:
9736 free(id_str);
9737 got_object_commit_close(commit);
9738 free(logmsg);
9739 return err;
9742 static const struct got_error *
9743 show_rebase_progress(struct got_commit_object *commit,
9744 struct got_object_id *old_id, struct got_object_id *new_id)
9746 const struct got_error *err;
9747 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9749 err = got_object_id_str(&old_id_str, old_id);
9750 if (err)
9751 goto done;
9753 if (new_id) {
9754 err = got_object_id_str(&new_id_str, new_id);
9755 if (err)
9756 goto done;
9759 old_id_str[12] = '\0';
9760 if (new_id_str)
9761 new_id_str[12] = '\0';
9763 err = get_short_logmsg(&logmsg, 42, commit);
9764 if (err)
9765 goto done;
9767 printf("%s -> %s: %s\n", old_id_str,
9768 new_id_str ? new_id_str : "no-op change", logmsg);
9769 done:
9770 free(old_id_str);
9771 free(new_id_str);
9772 free(logmsg);
9773 return err;
9776 static const struct got_error *
9777 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9778 struct got_reference *branch, struct got_reference *new_base_branch,
9779 struct got_reference *tmp_branch, struct got_repository *repo,
9780 int create_backup)
9782 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9783 return got_worktree_rebase_complete(worktree, fileindex,
9784 new_base_branch, tmp_branch, branch, repo, create_backup);
9787 static const struct got_error *
9788 rebase_commit(struct got_pathlist_head *merged_paths,
9789 struct got_worktree *worktree, struct got_fileindex *fileindex,
9790 struct got_reference *tmp_branch, const char *committer,
9791 struct got_object_id *commit_id, struct got_repository *repo)
9793 const struct got_error *error;
9794 struct got_commit_object *commit;
9795 struct got_object_id *new_commit_id;
9797 error = got_object_open_as_commit(&commit, repo, commit_id);
9798 if (error)
9799 return error;
9801 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9802 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9803 repo);
9804 if (error) {
9805 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9806 goto done;
9807 error = show_rebase_progress(commit, commit_id, NULL);
9808 } else {
9809 error = show_rebase_progress(commit, commit_id, new_commit_id);
9810 free(new_commit_id);
9812 done:
9813 got_object_commit_close(commit);
9814 return error;
9817 struct check_path_prefix_arg {
9818 const char *path_prefix;
9819 size_t len;
9820 int errcode;
9823 static const struct got_error *
9824 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9825 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9826 struct got_object_id *id1, struct got_object_id *id2,
9827 const char *path1, const char *path2,
9828 mode_t mode1, mode_t mode2, struct got_repository *repo)
9830 struct check_path_prefix_arg *a = arg;
9832 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9833 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9834 return got_error(a->errcode);
9836 return NULL;
9839 static const struct got_error *
9840 check_path_prefix(struct got_object_id *parent_id,
9841 struct got_object_id *commit_id, const char *path_prefix,
9842 int errcode, struct got_repository *repo)
9844 const struct got_error *err;
9845 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9846 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9847 struct check_path_prefix_arg cpp_arg;
9849 if (got_path_is_root_dir(path_prefix))
9850 return NULL;
9852 err = got_object_open_as_commit(&commit, repo, commit_id);
9853 if (err)
9854 goto done;
9856 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9857 if (err)
9858 goto done;
9860 err = got_object_open_as_tree(&tree1, repo,
9861 got_object_commit_get_tree_id(parent_commit));
9862 if (err)
9863 goto done;
9865 err = got_object_open_as_tree(&tree2, repo,
9866 got_object_commit_get_tree_id(commit));
9867 if (err)
9868 goto done;
9870 cpp_arg.path_prefix = path_prefix;
9871 while (cpp_arg.path_prefix[0] == '/')
9872 cpp_arg.path_prefix++;
9873 cpp_arg.len = strlen(cpp_arg.path_prefix);
9874 cpp_arg.errcode = errcode;
9875 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9876 check_path_prefix_in_diff, &cpp_arg, 0);
9877 done:
9878 if (tree1)
9879 got_object_tree_close(tree1);
9880 if (tree2)
9881 got_object_tree_close(tree2);
9882 if (commit)
9883 got_object_commit_close(commit);
9884 if (parent_commit)
9885 got_object_commit_close(parent_commit);
9886 return err;
9889 static const struct got_error *
9890 collect_commits(struct got_object_id_queue *commits,
9891 struct got_object_id *initial_commit_id,
9892 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9893 const char *path_prefix, int path_prefix_errcode,
9894 struct got_repository *repo)
9896 const struct got_error *err = NULL;
9897 struct got_commit_graph *graph = NULL;
9898 struct got_object_id parent_id, commit_id;
9899 struct got_object_qid *qid;
9901 err = got_commit_graph_open(&graph, "/", 1);
9902 if (err)
9903 return err;
9905 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9906 check_cancelled, NULL);
9907 if (err)
9908 goto done;
9910 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9911 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9912 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9913 check_cancelled, NULL);
9914 if (err) {
9915 if (err->code == GOT_ERR_ITER_COMPLETED) {
9916 err = got_error_msg(GOT_ERR_ANCESTRY,
9917 "ran out of commits to rebase before "
9918 "youngest common ancestor commit has "
9919 "been reached?!?");
9921 goto done;
9922 } else {
9923 err = check_path_prefix(&parent_id, &commit_id,
9924 path_prefix, path_prefix_errcode, repo);
9925 if (err)
9926 goto done;
9928 err = got_object_qid_alloc(&qid, &commit_id);
9929 if (err)
9930 goto done;
9931 STAILQ_INSERT_HEAD(commits, qid, entry);
9933 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9936 done:
9937 got_commit_graph_close(graph);
9938 return err;
9941 static const struct got_error *
9942 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9944 const struct got_error *err = NULL;
9945 time_t committer_time;
9946 struct tm tm;
9947 char datebuf[11]; /* YYYY-MM-DD + NUL */
9948 char *author0 = NULL, *author, *smallerthan;
9949 char *logmsg0 = NULL, *logmsg, *newline;
9951 committer_time = got_object_commit_get_committer_time(commit);
9952 if (gmtime_r(&committer_time, &tm) == NULL)
9953 return got_error_from_errno("gmtime_r");
9954 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9955 return got_error(GOT_ERR_NO_SPACE);
9957 author0 = strdup(got_object_commit_get_author(commit));
9958 if (author0 == NULL)
9959 return got_error_from_errno("strdup");
9960 author = author0;
9961 smallerthan = strchr(author, '<');
9962 if (smallerthan && smallerthan[1] != '\0')
9963 author = smallerthan + 1;
9964 author[strcspn(author, "@>")] = '\0';
9966 err = got_object_commit_get_logmsg(&logmsg0, commit);
9967 if (err)
9968 goto done;
9969 logmsg = logmsg0;
9970 while (*logmsg == '\n')
9971 logmsg++;
9972 newline = strchr(logmsg, '\n');
9973 if (newline)
9974 *newline = '\0';
9976 if (asprintf(brief_str, "%s %s %s",
9977 datebuf, author, logmsg) == -1)
9978 err = got_error_from_errno("asprintf");
9979 done:
9980 free(author0);
9981 free(logmsg0);
9982 return err;
9985 static const struct got_error *
9986 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9987 struct got_repository *repo)
9989 const struct got_error *err;
9990 char *id_str;
9992 err = got_object_id_str(&id_str, id);
9993 if (err)
9994 return err;
9996 err = got_ref_delete(ref, repo);
9997 if (err)
9998 goto done;
10000 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10001 done:
10002 free(id_str);
10003 return err;
10006 static const struct got_error *
10007 print_backup_ref(const char *branch_name, const char *new_id_str,
10008 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10009 struct got_reflist_object_id_map *refs_idmap,
10010 struct got_repository *repo)
10012 const struct got_error *err = NULL;
10013 struct got_reflist_head *refs;
10014 char *refs_str = NULL;
10015 struct got_object_id *new_commit_id = NULL;
10016 struct got_commit_object *new_commit = NULL;
10017 char *new_commit_brief_str = NULL;
10018 struct got_object_id *yca_id = NULL;
10019 struct got_commit_object *yca_commit = NULL;
10020 char *yca_id_str = NULL, *yca_brief_str = NULL;
10021 char *custom_refs_str;
10023 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10024 return got_error_from_errno("asprintf");
10026 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10027 0, 0, refs_idmap, custom_refs_str);
10028 if (err)
10029 goto done;
10031 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10032 if (err)
10033 goto done;
10035 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10036 if (refs) {
10037 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10038 if (err)
10039 goto done;
10042 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10043 if (err)
10044 goto done;
10046 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10047 if (err)
10048 goto done;
10050 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10051 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10052 if (err)
10053 goto done;
10055 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10056 refs_str ? " (" : "", refs_str ? refs_str : "",
10057 refs_str ? ")" : "", new_commit_brief_str);
10058 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10059 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10060 free(refs_str);
10061 refs_str = NULL;
10063 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10064 if (err)
10065 goto done;
10067 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10068 if (err)
10069 goto done;
10071 err = got_object_id_str(&yca_id_str, yca_id);
10072 if (err)
10073 goto done;
10075 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10076 if (refs) {
10077 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10078 if (err)
10079 goto done;
10081 printf("history forked at %s%s%s%s\n %s\n",
10082 yca_id_str,
10083 refs_str ? " (" : "", refs_str ? refs_str : "",
10084 refs_str ? ")" : "", yca_brief_str);
10086 done:
10087 free(custom_refs_str);
10088 free(new_commit_id);
10089 free(refs_str);
10090 free(yca_id);
10091 free(yca_id_str);
10092 free(yca_brief_str);
10093 if (new_commit)
10094 got_object_commit_close(new_commit);
10095 if (yca_commit)
10096 got_object_commit_close(yca_commit);
10098 return NULL;
10101 static const struct got_error *
10102 process_backup_refs(const char *backup_ref_prefix,
10103 const char *wanted_branch_name,
10104 int delete, struct got_repository *repo)
10106 const struct got_error *err;
10107 struct got_reflist_head refs, backup_refs;
10108 struct got_reflist_entry *re;
10109 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10110 struct got_object_id *old_commit_id = NULL;
10111 char *branch_name = NULL;
10112 struct got_commit_object *old_commit = NULL;
10113 struct got_reflist_object_id_map *refs_idmap = NULL;
10114 int wanted_branch_found = 0;
10116 TAILQ_INIT(&refs);
10117 TAILQ_INIT(&backup_refs);
10119 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10120 if (err)
10121 return err;
10123 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10124 if (err)
10125 goto done;
10127 if (wanted_branch_name) {
10128 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10129 wanted_branch_name += 11;
10132 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10133 got_ref_cmp_by_commit_timestamp_descending, repo);
10134 if (err)
10135 goto done;
10137 TAILQ_FOREACH(re, &backup_refs, entry) {
10138 const char *refname = got_ref_get_name(re->ref);
10139 char *slash;
10141 err = check_cancelled(NULL);
10142 if (err)
10143 break;
10145 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10146 if (err)
10147 break;
10149 err = got_object_open_as_commit(&old_commit, repo,
10150 old_commit_id);
10151 if (err)
10152 break;
10154 if (strncmp(backup_ref_prefix, refname,
10155 backup_ref_prefix_len) == 0)
10156 refname += backup_ref_prefix_len;
10158 while (refname[0] == '/')
10159 refname++;
10161 branch_name = strdup(refname);
10162 if (branch_name == NULL) {
10163 err = got_error_from_errno("strdup");
10164 break;
10166 slash = strrchr(branch_name, '/');
10167 if (slash) {
10168 *slash = '\0';
10169 refname += strlen(branch_name) + 1;
10172 if (wanted_branch_name == NULL ||
10173 strcmp(wanted_branch_name, branch_name) == 0) {
10174 wanted_branch_found = 1;
10175 if (delete) {
10176 err = delete_backup_ref(re->ref,
10177 old_commit_id, repo);
10178 } else {
10179 err = print_backup_ref(branch_name, refname,
10180 old_commit_id, old_commit, refs_idmap,
10181 repo);
10183 if (err)
10184 break;
10187 free(old_commit_id);
10188 old_commit_id = NULL;
10189 free(branch_name);
10190 branch_name = NULL;
10191 got_object_commit_close(old_commit);
10192 old_commit = NULL;
10195 if (wanted_branch_name && !wanted_branch_found) {
10196 err = got_error_fmt(GOT_ERR_NOT_REF,
10197 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10199 done:
10200 if (refs_idmap)
10201 got_reflist_object_id_map_free(refs_idmap);
10202 got_ref_list_free(&refs);
10203 got_ref_list_free(&backup_refs);
10204 free(old_commit_id);
10205 free(branch_name);
10206 if (old_commit)
10207 got_object_commit_close(old_commit);
10208 return err;
10211 static const struct got_error *
10212 abort_progress(void *arg, unsigned char status, const char *path)
10215 * Unversioned files should not clutter progress output when
10216 * an operation is aborted.
10218 if (status == GOT_STATUS_UNVERSIONED)
10219 return NULL;
10221 return update_progress(arg, status, path);
10224 static const struct got_error *
10225 cmd_rebase(int argc, char *argv[])
10227 const struct got_error *error = NULL;
10228 struct got_worktree *worktree = NULL;
10229 struct got_repository *repo = NULL;
10230 struct got_fileindex *fileindex = NULL;
10231 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10232 struct got_reference *branch = NULL;
10233 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10234 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10235 struct got_object_id *resume_commit_id = NULL;
10236 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10237 struct got_object_id *head_commit_id = NULL;
10238 struct got_reference *head_ref = NULL;
10239 struct got_commit_object *commit = NULL;
10240 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10241 int histedit_in_progress = 0, merge_in_progress = 0;
10242 int create_backup = 1, list_backups = 0, delete_backups = 0;
10243 struct got_object_id_queue commits;
10244 struct got_pathlist_head merged_paths;
10245 const struct got_object_id_queue *parent_ids;
10246 struct got_object_qid *qid, *pid;
10247 struct got_update_progress_arg upa;
10248 int *pack_fds = NULL;
10250 STAILQ_INIT(&commits);
10251 TAILQ_INIT(&merged_paths);
10252 memset(&upa, 0, sizeof(upa));
10254 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10255 switch (ch) {
10256 case 'a':
10257 abort_rebase = 1;
10258 break;
10259 case 'c':
10260 continue_rebase = 1;
10261 break;
10262 case 'l':
10263 list_backups = 1;
10264 break;
10265 case 'X':
10266 delete_backups = 1;
10267 break;
10268 default:
10269 usage_rebase();
10270 /* NOTREACHED */
10274 argc -= optind;
10275 argv += optind;
10277 #ifndef PROFILE
10278 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10279 "unveil", NULL) == -1)
10280 err(1, "pledge");
10281 #endif
10282 if (list_backups) {
10283 if (abort_rebase)
10284 option_conflict('l', 'a');
10285 if (continue_rebase)
10286 option_conflict('l', 'c');
10287 if (delete_backups)
10288 option_conflict('l', 'X');
10289 if (argc != 0 && argc != 1)
10290 usage_rebase();
10291 } else if (delete_backups) {
10292 if (abort_rebase)
10293 option_conflict('X', 'a');
10294 if (continue_rebase)
10295 option_conflict('X', 'c');
10296 if (list_backups)
10297 option_conflict('l', 'X');
10298 if (argc != 0 && argc != 1)
10299 usage_rebase();
10300 } else {
10301 if (abort_rebase && continue_rebase)
10302 usage_rebase();
10303 else if (abort_rebase || continue_rebase) {
10304 if (argc != 0)
10305 usage_rebase();
10306 } else if (argc != 1)
10307 usage_rebase();
10310 cwd = getcwd(NULL, 0);
10311 if (cwd == NULL) {
10312 error = got_error_from_errno("getcwd");
10313 goto done;
10316 error = got_repo_pack_fds_open(&pack_fds);
10317 if (error != NULL)
10318 goto done;
10320 error = got_worktree_open(&worktree, cwd);
10321 if (error) {
10322 if (list_backups || delete_backups) {
10323 if (error->code != GOT_ERR_NOT_WORKTREE)
10324 goto done;
10325 } else {
10326 if (error->code == GOT_ERR_NOT_WORKTREE)
10327 error = wrap_not_worktree_error(error,
10328 "rebase", cwd);
10329 goto done;
10333 error = get_gitconfig_path(&gitconfig_path);
10334 if (error)
10335 goto done;
10336 error = got_repo_open(&repo,
10337 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10338 gitconfig_path, pack_fds);
10339 if (error != NULL)
10340 goto done;
10342 error = get_author(&committer, repo, worktree);
10343 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10344 goto done;
10346 error = apply_unveil(got_repo_get_path(repo), 0,
10347 worktree ? got_worktree_get_root_path(worktree) : NULL);
10348 if (error)
10349 goto done;
10351 if (list_backups || delete_backups) {
10352 error = process_backup_refs(
10353 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10354 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10355 goto done; /* nothing else to do */
10358 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10359 worktree);
10360 if (error)
10361 goto done;
10362 if (histedit_in_progress) {
10363 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10364 goto done;
10367 error = got_worktree_merge_in_progress(&merge_in_progress,
10368 worktree, repo);
10369 if (error)
10370 goto done;
10371 if (merge_in_progress) {
10372 error = got_error(GOT_ERR_MERGE_BUSY);
10373 goto done;
10376 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10377 if (error)
10378 goto done;
10380 if (abort_rebase) {
10381 if (!rebase_in_progress) {
10382 error = got_error(GOT_ERR_NOT_REBASING);
10383 goto done;
10385 error = got_worktree_rebase_continue(&resume_commit_id,
10386 &new_base_branch, &tmp_branch, &branch, &fileindex,
10387 worktree, repo);
10388 if (error)
10389 goto done;
10390 printf("Switching work tree to %s\n",
10391 got_ref_get_symref_target(new_base_branch));
10392 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10393 new_base_branch, abort_progress, &upa);
10394 if (error)
10395 goto done;
10396 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10397 print_merge_progress_stats(&upa);
10398 goto done; /* nothing else to do */
10401 if (continue_rebase) {
10402 if (!rebase_in_progress) {
10403 error = got_error(GOT_ERR_NOT_REBASING);
10404 goto done;
10406 error = got_worktree_rebase_continue(&resume_commit_id,
10407 &new_base_branch, &tmp_branch, &branch, &fileindex,
10408 worktree, repo);
10409 if (error)
10410 goto done;
10412 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10413 committer, resume_commit_id, repo);
10414 if (error)
10415 goto done;
10417 yca_id = got_object_id_dup(resume_commit_id);
10418 if (yca_id == NULL) {
10419 error = got_error_from_errno("got_object_id_dup");
10420 goto done;
10422 } else {
10423 error = got_ref_open(&branch, repo, argv[0], 0);
10424 if (error != NULL)
10425 goto done;
10426 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10427 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10428 "will not rebase a branch which lives outside "
10429 "the \"refs/heads/\" reference namespace");
10430 goto done;
10434 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10435 if (error)
10436 goto done;
10438 if (!continue_rebase) {
10439 struct got_object_id *base_commit_id;
10441 error = got_ref_open(&head_ref, repo,
10442 got_worktree_get_head_ref_name(worktree), 0);
10443 if (error)
10444 goto done;
10445 error = got_ref_resolve(&head_commit_id, repo, head_ref);
10446 if (error)
10447 goto done;
10448 base_commit_id = got_worktree_get_base_commit_id(worktree);
10449 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
10450 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
10451 goto done;
10454 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10455 base_commit_id, branch_head_commit_id, 1, repo,
10456 check_cancelled, NULL);
10457 if (error)
10458 goto done;
10459 if (yca_id == NULL) {
10460 error = got_error_msg(GOT_ERR_ANCESTRY,
10461 "specified branch shares no common ancestry "
10462 "with work tree's branch");
10463 goto done;
10466 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10467 if (error) {
10468 if (error->code != GOT_ERR_ANCESTRY)
10469 goto done;
10470 error = NULL;
10471 } else {
10472 struct got_pathlist_head paths;
10473 printf("%s is already based on %s\n",
10474 got_ref_get_name(branch),
10475 got_worktree_get_head_ref_name(worktree));
10476 error = switch_head_ref(branch, branch_head_commit_id,
10477 worktree, repo);
10478 if (error)
10479 goto done;
10480 error = got_worktree_set_base_commit_id(worktree, repo,
10481 branch_head_commit_id);
10482 if (error)
10483 goto done;
10484 TAILQ_INIT(&paths);
10485 error = got_pathlist_append(&paths, "", NULL);
10486 if (error)
10487 goto done;
10488 error = got_worktree_checkout_files(worktree,
10489 &paths, repo, update_progress, &upa,
10490 check_cancelled, NULL);
10491 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
10492 if (error)
10493 goto done;
10494 if (upa.did_something) {
10495 char *id_str;
10496 error = got_object_id_str(&id_str,
10497 branch_head_commit_id);
10498 if (error)
10499 goto done;
10500 printf("Updated to %s: %s\n",
10501 got_worktree_get_head_ref_name(worktree),
10502 id_str);
10503 free(id_str);
10504 } else
10505 printf("Already up-to-date\n");
10506 print_update_progress_stats(&upa);
10507 goto done;
10511 commit_id = branch_head_commit_id;
10512 error = got_object_open_as_commit(&commit, repo, commit_id);
10513 if (error)
10514 goto done;
10516 parent_ids = got_object_commit_get_parent_ids(commit);
10517 pid = STAILQ_FIRST(parent_ids);
10518 if (pid == NULL) {
10519 error = got_error(GOT_ERR_EMPTY_REBASE);
10520 goto done;
10522 error = collect_commits(&commits, commit_id, &pid->id,
10523 yca_id, got_worktree_get_path_prefix(worktree),
10524 GOT_ERR_REBASE_PATH, repo);
10525 got_object_commit_close(commit);
10526 commit = NULL;
10527 if (error)
10528 goto done;
10530 if (!continue_rebase) {
10531 error = got_worktree_rebase_prepare(&new_base_branch,
10532 &tmp_branch, &fileindex, worktree, branch, repo);
10533 if (error)
10534 goto done;
10537 if (STAILQ_EMPTY(&commits)) {
10538 if (continue_rebase) {
10539 error = rebase_complete(worktree, fileindex,
10540 branch, new_base_branch, tmp_branch, repo,
10541 create_backup);
10542 goto done;
10543 } else {
10544 /* Fast-forward the reference of the branch. */
10545 struct got_object_id *new_head_commit_id;
10546 char *id_str;
10547 error = got_ref_resolve(&new_head_commit_id, repo,
10548 new_base_branch);
10549 if (error)
10550 goto done;
10551 error = got_object_id_str(&id_str, new_head_commit_id);
10552 if (error)
10553 goto done;
10554 printf("Forwarding %s to commit %s\n",
10555 got_ref_get_name(branch), id_str);
10556 free(id_str);
10557 error = got_ref_change_ref(branch,
10558 new_head_commit_id);
10559 if (error)
10560 goto done;
10561 /* No backup needed since objects did not change. */
10562 create_backup = 0;
10566 pid = NULL;
10567 STAILQ_FOREACH(qid, &commits, entry) {
10569 commit_id = &qid->id;
10570 parent_id = pid ? &pid->id : yca_id;
10571 pid = qid;
10573 memset(&upa, 0, sizeof(upa));
10574 error = got_worktree_rebase_merge_files(&merged_paths,
10575 worktree, fileindex, parent_id, commit_id, repo,
10576 update_progress, &upa, check_cancelled, NULL);
10577 if (error)
10578 goto done;
10580 print_merge_progress_stats(&upa);
10581 if (upa.conflicts > 0 || upa.missing > 0 ||
10582 upa.not_deleted > 0 || upa.unversioned > 0) {
10583 if (upa.conflicts > 0) {
10584 error = show_rebase_merge_conflict(&qid->id,
10585 repo);
10586 if (error)
10587 goto done;
10589 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10590 break;
10593 error = rebase_commit(&merged_paths, worktree, fileindex,
10594 tmp_branch, committer, commit_id, repo);
10595 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10596 if (error)
10597 goto done;
10600 if (upa.conflicts > 0 || upa.missing > 0 ||
10601 upa.not_deleted > 0 || upa.unversioned > 0) {
10602 error = got_worktree_rebase_postpone(worktree, fileindex);
10603 if (error)
10604 goto done;
10605 if (upa.conflicts > 0 && upa.missing == 0 &&
10606 upa.not_deleted == 0 && upa.unversioned == 0) {
10607 error = got_error_msg(GOT_ERR_CONFLICTS,
10608 "conflicts must be resolved before rebasing "
10609 "can continue");
10610 } else if (upa.conflicts > 0) {
10611 error = got_error_msg(GOT_ERR_CONFLICTS,
10612 "conflicts must be resolved before rebasing "
10613 "can continue; changes destined for some "
10614 "files were not yet merged and should be "
10615 "merged manually if required before the "
10616 "rebase operation is continued");
10617 } else {
10618 error = got_error_msg(GOT_ERR_CONFLICTS,
10619 "changes destined for some files were not "
10620 "yet merged and should be merged manually "
10621 "if required before the rebase operation "
10622 "is continued");
10624 } else
10625 error = rebase_complete(worktree, fileindex, branch,
10626 new_base_branch, tmp_branch, repo, create_backup);
10627 done:
10628 free(cwd);
10629 free(committer);
10630 free(gitconfig_path);
10631 got_object_id_queue_free(&commits);
10632 free(branch_head_commit_id);
10633 free(resume_commit_id);
10634 free(head_commit_id);
10635 free(yca_id);
10636 if (commit)
10637 got_object_commit_close(commit);
10638 if (branch)
10639 got_ref_close(branch);
10640 if (new_base_branch)
10641 got_ref_close(new_base_branch);
10642 if (tmp_branch)
10643 got_ref_close(tmp_branch);
10644 if (head_ref)
10645 got_ref_close(head_ref);
10646 if (worktree)
10647 got_worktree_close(worktree);
10648 if (repo) {
10649 const struct got_error *close_err = got_repo_close(repo);
10650 if (error == NULL)
10651 error = close_err;
10653 if (pack_fds) {
10654 const struct got_error *pack_err =
10655 got_repo_pack_fds_close(pack_fds);
10656 if (error == NULL)
10657 error = pack_err;
10659 return error;
10662 __dead static void
10663 usage_histedit(void)
10665 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10666 "[branch]\n", getprogname());
10667 exit(1);
10670 #define GOT_HISTEDIT_PICK 'p'
10671 #define GOT_HISTEDIT_EDIT 'e'
10672 #define GOT_HISTEDIT_FOLD 'f'
10673 #define GOT_HISTEDIT_DROP 'd'
10674 #define GOT_HISTEDIT_MESG 'm'
10676 static const struct got_histedit_cmd {
10677 unsigned char code;
10678 const char *name;
10679 const char *desc;
10680 } got_histedit_cmds[] = {
10681 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10682 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10683 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10684 "be used" },
10685 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10686 { GOT_HISTEDIT_MESG, "mesg",
10687 "single-line log message for commit above (open editor if empty)" },
10690 struct got_histedit_list_entry {
10691 TAILQ_ENTRY(got_histedit_list_entry) entry;
10692 struct got_object_id *commit_id;
10693 const struct got_histedit_cmd *cmd;
10694 char *logmsg;
10696 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10698 static const struct got_error *
10699 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10700 FILE *f, struct got_repository *repo)
10702 const struct got_error *err = NULL;
10703 char *logmsg = NULL, *id_str = NULL;
10704 struct got_commit_object *commit = NULL;
10705 int n;
10707 err = got_object_open_as_commit(&commit, repo, commit_id);
10708 if (err)
10709 goto done;
10711 err = get_short_logmsg(&logmsg, 34, commit);
10712 if (err)
10713 goto done;
10715 err = got_object_id_str(&id_str, commit_id);
10716 if (err)
10717 goto done;
10719 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10720 if (n < 0)
10721 err = got_ferror(f, GOT_ERR_IO);
10722 done:
10723 if (commit)
10724 got_object_commit_close(commit);
10725 free(id_str);
10726 free(logmsg);
10727 return err;
10730 static const struct got_error *
10731 histedit_write_commit_list(struct got_object_id_queue *commits,
10732 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10733 struct got_repository *repo)
10735 const struct got_error *err = NULL;
10736 struct got_object_qid *qid;
10737 const char *histedit_cmd = NULL;
10739 if (STAILQ_EMPTY(commits))
10740 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10742 STAILQ_FOREACH(qid, commits, entry) {
10743 histedit_cmd = got_histedit_cmds[0].name;
10744 if (edit_only)
10745 histedit_cmd = "edit";
10746 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10747 histedit_cmd = "fold";
10748 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10749 if (err)
10750 break;
10751 if (edit_logmsg_only) {
10752 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10753 if (n < 0) {
10754 err = got_ferror(f, GOT_ERR_IO);
10755 break;
10760 return err;
10763 static const struct got_error *
10764 write_cmd_list(FILE *f, const char *branch_name,
10765 struct got_object_id_queue *commits)
10767 const struct got_error *err = NULL;
10768 size_t i;
10769 int n;
10770 char *id_str;
10771 struct got_object_qid *qid;
10773 qid = STAILQ_FIRST(commits);
10774 err = got_object_id_str(&id_str, &qid->id);
10775 if (err)
10776 return err;
10778 n = fprintf(f,
10779 "# Editing the history of branch '%s' starting at\n"
10780 "# commit %s\n"
10781 "# Commits will be processed in order from top to "
10782 "bottom of this file.\n", branch_name, id_str);
10783 if (n < 0) {
10784 err = got_ferror(f, GOT_ERR_IO);
10785 goto done;
10788 n = fprintf(f, "# Available histedit commands:\n");
10789 if (n < 0) {
10790 err = got_ferror(f, GOT_ERR_IO);
10791 goto done;
10794 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10795 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10796 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10797 cmd->desc);
10798 if (n < 0) {
10799 err = got_ferror(f, GOT_ERR_IO);
10800 break;
10803 done:
10804 free(id_str);
10805 return err;
10808 static const struct got_error *
10809 histedit_syntax_error(int lineno)
10811 static char msg[42];
10812 int ret;
10814 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10815 lineno);
10816 if (ret < 0 || (size_t)ret >= sizeof(msg))
10817 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10819 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10822 static const struct got_error *
10823 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10824 char *logmsg, struct got_repository *repo)
10826 const struct got_error *err;
10827 struct got_commit_object *folded_commit = NULL;
10828 char *id_str, *folded_logmsg = NULL;
10830 err = got_object_id_str(&id_str, hle->commit_id);
10831 if (err)
10832 return err;
10834 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10835 if (err)
10836 goto done;
10838 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10839 if (err)
10840 goto done;
10841 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10842 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10843 folded_logmsg) == -1) {
10844 err = got_error_from_errno("asprintf");
10846 done:
10847 if (folded_commit)
10848 got_object_commit_close(folded_commit);
10849 free(id_str);
10850 free(folded_logmsg);
10851 return err;
10854 static struct got_histedit_list_entry *
10855 get_folded_commits(struct got_histedit_list_entry *hle)
10857 struct got_histedit_list_entry *prev, *folded = NULL;
10859 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10860 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10861 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10862 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10863 folded = prev;
10864 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10867 return folded;
10870 static const struct got_error *
10871 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10872 struct got_repository *repo)
10874 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10875 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10876 const struct got_error *err = NULL;
10877 struct got_commit_object *commit = NULL;
10878 int logmsg_len;
10879 int fd;
10880 struct got_histedit_list_entry *folded = NULL;
10882 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10883 if (err)
10884 return err;
10886 folded = get_folded_commits(hle);
10887 if (folded) {
10888 while (folded != hle) {
10889 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10890 folded = TAILQ_NEXT(folded, entry);
10891 continue;
10893 err = append_folded_commit_msg(&new_msg, folded,
10894 logmsg, repo);
10895 if (err)
10896 goto done;
10897 free(logmsg);
10898 logmsg = new_msg;
10899 folded = TAILQ_NEXT(folded, entry);
10903 err = got_object_id_str(&id_str, hle->commit_id);
10904 if (err)
10905 goto done;
10906 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10907 if (err)
10908 goto done;
10909 logmsg_len = asprintf(&new_msg,
10910 "%s\n# original log message of commit %s: %s",
10911 logmsg ? logmsg : "", id_str, orig_logmsg);
10912 if (logmsg_len == -1) {
10913 err = got_error_from_errno("asprintf");
10914 goto done;
10916 free(logmsg);
10917 logmsg = new_msg;
10919 err = got_object_id_str(&id_str, hle->commit_id);
10920 if (err)
10921 goto done;
10923 err = got_opentemp_named_fd(&logmsg_path, &fd,
10924 GOT_TMPDIR_STR "/got-logmsg", "");
10925 if (err)
10926 goto done;
10928 write(fd, logmsg, logmsg_len);
10929 close(fd);
10931 err = get_editor(&editor);
10932 if (err)
10933 goto done;
10935 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10936 logmsg_len, 0);
10937 if (err) {
10938 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10939 goto done;
10940 err = NULL;
10941 hle->logmsg = strdup(new_msg);
10942 if (hle->logmsg == NULL)
10943 err = got_error_from_errno("strdup");
10945 done:
10946 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10947 err = got_error_from_errno2("unlink", logmsg_path);
10948 free(logmsg_path);
10949 free(logmsg);
10950 free(orig_logmsg);
10951 free(editor);
10952 if (commit)
10953 got_object_commit_close(commit);
10954 return err;
10957 static const struct got_error *
10958 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10959 FILE *f, struct got_repository *repo)
10961 const struct got_error *err = NULL;
10962 char *line = NULL, *p, *end;
10963 size_t i, size;
10964 ssize_t len;
10965 int lineno = 0, lastcmd = -1;
10966 const struct got_histedit_cmd *cmd;
10967 struct got_object_id *commit_id = NULL;
10968 struct got_histedit_list_entry *hle = NULL;
10970 for (;;) {
10971 len = getline(&line, &size, f);
10972 if (len == -1) {
10973 const struct got_error *getline_err;
10974 if (feof(f))
10975 break;
10976 getline_err = got_error_from_errno("getline");
10977 err = got_ferror(f, getline_err->code);
10978 break;
10980 lineno++;
10981 p = line;
10982 while (isspace((unsigned char)p[0]))
10983 p++;
10984 if (p[0] == '#' || p[0] == '\0') {
10985 free(line);
10986 line = NULL;
10987 continue;
10989 cmd = NULL;
10990 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10991 cmd = &got_histedit_cmds[i];
10992 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10993 isspace((unsigned char)p[strlen(cmd->name)])) {
10994 p += strlen(cmd->name);
10995 break;
10997 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10998 p++;
10999 break;
11002 if (i == nitems(got_histedit_cmds)) {
11003 err = histedit_syntax_error(lineno);
11004 break;
11006 while (isspace((unsigned char)p[0]))
11007 p++;
11008 if (cmd->code == GOT_HISTEDIT_MESG) {
11009 if (lastcmd != GOT_HISTEDIT_PICK &&
11010 lastcmd != GOT_HISTEDIT_EDIT) {
11011 err = got_error(GOT_ERR_HISTEDIT_CMD);
11012 break;
11014 if (p[0] == '\0') {
11015 err = histedit_edit_logmsg(hle, repo);
11016 if (err)
11017 break;
11018 } else {
11019 hle->logmsg = strdup(p);
11020 if (hle->logmsg == NULL) {
11021 err = got_error_from_errno("strdup");
11022 break;
11025 free(line);
11026 line = NULL;
11027 lastcmd = cmd->code;
11028 continue;
11029 } else {
11030 end = p;
11031 while (end[0] && !isspace((unsigned char)end[0]))
11032 end++;
11033 *end = '\0';
11035 err = got_object_resolve_id_str(&commit_id, repo, p);
11036 if (err) {
11037 /* override error code */
11038 err = histedit_syntax_error(lineno);
11039 break;
11042 hle = malloc(sizeof(*hle));
11043 if (hle == NULL) {
11044 err = got_error_from_errno("malloc");
11045 break;
11047 hle->cmd = cmd;
11048 hle->commit_id = commit_id;
11049 hle->logmsg = NULL;
11050 commit_id = NULL;
11051 free(line);
11052 line = NULL;
11053 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11054 lastcmd = cmd->code;
11057 free(line);
11058 free(commit_id);
11059 return err;
11062 static const struct got_error *
11063 histedit_check_script(struct got_histedit_list *histedit_cmds,
11064 struct got_object_id_queue *commits, struct got_repository *repo)
11066 const struct got_error *err = NULL;
11067 struct got_object_qid *qid;
11068 struct got_histedit_list_entry *hle;
11069 static char msg[92];
11070 char *id_str;
11072 if (TAILQ_EMPTY(histedit_cmds))
11073 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11074 "histedit script contains no commands");
11075 if (STAILQ_EMPTY(commits))
11076 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11078 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11079 struct got_histedit_list_entry *hle2;
11080 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11081 if (hle == hle2)
11082 continue;
11083 if (got_object_id_cmp(hle->commit_id,
11084 hle2->commit_id) != 0)
11085 continue;
11086 err = got_object_id_str(&id_str, hle->commit_id);
11087 if (err)
11088 return err;
11089 snprintf(msg, sizeof(msg), "commit %s is listed "
11090 "more than once in histedit script", id_str);
11091 free(id_str);
11092 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11096 STAILQ_FOREACH(qid, commits, entry) {
11097 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11098 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11099 break;
11101 if (hle == NULL) {
11102 err = got_object_id_str(&id_str, &qid->id);
11103 if (err)
11104 return err;
11105 snprintf(msg, sizeof(msg),
11106 "commit %s missing from histedit script", id_str);
11107 free(id_str);
11108 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11112 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11113 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11114 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11115 "last commit in histedit script cannot be folded");
11117 return NULL;
11120 static const struct got_error *
11121 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11122 const char *path, struct got_object_id_queue *commits,
11123 struct got_repository *repo)
11125 const struct got_error *err = NULL;
11126 char *editor;
11127 FILE *f = NULL;
11129 err = get_editor(&editor);
11130 if (err)
11131 return err;
11133 if (spawn_editor(editor, path) == -1) {
11134 err = got_error_from_errno("failed spawning editor");
11135 goto done;
11138 f = fopen(path, "re");
11139 if (f == NULL) {
11140 err = got_error_from_errno("fopen");
11141 goto done;
11143 err = histedit_parse_list(histedit_cmds, f, repo);
11144 if (err)
11145 goto done;
11147 err = histedit_check_script(histedit_cmds, commits, repo);
11148 done:
11149 if (f && fclose(f) == EOF && err == NULL)
11150 err = got_error_from_errno("fclose");
11151 free(editor);
11152 return err;
11155 static const struct got_error *
11156 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11157 struct got_object_id_queue *, const char *, const char *,
11158 struct got_repository *);
11160 static const struct got_error *
11161 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11162 struct got_object_id_queue *commits, const char *branch_name,
11163 int edit_logmsg_only, int fold_only, int edit_only,
11164 struct got_repository *repo)
11166 const struct got_error *err;
11167 FILE *f = NULL;
11168 char *path = NULL;
11170 err = got_opentemp_named(&path, &f, "got-histedit", "");
11171 if (err)
11172 return err;
11174 err = write_cmd_list(f, branch_name, commits);
11175 if (err)
11176 goto done;
11178 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11179 fold_only, edit_only, repo);
11180 if (err)
11181 goto done;
11183 if (edit_logmsg_only || fold_only || edit_only) {
11184 rewind(f);
11185 err = histedit_parse_list(histedit_cmds, f, repo);
11186 } else {
11187 if (fclose(f) == EOF) {
11188 err = got_error_from_errno("fclose");
11189 goto done;
11191 f = NULL;
11192 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11193 if (err) {
11194 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11195 err->code != GOT_ERR_HISTEDIT_CMD)
11196 goto done;
11197 err = histedit_edit_list_retry(histedit_cmds, err,
11198 commits, path, branch_name, repo);
11201 done:
11202 if (f && fclose(f) == EOF && err == NULL)
11203 err = got_error_from_errno("fclose");
11204 if (path && unlink(path) != 0 && err == NULL)
11205 err = got_error_from_errno2("unlink", path);
11206 free(path);
11207 return err;
11210 static const struct got_error *
11211 histedit_save_list(struct got_histedit_list *histedit_cmds,
11212 struct got_worktree *worktree, struct got_repository *repo)
11214 const struct got_error *err = NULL;
11215 char *path = NULL;
11216 FILE *f = NULL;
11217 struct got_histedit_list_entry *hle;
11218 struct got_commit_object *commit = NULL;
11220 err = got_worktree_get_histedit_script_path(&path, worktree);
11221 if (err)
11222 return err;
11224 f = fopen(path, "we");
11225 if (f == NULL) {
11226 err = got_error_from_errno2("fopen", path);
11227 goto done;
11229 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11230 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11231 repo);
11232 if (err)
11233 break;
11235 if (hle->logmsg) {
11236 int n = fprintf(f, "%c %s\n",
11237 GOT_HISTEDIT_MESG, hle->logmsg);
11238 if (n < 0) {
11239 err = got_ferror(f, GOT_ERR_IO);
11240 break;
11244 done:
11245 if (f && fclose(f) == EOF && err == NULL)
11246 err = got_error_from_errno("fclose");
11247 free(path);
11248 if (commit)
11249 got_object_commit_close(commit);
11250 return err;
11253 static void
11254 histedit_free_list(struct got_histedit_list *histedit_cmds)
11256 struct got_histedit_list_entry *hle;
11258 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11259 TAILQ_REMOVE(histedit_cmds, hle, entry);
11260 free(hle);
11264 static const struct got_error *
11265 histedit_load_list(struct got_histedit_list *histedit_cmds,
11266 const char *path, struct got_repository *repo)
11268 const struct got_error *err = NULL;
11269 FILE *f = NULL;
11271 f = fopen(path, "re");
11272 if (f == NULL) {
11273 err = got_error_from_errno2("fopen", path);
11274 goto done;
11277 err = histedit_parse_list(histedit_cmds, f, repo);
11278 done:
11279 if (f && fclose(f) == EOF && err == NULL)
11280 err = got_error_from_errno("fclose");
11281 return err;
11284 static const struct got_error *
11285 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11286 const struct got_error *edit_err, struct got_object_id_queue *commits,
11287 const char *path, const char *branch_name, struct got_repository *repo)
11289 const struct got_error *err = NULL, *prev_err = edit_err;
11290 int resp = ' ';
11292 while (resp != 'c' && resp != 'r' && resp != 'a') {
11293 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11294 "or (a)bort: ", getprogname(), prev_err->msg);
11295 resp = getchar();
11296 if (resp == '\n')
11297 resp = getchar();
11298 if (resp == 'c') {
11299 histedit_free_list(histedit_cmds);
11300 err = histedit_run_editor(histedit_cmds, path, commits,
11301 repo);
11302 if (err) {
11303 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11304 err->code != GOT_ERR_HISTEDIT_CMD)
11305 break;
11306 prev_err = err;
11307 resp = ' ';
11308 continue;
11310 break;
11311 } else if (resp == 'r') {
11312 histedit_free_list(histedit_cmds);
11313 err = histedit_edit_script(histedit_cmds,
11314 commits, branch_name, 0, 0, 0, repo);
11315 if (err) {
11316 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11317 err->code != GOT_ERR_HISTEDIT_CMD)
11318 break;
11319 prev_err = err;
11320 resp = ' ';
11321 continue;
11323 break;
11324 } else if (resp == 'a') {
11325 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11326 break;
11327 } else
11328 printf("invalid response '%c'\n", resp);
11331 return err;
11334 static const struct got_error *
11335 histedit_complete(struct got_worktree *worktree,
11336 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11337 struct got_reference *branch, struct got_repository *repo)
11339 printf("Switching work tree to %s\n",
11340 got_ref_get_symref_target(branch));
11341 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11342 branch, repo);
11345 static const struct got_error *
11346 show_histedit_progress(struct got_commit_object *commit,
11347 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11349 const struct got_error *err;
11350 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11352 err = got_object_id_str(&old_id_str, hle->commit_id);
11353 if (err)
11354 goto done;
11356 if (new_id) {
11357 err = got_object_id_str(&new_id_str, new_id);
11358 if (err)
11359 goto done;
11362 old_id_str[12] = '\0';
11363 if (new_id_str)
11364 new_id_str[12] = '\0';
11366 if (hle->logmsg) {
11367 logmsg = strdup(hle->logmsg);
11368 if (logmsg == NULL) {
11369 err = got_error_from_errno("strdup");
11370 goto done;
11372 trim_logmsg(logmsg, 42);
11373 } else {
11374 err = get_short_logmsg(&logmsg, 42, commit);
11375 if (err)
11376 goto done;
11379 switch (hle->cmd->code) {
11380 case GOT_HISTEDIT_PICK:
11381 case GOT_HISTEDIT_EDIT:
11382 printf("%s -> %s: %s\n", old_id_str,
11383 new_id_str ? new_id_str : "no-op change", logmsg);
11384 break;
11385 case GOT_HISTEDIT_DROP:
11386 case GOT_HISTEDIT_FOLD:
11387 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11388 logmsg);
11389 break;
11390 default:
11391 break;
11393 done:
11394 free(old_id_str);
11395 free(new_id_str);
11396 return err;
11399 static const struct got_error *
11400 histedit_commit(struct got_pathlist_head *merged_paths,
11401 struct got_worktree *worktree, struct got_fileindex *fileindex,
11402 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11403 const char *committer, struct got_repository *repo)
11405 const struct got_error *err;
11406 struct got_commit_object *commit;
11407 struct got_object_id *new_commit_id;
11409 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11410 && hle->logmsg == NULL) {
11411 err = histedit_edit_logmsg(hle, repo);
11412 if (err)
11413 return err;
11416 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11417 if (err)
11418 return err;
11420 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11421 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11422 hle->logmsg, repo);
11423 if (err) {
11424 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11425 goto done;
11426 err = show_histedit_progress(commit, hle, NULL);
11427 } else {
11428 err = show_histedit_progress(commit, hle, new_commit_id);
11429 free(new_commit_id);
11431 done:
11432 got_object_commit_close(commit);
11433 return err;
11436 static const struct got_error *
11437 histedit_skip_commit(struct got_histedit_list_entry *hle,
11438 struct got_worktree *worktree, struct got_repository *repo)
11440 const struct got_error *error;
11441 struct got_commit_object *commit;
11443 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11444 repo);
11445 if (error)
11446 return error;
11448 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11449 if (error)
11450 return error;
11452 error = show_histedit_progress(commit, hle, NULL);
11453 got_object_commit_close(commit);
11454 return error;
11457 static const struct got_error *
11458 check_local_changes(void *arg, unsigned char status,
11459 unsigned char staged_status, const char *path,
11460 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11461 struct got_object_id *commit_id, int dirfd, const char *de_name)
11463 int *have_local_changes = arg;
11465 switch (status) {
11466 case GOT_STATUS_ADD:
11467 case GOT_STATUS_DELETE:
11468 case GOT_STATUS_MODIFY:
11469 case GOT_STATUS_CONFLICT:
11470 *have_local_changes = 1;
11471 return got_error(GOT_ERR_CANCELLED);
11472 default:
11473 break;
11476 switch (staged_status) {
11477 case GOT_STATUS_ADD:
11478 case GOT_STATUS_DELETE:
11479 case GOT_STATUS_MODIFY:
11480 *have_local_changes = 1;
11481 return got_error(GOT_ERR_CANCELLED);
11482 default:
11483 break;
11486 return NULL;
11489 static const struct got_error *
11490 cmd_histedit(int argc, char *argv[])
11492 const struct got_error *error = NULL;
11493 struct got_worktree *worktree = NULL;
11494 struct got_fileindex *fileindex = NULL;
11495 struct got_repository *repo = NULL;
11496 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11497 struct got_reference *branch = NULL;
11498 struct got_reference *tmp_branch = NULL;
11499 struct got_object_id *resume_commit_id = NULL;
11500 struct got_object_id *base_commit_id = NULL;
11501 struct got_object_id *head_commit_id = NULL;
11502 struct got_commit_object *commit = NULL;
11503 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11504 struct got_update_progress_arg upa;
11505 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11506 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11507 int list_backups = 0, delete_backups = 0;
11508 const char *edit_script_path = NULL;
11509 struct got_object_id_queue commits;
11510 struct got_pathlist_head merged_paths;
11511 const struct got_object_id_queue *parent_ids;
11512 struct got_object_qid *pid;
11513 struct got_histedit_list histedit_cmds;
11514 struct got_histedit_list_entry *hle;
11515 int *pack_fds = NULL;
11517 STAILQ_INIT(&commits);
11518 TAILQ_INIT(&histedit_cmds);
11519 TAILQ_INIT(&merged_paths);
11520 memset(&upa, 0, sizeof(upa));
11522 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11523 switch (ch) {
11524 case 'a':
11525 abort_edit = 1;
11526 break;
11527 case 'c':
11528 continue_edit = 1;
11529 break;
11530 case 'e':
11531 edit_only = 1;
11532 break;
11533 case 'F':
11534 edit_script_path = optarg;
11535 break;
11536 case 'f':
11537 fold_only = 1;
11538 break;
11539 case 'l':
11540 list_backups = 1;
11541 break;
11542 case 'm':
11543 edit_logmsg_only = 1;
11544 break;
11545 case 'X':
11546 delete_backups = 1;
11547 break;
11548 default:
11549 usage_histedit();
11550 /* NOTREACHED */
11554 argc -= optind;
11555 argv += optind;
11557 #ifndef PROFILE
11558 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11559 "unveil", NULL) == -1)
11560 err(1, "pledge");
11561 #endif
11562 if (abort_edit && continue_edit)
11563 option_conflict('a', 'c');
11564 if (edit_script_path && edit_logmsg_only)
11565 option_conflict('F', 'm');
11566 if (abort_edit && edit_logmsg_only)
11567 option_conflict('a', 'm');
11568 if (continue_edit && edit_logmsg_only)
11569 option_conflict('c', 'm');
11570 if (abort_edit && fold_only)
11571 option_conflict('a', 'f');
11572 if (continue_edit && fold_only)
11573 option_conflict('c', 'f');
11574 if (fold_only && edit_logmsg_only)
11575 option_conflict('f', 'm');
11576 if (edit_script_path && fold_only)
11577 option_conflict('F', 'f');
11578 if (abort_edit && edit_only)
11579 option_conflict('a', 'e');
11580 if (continue_edit && edit_only)
11581 option_conflict('c', 'e');
11582 if (edit_only && edit_logmsg_only)
11583 option_conflict('e', 'm');
11584 if (edit_script_path && edit_only)
11585 option_conflict('F', 'e');
11586 if (list_backups) {
11587 if (abort_edit)
11588 option_conflict('l', 'a');
11589 if (continue_edit)
11590 option_conflict('l', 'c');
11591 if (edit_script_path)
11592 option_conflict('l', 'F');
11593 if (edit_logmsg_only)
11594 option_conflict('l', 'm');
11595 if (fold_only)
11596 option_conflict('l', 'f');
11597 if (edit_only)
11598 option_conflict('l', 'e');
11599 if (delete_backups)
11600 option_conflict('l', 'X');
11601 if (argc != 0 && argc != 1)
11602 usage_histedit();
11603 } else if (delete_backups) {
11604 if (abort_edit)
11605 option_conflict('X', 'a');
11606 if (continue_edit)
11607 option_conflict('X', 'c');
11608 if (edit_script_path)
11609 option_conflict('X', 'F');
11610 if (edit_logmsg_only)
11611 option_conflict('X', 'm');
11612 if (fold_only)
11613 option_conflict('X', 'f');
11614 if (edit_only)
11615 option_conflict('X', 'e');
11616 if (list_backups)
11617 option_conflict('X', 'l');
11618 if (argc != 0 && argc != 1)
11619 usage_histedit();
11620 } else if (argc != 0)
11621 usage_histedit();
11624 * This command cannot apply unveil(2) in all cases because the
11625 * user may choose to run an editor to edit the histedit script
11626 * and to edit individual commit log messages.
11627 * unveil(2) traverses exec(2); if an editor is used we have to
11628 * apply unveil after edit script and log messages have been written.
11629 * XXX TODO: Make use of unveil(2) where possible.
11632 cwd = getcwd(NULL, 0);
11633 if (cwd == NULL) {
11634 error = got_error_from_errno("getcwd");
11635 goto done;
11638 error = got_repo_pack_fds_open(&pack_fds);
11639 if (error != NULL)
11640 goto done;
11642 error = got_worktree_open(&worktree, cwd);
11643 if (error) {
11644 if (list_backups || delete_backups) {
11645 if (error->code != GOT_ERR_NOT_WORKTREE)
11646 goto done;
11647 } else {
11648 if (error->code == GOT_ERR_NOT_WORKTREE)
11649 error = wrap_not_worktree_error(error,
11650 "histedit", cwd);
11651 goto done;
11655 if (list_backups || delete_backups) {
11656 error = got_repo_open(&repo,
11657 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11658 NULL, pack_fds);
11659 if (error != NULL)
11660 goto done;
11661 error = apply_unveil(got_repo_get_path(repo), 0,
11662 worktree ? got_worktree_get_root_path(worktree) : NULL);
11663 if (error)
11664 goto done;
11665 error = process_backup_refs(
11666 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11667 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11668 goto done; /* nothing else to do */
11671 error = get_gitconfig_path(&gitconfig_path);
11672 if (error)
11673 goto done;
11674 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11675 gitconfig_path, pack_fds);
11676 if (error != NULL)
11677 goto done;
11679 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11680 if (error)
11681 goto done;
11682 if (rebase_in_progress) {
11683 error = got_error(GOT_ERR_REBASING);
11684 goto done;
11687 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11688 repo);
11689 if (error)
11690 goto done;
11691 if (merge_in_progress) {
11692 error = got_error(GOT_ERR_MERGE_BUSY);
11693 goto done;
11696 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11697 if (error)
11698 goto done;
11700 if (edit_in_progress && edit_logmsg_only) {
11701 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11702 "histedit operation is in progress in this "
11703 "work tree and must be continued or aborted "
11704 "before the -m option can be used");
11705 goto done;
11707 if (edit_in_progress && fold_only) {
11708 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11709 "histedit operation is in progress in this "
11710 "work tree and must be continued or aborted "
11711 "before the -f option can be used");
11712 goto done;
11714 if (edit_in_progress && edit_only) {
11715 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11716 "histedit operation is in progress in this "
11717 "work tree and must be continued or aborted "
11718 "before the -e option can be used");
11719 goto done;
11722 if (edit_in_progress && abort_edit) {
11723 error = got_worktree_histedit_continue(&resume_commit_id,
11724 &tmp_branch, &branch, &base_commit_id, &fileindex,
11725 worktree, repo);
11726 if (error)
11727 goto done;
11728 printf("Switching work tree to %s\n",
11729 got_ref_get_symref_target(branch));
11730 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11731 branch, base_commit_id, abort_progress, &upa);
11732 if (error)
11733 goto done;
11734 printf("Histedit of %s aborted\n",
11735 got_ref_get_symref_target(branch));
11736 print_merge_progress_stats(&upa);
11737 goto done; /* nothing else to do */
11738 } else if (abort_edit) {
11739 error = got_error(GOT_ERR_NOT_HISTEDIT);
11740 goto done;
11743 error = get_author(&committer, repo, worktree);
11744 if (error)
11745 goto done;
11747 if (continue_edit) {
11748 char *path;
11750 if (!edit_in_progress) {
11751 error = got_error(GOT_ERR_NOT_HISTEDIT);
11752 goto done;
11755 error = got_worktree_get_histedit_script_path(&path, worktree);
11756 if (error)
11757 goto done;
11759 error = histedit_load_list(&histedit_cmds, path, repo);
11760 free(path);
11761 if (error)
11762 goto done;
11764 error = got_worktree_histedit_continue(&resume_commit_id,
11765 &tmp_branch, &branch, &base_commit_id, &fileindex,
11766 worktree, repo);
11767 if (error)
11768 goto done;
11770 error = got_ref_resolve(&head_commit_id, repo, branch);
11771 if (error)
11772 goto done;
11774 error = got_object_open_as_commit(&commit, repo,
11775 head_commit_id);
11776 if (error)
11777 goto done;
11778 parent_ids = got_object_commit_get_parent_ids(commit);
11779 pid = STAILQ_FIRST(parent_ids);
11780 if (pid == NULL) {
11781 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11782 goto done;
11784 error = collect_commits(&commits, head_commit_id, &pid->id,
11785 base_commit_id, got_worktree_get_path_prefix(worktree),
11786 GOT_ERR_HISTEDIT_PATH, repo);
11787 got_object_commit_close(commit);
11788 commit = NULL;
11789 if (error)
11790 goto done;
11791 } else {
11792 if (edit_in_progress) {
11793 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11794 goto done;
11797 error = got_ref_open(&branch, repo,
11798 got_worktree_get_head_ref_name(worktree), 0);
11799 if (error != NULL)
11800 goto done;
11802 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11803 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11804 "will not edit commit history of a branch outside "
11805 "the \"refs/heads/\" reference namespace");
11806 goto done;
11809 error = got_ref_resolve(&head_commit_id, repo, branch);
11810 got_ref_close(branch);
11811 branch = NULL;
11812 if (error)
11813 goto done;
11815 error = got_object_open_as_commit(&commit, repo,
11816 head_commit_id);
11817 if (error)
11818 goto done;
11819 parent_ids = got_object_commit_get_parent_ids(commit);
11820 pid = STAILQ_FIRST(parent_ids);
11821 if (pid == NULL) {
11822 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11823 goto done;
11825 error = collect_commits(&commits, head_commit_id, &pid->id,
11826 got_worktree_get_base_commit_id(worktree),
11827 got_worktree_get_path_prefix(worktree),
11828 GOT_ERR_HISTEDIT_PATH, repo);
11829 got_object_commit_close(commit);
11830 commit = NULL;
11831 if (error)
11832 goto done;
11834 if (STAILQ_EMPTY(&commits)) {
11835 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11836 goto done;
11839 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11840 &base_commit_id, &fileindex, worktree, repo);
11841 if (error)
11842 goto done;
11844 if (edit_script_path) {
11845 error = histedit_load_list(&histedit_cmds,
11846 edit_script_path, repo);
11847 if (error) {
11848 got_worktree_histedit_abort(worktree, fileindex,
11849 repo, branch, base_commit_id,
11850 abort_progress, &upa);
11851 print_merge_progress_stats(&upa);
11852 goto done;
11854 } else {
11855 const char *branch_name;
11856 branch_name = got_ref_get_symref_target(branch);
11857 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11858 branch_name += 11;
11859 error = histedit_edit_script(&histedit_cmds, &commits,
11860 branch_name, edit_logmsg_only, fold_only,
11861 edit_only, repo);
11862 if (error) {
11863 got_worktree_histedit_abort(worktree, fileindex,
11864 repo, branch, base_commit_id,
11865 abort_progress, &upa);
11866 print_merge_progress_stats(&upa);
11867 goto done;
11872 error = histedit_save_list(&histedit_cmds, worktree,
11873 repo);
11874 if (error) {
11875 got_worktree_histedit_abort(worktree, fileindex,
11876 repo, branch, base_commit_id,
11877 abort_progress, &upa);
11878 print_merge_progress_stats(&upa);
11879 goto done;
11884 error = histedit_check_script(&histedit_cmds, &commits, repo);
11885 if (error)
11886 goto done;
11888 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11889 if (resume_commit_id) {
11890 if (got_object_id_cmp(hle->commit_id,
11891 resume_commit_id) != 0)
11892 continue;
11894 resume_commit_id = NULL;
11895 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11896 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11897 error = histedit_skip_commit(hle, worktree,
11898 repo);
11899 if (error)
11900 goto done;
11901 } else {
11902 struct got_pathlist_head paths;
11903 int have_changes = 0;
11905 TAILQ_INIT(&paths);
11906 error = got_pathlist_append(&paths, "", NULL);
11907 if (error)
11908 goto done;
11909 error = got_worktree_status(worktree, &paths,
11910 repo, 0, check_local_changes, &have_changes,
11911 check_cancelled, NULL);
11912 got_pathlist_free(&paths,
11913 GOT_PATHLIST_FREE_NONE);
11914 if (error) {
11915 if (error->code != GOT_ERR_CANCELLED)
11916 goto done;
11917 if (sigint_received || sigpipe_received)
11918 goto done;
11920 if (have_changes) {
11921 error = histedit_commit(NULL, worktree,
11922 fileindex, tmp_branch, hle,
11923 committer, repo);
11924 if (error)
11925 goto done;
11926 } else {
11927 error = got_object_open_as_commit(
11928 &commit, repo, hle->commit_id);
11929 if (error)
11930 goto done;
11931 error = show_histedit_progress(commit,
11932 hle, NULL);
11933 got_object_commit_close(commit);
11934 commit = NULL;
11935 if (error)
11936 goto done;
11939 continue;
11942 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11943 error = histedit_skip_commit(hle, worktree, repo);
11944 if (error)
11945 goto done;
11946 continue;
11949 error = got_object_open_as_commit(&commit, repo,
11950 hle->commit_id);
11951 if (error)
11952 goto done;
11953 parent_ids = got_object_commit_get_parent_ids(commit);
11954 pid = STAILQ_FIRST(parent_ids);
11956 error = got_worktree_histedit_merge_files(&merged_paths,
11957 worktree, fileindex, &pid->id, hle->commit_id, repo,
11958 update_progress, &upa, check_cancelled, NULL);
11959 if (error)
11960 goto done;
11961 got_object_commit_close(commit);
11962 commit = NULL;
11964 print_merge_progress_stats(&upa);
11965 if (upa.conflicts > 0 || upa.missing > 0 ||
11966 upa.not_deleted > 0 || upa.unversioned > 0) {
11967 if (upa.conflicts > 0) {
11968 error = show_rebase_merge_conflict(
11969 hle->commit_id, repo);
11970 if (error)
11971 goto done;
11973 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11974 break;
11977 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11978 char *id_str;
11979 error = got_object_id_str(&id_str, hle->commit_id);
11980 if (error)
11981 goto done;
11982 printf("Stopping histedit for amending commit %s\n",
11983 id_str);
11984 free(id_str);
11985 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11986 error = got_worktree_histedit_postpone(worktree,
11987 fileindex);
11988 goto done;
11991 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11992 error = histedit_skip_commit(hle, worktree, repo);
11993 if (error)
11994 goto done;
11995 continue;
11998 error = histedit_commit(&merged_paths, worktree, fileindex,
11999 tmp_branch, hle, committer, repo);
12000 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12001 if (error)
12002 goto done;
12005 if (upa.conflicts > 0 || upa.missing > 0 ||
12006 upa.not_deleted > 0 || upa.unversioned > 0) {
12007 error = got_worktree_histedit_postpone(worktree, fileindex);
12008 if (error)
12009 goto done;
12010 if (upa.conflicts > 0 && upa.missing == 0 &&
12011 upa.not_deleted == 0 && upa.unversioned == 0) {
12012 error = got_error_msg(GOT_ERR_CONFLICTS,
12013 "conflicts must be resolved before histedit "
12014 "can continue");
12015 } else if (upa.conflicts > 0) {
12016 error = got_error_msg(GOT_ERR_CONFLICTS,
12017 "conflicts must be resolved before histedit "
12018 "can continue; changes destined for some "
12019 "files were not yet merged and should be "
12020 "merged manually if required before the "
12021 "histedit operation is continued");
12022 } else {
12023 error = got_error_msg(GOT_ERR_CONFLICTS,
12024 "changes destined for some files were not "
12025 "yet merged and should be merged manually "
12026 "if required before the histedit operation "
12027 "is continued");
12029 } else
12030 error = histedit_complete(worktree, fileindex, tmp_branch,
12031 branch, repo);
12032 done:
12033 free(cwd);
12034 free(committer);
12035 free(gitconfig_path);
12036 got_object_id_queue_free(&commits);
12037 histedit_free_list(&histedit_cmds);
12038 free(head_commit_id);
12039 free(base_commit_id);
12040 free(resume_commit_id);
12041 if (commit)
12042 got_object_commit_close(commit);
12043 if (branch)
12044 got_ref_close(branch);
12045 if (tmp_branch)
12046 got_ref_close(tmp_branch);
12047 if (worktree)
12048 got_worktree_close(worktree);
12049 if (repo) {
12050 const struct got_error *close_err = got_repo_close(repo);
12051 if (error == NULL)
12052 error = close_err;
12054 if (pack_fds) {
12055 const struct got_error *pack_err =
12056 got_repo_pack_fds_close(pack_fds);
12057 if (error == NULL)
12058 error = pack_err;
12060 return error;
12063 __dead static void
12064 usage_integrate(void)
12066 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12067 exit(1);
12070 static const struct got_error *
12071 cmd_integrate(int argc, char *argv[])
12073 const struct got_error *error = NULL;
12074 struct got_repository *repo = NULL;
12075 struct got_worktree *worktree = NULL;
12076 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12077 const char *branch_arg = NULL;
12078 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12079 struct got_fileindex *fileindex = NULL;
12080 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12081 int ch;
12082 struct got_update_progress_arg upa;
12083 int *pack_fds = NULL;
12085 while ((ch = getopt(argc, argv, "")) != -1) {
12086 switch (ch) {
12087 default:
12088 usage_integrate();
12089 /* NOTREACHED */
12093 argc -= optind;
12094 argv += optind;
12096 if (argc != 1)
12097 usage_integrate();
12098 branch_arg = argv[0];
12099 #ifndef PROFILE
12100 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12101 "unveil", NULL) == -1)
12102 err(1, "pledge");
12103 #endif
12104 cwd = getcwd(NULL, 0);
12105 if (cwd == NULL) {
12106 error = got_error_from_errno("getcwd");
12107 goto done;
12110 error = got_repo_pack_fds_open(&pack_fds);
12111 if (error != NULL)
12112 goto done;
12114 error = got_worktree_open(&worktree, cwd);
12115 if (error) {
12116 if (error->code == GOT_ERR_NOT_WORKTREE)
12117 error = wrap_not_worktree_error(error, "integrate",
12118 cwd);
12119 goto done;
12122 error = check_rebase_or_histedit_in_progress(worktree);
12123 if (error)
12124 goto done;
12126 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12127 NULL, pack_fds);
12128 if (error != NULL)
12129 goto done;
12131 error = apply_unveil(got_repo_get_path(repo), 0,
12132 got_worktree_get_root_path(worktree));
12133 if (error)
12134 goto done;
12136 error = check_merge_in_progress(worktree, repo);
12137 if (error)
12138 goto done;
12140 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12141 error = got_error_from_errno("asprintf");
12142 goto done;
12145 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12146 &base_branch_ref, worktree, refname, repo);
12147 if (error)
12148 goto done;
12150 refname = strdup(got_ref_get_name(branch_ref));
12151 if (refname == NULL) {
12152 error = got_error_from_errno("strdup");
12153 got_worktree_integrate_abort(worktree, fileindex, repo,
12154 branch_ref, base_branch_ref);
12155 goto done;
12157 base_refname = strdup(got_ref_get_name(base_branch_ref));
12158 if (base_refname == NULL) {
12159 error = got_error_from_errno("strdup");
12160 got_worktree_integrate_abort(worktree, fileindex, repo,
12161 branch_ref, base_branch_ref);
12162 goto done;
12164 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12165 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12166 got_worktree_integrate_abort(worktree, fileindex, repo,
12167 branch_ref, base_branch_ref);
12168 goto done;
12171 error = got_ref_resolve(&commit_id, repo, branch_ref);
12172 if (error)
12173 goto done;
12175 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12176 if (error)
12177 goto done;
12179 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12180 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12181 "specified branch has already been integrated");
12182 got_worktree_integrate_abort(worktree, fileindex, repo,
12183 branch_ref, base_branch_ref);
12184 goto done;
12187 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12188 if (error) {
12189 if (error->code == GOT_ERR_ANCESTRY)
12190 error = got_error(GOT_ERR_REBASE_REQUIRED);
12191 got_worktree_integrate_abort(worktree, fileindex, repo,
12192 branch_ref, base_branch_ref);
12193 goto done;
12196 memset(&upa, 0, sizeof(upa));
12197 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12198 branch_ref, base_branch_ref, update_progress, &upa,
12199 check_cancelled, NULL);
12200 if (error)
12201 goto done;
12203 printf("Integrated %s into %s\n", refname, base_refname);
12204 print_update_progress_stats(&upa);
12205 done:
12206 if (repo) {
12207 const struct got_error *close_err = got_repo_close(repo);
12208 if (error == NULL)
12209 error = close_err;
12211 if (worktree)
12212 got_worktree_close(worktree);
12213 if (pack_fds) {
12214 const struct got_error *pack_err =
12215 got_repo_pack_fds_close(pack_fds);
12216 if (error == NULL)
12217 error = pack_err;
12219 free(cwd);
12220 free(base_commit_id);
12221 free(commit_id);
12222 free(refname);
12223 free(base_refname);
12224 return error;
12227 __dead static void
12228 usage_merge(void)
12230 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12231 exit(1);
12234 static const struct got_error *
12235 cmd_merge(int argc, char *argv[])
12237 const struct got_error *error = NULL;
12238 struct got_worktree *worktree = NULL;
12239 struct got_repository *repo = NULL;
12240 struct got_fileindex *fileindex = NULL;
12241 char *cwd = NULL, *id_str = NULL, *author = NULL;
12242 struct got_reference *branch = NULL, *wt_branch = NULL;
12243 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12244 struct got_object_id *wt_branch_tip = NULL;
12245 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12246 int interrupt_merge = 0;
12247 struct got_update_progress_arg upa;
12248 struct got_object_id *merge_commit_id = NULL;
12249 char *branch_name = NULL;
12250 int *pack_fds = NULL;
12252 memset(&upa, 0, sizeof(upa));
12254 while ((ch = getopt(argc, argv, "acn")) != -1) {
12255 switch (ch) {
12256 case 'a':
12257 abort_merge = 1;
12258 break;
12259 case 'c':
12260 continue_merge = 1;
12261 break;
12262 case 'n':
12263 interrupt_merge = 1;
12264 break;
12265 default:
12266 usage_rebase();
12267 /* NOTREACHED */
12271 argc -= optind;
12272 argv += optind;
12274 #ifndef PROFILE
12275 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12276 "unveil", NULL) == -1)
12277 err(1, "pledge");
12278 #endif
12280 if (abort_merge && continue_merge)
12281 option_conflict('a', 'c');
12282 if (abort_merge || continue_merge) {
12283 if (argc != 0)
12284 usage_merge();
12285 } else if (argc != 1)
12286 usage_merge();
12288 cwd = getcwd(NULL, 0);
12289 if (cwd == NULL) {
12290 error = got_error_from_errno("getcwd");
12291 goto done;
12294 error = got_repo_pack_fds_open(&pack_fds);
12295 if (error != NULL)
12296 goto done;
12298 error = got_worktree_open(&worktree, cwd);
12299 if (error) {
12300 if (error->code == GOT_ERR_NOT_WORKTREE)
12301 error = wrap_not_worktree_error(error,
12302 "merge", cwd);
12303 goto done;
12306 error = got_repo_open(&repo,
12307 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12308 pack_fds);
12309 if (error != NULL)
12310 goto done;
12312 error = apply_unveil(got_repo_get_path(repo), 0,
12313 worktree ? got_worktree_get_root_path(worktree) : NULL);
12314 if (error)
12315 goto done;
12317 error = check_rebase_or_histedit_in_progress(worktree);
12318 if (error)
12319 goto done;
12321 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12322 repo);
12323 if (error)
12324 goto done;
12326 if (abort_merge) {
12327 if (!merge_in_progress) {
12328 error = got_error(GOT_ERR_NOT_MERGING);
12329 goto done;
12331 error = got_worktree_merge_continue(&branch_name,
12332 &branch_tip, &fileindex, worktree, repo);
12333 if (error)
12334 goto done;
12335 error = got_worktree_merge_abort(worktree, fileindex, repo,
12336 abort_progress, &upa);
12337 if (error)
12338 goto done;
12339 printf("Merge of %s aborted\n", branch_name);
12340 goto done; /* nothing else to do */
12343 error = get_author(&author, repo, worktree);
12344 if (error)
12345 goto done;
12347 if (continue_merge) {
12348 if (!merge_in_progress) {
12349 error = got_error(GOT_ERR_NOT_MERGING);
12350 goto done;
12352 error = got_worktree_merge_continue(&branch_name,
12353 &branch_tip, &fileindex, worktree, repo);
12354 if (error)
12355 goto done;
12356 } else {
12357 error = got_ref_open(&branch, repo, argv[0], 0);
12358 if (error != NULL)
12359 goto done;
12360 branch_name = strdup(got_ref_get_name(branch));
12361 if (branch_name == NULL) {
12362 error = got_error_from_errno("strdup");
12363 goto done;
12365 error = got_ref_resolve(&branch_tip, repo, branch);
12366 if (error)
12367 goto done;
12370 error = got_ref_open(&wt_branch, repo,
12371 got_worktree_get_head_ref_name(worktree), 0);
12372 if (error)
12373 goto done;
12374 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12375 if (error)
12376 goto done;
12377 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12378 wt_branch_tip, branch_tip, 0, repo,
12379 check_cancelled, NULL);
12380 if (error && error->code != GOT_ERR_ANCESTRY)
12381 goto done;
12383 if (!continue_merge) {
12384 error = check_path_prefix(wt_branch_tip, branch_tip,
12385 got_worktree_get_path_prefix(worktree),
12386 GOT_ERR_MERGE_PATH, repo);
12387 if (error)
12388 goto done;
12389 if (yca_id) {
12390 error = check_same_branch(wt_branch_tip, branch,
12391 yca_id, repo);
12392 if (error) {
12393 if (error->code != GOT_ERR_ANCESTRY)
12394 goto done;
12395 error = NULL;
12396 } else {
12397 static char msg[512];
12398 snprintf(msg, sizeof(msg),
12399 "cannot create a merge commit because "
12400 "%s is based on %s; %s can be integrated "
12401 "with 'got integrate' instead", branch_name,
12402 got_worktree_get_head_ref_name(worktree),
12403 branch_name);
12404 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12405 goto done;
12408 error = got_worktree_merge_prepare(&fileindex, worktree,
12409 branch, repo);
12410 if (error)
12411 goto done;
12413 error = got_worktree_merge_branch(worktree, fileindex,
12414 yca_id, branch_tip, repo, update_progress, &upa,
12415 check_cancelled, NULL);
12416 if (error)
12417 goto done;
12418 print_merge_progress_stats(&upa);
12419 if (!upa.did_something) {
12420 error = got_worktree_merge_abort(worktree, fileindex,
12421 repo, abort_progress, &upa);
12422 if (error)
12423 goto done;
12424 printf("Already up-to-date\n");
12425 goto done;
12429 if (interrupt_merge) {
12430 error = got_worktree_merge_postpone(worktree, fileindex);
12431 if (error)
12432 goto done;
12433 printf("Merge of %s interrupted on request\n", branch_name);
12434 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12435 upa.not_deleted > 0 || upa.unversioned > 0) {
12436 error = got_worktree_merge_postpone(worktree, fileindex);
12437 if (error)
12438 goto done;
12439 if (upa.conflicts > 0 && upa.missing == 0 &&
12440 upa.not_deleted == 0 && upa.unversioned == 0) {
12441 error = got_error_msg(GOT_ERR_CONFLICTS,
12442 "conflicts must be resolved before merging "
12443 "can continue");
12444 } else if (upa.conflicts > 0) {
12445 error = got_error_msg(GOT_ERR_CONFLICTS,
12446 "conflicts must be resolved before merging "
12447 "can continue; changes destined for some "
12448 "files were not yet merged and "
12449 "should be merged manually if required before the "
12450 "merge operation is continued");
12451 } else {
12452 error = got_error_msg(GOT_ERR_CONFLICTS,
12453 "changes destined for some "
12454 "files were not yet merged and should be "
12455 "merged manually if required before the "
12456 "merge operation is continued");
12458 goto done;
12459 } else {
12460 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12461 fileindex, author, NULL, 1, branch_tip, branch_name,
12462 repo, continue_merge ? print_status : NULL, NULL);
12463 if (error)
12464 goto done;
12465 error = got_worktree_merge_complete(worktree, fileindex, repo);
12466 if (error)
12467 goto done;
12468 error = got_object_id_str(&id_str, merge_commit_id);
12469 if (error)
12470 goto done;
12471 printf("Merged %s into %s: %s\n", branch_name,
12472 got_worktree_get_head_ref_name(worktree),
12473 id_str);
12476 done:
12477 free(id_str);
12478 free(merge_commit_id);
12479 free(author);
12480 free(branch_tip);
12481 free(branch_name);
12482 free(yca_id);
12483 if (branch)
12484 got_ref_close(branch);
12485 if (wt_branch)
12486 got_ref_close(wt_branch);
12487 if (worktree)
12488 got_worktree_close(worktree);
12489 if (repo) {
12490 const struct got_error *close_err = got_repo_close(repo);
12491 if (error == NULL)
12492 error = close_err;
12494 if (pack_fds) {
12495 const struct got_error *pack_err =
12496 got_repo_pack_fds_close(pack_fds);
12497 if (error == NULL)
12498 error = pack_err;
12500 return error;
12503 __dead static void
12504 usage_stage(void)
12506 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12507 "[path ...]\n", getprogname());
12508 exit(1);
12511 static const struct got_error *
12512 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12513 const char *path, struct got_object_id *blob_id,
12514 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12515 int dirfd, const char *de_name)
12517 const struct got_error *err = NULL;
12518 char *id_str = NULL;
12520 if (staged_status != GOT_STATUS_ADD &&
12521 staged_status != GOT_STATUS_MODIFY &&
12522 staged_status != GOT_STATUS_DELETE)
12523 return NULL;
12525 if (staged_status == GOT_STATUS_ADD ||
12526 staged_status == GOT_STATUS_MODIFY)
12527 err = got_object_id_str(&id_str, staged_blob_id);
12528 else
12529 err = got_object_id_str(&id_str, blob_id);
12530 if (err)
12531 return err;
12533 printf("%s %c %s\n", id_str, staged_status, path);
12534 free(id_str);
12535 return NULL;
12538 static const struct got_error *
12539 cmd_stage(int argc, char *argv[])
12541 const struct got_error *error = NULL;
12542 struct got_repository *repo = NULL;
12543 struct got_worktree *worktree = NULL;
12544 char *cwd = NULL;
12545 struct got_pathlist_head paths;
12546 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12547 FILE *patch_script_file = NULL;
12548 const char *patch_script_path = NULL;
12549 struct choose_patch_arg cpa;
12550 int *pack_fds = NULL;
12552 TAILQ_INIT(&paths);
12554 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12555 switch (ch) {
12556 case 'F':
12557 patch_script_path = optarg;
12558 break;
12559 case 'l':
12560 list_stage = 1;
12561 break;
12562 case 'p':
12563 pflag = 1;
12564 break;
12565 case 'S':
12566 allow_bad_symlinks = 1;
12567 break;
12568 default:
12569 usage_stage();
12570 /* NOTREACHED */
12574 argc -= optind;
12575 argv += optind;
12577 #ifndef PROFILE
12578 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12579 "unveil", NULL) == -1)
12580 err(1, "pledge");
12581 #endif
12582 if (list_stage && (pflag || patch_script_path))
12583 errx(1, "-l option cannot be used with other options");
12584 if (patch_script_path && !pflag)
12585 errx(1, "-F option can only be used together with -p option");
12587 cwd = getcwd(NULL, 0);
12588 if (cwd == NULL) {
12589 error = got_error_from_errno("getcwd");
12590 goto done;
12593 error = got_repo_pack_fds_open(&pack_fds);
12594 if (error != NULL)
12595 goto done;
12597 error = got_worktree_open(&worktree, cwd);
12598 if (error) {
12599 if (error->code == GOT_ERR_NOT_WORKTREE)
12600 error = wrap_not_worktree_error(error, "stage", cwd);
12601 goto done;
12604 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12605 NULL, pack_fds);
12606 if (error != NULL)
12607 goto done;
12609 if (patch_script_path) {
12610 patch_script_file = fopen(patch_script_path, "re");
12611 if (patch_script_file == NULL) {
12612 error = got_error_from_errno2("fopen",
12613 patch_script_path);
12614 goto done;
12617 error = apply_unveil(got_repo_get_path(repo), 0,
12618 got_worktree_get_root_path(worktree));
12619 if (error)
12620 goto done;
12622 error = check_merge_in_progress(worktree, repo);
12623 if (error)
12624 goto done;
12626 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12627 if (error)
12628 goto done;
12630 if (list_stage)
12631 error = got_worktree_status(worktree, &paths, repo, 0,
12632 print_stage, NULL, check_cancelled, NULL);
12633 else {
12634 cpa.patch_script_file = patch_script_file;
12635 cpa.action = "stage";
12636 error = got_worktree_stage(worktree, &paths,
12637 pflag ? NULL : print_status, NULL,
12638 pflag ? choose_patch : NULL, &cpa,
12639 allow_bad_symlinks, repo);
12641 done:
12642 if (patch_script_file && fclose(patch_script_file) == EOF &&
12643 error == NULL)
12644 error = got_error_from_errno2("fclose", patch_script_path);
12645 if (repo) {
12646 const struct got_error *close_err = got_repo_close(repo);
12647 if (error == NULL)
12648 error = close_err;
12650 if (worktree)
12651 got_worktree_close(worktree);
12652 if (pack_fds) {
12653 const struct got_error *pack_err =
12654 got_repo_pack_fds_close(pack_fds);
12655 if (error == NULL)
12656 error = pack_err;
12658 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12659 free(cwd);
12660 return error;
12663 __dead static void
12664 usage_unstage(void)
12666 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12667 "[path ...]\n", getprogname());
12668 exit(1);
12672 static const struct got_error *
12673 cmd_unstage(int argc, char *argv[])
12675 const struct got_error *error = NULL;
12676 struct got_repository *repo = NULL;
12677 struct got_worktree *worktree = NULL;
12678 char *cwd = NULL;
12679 struct got_pathlist_head paths;
12680 int ch, pflag = 0;
12681 struct got_update_progress_arg upa;
12682 FILE *patch_script_file = NULL;
12683 const char *patch_script_path = NULL;
12684 struct choose_patch_arg cpa;
12685 int *pack_fds = NULL;
12687 TAILQ_INIT(&paths);
12689 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12690 switch (ch) {
12691 case 'F':
12692 patch_script_path = optarg;
12693 break;
12694 case 'p':
12695 pflag = 1;
12696 break;
12697 default:
12698 usage_unstage();
12699 /* NOTREACHED */
12703 argc -= optind;
12704 argv += optind;
12706 #ifndef PROFILE
12707 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12708 "unveil", NULL) == -1)
12709 err(1, "pledge");
12710 #endif
12711 if (patch_script_path && !pflag)
12712 errx(1, "-F option can only be used together with -p option");
12714 cwd = getcwd(NULL, 0);
12715 if (cwd == NULL) {
12716 error = got_error_from_errno("getcwd");
12717 goto done;
12720 error = got_repo_pack_fds_open(&pack_fds);
12721 if (error != NULL)
12722 goto done;
12724 error = got_worktree_open(&worktree, cwd);
12725 if (error) {
12726 if (error->code == GOT_ERR_NOT_WORKTREE)
12727 error = wrap_not_worktree_error(error, "unstage", cwd);
12728 goto done;
12731 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12732 NULL, pack_fds);
12733 if (error != NULL)
12734 goto done;
12736 if (patch_script_path) {
12737 patch_script_file = fopen(patch_script_path, "re");
12738 if (patch_script_file == NULL) {
12739 error = got_error_from_errno2("fopen",
12740 patch_script_path);
12741 goto done;
12745 error = apply_unveil(got_repo_get_path(repo), 0,
12746 got_worktree_get_root_path(worktree));
12747 if (error)
12748 goto done;
12750 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12751 if (error)
12752 goto done;
12754 cpa.patch_script_file = patch_script_file;
12755 cpa.action = "unstage";
12756 memset(&upa, 0, sizeof(upa));
12757 error = got_worktree_unstage(worktree, &paths, update_progress,
12758 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12759 if (!error)
12760 print_merge_progress_stats(&upa);
12761 done:
12762 if (patch_script_file && fclose(patch_script_file) == EOF &&
12763 error == NULL)
12764 error = got_error_from_errno2("fclose", patch_script_path);
12765 if (repo) {
12766 const struct got_error *close_err = got_repo_close(repo);
12767 if (error == NULL)
12768 error = close_err;
12770 if (worktree)
12771 got_worktree_close(worktree);
12772 if (pack_fds) {
12773 const struct got_error *pack_err =
12774 got_repo_pack_fds_close(pack_fds);
12775 if (error == NULL)
12776 error = pack_err;
12778 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12779 free(cwd);
12780 return error;
12783 __dead static void
12784 usage_cat(void)
12786 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12787 "arg ...\n", getprogname());
12788 exit(1);
12791 static const struct got_error *
12792 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12794 const struct got_error *err;
12795 struct got_blob_object *blob;
12796 int fd = -1;
12798 fd = got_opentempfd();
12799 if (fd == -1)
12800 return got_error_from_errno("got_opentempfd");
12802 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12803 if (err)
12804 goto done;
12806 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12807 done:
12808 if (fd != -1 && close(fd) == -1 && err == NULL)
12809 err = got_error_from_errno("close");
12810 if (blob)
12811 got_object_blob_close(blob);
12812 return err;
12815 static const struct got_error *
12816 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12818 const struct got_error *err;
12819 struct got_tree_object *tree;
12820 int nentries, i;
12822 err = got_object_open_as_tree(&tree, repo, id);
12823 if (err)
12824 return err;
12826 nentries = got_object_tree_get_nentries(tree);
12827 for (i = 0; i < nentries; i++) {
12828 struct got_tree_entry *te;
12829 char *id_str;
12830 if (sigint_received || sigpipe_received)
12831 break;
12832 te = got_object_tree_get_entry(tree, i);
12833 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12834 if (err)
12835 break;
12836 fprintf(outfile, "%s %.7o %s\n", id_str,
12837 got_tree_entry_get_mode(te),
12838 got_tree_entry_get_name(te));
12839 free(id_str);
12842 got_object_tree_close(tree);
12843 return err;
12846 static const struct got_error *
12847 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12849 const struct got_error *err;
12850 struct got_commit_object *commit;
12851 const struct got_object_id_queue *parent_ids;
12852 struct got_object_qid *pid;
12853 char *id_str = NULL;
12854 const char *logmsg = NULL;
12855 char gmtoff[6];
12857 err = got_object_open_as_commit(&commit, repo, id);
12858 if (err)
12859 return err;
12861 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12862 if (err)
12863 goto done;
12865 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12866 parent_ids = got_object_commit_get_parent_ids(commit);
12867 fprintf(outfile, "numparents %d\n",
12868 got_object_commit_get_nparents(commit));
12869 STAILQ_FOREACH(pid, parent_ids, entry) {
12870 char *pid_str;
12871 err = got_object_id_str(&pid_str, &pid->id);
12872 if (err)
12873 goto done;
12874 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12875 free(pid_str);
12877 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12878 got_object_commit_get_author_gmtoff(commit));
12879 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12880 got_object_commit_get_author(commit),
12881 (long long)got_object_commit_get_author_time(commit),
12882 gmtoff);
12884 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12885 got_object_commit_get_committer_gmtoff(commit));
12886 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12887 got_object_commit_get_committer(commit),
12888 (long long)got_object_commit_get_committer_time(commit),
12889 gmtoff);
12891 logmsg = got_object_commit_get_logmsg_raw(commit);
12892 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12893 fprintf(outfile, "%s", logmsg);
12894 done:
12895 free(id_str);
12896 got_object_commit_close(commit);
12897 return err;
12900 static const struct got_error *
12901 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12903 const struct got_error *err;
12904 struct got_tag_object *tag;
12905 char *id_str = NULL;
12906 const char *tagmsg = NULL;
12907 char gmtoff[6];
12909 err = got_object_open_as_tag(&tag, repo, id);
12910 if (err)
12911 return err;
12913 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12914 if (err)
12915 goto done;
12917 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12919 switch (got_object_tag_get_object_type(tag)) {
12920 case GOT_OBJ_TYPE_BLOB:
12921 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12922 GOT_OBJ_LABEL_BLOB);
12923 break;
12924 case GOT_OBJ_TYPE_TREE:
12925 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12926 GOT_OBJ_LABEL_TREE);
12927 break;
12928 case GOT_OBJ_TYPE_COMMIT:
12929 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12930 GOT_OBJ_LABEL_COMMIT);
12931 break;
12932 case GOT_OBJ_TYPE_TAG:
12933 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12934 GOT_OBJ_LABEL_TAG);
12935 break;
12936 default:
12937 break;
12940 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12941 got_object_tag_get_name(tag));
12943 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12944 got_object_tag_get_tagger_gmtoff(tag));
12945 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12946 got_object_tag_get_tagger(tag),
12947 (long long)got_object_tag_get_tagger_time(tag),
12948 gmtoff);
12950 tagmsg = got_object_tag_get_message(tag);
12951 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12952 fprintf(outfile, "%s", tagmsg);
12953 done:
12954 free(id_str);
12955 got_object_tag_close(tag);
12956 return err;
12959 static const struct got_error *
12960 cmd_cat(int argc, char *argv[])
12962 const struct got_error *error;
12963 struct got_repository *repo = NULL;
12964 struct got_worktree *worktree = NULL;
12965 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12966 const char *commit_id_str = NULL;
12967 struct got_object_id *id = NULL, *commit_id = NULL;
12968 struct got_commit_object *commit = NULL;
12969 int ch, obj_type, i, force_path = 0;
12970 struct got_reflist_head refs;
12971 int *pack_fds = NULL;
12973 TAILQ_INIT(&refs);
12975 #ifndef PROFILE
12976 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12977 NULL) == -1)
12978 err(1, "pledge");
12979 #endif
12981 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12982 switch (ch) {
12983 case 'c':
12984 commit_id_str = optarg;
12985 break;
12986 case 'P':
12987 force_path = 1;
12988 break;
12989 case 'r':
12990 repo_path = realpath(optarg, NULL);
12991 if (repo_path == NULL)
12992 return got_error_from_errno2("realpath",
12993 optarg);
12994 got_path_strip_trailing_slashes(repo_path);
12995 break;
12996 default:
12997 usage_cat();
12998 /* NOTREACHED */
13002 argc -= optind;
13003 argv += optind;
13005 cwd = getcwd(NULL, 0);
13006 if (cwd == NULL) {
13007 error = got_error_from_errno("getcwd");
13008 goto done;
13011 error = got_repo_pack_fds_open(&pack_fds);
13012 if (error != NULL)
13013 goto done;
13015 if (repo_path == NULL) {
13016 error = got_worktree_open(&worktree, cwd);
13017 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13018 goto done;
13019 if (worktree) {
13020 repo_path = strdup(
13021 got_worktree_get_repo_path(worktree));
13022 if (repo_path == NULL) {
13023 error = got_error_from_errno("strdup");
13024 goto done;
13027 /* Release work tree lock. */
13028 got_worktree_close(worktree);
13029 worktree = NULL;
13033 if (repo_path == NULL) {
13034 repo_path = strdup(cwd);
13035 if (repo_path == NULL)
13036 return got_error_from_errno("strdup");
13039 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13040 free(repo_path);
13041 if (error != NULL)
13042 goto done;
13044 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13045 if (error)
13046 goto done;
13048 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13049 if (error)
13050 goto done;
13052 if (commit_id_str == NULL)
13053 commit_id_str = GOT_REF_HEAD;
13054 error = got_repo_match_object_id(&commit_id, NULL,
13055 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13056 if (error)
13057 goto done;
13059 error = got_object_open_as_commit(&commit, repo, commit_id);
13060 if (error)
13061 goto done;
13063 for (i = 0; i < argc; i++) {
13064 if (force_path) {
13065 error = got_object_id_by_path(&id, repo, commit,
13066 argv[i]);
13067 if (error)
13068 break;
13069 } else {
13070 error = got_repo_match_object_id(&id, &label, argv[i],
13071 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13072 repo);
13073 if (error) {
13074 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13075 error->code != GOT_ERR_NOT_REF)
13076 break;
13077 error = got_object_id_by_path(&id, repo,
13078 commit, argv[i]);
13079 if (error)
13080 break;
13084 error = got_object_get_type(&obj_type, repo, id);
13085 if (error)
13086 break;
13088 switch (obj_type) {
13089 case GOT_OBJ_TYPE_BLOB:
13090 error = cat_blob(id, repo, stdout);
13091 break;
13092 case GOT_OBJ_TYPE_TREE:
13093 error = cat_tree(id, repo, stdout);
13094 break;
13095 case GOT_OBJ_TYPE_COMMIT:
13096 error = cat_commit(id, repo, stdout);
13097 break;
13098 case GOT_OBJ_TYPE_TAG:
13099 error = cat_tag(id, repo, stdout);
13100 break;
13101 default:
13102 error = got_error(GOT_ERR_OBJ_TYPE);
13103 break;
13105 if (error)
13106 break;
13107 free(label);
13108 label = NULL;
13109 free(id);
13110 id = NULL;
13112 done:
13113 free(label);
13114 free(id);
13115 free(commit_id);
13116 if (commit)
13117 got_object_commit_close(commit);
13118 if (worktree)
13119 got_worktree_close(worktree);
13120 if (repo) {
13121 const struct got_error *close_err = got_repo_close(repo);
13122 if (error == NULL)
13123 error = close_err;
13125 if (pack_fds) {
13126 const struct got_error *pack_err =
13127 got_repo_pack_fds_close(pack_fds);
13128 if (error == NULL)
13129 error = pack_err;
13132 got_ref_list_free(&refs);
13133 return error;
13136 __dead static void
13137 usage_info(void)
13139 fprintf(stderr, "usage: %s info [path ...]\n",
13140 getprogname());
13141 exit(1);
13144 static const struct got_error *
13145 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13146 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13147 struct got_object_id *commit_id)
13149 const struct got_error *err = NULL;
13150 char *id_str = NULL;
13151 char datebuf[128];
13152 struct tm mytm, *tm;
13153 struct got_pathlist_head *paths = arg;
13154 struct got_pathlist_entry *pe;
13157 * Clear error indication from any of the path arguments which
13158 * would cause this file index entry to be displayed.
13160 TAILQ_FOREACH(pe, paths, entry) {
13161 if (got_path_cmp(path, pe->path, strlen(path),
13162 pe->path_len) == 0 ||
13163 got_path_is_child(path, pe->path, pe->path_len))
13164 pe->data = NULL; /* no error */
13167 printf(GOT_COMMIT_SEP_STR);
13168 if (S_ISLNK(mode))
13169 printf("symlink: %s\n", path);
13170 else if (S_ISREG(mode)) {
13171 printf("file: %s\n", path);
13172 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13173 } else if (S_ISDIR(mode))
13174 printf("directory: %s\n", path);
13175 else
13176 printf("something: %s\n", path);
13178 tm = localtime_r(&mtime, &mytm);
13179 if (tm == NULL)
13180 return NULL;
13181 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13182 return got_error(GOT_ERR_NO_SPACE);
13183 printf("timestamp: %s\n", datebuf);
13185 if (blob_id) {
13186 err = got_object_id_str(&id_str, blob_id);
13187 if (err)
13188 return err;
13189 printf("based on blob: %s\n", id_str);
13190 free(id_str);
13193 if (staged_blob_id) {
13194 err = got_object_id_str(&id_str, staged_blob_id);
13195 if (err)
13196 return err;
13197 printf("based on staged blob: %s\n", id_str);
13198 free(id_str);
13201 if (commit_id) {
13202 err = got_object_id_str(&id_str, commit_id);
13203 if (err)
13204 return err;
13205 printf("based on commit: %s\n", id_str);
13206 free(id_str);
13209 return NULL;
13212 static const struct got_error *
13213 cmd_info(int argc, char *argv[])
13215 const struct got_error *error = NULL;
13216 struct got_worktree *worktree = NULL;
13217 char *cwd = NULL, *id_str = NULL;
13218 struct got_pathlist_head paths;
13219 char *uuidstr = NULL;
13220 int ch, show_files = 0;
13222 TAILQ_INIT(&paths);
13224 while ((ch = getopt(argc, argv, "")) != -1) {
13225 switch (ch) {
13226 default:
13227 usage_info();
13228 /* NOTREACHED */
13232 argc -= optind;
13233 argv += optind;
13235 #ifndef PROFILE
13236 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13237 NULL) == -1)
13238 err(1, "pledge");
13239 #endif
13240 cwd = getcwd(NULL, 0);
13241 if (cwd == NULL) {
13242 error = got_error_from_errno("getcwd");
13243 goto done;
13246 error = got_worktree_open(&worktree, cwd);
13247 if (error) {
13248 if (error->code == GOT_ERR_NOT_WORKTREE)
13249 error = wrap_not_worktree_error(error, "info", cwd);
13250 goto done;
13253 #ifndef PROFILE
13254 /* Remove "wpath cpath proc exec sendfd" promises. */
13255 if (pledge("stdio rpath flock unveil", NULL) == -1)
13256 err(1, "pledge");
13257 #endif
13258 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13259 if (error)
13260 goto done;
13262 if (argc >= 1) {
13263 error = get_worktree_paths_from_argv(&paths, argc, argv,
13264 worktree);
13265 if (error)
13266 goto done;
13267 show_files = 1;
13270 error = got_object_id_str(&id_str,
13271 got_worktree_get_base_commit_id(worktree));
13272 if (error)
13273 goto done;
13275 error = got_worktree_get_uuid(&uuidstr, worktree);
13276 if (error)
13277 goto done;
13279 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13280 printf("work tree base commit: %s\n", id_str);
13281 printf("work tree path prefix: %s\n",
13282 got_worktree_get_path_prefix(worktree));
13283 printf("work tree branch reference: %s\n",
13284 got_worktree_get_head_ref_name(worktree));
13285 printf("work tree UUID: %s\n", uuidstr);
13286 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13288 if (show_files) {
13289 struct got_pathlist_entry *pe;
13290 TAILQ_FOREACH(pe, &paths, entry) {
13291 if (pe->path_len == 0)
13292 continue;
13294 * Assume this path will fail. This will be corrected
13295 * in print_path_info() in case the path does suceeed.
13297 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13299 error = got_worktree_path_info(worktree, &paths,
13300 print_path_info, &paths, check_cancelled, NULL);
13301 if (error)
13302 goto done;
13303 TAILQ_FOREACH(pe, &paths, entry) {
13304 if (pe->data != NULL) {
13305 const struct got_error *perr;
13307 perr = pe->data;
13308 error = got_error_fmt(perr->code, "%s",
13309 pe->path);
13310 break;
13314 done:
13315 if (worktree)
13316 got_worktree_close(worktree);
13317 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13318 free(cwd);
13319 free(id_str);
13320 free(uuidstr);
13321 return error;