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, struct got_diffstat_cb_arg *dsa,
3614 struct got_repository *repo, 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, dsa, 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_diffstat_cb_arg *dsa,
3676 struct got_repository *repo, FILE *outfile)
3678 const struct got_error *err = NULL;
3679 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3680 struct got_diff_blob_output_unidiff_arg arg;
3681 FILE *f1 = NULL, *f2 = NULL;
3682 int fd1 = -1, fd2 = -1;
3684 if (tree_id1) {
3685 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3686 if (err)
3687 goto done;
3688 fd1 = got_opentempfd();
3689 if (fd1 == -1) {
3690 err = got_error_from_errno("got_opentempfd");
3691 goto done;
3695 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3696 if (err)
3697 goto done;
3699 f1 = got_opentemp();
3700 if (f1 == NULL) {
3701 err = got_error_from_errno("got_opentemp");
3702 goto done;
3705 f2 = got_opentemp();
3706 if (f2 == NULL) {
3707 err = got_error_from_errno("got_opentemp");
3708 goto done;
3710 fd2 = got_opentempfd();
3711 if (fd2 == -1) {
3712 err = got_error_from_errno("got_opentempfd");
3713 goto done;
3715 arg.diff_context = diff_context;
3716 arg.ignore_whitespace = ignore_whitespace;
3717 arg.force_text_diff = force_text_diff;
3718 arg.diffstat = dsa;
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_diffstat_cb_arg *dsa,
3832 struct got_repository *repo, 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, dsa, repo, outfile);
3884 break;
3885 case GOT_OBJ_TYPE_TREE:
3886 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3887 0, 0, dsa, 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 dsa, 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, NULL, 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, const char *header)
4158 struct got_pathlist_entry *pe;
4160 if (header != NULL)
4161 printf("%s\n", header);
4163 TAILQ_FOREACH(pe, dsa->paths, entry) {
4164 struct got_diff_changed_path *cp = pe->data;
4165 int pad = dsa->max_path_len - pe->path_len + 1;
4167 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4168 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4170 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4171 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4172 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4174 if (fflush(stdout) != 0)
4175 return got_error_from_errno("fflush");
4177 return NULL;
4180 static const struct got_error *
4181 printfile(FILE *f)
4183 char buf[8192];
4184 size_t r;
4186 if (fseeko(f, 0L, SEEK_SET) == -1)
4187 return got_error_from_errno("fseek");
4189 for (;;) {
4190 r = fread(buf, 1, sizeof(buf), f);
4191 if (r == 0) {
4192 if (ferror(f))
4193 return got_error_from_errno("fread");
4194 if (feof(f))
4195 break;
4197 if (fwrite(buf, 1, r, stdout) != r)
4198 return got_ferror(stdout, GOT_ERR_IO);
4201 return NULL;
4204 static const struct got_error *
4205 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4206 struct got_repository *repo, const char *path,
4207 struct got_pathlist_head *changed_paths,
4208 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4209 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4211 const struct got_error *err = NULL;
4212 FILE *f = NULL;
4213 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4214 char datebuf[26];
4215 time_t committer_time;
4216 const char *author, *committer;
4217 char *refs_str = NULL;
4219 err = got_object_id_str(&id_str, id);
4220 if (err)
4221 return err;
4223 if (custom_refs_str == NULL) {
4224 struct got_reflist_head *refs;
4225 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4226 if (refs) {
4227 err = build_refs_str(&refs_str, refs, id, repo, 0);
4228 if (err)
4229 goto done;
4233 printf(GOT_COMMIT_SEP_STR);
4234 if (custom_refs_str)
4235 printf("commit %s (%s)\n", id_str, custom_refs_str);
4236 else
4237 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4238 refs_str ? refs_str : "", refs_str ? ")" : "");
4239 free(id_str);
4240 id_str = NULL;
4241 free(refs_str);
4242 refs_str = NULL;
4243 printf("from: %s\n", got_object_commit_get_author(commit));
4244 author = got_object_commit_get_author(commit);
4245 committer = got_object_commit_get_committer(commit);
4246 if (strcmp(author, committer) != 0)
4247 printf("via: %s\n", committer);
4248 committer_time = got_object_commit_get_committer_time(commit);
4249 datestr = get_datestr(&committer_time, datebuf);
4250 if (datestr)
4251 printf("date: %s UTC\n", datestr);
4252 if (got_object_commit_get_nparents(commit) > 1) {
4253 const struct got_object_id_queue *parent_ids;
4254 struct got_object_qid *qid;
4255 int n = 1;
4256 parent_ids = got_object_commit_get_parent_ids(commit);
4257 STAILQ_FOREACH(qid, parent_ids, entry) {
4258 err = got_object_id_str(&id_str, &qid->id);
4259 if (err)
4260 goto done;
4261 printf("parent %d: %s\n", n++, id_str);
4262 free(id_str);
4263 id_str = NULL;
4267 err = got_object_commit_get_logmsg(&logmsg0, commit);
4268 if (err)
4269 goto done;
4271 logmsg = logmsg0;
4272 do {
4273 line = strsep(&logmsg, "\n");
4274 if (line)
4275 printf(" %s\n", line);
4276 } while (line);
4277 free(logmsg0);
4279 if (changed_paths && diffstat == NULL) {
4280 struct got_pathlist_entry *pe;
4282 TAILQ_FOREACH(pe, changed_paths, entry) {
4283 struct got_diff_changed_path *cp = pe->data;
4285 printf(" %c %s\n", cp->status, pe->path);
4287 printf("\n");
4289 if (show_patch) {
4290 if (diffstat) {
4291 f = got_opentemp();
4292 if (f == NULL) {
4293 err = got_error_from_errno("got_opentemp");
4294 goto done;
4298 err = print_patch(commit, id, path, diff_context, diffstat,
4299 repo, diffstat == NULL ? stdout : f);
4300 if (err)
4301 goto done;
4303 if (diffstat) {
4304 err = print_diffstat(diffstat, NULL);
4305 if (err)
4306 goto done;
4307 if (show_patch) {
4308 err = printfile(f);
4309 if (err)
4310 goto done;
4313 if (show_patch)
4314 printf("\n");
4316 if (fflush(stdout) != 0 && err == NULL)
4317 err = got_error_from_errno("fflush");
4318 done:
4319 if (f && fclose(f) == EOF && err == NULL)
4320 err = got_error_from_errno("fclose");
4321 free(id_str);
4322 free(refs_str);
4323 return err;
4326 static const struct got_error *
4327 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4328 struct got_repository *repo, const char *path, int show_changed_paths,
4329 int show_diffstat, int show_patch, const char *search_pattern,
4330 int diff_context, int limit, int log_branches, int reverse_display_order,
4331 struct got_reflist_object_id_map *refs_idmap, int one_line,
4332 FILE *tmpfile)
4334 const struct got_error *err;
4335 struct got_commit_graph *graph;
4336 regex_t regex;
4337 int have_match;
4338 struct got_object_id_queue reversed_commits;
4339 struct got_object_qid *qid;
4340 struct got_commit_object *commit;
4341 struct got_pathlist_head changed_paths;
4343 STAILQ_INIT(&reversed_commits);
4344 TAILQ_INIT(&changed_paths);
4346 if (search_pattern && regcomp(&regex, search_pattern,
4347 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4348 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4350 err = got_commit_graph_open(&graph, path, !log_branches);
4351 if (err)
4352 return err;
4353 err = got_commit_graph_iter_start(graph, root_id, repo,
4354 check_cancelled, NULL);
4355 if (err)
4356 goto done;
4357 for (;;) {
4358 struct got_object_id id;
4359 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4360 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4362 if (sigint_received || sigpipe_received)
4363 break;
4365 err = got_commit_graph_iter_next(&id, graph, repo,
4366 check_cancelled, NULL);
4367 if (err) {
4368 if (err->code == GOT_ERR_ITER_COMPLETED)
4369 err = NULL;
4370 break;
4373 err = got_object_open_as_commit(&commit, repo, &id);
4374 if (err)
4375 break;
4377 if ((show_changed_paths || (show_diffstat && !show_patch))
4378 && !reverse_display_order) {
4379 err = get_changed_paths(&changed_paths, commit, repo,
4380 show_diffstat ? &dsa : NULL);
4381 if (err)
4382 break;
4385 if (search_pattern) {
4386 err = match_commit(&have_match, &id, commit, &regex);
4387 if (err) {
4388 got_object_commit_close(commit);
4389 break;
4391 if (have_match == 0 && show_changed_paths)
4392 match_changed_paths(&have_match,
4393 &changed_paths, &regex);
4394 if (have_match == 0 && show_patch) {
4395 err = match_patch(&have_match, commit, &id,
4396 path, diff_context, repo, &regex, tmpfile);
4397 if (err)
4398 break;
4400 if (have_match == 0) {
4401 got_object_commit_close(commit);
4402 got_pathlist_free(&changed_paths,
4403 GOT_PATHLIST_FREE_ALL);
4404 continue;
4408 if (reverse_display_order) {
4409 err = got_object_qid_alloc(&qid, &id);
4410 if (err)
4411 break;
4412 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4413 got_object_commit_close(commit);
4414 } else {
4415 if (one_line)
4416 err = print_commit_oneline(commit, &id,
4417 repo, refs_idmap);
4418 else
4419 err = print_commit(commit, &id, repo, path,
4420 (show_changed_paths || show_diffstat) ?
4421 &changed_paths : NULL,
4422 show_diffstat ? &dsa : NULL, show_patch,
4423 diff_context, refs_idmap, NULL);
4424 got_object_commit_close(commit);
4425 if (err)
4426 break;
4428 if ((limit && --limit == 0) ||
4429 (end_id && got_object_id_cmp(&id, end_id) == 0))
4430 break;
4432 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4434 if (reverse_display_order) {
4435 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4436 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4437 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4439 err = got_object_open_as_commit(&commit, repo,
4440 &qid->id);
4441 if (err)
4442 break;
4443 if (show_changed_paths ||
4444 (show_diffstat && !show_patch)) {
4445 err = get_changed_paths(&changed_paths, commit,
4446 repo, show_diffstat ? &dsa : NULL);
4447 if (err)
4448 break;
4450 if (one_line)
4451 err = print_commit_oneline(commit, &qid->id,
4452 repo, refs_idmap);
4453 else
4454 err = print_commit(commit, &qid->id, repo, path,
4455 (show_changed_paths || show_diffstat) ?
4456 &changed_paths : NULL,
4457 show_diffstat ? &dsa : NULL, show_patch,
4458 diff_context, refs_idmap, NULL);
4459 got_object_commit_close(commit);
4460 if (err)
4461 break;
4462 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4465 done:
4466 while (!STAILQ_EMPTY(&reversed_commits)) {
4467 qid = STAILQ_FIRST(&reversed_commits);
4468 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4469 got_object_qid_free(qid);
4471 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4472 if (search_pattern)
4473 regfree(&regex);
4474 got_commit_graph_close(graph);
4475 return err;
4478 __dead static void
4479 usage_log(void)
4481 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4482 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4483 "[path]\n", getprogname());
4484 exit(1);
4487 static int
4488 get_default_log_limit(void)
4490 const char *got_default_log_limit;
4491 long long n;
4492 const char *errstr;
4494 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4495 if (got_default_log_limit == NULL)
4496 return 0;
4497 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4498 if (errstr != NULL)
4499 return 0;
4500 return n;
4503 static const struct got_error *
4504 cmd_log(int argc, char *argv[])
4506 const struct got_error *error;
4507 struct got_repository *repo = NULL;
4508 struct got_worktree *worktree = NULL;
4509 struct got_object_id *start_id = NULL, *end_id = NULL;
4510 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4511 const char *start_commit = NULL, *end_commit = NULL;
4512 const char *search_pattern = NULL;
4513 int diff_context = -1, ch;
4514 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4515 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4516 const char *errstr;
4517 struct got_reflist_head refs;
4518 struct got_reflist_object_id_map *refs_idmap = NULL;
4519 FILE *tmpfile = NULL;
4520 int *pack_fds = NULL;
4522 TAILQ_INIT(&refs);
4524 #ifndef PROFILE
4525 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4526 NULL)
4527 == -1)
4528 err(1, "pledge");
4529 #endif
4531 limit = get_default_log_limit();
4533 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4534 switch (ch) {
4535 case 'b':
4536 log_branches = 1;
4537 break;
4538 case 'C':
4539 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4540 &errstr);
4541 if (errstr != NULL)
4542 errx(1, "number of context lines is %s: %s",
4543 errstr, optarg);
4544 break;
4545 case 'c':
4546 start_commit = optarg;
4547 break;
4548 case 'd':
4549 show_diffstat = 1;
4550 break;
4551 case 'l':
4552 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4553 if (errstr != NULL)
4554 errx(1, "number of commits is %s: %s",
4555 errstr, optarg);
4556 break;
4557 case 'P':
4558 show_changed_paths = 1;
4559 break;
4560 case 'p':
4561 show_patch = 1;
4562 break;
4563 case 'R':
4564 reverse_display_order = 1;
4565 break;
4566 case 'r':
4567 repo_path = realpath(optarg, NULL);
4568 if (repo_path == NULL)
4569 return got_error_from_errno2("realpath",
4570 optarg);
4571 got_path_strip_trailing_slashes(repo_path);
4572 break;
4573 case 'S':
4574 search_pattern = optarg;
4575 break;
4576 case 's':
4577 one_line = 1;
4578 break;
4579 case 'x':
4580 end_commit = optarg;
4581 break;
4582 default:
4583 usage_log();
4584 /* NOTREACHED */
4588 argc -= optind;
4589 argv += optind;
4591 if (diff_context == -1)
4592 diff_context = 3;
4593 else if (!show_patch)
4594 errx(1, "-C requires -p");
4596 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4597 errx(1, "cannot use -s with -d, -p or -P");
4599 cwd = getcwd(NULL, 0);
4600 if (cwd == NULL) {
4601 error = got_error_from_errno("getcwd");
4602 goto done;
4605 error = got_repo_pack_fds_open(&pack_fds);
4606 if (error != NULL)
4607 goto done;
4609 if (repo_path == NULL) {
4610 error = got_worktree_open(&worktree, cwd);
4611 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4612 goto done;
4613 error = NULL;
4616 if (argc == 1) {
4617 if (worktree) {
4618 error = got_worktree_resolve_path(&path, worktree,
4619 argv[0]);
4620 if (error)
4621 goto done;
4622 } else {
4623 path = strdup(argv[0]);
4624 if (path == NULL) {
4625 error = got_error_from_errno("strdup");
4626 goto done;
4629 } else if (argc != 0)
4630 usage_log();
4632 if (repo_path == NULL) {
4633 repo_path = worktree ?
4634 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4636 if (repo_path == NULL) {
4637 error = got_error_from_errno("strdup");
4638 goto done;
4641 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4642 if (error != NULL)
4643 goto done;
4645 error = apply_unveil(got_repo_get_path(repo), 1,
4646 worktree ? got_worktree_get_root_path(worktree) : NULL);
4647 if (error)
4648 goto done;
4650 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4651 if (error)
4652 goto done;
4654 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4655 if (error)
4656 goto done;
4658 if (start_commit == NULL) {
4659 struct got_reference *head_ref;
4660 struct got_commit_object *commit = NULL;
4661 error = got_ref_open(&head_ref, repo,
4662 worktree ? got_worktree_get_head_ref_name(worktree)
4663 : GOT_REF_HEAD, 0);
4664 if (error != NULL)
4665 goto done;
4666 error = got_ref_resolve(&start_id, repo, head_ref);
4667 got_ref_close(head_ref);
4668 if (error != NULL)
4669 goto done;
4670 error = got_object_open_as_commit(&commit, repo,
4671 start_id);
4672 if (error != NULL)
4673 goto done;
4674 got_object_commit_close(commit);
4675 } else {
4676 error = got_repo_match_object_id(&start_id, NULL,
4677 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4678 if (error != NULL)
4679 goto done;
4681 if (end_commit != NULL) {
4682 error = got_repo_match_object_id(&end_id, NULL,
4683 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4684 if (error != NULL)
4685 goto done;
4688 if (worktree) {
4690 * If a path was specified on the command line it was resolved
4691 * to a path in the work tree above. Prepend the work tree's
4692 * path prefix to obtain the corresponding in-repository path.
4694 if (path) {
4695 const char *prefix;
4696 prefix = got_worktree_get_path_prefix(worktree);
4697 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4698 (path[0] != '\0') ? "/" : "", path) == -1) {
4699 error = got_error_from_errno("asprintf");
4700 goto done;
4703 } else
4704 error = got_repo_map_path(&in_repo_path, repo,
4705 path ? path : "");
4706 if (error != NULL)
4707 goto done;
4708 if (in_repo_path) {
4709 free(path);
4710 path = in_repo_path;
4713 if (worktree) {
4714 /* Release work tree lock. */
4715 got_worktree_close(worktree);
4716 worktree = NULL;
4719 if (search_pattern && show_patch) {
4720 tmpfile = got_opentemp();
4721 if (tmpfile == NULL) {
4722 error = got_error_from_errno("got_opentemp");
4723 goto done;
4727 error = print_commits(start_id, end_id, repo, path ? path : "",
4728 show_changed_paths, show_diffstat, show_patch, search_pattern,
4729 diff_context, limit, log_branches, reverse_display_order,
4730 refs_idmap, one_line, tmpfile);
4731 done:
4732 free(path);
4733 free(repo_path);
4734 free(cwd);
4735 if (worktree)
4736 got_worktree_close(worktree);
4737 if (repo) {
4738 const struct got_error *close_err = got_repo_close(repo);
4739 if (error == NULL)
4740 error = close_err;
4742 if (pack_fds) {
4743 const struct got_error *pack_err =
4744 got_repo_pack_fds_close(pack_fds);
4745 if (error == NULL)
4746 error = pack_err;
4748 if (refs_idmap)
4749 got_reflist_object_id_map_free(refs_idmap);
4750 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4751 error = got_error_from_errno("fclose");
4752 got_ref_list_free(&refs);
4753 return error;
4756 __dead static void
4757 usage_diff(void)
4759 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4760 "[-r repository-path] [object1 object2 | path ...]\n",
4761 getprogname());
4762 exit(1);
4765 struct print_diff_arg {
4766 struct got_repository *repo;
4767 struct got_worktree *worktree;
4768 struct got_diffstat_cb_arg *diffstat;
4769 int diff_context;
4770 const char *id_str;
4771 int header_shown;
4772 int diff_staged;
4773 enum got_diff_algorithm diff_algo;
4774 int ignore_whitespace;
4775 int force_text_diff;
4776 FILE *f1;
4777 FILE *f2;
4778 FILE *outfile;
4782 * Create a file which contains the target path of a symlink so we can feed
4783 * it as content to the diff engine.
4785 static const struct got_error *
4786 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4787 const char *abspath)
4789 const struct got_error *err = NULL;
4790 char target_path[PATH_MAX];
4791 ssize_t target_len, outlen;
4793 *fd = -1;
4795 if (dirfd != -1) {
4796 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4797 if (target_len == -1)
4798 return got_error_from_errno2("readlinkat", abspath);
4799 } else {
4800 target_len = readlink(abspath, target_path, PATH_MAX);
4801 if (target_len == -1)
4802 return got_error_from_errno2("readlink", abspath);
4805 *fd = got_opentempfd();
4806 if (*fd == -1)
4807 return got_error_from_errno("got_opentempfd");
4809 outlen = write(*fd, target_path, target_len);
4810 if (outlen == -1) {
4811 err = got_error_from_errno("got_opentempfd");
4812 goto done;
4815 if (lseek(*fd, 0, SEEK_SET) == -1) {
4816 err = got_error_from_errno2("lseek", abspath);
4817 goto done;
4819 done:
4820 if (err) {
4821 close(*fd);
4822 *fd = -1;
4824 return err;
4827 static const struct got_error *
4828 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4829 const char *path, struct got_object_id *blob_id,
4830 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4831 int dirfd, const char *de_name)
4833 struct print_diff_arg *a = arg;
4834 const struct got_error *err = NULL;
4835 struct got_blob_object *blob1 = NULL;
4836 int fd = -1, fd1 = -1, fd2 = -1;
4837 FILE *f2 = NULL;
4838 char *abspath = NULL, *label1 = NULL;
4839 struct stat sb;
4840 off_t size1 = 0;
4841 int f2_exists = 0;
4843 memset(&sb, 0, sizeof(sb));
4845 if (a->diff_staged) {
4846 if (staged_status != GOT_STATUS_MODIFY &&
4847 staged_status != GOT_STATUS_ADD &&
4848 staged_status != GOT_STATUS_DELETE)
4849 return NULL;
4850 } else {
4851 if (staged_status == GOT_STATUS_DELETE)
4852 return NULL;
4853 if (status == GOT_STATUS_NONEXISTENT)
4854 return got_error_set_errno(ENOENT, path);
4855 if (status != GOT_STATUS_MODIFY &&
4856 status != GOT_STATUS_ADD &&
4857 status != GOT_STATUS_DELETE &&
4858 status != GOT_STATUS_CONFLICT)
4859 return NULL;
4862 err = got_opentemp_truncate(a->f1);
4863 if (err)
4864 return got_error_from_errno("got_opentemp_truncate");
4865 err = got_opentemp_truncate(a->f2);
4866 if (err)
4867 return got_error_from_errno("got_opentemp_truncate");
4869 if (!a->header_shown) {
4870 if (fprintf(a->outfile, "diff %s%s\n",
4871 a->diff_staged ? "-s " : "",
4872 got_worktree_get_root_path(a->worktree)) < 0) {
4873 err = got_error_from_errno("fprintf");
4874 goto done;
4876 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4877 err = got_error_from_errno("fprintf");
4878 goto done;
4880 if (fprintf(a->outfile, "path + %s%s\n",
4881 got_worktree_get_root_path(a->worktree),
4882 a->diff_staged ? " (staged changes)" : "") < 0) {
4883 err = got_error_from_errno("fprintf");
4884 goto done;
4886 a->header_shown = 1;
4889 if (a->diff_staged) {
4890 const char *label1 = NULL, *label2 = NULL;
4891 switch (staged_status) {
4892 case GOT_STATUS_MODIFY:
4893 label1 = path;
4894 label2 = path;
4895 break;
4896 case GOT_STATUS_ADD:
4897 label2 = path;
4898 break;
4899 case GOT_STATUS_DELETE:
4900 label1 = path;
4901 break;
4902 default:
4903 return got_error(GOT_ERR_FILE_STATUS);
4905 fd1 = got_opentempfd();
4906 if (fd1 == -1) {
4907 err = got_error_from_errno("got_opentempfd");
4908 goto done;
4910 fd2 = got_opentempfd();
4911 if (fd2 == -1) {
4912 err = got_error_from_errno("got_opentempfd");
4913 goto done;
4915 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4916 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4917 a->diff_algo, a->diff_context, a->ignore_whitespace,
4918 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4919 goto done;
4922 fd1 = got_opentempfd();
4923 if (fd1 == -1) {
4924 err = got_error_from_errno("got_opentempfd");
4925 goto done;
4928 if (staged_status == GOT_STATUS_ADD ||
4929 staged_status == GOT_STATUS_MODIFY) {
4930 char *id_str;
4931 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4932 8192, fd1);
4933 if (err)
4934 goto done;
4935 err = got_object_id_str(&id_str, staged_blob_id);
4936 if (err)
4937 goto done;
4938 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4939 err = got_error_from_errno("asprintf");
4940 free(id_str);
4941 goto done;
4943 free(id_str);
4944 } else if (status != GOT_STATUS_ADD) {
4945 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4946 fd1);
4947 if (err)
4948 goto done;
4951 if (status != GOT_STATUS_DELETE) {
4952 if (asprintf(&abspath, "%s/%s",
4953 got_worktree_get_root_path(a->worktree), path) == -1) {
4954 err = got_error_from_errno("asprintf");
4955 goto done;
4958 if (dirfd != -1) {
4959 fd = openat(dirfd, de_name,
4960 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4961 if (fd == -1) {
4962 if (!got_err_open_nofollow_on_symlink()) {
4963 err = got_error_from_errno2("openat",
4964 abspath);
4965 goto done;
4967 err = get_symlink_target_file(&fd, dirfd,
4968 de_name, abspath);
4969 if (err)
4970 goto done;
4972 } else {
4973 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4974 if (fd == -1) {
4975 if (!got_err_open_nofollow_on_symlink()) {
4976 err = got_error_from_errno2("open",
4977 abspath);
4978 goto done;
4980 err = get_symlink_target_file(&fd, dirfd,
4981 de_name, abspath);
4982 if (err)
4983 goto done;
4986 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4987 err = got_error_from_errno2("fstatat", abspath);
4988 goto done;
4990 f2 = fdopen(fd, "r");
4991 if (f2 == NULL) {
4992 err = got_error_from_errno2("fdopen", abspath);
4993 goto done;
4995 fd = -1;
4996 f2_exists = 1;
4999 if (blob1) {
5000 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5001 a->f1, blob1);
5002 if (err)
5003 goto done;
5006 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5007 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5008 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5009 done:
5010 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5011 err = got_error_from_errno("close");
5012 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5013 err = got_error_from_errno("close");
5014 if (blob1)
5015 got_object_blob_close(blob1);
5016 if (fd != -1 && close(fd) == -1 && err == NULL)
5017 err = got_error_from_errno("close");
5018 if (f2 && fclose(f2) == EOF && err == NULL)
5019 err = got_error_from_errno("fclose");
5020 free(abspath);
5021 return err;
5024 static const struct got_error *
5025 cmd_diff(int argc, char *argv[])
5027 const struct got_error *error;
5028 struct got_repository *repo = NULL;
5029 struct got_worktree *worktree = NULL;
5030 char *cwd = NULL, *repo_path = NULL;
5031 const char *commit_args[2] = { NULL, NULL };
5032 int ncommit_args = 0;
5033 struct got_object_id *ids[2] = { NULL, NULL };
5034 char *labels[2] = { NULL, NULL };
5035 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5036 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5037 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5038 const char *errstr;
5039 struct got_reflist_head refs;
5040 struct got_pathlist_head diffstat_paths, paths;
5041 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5042 int fd1 = -1, fd2 = -1;
5043 int *pack_fds = NULL;
5044 struct got_diffstat_cb_arg dsa;
5046 memset(&dsa, 0, sizeof(dsa));
5048 TAILQ_INIT(&refs);
5049 TAILQ_INIT(&paths);
5050 TAILQ_INIT(&diffstat_paths);
5052 #ifndef PROFILE
5053 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5054 NULL) == -1)
5055 err(1, "pledge");
5056 #endif
5058 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5059 switch (ch) {
5060 case 'a':
5061 force_text_diff = 1;
5062 break;
5063 case 'C':
5064 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5065 &errstr);
5066 if (errstr != NULL)
5067 errx(1, "number of context lines is %s: %s",
5068 errstr, optarg);
5069 break;
5070 case 'c':
5071 if (ncommit_args >= 2)
5072 errx(1, "too many -c options used");
5073 commit_args[ncommit_args++] = optarg;
5074 break;
5075 case 'd':
5076 show_diffstat = 1;
5077 break;
5078 case 'P':
5079 force_path = 1;
5080 break;
5081 case 'r':
5082 repo_path = realpath(optarg, NULL);
5083 if (repo_path == NULL)
5084 return got_error_from_errno2("realpath",
5085 optarg);
5086 got_path_strip_trailing_slashes(repo_path);
5087 rflag = 1;
5088 break;
5089 case 's':
5090 diff_staged = 1;
5091 break;
5092 case 'w':
5093 ignore_whitespace = 1;
5094 break;
5095 default:
5096 usage_diff();
5097 /* NOTREACHED */
5101 argc -= optind;
5102 argv += optind;
5104 cwd = getcwd(NULL, 0);
5105 if (cwd == NULL) {
5106 error = got_error_from_errno("getcwd");
5107 goto done;
5110 error = got_repo_pack_fds_open(&pack_fds);
5111 if (error != NULL)
5112 goto done;
5114 if (repo_path == NULL) {
5115 error = got_worktree_open(&worktree, cwd);
5116 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5117 goto done;
5118 else
5119 error = NULL;
5120 if (worktree) {
5121 repo_path =
5122 strdup(got_worktree_get_repo_path(worktree));
5123 if (repo_path == NULL) {
5124 error = got_error_from_errno("strdup");
5125 goto done;
5127 } else {
5128 repo_path = strdup(cwd);
5129 if (repo_path == NULL) {
5130 error = got_error_from_errno("strdup");
5131 goto done;
5136 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5137 free(repo_path);
5138 if (error != NULL)
5139 goto done;
5141 if (show_diffstat) {
5142 dsa.paths = &diffstat_paths;
5143 dsa.force_text = force_text_diff;
5144 dsa.ignore_ws = ignore_whitespace;
5145 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5148 if (rflag || worktree == NULL || ncommit_args > 0) {
5149 if (force_path) {
5150 error = got_error_msg(GOT_ERR_NOT_IMPL,
5151 "-P option can only be used when diffing "
5152 "a work tree");
5153 goto done;
5155 if (diff_staged) {
5156 error = got_error_msg(GOT_ERR_NOT_IMPL,
5157 "-s option can only be used when diffing "
5158 "a work tree");
5159 goto done;
5163 error = apply_unveil(got_repo_get_path(repo), 1,
5164 worktree ? got_worktree_get_root_path(worktree) : NULL);
5165 if (error)
5166 goto done;
5168 if ((!force_path && argc == 2) || ncommit_args > 0) {
5169 int obj_type = (ncommit_args > 0 ?
5170 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5171 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5172 NULL);
5173 if (error)
5174 goto done;
5175 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5176 const char *arg;
5177 if (ncommit_args > 0)
5178 arg = commit_args[i];
5179 else
5180 arg = argv[i];
5181 error = got_repo_match_object_id(&ids[i], &labels[i],
5182 arg, obj_type, &refs, repo);
5183 if (error) {
5184 if (error->code != GOT_ERR_NOT_REF &&
5185 error->code != GOT_ERR_NO_OBJ)
5186 goto done;
5187 if (ncommit_args > 0)
5188 goto done;
5189 error = NULL;
5190 break;
5195 f1 = got_opentemp();
5196 if (f1 == NULL) {
5197 error = got_error_from_errno("got_opentemp");
5198 goto done;
5201 f2 = got_opentemp();
5202 if (f2 == NULL) {
5203 error = got_error_from_errno("got_opentemp");
5204 goto done;
5207 outfile = got_opentemp();
5208 if (outfile == NULL) {
5209 error = got_error_from_errno("got_opentemp");
5210 goto done;
5213 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5214 struct print_diff_arg arg;
5215 char *id_str;
5217 if (worktree == NULL) {
5218 if (argc == 2 && ids[0] == NULL) {
5219 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5220 goto done;
5221 } else if (argc == 2 && ids[1] == NULL) {
5222 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5223 goto done;
5224 } else if (argc > 0) {
5225 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5226 "%s", "specified paths cannot be resolved");
5227 goto done;
5228 } else {
5229 error = got_error(GOT_ERR_NOT_WORKTREE);
5230 goto done;
5234 error = get_worktree_paths_from_argv(&paths, argc, argv,
5235 worktree);
5236 if (error)
5237 goto done;
5239 error = got_object_id_str(&id_str,
5240 got_worktree_get_base_commit_id(worktree));
5241 if (error)
5242 goto done;
5243 arg.repo = repo;
5244 arg.worktree = worktree;
5245 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5246 arg.diff_context = diff_context;
5247 arg.id_str = id_str;
5248 arg.header_shown = 0;
5249 arg.diff_staged = diff_staged;
5250 arg.ignore_whitespace = ignore_whitespace;
5251 arg.force_text_diff = force_text_diff;
5252 arg.diffstat = show_diffstat ? &dsa : NULL;
5253 arg.f1 = f1;
5254 arg.f2 = f2;
5255 arg.outfile = outfile;
5257 error = got_worktree_status(worktree, &paths, repo, 0,
5258 print_diff, &arg, check_cancelled, NULL);
5259 free(id_str);
5260 if (error)
5261 goto done;
5263 if (show_diffstat && dsa.nfiles > 0) {
5264 char *header;
5266 if (asprintf(&header, "diffstat %s%s",
5267 diff_staged ? "-s " : "",
5268 got_worktree_get_root_path(worktree)) == -1) {
5269 error = got_error_from_errno("asprintf");
5270 goto done;
5273 error = print_diffstat(&dsa, header);
5274 free(header);
5275 if (error)
5276 goto done;
5279 error = printfile(outfile);
5280 goto done;
5283 if (ncommit_args == 1) {
5284 struct got_commit_object *commit;
5285 error = got_object_open_as_commit(&commit, repo, ids[0]);
5286 if (error)
5287 goto done;
5289 labels[1] = labels[0];
5290 ids[1] = ids[0];
5291 if (got_object_commit_get_nparents(commit) > 0) {
5292 const struct got_object_id_queue *pids;
5293 struct got_object_qid *pid;
5294 pids = got_object_commit_get_parent_ids(commit);
5295 pid = STAILQ_FIRST(pids);
5296 ids[0] = got_object_id_dup(&pid->id);
5297 if (ids[0] == NULL) {
5298 error = got_error_from_errno(
5299 "got_object_id_dup");
5300 got_object_commit_close(commit);
5301 goto done;
5303 error = got_object_id_str(&labels[0], ids[0]);
5304 if (error) {
5305 got_object_commit_close(commit);
5306 goto done;
5308 } else {
5309 ids[0] = NULL;
5310 labels[0] = strdup("/dev/null");
5311 if (labels[0] == NULL) {
5312 error = got_error_from_errno("strdup");
5313 got_object_commit_close(commit);
5314 goto done;
5318 got_object_commit_close(commit);
5321 if (ncommit_args == 0 && argc > 2) {
5322 error = got_error_msg(GOT_ERR_BAD_PATH,
5323 "path arguments cannot be used when diffing two objects");
5324 goto done;
5327 if (ids[0]) {
5328 error = got_object_get_type(&type1, repo, ids[0]);
5329 if (error)
5330 goto done;
5333 error = got_object_get_type(&type2, repo, ids[1]);
5334 if (error)
5335 goto done;
5336 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5337 error = got_error(GOT_ERR_OBJ_TYPE);
5338 goto done;
5340 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5341 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5342 "path arguments cannot be used when diffing blobs");
5343 goto done;
5346 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5347 char *in_repo_path;
5348 struct got_pathlist_entry *new;
5349 if (worktree) {
5350 const char *prefix;
5351 char *p;
5352 error = got_worktree_resolve_path(&p, worktree,
5353 argv[i]);
5354 if (error)
5355 goto done;
5356 prefix = got_worktree_get_path_prefix(worktree);
5357 while (prefix[0] == '/')
5358 prefix++;
5359 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5360 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5361 p) == -1) {
5362 error = got_error_from_errno("asprintf");
5363 free(p);
5364 goto done;
5366 free(p);
5367 } else {
5368 char *mapped_path, *s;
5369 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5370 if (error)
5371 goto done;
5372 s = mapped_path;
5373 while (s[0] == '/')
5374 s++;
5375 in_repo_path = strdup(s);
5376 if (in_repo_path == NULL) {
5377 error = got_error_from_errno("asprintf");
5378 free(mapped_path);
5379 goto done;
5381 free(mapped_path);
5384 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5385 if (error || new == NULL /* duplicate */)
5386 free(in_repo_path);
5387 if (error)
5388 goto done;
5391 if (worktree) {
5392 /* Release work tree lock. */
5393 got_worktree_close(worktree);
5394 worktree = NULL;
5397 fd1 = got_opentempfd();
5398 if (fd1 == -1) {
5399 error = got_error_from_errno("got_opentempfd");
5400 goto done;
5403 fd2 = got_opentempfd();
5404 if (fd2 == -1) {
5405 error = got_error_from_errno("got_opentempfd");
5406 goto done;
5409 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5410 case GOT_OBJ_TYPE_BLOB:
5411 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5412 fd1, fd2, ids[0], ids[1], NULL, NULL,
5413 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5414 ignore_whitespace, force_text_diff,
5415 show_diffstat ? &dsa : NULL, repo, outfile);
5416 break;
5417 case GOT_OBJ_TYPE_TREE:
5418 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5419 ids[0], ids[1], &paths, "", "",
5420 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5421 ignore_whitespace, force_text_diff,
5422 show_diffstat ? &dsa : NULL, repo, outfile);
5423 break;
5424 case GOT_OBJ_TYPE_COMMIT:
5425 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5426 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5427 fd1, fd2, ids[0], ids[1], &paths,
5428 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5429 ignore_whitespace, force_text_diff,
5430 show_diffstat ? &dsa : NULL, repo, outfile);
5431 break;
5432 default:
5433 error = got_error(GOT_ERR_OBJ_TYPE);
5435 if (error)
5436 goto done;
5438 if (show_diffstat && dsa.nfiles > 0) {
5439 char *header = NULL;
5441 if (asprintf(&header, "diffstat %s %s",
5442 labels[0], labels[1]) == -1) {
5443 error = got_error_from_errno("asprintf");
5444 goto done;
5447 error = print_diffstat(&dsa, header);
5448 free(header);
5449 if (error)
5450 goto done;
5453 error = printfile(outfile);
5455 done:
5456 free(labels[0]);
5457 free(labels[1]);
5458 free(ids[0]);
5459 free(ids[1]);
5460 if (worktree)
5461 got_worktree_close(worktree);
5462 if (repo) {
5463 const struct got_error *close_err = got_repo_close(repo);
5464 if (error == NULL)
5465 error = close_err;
5467 if (pack_fds) {
5468 const struct got_error *pack_err =
5469 got_repo_pack_fds_close(pack_fds);
5470 if (error == NULL)
5471 error = pack_err;
5473 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5474 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5475 got_ref_list_free(&refs);
5476 if (outfile && fclose(outfile) == EOF && error == NULL)
5477 error = got_error_from_errno("fclose");
5478 if (f1 && fclose(f1) == EOF && error == NULL)
5479 error = got_error_from_errno("fclose");
5480 if (f2 && fclose(f2) == EOF && error == NULL)
5481 error = got_error_from_errno("fclose");
5482 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5483 error = got_error_from_errno("close");
5484 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5485 error = got_error_from_errno("close");
5486 return error;
5489 __dead static void
5490 usage_blame(void)
5492 fprintf(stderr,
5493 "usage: %s blame [-c commit] [-r repository-path] path\n",
5494 getprogname());
5495 exit(1);
5498 struct blame_line {
5499 int annotated;
5500 char *id_str;
5501 char *committer;
5502 char datebuf[11]; /* YYYY-MM-DD + NUL */
5505 struct blame_cb_args {
5506 struct blame_line *lines;
5507 int nlines;
5508 int nlines_prec;
5509 int lineno_cur;
5510 off_t *line_offsets;
5511 FILE *f;
5512 struct got_repository *repo;
5515 static const struct got_error *
5516 blame_cb(void *arg, int nlines, int lineno,
5517 struct got_commit_object *commit, struct got_object_id *id)
5519 const struct got_error *err = NULL;
5520 struct blame_cb_args *a = arg;
5521 struct blame_line *bline;
5522 char *line = NULL;
5523 size_t linesize = 0;
5524 off_t offset;
5525 struct tm tm;
5526 time_t committer_time;
5528 if (nlines != a->nlines ||
5529 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5530 return got_error(GOT_ERR_RANGE);
5532 if (sigint_received)
5533 return got_error(GOT_ERR_ITER_COMPLETED);
5535 if (lineno == -1)
5536 return NULL; /* no change in this commit */
5538 /* Annotate this line. */
5539 bline = &a->lines[lineno - 1];
5540 if (bline->annotated)
5541 return NULL;
5542 err = got_object_id_str(&bline->id_str, id);
5543 if (err)
5544 return err;
5546 bline->committer = strdup(got_object_commit_get_committer(commit));
5547 if (bline->committer == NULL) {
5548 err = got_error_from_errno("strdup");
5549 goto done;
5552 committer_time = got_object_commit_get_committer_time(commit);
5553 if (gmtime_r(&committer_time, &tm) == NULL)
5554 return got_error_from_errno("gmtime_r");
5555 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5556 &tm) == 0) {
5557 err = got_error(GOT_ERR_NO_SPACE);
5558 goto done;
5560 bline->annotated = 1;
5562 /* Print lines annotated so far. */
5563 bline = &a->lines[a->lineno_cur - 1];
5564 if (!bline->annotated)
5565 goto done;
5567 offset = a->line_offsets[a->lineno_cur - 1];
5568 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5569 err = got_error_from_errno("fseeko");
5570 goto done;
5573 while (a->lineno_cur <= a->nlines && bline->annotated) {
5574 char *smallerthan, *at, *nl, *committer;
5575 size_t len;
5577 if (getline(&line, &linesize, a->f) == -1) {
5578 if (ferror(a->f))
5579 err = got_error_from_errno("getline");
5580 break;
5583 committer = bline->committer;
5584 smallerthan = strchr(committer, '<');
5585 if (smallerthan && smallerthan[1] != '\0')
5586 committer = smallerthan + 1;
5587 at = strchr(committer, '@');
5588 if (at)
5589 *at = '\0';
5590 len = strlen(committer);
5591 if (len >= 9)
5592 committer[8] = '\0';
5594 nl = strchr(line, '\n');
5595 if (nl)
5596 *nl = '\0';
5597 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5598 bline->id_str, bline->datebuf, committer, line);
5600 a->lineno_cur++;
5601 bline = &a->lines[a->lineno_cur - 1];
5603 done:
5604 free(line);
5605 return err;
5608 static const struct got_error *
5609 cmd_blame(int argc, char *argv[])
5611 const struct got_error *error;
5612 struct got_repository *repo = NULL;
5613 struct got_worktree *worktree = NULL;
5614 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5615 char *link_target = NULL;
5616 struct got_object_id *obj_id = NULL;
5617 struct got_object_id *commit_id = NULL;
5618 struct got_commit_object *commit = NULL;
5619 struct got_blob_object *blob = NULL;
5620 char *commit_id_str = NULL;
5621 struct blame_cb_args bca;
5622 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5623 off_t filesize;
5624 int *pack_fds = NULL;
5625 FILE *f1 = NULL, *f2 = NULL;
5627 fd1 = got_opentempfd();
5628 if (fd1 == -1)
5629 return got_error_from_errno("got_opentempfd");
5631 memset(&bca, 0, sizeof(bca));
5633 #ifndef PROFILE
5634 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5635 NULL) == -1)
5636 err(1, "pledge");
5637 #endif
5639 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5640 switch (ch) {
5641 case 'c':
5642 commit_id_str = optarg;
5643 break;
5644 case 'r':
5645 repo_path = realpath(optarg, NULL);
5646 if (repo_path == NULL)
5647 return got_error_from_errno2("realpath",
5648 optarg);
5649 got_path_strip_trailing_slashes(repo_path);
5650 break;
5651 default:
5652 usage_blame();
5653 /* NOTREACHED */
5657 argc -= optind;
5658 argv += optind;
5660 if (argc == 1)
5661 path = argv[0];
5662 else
5663 usage_blame();
5665 cwd = getcwd(NULL, 0);
5666 if (cwd == NULL) {
5667 error = got_error_from_errno("getcwd");
5668 goto done;
5671 error = got_repo_pack_fds_open(&pack_fds);
5672 if (error != NULL)
5673 goto done;
5675 if (repo_path == NULL) {
5676 error = got_worktree_open(&worktree, cwd);
5677 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5678 goto done;
5679 else
5680 error = NULL;
5681 if (worktree) {
5682 repo_path =
5683 strdup(got_worktree_get_repo_path(worktree));
5684 if (repo_path == NULL) {
5685 error = got_error_from_errno("strdup");
5686 if (error)
5687 goto done;
5689 } else {
5690 repo_path = strdup(cwd);
5691 if (repo_path == NULL) {
5692 error = got_error_from_errno("strdup");
5693 goto done;
5698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5699 if (error != NULL)
5700 goto done;
5702 if (worktree) {
5703 const char *prefix = got_worktree_get_path_prefix(worktree);
5704 char *p;
5706 error = got_worktree_resolve_path(&p, worktree, path);
5707 if (error)
5708 goto done;
5709 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5710 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5711 p) == -1) {
5712 error = got_error_from_errno("asprintf");
5713 free(p);
5714 goto done;
5716 free(p);
5717 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5718 } else {
5719 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5720 if (error)
5721 goto done;
5722 error = got_repo_map_path(&in_repo_path, repo, path);
5724 if (error)
5725 goto done;
5727 if (commit_id_str == NULL) {
5728 struct got_reference *head_ref;
5729 error = got_ref_open(&head_ref, repo, worktree ?
5730 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5731 if (error != NULL)
5732 goto done;
5733 error = got_ref_resolve(&commit_id, repo, head_ref);
5734 got_ref_close(head_ref);
5735 if (error != NULL)
5736 goto done;
5737 } else {
5738 struct got_reflist_head refs;
5739 TAILQ_INIT(&refs);
5740 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5741 NULL);
5742 if (error)
5743 goto done;
5744 error = got_repo_match_object_id(&commit_id, NULL,
5745 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5746 got_ref_list_free(&refs);
5747 if (error)
5748 goto done;
5751 if (worktree) {
5752 /* Release work tree lock. */
5753 got_worktree_close(worktree);
5754 worktree = NULL;
5757 error = got_object_open_as_commit(&commit, repo, commit_id);
5758 if (error)
5759 goto done;
5761 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5762 commit, repo);
5763 if (error)
5764 goto done;
5766 error = got_object_id_by_path(&obj_id, repo, commit,
5767 link_target ? link_target : in_repo_path);
5768 if (error)
5769 goto done;
5771 error = got_object_get_type(&obj_type, repo, obj_id);
5772 if (error)
5773 goto done;
5775 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5776 error = got_error_path(link_target ? link_target : in_repo_path,
5777 GOT_ERR_OBJ_TYPE);
5778 goto done;
5781 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5782 if (error)
5783 goto done;
5784 bca.f = got_opentemp();
5785 if (bca.f == NULL) {
5786 error = got_error_from_errno("got_opentemp");
5787 goto done;
5789 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5790 &bca.line_offsets, bca.f, blob);
5791 if (error || bca.nlines == 0)
5792 goto done;
5794 /* Don't include \n at EOF in the blame line count. */
5795 if (bca.line_offsets[bca.nlines - 1] == filesize)
5796 bca.nlines--;
5798 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5799 if (bca.lines == NULL) {
5800 error = got_error_from_errno("calloc");
5801 goto done;
5803 bca.lineno_cur = 1;
5804 bca.nlines_prec = 0;
5805 i = bca.nlines;
5806 while (i > 0) {
5807 i /= 10;
5808 bca.nlines_prec++;
5810 bca.repo = repo;
5812 fd2 = got_opentempfd();
5813 if (fd2 == -1) {
5814 error = got_error_from_errno("got_opentempfd");
5815 goto done;
5817 fd3 = got_opentempfd();
5818 if (fd3 == -1) {
5819 error = got_error_from_errno("got_opentempfd");
5820 goto done;
5822 f1 = got_opentemp();
5823 if (f1 == NULL) {
5824 error = got_error_from_errno("got_opentemp");
5825 goto done;
5827 f2 = got_opentemp();
5828 if (f2 == NULL) {
5829 error = got_error_from_errno("got_opentemp");
5830 goto done;
5832 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5833 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5834 check_cancelled, NULL, fd2, fd3, f1, f2);
5835 done:
5836 free(in_repo_path);
5837 free(link_target);
5838 free(repo_path);
5839 free(cwd);
5840 free(commit_id);
5841 free(obj_id);
5842 if (commit)
5843 got_object_commit_close(commit);
5845 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5846 error = got_error_from_errno("close");
5847 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5848 error = got_error_from_errno("close");
5849 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5850 error = got_error_from_errno("close");
5851 if (f1 && fclose(f1) == EOF && error == NULL)
5852 error = got_error_from_errno("fclose");
5853 if (f2 && fclose(f2) == EOF && error == NULL)
5854 error = got_error_from_errno("fclose");
5856 if (blob)
5857 got_object_blob_close(blob);
5858 if (worktree)
5859 got_worktree_close(worktree);
5860 if (repo) {
5861 const struct got_error *close_err = got_repo_close(repo);
5862 if (error == NULL)
5863 error = close_err;
5865 if (pack_fds) {
5866 const struct got_error *pack_err =
5867 got_repo_pack_fds_close(pack_fds);
5868 if (error == NULL)
5869 error = pack_err;
5871 if (bca.lines) {
5872 for (i = 0; i < bca.nlines; i++) {
5873 struct blame_line *bline = &bca.lines[i];
5874 free(bline->id_str);
5875 free(bline->committer);
5877 free(bca.lines);
5879 free(bca.line_offsets);
5880 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5881 error = got_error_from_errno("fclose");
5882 return error;
5885 __dead static void
5886 usage_tree(void)
5888 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5889 "[path]\n", getprogname());
5890 exit(1);
5893 static const struct got_error *
5894 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5895 const char *root_path, struct got_repository *repo)
5897 const struct got_error *err = NULL;
5898 int is_root_path = (strcmp(path, root_path) == 0);
5899 const char *modestr = "";
5900 mode_t mode = got_tree_entry_get_mode(te);
5901 char *link_target = NULL;
5903 path += strlen(root_path);
5904 while (path[0] == '/')
5905 path++;
5907 if (got_object_tree_entry_is_submodule(te))
5908 modestr = "$";
5909 else if (S_ISLNK(mode)) {
5910 int i;
5912 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5913 if (err)
5914 return err;
5915 for (i = 0; i < strlen(link_target); i++) {
5916 if (!isprint((unsigned char)link_target[i]))
5917 link_target[i] = '?';
5920 modestr = "@";
5922 else if (S_ISDIR(mode))
5923 modestr = "/";
5924 else if (mode & S_IXUSR)
5925 modestr = "*";
5927 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5928 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5929 link_target ? " -> ": "", link_target ? link_target : "");
5931 free(link_target);
5932 return NULL;
5935 static const struct got_error *
5936 print_tree(const char *path, struct got_commit_object *commit,
5937 int show_ids, int recurse, const char *root_path,
5938 struct got_repository *repo)
5940 const struct got_error *err = NULL;
5941 struct got_object_id *tree_id = NULL;
5942 struct got_tree_object *tree = NULL;
5943 int nentries, i;
5945 err = got_object_id_by_path(&tree_id, repo, commit, path);
5946 if (err)
5947 goto done;
5949 err = got_object_open_as_tree(&tree, repo, tree_id);
5950 if (err)
5951 goto done;
5952 nentries = got_object_tree_get_nentries(tree);
5953 for (i = 0; i < nentries; i++) {
5954 struct got_tree_entry *te;
5955 char *id = NULL;
5957 if (sigint_received || sigpipe_received)
5958 break;
5960 te = got_object_tree_get_entry(tree, i);
5961 if (show_ids) {
5962 char *id_str;
5963 err = got_object_id_str(&id_str,
5964 got_tree_entry_get_id(te));
5965 if (err)
5966 goto done;
5967 if (asprintf(&id, "%s ", id_str) == -1) {
5968 err = got_error_from_errno("asprintf");
5969 free(id_str);
5970 goto done;
5972 free(id_str);
5974 err = print_entry(te, id, path, root_path, repo);
5975 free(id);
5976 if (err)
5977 goto done;
5979 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5980 char *child_path;
5981 if (asprintf(&child_path, "%s%s%s", path,
5982 path[0] == '/' && path[1] == '\0' ? "" : "/",
5983 got_tree_entry_get_name(te)) == -1) {
5984 err = got_error_from_errno("asprintf");
5985 goto done;
5987 err = print_tree(child_path, commit, show_ids, 1,
5988 root_path, repo);
5989 free(child_path);
5990 if (err)
5991 goto done;
5994 done:
5995 if (tree)
5996 got_object_tree_close(tree);
5997 free(tree_id);
5998 return err;
6001 static const struct got_error *
6002 cmd_tree(int argc, char *argv[])
6004 const struct got_error *error;
6005 struct got_repository *repo = NULL;
6006 struct got_worktree *worktree = NULL;
6007 const char *path, *refname = NULL;
6008 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6009 struct got_object_id *commit_id = NULL;
6010 struct got_commit_object *commit = NULL;
6011 char *commit_id_str = NULL;
6012 int show_ids = 0, recurse = 0;
6013 int ch;
6014 int *pack_fds = NULL;
6016 #ifndef PROFILE
6017 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6018 NULL) == -1)
6019 err(1, "pledge");
6020 #endif
6022 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6023 switch (ch) {
6024 case 'c':
6025 commit_id_str = optarg;
6026 break;
6027 case 'i':
6028 show_ids = 1;
6029 break;
6030 case 'R':
6031 recurse = 1;
6032 break;
6033 case 'r':
6034 repo_path = realpath(optarg, NULL);
6035 if (repo_path == NULL)
6036 return got_error_from_errno2("realpath",
6037 optarg);
6038 got_path_strip_trailing_slashes(repo_path);
6039 break;
6040 default:
6041 usage_tree();
6042 /* NOTREACHED */
6046 argc -= optind;
6047 argv += optind;
6049 if (argc == 1)
6050 path = argv[0];
6051 else if (argc > 1)
6052 usage_tree();
6053 else
6054 path = NULL;
6056 cwd = getcwd(NULL, 0);
6057 if (cwd == NULL) {
6058 error = got_error_from_errno("getcwd");
6059 goto done;
6062 error = got_repo_pack_fds_open(&pack_fds);
6063 if (error != NULL)
6064 goto done;
6066 if (repo_path == NULL) {
6067 error = got_worktree_open(&worktree, cwd);
6068 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6069 goto done;
6070 else
6071 error = NULL;
6072 if (worktree) {
6073 repo_path =
6074 strdup(got_worktree_get_repo_path(worktree));
6075 if (repo_path == NULL)
6076 error = got_error_from_errno("strdup");
6077 if (error)
6078 goto done;
6079 } else {
6080 repo_path = strdup(cwd);
6081 if (repo_path == NULL) {
6082 error = got_error_from_errno("strdup");
6083 goto done;
6088 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6089 if (error != NULL)
6090 goto done;
6092 if (worktree) {
6093 const char *prefix = got_worktree_get_path_prefix(worktree);
6094 char *p;
6096 if (path == NULL)
6097 path = "";
6098 error = got_worktree_resolve_path(&p, worktree, path);
6099 if (error)
6100 goto done;
6101 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6102 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6103 p) == -1) {
6104 error = got_error_from_errno("asprintf");
6105 free(p);
6106 goto done;
6108 free(p);
6109 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6110 if (error)
6111 goto done;
6112 } else {
6113 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6114 if (error)
6115 goto done;
6116 if (path == NULL)
6117 path = "/";
6118 error = got_repo_map_path(&in_repo_path, repo, path);
6119 if (error != NULL)
6120 goto done;
6123 if (commit_id_str == NULL) {
6124 struct got_reference *head_ref;
6125 if (worktree)
6126 refname = got_worktree_get_head_ref_name(worktree);
6127 else
6128 refname = GOT_REF_HEAD;
6129 error = got_ref_open(&head_ref, repo, refname, 0);
6130 if (error != NULL)
6131 goto done;
6132 error = got_ref_resolve(&commit_id, repo, head_ref);
6133 got_ref_close(head_ref);
6134 if (error != NULL)
6135 goto done;
6136 } else {
6137 struct got_reflist_head refs;
6138 TAILQ_INIT(&refs);
6139 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6140 NULL);
6141 if (error)
6142 goto done;
6143 error = got_repo_match_object_id(&commit_id, NULL,
6144 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6145 got_ref_list_free(&refs);
6146 if (error)
6147 goto done;
6150 if (worktree) {
6151 /* Release work tree lock. */
6152 got_worktree_close(worktree);
6153 worktree = NULL;
6156 error = got_object_open_as_commit(&commit, repo, commit_id);
6157 if (error)
6158 goto done;
6160 error = print_tree(in_repo_path, commit, show_ids, recurse,
6161 in_repo_path, repo);
6162 done:
6163 free(in_repo_path);
6164 free(repo_path);
6165 free(cwd);
6166 free(commit_id);
6167 if (commit)
6168 got_object_commit_close(commit);
6169 if (worktree)
6170 got_worktree_close(worktree);
6171 if (repo) {
6172 const struct got_error *close_err = got_repo_close(repo);
6173 if (error == NULL)
6174 error = close_err;
6176 if (pack_fds) {
6177 const struct got_error *pack_err =
6178 got_repo_pack_fds_close(pack_fds);
6179 if (error == NULL)
6180 error = pack_err;
6182 return error;
6185 __dead static void
6186 usage_status(void)
6188 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6189 "[-s status-codes] [path ...]\n", getprogname());
6190 exit(1);
6193 struct got_status_arg {
6194 char *status_codes;
6195 int suppress;
6198 static const struct got_error *
6199 print_status(void *arg, unsigned char status, unsigned char staged_status,
6200 const char *path, struct got_object_id *blob_id,
6201 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6202 int dirfd, const char *de_name)
6204 struct got_status_arg *st = arg;
6206 if (status == staged_status && (status == GOT_STATUS_DELETE))
6207 status = GOT_STATUS_NO_CHANGE;
6208 if (st != NULL && st->status_codes) {
6209 size_t ncodes = strlen(st->status_codes);
6210 int i, j = 0;
6212 for (i = 0; i < ncodes ; i++) {
6213 if (st->suppress) {
6214 if (status == st->status_codes[i] ||
6215 staged_status == st->status_codes[i]) {
6216 j++;
6217 continue;
6219 } else {
6220 if (status == st->status_codes[i] ||
6221 staged_status == st->status_codes[i])
6222 break;
6226 if (st->suppress && j == 0)
6227 goto print;
6229 if (i == ncodes)
6230 return NULL;
6232 print:
6233 printf("%c%c %s\n", status, staged_status, path);
6234 return NULL;
6237 static const struct got_error *
6238 cmd_status(int argc, char *argv[])
6240 const struct got_error *error = NULL;
6241 struct got_repository *repo = NULL;
6242 struct got_worktree *worktree = NULL;
6243 struct got_status_arg st;
6244 char *cwd = NULL;
6245 struct got_pathlist_head paths;
6246 int ch, i, no_ignores = 0;
6247 int *pack_fds = NULL;
6249 TAILQ_INIT(&paths);
6251 memset(&st, 0, sizeof(st));
6252 st.status_codes = NULL;
6253 st.suppress = 0;
6255 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6256 switch (ch) {
6257 case 'I':
6258 no_ignores = 1;
6259 break;
6260 case 'S':
6261 if (st.status_codes != NULL && st.suppress == 0)
6262 option_conflict('S', 's');
6263 st.suppress = 1;
6264 /* fallthrough */
6265 case 's':
6266 for (i = 0; i < strlen(optarg); i++) {
6267 switch (optarg[i]) {
6268 case GOT_STATUS_MODIFY:
6269 case GOT_STATUS_ADD:
6270 case GOT_STATUS_DELETE:
6271 case GOT_STATUS_CONFLICT:
6272 case GOT_STATUS_MISSING:
6273 case GOT_STATUS_OBSTRUCTED:
6274 case GOT_STATUS_UNVERSIONED:
6275 case GOT_STATUS_MODE_CHANGE:
6276 case GOT_STATUS_NONEXISTENT:
6277 break;
6278 default:
6279 errx(1, "invalid status code '%c'",
6280 optarg[i]);
6283 if (ch == 's' && st.suppress)
6284 option_conflict('s', 'S');
6285 st.status_codes = optarg;
6286 break;
6287 default:
6288 usage_status();
6289 /* NOTREACHED */
6293 argc -= optind;
6294 argv += optind;
6296 #ifndef PROFILE
6297 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6298 NULL) == -1)
6299 err(1, "pledge");
6300 #endif
6301 cwd = getcwd(NULL, 0);
6302 if (cwd == NULL) {
6303 error = got_error_from_errno("getcwd");
6304 goto done;
6307 error = got_repo_pack_fds_open(&pack_fds);
6308 if (error != NULL)
6309 goto done;
6311 error = got_worktree_open(&worktree, cwd);
6312 if (error) {
6313 if (error->code == GOT_ERR_NOT_WORKTREE)
6314 error = wrap_not_worktree_error(error, "status", cwd);
6315 goto done;
6318 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6319 NULL, pack_fds);
6320 if (error != NULL)
6321 goto done;
6323 error = apply_unveil(got_repo_get_path(repo), 1,
6324 got_worktree_get_root_path(worktree));
6325 if (error)
6326 goto done;
6328 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6329 if (error)
6330 goto done;
6332 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6333 print_status, &st, check_cancelled, NULL);
6334 done:
6335 if (pack_fds) {
6336 const struct got_error *pack_err =
6337 got_repo_pack_fds_close(pack_fds);
6338 if (error == NULL)
6339 error = pack_err;
6342 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6343 free(cwd);
6344 return error;
6347 __dead static void
6348 usage_ref(void)
6350 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6351 "[-s reference] [name]\n", getprogname());
6352 exit(1);
6355 static const struct got_error *
6356 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6358 static const struct got_error *err = NULL;
6359 struct got_reflist_head refs;
6360 struct got_reflist_entry *re;
6362 TAILQ_INIT(&refs);
6363 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6364 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6365 repo);
6366 if (err)
6367 return err;
6369 TAILQ_FOREACH(re, &refs, entry) {
6370 char *refstr;
6371 refstr = got_ref_to_str(re->ref);
6372 if (refstr == NULL) {
6373 err = got_error_from_errno("got_ref_to_str");
6374 break;
6376 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6377 free(refstr);
6380 got_ref_list_free(&refs);
6381 return err;
6384 static const struct got_error *
6385 delete_ref_by_name(struct got_repository *repo, const char *refname)
6387 const struct got_error *err;
6388 struct got_reference *ref;
6390 err = got_ref_open(&ref, repo, refname, 0);
6391 if (err)
6392 return err;
6394 err = delete_ref(repo, ref);
6395 got_ref_close(ref);
6396 return err;
6399 static const struct got_error *
6400 add_ref(struct got_repository *repo, const char *refname, const char *target)
6402 const struct got_error *err = NULL;
6403 struct got_object_id *id = NULL;
6404 struct got_reference *ref = NULL;
6405 struct got_reflist_head refs;
6408 * Don't let the user create a reference name with a leading '-'.
6409 * While technically a valid reference name, this case is usually
6410 * an unintended typo.
6412 if (refname[0] == '-')
6413 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6415 TAILQ_INIT(&refs);
6416 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6417 if (err)
6418 goto done;
6419 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6420 &refs, repo);
6421 got_ref_list_free(&refs);
6422 if (err)
6423 goto done;
6425 err = got_ref_alloc(&ref, refname, id);
6426 if (err)
6427 goto done;
6429 err = got_ref_write(ref, repo);
6430 done:
6431 if (ref)
6432 got_ref_close(ref);
6433 free(id);
6434 return err;
6437 static const struct got_error *
6438 add_symref(struct got_repository *repo, const char *refname, const char *target)
6440 const struct got_error *err = NULL;
6441 struct got_reference *ref = NULL;
6442 struct got_reference *target_ref = NULL;
6445 * Don't let the user create a reference name with a leading '-'.
6446 * While technically a valid reference name, this case is usually
6447 * an unintended typo.
6449 if (refname[0] == '-')
6450 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6452 err = got_ref_open(&target_ref, repo, target, 0);
6453 if (err)
6454 return err;
6456 err = got_ref_alloc_symref(&ref, refname, target_ref);
6457 if (err)
6458 goto done;
6460 err = got_ref_write(ref, repo);
6461 done:
6462 if (target_ref)
6463 got_ref_close(target_ref);
6464 if (ref)
6465 got_ref_close(ref);
6466 return err;
6469 static const struct got_error *
6470 cmd_ref(int argc, char *argv[])
6472 const struct got_error *error = NULL;
6473 struct got_repository *repo = NULL;
6474 struct got_worktree *worktree = NULL;
6475 char *cwd = NULL, *repo_path = NULL;
6476 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6477 const char *obj_arg = NULL, *symref_target= NULL;
6478 char *refname = NULL;
6479 int *pack_fds = NULL;
6481 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6482 switch (ch) {
6483 case 'c':
6484 obj_arg = optarg;
6485 break;
6486 case 'd':
6487 do_delete = 1;
6488 break;
6489 case 'l':
6490 do_list = 1;
6491 break;
6492 case 'r':
6493 repo_path = realpath(optarg, NULL);
6494 if (repo_path == NULL)
6495 return got_error_from_errno2("realpath",
6496 optarg);
6497 got_path_strip_trailing_slashes(repo_path);
6498 break;
6499 case 's':
6500 symref_target = optarg;
6501 break;
6502 case 't':
6503 sort_by_time = 1;
6504 break;
6505 default:
6506 usage_ref();
6507 /* NOTREACHED */
6511 if (obj_arg && do_list)
6512 option_conflict('c', 'l');
6513 if (obj_arg && do_delete)
6514 option_conflict('c', 'd');
6515 if (obj_arg && symref_target)
6516 option_conflict('c', 's');
6517 if (symref_target && do_delete)
6518 option_conflict('s', 'd');
6519 if (symref_target && do_list)
6520 option_conflict('s', 'l');
6521 if (do_delete && do_list)
6522 option_conflict('d', 'l');
6523 if (sort_by_time && !do_list)
6524 errx(1, "-t option requires -l option");
6526 argc -= optind;
6527 argv += optind;
6529 if (do_list) {
6530 if (argc != 0 && argc != 1)
6531 usage_ref();
6532 if (argc == 1) {
6533 refname = strdup(argv[0]);
6534 if (refname == NULL) {
6535 error = got_error_from_errno("strdup");
6536 goto done;
6539 } else {
6540 if (argc != 1)
6541 usage_ref();
6542 refname = strdup(argv[0]);
6543 if (refname == NULL) {
6544 error = got_error_from_errno("strdup");
6545 goto done;
6549 if (refname)
6550 got_path_strip_trailing_slashes(refname);
6552 #ifndef PROFILE
6553 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6554 "sendfd unveil", NULL) == -1)
6555 err(1, "pledge");
6556 #endif
6557 cwd = getcwd(NULL, 0);
6558 if (cwd == NULL) {
6559 error = got_error_from_errno("getcwd");
6560 goto done;
6563 error = got_repo_pack_fds_open(&pack_fds);
6564 if (error != NULL)
6565 goto done;
6567 if (repo_path == NULL) {
6568 error = got_worktree_open(&worktree, cwd);
6569 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6570 goto done;
6571 else
6572 error = NULL;
6573 if (worktree) {
6574 repo_path =
6575 strdup(got_worktree_get_repo_path(worktree));
6576 if (repo_path == NULL)
6577 error = got_error_from_errno("strdup");
6578 if (error)
6579 goto done;
6580 } else {
6581 repo_path = strdup(cwd);
6582 if (repo_path == NULL) {
6583 error = got_error_from_errno("strdup");
6584 goto done;
6589 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6590 if (error != NULL)
6591 goto done;
6593 #ifndef PROFILE
6594 if (do_list) {
6595 /* Remove "cpath" promise. */
6596 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6597 NULL) == -1)
6598 err(1, "pledge");
6600 #endif
6602 error = apply_unveil(got_repo_get_path(repo), do_list,
6603 worktree ? got_worktree_get_root_path(worktree) : NULL);
6604 if (error)
6605 goto done;
6607 if (do_list)
6608 error = list_refs(repo, refname, sort_by_time);
6609 else if (do_delete)
6610 error = delete_ref_by_name(repo, refname);
6611 else if (symref_target)
6612 error = add_symref(repo, refname, symref_target);
6613 else {
6614 if (obj_arg == NULL)
6615 usage_ref();
6616 error = add_ref(repo, refname, obj_arg);
6618 done:
6619 free(refname);
6620 if (repo) {
6621 const struct got_error *close_err = got_repo_close(repo);
6622 if (error == NULL)
6623 error = close_err;
6625 if (worktree)
6626 got_worktree_close(worktree);
6627 if (pack_fds) {
6628 const struct got_error *pack_err =
6629 got_repo_pack_fds_close(pack_fds);
6630 if (error == NULL)
6631 error = pack_err;
6633 free(cwd);
6634 free(repo_path);
6635 return error;
6638 __dead static void
6639 usage_branch(void)
6641 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6642 "[-r repository-path] [name]\n", getprogname());
6643 exit(1);
6646 static const struct got_error *
6647 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6648 struct got_reference *ref)
6650 const struct got_error *err = NULL;
6651 const char *refname, *marker = " ";
6652 char *refstr;
6654 refname = got_ref_get_name(ref);
6655 if (worktree && strcmp(refname,
6656 got_worktree_get_head_ref_name(worktree)) == 0) {
6657 struct got_object_id *id = NULL;
6659 err = got_ref_resolve(&id, repo, ref);
6660 if (err)
6661 return err;
6662 if (got_object_id_cmp(id,
6663 got_worktree_get_base_commit_id(worktree)) == 0)
6664 marker = "* ";
6665 else
6666 marker = "~ ";
6667 free(id);
6670 if (strncmp(refname, "refs/heads/", 11) == 0)
6671 refname += 11;
6672 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6673 refname += 18;
6674 if (strncmp(refname, "refs/remotes/", 13) == 0)
6675 refname += 13;
6677 refstr = got_ref_to_str(ref);
6678 if (refstr == NULL)
6679 return got_error_from_errno("got_ref_to_str");
6681 printf("%s%s: %s\n", marker, refname, refstr);
6682 free(refstr);
6683 return NULL;
6686 static const struct got_error *
6687 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6689 const char *refname;
6691 if (worktree == NULL)
6692 return got_error(GOT_ERR_NOT_WORKTREE);
6694 refname = got_worktree_get_head_ref_name(worktree);
6696 if (strncmp(refname, "refs/heads/", 11) == 0)
6697 refname += 11;
6698 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6699 refname += 18;
6701 printf("%s\n", refname);
6703 return NULL;
6706 static const struct got_error *
6707 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6708 int sort_by_time)
6710 static const struct got_error *err = NULL;
6711 struct got_reflist_head refs;
6712 struct got_reflist_entry *re;
6713 struct got_reference *temp_ref = NULL;
6714 int rebase_in_progress, histedit_in_progress;
6716 TAILQ_INIT(&refs);
6718 if (worktree) {
6719 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6720 worktree);
6721 if (err)
6722 return err;
6724 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6725 worktree);
6726 if (err)
6727 return err;
6729 if (rebase_in_progress || histedit_in_progress) {
6730 err = got_ref_open(&temp_ref, repo,
6731 got_worktree_get_head_ref_name(worktree), 0);
6732 if (err)
6733 return err;
6734 list_branch(repo, worktree, temp_ref);
6735 got_ref_close(temp_ref);
6739 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6740 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6741 repo);
6742 if (err)
6743 return err;
6745 TAILQ_FOREACH(re, &refs, entry)
6746 list_branch(repo, worktree, re->ref);
6748 got_ref_list_free(&refs);
6750 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6751 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6752 repo);
6753 if (err)
6754 return err;
6756 TAILQ_FOREACH(re, &refs, entry)
6757 list_branch(repo, worktree, re->ref);
6759 got_ref_list_free(&refs);
6761 return NULL;
6764 static const struct got_error *
6765 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6766 const char *branch_name)
6768 const struct got_error *err = NULL;
6769 struct got_reference *ref = NULL;
6770 char *refname, *remote_refname = NULL;
6772 if (strncmp(branch_name, "refs/", 5) == 0)
6773 branch_name += 5;
6774 if (strncmp(branch_name, "heads/", 6) == 0)
6775 branch_name += 6;
6776 else if (strncmp(branch_name, "remotes/", 8) == 0)
6777 branch_name += 8;
6779 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6780 return got_error_from_errno("asprintf");
6782 if (asprintf(&remote_refname, "refs/remotes/%s",
6783 branch_name) == -1) {
6784 err = got_error_from_errno("asprintf");
6785 goto done;
6788 err = got_ref_open(&ref, repo, refname, 0);
6789 if (err) {
6790 const struct got_error *err2;
6791 if (err->code != GOT_ERR_NOT_REF)
6792 goto done;
6794 * Keep 'err' intact such that if neither branch exists
6795 * we report "refs/heads" rather than "refs/remotes" in
6796 * our error message.
6798 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6799 if (err2)
6800 goto done;
6801 err = NULL;
6804 if (worktree &&
6805 strcmp(got_worktree_get_head_ref_name(worktree),
6806 got_ref_get_name(ref)) == 0) {
6807 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6808 "will not delete this work tree's current branch");
6809 goto done;
6812 err = delete_ref(repo, ref);
6813 done:
6814 if (ref)
6815 got_ref_close(ref);
6816 free(refname);
6817 free(remote_refname);
6818 return err;
6821 static const struct got_error *
6822 add_branch(struct got_repository *repo, const char *branch_name,
6823 struct got_object_id *base_commit_id)
6825 const struct got_error *err = NULL;
6826 struct got_reference *ref = NULL;
6827 char *refname = NULL;
6830 * Don't let the user create a branch name with a leading '-'.
6831 * While technically a valid reference name, this case is usually
6832 * an unintended typo.
6834 if (branch_name[0] == '-')
6835 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6837 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6838 branch_name += 11;
6840 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6841 err = got_error_from_errno("asprintf");
6842 goto done;
6845 err = got_ref_open(&ref, repo, refname, 0);
6846 if (err == NULL) {
6847 err = got_error(GOT_ERR_BRANCH_EXISTS);
6848 goto done;
6849 } else if (err->code != GOT_ERR_NOT_REF)
6850 goto done;
6852 err = got_ref_alloc(&ref, refname, base_commit_id);
6853 if (err)
6854 goto done;
6856 err = got_ref_write(ref, repo);
6857 done:
6858 if (ref)
6859 got_ref_close(ref);
6860 free(refname);
6861 return err;
6864 static const struct got_error *
6865 cmd_branch(int argc, char *argv[])
6867 const struct got_error *error = NULL;
6868 struct got_repository *repo = NULL;
6869 struct got_worktree *worktree = NULL;
6870 char *cwd = NULL, *repo_path = NULL;
6871 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6872 const char *delref = NULL, *commit_id_arg = NULL;
6873 struct got_reference *ref = NULL;
6874 struct got_pathlist_head paths;
6875 struct got_object_id *commit_id = NULL;
6876 char *commit_id_str = NULL;
6877 int *pack_fds = NULL;
6879 TAILQ_INIT(&paths);
6881 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6882 switch (ch) {
6883 case 'c':
6884 commit_id_arg = optarg;
6885 break;
6886 case 'd':
6887 delref = optarg;
6888 break;
6889 case 'l':
6890 do_list = 1;
6891 break;
6892 case 'n':
6893 do_update = 0;
6894 break;
6895 case 'r':
6896 repo_path = realpath(optarg, NULL);
6897 if (repo_path == NULL)
6898 return got_error_from_errno2("realpath",
6899 optarg);
6900 got_path_strip_trailing_slashes(repo_path);
6901 break;
6902 case 't':
6903 sort_by_time = 1;
6904 break;
6905 default:
6906 usage_branch();
6907 /* NOTREACHED */
6911 if (do_list && delref)
6912 option_conflict('l', 'd');
6913 if (sort_by_time && !do_list)
6914 errx(1, "-t option requires -l option");
6916 argc -= optind;
6917 argv += optind;
6919 if (!do_list && !delref && argc == 0)
6920 do_show = 1;
6922 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6923 errx(1, "-c option can only be used when creating a branch");
6925 if (do_list || delref) {
6926 if (argc > 0)
6927 usage_branch();
6928 } else if (!do_show && argc != 1)
6929 usage_branch();
6931 #ifndef PROFILE
6932 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6933 "sendfd unveil", NULL) == -1)
6934 err(1, "pledge");
6935 #endif
6936 cwd = getcwd(NULL, 0);
6937 if (cwd == NULL) {
6938 error = got_error_from_errno("getcwd");
6939 goto done;
6942 error = got_repo_pack_fds_open(&pack_fds);
6943 if (error != NULL)
6944 goto done;
6946 if (repo_path == NULL) {
6947 error = got_worktree_open(&worktree, cwd);
6948 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6949 goto done;
6950 else
6951 error = NULL;
6952 if (worktree) {
6953 repo_path =
6954 strdup(got_worktree_get_repo_path(worktree));
6955 if (repo_path == NULL)
6956 error = got_error_from_errno("strdup");
6957 if (error)
6958 goto done;
6959 } else {
6960 repo_path = strdup(cwd);
6961 if (repo_path == NULL) {
6962 error = got_error_from_errno("strdup");
6963 goto done;
6968 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6969 if (error != NULL)
6970 goto done;
6972 #ifndef PROFILE
6973 if (do_list || do_show) {
6974 /* Remove "cpath" promise. */
6975 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6976 NULL) == -1)
6977 err(1, "pledge");
6979 #endif
6981 error = apply_unveil(got_repo_get_path(repo), do_list,
6982 worktree ? got_worktree_get_root_path(worktree) : NULL);
6983 if (error)
6984 goto done;
6986 if (do_show)
6987 error = show_current_branch(repo, worktree);
6988 else if (do_list)
6989 error = list_branches(repo, worktree, sort_by_time);
6990 else if (delref)
6991 error = delete_branch(repo, worktree, delref);
6992 else {
6993 struct got_reflist_head refs;
6994 TAILQ_INIT(&refs);
6995 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6996 NULL);
6997 if (error)
6998 goto done;
6999 if (commit_id_arg == NULL)
7000 commit_id_arg = worktree ?
7001 got_worktree_get_head_ref_name(worktree) :
7002 GOT_REF_HEAD;
7003 error = got_repo_match_object_id(&commit_id, NULL,
7004 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7005 got_ref_list_free(&refs);
7006 if (error)
7007 goto done;
7008 error = add_branch(repo, argv[0], commit_id);
7009 if (error)
7010 goto done;
7011 if (worktree && do_update) {
7012 struct got_update_progress_arg upa;
7013 char *branch_refname = NULL;
7015 error = got_object_id_str(&commit_id_str, commit_id);
7016 if (error)
7017 goto done;
7018 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7019 worktree);
7020 if (error)
7021 goto done;
7022 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7023 == -1) {
7024 error = got_error_from_errno("asprintf");
7025 goto done;
7027 error = got_ref_open(&ref, repo, branch_refname, 0);
7028 free(branch_refname);
7029 if (error)
7030 goto done;
7031 error = switch_head_ref(ref, commit_id, worktree,
7032 repo);
7033 if (error)
7034 goto done;
7035 error = got_worktree_set_base_commit_id(worktree, repo,
7036 commit_id);
7037 if (error)
7038 goto done;
7039 memset(&upa, 0, sizeof(upa));
7040 error = got_worktree_checkout_files(worktree, &paths,
7041 repo, update_progress, &upa, check_cancelled,
7042 NULL);
7043 if (error)
7044 goto done;
7045 if (upa.did_something) {
7046 printf("Updated to %s: %s\n",
7047 got_worktree_get_head_ref_name(worktree),
7048 commit_id_str);
7050 print_update_progress_stats(&upa);
7053 done:
7054 if (ref)
7055 got_ref_close(ref);
7056 if (repo) {
7057 const struct got_error *close_err = got_repo_close(repo);
7058 if (error == NULL)
7059 error = close_err;
7061 if (worktree)
7062 got_worktree_close(worktree);
7063 if (pack_fds) {
7064 const struct got_error *pack_err =
7065 got_repo_pack_fds_close(pack_fds);
7066 if (error == NULL)
7067 error = pack_err;
7069 free(cwd);
7070 free(repo_path);
7071 free(commit_id);
7072 free(commit_id_str);
7073 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7074 return error;
7078 __dead static void
7079 usage_tag(void)
7081 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7082 "[-r repository-path] [-s signer-id] name\n", getprogname());
7083 exit(1);
7086 #if 0
7087 static const struct got_error *
7088 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7090 const struct got_error *err = NULL;
7091 struct got_reflist_entry *re, *se, *new;
7092 struct got_object_id *re_id, *se_id;
7093 struct got_tag_object *re_tag, *se_tag;
7094 time_t re_time, se_time;
7096 STAILQ_FOREACH(re, tags, entry) {
7097 se = STAILQ_FIRST(sorted);
7098 if (se == NULL) {
7099 err = got_reflist_entry_dup(&new, re);
7100 if (err)
7101 return err;
7102 STAILQ_INSERT_HEAD(sorted, new, entry);
7103 continue;
7104 } else {
7105 err = got_ref_resolve(&re_id, repo, re->ref);
7106 if (err)
7107 break;
7108 err = got_object_open_as_tag(&re_tag, repo, re_id);
7109 free(re_id);
7110 if (err)
7111 break;
7112 re_time = got_object_tag_get_tagger_time(re_tag);
7113 got_object_tag_close(re_tag);
7116 while (se) {
7117 err = got_ref_resolve(&se_id, repo, re->ref);
7118 if (err)
7119 break;
7120 err = got_object_open_as_tag(&se_tag, repo, se_id);
7121 free(se_id);
7122 if (err)
7123 break;
7124 se_time = got_object_tag_get_tagger_time(se_tag);
7125 got_object_tag_close(se_tag);
7127 if (se_time > re_time) {
7128 err = got_reflist_entry_dup(&new, re);
7129 if (err)
7130 return err;
7131 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7132 break;
7134 se = STAILQ_NEXT(se, entry);
7135 continue;
7138 done:
7139 return err;
7141 #endif
7143 static const struct got_error *
7144 get_tag_refname(char **refname, const char *tag_name)
7146 const struct got_error *err;
7148 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7149 *refname = strdup(tag_name);
7150 if (*refname == NULL)
7151 return got_error_from_errno("strdup");
7152 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7153 err = got_error_from_errno("asprintf");
7154 *refname = NULL;
7155 return err;
7158 return NULL;
7161 static const struct got_error *
7162 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7163 const char *allowed_signers, const char *revoked_signers, int verbosity)
7165 static const struct got_error *err = NULL;
7166 struct got_reflist_head refs;
7167 struct got_reflist_entry *re;
7168 char *wanted_refname = NULL;
7169 int bad_sigs = 0;
7171 TAILQ_INIT(&refs);
7173 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7174 if (err)
7175 return err;
7177 if (tag_name) {
7178 struct got_reference *ref;
7179 err = get_tag_refname(&wanted_refname, tag_name);
7180 if (err)
7181 goto done;
7182 /* Wanted tag reference should exist. */
7183 err = got_ref_open(&ref, repo, wanted_refname, 0);
7184 if (err)
7185 goto done;
7186 got_ref_close(ref);
7189 TAILQ_FOREACH(re, &refs, entry) {
7190 const char *refname;
7191 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7192 char datebuf[26];
7193 const char *tagger, *ssh_sig = NULL;
7194 char *sig_msg = NULL;
7195 time_t tagger_time;
7196 struct got_object_id *id;
7197 struct got_tag_object *tag;
7198 struct got_commit_object *commit = NULL;
7200 refname = got_ref_get_name(re->ref);
7201 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7202 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7203 continue;
7204 refname += 10;
7205 refstr = got_ref_to_str(re->ref);
7206 if (refstr == NULL) {
7207 err = got_error_from_errno("got_ref_to_str");
7208 break;
7211 err = got_ref_resolve(&id, repo, re->ref);
7212 if (err)
7213 break;
7214 err = got_object_open_as_tag(&tag, repo, id);
7215 if (err) {
7216 if (err->code != GOT_ERR_OBJ_TYPE) {
7217 free(id);
7218 break;
7220 /* "lightweight" tag */
7221 err = got_object_open_as_commit(&commit, repo, id);
7222 if (err) {
7223 free(id);
7224 break;
7226 tagger = got_object_commit_get_committer(commit);
7227 tagger_time =
7228 got_object_commit_get_committer_time(commit);
7229 err = got_object_id_str(&id_str, id);
7230 free(id);
7231 if (err)
7232 break;
7233 } else {
7234 free(id);
7235 tagger = got_object_tag_get_tagger(tag);
7236 tagger_time = got_object_tag_get_tagger_time(tag);
7237 err = got_object_id_str(&id_str,
7238 got_object_tag_get_object_id(tag));
7239 if (err)
7240 break;
7243 if (tag && verify_tags) {
7244 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7245 got_object_tag_get_message(tag));
7246 if (ssh_sig && allowed_signers == NULL) {
7247 err = got_error_msg(
7248 GOT_ERR_VERIFY_TAG_SIGNATURE,
7249 "SSH signature verification requires "
7250 "setting allowed_signers in "
7251 "got.conf(5)");
7252 break;
7256 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7257 free(refstr);
7258 printf("from: %s\n", tagger);
7259 datestr = get_datestr(&tagger_time, datebuf);
7260 if (datestr)
7261 printf("date: %s UTC\n", datestr);
7262 if (commit)
7263 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7264 else {
7265 switch (got_object_tag_get_object_type(tag)) {
7266 case GOT_OBJ_TYPE_BLOB:
7267 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7268 id_str);
7269 break;
7270 case GOT_OBJ_TYPE_TREE:
7271 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7272 id_str);
7273 break;
7274 case GOT_OBJ_TYPE_COMMIT:
7275 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7276 id_str);
7277 break;
7278 case GOT_OBJ_TYPE_TAG:
7279 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7280 id_str);
7281 break;
7282 default:
7283 break;
7286 free(id_str);
7288 if (ssh_sig) {
7289 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7290 allowed_signers, revoked_signers, verbosity);
7291 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7292 bad_sigs = 1;
7293 else if (err)
7294 break;
7295 printf("signature: %s", sig_msg);
7296 free(sig_msg);
7297 sig_msg = NULL;
7300 if (commit) {
7301 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7302 if (err)
7303 break;
7304 got_object_commit_close(commit);
7305 } else {
7306 tagmsg0 = strdup(got_object_tag_get_message(tag));
7307 got_object_tag_close(tag);
7308 if (tagmsg0 == NULL) {
7309 err = got_error_from_errno("strdup");
7310 break;
7314 tagmsg = tagmsg0;
7315 do {
7316 line = strsep(&tagmsg, "\n");
7317 if (line)
7318 printf(" %s\n", line);
7319 } while (line);
7320 free(tagmsg0);
7322 done:
7323 got_ref_list_free(&refs);
7324 free(wanted_refname);
7326 if (err == NULL && bad_sigs)
7327 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7328 return err;
7331 static const struct got_error *
7332 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7333 const char *tag_name, const char *repo_path)
7335 const struct got_error *err = NULL;
7336 char *template = NULL, *initial_content = NULL;
7337 char *editor = NULL;
7338 int initial_content_len;
7339 int fd = -1;
7341 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7342 err = got_error_from_errno("asprintf");
7343 goto done;
7346 initial_content_len = asprintf(&initial_content,
7347 "\n# tagging commit %s as %s\n",
7348 commit_id_str, tag_name);
7349 if (initial_content_len == -1) {
7350 err = got_error_from_errno("asprintf");
7351 goto done;
7354 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7355 if (err)
7356 goto done;
7358 if (write(fd, initial_content, initial_content_len) == -1) {
7359 err = got_error_from_errno2("write", *tagmsg_path);
7360 goto done;
7363 err = get_editor(&editor);
7364 if (err)
7365 goto done;
7366 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7367 initial_content_len, 1);
7368 done:
7369 free(initial_content);
7370 free(template);
7371 free(editor);
7373 if (fd != -1 && close(fd) == -1 && err == NULL)
7374 err = got_error_from_errno2("close", *tagmsg_path);
7376 if (err) {
7377 free(*tagmsg);
7378 *tagmsg = NULL;
7380 return err;
7383 static const struct got_error *
7384 add_tag(struct got_repository *repo, const char *tagger,
7385 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7386 const char *signer_id, int verbosity)
7388 const struct got_error *err = NULL;
7389 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7390 char *label = NULL, *commit_id_str = NULL;
7391 struct got_reference *ref = NULL;
7392 char *refname = NULL, *tagmsg = NULL;
7393 char *tagmsg_path = NULL, *tag_id_str = NULL;
7394 int preserve_tagmsg = 0;
7395 struct got_reflist_head refs;
7397 TAILQ_INIT(&refs);
7400 * Don't let the user create a tag name with a leading '-'.
7401 * While technically a valid reference name, this case is usually
7402 * an unintended typo.
7404 if (tag_name[0] == '-')
7405 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7407 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7408 if (err)
7409 goto done;
7411 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7412 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7413 if (err)
7414 goto done;
7416 err = got_object_id_str(&commit_id_str, commit_id);
7417 if (err)
7418 goto done;
7420 err = get_tag_refname(&refname, tag_name);
7421 if (err)
7422 goto done;
7423 if (strncmp("refs/tags/", tag_name, 10) == 0)
7424 tag_name += 10;
7426 err = got_ref_open(&ref, repo, refname, 0);
7427 if (err == NULL) {
7428 err = got_error(GOT_ERR_TAG_EXISTS);
7429 goto done;
7430 } else if (err->code != GOT_ERR_NOT_REF)
7431 goto done;
7433 if (tagmsg_arg == NULL) {
7434 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7435 tag_name, got_repo_get_path(repo));
7436 if (err) {
7437 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7438 tagmsg_path != NULL)
7439 preserve_tagmsg = 1;
7440 goto done;
7442 /* Editor is done; we can now apply unveil(2) */
7443 err = got_sigs_apply_unveil();
7444 if (err)
7445 goto done;
7446 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7447 if (err)
7448 goto done;
7451 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7452 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7453 verbosity);
7454 if (err) {
7455 if (tagmsg_path)
7456 preserve_tagmsg = 1;
7457 goto done;
7460 err = got_ref_alloc(&ref, refname, tag_id);
7461 if (err) {
7462 if (tagmsg_path)
7463 preserve_tagmsg = 1;
7464 goto done;
7467 err = got_ref_write(ref, repo);
7468 if (err) {
7469 if (tagmsg_path)
7470 preserve_tagmsg = 1;
7471 goto done;
7474 err = got_object_id_str(&tag_id_str, tag_id);
7475 if (err) {
7476 if (tagmsg_path)
7477 preserve_tagmsg = 1;
7478 goto done;
7480 printf("Created tag %s\n", tag_id_str);
7481 done:
7482 if (preserve_tagmsg) {
7483 fprintf(stderr, "%s: tag message preserved in %s\n",
7484 getprogname(), tagmsg_path);
7485 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7486 err = got_error_from_errno2("unlink", tagmsg_path);
7487 free(tag_id_str);
7488 if (ref)
7489 got_ref_close(ref);
7490 free(commit_id);
7491 free(commit_id_str);
7492 free(refname);
7493 free(tagmsg);
7494 free(tagmsg_path);
7495 got_ref_list_free(&refs);
7496 return err;
7499 static const struct got_error *
7500 cmd_tag(int argc, char *argv[])
7502 const struct got_error *error = NULL;
7503 struct got_repository *repo = NULL;
7504 struct got_worktree *worktree = NULL;
7505 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7506 char *gitconfig_path = NULL, *tagger = NULL;
7507 char *allowed_signers = NULL, *revoked_signers = NULL;
7508 char *signer_id = NULL;
7509 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7510 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7511 int *pack_fds = NULL;
7513 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7514 switch (ch) {
7515 case 'c':
7516 commit_id_arg = optarg;
7517 break;
7518 case 'l':
7519 do_list = 1;
7520 break;
7521 case 'm':
7522 tagmsg = optarg;
7523 break;
7524 case 'r':
7525 repo_path = realpath(optarg, NULL);
7526 if (repo_path == NULL) {
7527 error = got_error_from_errno2("realpath",
7528 optarg);
7529 goto done;
7531 got_path_strip_trailing_slashes(repo_path);
7532 break;
7533 case 's':
7534 signer_id = strdup(optarg);
7535 if (signer_id == NULL) {
7536 error = got_error_from_errno("strdup");
7537 goto done;
7539 break;
7540 case 'V':
7541 verify_tags = 1;
7542 break;
7543 case 'v':
7544 if (verbosity < 0)
7545 verbosity = 0;
7546 else if (verbosity < 3)
7547 verbosity++;
7548 break;
7549 default:
7550 usage_tag();
7551 /* NOTREACHED */
7555 argc -= optind;
7556 argv += optind;
7558 if (do_list || verify_tags) {
7559 if (commit_id_arg != NULL)
7560 errx(1,
7561 "-c option can only be used when creating a tag");
7562 if (tagmsg) {
7563 if (do_list)
7564 option_conflict('l', 'm');
7565 else
7566 option_conflict('V', 'm');
7568 if (signer_id) {
7569 if (do_list)
7570 option_conflict('l', 's');
7571 else
7572 option_conflict('V', 's');
7574 if (argc > 1)
7575 usage_tag();
7576 } else if (argc != 1)
7577 usage_tag();
7579 if (argc == 1)
7580 tag_name = argv[0];
7582 #ifndef PROFILE
7583 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7584 "sendfd unveil", NULL) == -1)
7585 err(1, "pledge");
7586 #endif
7587 cwd = getcwd(NULL, 0);
7588 if (cwd == NULL) {
7589 error = got_error_from_errno("getcwd");
7590 goto done;
7593 error = got_repo_pack_fds_open(&pack_fds);
7594 if (error != NULL)
7595 goto done;
7597 if (repo_path == NULL) {
7598 error = got_worktree_open(&worktree, cwd);
7599 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7600 goto done;
7601 else
7602 error = NULL;
7603 if (worktree) {
7604 repo_path =
7605 strdup(got_worktree_get_repo_path(worktree));
7606 if (repo_path == NULL)
7607 error = got_error_from_errno("strdup");
7608 if (error)
7609 goto done;
7610 } else {
7611 repo_path = strdup(cwd);
7612 if (repo_path == NULL) {
7613 error = got_error_from_errno("strdup");
7614 goto done;
7619 if (do_list || verify_tags) {
7620 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7621 if (error != NULL)
7622 goto done;
7623 error = get_allowed_signers(&allowed_signers, repo, worktree);
7624 if (error)
7625 goto done;
7626 error = get_revoked_signers(&revoked_signers, repo, worktree);
7627 if (error)
7628 goto done;
7629 if (worktree) {
7630 /* Release work tree lock. */
7631 got_worktree_close(worktree);
7632 worktree = NULL;
7636 * Remove "cpath" promise unless needed for signature tmpfile
7637 * creation.
7639 if (verify_tags)
7640 got_sigs_apply_unveil();
7641 else {
7642 #ifndef PROFILE
7643 if (pledge("stdio rpath wpath flock proc exec sendfd "
7644 "unveil", NULL) == -1)
7645 err(1, "pledge");
7646 #endif
7648 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7649 if (error)
7650 goto done;
7651 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7652 revoked_signers, verbosity);
7653 } else {
7654 error = get_gitconfig_path(&gitconfig_path);
7655 if (error)
7656 goto done;
7657 error = got_repo_open(&repo, repo_path, gitconfig_path,
7658 pack_fds);
7659 if (error != NULL)
7660 goto done;
7662 error = get_author(&tagger, repo, worktree);
7663 if (error)
7664 goto done;
7665 if (signer_id == NULL) {
7666 error = get_signer_id(&signer_id, repo, worktree);
7667 if (error)
7668 goto done;
7671 if (tagmsg) {
7672 if (signer_id) {
7673 error = got_sigs_apply_unveil();
7674 if (error)
7675 goto done;
7677 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7678 if (error)
7679 goto done;
7682 if (commit_id_arg == NULL) {
7683 struct got_reference *head_ref;
7684 struct got_object_id *commit_id;
7685 error = got_ref_open(&head_ref, repo,
7686 worktree ? got_worktree_get_head_ref_name(worktree)
7687 : GOT_REF_HEAD, 0);
7688 if (error)
7689 goto done;
7690 error = got_ref_resolve(&commit_id, repo, head_ref);
7691 got_ref_close(head_ref);
7692 if (error)
7693 goto done;
7694 error = got_object_id_str(&commit_id_str, commit_id);
7695 free(commit_id);
7696 if (error)
7697 goto done;
7700 if (worktree) {
7701 /* Release work tree lock. */
7702 got_worktree_close(worktree);
7703 worktree = NULL;
7706 error = add_tag(repo, tagger, tag_name,
7707 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7708 signer_id, verbosity);
7710 done:
7711 if (repo) {
7712 const struct got_error *close_err = got_repo_close(repo);
7713 if (error == NULL)
7714 error = close_err;
7716 if (worktree)
7717 got_worktree_close(worktree);
7718 if (pack_fds) {
7719 const struct got_error *pack_err =
7720 got_repo_pack_fds_close(pack_fds);
7721 if (error == NULL)
7722 error = pack_err;
7724 free(cwd);
7725 free(repo_path);
7726 free(gitconfig_path);
7727 free(commit_id_str);
7728 free(tagger);
7729 free(allowed_signers);
7730 free(revoked_signers);
7731 free(signer_id);
7732 return error;
7735 __dead static void
7736 usage_add(void)
7738 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7739 exit(1);
7742 static const struct got_error *
7743 add_progress(void *arg, unsigned char status, const char *path)
7745 while (path[0] == '/')
7746 path++;
7747 printf("%c %s\n", status, path);
7748 return NULL;
7751 static const struct got_error *
7752 cmd_add(int argc, char *argv[])
7754 const struct got_error *error = NULL;
7755 struct got_repository *repo = NULL;
7756 struct got_worktree *worktree = NULL;
7757 char *cwd = NULL;
7758 struct got_pathlist_head paths;
7759 struct got_pathlist_entry *pe;
7760 int ch, can_recurse = 0, no_ignores = 0;
7761 int *pack_fds = NULL;
7763 TAILQ_INIT(&paths);
7765 while ((ch = getopt(argc, argv, "IR")) != -1) {
7766 switch (ch) {
7767 case 'I':
7768 no_ignores = 1;
7769 break;
7770 case 'R':
7771 can_recurse = 1;
7772 break;
7773 default:
7774 usage_add();
7775 /* NOTREACHED */
7779 argc -= optind;
7780 argv += optind;
7782 #ifndef PROFILE
7783 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7784 NULL) == -1)
7785 err(1, "pledge");
7786 #endif
7787 if (argc < 1)
7788 usage_add();
7790 cwd = getcwd(NULL, 0);
7791 if (cwd == NULL) {
7792 error = got_error_from_errno("getcwd");
7793 goto done;
7796 error = got_repo_pack_fds_open(&pack_fds);
7797 if (error != NULL)
7798 goto done;
7800 error = got_worktree_open(&worktree, cwd);
7801 if (error) {
7802 if (error->code == GOT_ERR_NOT_WORKTREE)
7803 error = wrap_not_worktree_error(error, "add", cwd);
7804 goto done;
7807 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7808 NULL, pack_fds);
7809 if (error != NULL)
7810 goto done;
7812 error = apply_unveil(got_repo_get_path(repo), 1,
7813 got_worktree_get_root_path(worktree));
7814 if (error)
7815 goto done;
7817 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7818 if (error)
7819 goto done;
7821 if (!can_recurse) {
7822 char *ondisk_path;
7823 struct stat sb;
7824 TAILQ_FOREACH(pe, &paths, entry) {
7825 if (asprintf(&ondisk_path, "%s/%s",
7826 got_worktree_get_root_path(worktree),
7827 pe->path) == -1) {
7828 error = got_error_from_errno("asprintf");
7829 goto done;
7831 if (lstat(ondisk_path, &sb) == -1) {
7832 if (errno == ENOENT) {
7833 free(ondisk_path);
7834 continue;
7836 error = got_error_from_errno2("lstat",
7837 ondisk_path);
7838 free(ondisk_path);
7839 goto done;
7841 free(ondisk_path);
7842 if (S_ISDIR(sb.st_mode)) {
7843 error = got_error_msg(GOT_ERR_BAD_PATH,
7844 "adding directories requires -R option");
7845 goto done;
7850 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7851 NULL, repo, no_ignores);
7852 done:
7853 if (repo) {
7854 const struct got_error *close_err = got_repo_close(repo);
7855 if (error == NULL)
7856 error = close_err;
7858 if (worktree)
7859 got_worktree_close(worktree);
7860 if (pack_fds) {
7861 const struct got_error *pack_err =
7862 got_repo_pack_fds_close(pack_fds);
7863 if (error == NULL)
7864 error = pack_err;
7866 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7867 free(cwd);
7868 return error;
7871 __dead static void
7872 usage_remove(void)
7874 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7875 getprogname());
7876 exit(1);
7879 static const struct got_error *
7880 print_remove_status(void *arg, unsigned char status,
7881 unsigned char staged_status, const char *path)
7883 while (path[0] == '/')
7884 path++;
7885 if (status == GOT_STATUS_NONEXISTENT)
7886 return NULL;
7887 if (status == staged_status && (status == GOT_STATUS_DELETE))
7888 status = GOT_STATUS_NO_CHANGE;
7889 printf("%c%c %s\n", status, staged_status, path);
7890 return NULL;
7893 static const struct got_error *
7894 cmd_remove(int argc, char *argv[])
7896 const struct got_error *error = NULL;
7897 struct got_worktree *worktree = NULL;
7898 struct got_repository *repo = NULL;
7899 const char *status_codes = NULL;
7900 char *cwd = NULL;
7901 struct got_pathlist_head paths;
7902 struct got_pathlist_entry *pe;
7903 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7904 int ignore_missing_paths = 0;
7905 int *pack_fds = NULL;
7907 TAILQ_INIT(&paths);
7909 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7910 switch (ch) {
7911 case 'f':
7912 delete_local_mods = 1;
7913 ignore_missing_paths = 1;
7914 break;
7915 case 'k':
7916 keep_on_disk = 1;
7917 break;
7918 case 'R':
7919 can_recurse = 1;
7920 break;
7921 case 's':
7922 for (i = 0; i < strlen(optarg); i++) {
7923 switch (optarg[i]) {
7924 case GOT_STATUS_MODIFY:
7925 delete_local_mods = 1;
7926 break;
7927 case GOT_STATUS_MISSING:
7928 ignore_missing_paths = 1;
7929 break;
7930 default:
7931 errx(1, "invalid status code '%c'",
7932 optarg[i]);
7935 status_codes = optarg;
7936 break;
7937 default:
7938 usage_remove();
7939 /* NOTREACHED */
7943 argc -= optind;
7944 argv += optind;
7946 #ifndef PROFILE
7947 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7948 NULL) == -1)
7949 err(1, "pledge");
7950 #endif
7951 if (argc < 1)
7952 usage_remove();
7954 cwd = getcwd(NULL, 0);
7955 if (cwd == NULL) {
7956 error = got_error_from_errno("getcwd");
7957 goto done;
7960 error = got_repo_pack_fds_open(&pack_fds);
7961 if (error != NULL)
7962 goto done;
7964 error = got_worktree_open(&worktree, cwd);
7965 if (error) {
7966 if (error->code == GOT_ERR_NOT_WORKTREE)
7967 error = wrap_not_worktree_error(error, "remove", cwd);
7968 goto done;
7971 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7972 NULL, pack_fds);
7973 if (error)
7974 goto done;
7976 error = apply_unveil(got_repo_get_path(repo), 1,
7977 got_worktree_get_root_path(worktree));
7978 if (error)
7979 goto done;
7981 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7982 if (error)
7983 goto done;
7985 if (!can_recurse) {
7986 char *ondisk_path;
7987 struct stat sb;
7988 TAILQ_FOREACH(pe, &paths, entry) {
7989 if (asprintf(&ondisk_path, "%s/%s",
7990 got_worktree_get_root_path(worktree),
7991 pe->path) == -1) {
7992 error = got_error_from_errno("asprintf");
7993 goto done;
7995 if (lstat(ondisk_path, &sb) == -1) {
7996 if (errno == ENOENT) {
7997 free(ondisk_path);
7998 continue;
8000 error = got_error_from_errno2("lstat",
8001 ondisk_path);
8002 free(ondisk_path);
8003 goto done;
8005 free(ondisk_path);
8006 if (S_ISDIR(sb.st_mode)) {
8007 error = got_error_msg(GOT_ERR_BAD_PATH,
8008 "removing directories requires -R option");
8009 goto done;
8014 error = got_worktree_schedule_delete(worktree, &paths,
8015 delete_local_mods, status_codes, print_remove_status, NULL,
8016 repo, keep_on_disk, ignore_missing_paths);
8017 done:
8018 if (repo) {
8019 const struct got_error *close_err = got_repo_close(repo);
8020 if (error == NULL)
8021 error = close_err;
8023 if (worktree)
8024 got_worktree_close(worktree);
8025 if (pack_fds) {
8026 const struct got_error *pack_err =
8027 got_repo_pack_fds_close(pack_fds);
8028 if (error == NULL)
8029 error = pack_err;
8031 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8032 free(cwd);
8033 return error;
8036 __dead static void
8037 usage_patch(void)
8039 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8040 "[patchfile]\n", getprogname());
8041 exit(1);
8044 static const struct got_error *
8045 patch_from_stdin(int *patchfd)
8047 const struct got_error *err = NULL;
8048 ssize_t r;
8049 char buf[BUFSIZ];
8050 sig_t sighup, sigint, sigquit;
8052 *patchfd = got_opentempfd();
8053 if (*patchfd == -1)
8054 return got_error_from_errno("got_opentempfd");
8056 sighup = signal(SIGHUP, SIG_DFL);
8057 sigint = signal(SIGINT, SIG_DFL);
8058 sigquit = signal(SIGQUIT, SIG_DFL);
8060 for (;;) {
8061 r = read(0, buf, sizeof(buf));
8062 if (r == -1) {
8063 err = got_error_from_errno("read");
8064 break;
8066 if (r == 0)
8067 break;
8068 if (write(*patchfd, buf, r) == -1) {
8069 err = got_error_from_errno("write");
8070 break;
8074 signal(SIGHUP, sighup);
8075 signal(SIGINT, sigint);
8076 signal(SIGQUIT, sigquit);
8078 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8079 err = got_error_from_errno("lseek");
8081 if (err != NULL) {
8082 close(*patchfd);
8083 *patchfd = -1;
8086 return err;
8089 static const struct got_error *
8090 patch_progress(void *arg, const char *old, const char *new,
8091 unsigned char status, const struct got_error *error, int old_from,
8092 int old_lines, int new_from, int new_lines, int offset,
8093 int ws_mangled, const struct got_error *hunk_err)
8095 const char *path = new == NULL ? old : new;
8097 while (*path == '/')
8098 path++;
8100 if (status != 0)
8101 printf("%c %s\n", status, path);
8103 if (error != NULL)
8104 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8106 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8107 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8108 old_lines, new_from, new_lines);
8109 if (hunk_err != NULL)
8110 printf("%s\n", hunk_err->msg);
8111 else if (offset != 0)
8112 printf("applied with offset %d\n", offset);
8113 else
8114 printf("hunk contains mangled whitespace\n");
8117 return NULL;
8120 static const struct got_error *
8121 cmd_patch(int argc, char *argv[])
8123 const struct got_error *error = NULL, *close_error = NULL;
8124 struct got_worktree *worktree = NULL;
8125 struct got_repository *repo = NULL;
8126 struct got_reflist_head refs;
8127 struct got_object_id *commit_id = NULL;
8128 const char *commit_id_str = NULL;
8129 struct stat sb;
8130 const char *errstr;
8131 char *cwd = NULL;
8132 int ch, nop = 0, strip = -1, reverse = 0;
8133 int patchfd;
8134 int *pack_fds = NULL;
8136 TAILQ_INIT(&refs);
8138 #ifndef PROFILE
8139 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8140 "unveil", NULL) == -1)
8141 err(1, "pledge");
8142 #endif
8144 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8145 switch (ch) {
8146 case 'c':
8147 commit_id_str = optarg;
8148 break;
8149 case 'n':
8150 nop = 1;
8151 break;
8152 case 'p':
8153 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8154 if (errstr != NULL)
8155 errx(1, "pathname strip count is %s: %s",
8156 errstr, optarg);
8157 break;
8158 case 'R':
8159 reverse = 1;
8160 break;
8161 default:
8162 usage_patch();
8163 /* NOTREACHED */
8167 argc -= optind;
8168 argv += optind;
8170 if (argc == 0) {
8171 error = patch_from_stdin(&patchfd);
8172 if (error)
8173 return error;
8174 } else if (argc == 1) {
8175 patchfd = open(argv[0], O_RDONLY);
8176 if (patchfd == -1) {
8177 error = got_error_from_errno2("open", argv[0]);
8178 return error;
8180 if (fstat(patchfd, &sb) == -1) {
8181 error = got_error_from_errno2("fstat", argv[0]);
8182 goto done;
8184 if (!S_ISREG(sb.st_mode)) {
8185 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8186 goto done;
8188 } else
8189 usage_patch();
8191 if ((cwd = getcwd(NULL, 0)) == NULL) {
8192 error = got_error_from_errno("getcwd");
8193 goto done;
8196 error = got_repo_pack_fds_open(&pack_fds);
8197 if (error != NULL)
8198 goto done;
8200 error = got_worktree_open(&worktree, cwd);
8201 if (error != NULL)
8202 goto done;
8204 const char *repo_path = got_worktree_get_repo_path(worktree);
8205 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8206 if (error != NULL)
8207 goto done;
8209 error = apply_unveil(got_repo_get_path(repo), 0,
8210 got_worktree_get_root_path(worktree));
8211 if (error != NULL)
8212 goto done;
8214 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8215 if (error)
8216 goto done;
8218 if (commit_id_str != NULL) {
8219 error = got_repo_match_object_id(&commit_id, NULL,
8220 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8221 if (error)
8222 goto done;
8225 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8226 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8228 done:
8229 got_ref_list_free(&refs);
8230 free(commit_id);
8231 if (repo) {
8232 close_error = got_repo_close(repo);
8233 if (error == NULL)
8234 error = close_error;
8236 if (worktree != NULL) {
8237 close_error = got_worktree_close(worktree);
8238 if (error == NULL)
8239 error = close_error;
8241 if (pack_fds) {
8242 const struct got_error *pack_err =
8243 got_repo_pack_fds_close(pack_fds);
8244 if (error == NULL)
8245 error = pack_err;
8247 free(cwd);
8248 return error;
8251 __dead static void
8252 usage_revert(void)
8254 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8255 getprogname());
8256 exit(1);
8259 static const struct got_error *
8260 revert_progress(void *arg, unsigned char status, const char *path)
8262 if (status == GOT_STATUS_UNVERSIONED)
8263 return NULL;
8265 while (path[0] == '/')
8266 path++;
8267 printf("%c %s\n", status, path);
8268 return NULL;
8271 struct choose_patch_arg {
8272 FILE *patch_script_file;
8273 const char *action;
8276 static const struct got_error *
8277 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8278 int nchanges, const char *action)
8280 const struct got_error *err;
8281 char *line = NULL;
8282 size_t linesize = 0;
8283 ssize_t linelen;
8285 switch (status) {
8286 case GOT_STATUS_ADD:
8287 printf("A %s\n%s this addition? [y/n] ", path, action);
8288 break;
8289 case GOT_STATUS_DELETE:
8290 printf("D %s\n%s this deletion? [y/n] ", path, action);
8291 break;
8292 case GOT_STATUS_MODIFY:
8293 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8294 return got_error_from_errno("fseek");
8295 printf(GOT_COMMIT_SEP_STR);
8296 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8297 printf("%s", line);
8298 if (linelen == -1 && ferror(patch_file)) {
8299 err = got_error_from_errno("getline");
8300 free(line);
8301 return err;
8303 free(line);
8304 printf(GOT_COMMIT_SEP_STR);
8305 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8306 path, n, nchanges, action);
8307 break;
8308 default:
8309 return got_error_path(path, GOT_ERR_FILE_STATUS);
8312 fflush(stdout);
8313 return NULL;
8316 static const struct got_error *
8317 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8318 FILE *patch_file, int n, int nchanges)
8320 const struct got_error *err = NULL;
8321 char *line = NULL;
8322 size_t linesize = 0;
8323 ssize_t linelen;
8324 int resp = ' ';
8325 struct choose_patch_arg *a = arg;
8327 *choice = GOT_PATCH_CHOICE_NONE;
8329 if (a->patch_script_file) {
8330 char *nl;
8331 err = show_change(status, path, patch_file, n, nchanges,
8332 a->action);
8333 if (err)
8334 return err;
8335 linelen = getline(&line, &linesize, a->patch_script_file);
8336 if (linelen == -1) {
8337 if (ferror(a->patch_script_file))
8338 return got_error_from_errno("getline");
8339 return NULL;
8341 nl = strchr(line, '\n');
8342 if (nl)
8343 *nl = '\0';
8344 if (strcmp(line, "y") == 0) {
8345 *choice = GOT_PATCH_CHOICE_YES;
8346 printf("y\n");
8347 } else if (strcmp(line, "n") == 0) {
8348 *choice = GOT_PATCH_CHOICE_NO;
8349 printf("n\n");
8350 } else if (strcmp(line, "q") == 0 &&
8351 status == GOT_STATUS_MODIFY) {
8352 *choice = GOT_PATCH_CHOICE_QUIT;
8353 printf("q\n");
8354 } else
8355 printf("invalid response '%s'\n", line);
8356 free(line);
8357 return NULL;
8360 while (resp != 'y' && resp != 'n' && resp != 'q') {
8361 err = show_change(status, path, patch_file, n, nchanges,
8362 a->action);
8363 if (err)
8364 return err;
8365 resp = getchar();
8366 if (resp == '\n')
8367 resp = getchar();
8368 if (status == GOT_STATUS_MODIFY) {
8369 if (resp != 'y' && resp != 'n' && resp != 'q') {
8370 printf("invalid response '%c'\n", resp);
8371 resp = ' ';
8373 } else if (resp != 'y' && resp != 'n') {
8374 printf("invalid response '%c'\n", resp);
8375 resp = ' ';
8379 if (resp == 'y')
8380 *choice = GOT_PATCH_CHOICE_YES;
8381 else if (resp == 'n')
8382 *choice = GOT_PATCH_CHOICE_NO;
8383 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8384 *choice = GOT_PATCH_CHOICE_QUIT;
8386 return NULL;
8389 static const struct got_error *
8390 cmd_revert(int argc, char *argv[])
8392 const struct got_error *error = NULL;
8393 struct got_worktree *worktree = NULL;
8394 struct got_repository *repo = NULL;
8395 char *cwd = NULL, *path = NULL;
8396 struct got_pathlist_head paths;
8397 struct got_pathlist_entry *pe;
8398 int ch, can_recurse = 0, pflag = 0;
8399 FILE *patch_script_file = NULL;
8400 const char *patch_script_path = NULL;
8401 struct choose_patch_arg cpa;
8402 int *pack_fds = NULL;
8404 TAILQ_INIT(&paths);
8406 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8407 switch (ch) {
8408 case 'F':
8409 patch_script_path = optarg;
8410 break;
8411 case 'p':
8412 pflag = 1;
8413 break;
8414 case 'R':
8415 can_recurse = 1;
8416 break;
8417 default:
8418 usage_revert();
8419 /* NOTREACHED */
8423 argc -= optind;
8424 argv += optind;
8426 #ifndef PROFILE
8427 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8428 "unveil", NULL) == -1)
8429 err(1, "pledge");
8430 #endif
8431 if (argc < 1)
8432 usage_revert();
8433 if (patch_script_path && !pflag)
8434 errx(1, "-F option can only be used together with -p option");
8436 cwd = getcwd(NULL, 0);
8437 if (cwd == NULL) {
8438 error = got_error_from_errno("getcwd");
8439 goto done;
8442 error = got_repo_pack_fds_open(&pack_fds);
8443 if (error != NULL)
8444 goto done;
8446 error = got_worktree_open(&worktree, cwd);
8447 if (error) {
8448 if (error->code == GOT_ERR_NOT_WORKTREE)
8449 error = wrap_not_worktree_error(error, "revert", cwd);
8450 goto done;
8453 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8454 NULL, pack_fds);
8455 if (error != NULL)
8456 goto done;
8458 if (patch_script_path) {
8459 patch_script_file = fopen(patch_script_path, "re");
8460 if (patch_script_file == NULL) {
8461 error = got_error_from_errno2("fopen",
8462 patch_script_path);
8463 goto done;
8466 error = apply_unveil(got_repo_get_path(repo), 1,
8467 got_worktree_get_root_path(worktree));
8468 if (error)
8469 goto done;
8471 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8472 if (error)
8473 goto done;
8475 if (!can_recurse) {
8476 char *ondisk_path;
8477 struct stat sb;
8478 TAILQ_FOREACH(pe, &paths, entry) {
8479 if (asprintf(&ondisk_path, "%s/%s",
8480 got_worktree_get_root_path(worktree),
8481 pe->path) == -1) {
8482 error = got_error_from_errno("asprintf");
8483 goto done;
8485 if (lstat(ondisk_path, &sb) == -1) {
8486 if (errno == ENOENT) {
8487 free(ondisk_path);
8488 continue;
8490 error = got_error_from_errno2("lstat",
8491 ondisk_path);
8492 free(ondisk_path);
8493 goto done;
8495 free(ondisk_path);
8496 if (S_ISDIR(sb.st_mode)) {
8497 error = got_error_msg(GOT_ERR_BAD_PATH,
8498 "reverting directories requires -R option");
8499 goto done;
8504 cpa.patch_script_file = patch_script_file;
8505 cpa.action = "revert";
8506 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8507 pflag ? choose_patch : NULL, &cpa, repo);
8508 done:
8509 if (patch_script_file && fclose(patch_script_file) == EOF &&
8510 error == NULL)
8511 error = got_error_from_errno2("fclose", patch_script_path);
8512 if (repo) {
8513 const struct got_error *close_err = got_repo_close(repo);
8514 if (error == NULL)
8515 error = close_err;
8517 if (worktree)
8518 got_worktree_close(worktree);
8519 if (pack_fds) {
8520 const struct got_error *pack_err =
8521 got_repo_pack_fds_close(pack_fds);
8522 if (error == NULL)
8523 error = pack_err;
8525 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8526 free(path);
8527 free(cwd);
8528 return error;
8531 __dead static void
8532 usage_commit(void)
8534 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8535 "[-m message] [path ...]\n", getprogname());
8536 exit(1);
8539 struct collect_commit_logmsg_arg {
8540 const char *cmdline_log;
8541 const char *prepared_log;
8542 int non_interactive;
8543 const char *editor;
8544 const char *worktree_path;
8545 const char *branch_name;
8546 const char *repo_path;
8547 char *logmsg_path;
8551 static const struct got_error *
8552 read_prepared_logmsg(char **logmsg, const char *path)
8554 const struct got_error *err = NULL;
8555 FILE *f = NULL;
8556 struct stat sb;
8557 size_t r;
8559 *logmsg = NULL;
8560 memset(&sb, 0, sizeof(sb));
8562 f = fopen(path, "re");
8563 if (f == NULL)
8564 return got_error_from_errno2("fopen", path);
8566 if (fstat(fileno(f), &sb) == -1) {
8567 err = got_error_from_errno2("fstat", path);
8568 goto done;
8570 if (sb.st_size == 0) {
8571 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8572 goto done;
8575 *logmsg = malloc(sb.st_size + 1);
8576 if (*logmsg == NULL) {
8577 err = got_error_from_errno("malloc");
8578 goto done;
8581 r = fread(*logmsg, 1, sb.st_size, f);
8582 if (r != sb.st_size) {
8583 if (ferror(f))
8584 err = got_error_from_errno2("fread", path);
8585 else
8586 err = got_error(GOT_ERR_IO);
8587 goto done;
8589 (*logmsg)[sb.st_size] = '\0';
8590 done:
8591 if (fclose(f) == EOF && err == NULL)
8592 err = got_error_from_errno2("fclose", path);
8593 if (err) {
8594 free(*logmsg);
8595 *logmsg = NULL;
8597 return err;
8600 static const struct got_error *
8601 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8602 const char *diff_path, char **logmsg, void *arg)
8604 char *initial_content = NULL;
8605 struct got_pathlist_entry *pe;
8606 const struct got_error *err = NULL;
8607 char *template = NULL;
8608 struct collect_commit_logmsg_arg *a = arg;
8609 int initial_content_len;
8610 int fd = -1;
8611 size_t len;
8613 /* if a message was specified on the command line, just use it */
8614 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8615 len = strlen(a->cmdline_log) + 1;
8616 *logmsg = malloc(len + 1);
8617 if (*logmsg == NULL)
8618 return got_error_from_errno("malloc");
8619 strlcpy(*logmsg, a->cmdline_log, len);
8620 return NULL;
8621 } else if (a->prepared_log != NULL && a->non_interactive)
8622 return read_prepared_logmsg(logmsg, a->prepared_log);
8624 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8625 return got_error_from_errno("asprintf");
8627 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8628 if (err)
8629 goto done;
8631 if (a->prepared_log) {
8632 char *msg;
8633 err = read_prepared_logmsg(&msg, a->prepared_log);
8634 if (err)
8635 goto done;
8636 if (write(fd, msg, strlen(msg)) == -1) {
8637 err = got_error_from_errno2("write", a->logmsg_path);
8638 free(msg);
8639 goto done;
8641 free(msg);
8644 initial_content_len = asprintf(&initial_content,
8645 "\n# changes to be committed on branch %s:\n",
8646 a->branch_name);
8647 if (initial_content_len == -1) {
8648 err = got_error_from_errno("asprintf");
8649 goto done;
8652 if (write(fd, initial_content, initial_content_len) == -1) {
8653 err = got_error_from_errno2("write", a->logmsg_path);
8654 goto done;
8657 TAILQ_FOREACH(pe, commitable_paths, entry) {
8658 struct got_commitable *ct = pe->data;
8659 dprintf(fd, "# %c %s\n",
8660 got_commitable_get_status(ct),
8661 got_commitable_get_path(ct));
8664 if (diff_path) {
8665 dprintf(fd, "# detailed changes can be viewed in %s\n",
8666 diff_path);
8669 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8670 initial_content_len, a->prepared_log ? 0 : 1);
8671 done:
8672 free(initial_content);
8673 free(template);
8675 if (fd != -1 && close(fd) == -1 && err == NULL)
8676 err = got_error_from_errno2("close", a->logmsg_path);
8678 /* Editor is done; we can now apply unveil(2) */
8679 if (err == NULL)
8680 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8681 if (err) {
8682 free(*logmsg);
8683 *logmsg = NULL;
8685 return err;
8688 static const struct got_error *
8689 cmd_commit(int argc, char *argv[])
8691 const struct got_error *error = NULL;
8692 struct got_worktree *worktree = NULL;
8693 struct got_repository *repo = NULL;
8694 char *cwd = NULL, *id_str = NULL;
8695 struct got_object_id *id = NULL;
8696 const char *logmsg = NULL;
8697 char *prepared_logmsg = NULL;
8698 struct collect_commit_logmsg_arg cl_arg;
8699 const char *author = NULL;
8700 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8701 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8702 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8703 int show_diff = 1;
8704 struct got_pathlist_head paths;
8705 int *pack_fds = NULL;
8707 TAILQ_INIT(&paths);
8708 cl_arg.logmsg_path = NULL;
8710 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8711 switch (ch) {
8712 case 'A':
8713 author = optarg;
8714 error = valid_author(author);
8715 if (error)
8716 return error;
8717 break;
8718 case 'F':
8719 if (logmsg != NULL)
8720 option_conflict('F', 'm');
8721 prepared_logmsg = realpath(optarg, NULL);
8722 if (prepared_logmsg == NULL)
8723 return got_error_from_errno2("realpath",
8724 optarg);
8725 break;
8726 case 'm':
8727 if (prepared_logmsg)
8728 option_conflict('m', 'F');
8729 logmsg = optarg;
8730 break;
8731 case 'N':
8732 non_interactive = 1;
8733 break;
8734 case 'n':
8735 show_diff = 0;
8736 break;
8737 case 'S':
8738 allow_bad_symlinks = 1;
8739 break;
8740 default:
8741 usage_commit();
8742 /* NOTREACHED */
8746 argc -= optind;
8747 argv += optind;
8749 #ifndef PROFILE
8750 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8751 "unveil", NULL) == -1)
8752 err(1, "pledge");
8753 #endif
8754 cwd = getcwd(NULL, 0);
8755 if (cwd == NULL) {
8756 error = got_error_from_errno("getcwd");
8757 goto done;
8760 error = got_repo_pack_fds_open(&pack_fds);
8761 if (error != NULL)
8762 goto done;
8764 error = got_worktree_open(&worktree, cwd);
8765 if (error) {
8766 if (error->code == GOT_ERR_NOT_WORKTREE)
8767 error = wrap_not_worktree_error(error, "commit", cwd);
8768 goto done;
8771 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8772 if (error)
8773 goto done;
8774 if (rebase_in_progress) {
8775 error = got_error(GOT_ERR_REBASING);
8776 goto done;
8779 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8780 worktree);
8781 if (error)
8782 goto done;
8784 error = get_gitconfig_path(&gitconfig_path);
8785 if (error)
8786 goto done;
8787 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8788 gitconfig_path, pack_fds);
8789 if (error != NULL)
8790 goto done;
8792 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8793 if (error)
8794 goto done;
8795 if (merge_in_progress) {
8796 error = got_error(GOT_ERR_MERGE_BUSY);
8797 goto done;
8800 error = get_author(&committer, repo, worktree);
8801 if (error)
8802 goto done;
8804 if (author != NULL && !strcmp(committer, author)) {
8805 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8806 goto done;
8809 if (author == NULL)
8810 author = committer;
8813 * unveil(2) traverses exec(2); if an editor is used we have
8814 * to apply unveil after the log message has been written.
8816 if (logmsg == NULL || strlen(logmsg) == 0)
8817 error = get_editor(&editor);
8818 else
8819 error = apply_unveil(got_repo_get_path(repo), 0,
8820 got_worktree_get_root_path(worktree));
8821 if (error)
8822 goto done;
8824 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8825 if (error)
8826 goto done;
8828 cl_arg.editor = editor;
8829 cl_arg.cmdline_log = logmsg;
8830 cl_arg.prepared_log = prepared_logmsg;
8831 cl_arg.non_interactive = non_interactive;
8832 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8833 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8834 if (!histedit_in_progress) {
8835 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8836 error = got_error(GOT_ERR_COMMIT_BRANCH);
8837 goto done;
8839 cl_arg.branch_name += 11;
8841 cl_arg.repo_path = got_repo_get_path(repo);
8842 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8843 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8844 print_status, NULL, repo);
8845 if (error) {
8846 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8847 cl_arg.logmsg_path != NULL)
8848 preserve_logmsg = 1;
8849 goto done;
8852 error = got_object_id_str(&id_str, id);
8853 if (error)
8854 goto done;
8855 printf("Created commit %s\n", id_str);
8856 done:
8857 if (preserve_logmsg) {
8858 fprintf(stderr, "%s: log message preserved in %s\n",
8859 getprogname(), cl_arg.logmsg_path);
8860 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8861 error == NULL)
8862 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8863 free(cl_arg.logmsg_path);
8864 if (repo) {
8865 const struct got_error *close_err = got_repo_close(repo);
8866 if (error == NULL)
8867 error = close_err;
8869 if (worktree)
8870 got_worktree_close(worktree);
8871 if (pack_fds) {
8872 const struct got_error *pack_err =
8873 got_repo_pack_fds_close(pack_fds);
8874 if (error == NULL)
8875 error = pack_err;
8877 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8878 free(cwd);
8879 free(id_str);
8880 free(gitconfig_path);
8881 free(editor);
8882 free(committer);
8883 free(prepared_logmsg);
8884 return error;
8887 __dead static void
8888 usage_send(void)
8890 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8891 "[-r repository-path] [-t tag] [remote-repository]\n",
8892 getprogname());
8893 exit(1);
8896 static void
8897 print_load_info(int print_colored, int print_found, int print_trees,
8898 int ncolored, int nfound, int ntrees)
8900 if (print_colored) {
8901 printf("%d commit%s colored", ncolored,
8902 ncolored == 1 ? "" : "s");
8904 if (print_found) {
8905 printf("%s%d object%s found",
8906 ncolored > 0 ? "; " : "",
8907 nfound, nfound == 1 ? "" : "s");
8909 if (print_trees) {
8910 printf("; %d tree%s scanned", ntrees,
8911 ntrees == 1 ? "" : "s");
8915 struct got_send_progress_arg {
8916 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8917 int verbosity;
8918 int last_ncolored;
8919 int last_nfound;
8920 int last_ntrees;
8921 int loading_done;
8922 int last_ncommits;
8923 int last_nobj_total;
8924 int last_p_deltify;
8925 int last_p_written;
8926 int last_p_sent;
8927 int printed_something;
8928 int sent_something;
8929 struct got_pathlist_head *delete_branches;
8932 static const struct got_error *
8933 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8934 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8935 int nobj_written, off_t bytes_sent, const char *refname,
8936 const char *errmsg, int success)
8938 struct got_send_progress_arg *a = arg;
8939 char scaled_packsize[FMT_SCALED_STRSIZE];
8940 char scaled_sent[FMT_SCALED_STRSIZE];
8941 int p_deltify = 0, p_written = 0, p_sent = 0;
8942 int print_colored = 0, print_found = 0, print_trees = 0;
8943 int print_searching = 0, print_total = 0;
8944 int print_deltify = 0, print_written = 0, print_sent = 0;
8946 if (a->verbosity < 0)
8947 return NULL;
8949 if (refname) {
8950 const char *status = success ? "accepted" : "rejected";
8952 if (success) {
8953 struct got_pathlist_entry *pe;
8954 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8955 const char *branchname = pe->path;
8956 if (got_path_cmp(branchname, refname,
8957 strlen(branchname), strlen(refname)) == 0) {
8958 status = "deleted";
8959 a->sent_something = 1;
8960 break;
8965 if (a->printed_something)
8966 putchar('\n');
8967 printf("Server has %s %s", status, refname);
8968 if (errmsg)
8969 printf(": %s", errmsg);
8970 a->printed_something = 1;
8971 return NULL;
8974 if (a->last_ncolored != ncolored) {
8975 print_colored = 1;
8976 a->last_ncolored = ncolored;
8979 if (a->last_nfound != nfound) {
8980 print_colored = 1;
8981 print_found = 1;
8982 a->last_nfound = nfound;
8985 if (a->last_ntrees != ntrees) {
8986 print_colored = 1;
8987 print_found = 1;
8988 print_trees = 1;
8989 a->last_ntrees = ntrees;
8992 if ((print_colored || print_found || print_trees) &&
8993 !a->loading_done) {
8994 printf("\r");
8995 print_load_info(print_colored, print_found, print_trees,
8996 ncolored, nfound, ntrees);
8997 a->printed_something = 1;
8998 fflush(stdout);
8999 return NULL;
9000 } else if (!a->loading_done) {
9001 printf("\r");
9002 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9003 printf("\n");
9004 a->loading_done = 1;
9007 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9008 return got_error_from_errno("fmt_scaled");
9009 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9010 return got_error_from_errno("fmt_scaled");
9012 if (a->last_ncommits != ncommits) {
9013 print_searching = 1;
9014 a->last_ncommits = ncommits;
9017 if (a->last_nobj_total != nobj_total) {
9018 print_searching = 1;
9019 print_total = 1;
9020 a->last_nobj_total = nobj_total;
9023 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9024 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9025 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9026 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9027 return got_error(GOT_ERR_NO_SPACE);
9030 if (nobj_deltify > 0 || nobj_written > 0) {
9031 if (nobj_deltify > 0) {
9032 p_deltify = (nobj_deltify * 100) / nobj_total;
9033 if (p_deltify != a->last_p_deltify) {
9034 a->last_p_deltify = p_deltify;
9035 print_searching = 1;
9036 print_total = 1;
9037 print_deltify = 1;
9040 if (nobj_written > 0) {
9041 p_written = (nobj_written * 100) / nobj_total;
9042 if (p_written != a->last_p_written) {
9043 a->last_p_written = p_written;
9044 print_searching = 1;
9045 print_total = 1;
9046 print_deltify = 1;
9047 print_written = 1;
9052 if (bytes_sent > 0) {
9053 p_sent = (bytes_sent * 100) / packfile_size;
9054 if (p_sent != a->last_p_sent) {
9055 a->last_p_sent = p_sent;
9056 print_searching = 1;
9057 print_total = 1;
9058 print_deltify = 1;
9059 print_written = 1;
9060 print_sent = 1;
9062 a->sent_something = 1;
9065 if (print_searching || print_total || print_deltify || print_written ||
9066 print_sent)
9067 printf("\r");
9068 if (print_searching)
9069 printf("packing %d reference%s", ncommits,
9070 ncommits == 1 ? "" : "s");
9071 if (print_total)
9072 printf("; %d object%s", nobj_total,
9073 nobj_total == 1 ? "" : "s");
9074 if (print_deltify)
9075 printf("; deltify: %d%%", p_deltify);
9076 if (print_sent)
9077 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9078 scaled_packsize, p_sent);
9079 else if (print_written)
9080 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9081 scaled_packsize, p_written);
9082 if (print_searching || print_total || print_deltify ||
9083 print_written || print_sent) {
9084 a->printed_something = 1;
9085 fflush(stdout);
9087 return NULL;
9090 static const struct got_error *
9091 cmd_send(int argc, char *argv[])
9093 const struct got_error *error = NULL;
9094 char *cwd = NULL, *repo_path = NULL;
9095 const char *remote_name;
9096 char *proto = NULL, *host = NULL, *port = NULL;
9097 char *repo_name = NULL, *server_path = NULL;
9098 const struct got_remote_repo *remotes, *remote = NULL;
9099 int nremotes, nbranches = 0, ndelete_branches = 0;
9100 struct got_repository *repo = NULL;
9101 struct got_worktree *worktree = NULL;
9102 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9103 struct got_pathlist_head branches;
9104 struct got_pathlist_head tags;
9105 struct got_reflist_head all_branches;
9106 struct got_reflist_head all_tags;
9107 struct got_pathlist_head delete_args;
9108 struct got_pathlist_head delete_branches;
9109 struct got_reflist_entry *re;
9110 struct got_pathlist_entry *pe;
9111 int i, ch, sendfd = -1, sendstatus;
9112 pid_t sendpid = -1;
9113 struct got_send_progress_arg spa;
9114 int verbosity = 0, overwrite_refs = 0;
9115 int send_all_branches = 0, send_all_tags = 0;
9116 struct got_reference *ref = NULL;
9117 int *pack_fds = NULL;
9119 TAILQ_INIT(&branches);
9120 TAILQ_INIT(&tags);
9121 TAILQ_INIT(&all_branches);
9122 TAILQ_INIT(&all_tags);
9123 TAILQ_INIT(&delete_args);
9124 TAILQ_INIT(&delete_branches);
9126 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9127 switch (ch) {
9128 case 'a':
9129 send_all_branches = 1;
9130 break;
9131 case 'b':
9132 error = got_pathlist_append(&branches, optarg, NULL);
9133 if (error)
9134 return error;
9135 nbranches++;
9136 break;
9137 case 'd':
9138 error = got_pathlist_append(&delete_args, optarg, NULL);
9139 if (error)
9140 return error;
9141 break;
9142 case 'f':
9143 overwrite_refs = 1;
9144 break;
9145 case 'q':
9146 verbosity = -1;
9147 break;
9148 case 'r':
9149 repo_path = realpath(optarg, NULL);
9150 if (repo_path == NULL)
9151 return got_error_from_errno2("realpath",
9152 optarg);
9153 got_path_strip_trailing_slashes(repo_path);
9154 break;
9155 case 'T':
9156 send_all_tags = 1;
9157 break;
9158 case 't':
9159 error = got_pathlist_append(&tags, optarg, NULL);
9160 if (error)
9161 return error;
9162 break;
9163 case 'v':
9164 if (verbosity < 0)
9165 verbosity = 0;
9166 else if (verbosity < 3)
9167 verbosity++;
9168 break;
9169 default:
9170 usage_send();
9171 /* NOTREACHED */
9174 argc -= optind;
9175 argv += optind;
9177 if (send_all_branches && !TAILQ_EMPTY(&branches))
9178 option_conflict('a', 'b');
9179 if (send_all_tags && !TAILQ_EMPTY(&tags))
9180 option_conflict('T', 't');
9183 if (argc == 0)
9184 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9185 else if (argc == 1)
9186 remote_name = argv[0];
9187 else
9188 usage_send();
9190 cwd = getcwd(NULL, 0);
9191 if (cwd == NULL) {
9192 error = got_error_from_errno("getcwd");
9193 goto done;
9196 error = got_repo_pack_fds_open(&pack_fds);
9197 if (error != NULL)
9198 goto done;
9200 if (repo_path == NULL) {
9201 error = got_worktree_open(&worktree, cwd);
9202 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9203 goto done;
9204 else
9205 error = NULL;
9206 if (worktree) {
9207 repo_path =
9208 strdup(got_worktree_get_repo_path(worktree));
9209 if (repo_path == NULL)
9210 error = got_error_from_errno("strdup");
9211 if (error)
9212 goto done;
9213 } else {
9214 repo_path = strdup(cwd);
9215 if (repo_path == NULL) {
9216 error = got_error_from_errno("strdup");
9217 goto done;
9222 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9223 if (error)
9224 goto done;
9226 if (worktree) {
9227 worktree_conf = got_worktree_get_gotconfig(worktree);
9228 if (worktree_conf) {
9229 got_gotconfig_get_remotes(&nremotes, &remotes,
9230 worktree_conf);
9231 for (i = 0; i < nremotes; i++) {
9232 if (strcmp(remotes[i].name, remote_name) == 0) {
9233 remote = &remotes[i];
9234 break;
9239 if (remote == NULL) {
9240 repo_conf = got_repo_get_gotconfig(repo);
9241 if (repo_conf) {
9242 got_gotconfig_get_remotes(&nremotes, &remotes,
9243 repo_conf);
9244 for (i = 0; i < nremotes; i++) {
9245 if (strcmp(remotes[i].name, remote_name) == 0) {
9246 remote = &remotes[i];
9247 break;
9252 if (remote == NULL) {
9253 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9254 for (i = 0; i < nremotes; i++) {
9255 if (strcmp(remotes[i].name, remote_name) == 0) {
9256 remote = &remotes[i];
9257 break;
9261 if (remote == NULL) {
9262 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9263 goto done;
9266 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9267 &repo_name, remote->send_url);
9268 if (error)
9269 goto done;
9271 if (strcmp(proto, "git") == 0) {
9272 #ifndef PROFILE
9273 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9274 "sendfd dns inet unveil", NULL) == -1)
9275 err(1, "pledge");
9276 #endif
9277 } else if (strcmp(proto, "git+ssh") == 0 ||
9278 strcmp(proto, "ssh") == 0) {
9279 #ifndef PROFILE
9280 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9281 "sendfd unveil", NULL) == -1)
9282 err(1, "pledge");
9283 #endif
9284 } else if (strcmp(proto, "http") == 0 ||
9285 strcmp(proto, "git+http") == 0) {
9286 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9287 goto done;
9288 } else {
9289 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9290 goto done;
9293 error = got_dial_apply_unveil(proto);
9294 if (error)
9295 goto done;
9297 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9298 if (error)
9299 goto done;
9301 if (send_all_branches) {
9302 error = got_ref_list(&all_branches, repo, "refs/heads",
9303 got_ref_cmp_by_name, NULL);
9304 if (error)
9305 goto done;
9306 TAILQ_FOREACH(re, &all_branches, entry) {
9307 const char *branchname = got_ref_get_name(re->ref);
9308 error = got_pathlist_append(&branches,
9309 branchname, NULL);
9310 if (error)
9311 goto done;
9312 nbranches++;
9314 } else if (nbranches == 0) {
9315 for (i = 0; i < remote->nsend_branches; i++) {
9316 error = got_pathlist_append(&branches,
9317 remote->send_branches[i], NULL);
9318 if (error)
9319 goto done;
9323 if (send_all_tags) {
9324 error = got_ref_list(&all_tags, repo, "refs/tags",
9325 got_ref_cmp_by_name, NULL);
9326 if (error)
9327 goto done;
9328 TAILQ_FOREACH(re, &all_tags, entry) {
9329 const char *tagname = got_ref_get_name(re->ref);
9330 error = got_pathlist_append(&tags,
9331 tagname, NULL);
9332 if (error)
9333 goto done;
9338 * To prevent accidents only branches in refs/heads/ can be deleted
9339 * with 'got send -d'.
9340 * Deleting anything else requires local repository access or Git.
9342 TAILQ_FOREACH(pe, &delete_args, entry) {
9343 const char *branchname = pe->path;
9344 char *s;
9345 struct got_pathlist_entry *new;
9346 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9347 s = strdup(branchname);
9348 if (s == NULL) {
9349 error = got_error_from_errno("strdup");
9350 goto done;
9352 } else {
9353 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9354 error = got_error_from_errno("asprintf");
9355 goto done;
9358 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9359 if (error || new == NULL /* duplicate */)
9360 free(s);
9361 if (error)
9362 goto done;
9363 ndelete_branches++;
9366 if (nbranches == 0 && ndelete_branches == 0) {
9367 struct got_reference *head_ref;
9368 if (worktree)
9369 error = got_ref_open(&head_ref, repo,
9370 got_worktree_get_head_ref_name(worktree), 0);
9371 else
9372 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9373 if (error)
9374 goto done;
9375 if (got_ref_is_symbolic(head_ref)) {
9376 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9377 got_ref_close(head_ref);
9378 if (error)
9379 goto done;
9380 } else
9381 ref = head_ref;
9382 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9383 NULL);
9384 if (error)
9385 goto done;
9386 nbranches++;
9389 if (verbosity >= 0) {
9390 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9391 remote->name, proto, host,
9392 port ? ":" : "", port ? port : "",
9393 *server_path == '/' ? "" : "/", server_path);
9396 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9397 server_path, verbosity);
9398 if (error)
9399 goto done;
9401 memset(&spa, 0, sizeof(spa));
9402 spa.last_scaled_packsize[0] = '\0';
9403 spa.last_p_deltify = -1;
9404 spa.last_p_written = -1;
9405 spa.verbosity = verbosity;
9406 spa.delete_branches = &delete_branches;
9407 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9408 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9409 check_cancelled, NULL);
9410 if (spa.printed_something)
9411 putchar('\n');
9412 if (error)
9413 goto done;
9414 if (!spa.sent_something && verbosity >= 0)
9415 printf("Already up-to-date\n");
9416 done:
9417 if (sendpid > 0) {
9418 if (kill(sendpid, SIGTERM) == -1)
9419 error = got_error_from_errno("kill");
9420 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9421 error = got_error_from_errno("waitpid");
9423 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9424 error = got_error_from_errno("close");
9425 if (repo) {
9426 const struct got_error *close_err = got_repo_close(repo);
9427 if (error == NULL)
9428 error = close_err;
9430 if (worktree)
9431 got_worktree_close(worktree);
9432 if (pack_fds) {
9433 const struct got_error *pack_err =
9434 got_repo_pack_fds_close(pack_fds);
9435 if (error == NULL)
9436 error = pack_err;
9438 if (ref)
9439 got_ref_close(ref);
9440 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9441 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9442 got_ref_list_free(&all_branches);
9443 got_ref_list_free(&all_tags);
9444 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9445 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9446 free(cwd);
9447 free(repo_path);
9448 free(proto);
9449 free(host);
9450 free(port);
9451 free(server_path);
9452 free(repo_name);
9453 return error;
9456 __dead static void
9457 usage_cherrypick(void)
9459 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9460 exit(1);
9463 static const struct got_error *
9464 cmd_cherrypick(int argc, char *argv[])
9466 const struct got_error *error = NULL;
9467 struct got_worktree *worktree = NULL;
9468 struct got_repository *repo = NULL;
9469 char *cwd = NULL, *commit_id_str = NULL;
9470 struct got_object_id *commit_id = NULL;
9471 struct got_commit_object *commit = NULL;
9472 struct got_object_qid *pid;
9473 int ch;
9474 struct got_update_progress_arg upa;
9475 int *pack_fds = NULL;
9477 while ((ch = getopt(argc, argv, "")) != -1) {
9478 switch (ch) {
9479 default:
9480 usage_cherrypick();
9481 /* NOTREACHED */
9485 argc -= optind;
9486 argv += optind;
9488 #ifndef PROFILE
9489 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9490 "unveil", NULL) == -1)
9491 err(1, "pledge");
9492 #endif
9493 if (argc != 1)
9494 usage_cherrypick();
9496 cwd = getcwd(NULL, 0);
9497 if (cwd == NULL) {
9498 error = got_error_from_errno("getcwd");
9499 goto done;
9502 error = got_repo_pack_fds_open(&pack_fds);
9503 if (error != NULL)
9504 goto done;
9506 error = got_worktree_open(&worktree, cwd);
9507 if (error) {
9508 if (error->code == GOT_ERR_NOT_WORKTREE)
9509 error = wrap_not_worktree_error(error, "cherrypick",
9510 cwd);
9511 goto done;
9514 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9515 NULL, pack_fds);
9516 if (error != NULL)
9517 goto done;
9519 error = apply_unveil(got_repo_get_path(repo), 0,
9520 got_worktree_get_root_path(worktree));
9521 if (error)
9522 goto done;
9524 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9525 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9526 if (error)
9527 goto done;
9528 error = got_object_id_str(&commit_id_str, commit_id);
9529 if (error)
9530 goto done;
9532 error = got_object_open_as_commit(&commit, repo, commit_id);
9533 if (error)
9534 goto done;
9535 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9536 memset(&upa, 0, sizeof(upa));
9537 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9538 commit_id, repo, update_progress, &upa, check_cancelled,
9539 NULL);
9540 if (error != NULL)
9541 goto done;
9543 if (upa.did_something)
9544 printf("Merged commit %s\n", commit_id_str);
9545 print_merge_progress_stats(&upa);
9546 done:
9547 if (commit)
9548 got_object_commit_close(commit);
9549 free(commit_id_str);
9550 if (worktree)
9551 got_worktree_close(worktree);
9552 if (repo) {
9553 const struct got_error *close_err = got_repo_close(repo);
9554 if (error == NULL)
9555 error = close_err;
9557 if (pack_fds) {
9558 const struct got_error *pack_err =
9559 got_repo_pack_fds_close(pack_fds);
9560 if (error == NULL)
9561 error = pack_err;
9564 return error;
9567 __dead static void
9568 usage_backout(void)
9570 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9571 exit(1);
9574 static const struct got_error *
9575 cmd_backout(int argc, char *argv[])
9577 const struct got_error *error = NULL;
9578 struct got_worktree *worktree = NULL;
9579 struct got_repository *repo = NULL;
9580 char *cwd = NULL, *commit_id_str = NULL;
9581 struct got_object_id *commit_id = NULL;
9582 struct got_commit_object *commit = NULL;
9583 struct got_object_qid *pid;
9584 int ch;
9585 struct got_update_progress_arg upa;
9586 int *pack_fds = NULL;
9588 while ((ch = getopt(argc, argv, "")) != -1) {
9589 switch (ch) {
9590 default:
9591 usage_backout();
9592 /* NOTREACHED */
9596 argc -= optind;
9597 argv += optind;
9599 #ifndef PROFILE
9600 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9601 "unveil", NULL) == -1)
9602 err(1, "pledge");
9603 #endif
9604 if (argc != 1)
9605 usage_backout();
9607 cwd = getcwd(NULL, 0);
9608 if (cwd == NULL) {
9609 error = got_error_from_errno("getcwd");
9610 goto done;
9613 error = got_repo_pack_fds_open(&pack_fds);
9614 if (error != NULL)
9615 goto done;
9617 error = got_worktree_open(&worktree, cwd);
9618 if (error) {
9619 if (error->code == GOT_ERR_NOT_WORKTREE)
9620 error = wrap_not_worktree_error(error, "backout", cwd);
9621 goto done;
9624 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9625 NULL, pack_fds);
9626 if (error != NULL)
9627 goto done;
9629 error = apply_unveil(got_repo_get_path(repo), 0,
9630 got_worktree_get_root_path(worktree));
9631 if (error)
9632 goto done;
9634 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9635 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9636 if (error)
9637 goto done;
9638 error = got_object_id_str(&commit_id_str, commit_id);
9639 if (error)
9640 goto done;
9642 error = got_object_open_as_commit(&commit, repo, commit_id);
9643 if (error)
9644 goto done;
9645 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9646 if (pid == NULL) {
9647 error = got_error(GOT_ERR_ROOT_COMMIT);
9648 goto done;
9651 memset(&upa, 0, sizeof(upa));
9652 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9653 repo, update_progress, &upa, check_cancelled, NULL);
9654 if (error != NULL)
9655 goto done;
9657 if (upa.did_something)
9658 printf("Backed out commit %s\n", commit_id_str);
9659 print_merge_progress_stats(&upa);
9660 done:
9661 if (commit)
9662 got_object_commit_close(commit);
9663 free(commit_id_str);
9664 if (worktree)
9665 got_worktree_close(worktree);
9666 if (repo) {
9667 const struct got_error *close_err = got_repo_close(repo);
9668 if (error == NULL)
9669 error = close_err;
9671 if (pack_fds) {
9672 const struct got_error *pack_err =
9673 got_repo_pack_fds_close(pack_fds);
9674 if (error == NULL)
9675 error = pack_err;
9677 return error;
9680 __dead static void
9681 usage_rebase(void)
9683 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9684 exit(1);
9687 static void
9688 trim_logmsg(char *logmsg, int limit)
9690 char *nl;
9691 size_t len;
9693 len = strlen(logmsg);
9694 if (len > limit)
9695 len = limit;
9696 logmsg[len] = '\0';
9697 nl = strchr(logmsg, '\n');
9698 if (nl)
9699 *nl = '\0';
9702 static const struct got_error *
9703 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9705 const struct got_error *err;
9706 char *logmsg0 = NULL;
9707 const char *s;
9709 err = got_object_commit_get_logmsg(&logmsg0, commit);
9710 if (err)
9711 return err;
9713 s = logmsg0;
9714 while (isspace((unsigned char)s[0]))
9715 s++;
9717 *logmsg = strdup(s);
9718 if (*logmsg == NULL) {
9719 err = got_error_from_errno("strdup");
9720 goto done;
9723 trim_logmsg(*logmsg, limit);
9724 done:
9725 free(logmsg0);
9726 return err;
9729 static const struct got_error *
9730 show_rebase_merge_conflict(struct got_object_id *id,
9731 struct got_repository *repo)
9733 const struct got_error *err;
9734 struct got_commit_object *commit = NULL;
9735 char *id_str = NULL, *logmsg = NULL;
9737 err = got_object_open_as_commit(&commit, repo, id);
9738 if (err)
9739 return err;
9741 err = got_object_id_str(&id_str, id);
9742 if (err)
9743 goto done;
9745 id_str[12] = '\0';
9747 err = get_short_logmsg(&logmsg, 42, commit);
9748 if (err)
9749 goto done;
9751 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9752 done:
9753 free(id_str);
9754 got_object_commit_close(commit);
9755 free(logmsg);
9756 return err;
9759 static const struct got_error *
9760 show_rebase_progress(struct got_commit_object *commit,
9761 struct got_object_id *old_id, struct got_object_id *new_id)
9763 const struct got_error *err;
9764 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9766 err = got_object_id_str(&old_id_str, old_id);
9767 if (err)
9768 goto done;
9770 if (new_id) {
9771 err = got_object_id_str(&new_id_str, new_id);
9772 if (err)
9773 goto done;
9776 old_id_str[12] = '\0';
9777 if (new_id_str)
9778 new_id_str[12] = '\0';
9780 err = get_short_logmsg(&logmsg, 42, commit);
9781 if (err)
9782 goto done;
9784 printf("%s -> %s: %s\n", old_id_str,
9785 new_id_str ? new_id_str : "no-op change", logmsg);
9786 done:
9787 free(old_id_str);
9788 free(new_id_str);
9789 free(logmsg);
9790 return err;
9793 static const struct got_error *
9794 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9795 struct got_reference *branch, struct got_reference *new_base_branch,
9796 struct got_reference *tmp_branch, struct got_repository *repo,
9797 int create_backup)
9799 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9800 return got_worktree_rebase_complete(worktree, fileindex,
9801 new_base_branch, tmp_branch, branch, repo, create_backup);
9804 static const struct got_error *
9805 rebase_commit(struct got_pathlist_head *merged_paths,
9806 struct got_worktree *worktree, struct got_fileindex *fileindex,
9807 struct got_reference *tmp_branch, const char *committer,
9808 struct got_object_id *commit_id, struct got_repository *repo)
9810 const struct got_error *error;
9811 struct got_commit_object *commit;
9812 struct got_object_id *new_commit_id;
9814 error = got_object_open_as_commit(&commit, repo, commit_id);
9815 if (error)
9816 return error;
9818 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9819 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9820 repo);
9821 if (error) {
9822 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9823 goto done;
9824 error = show_rebase_progress(commit, commit_id, NULL);
9825 } else {
9826 error = show_rebase_progress(commit, commit_id, new_commit_id);
9827 free(new_commit_id);
9829 done:
9830 got_object_commit_close(commit);
9831 return error;
9834 struct check_path_prefix_arg {
9835 const char *path_prefix;
9836 size_t len;
9837 int errcode;
9840 static const struct got_error *
9841 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9842 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9843 struct got_object_id *id1, struct got_object_id *id2,
9844 const char *path1, const char *path2,
9845 mode_t mode1, mode_t mode2, struct got_repository *repo)
9847 struct check_path_prefix_arg *a = arg;
9849 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9850 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9851 return got_error(a->errcode);
9853 return NULL;
9856 static const struct got_error *
9857 check_path_prefix(struct got_object_id *parent_id,
9858 struct got_object_id *commit_id, const char *path_prefix,
9859 int errcode, struct got_repository *repo)
9861 const struct got_error *err;
9862 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9863 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9864 struct check_path_prefix_arg cpp_arg;
9866 if (got_path_is_root_dir(path_prefix))
9867 return NULL;
9869 err = got_object_open_as_commit(&commit, repo, commit_id);
9870 if (err)
9871 goto done;
9873 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9874 if (err)
9875 goto done;
9877 err = got_object_open_as_tree(&tree1, repo,
9878 got_object_commit_get_tree_id(parent_commit));
9879 if (err)
9880 goto done;
9882 err = got_object_open_as_tree(&tree2, repo,
9883 got_object_commit_get_tree_id(commit));
9884 if (err)
9885 goto done;
9887 cpp_arg.path_prefix = path_prefix;
9888 while (cpp_arg.path_prefix[0] == '/')
9889 cpp_arg.path_prefix++;
9890 cpp_arg.len = strlen(cpp_arg.path_prefix);
9891 cpp_arg.errcode = errcode;
9892 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9893 check_path_prefix_in_diff, &cpp_arg, 0);
9894 done:
9895 if (tree1)
9896 got_object_tree_close(tree1);
9897 if (tree2)
9898 got_object_tree_close(tree2);
9899 if (commit)
9900 got_object_commit_close(commit);
9901 if (parent_commit)
9902 got_object_commit_close(parent_commit);
9903 return err;
9906 static const struct got_error *
9907 collect_commits(struct got_object_id_queue *commits,
9908 struct got_object_id *initial_commit_id,
9909 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9910 const char *path_prefix, int path_prefix_errcode,
9911 struct got_repository *repo)
9913 const struct got_error *err = NULL;
9914 struct got_commit_graph *graph = NULL;
9915 struct got_object_id parent_id, commit_id;
9916 struct got_object_qid *qid;
9918 err = got_commit_graph_open(&graph, "/", 1);
9919 if (err)
9920 return err;
9922 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9923 check_cancelled, NULL);
9924 if (err)
9925 goto done;
9927 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9928 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9929 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9930 check_cancelled, NULL);
9931 if (err) {
9932 if (err->code == GOT_ERR_ITER_COMPLETED) {
9933 err = got_error_msg(GOT_ERR_ANCESTRY,
9934 "ran out of commits to rebase before "
9935 "youngest common ancestor commit has "
9936 "been reached?!?");
9938 goto done;
9939 } else {
9940 err = check_path_prefix(&parent_id, &commit_id,
9941 path_prefix, path_prefix_errcode, repo);
9942 if (err)
9943 goto done;
9945 err = got_object_qid_alloc(&qid, &commit_id);
9946 if (err)
9947 goto done;
9948 STAILQ_INSERT_HEAD(commits, qid, entry);
9950 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9953 done:
9954 got_commit_graph_close(graph);
9955 return err;
9958 static const struct got_error *
9959 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9961 const struct got_error *err = NULL;
9962 time_t committer_time;
9963 struct tm tm;
9964 char datebuf[11]; /* YYYY-MM-DD + NUL */
9965 char *author0 = NULL, *author, *smallerthan;
9966 char *logmsg0 = NULL, *logmsg, *newline;
9968 committer_time = got_object_commit_get_committer_time(commit);
9969 if (gmtime_r(&committer_time, &tm) == NULL)
9970 return got_error_from_errno("gmtime_r");
9971 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9972 return got_error(GOT_ERR_NO_SPACE);
9974 author0 = strdup(got_object_commit_get_author(commit));
9975 if (author0 == NULL)
9976 return got_error_from_errno("strdup");
9977 author = author0;
9978 smallerthan = strchr(author, '<');
9979 if (smallerthan && smallerthan[1] != '\0')
9980 author = smallerthan + 1;
9981 author[strcspn(author, "@>")] = '\0';
9983 err = got_object_commit_get_logmsg(&logmsg0, commit);
9984 if (err)
9985 goto done;
9986 logmsg = logmsg0;
9987 while (*logmsg == '\n')
9988 logmsg++;
9989 newline = strchr(logmsg, '\n');
9990 if (newline)
9991 *newline = '\0';
9993 if (asprintf(brief_str, "%s %s %s",
9994 datebuf, author, logmsg) == -1)
9995 err = got_error_from_errno("asprintf");
9996 done:
9997 free(author0);
9998 free(logmsg0);
9999 return err;
10002 static const struct got_error *
10003 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10004 struct got_repository *repo)
10006 const struct got_error *err;
10007 char *id_str;
10009 err = got_object_id_str(&id_str, id);
10010 if (err)
10011 return err;
10013 err = got_ref_delete(ref, repo);
10014 if (err)
10015 goto done;
10017 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10018 done:
10019 free(id_str);
10020 return err;
10023 static const struct got_error *
10024 print_backup_ref(const char *branch_name, const char *new_id_str,
10025 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10026 struct got_reflist_object_id_map *refs_idmap,
10027 struct got_repository *repo)
10029 const struct got_error *err = NULL;
10030 struct got_reflist_head *refs;
10031 char *refs_str = NULL;
10032 struct got_object_id *new_commit_id = NULL;
10033 struct got_commit_object *new_commit = NULL;
10034 char *new_commit_brief_str = NULL;
10035 struct got_object_id *yca_id = NULL;
10036 struct got_commit_object *yca_commit = NULL;
10037 char *yca_id_str = NULL, *yca_brief_str = NULL;
10038 char *custom_refs_str;
10040 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10041 return got_error_from_errno("asprintf");
10043 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10044 0, 0, refs_idmap, custom_refs_str);
10045 if (err)
10046 goto done;
10048 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10049 if (err)
10050 goto done;
10052 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10053 if (refs) {
10054 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10055 if (err)
10056 goto done;
10059 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10060 if (err)
10061 goto done;
10063 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10064 if (err)
10065 goto done;
10067 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10068 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10069 if (err)
10070 goto done;
10072 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10073 refs_str ? " (" : "", refs_str ? refs_str : "",
10074 refs_str ? ")" : "", new_commit_brief_str);
10075 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10076 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10077 free(refs_str);
10078 refs_str = NULL;
10080 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10081 if (err)
10082 goto done;
10084 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10085 if (err)
10086 goto done;
10088 err = got_object_id_str(&yca_id_str, yca_id);
10089 if (err)
10090 goto done;
10092 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10093 if (refs) {
10094 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10095 if (err)
10096 goto done;
10098 printf("history forked at %s%s%s%s\n %s\n",
10099 yca_id_str,
10100 refs_str ? " (" : "", refs_str ? refs_str : "",
10101 refs_str ? ")" : "", yca_brief_str);
10103 done:
10104 free(custom_refs_str);
10105 free(new_commit_id);
10106 free(refs_str);
10107 free(yca_id);
10108 free(yca_id_str);
10109 free(yca_brief_str);
10110 if (new_commit)
10111 got_object_commit_close(new_commit);
10112 if (yca_commit)
10113 got_object_commit_close(yca_commit);
10115 return NULL;
10118 static const struct got_error *
10119 process_backup_refs(const char *backup_ref_prefix,
10120 const char *wanted_branch_name,
10121 int delete, struct got_repository *repo)
10123 const struct got_error *err;
10124 struct got_reflist_head refs, backup_refs;
10125 struct got_reflist_entry *re;
10126 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10127 struct got_object_id *old_commit_id = NULL;
10128 char *branch_name = NULL;
10129 struct got_commit_object *old_commit = NULL;
10130 struct got_reflist_object_id_map *refs_idmap = NULL;
10131 int wanted_branch_found = 0;
10133 TAILQ_INIT(&refs);
10134 TAILQ_INIT(&backup_refs);
10136 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10137 if (err)
10138 return err;
10140 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10141 if (err)
10142 goto done;
10144 if (wanted_branch_name) {
10145 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10146 wanted_branch_name += 11;
10149 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10150 got_ref_cmp_by_commit_timestamp_descending, repo);
10151 if (err)
10152 goto done;
10154 TAILQ_FOREACH(re, &backup_refs, entry) {
10155 const char *refname = got_ref_get_name(re->ref);
10156 char *slash;
10158 err = check_cancelled(NULL);
10159 if (err)
10160 break;
10162 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10163 if (err)
10164 break;
10166 err = got_object_open_as_commit(&old_commit, repo,
10167 old_commit_id);
10168 if (err)
10169 break;
10171 if (strncmp(backup_ref_prefix, refname,
10172 backup_ref_prefix_len) == 0)
10173 refname += backup_ref_prefix_len;
10175 while (refname[0] == '/')
10176 refname++;
10178 branch_name = strdup(refname);
10179 if (branch_name == NULL) {
10180 err = got_error_from_errno("strdup");
10181 break;
10183 slash = strrchr(branch_name, '/');
10184 if (slash) {
10185 *slash = '\0';
10186 refname += strlen(branch_name) + 1;
10189 if (wanted_branch_name == NULL ||
10190 strcmp(wanted_branch_name, branch_name) == 0) {
10191 wanted_branch_found = 1;
10192 if (delete) {
10193 err = delete_backup_ref(re->ref,
10194 old_commit_id, repo);
10195 } else {
10196 err = print_backup_ref(branch_name, refname,
10197 old_commit_id, old_commit, refs_idmap,
10198 repo);
10200 if (err)
10201 break;
10204 free(old_commit_id);
10205 old_commit_id = NULL;
10206 free(branch_name);
10207 branch_name = NULL;
10208 got_object_commit_close(old_commit);
10209 old_commit = NULL;
10212 if (wanted_branch_name && !wanted_branch_found) {
10213 err = got_error_fmt(GOT_ERR_NOT_REF,
10214 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10216 done:
10217 if (refs_idmap)
10218 got_reflist_object_id_map_free(refs_idmap);
10219 got_ref_list_free(&refs);
10220 got_ref_list_free(&backup_refs);
10221 free(old_commit_id);
10222 free(branch_name);
10223 if (old_commit)
10224 got_object_commit_close(old_commit);
10225 return err;
10228 static const struct got_error *
10229 abort_progress(void *arg, unsigned char status, const char *path)
10232 * Unversioned files should not clutter progress output when
10233 * an operation is aborted.
10235 if (status == GOT_STATUS_UNVERSIONED)
10236 return NULL;
10238 return update_progress(arg, status, path);
10241 static const struct got_error *
10242 cmd_rebase(int argc, char *argv[])
10244 const struct got_error *error = NULL;
10245 struct got_worktree *worktree = NULL;
10246 struct got_repository *repo = NULL;
10247 struct got_fileindex *fileindex = NULL;
10248 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10249 struct got_reference *branch = NULL;
10250 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10251 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10252 struct got_object_id *resume_commit_id = NULL;
10253 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10254 struct got_object_id *head_commit_id = NULL;
10255 struct got_reference *head_ref = NULL;
10256 struct got_commit_object *commit = NULL;
10257 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10258 int histedit_in_progress = 0, merge_in_progress = 0;
10259 int create_backup = 1, list_backups = 0, delete_backups = 0;
10260 struct got_object_id_queue commits;
10261 struct got_pathlist_head merged_paths;
10262 const struct got_object_id_queue *parent_ids;
10263 struct got_object_qid *qid, *pid;
10264 struct got_update_progress_arg upa;
10265 int *pack_fds = NULL;
10267 STAILQ_INIT(&commits);
10268 TAILQ_INIT(&merged_paths);
10269 memset(&upa, 0, sizeof(upa));
10271 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10272 switch (ch) {
10273 case 'a':
10274 abort_rebase = 1;
10275 break;
10276 case 'c':
10277 continue_rebase = 1;
10278 break;
10279 case 'l':
10280 list_backups = 1;
10281 break;
10282 case 'X':
10283 delete_backups = 1;
10284 break;
10285 default:
10286 usage_rebase();
10287 /* NOTREACHED */
10291 argc -= optind;
10292 argv += optind;
10294 #ifndef PROFILE
10295 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10296 "unveil", NULL) == -1)
10297 err(1, "pledge");
10298 #endif
10299 if (list_backups) {
10300 if (abort_rebase)
10301 option_conflict('l', 'a');
10302 if (continue_rebase)
10303 option_conflict('l', 'c');
10304 if (delete_backups)
10305 option_conflict('l', 'X');
10306 if (argc != 0 && argc != 1)
10307 usage_rebase();
10308 } else if (delete_backups) {
10309 if (abort_rebase)
10310 option_conflict('X', 'a');
10311 if (continue_rebase)
10312 option_conflict('X', 'c');
10313 if (list_backups)
10314 option_conflict('l', 'X');
10315 if (argc != 0 && argc != 1)
10316 usage_rebase();
10317 } else {
10318 if (abort_rebase && continue_rebase)
10319 usage_rebase();
10320 else if (abort_rebase || continue_rebase) {
10321 if (argc != 0)
10322 usage_rebase();
10323 } else if (argc != 1)
10324 usage_rebase();
10327 cwd = getcwd(NULL, 0);
10328 if (cwd == NULL) {
10329 error = got_error_from_errno("getcwd");
10330 goto done;
10333 error = got_repo_pack_fds_open(&pack_fds);
10334 if (error != NULL)
10335 goto done;
10337 error = got_worktree_open(&worktree, cwd);
10338 if (error) {
10339 if (list_backups || delete_backups) {
10340 if (error->code != GOT_ERR_NOT_WORKTREE)
10341 goto done;
10342 } else {
10343 if (error->code == GOT_ERR_NOT_WORKTREE)
10344 error = wrap_not_worktree_error(error,
10345 "rebase", cwd);
10346 goto done;
10350 error = get_gitconfig_path(&gitconfig_path);
10351 if (error)
10352 goto done;
10353 error = got_repo_open(&repo,
10354 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10355 gitconfig_path, pack_fds);
10356 if (error != NULL)
10357 goto done;
10359 error = get_author(&committer, repo, worktree);
10360 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10361 goto done;
10363 error = apply_unveil(got_repo_get_path(repo), 0,
10364 worktree ? got_worktree_get_root_path(worktree) : NULL);
10365 if (error)
10366 goto done;
10368 if (list_backups || delete_backups) {
10369 error = process_backup_refs(
10370 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10371 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10372 goto done; /* nothing else to do */
10375 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10376 worktree);
10377 if (error)
10378 goto done;
10379 if (histedit_in_progress) {
10380 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10381 goto done;
10384 error = got_worktree_merge_in_progress(&merge_in_progress,
10385 worktree, repo);
10386 if (error)
10387 goto done;
10388 if (merge_in_progress) {
10389 error = got_error(GOT_ERR_MERGE_BUSY);
10390 goto done;
10393 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10394 if (error)
10395 goto done;
10397 if (abort_rebase) {
10398 if (!rebase_in_progress) {
10399 error = got_error(GOT_ERR_NOT_REBASING);
10400 goto done;
10402 error = got_worktree_rebase_continue(&resume_commit_id,
10403 &new_base_branch, &tmp_branch, &branch, &fileindex,
10404 worktree, repo);
10405 if (error)
10406 goto done;
10407 printf("Switching work tree to %s\n",
10408 got_ref_get_symref_target(new_base_branch));
10409 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10410 new_base_branch, abort_progress, &upa);
10411 if (error)
10412 goto done;
10413 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10414 print_merge_progress_stats(&upa);
10415 goto done; /* nothing else to do */
10418 if (continue_rebase) {
10419 if (!rebase_in_progress) {
10420 error = got_error(GOT_ERR_NOT_REBASING);
10421 goto done;
10423 error = got_worktree_rebase_continue(&resume_commit_id,
10424 &new_base_branch, &tmp_branch, &branch, &fileindex,
10425 worktree, repo);
10426 if (error)
10427 goto done;
10429 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10430 committer, resume_commit_id, repo);
10431 if (error)
10432 goto done;
10434 yca_id = got_object_id_dup(resume_commit_id);
10435 if (yca_id == NULL) {
10436 error = got_error_from_errno("got_object_id_dup");
10437 goto done;
10439 } else {
10440 error = got_ref_open(&branch, repo, argv[0], 0);
10441 if (error != NULL)
10442 goto done;
10443 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10444 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10445 "will not rebase a branch which lives outside "
10446 "the \"refs/heads/\" reference namespace");
10447 goto done;
10451 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10452 if (error)
10453 goto done;
10455 if (!continue_rebase) {
10456 struct got_object_id *base_commit_id;
10458 error = got_ref_open(&head_ref, repo,
10459 got_worktree_get_head_ref_name(worktree), 0);
10460 if (error)
10461 goto done;
10462 error = got_ref_resolve(&head_commit_id, repo, head_ref);
10463 if (error)
10464 goto done;
10465 base_commit_id = got_worktree_get_base_commit_id(worktree);
10466 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
10467 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
10468 goto done;
10471 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10472 base_commit_id, branch_head_commit_id, 1, repo,
10473 check_cancelled, NULL);
10474 if (error)
10475 goto done;
10476 if (yca_id == NULL) {
10477 error = got_error_msg(GOT_ERR_ANCESTRY,
10478 "specified branch shares no common ancestry "
10479 "with work tree's branch");
10480 goto done;
10483 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10484 if (error) {
10485 if (error->code != GOT_ERR_ANCESTRY)
10486 goto done;
10487 error = NULL;
10488 } else {
10489 struct got_pathlist_head paths;
10490 printf("%s is already based on %s\n",
10491 got_ref_get_name(branch),
10492 got_worktree_get_head_ref_name(worktree));
10493 error = switch_head_ref(branch, branch_head_commit_id,
10494 worktree, repo);
10495 if (error)
10496 goto done;
10497 error = got_worktree_set_base_commit_id(worktree, repo,
10498 branch_head_commit_id);
10499 if (error)
10500 goto done;
10501 TAILQ_INIT(&paths);
10502 error = got_pathlist_append(&paths, "", NULL);
10503 if (error)
10504 goto done;
10505 error = got_worktree_checkout_files(worktree,
10506 &paths, repo, update_progress, &upa,
10507 check_cancelled, NULL);
10508 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
10509 if (error)
10510 goto done;
10511 if (upa.did_something) {
10512 char *id_str;
10513 error = got_object_id_str(&id_str,
10514 branch_head_commit_id);
10515 if (error)
10516 goto done;
10517 printf("Updated to %s: %s\n",
10518 got_worktree_get_head_ref_name(worktree),
10519 id_str);
10520 free(id_str);
10521 } else
10522 printf("Already up-to-date\n");
10523 print_update_progress_stats(&upa);
10524 goto done;
10528 commit_id = branch_head_commit_id;
10529 error = got_object_open_as_commit(&commit, repo, commit_id);
10530 if (error)
10531 goto done;
10533 parent_ids = got_object_commit_get_parent_ids(commit);
10534 pid = STAILQ_FIRST(parent_ids);
10535 if (pid == NULL) {
10536 error = got_error(GOT_ERR_EMPTY_REBASE);
10537 goto done;
10539 error = collect_commits(&commits, commit_id, &pid->id,
10540 yca_id, got_worktree_get_path_prefix(worktree),
10541 GOT_ERR_REBASE_PATH, repo);
10542 got_object_commit_close(commit);
10543 commit = NULL;
10544 if (error)
10545 goto done;
10547 if (!continue_rebase) {
10548 error = got_worktree_rebase_prepare(&new_base_branch,
10549 &tmp_branch, &fileindex, worktree, branch, repo);
10550 if (error)
10551 goto done;
10554 if (STAILQ_EMPTY(&commits)) {
10555 if (continue_rebase) {
10556 error = rebase_complete(worktree, fileindex,
10557 branch, new_base_branch, tmp_branch, repo,
10558 create_backup);
10559 goto done;
10560 } else {
10561 /* Fast-forward the reference of the branch. */
10562 struct got_object_id *new_head_commit_id;
10563 char *id_str;
10564 error = got_ref_resolve(&new_head_commit_id, repo,
10565 new_base_branch);
10566 if (error)
10567 goto done;
10568 error = got_object_id_str(&id_str, new_head_commit_id);
10569 if (error)
10570 goto done;
10571 printf("Forwarding %s to commit %s\n",
10572 got_ref_get_name(branch), id_str);
10573 free(id_str);
10574 error = got_ref_change_ref(branch,
10575 new_head_commit_id);
10576 if (error)
10577 goto done;
10578 /* No backup needed since objects did not change. */
10579 create_backup = 0;
10583 pid = NULL;
10584 STAILQ_FOREACH(qid, &commits, entry) {
10586 commit_id = &qid->id;
10587 parent_id = pid ? &pid->id : yca_id;
10588 pid = qid;
10590 memset(&upa, 0, sizeof(upa));
10591 error = got_worktree_rebase_merge_files(&merged_paths,
10592 worktree, fileindex, parent_id, commit_id, repo,
10593 update_progress, &upa, check_cancelled, NULL);
10594 if (error)
10595 goto done;
10597 print_merge_progress_stats(&upa);
10598 if (upa.conflicts > 0 || upa.missing > 0 ||
10599 upa.not_deleted > 0 || upa.unversioned > 0) {
10600 if (upa.conflicts > 0) {
10601 error = show_rebase_merge_conflict(&qid->id,
10602 repo);
10603 if (error)
10604 goto done;
10606 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10607 break;
10610 error = rebase_commit(&merged_paths, worktree, fileindex,
10611 tmp_branch, committer, commit_id, repo);
10612 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10613 if (error)
10614 goto done;
10617 if (upa.conflicts > 0 || upa.missing > 0 ||
10618 upa.not_deleted > 0 || upa.unversioned > 0) {
10619 error = got_worktree_rebase_postpone(worktree, fileindex);
10620 if (error)
10621 goto done;
10622 if (upa.conflicts > 0 && upa.missing == 0 &&
10623 upa.not_deleted == 0 && upa.unversioned == 0) {
10624 error = got_error_msg(GOT_ERR_CONFLICTS,
10625 "conflicts must be resolved before rebasing "
10626 "can continue");
10627 } else if (upa.conflicts > 0) {
10628 error = got_error_msg(GOT_ERR_CONFLICTS,
10629 "conflicts must be resolved before rebasing "
10630 "can continue; changes destined for some "
10631 "files were not yet merged and should be "
10632 "merged manually if required before the "
10633 "rebase operation is continued");
10634 } else {
10635 error = got_error_msg(GOT_ERR_CONFLICTS,
10636 "changes destined for some files were not "
10637 "yet merged and should be merged manually "
10638 "if required before the rebase operation "
10639 "is continued");
10641 } else
10642 error = rebase_complete(worktree, fileindex, branch,
10643 new_base_branch, tmp_branch, repo, create_backup);
10644 done:
10645 free(cwd);
10646 free(committer);
10647 free(gitconfig_path);
10648 got_object_id_queue_free(&commits);
10649 free(branch_head_commit_id);
10650 free(resume_commit_id);
10651 free(head_commit_id);
10652 free(yca_id);
10653 if (commit)
10654 got_object_commit_close(commit);
10655 if (branch)
10656 got_ref_close(branch);
10657 if (new_base_branch)
10658 got_ref_close(new_base_branch);
10659 if (tmp_branch)
10660 got_ref_close(tmp_branch);
10661 if (head_ref)
10662 got_ref_close(head_ref);
10663 if (worktree)
10664 got_worktree_close(worktree);
10665 if (repo) {
10666 const struct got_error *close_err = got_repo_close(repo);
10667 if (error == NULL)
10668 error = close_err;
10670 if (pack_fds) {
10671 const struct got_error *pack_err =
10672 got_repo_pack_fds_close(pack_fds);
10673 if (error == NULL)
10674 error = pack_err;
10676 return error;
10679 __dead static void
10680 usage_histedit(void)
10682 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10683 "[branch]\n", getprogname());
10684 exit(1);
10687 #define GOT_HISTEDIT_PICK 'p'
10688 #define GOT_HISTEDIT_EDIT 'e'
10689 #define GOT_HISTEDIT_FOLD 'f'
10690 #define GOT_HISTEDIT_DROP 'd'
10691 #define GOT_HISTEDIT_MESG 'm'
10693 static const struct got_histedit_cmd {
10694 unsigned char code;
10695 const char *name;
10696 const char *desc;
10697 } got_histedit_cmds[] = {
10698 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10699 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10700 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10701 "be used" },
10702 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10703 { GOT_HISTEDIT_MESG, "mesg",
10704 "single-line log message for commit above (open editor if empty)" },
10707 struct got_histedit_list_entry {
10708 TAILQ_ENTRY(got_histedit_list_entry) entry;
10709 struct got_object_id *commit_id;
10710 const struct got_histedit_cmd *cmd;
10711 char *logmsg;
10713 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10715 static const struct got_error *
10716 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10717 FILE *f, struct got_repository *repo)
10719 const struct got_error *err = NULL;
10720 char *logmsg = NULL, *id_str = NULL;
10721 struct got_commit_object *commit = NULL;
10722 int n;
10724 err = got_object_open_as_commit(&commit, repo, commit_id);
10725 if (err)
10726 goto done;
10728 err = get_short_logmsg(&logmsg, 34, commit);
10729 if (err)
10730 goto done;
10732 err = got_object_id_str(&id_str, commit_id);
10733 if (err)
10734 goto done;
10736 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10737 if (n < 0)
10738 err = got_ferror(f, GOT_ERR_IO);
10739 done:
10740 if (commit)
10741 got_object_commit_close(commit);
10742 free(id_str);
10743 free(logmsg);
10744 return err;
10747 static const struct got_error *
10748 histedit_write_commit_list(struct got_object_id_queue *commits,
10749 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10750 struct got_repository *repo)
10752 const struct got_error *err = NULL;
10753 struct got_object_qid *qid;
10754 const char *histedit_cmd = NULL;
10756 if (STAILQ_EMPTY(commits))
10757 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10759 STAILQ_FOREACH(qid, commits, entry) {
10760 histedit_cmd = got_histedit_cmds[0].name;
10761 if (edit_only)
10762 histedit_cmd = "edit";
10763 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10764 histedit_cmd = "fold";
10765 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10766 if (err)
10767 break;
10768 if (edit_logmsg_only) {
10769 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10770 if (n < 0) {
10771 err = got_ferror(f, GOT_ERR_IO);
10772 break;
10777 return err;
10780 static const struct got_error *
10781 write_cmd_list(FILE *f, const char *branch_name,
10782 struct got_object_id_queue *commits)
10784 const struct got_error *err = NULL;
10785 size_t i;
10786 int n;
10787 char *id_str;
10788 struct got_object_qid *qid;
10790 qid = STAILQ_FIRST(commits);
10791 err = got_object_id_str(&id_str, &qid->id);
10792 if (err)
10793 return err;
10795 n = fprintf(f,
10796 "# Editing the history of branch '%s' starting at\n"
10797 "# commit %s\n"
10798 "# Commits will be processed in order from top to "
10799 "bottom of this file.\n", branch_name, id_str);
10800 if (n < 0) {
10801 err = got_ferror(f, GOT_ERR_IO);
10802 goto done;
10805 n = fprintf(f, "# Available histedit commands:\n");
10806 if (n < 0) {
10807 err = got_ferror(f, GOT_ERR_IO);
10808 goto done;
10811 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10812 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10813 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10814 cmd->desc);
10815 if (n < 0) {
10816 err = got_ferror(f, GOT_ERR_IO);
10817 break;
10820 done:
10821 free(id_str);
10822 return err;
10825 static const struct got_error *
10826 histedit_syntax_error(int lineno)
10828 static char msg[42];
10829 int ret;
10831 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10832 lineno);
10833 if (ret < 0 || (size_t)ret >= sizeof(msg))
10834 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10836 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10839 static const struct got_error *
10840 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10841 char *logmsg, struct got_repository *repo)
10843 const struct got_error *err;
10844 struct got_commit_object *folded_commit = NULL;
10845 char *id_str, *folded_logmsg = NULL;
10847 err = got_object_id_str(&id_str, hle->commit_id);
10848 if (err)
10849 return err;
10851 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10852 if (err)
10853 goto done;
10855 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10856 if (err)
10857 goto done;
10858 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10859 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10860 folded_logmsg) == -1) {
10861 err = got_error_from_errno("asprintf");
10863 done:
10864 if (folded_commit)
10865 got_object_commit_close(folded_commit);
10866 free(id_str);
10867 free(folded_logmsg);
10868 return err;
10871 static struct got_histedit_list_entry *
10872 get_folded_commits(struct got_histedit_list_entry *hle)
10874 struct got_histedit_list_entry *prev, *folded = NULL;
10876 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10877 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10878 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10879 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10880 folded = prev;
10881 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10884 return folded;
10887 static const struct got_error *
10888 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10889 struct got_repository *repo)
10891 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10892 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10893 const struct got_error *err = NULL;
10894 struct got_commit_object *commit = NULL;
10895 int logmsg_len;
10896 int fd;
10897 struct got_histedit_list_entry *folded = NULL;
10899 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10900 if (err)
10901 return err;
10903 folded = get_folded_commits(hle);
10904 if (folded) {
10905 while (folded != hle) {
10906 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10907 folded = TAILQ_NEXT(folded, entry);
10908 continue;
10910 err = append_folded_commit_msg(&new_msg, folded,
10911 logmsg, repo);
10912 if (err)
10913 goto done;
10914 free(logmsg);
10915 logmsg = new_msg;
10916 folded = TAILQ_NEXT(folded, entry);
10920 err = got_object_id_str(&id_str, hle->commit_id);
10921 if (err)
10922 goto done;
10923 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10924 if (err)
10925 goto done;
10926 logmsg_len = asprintf(&new_msg,
10927 "%s\n# original log message of commit %s: %s",
10928 logmsg ? logmsg : "", id_str, orig_logmsg);
10929 if (logmsg_len == -1) {
10930 err = got_error_from_errno("asprintf");
10931 goto done;
10933 free(logmsg);
10934 logmsg = new_msg;
10936 err = got_object_id_str(&id_str, hle->commit_id);
10937 if (err)
10938 goto done;
10940 err = got_opentemp_named_fd(&logmsg_path, &fd,
10941 GOT_TMPDIR_STR "/got-logmsg", "");
10942 if (err)
10943 goto done;
10945 write(fd, logmsg, logmsg_len);
10946 close(fd);
10948 err = get_editor(&editor);
10949 if (err)
10950 goto done;
10952 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10953 logmsg_len, 0);
10954 if (err) {
10955 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10956 goto done;
10957 err = NULL;
10958 hle->logmsg = strdup(new_msg);
10959 if (hle->logmsg == NULL)
10960 err = got_error_from_errno("strdup");
10962 done:
10963 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10964 err = got_error_from_errno2("unlink", logmsg_path);
10965 free(logmsg_path);
10966 free(logmsg);
10967 free(orig_logmsg);
10968 free(editor);
10969 if (commit)
10970 got_object_commit_close(commit);
10971 return err;
10974 static const struct got_error *
10975 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10976 FILE *f, struct got_repository *repo)
10978 const struct got_error *err = NULL;
10979 char *line = NULL, *p, *end;
10980 size_t i, size;
10981 ssize_t len;
10982 int lineno = 0, lastcmd = -1;
10983 const struct got_histedit_cmd *cmd;
10984 struct got_object_id *commit_id = NULL;
10985 struct got_histedit_list_entry *hle = NULL;
10987 for (;;) {
10988 len = getline(&line, &size, f);
10989 if (len == -1) {
10990 const struct got_error *getline_err;
10991 if (feof(f))
10992 break;
10993 getline_err = got_error_from_errno("getline");
10994 err = got_ferror(f, getline_err->code);
10995 break;
10997 lineno++;
10998 p = line;
10999 while (isspace((unsigned char)p[0]))
11000 p++;
11001 if (p[0] == '#' || p[0] == '\0') {
11002 free(line);
11003 line = NULL;
11004 continue;
11006 cmd = NULL;
11007 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11008 cmd = &got_histedit_cmds[i];
11009 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11010 isspace((unsigned char)p[strlen(cmd->name)])) {
11011 p += strlen(cmd->name);
11012 break;
11014 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11015 p++;
11016 break;
11019 if (i == nitems(got_histedit_cmds)) {
11020 err = histedit_syntax_error(lineno);
11021 break;
11023 while (isspace((unsigned char)p[0]))
11024 p++;
11025 if (cmd->code == GOT_HISTEDIT_MESG) {
11026 if (lastcmd != GOT_HISTEDIT_PICK &&
11027 lastcmd != GOT_HISTEDIT_EDIT) {
11028 err = got_error(GOT_ERR_HISTEDIT_CMD);
11029 break;
11031 if (p[0] == '\0') {
11032 err = histedit_edit_logmsg(hle, repo);
11033 if (err)
11034 break;
11035 } else {
11036 hle->logmsg = strdup(p);
11037 if (hle->logmsg == NULL) {
11038 err = got_error_from_errno("strdup");
11039 break;
11042 free(line);
11043 line = NULL;
11044 lastcmd = cmd->code;
11045 continue;
11046 } else {
11047 end = p;
11048 while (end[0] && !isspace((unsigned char)end[0]))
11049 end++;
11050 *end = '\0';
11052 err = got_object_resolve_id_str(&commit_id, repo, p);
11053 if (err) {
11054 /* override error code */
11055 err = histedit_syntax_error(lineno);
11056 break;
11059 hle = malloc(sizeof(*hle));
11060 if (hle == NULL) {
11061 err = got_error_from_errno("malloc");
11062 break;
11064 hle->cmd = cmd;
11065 hle->commit_id = commit_id;
11066 hle->logmsg = NULL;
11067 commit_id = NULL;
11068 free(line);
11069 line = NULL;
11070 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11071 lastcmd = cmd->code;
11074 free(line);
11075 free(commit_id);
11076 return err;
11079 static const struct got_error *
11080 histedit_check_script(struct got_histedit_list *histedit_cmds,
11081 struct got_object_id_queue *commits, struct got_repository *repo)
11083 const struct got_error *err = NULL;
11084 struct got_object_qid *qid;
11085 struct got_histedit_list_entry *hle;
11086 static char msg[92];
11087 char *id_str;
11089 if (TAILQ_EMPTY(histedit_cmds))
11090 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11091 "histedit script contains no commands");
11092 if (STAILQ_EMPTY(commits))
11093 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11095 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11096 struct got_histedit_list_entry *hle2;
11097 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11098 if (hle == hle2)
11099 continue;
11100 if (got_object_id_cmp(hle->commit_id,
11101 hle2->commit_id) != 0)
11102 continue;
11103 err = got_object_id_str(&id_str, hle->commit_id);
11104 if (err)
11105 return err;
11106 snprintf(msg, sizeof(msg), "commit %s is listed "
11107 "more than once in histedit script", id_str);
11108 free(id_str);
11109 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11113 STAILQ_FOREACH(qid, commits, entry) {
11114 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11115 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11116 break;
11118 if (hle == NULL) {
11119 err = got_object_id_str(&id_str, &qid->id);
11120 if (err)
11121 return err;
11122 snprintf(msg, sizeof(msg),
11123 "commit %s missing from histedit script", id_str);
11124 free(id_str);
11125 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11129 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11130 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11131 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11132 "last commit in histedit script cannot be folded");
11134 return NULL;
11137 static const struct got_error *
11138 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11139 const char *path, struct got_object_id_queue *commits,
11140 struct got_repository *repo)
11142 const struct got_error *err = NULL;
11143 char *editor;
11144 FILE *f = NULL;
11146 err = get_editor(&editor);
11147 if (err)
11148 return err;
11150 if (spawn_editor(editor, path) == -1) {
11151 err = got_error_from_errno("failed spawning editor");
11152 goto done;
11155 f = fopen(path, "re");
11156 if (f == NULL) {
11157 err = got_error_from_errno("fopen");
11158 goto done;
11160 err = histedit_parse_list(histedit_cmds, f, repo);
11161 if (err)
11162 goto done;
11164 err = histedit_check_script(histedit_cmds, commits, repo);
11165 done:
11166 if (f && fclose(f) == EOF && err == NULL)
11167 err = got_error_from_errno("fclose");
11168 free(editor);
11169 return err;
11172 static const struct got_error *
11173 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11174 struct got_object_id_queue *, const char *, const char *,
11175 struct got_repository *);
11177 static const struct got_error *
11178 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11179 struct got_object_id_queue *commits, const char *branch_name,
11180 int edit_logmsg_only, int fold_only, int edit_only,
11181 struct got_repository *repo)
11183 const struct got_error *err;
11184 FILE *f = NULL;
11185 char *path = NULL;
11187 err = got_opentemp_named(&path, &f, "got-histedit", "");
11188 if (err)
11189 return err;
11191 err = write_cmd_list(f, branch_name, commits);
11192 if (err)
11193 goto done;
11195 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11196 fold_only, edit_only, repo);
11197 if (err)
11198 goto done;
11200 if (edit_logmsg_only || fold_only || edit_only) {
11201 rewind(f);
11202 err = histedit_parse_list(histedit_cmds, f, repo);
11203 } else {
11204 if (fclose(f) == EOF) {
11205 err = got_error_from_errno("fclose");
11206 goto done;
11208 f = NULL;
11209 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11210 if (err) {
11211 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11212 err->code != GOT_ERR_HISTEDIT_CMD)
11213 goto done;
11214 err = histedit_edit_list_retry(histedit_cmds, err,
11215 commits, path, branch_name, repo);
11218 done:
11219 if (f && fclose(f) == EOF && err == NULL)
11220 err = got_error_from_errno("fclose");
11221 if (path && unlink(path) != 0 && err == NULL)
11222 err = got_error_from_errno2("unlink", path);
11223 free(path);
11224 return err;
11227 static const struct got_error *
11228 histedit_save_list(struct got_histedit_list *histedit_cmds,
11229 struct got_worktree *worktree, struct got_repository *repo)
11231 const struct got_error *err = NULL;
11232 char *path = NULL;
11233 FILE *f = NULL;
11234 struct got_histedit_list_entry *hle;
11235 struct got_commit_object *commit = NULL;
11237 err = got_worktree_get_histedit_script_path(&path, worktree);
11238 if (err)
11239 return err;
11241 f = fopen(path, "we");
11242 if (f == NULL) {
11243 err = got_error_from_errno2("fopen", path);
11244 goto done;
11246 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11247 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11248 repo);
11249 if (err)
11250 break;
11252 if (hle->logmsg) {
11253 int n = fprintf(f, "%c %s\n",
11254 GOT_HISTEDIT_MESG, hle->logmsg);
11255 if (n < 0) {
11256 err = got_ferror(f, GOT_ERR_IO);
11257 break;
11261 done:
11262 if (f && fclose(f) == EOF && err == NULL)
11263 err = got_error_from_errno("fclose");
11264 free(path);
11265 if (commit)
11266 got_object_commit_close(commit);
11267 return err;
11270 static void
11271 histedit_free_list(struct got_histedit_list *histedit_cmds)
11273 struct got_histedit_list_entry *hle;
11275 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11276 TAILQ_REMOVE(histedit_cmds, hle, entry);
11277 free(hle);
11281 static const struct got_error *
11282 histedit_load_list(struct got_histedit_list *histedit_cmds,
11283 const char *path, struct got_repository *repo)
11285 const struct got_error *err = NULL;
11286 FILE *f = NULL;
11288 f = fopen(path, "re");
11289 if (f == NULL) {
11290 err = got_error_from_errno2("fopen", path);
11291 goto done;
11294 err = histedit_parse_list(histedit_cmds, f, repo);
11295 done:
11296 if (f && fclose(f) == EOF && err == NULL)
11297 err = got_error_from_errno("fclose");
11298 return err;
11301 static const struct got_error *
11302 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11303 const struct got_error *edit_err, struct got_object_id_queue *commits,
11304 const char *path, const char *branch_name, struct got_repository *repo)
11306 const struct got_error *err = NULL, *prev_err = edit_err;
11307 int resp = ' ';
11309 while (resp != 'c' && resp != 'r' && resp != 'a') {
11310 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11311 "or (a)bort: ", getprogname(), prev_err->msg);
11312 resp = getchar();
11313 if (resp == '\n')
11314 resp = getchar();
11315 if (resp == 'c') {
11316 histedit_free_list(histedit_cmds);
11317 err = histedit_run_editor(histedit_cmds, path, commits,
11318 repo);
11319 if (err) {
11320 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11321 err->code != GOT_ERR_HISTEDIT_CMD)
11322 break;
11323 prev_err = err;
11324 resp = ' ';
11325 continue;
11327 break;
11328 } else if (resp == 'r') {
11329 histedit_free_list(histedit_cmds);
11330 err = histedit_edit_script(histedit_cmds,
11331 commits, branch_name, 0, 0, 0, repo);
11332 if (err) {
11333 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11334 err->code != GOT_ERR_HISTEDIT_CMD)
11335 break;
11336 prev_err = err;
11337 resp = ' ';
11338 continue;
11340 break;
11341 } else if (resp == 'a') {
11342 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11343 break;
11344 } else
11345 printf("invalid response '%c'\n", resp);
11348 return err;
11351 static const struct got_error *
11352 histedit_complete(struct got_worktree *worktree,
11353 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11354 struct got_reference *branch, struct got_repository *repo)
11356 printf("Switching work tree to %s\n",
11357 got_ref_get_symref_target(branch));
11358 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11359 branch, repo);
11362 static const struct got_error *
11363 show_histedit_progress(struct got_commit_object *commit,
11364 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11366 const struct got_error *err;
11367 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11369 err = got_object_id_str(&old_id_str, hle->commit_id);
11370 if (err)
11371 goto done;
11373 if (new_id) {
11374 err = got_object_id_str(&new_id_str, new_id);
11375 if (err)
11376 goto done;
11379 old_id_str[12] = '\0';
11380 if (new_id_str)
11381 new_id_str[12] = '\0';
11383 if (hle->logmsg) {
11384 logmsg = strdup(hle->logmsg);
11385 if (logmsg == NULL) {
11386 err = got_error_from_errno("strdup");
11387 goto done;
11389 trim_logmsg(logmsg, 42);
11390 } else {
11391 err = get_short_logmsg(&logmsg, 42, commit);
11392 if (err)
11393 goto done;
11396 switch (hle->cmd->code) {
11397 case GOT_HISTEDIT_PICK:
11398 case GOT_HISTEDIT_EDIT:
11399 printf("%s -> %s: %s\n", old_id_str,
11400 new_id_str ? new_id_str : "no-op change", logmsg);
11401 break;
11402 case GOT_HISTEDIT_DROP:
11403 case GOT_HISTEDIT_FOLD:
11404 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11405 logmsg);
11406 break;
11407 default:
11408 break;
11410 done:
11411 free(old_id_str);
11412 free(new_id_str);
11413 return err;
11416 static const struct got_error *
11417 histedit_commit(struct got_pathlist_head *merged_paths,
11418 struct got_worktree *worktree, struct got_fileindex *fileindex,
11419 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11420 const char *committer, struct got_repository *repo)
11422 const struct got_error *err;
11423 struct got_commit_object *commit;
11424 struct got_object_id *new_commit_id;
11426 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11427 && hle->logmsg == NULL) {
11428 err = histedit_edit_logmsg(hle, repo);
11429 if (err)
11430 return err;
11433 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11434 if (err)
11435 return err;
11437 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11438 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11439 hle->logmsg, repo);
11440 if (err) {
11441 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11442 goto done;
11443 err = show_histedit_progress(commit, hle, NULL);
11444 } else {
11445 err = show_histedit_progress(commit, hle, new_commit_id);
11446 free(new_commit_id);
11448 done:
11449 got_object_commit_close(commit);
11450 return err;
11453 static const struct got_error *
11454 histedit_skip_commit(struct got_histedit_list_entry *hle,
11455 struct got_worktree *worktree, struct got_repository *repo)
11457 const struct got_error *error;
11458 struct got_commit_object *commit;
11460 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11461 repo);
11462 if (error)
11463 return error;
11465 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11466 if (error)
11467 return error;
11469 error = show_histedit_progress(commit, hle, NULL);
11470 got_object_commit_close(commit);
11471 return error;
11474 static const struct got_error *
11475 check_local_changes(void *arg, unsigned char status,
11476 unsigned char staged_status, const char *path,
11477 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11478 struct got_object_id *commit_id, int dirfd, const char *de_name)
11480 int *have_local_changes = arg;
11482 switch (status) {
11483 case GOT_STATUS_ADD:
11484 case GOT_STATUS_DELETE:
11485 case GOT_STATUS_MODIFY:
11486 case GOT_STATUS_CONFLICT:
11487 *have_local_changes = 1;
11488 return got_error(GOT_ERR_CANCELLED);
11489 default:
11490 break;
11493 switch (staged_status) {
11494 case GOT_STATUS_ADD:
11495 case GOT_STATUS_DELETE:
11496 case GOT_STATUS_MODIFY:
11497 *have_local_changes = 1;
11498 return got_error(GOT_ERR_CANCELLED);
11499 default:
11500 break;
11503 return NULL;
11506 static const struct got_error *
11507 cmd_histedit(int argc, char *argv[])
11509 const struct got_error *error = NULL;
11510 struct got_worktree *worktree = NULL;
11511 struct got_fileindex *fileindex = NULL;
11512 struct got_repository *repo = NULL;
11513 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11514 struct got_reference *branch = NULL;
11515 struct got_reference *tmp_branch = NULL;
11516 struct got_object_id *resume_commit_id = NULL;
11517 struct got_object_id *base_commit_id = NULL;
11518 struct got_object_id *head_commit_id = NULL;
11519 struct got_commit_object *commit = NULL;
11520 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11521 struct got_update_progress_arg upa;
11522 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11523 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11524 int list_backups = 0, delete_backups = 0;
11525 const char *edit_script_path = NULL;
11526 struct got_object_id_queue commits;
11527 struct got_pathlist_head merged_paths;
11528 const struct got_object_id_queue *parent_ids;
11529 struct got_object_qid *pid;
11530 struct got_histedit_list histedit_cmds;
11531 struct got_histedit_list_entry *hle;
11532 int *pack_fds = NULL;
11534 STAILQ_INIT(&commits);
11535 TAILQ_INIT(&histedit_cmds);
11536 TAILQ_INIT(&merged_paths);
11537 memset(&upa, 0, sizeof(upa));
11539 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11540 switch (ch) {
11541 case 'a':
11542 abort_edit = 1;
11543 break;
11544 case 'c':
11545 continue_edit = 1;
11546 break;
11547 case 'e':
11548 edit_only = 1;
11549 break;
11550 case 'F':
11551 edit_script_path = optarg;
11552 break;
11553 case 'f':
11554 fold_only = 1;
11555 break;
11556 case 'l':
11557 list_backups = 1;
11558 break;
11559 case 'm':
11560 edit_logmsg_only = 1;
11561 break;
11562 case 'X':
11563 delete_backups = 1;
11564 break;
11565 default:
11566 usage_histedit();
11567 /* NOTREACHED */
11571 argc -= optind;
11572 argv += optind;
11574 #ifndef PROFILE
11575 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11576 "unveil", NULL) == -1)
11577 err(1, "pledge");
11578 #endif
11579 if (abort_edit && continue_edit)
11580 option_conflict('a', 'c');
11581 if (edit_script_path && edit_logmsg_only)
11582 option_conflict('F', 'm');
11583 if (abort_edit && edit_logmsg_only)
11584 option_conflict('a', 'm');
11585 if (continue_edit && edit_logmsg_only)
11586 option_conflict('c', 'm');
11587 if (abort_edit && fold_only)
11588 option_conflict('a', 'f');
11589 if (continue_edit && fold_only)
11590 option_conflict('c', 'f');
11591 if (fold_only && edit_logmsg_only)
11592 option_conflict('f', 'm');
11593 if (edit_script_path && fold_only)
11594 option_conflict('F', 'f');
11595 if (abort_edit && edit_only)
11596 option_conflict('a', 'e');
11597 if (continue_edit && edit_only)
11598 option_conflict('c', 'e');
11599 if (edit_only && edit_logmsg_only)
11600 option_conflict('e', 'm');
11601 if (edit_script_path && edit_only)
11602 option_conflict('F', 'e');
11603 if (list_backups) {
11604 if (abort_edit)
11605 option_conflict('l', 'a');
11606 if (continue_edit)
11607 option_conflict('l', 'c');
11608 if (edit_script_path)
11609 option_conflict('l', 'F');
11610 if (edit_logmsg_only)
11611 option_conflict('l', 'm');
11612 if (fold_only)
11613 option_conflict('l', 'f');
11614 if (edit_only)
11615 option_conflict('l', 'e');
11616 if (delete_backups)
11617 option_conflict('l', 'X');
11618 if (argc != 0 && argc != 1)
11619 usage_histedit();
11620 } else if (delete_backups) {
11621 if (abort_edit)
11622 option_conflict('X', 'a');
11623 if (continue_edit)
11624 option_conflict('X', 'c');
11625 if (edit_script_path)
11626 option_conflict('X', 'F');
11627 if (edit_logmsg_only)
11628 option_conflict('X', 'm');
11629 if (fold_only)
11630 option_conflict('X', 'f');
11631 if (edit_only)
11632 option_conflict('X', 'e');
11633 if (list_backups)
11634 option_conflict('X', 'l');
11635 if (argc != 0 && argc != 1)
11636 usage_histedit();
11637 } else if (argc != 0)
11638 usage_histedit();
11641 * This command cannot apply unveil(2) in all cases because the
11642 * user may choose to run an editor to edit the histedit script
11643 * and to edit individual commit log messages.
11644 * unveil(2) traverses exec(2); if an editor is used we have to
11645 * apply unveil after edit script and log messages have been written.
11646 * XXX TODO: Make use of unveil(2) where possible.
11649 cwd = getcwd(NULL, 0);
11650 if (cwd == NULL) {
11651 error = got_error_from_errno("getcwd");
11652 goto done;
11655 error = got_repo_pack_fds_open(&pack_fds);
11656 if (error != NULL)
11657 goto done;
11659 error = got_worktree_open(&worktree, cwd);
11660 if (error) {
11661 if (list_backups || delete_backups) {
11662 if (error->code != GOT_ERR_NOT_WORKTREE)
11663 goto done;
11664 } else {
11665 if (error->code == GOT_ERR_NOT_WORKTREE)
11666 error = wrap_not_worktree_error(error,
11667 "histedit", cwd);
11668 goto done;
11672 if (list_backups || delete_backups) {
11673 error = got_repo_open(&repo,
11674 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11675 NULL, pack_fds);
11676 if (error != NULL)
11677 goto done;
11678 error = apply_unveil(got_repo_get_path(repo), 0,
11679 worktree ? got_worktree_get_root_path(worktree) : NULL);
11680 if (error)
11681 goto done;
11682 error = process_backup_refs(
11683 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11684 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11685 goto done; /* nothing else to do */
11688 error = get_gitconfig_path(&gitconfig_path);
11689 if (error)
11690 goto done;
11691 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11692 gitconfig_path, pack_fds);
11693 if (error != NULL)
11694 goto done;
11696 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11697 if (error)
11698 goto done;
11699 if (rebase_in_progress) {
11700 error = got_error(GOT_ERR_REBASING);
11701 goto done;
11704 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11705 repo);
11706 if (error)
11707 goto done;
11708 if (merge_in_progress) {
11709 error = got_error(GOT_ERR_MERGE_BUSY);
11710 goto done;
11713 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11714 if (error)
11715 goto done;
11717 if (edit_in_progress && edit_logmsg_only) {
11718 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11719 "histedit operation is in progress in this "
11720 "work tree and must be continued or aborted "
11721 "before the -m option can be used");
11722 goto done;
11724 if (edit_in_progress && fold_only) {
11725 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11726 "histedit operation is in progress in this "
11727 "work tree and must be continued or aborted "
11728 "before the -f option can be used");
11729 goto done;
11731 if (edit_in_progress && edit_only) {
11732 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11733 "histedit operation is in progress in this "
11734 "work tree and must be continued or aborted "
11735 "before the -e option can be used");
11736 goto done;
11739 if (edit_in_progress && abort_edit) {
11740 error = got_worktree_histedit_continue(&resume_commit_id,
11741 &tmp_branch, &branch, &base_commit_id, &fileindex,
11742 worktree, repo);
11743 if (error)
11744 goto done;
11745 printf("Switching work tree to %s\n",
11746 got_ref_get_symref_target(branch));
11747 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11748 branch, base_commit_id, abort_progress, &upa);
11749 if (error)
11750 goto done;
11751 printf("Histedit of %s aborted\n",
11752 got_ref_get_symref_target(branch));
11753 print_merge_progress_stats(&upa);
11754 goto done; /* nothing else to do */
11755 } else if (abort_edit) {
11756 error = got_error(GOT_ERR_NOT_HISTEDIT);
11757 goto done;
11760 error = get_author(&committer, repo, worktree);
11761 if (error)
11762 goto done;
11764 if (continue_edit) {
11765 char *path;
11767 if (!edit_in_progress) {
11768 error = got_error(GOT_ERR_NOT_HISTEDIT);
11769 goto done;
11772 error = got_worktree_get_histedit_script_path(&path, worktree);
11773 if (error)
11774 goto done;
11776 error = histedit_load_list(&histedit_cmds, path, repo);
11777 free(path);
11778 if (error)
11779 goto done;
11781 error = got_worktree_histedit_continue(&resume_commit_id,
11782 &tmp_branch, &branch, &base_commit_id, &fileindex,
11783 worktree, repo);
11784 if (error)
11785 goto done;
11787 error = got_ref_resolve(&head_commit_id, repo, branch);
11788 if (error)
11789 goto done;
11791 error = got_object_open_as_commit(&commit, repo,
11792 head_commit_id);
11793 if (error)
11794 goto done;
11795 parent_ids = got_object_commit_get_parent_ids(commit);
11796 pid = STAILQ_FIRST(parent_ids);
11797 if (pid == NULL) {
11798 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11799 goto done;
11801 error = collect_commits(&commits, head_commit_id, &pid->id,
11802 base_commit_id, got_worktree_get_path_prefix(worktree),
11803 GOT_ERR_HISTEDIT_PATH, repo);
11804 got_object_commit_close(commit);
11805 commit = NULL;
11806 if (error)
11807 goto done;
11808 } else {
11809 if (edit_in_progress) {
11810 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11811 goto done;
11814 error = got_ref_open(&branch, repo,
11815 got_worktree_get_head_ref_name(worktree), 0);
11816 if (error != NULL)
11817 goto done;
11819 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11820 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11821 "will not edit commit history of a branch outside "
11822 "the \"refs/heads/\" reference namespace");
11823 goto done;
11826 error = got_ref_resolve(&head_commit_id, repo, branch);
11827 got_ref_close(branch);
11828 branch = NULL;
11829 if (error)
11830 goto done;
11832 error = got_object_open_as_commit(&commit, repo,
11833 head_commit_id);
11834 if (error)
11835 goto done;
11836 parent_ids = got_object_commit_get_parent_ids(commit);
11837 pid = STAILQ_FIRST(parent_ids);
11838 if (pid == NULL) {
11839 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11840 goto done;
11842 error = collect_commits(&commits, head_commit_id, &pid->id,
11843 got_worktree_get_base_commit_id(worktree),
11844 got_worktree_get_path_prefix(worktree),
11845 GOT_ERR_HISTEDIT_PATH, repo);
11846 got_object_commit_close(commit);
11847 commit = NULL;
11848 if (error)
11849 goto done;
11851 if (STAILQ_EMPTY(&commits)) {
11852 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11853 goto done;
11856 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11857 &base_commit_id, &fileindex, worktree, repo);
11858 if (error)
11859 goto done;
11861 if (edit_script_path) {
11862 error = histedit_load_list(&histedit_cmds,
11863 edit_script_path, repo);
11864 if (error) {
11865 got_worktree_histedit_abort(worktree, fileindex,
11866 repo, branch, base_commit_id,
11867 abort_progress, &upa);
11868 print_merge_progress_stats(&upa);
11869 goto done;
11871 } else {
11872 const char *branch_name;
11873 branch_name = got_ref_get_symref_target(branch);
11874 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11875 branch_name += 11;
11876 error = histedit_edit_script(&histedit_cmds, &commits,
11877 branch_name, edit_logmsg_only, fold_only,
11878 edit_only, repo);
11879 if (error) {
11880 got_worktree_histedit_abort(worktree, fileindex,
11881 repo, branch, base_commit_id,
11882 abort_progress, &upa);
11883 print_merge_progress_stats(&upa);
11884 goto done;
11889 error = histedit_save_list(&histedit_cmds, worktree,
11890 repo);
11891 if (error) {
11892 got_worktree_histedit_abort(worktree, fileindex,
11893 repo, branch, base_commit_id,
11894 abort_progress, &upa);
11895 print_merge_progress_stats(&upa);
11896 goto done;
11901 error = histedit_check_script(&histedit_cmds, &commits, repo);
11902 if (error)
11903 goto done;
11905 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11906 if (resume_commit_id) {
11907 if (got_object_id_cmp(hle->commit_id,
11908 resume_commit_id) != 0)
11909 continue;
11911 resume_commit_id = NULL;
11912 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11913 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11914 error = histedit_skip_commit(hle, worktree,
11915 repo);
11916 if (error)
11917 goto done;
11918 } else {
11919 struct got_pathlist_head paths;
11920 int have_changes = 0;
11922 TAILQ_INIT(&paths);
11923 error = got_pathlist_append(&paths, "", NULL);
11924 if (error)
11925 goto done;
11926 error = got_worktree_status(worktree, &paths,
11927 repo, 0, check_local_changes, &have_changes,
11928 check_cancelled, NULL);
11929 got_pathlist_free(&paths,
11930 GOT_PATHLIST_FREE_NONE);
11931 if (error) {
11932 if (error->code != GOT_ERR_CANCELLED)
11933 goto done;
11934 if (sigint_received || sigpipe_received)
11935 goto done;
11937 if (have_changes) {
11938 error = histedit_commit(NULL, worktree,
11939 fileindex, tmp_branch, hle,
11940 committer, repo);
11941 if (error)
11942 goto done;
11943 } else {
11944 error = got_object_open_as_commit(
11945 &commit, repo, hle->commit_id);
11946 if (error)
11947 goto done;
11948 error = show_histedit_progress(commit,
11949 hle, NULL);
11950 got_object_commit_close(commit);
11951 commit = NULL;
11952 if (error)
11953 goto done;
11956 continue;
11959 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11960 error = histedit_skip_commit(hle, worktree, repo);
11961 if (error)
11962 goto done;
11963 continue;
11966 error = got_object_open_as_commit(&commit, repo,
11967 hle->commit_id);
11968 if (error)
11969 goto done;
11970 parent_ids = got_object_commit_get_parent_ids(commit);
11971 pid = STAILQ_FIRST(parent_ids);
11973 error = got_worktree_histedit_merge_files(&merged_paths,
11974 worktree, fileindex, &pid->id, hle->commit_id, repo,
11975 update_progress, &upa, check_cancelled, NULL);
11976 if (error)
11977 goto done;
11978 got_object_commit_close(commit);
11979 commit = NULL;
11981 print_merge_progress_stats(&upa);
11982 if (upa.conflicts > 0 || upa.missing > 0 ||
11983 upa.not_deleted > 0 || upa.unversioned > 0) {
11984 if (upa.conflicts > 0) {
11985 error = show_rebase_merge_conflict(
11986 hle->commit_id, repo);
11987 if (error)
11988 goto done;
11990 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11991 break;
11994 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11995 char *id_str;
11996 error = got_object_id_str(&id_str, hle->commit_id);
11997 if (error)
11998 goto done;
11999 printf("Stopping histedit for amending commit %s\n",
12000 id_str);
12001 free(id_str);
12002 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12003 error = got_worktree_histedit_postpone(worktree,
12004 fileindex);
12005 goto done;
12008 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12009 error = histedit_skip_commit(hle, worktree, repo);
12010 if (error)
12011 goto done;
12012 continue;
12015 error = histedit_commit(&merged_paths, worktree, fileindex,
12016 tmp_branch, hle, committer, repo);
12017 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12018 if (error)
12019 goto done;
12022 if (upa.conflicts > 0 || upa.missing > 0 ||
12023 upa.not_deleted > 0 || upa.unversioned > 0) {
12024 error = got_worktree_histedit_postpone(worktree, fileindex);
12025 if (error)
12026 goto done;
12027 if (upa.conflicts > 0 && upa.missing == 0 &&
12028 upa.not_deleted == 0 && upa.unversioned == 0) {
12029 error = got_error_msg(GOT_ERR_CONFLICTS,
12030 "conflicts must be resolved before histedit "
12031 "can continue");
12032 } else if (upa.conflicts > 0) {
12033 error = got_error_msg(GOT_ERR_CONFLICTS,
12034 "conflicts must be resolved before histedit "
12035 "can continue; changes destined for some "
12036 "files were not yet merged and should be "
12037 "merged manually if required before the "
12038 "histedit operation is continued");
12039 } else {
12040 error = got_error_msg(GOT_ERR_CONFLICTS,
12041 "changes destined for some files were not "
12042 "yet merged and should be merged manually "
12043 "if required before the histedit operation "
12044 "is continued");
12046 } else
12047 error = histedit_complete(worktree, fileindex, tmp_branch,
12048 branch, repo);
12049 done:
12050 free(cwd);
12051 free(committer);
12052 free(gitconfig_path);
12053 got_object_id_queue_free(&commits);
12054 histedit_free_list(&histedit_cmds);
12055 free(head_commit_id);
12056 free(base_commit_id);
12057 free(resume_commit_id);
12058 if (commit)
12059 got_object_commit_close(commit);
12060 if (branch)
12061 got_ref_close(branch);
12062 if (tmp_branch)
12063 got_ref_close(tmp_branch);
12064 if (worktree)
12065 got_worktree_close(worktree);
12066 if (repo) {
12067 const struct got_error *close_err = got_repo_close(repo);
12068 if (error == NULL)
12069 error = close_err;
12071 if (pack_fds) {
12072 const struct got_error *pack_err =
12073 got_repo_pack_fds_close(pack_fds);
12074 if (error == NULL)
12075 error = pack_err;
12077 return error;
12080 __dead static void
12081 usage_integrate(void)
12083 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12084 exit(1);
12087 static const struct got_error *
12088 cmd_integrate(int argc, char *argv[])
12090 const struct got_error *error = NULL;
12091 struct got_repository *repo = NULL;
12092 struct got_worktree *worktree = NULL;
12093 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12094 const char *branch_arg = NULL;
12095 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12096 struct got_fileindex *fileindex = NULL;
12097 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12098 int ch;
12099 struct got_update_progress_arg upa;
12100 int *pack_fds = NULL;
12102 while ((ch = getopt(argc, argv, "")) != -1) {
12103 switch (ch) {
12104 default:
12105 usage_integrate();
12106 /* NOTREACHED */
12110 argc -= optind;
12111 argv += optind;
12113 if (argc != 1)
12114 usage_integrate();
12115 branch_arg = argv[0];
12116 #ifndef PROFILE
12117 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12118 "unveil", NULL) == -1)
12119 err(1, "pledge");
12120 #endif
12121 cwd = getcwd(NULL, 0);
12122 if (cwd == NULL) {
12123 error = got_error_from_errno("getcwd");
12124 goto done;
12127 error = got_repo_pack_fds_open(&pack_fds);
12128 if (error != NULL)
12129 goto done;
12131 error = got_worktree_open(&worktree, cwd);
12132 if (error) {
12133 if (error->code == GOT_ERR_NOT_WORKTREE)
12134 error = wrap_not_worktree_error(error, "integrate",
12135 cwd);
12136 goto done;
12139 error = check_rebase_or_histedit_in_progress(worktree);
12140 if (error)
12141 goto done;
12143 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12144 NULL, pack_fds);
12145 if (error != NULL)
12146 goto done;
12148 error = apply_unveil(got_repo_get_path(repo), 0,
12149 got_worktree_get_root_path(worktree));
12150 if (error)
12151 goto done;
12153 error = check_merge_in_progress(worktree, repo);
12154 if (error)
12155 goto done;
12157 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12158 error = got_error_from_errno("asprintf");
12159 goto done;
12162 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12163 &base_branch_ref, worktree, refname, repo);
12164 if (error)
12165 goto done;
12167 refname = strdup(got_ref_get_name(branch_ref));
12168 if (refname == NULL) {
12169 error = got_error_from_errno("strdup");
12170 got_worktree_integrate_abort(worktree, fileindex, repo,
12171 branch_ref, base_branch_ref);
12172 goto done;
12174 base_refname = strdup(got_ref_get_name(base_branch_ref));
12175 if (base_refname == NULL) {
12176 error = got_error_from_errno("strdup");
12177 got_worktree_integrate_abort(worktree, fileindex, repo,
12178 branch_ref, base_branch_ref);
12179 goto done;
12181 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12182 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12183 got_worktree_integrate_abort(worktree, fileindex, repo,
12184 branch_ref, base_branch_ref);
12185 goto done;
12188 error = got_ref_resolve(&commit_id, repo, branch_ref);
12189 if (error)
12190 goto done;
12192 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12193 if (error)
12194 goto done;
12196 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12197 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12198 "specified branch has already been integrated");
12199 got_worktree_integrate_abort(worktree, fileindex, repo,
12200 branch_ref, base_branch_ref);
12201 goto done;
12204 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12205 if (error) {
12206 if (error->code == GOT_ERR_ANCESTRY)
12207 error = got_error(GOT_ERR_REBASE_REQUIRED);
12208 got_worktree_integrate_abort(worktree, fileindex, repo,
12209 branch_ref, base_branch_ref);
12210 goto done;
12213 memset(&upa, 0, sizeof(upa));
12214 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12215 branch_ref, base_branch_ref, update_progress, &upa,
12216 check_cancelled, NULL);
12217 if (error)
12218 goto done;
12220 printf("Integrated %s into %s\n", refname, base_refname);
12221 print_update_progress_stats(&upa);
12222 done:
12223 if (repo) {
12224 const struct got_error *close_err = got_repo_close(repo);
12225 if (error == NULL)
12226 error = close_err;
12228 if (worktree)
12229 got_worktree_close(worktree);
12230 if (pack_fds) {
12231 const struct got_error *pack_err =
12232 got_repo_pack_fds_close(pack_fds);
12233 if (error == NULL)
12234 error = pack_err;
12236 free(cwd);
12237 free(base_commit_id);
12238 free(commit_id);
12239 free(refname);
12240 free(base_refname);
12241 return error;
12244 __dead static void
12245 usage_merge(void)
12247 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12248 exit(1);
12251 static const struct got_error *
12252 cmd_merge(int argc, char *argv[])
12254 const struct got_error *error = NULL;
12255 struct got_worktree *worktree = NULL;
12256 struct got_repository *repo = NULL;
12257 struct got_fileindex *fileindex = NULL;
12258 char *cwd = NULL, *id_str = NULL, *author = NULL;
12259 struct got_reference *branch = NULL, *wt_branch = NULL;
12260 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12261 struct got_object_id *wt_branch_tip = NULL;
12262 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12263 int interrupt_merge = 0;
12264 struct got_update_progress_arg upa;
12265 struct got_object_id *merge_commit_id = NULL;
12266 char *branch_name = NULL;
12267 int *pack_fds = NULL;
12269 memset(&upa, 0, sizeof(upa));
12271 while ((ch = getopt(argc, argv, "acn")) != -1) {
12272 switch (ch) {
12273 case 'a':
12274 abort_merge = 1;
12275 break;
12276 case 'c':
12277 continue_merge = 1;
12278 break;
12279 case 'n':
12280 interrupt_merge = 1;
12281 break;
12282 default:
12283 usage_rebase();
12284 /* NOTREACHED */
12288 argc -= optind;
12289 argv += optind;
12291 #ifndef PROFILE
12292 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12293 "unveil", NULL) == -1)
12294 err(1, "pledge");
12295 #endif
12297 if (abort_merge && continue_merge)
12298 option_conflict('a', 'c');
12299 if (abort_merge || continue_merge) {
12300 if (argc != 0)
12301 usage_merge();
12302 } else if (argc != 1)
12303 usage_merge();
12305 cwd = getcwd(NULL, 0);
12306 if (cwd == NULL) {
12307 error = got_error_from_errno("getcwd");
12308 goto done;
12311 error = got_repo_pack_fds_open(&pack_fds);
12312 if (error != NULL)
12313 goto done;
12315 error = got_worktree_open(&worktree, cwd);
12316 if (error) {
12317 if (error->code == GOT_ERR_NOT_WORKTREE)
12318 error = wrap_not_worktree_error(error,
12319 "merge", cwd);
12320 goto done;
12323 error = got_repo_open(&repo,
12324 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12325 pack_fds);
12326 if (error != NULL)
12327 goto done;
12329 error = apply_unveil(got_repo_get_path(repo), 0,
12330 worktree ? got_worktree_get_root_path(worktree) : NULL);
12331 if (error)
12332 goto done;
12334 error = check_rebase_or_histedit_in_progress(worktree);
12335 if (error)
12336 goto done;
12338 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12339 repo);
12340 if (error)
12341 goto done;
12343 if (abort_merge) {
12344 if (!merge_in_progress) {
12345 error = got_error(GOT_ERR_NOT_MERGING);
12346 goto done;
12348 error = got_worktree_merge_continue(&branch_name,
12349 &branch_tip, &fileindex, worktree, repo);
12350 if (error)
12351 goto done;
12352 error = got_worktree_merge_abort(worktree, fileindex, repo,
12353 abort_progress, &upa);
12354 if (error)
12355 goto done;
12356 printf("Merge of %s aborted\n", branch_name);
12357 goto done; /* nothing else to do */
12360 error = get_author(&author, repo, worktree);
12361 if (error)
12362 goto done;
12364 if (continue_merge) {
12365 if (!merge_in_progress) {
12366 error = got_error(GOT_ERR_NOT_MERGING);
12367 goto done;
12369 error = got_worktree_merge_continue(&branch_name,
12370 &branch_tip, &fileindex, worktree, repo);
12371 if (error)
12372 goto done;
12373 } else {
12374 error = got_ref_open(&branch, repo, argv[0], 0);
12375 if (error != NULL)
12376 goto done;
12377 branch_name = strdup(got_ref_get_name(branch));
12378 if (branch_name == NULL) {
12379 error = got_error_from_errno("strdup");
12380 goto done;
12382 error = got_ref_resolve(&branch_tip, repo, branch);
12383 if (error)
12384 goto done;
12387 error = got_ref_open(&wt_branch, repo,
12388 got_worktree_get_head_ref_name(worktree), 0);
12389 if (error)
12390 goto done;
12391 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12392 if (error)
12393 goto done;
12394 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12395 wt_branch_tip, branch_tip, 0, repo,
12396 check_cancelled, NULL);
12397 if (error && error->code != GOT_ERR_ANCESTRY)
12398 goto done;
12400 if (!continue_merge) {
12401 error = check_path_prefix(wt_branch_tip, branch_tip,
12402 got_worktree_get_path_prefix(worktree),
12403 GOT_ERR_MERGE_PATH, repo);
12404 if (error)
12405 goto done;
12406 if (yca_id) {
12407 error = check_same_branch(wt_branch_tip, branch,
12408 yca_id, repo);
12409 if (error) {
12410 if (error->code != GOT_ERR_ANCESTRY)
12411 goto done;
12412 error = NULL;
12413 } else {
12414 static char msg[512];
12415 snprintf(msg, sizeof(msg),
12416 "cannot create a merge commit because "
12417 "%s is based on %s; %s can be integrated "
12418 "with 'got integrate' instead", branch_name,
12419 got_worktree_get_head_ref_name(worktree),
12420 branch_name);
12421 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12422 goto done;
12425 error = got_worktree_merge_prepare(&fileindex, worktree,
12426 branch, repo);
12427 if (error)
12428 goto done;
12430 error = got_worktree_merge_branch(worktree, fileindex,
12431 yca_id, branch_tip, repo, update_progress, &upa,
12432 check_cancelled, NULL);
12433 if (error)
12434 goto done;
12435 print_merge_progress_stats(&upa);
12436 if (!upa.did_something) {
12437 error = got_worktree_merge_abort(worktree, fileindex,
12438 repo, abort_progress, &upa);
12439 if (error)
12440 goto done;
12441 printf("Already up-to-date\n");
12442 goto done;
12446 if (interrupt_merge) {
12447 error = got_worktree_merge_postpone(worktree, fileindex);
12448 if (error)
12449 goto done;
12450 printf("Merge of %s interrupted on request\n", branch_name);
12451 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12452 upa.not_deleted > 0 || upa.unversioned > 0) {
12453 error = got_worktree_merge_postpone(worktree, fileindex);
12454 if (error)
12455 goto done;
12456 if (upa.conflicts > 0 && upa.missing == 0 &&
12457 upa.not_deleted == 0 && upa.unversioned == 0) {
12458 error = got_error_msg(GOT_ERR_CONFLICTS,
12459 "conflicts must be resolved before merging "
12460 "can continue");
12461 } else if (upa.conflicts > 0) {
12462 error = got_error_msg(GOT_ERR_CONFLICTS,
12463 "conflicts must be resolved before merging "
12464 "can continue; changes destined for some "
12465 "files were not yet merged and "
12466 "should be merged manually if required before the "
12467 "merge operation is continued");
12468 } else {
12469 error = got_error_msg(GOT_ERR_CONFLICTS,
12470 "changes destined for some "
12471 "files were not yet merged and should be "
12472 "merged manually if required before the "
12473 "merge operation is continued");
12475 goto done;
12476 } else {
12477 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12478 fileindex, author, NULL, 1, branch_tip, branch_name,
12479 repo, continue_merge ? print_status : NULL, NULL);
12480 if (error)
12481 goto done;
12482 error = got_worktree_merge_complete(worktree, fileindex, repo);
12483 if (error)
12484 goto done;
12485 error = got_object_id_str(&id_str, merge_commit_id);
12486 if (error)
12487 goto done;
12488 printf("Merged %s into %s: %s\n", branch_name,
12489 got_worktree_get_head_ref_name(worktree),
12490 id_str);
12493 done:
12494 free(id_str);
12495 free(merge_commit_id);
12496 free(author);
12497 free(branch_tip);
12498 free(branch_name);
12499 free(yca_id);
12500 if (branch)
12501 got_ref_close(branch);
12502 if (wt_branch)
12503 got_ref_close(wt_branch);
12504 if (worktree)
12505 got_worktree_close(worktree);
12506 if (repo) {
12507 const struct got_error *close_err = got_repo_close(repo);
12508 if (error == NULL)
12509 error = close_err;
12511 if (pack_fds) {
12512 const struct got_error *pack_err =
12513 got_repo_pack_fds_close(pack_fds);
12514 if (error == NULL)
12515 error = pack_err;
12517 return error;
12520 __dead static void
12521 usage_stage(void)
12523 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12524 "[path ...]\n", getprogname());
12525 exit(1);
12528 static const struct got_error *
12529 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12530 const char *path, struct got_object_id *blob_id,
12531 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12532 int dirfd, const char *de_name)
12534 const struct got_error *err = NULL;
12535 char *id_str = NULL;
12537 if (staged_status != GOT_STATUS_ADD &&
12538 staged_status != GOT_STATUS_MODIFY &&
12539 staged_status != GOT_STATUS_DELETE)
12540 return NULL;
12542 if (staged_status == GOT_STATUS_ADD ||
12543 staged_status == GOT_STATUS_MODIFY)
12544 err = got_object_id_str(&id_str, staged_blob_id);
12545 else
12546 err = got_object_id_str(&id_str, blob_id);
12547 if (err)
12548 return err;
12550 printf("%s %c %s\n", id_str, staged_status, path);
12551 free(id_str);
12552 return NULL;
12555 static const struct got_error *
12556 cmd_stage(int argc, char *argv[])
12558 const struct got_error *error = NULL;
12559 struct got_repository *repo = NULL;
12560 struct got_worktree *worktree = NULL;
12561 char *cwd = NULL;
12562 struct got_pathlist_head paths;
12563 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12564 FILE *patch_script_file = NULL;
12565 const char *patch_script_path = NULL;
12566 struct choose_patch_arg cpa;
12567 int *pack_fds = NULL;
12569 TAILQ_INIT(&paths);
12571 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12572 switch (ch) {
12573 case 'F':
12574 patch_script_path = optarg;
12575 break;
12576 case 'l':
12577 list_stage = 1;
12578 break;
12579 case 'p':
12580 pflag = 1;
12581 break;
12582 case 'S':
12583 allow_bad_symlinks = 1;
12584 break;
12585 default:
12586 usage_stage();
12587 /* NOTREACHED */
12591 argc -= optind;
12592 argv += optind;
12594 #ifndef PROFILE
12595 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12596 "unveil", NULL) == -1)
12597 err(1, "pledge");
12598 #endif
12599 if (list_stage && (pflag || patch_script_path))
12600 errx(1, "-l option cannot be used with other options");
12601 if (patch_script_path && !pflag)
12602 errx(1, "-F option can only be used together with -p option");
12604 cwd = getcwd(NULL, 0);
12605 if (cwd == NULL) {
12606 error = got_error_from_errno("getcwd");
12607 goto done;
12610 error = got_repo_pack_fds_open(&pack_fds);
12611 if (error != NULL)
12612 goto done;
12614 error = got_worktree_open(&worktree, cwd);
12615 if (error) {
12616 if (error->code == GOT_ERR_NOT_WORKTREE)
12617 error = wrap_not_worktree_error(error, "stage", cwd);
12618 goto done;
12621 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12622 NULL, pack_fds);
12623 if (error != NULL)
12624 goto done;
12626 if (patch_script_path) {
12627 patch_script_file = fopen(patch_script_path, "re");
12628 if (patch_script_file == NULL) {
12629 error = got_error_from_errno2("fopen",
12630 patch_script_path);
12631 goto done;
12634 error = apply_unveil(got_repo_get_path(repo), 0,
12635 got_worktree_get_root_path(worktree));
12636 if (error)
12637 goto done;
12639 error = check_merge_in_progress(worktree, repo);
12640 if (error)
12641 goto done;
12643 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12644 if (error)
12645 goto done;
12647 if (list_stage)
12648 error = got_worktree_status(worktree, &paths, repo, 0,
12649 print_stage, NULL, check_cancelled, NULL);
12650 else {
12651 cpa.patch_script_file = patch_script_file;
12652 cpa.action = "stage";
12653 error = got_worktree_stage(worktree, &paths,
12654 pflag ? NULL : print_status, NULL,
12655 pflag ? choose_patch : NULL, &cpa,
12656 allow_bad_symlinks, repo);
12658 done:
12659 if (patch_script_file && fclose(patch_script_file) == EOF &&
12660 error == NULL)
12661 error = got_error_from_errno2("fclose", patch_script_path);
12662 if (repo) {
12663 const struct got_error *close_err = got_repo_close(repo);
12664 if (error == NULL)
12665 error = close_err;
12667 if (worktree)
12668 got_worktree_close(worktree);
12669 if (pack_fds) {
12670 const struct got_error *pack_err =
12671 got_repo_pack_fds_close(pack_fds);
12672 if (error == NULL)
12673 error = pack_err;
12675 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12676 free(cwd);
12677 return error;
12680 __dead static void
12681 usage_unstage(void)
12683 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12684 "[path ...]\n", getprogname());
12685 exit(1);
12689 static const struct got_error *
12690 cmd_unstage(int argc, char *argv[])
12692 const struct got_error *error = NULL;
12693 struct got_repository *repo = NULL;
12694 struct got_worktree *worktree = NULL;
12695 char *cwd = NULL;
12696 struct got_pathlist_head paths;
12697 int ch, pflag = 0;
12698 struct got_update_progress_arg upa;
12699 FILE *patch_script_file = NULL;
12700 const char *patch_script_path = NULL;
12701 struct choose_patch_arg cpa;
12702 int *pack_fds = NULL;
12704 TAILQ_INIT(&paths);
12706 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12707 switch (ch) {
12708 case 'F':
12709 patch_script_path = optarg;
12710 break;
12711 case 'p':
12712 pflag = 1;
12713 break;
12714 default:
12715 usage_unstage();
12716 /* NOTREACHED */
12720 argc -= optind;
12721 argv += optind;
12723 #ifndef PROFILE
12724 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12725 "unveil", NULL) == -1)
12726 err(1, "pledge");
12727 #endif
12728 if (patch_script_path && !pflag)
12729 errx(1, "-F option can only be used together with -p option");
12731 cwd = getcwd(NULL, 0);
12732 if (cwd == NULL) {
12733 error = got_error_from_errno("getcwd");
12734 goto done;
12737 error = got_repo_pack_fds_open(&pack_fds);
12738 if (error != NULL)
12739 goto done;
12741 error = got_worktree_open(&worktree, cwd);
12742 if (error) {
12743 if (error->code == GOT_ERR_NOT_WORKTREE)
12744 error = wrap_not_worktree_error(error, "unstage", cwd);
12745 goto done;
12748 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12749 NULL, pack_fds);
12750 if (error != NULL)
12751 goto done;
12753 if (patch_script_path) {
12754 patch_script_file = fopen(patch_script_path, "re");
12755 if (patch_script_file == NULL) {
12756 error = got_error_from_errno2("fopen",
12757 patch_script_path);
12758 goto done;
12762 error = apply_unveil(got_repo_get_path(repo), 0,
12763 got_worktree_get_root_path(worktree));
12764 if (error)
12765 goto done;
12767 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12768 if (error)
12769 goto done;
12771 cpa.patch_script_file = patch_script_file;
12772 cpa.action = "unstage";
12773 memset(&upa, 0, sizeof(upa));
12774 error = got_worktree_unstage(worktree, &paths, update_progress,
12775 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12776 if (!error)
12777 print_merge_progress_stats(&upa);
12778 done:
12779 if (patch_script_file && fclose(patch_script_file) == EOF &&
12780 error == NULL)
12781 error = got_error_from_errno2("fclose", patch_script_path);
12782 if (repo) {
12783 const struct got_error *close_err = got_repo_close(repo);
12784 if (error == NULL)
12785 error = close_err;
12787 if (worktree)
12788 got_worktree_close(worktree);
12789 if (pack_fds) {
12790 const struct got_error *pack_err =
12791 got_repo_pack_fds_close(pack_fds);
12792 if (error == NULL)
12793 error = pack_err;
12795 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12796 free(cwd);
12797 return error;
12800 __dead static void
12801 usage_cat(void)
12803 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12804 "arg ...\n", getprogname());
12805 exit(1);
12808 static const struct got_error *
12809 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12811 const struct got_error *err;
12812 struct got_blob_object *blob;
12813 int fd = -1;
12815 fd = got_opentempfd();
12816 if (fd == -1)
12817 return got_error_from_errno("got_opentempfd");
12819 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12820 if (err)
12821 goto done;
12823 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12824 done:
12825 if (fd != -1 && close(fd) == -1 && err == NULL)
12826 err = got_error_from_errno("close");
12827 if (blob)
12828 got_object_blob_close(blob);
12829 return err;
12832 static const struct got_error *
12833 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12835 const struct got_error *err;
12836 struct got_tree_object *tree;
12837 int nentries, i;
12839 err = got_object_open_as_tree(&tree, repo, id);
12840 if (err)
12841 return err;
12843 nentries = got_object_tree_get_nentries(tree);
12844 for (i = 0; i < nentries; i++) {
12845 struct got_tree_entry *te;
12846 char *id_str;
12847 if (sigint_received || sigpipe_received)
12848 break;
12849 te = got_object_tree_get_entry(tree, i);
12850 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12851 if (err)
12852 break;
12853 fprintf(outfile, "%s %.7o %s\n", id_str,
12854 got_tree_entry_get_mode(te),
12855 got_tree_entry_get_name(te));
12856 free(id_str);
12859 got_object_tree_close(tree);
12860 return err;
12863 static const struct got_error *
12864 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12866 const struct got_error *err;
12867 struct got_commit_object *commit;
12868 const struct got_object_id_queue *parent_ids;
12869 struct got_object_qid *pid;
12870 char *id_str = NULL;
12871 const char *logmsg = NULL;
12872 char gmtoff[6];
12874 err = got_object_open_as_commit(&commit, repo, id);
12875 if (err)
12876 return err;
12878 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12879 if (err)
12880 goto done;
12882 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12883 parent_ids = got_object_commit_get_parent_ids(commit);
12884 fprintf(outfile, "numparents %d\n",
12885 got_object_commit_get_nparents(commit));
12886 STAILQ_FOREACH(pid, parent_ids, entry) {
12887 char *pid_str;
12888 err = got_object_id_str(&pid_str, &pid->id);
12889 if (err)
12890 goto done;
12891 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12892 free(pid_str);
12894 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12895 got_object_commit_get_author_gmtoff(commit));
12896 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12897 got_object_commit_get_author(commit),
12898 (long long)got_object_commit_get_author_time(commit),
12899 gmtoff);
12901 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12902 got_object_commit_get_committer_gmtoff(commit));
12903 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12904 got_object_commit_get_committer(commit),
12905 (long long)got_object_commit_get_committer_time(commit),
12906 gmtoff);
12908 logmsg = got_object_commit_get_logmsg_raw(commit);
12909 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12910 fprintf(outfile, "%s", logmsg);
12911 done:
12912 free(id_str);
12913 got_object_commit_close(commit);
12914 return err;
12917 static const struct got_error *
12918 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12920 const struct got_error *err;
12921 struct got_tag_object *tag;
12922 char *id_str = NULL;
12923 const char *tagmsg = NULL;
12924 char gmtoff[6];
12926 err = got_object_open_as_tag(&tag, repo, id);
12927 if (err)
12928 return err;
12930 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12931 if (err)
12932 goto done;
12934 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12936 switch (got_object_tag_get_object_type(tag)) {
12937 case GOT_OBJ_TYPE_BLOB:
12938 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12939 GOT_OBJ_LABEL_BLOB);
12940 break;
12941 case GOT_OBJ_TYPE_TREE:
12942 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12943 GOT_OBJ_LABEL_TREE);
12944 break;
12945 case GOT_OBJ_TYPE_COMMIT:
12946 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12947 GOT_OBJ_LABEL_COMMIT);
12948 break;
12949 case GOT_OBJ_TYPE_TAG:
12950 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12951 GOT_OBJ_LABEL_TAG);
12952 break;
12953 default:
12954 break;
12957 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12958 got_object_tag_get_name(tag));
12960 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12961 got_object_tag_get_tagger_gmtoff(tag));
12962 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12963 got_object_tag_get_tagger(tag),
12964 (long long)got_object_tag_get_tagger_time(tag),
12965 gmtoff);
12967 tagmsg = got_object_tag_get_message(tag);
12968 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12969 fprintf(outfile, "%s", tagmsg);
12970 done:
12971 free(id_str);
12972 got_object_tag_close(tag);
12973 return err;
12976 static const struct got_error *
12977 cmd_cat(int argc, char *argv[])
12979 const struct got_error *error;
12980 struct got_repository *repo = NULL;
12981 struct got_worktree *worktree = NULL;
12982 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12983 const char *commit_id_str = NULL;
12984 struct got_object_id *id = NULL, *commit_id = NULL;
12985 struct got_commit_object *commit = NULL;
12986 int ch, obj_type, i, force_path = 0;
12987 struct got_reflist_head refs;
12988 int *pack_fds = NULL;
12990 TAILQ_INIT(&refs);
12992 #ifndef PROFILE
12993 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12994 NULL) == -1)
12995 err(1, "pledge");
12996 #endif
12998 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12999 switch (ch) {
13000 case 'c':
13001 commit_id_str = optarg;
13002 break;
13003 case 'P':
13004 force_path = 1;
13005 break;
13006 case 'r':
13007 repo_path = realpath(optarg, NULL);
13008 if (repo_path == NULL)
13009 return got_error_from_errno2("realpath",
13010 optarg);
13011 got_path_strip_trailing_slashes(repo_path);
13012 break;
13013 default:
13014 usage_cat();
13015 /* NOTREACHED */
13019 argc -= optind;
13020 argv += optind;
13022 cwd = getcwd(NULL, 0);
13023 if (cwd == NULL) {
13024 error = got_error_from_errno("getcwd");
13025 goto done;
13028 error = got_repo_pack_fds_open(&pack_fds);
13029 if (error != NULL)
13030 goto done;
13032 if (repo_path == NULL) {
13033 error = got_worktree_open(&worktree, cwd);
13034 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13035 goto done;
13036 if (worktree) {
13037 repo_path = strdup(
13038 got_worktree_get_repo_path(worktree));
13039 if (repo_path == NULL) {
13040 error = got_error_from_errno("strdup");
13041 goto done;
13044 /* Release work tree lock. */
13045 got_worktree_close(worktree);
13046 worktree = NULL;
13050 if (repo_path == NULL) {
13051 repo_path = strdup(cwd);
13052 if (repo_path == NULL)
13053 return got_error_from_errno("strdup");
13056 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13057 free(repo_path);
13058 if (error != NULL)
13059 goto done;
13061 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13062 if (error)
13063 goto done;
13065 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13066 if (error)
13067 goto done;
13069 if (commit_id_str == NULL)
13070 commit_id_str = GOT_REF_HEAD;
13071 error = got_repo_match_object_id(&commit_id, NULL,
13072 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13073 if (error)
13074 goto done;
13076 error = got_object_open_as_commit(&commit, repo, commit_id);
13077 if (error)
13078 goto done;
13080 for (i = 0; i < argc; i++) {
13081 if (force_path) {
13082 error = got_object_id_by_path(&id, repo, commit,
13083 argv[i]);
13084 if (error)
13085 break;
13086 } else {
13087 error = got_repo_match_object_id(&id, &label, argv[i],
13088 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13089 repo);
13090 if (error) {
13091 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13092 error->code != GOT_ERR_NOT_REF)
13093 break;
13094 error = got_object_id_by_path(&id, repo,
13095 commit, argv[i]);
13096 if (error)
13097 break;
13101 error = got_object_get_type(&obj_type, repo, id);
13102 if (error)
13103 break;
13105 switch (obj_type) {
13106 case GOT_OBJ_TYPE_BLOB:
13107 error = cat_blob(id, repo, stdout);
13108 break;
13109 case GOT_OBJ_TYPE_TREE:
13110 error = cat_tree(id, repo, stdout);
13111 break;
13112 case GOT_OBJ_TYPE_COMMIT:
13113 error = cat_commit(id, repo, stdout);
13114 break;
13115 case GOT_OBJ_TYPE_TAG:
13116 error = cat_tag(id, repo, stdout);
13117 break;
13118 default:
13119 error = got_error(GOT_ERR_OBJ_TYPE);
13120 break;
13122 if (error)
13123 break;
13124 free(label);
13125 label = NULL;
13126 free(id);
13127 id = NULL;
13129 done:
13130 free(label);
13131 free(id);
13132 free(commit_id);
13133 if (commit)
13134 got_object_commit_close(commit);
13135 if (worktree)
13136 got_worktree_close(worktree);
13137 if (repo) {
13138 const struct got_error *close_err = got_repo_close(repo);
13139 if (error == NULL)
13140 error = close_err;
13142 if (pack_fds) {
13143 const struct got_error *pack_err =
13144 got_repo_pack_fds_close(pack_fds);
13145 if (error == NULL)
13146 error = pack_err;
13149 got_ref_list_free(&refs);
13150 return error;
13153 __dead static void
13154 usage_info(void)
13156 fprintf(stderr, "usage: %s info [path ...]\n",
13157 getprogname());
13158 exit(1);
13161 static const struct got_error *
13162 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13163 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13164 struct got_object_id *commit_id)
13166 const struct got_error *err = NULL;
13167 char *id_str = NULL;
13168 char datebuf[128];
13169 struct tm mytm, *tm;
13170 struct got_pathlist_head *paths = arg;
13171 struct got_pathlist_entry *pe;
13174 * Clear error indication from any of the path arguments which
13175 * would cause this file index entry to be displayed.
13177 TAILQ_FOREACH(pe, paths, entry) {
13178 if (got_path_cmp(path, pe->path, strlen(path),
13179 pe->path_len) == 0 ||
13180 got_path_is_child(path, pe->path, pe->path_len))
13181 pe->data = NULL; /* no error */
13184 printf(GOT_COMMIT_SEP_STR);
13185 if (S_ISLNK(mode))
13186 printf("symlink: %s\n", path);
13187 else if (S_ISREG(mode)) {
13188 printf("file: %s\n", path);
13189 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13190 } else if (S_ISDIR(mode))
13191 printf("directory: %s\n", path);
13192 else
13193 printf("something: %s\n", path);
13195 tm = localtime_r(&mtime, &mytm);
13196 if (tm == NULL)
13197 return NULL;
13198 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13199 return got_error(GOT_ERR_NO_SPACE);
13200 printf("timestamp: %s\n", datebuf);
13202 if (blob_id) {
13203 err = got_object_id_str(&id_str, blob_id);
13204 if (err)
13205 return err;
13206 printf("based on blob: %s\n", id_str);
13207 free(id_str);
13210 if (staged_blob_id) {
13211 err = got_object_id_str(&id_str, staged_blob_id);
13212 if (err)
13213 return err;
13214 printf("based on staged blob: %s\n", id_str);
13215 free(id_str);
13218 if (commit_id) {
13219 err = got_object_id_str(&id_str, commit_id);
13220 if (err)
13221 return err;
13222 printf("based on commit: %s\n", id_str);
13223 free(id_str);
13226 return NULL;
13229 static const struct got_error *
13230 cmd_info(int argc, char *argv[])
13232 const struct got_error *error = NULL;
13233 struct got_worktree *worktree = NULL;
13234 char *cwd = NULL, *id_str = NULL;
13235 struct got_pathlist_head paths;
13236 char *uuidstr = NULL;
13237 int ch, show_files = 0;
13239 TAILQ_INIT(&paths);
13241 while ((ch = getopt(argc, argv, "")) != -1) {
13242 switch (ch) {
13243 default:
13244 usage_info();
13245 /* NOTREACHED */
13249 argc -= optind;
13250 argv += optind;
13252 #ifndef PROFILE
13253 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13254 NULL) == -1)
13255 err(1, "pledge");
13256 #endif
13257 cwd = getcwd(NULL, 0);
13258 if (cwd == NULL) {
13259 error = got_error_from_errno("getcwd");
13260 goto done;
13263 error = got_worktree_open(&worktree, cwd);
13264 if (error) {
13265 if (error->code == GOT_ERR_NOT_WORKTREE)
13266 error = wrap_not_worktree_error(error, "info", cwd);
13267 goto done;
13270 #ifndef PROFILE
13271 /* Remove "wpath cpath proc exec sendfd" promises. */
13272 if (pledge("stdio rpath flock unveil", NULL) == -1)
13273 err(1, "pledge");
13274 #endif
13275 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13276 if (error)
13277 goto done;
13279 if (argc >= 1) {
13280 error = get_worktree_paths_from_argv(&paths, argc, argv,
13281 worktree);
13282 if (error)
13283 goto done;
13284 show_files = 1;
13287 error = got_object_id_str(&id_str,
13288 got_worktree_get_base_commit_id(worktree));
13289 if (error)
13290 goto done;
13292 error = got_worktree_get_uuid(&uuidstr, worktree);
13293 if (error)
13294 goto done;
13296 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13297 printf("work tree base commit: %s\n", id_str);
13298 printf("work tree path prefix: %s\n",
13299 got_worktree_get_path_prefix(worktree));
13300 printf("work tree branch reference: %s\n",
13301 got_worktree_get_head_ref_name(worktree));
13302 printf("work tree UUID: %s\n", uuidstr);
13303 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13305 if (show_files) {
13306 struct got_pathlist_entry *pe;
13307 TAILQ_FOREACH(pe, &paths, entry) {
13308 if (pe->path_len == 0)
13309 continue;
13311 * Assume this path will fail. This will be corrected
13312 * in print_path_info() in case the path does suceeed.
13314 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13316 error = got_worktree_path_info(worktree, &paths,
13317 print_path_info, &paths, check_cancelled, NULL);
13318 if (error)
13319 goto done;
13320 TAILQ_FOREACH(pe, &paths, entry) {
13321 if (pe->data != NULL) {
13322 const struct got_error *perr;
13324 perr = pe->data;
13325 error = got_error_fmt(perr->code, "%s",
13326 pe->path);
13327 break;
13331 done:
13332 if (worktree)
13333 got_worktree_close(worktree);
13334 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13335 free(cwd);
13336 free(id_str);
13337 free(uuidstr);
13338 return error;