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 char *
713 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
715 const char *got_signer_id = NULL;
716 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
718 if (worktree)
719 worktree_conf = got_worktree_get_gotconfig(worktree);
720 repo_conf = got_repo_get_gotconfig(repo);
722 /*
723 * Priority of potential author information sources, from most
724 * significant to least significant:
725 * 1) work tree's .got/got.conf file
726 * 2) repository's got.conf file
727 */
729 if (worktree_conf)
730 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
731 if (got_signer_id == NULL)
732 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
734 return got_signer_id;
737 static const struct got_error *
738 get_gitconfig_path(char **gitconfig_path)
740 const char *homedir = getenv("HOME");
742 *gitconfig_path = NULL;
743 if (homedir) {
744 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
745 return got_error_from_errno("asprintf");
748 return NULL;
751 static const struct got_error *
752 cmd_import(int argc, char *argv[])
754 const struct got_error *error = NULL;
755 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
756 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
757 const char *branch_name = NULL;
758 char *id_str = NULL, *logmsg_path = NULL;
759 char refname[PATH_MAX] = "refs/heads/";
760 struct got_repository *repo = NULL;
761 struct got_reference *branch_ref = NULL, *head_ref = NULL;
762 struct got_object_id *new_commit_id = NULL;
763 int ch, n = 0;
764 struct got_pathlist_head ignores;
765 struct got_pathlist_entry *pe;
766 int preserve_logmsg = 0;
767 int *pack_fds = NULL;
769 TAILQ_INIT(&ignores);
771 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
772 switch (ch) {
773 case 'b':
774 branch_name = optarg;
775 break;
776 case 'I':
777 if (optarg[0] == '\0')
778 break;
779 error = got_pathlist_insert(&pe, &ignores, optarg,
780 NULL);
781 if (error)
782 goto done;
783 break;
784 case 'm':
785 logmsg = strdup(optarg);
786 if (logmsg == NULL) {
787 error = got_error_from_errno("strdup");
788 goto done;
790 break;
791 case 'r':
792 repo_path = realpath(optarg, NULL);
793 if (repo_path == NULL) {
794 error = got_error_from_errno2("realpath",
795 optarg);
796 goto done;
798 break;
799 default:
800 usage_import();
801 /* NOTREACHED */
805 argc -= optind;
806 argv += optind;
808 #ifndef PROFILE
809 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
810 "unveil",
811 NULL) == -1)
812 err(1, "pledge");
813 #endif
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name && branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
846 if (error && error->code != GOT_ERR_NOT_REF)
847 goto done;
849 if (branch_name)
850 n = strlcat(refname, branch_name, sizeof(refname));
851 else if (head_ref && got_ref_is_symbolic(head_ref))
852 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
853 sizeof(refname));
854 else
855 n = strlcat(refname, "main", sizeof(refname));
856 if (n >= sizeof(refname)) {
857 error = got_error(GOT_ERR_NO_SPACE);
858 goto done;
861 error = got_ref_open(&branch_ref, repo, refname, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF)
864 goto done;
865 } else {
866 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
867 "import target branch already exists");
868 goto done;
871 path_dir = realpath(argv[0], NULL);
872 if (path_dir == NULL) {
873 error = got_error_from_errno2("realpath", argv[0]);
874 goto done;
876 got_path_strip_trailing_slashes(path_dir);
878 /*
879 * unveil(2) traverses exec(2); if an editor is used we have
880 * to apply unveil after the log message has been written.
881 */
882 if (logmsg == NULL || strlen(logmsg) == 0) {
883 error = get_editor(&editor);
884 if (error)
885 goto done;
886 free(logmsg);
887 error = collect_import_msg(&logmsg, &logmsg_path, editor,
888 path_dir, refname);
889 if (error) {
890 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
891 logmsg_path != NULL)
892 preserve_logmsg = 1;
893 goto done;
897 if (unveil(path_dir, "r") != 0) {
898 error = got_error_from_errno2("unveil", path_dir);
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_repo_import(&new_commit_id, path_dir, logmsg,
912 author, &ignores, repo, import_progress, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_write(branch_ref, repo);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_object_id_str(&id_str, new_commit_id);
934 if (error) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
941 if (error) {
942 if (error->code != GOT_ERR_NOT_REF) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
949 branch_ref);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_write(head_ref, repo);
957 if (error) {
958 if (logmsg_path)
959 preserve_logmsg = 1;
960 goto done;
964 printf("Created branch %s with commit %s\n",
965 got_ref_get_name(branch_ref), id_str);
966 done:
967 if (pack_fds) {
968 const struct got_error *pack_err =
969 got_repo_pack_fds_close(pack_fds);
970 if (error == NULL)
971 error = pack_err;
973 if (preserve_logmsg) {
974 fprintf(stderr, "%s: log message preserved in %s\n",
975 getprogname(), logmsg_path);
976 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
977 error = got_error_from_errno2("unlink", logmsg_path);
978 free(logmsg);
979 free(logmsg_path);
980 free(repo_path);
981 free(editor);
982 free(new_commit_id);
983 free(id_str);
984 free(author);
985 free(gitconfig_path);
986 if (branch_ref)
987 got_ref_close(branch_ref);
988 if (head_ref)
989 got_ref_close(head_ref);
990 return error;
993 __dead static void
994 usage_clone(void)
996 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
997 "repository-URL [directory]\n", getprogname());
998 exit(1);
1001 struct got_fetch_progress_arg {
1002 char last_scaled_size[FMT_SCALED_STRSIZE];
1003 int last_p_indexed;
1004 int last_p_resolved;
1005 int verbosity;
1007 struct got_repository *repo;
1009 int create_configs;
1010 int configs_created;
1011 struct {
1012 struct got_pathlist_head *symrefs;
1013 struct got_pathlist_head *wanted_branches;
1014 struct got_pathlist_head *wanted_refs;
1015 const char *proto;
1016 const char *host;
1017 const char *port;
1018 const char *remote_repo_path;
1019 const char *git_url;
1020 int fetch_all_branches;
1021 int mirror_references;
1022 } config_info;
1025 /* XXX forward declaration */
1026 static const struct got_error *
1027 create_config_files(const char *proto, const char *host, const char *port,
1028 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1029 int mirror_references, struct got_pathlist_head *symrefs,
1030 struct got_pathlist_head *wanted_branches,
1031 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1033 static const struct got_error *
1034 fetch_progress(void *arg, const char *message, off_t packfile_size,
1035 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1037 const struct got_error *err = NULL;
1038 struct got_fetch_progress_arg *a = arg;
1039 char scaled_size[FMT_SCALED_STRSIZE];
1040 int p_indexed, p_resolved;
1041 int print_size = 0, print_indexed = 0, print_resolved = 0;
1044 * In order to allow a failed clone to be resumed with 'got fetch'
1045 * we try to create configuration files as soon as possible.
1046 * Once the server has sent information about its default branch
1047 * we have all required information.
1049 if (a->create_configs && !a->configs_created &&
1050 !TAILQ_EMPTY(a->config_info.symrefs)) {
1051 err = create_config_files(a->config_info.proto,
1052 a->config_info.host, a->config_info.port,
1053 a->config_info.remote_repo_path,
1054 a->config_info.git_url,
1055 a->config_info.fetch_all_branches,
1056 a->config_info.mirror_references,
1057 a->config_info.symrefs,
1058 a->config_info.wanted_branches,
1059 a->config_info.wanted_refs, a->repo);
1060 if (err)
1061 return err;
1062 a->configs_created = 1;
1065 if (a->verbosity < 0)
1066 return NULL;
1068 if (message && message[0] != '\0') {
1069 printf("\rserver: %s", message);
1070 fflush(stdout);
1071 return NULL;
1074 if (packfile_size > 0 || nobj_indexed > 0) {
1075 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1076 (a->last_scaled_size[0] == '\0' ||
1077 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1078 print_size = 1;
1079 if (strlcpy(a->last_scaled_size, scaled_size,
1080 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1081 return got_error(GOT_ERR_NO_SPACE);
1083 if (nobj_indexed > 0) {
1084 p_indexed = (nobj_indexed * 100) / nobj_total;
1085 if (p_indexed != a->last_p_indexed) {
1086 a->last_p_indexed = p_indexed;
1087 print_indexed = 1;
1088 print_size = 1;
1091 if (nobj_resolved > 0) {
1092 p_resolved = (nobj_resolved * 100) /
1093 (nobj_total - nobj_loose);
1094 if (p_resolved != a->last_p_resolved) {
1095 a->last_p_resolved = p_resolved;
1096 print_resolved = 1;
1097 print_indexed = 1;
1098 print_size = 1;
1103 if (print_size || print_indexed || print_resolved)
1104 printf("\r");
1105 if (print_size)
1106 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1107 if (print_indexed)
1108 printf("; indexing %d%%", p_indexed);
1109 if (print_resolved)
1110 printf("; resolving deltas %d%%", p_resolved);
1111 if (print_size || print_indexed || print_resolved)
1112 fflush(stdout);
1114 return NULL;
1117 static const struct got_error *
1118 create_symref(const char *refname, struct got_reference *target_ref,
1119 int verbosity, struct got_repository *repo)
1121 const struct got_error *err;
1122 struct got_reference *head_symref;
1124 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1125 if (err)
1126 return err;
1128 err = got_ref_write(head_symref, repo);
1129 if (err == NULL && verbosity > 0) {
1130 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1131 got_ref_get_name(target_ref));
1133 got_ref_close(head_symref);
1134 return err;
1137 static const struct got_error *
1138 list_remote_refs(struct got_pathlist_head *symrefs,
1139 struct got_pathlist_head *refs)
1141 const struct got_error *err;
1142 struct got_pathlist_entry *pe;
1144 TAILQ_FOREACH(pe, symrefs, entry) {
1145 const char *refname = pe->path;
1146 const char *targetref = pe->data;
1148 printf("%s: %s\n", refname, targetref);
1151 TAILQ_FOREACH(pe, refs, entry) {
1152 const char *refname = pe->path;
1153 struct got_object_id *id = pe->data;
1154 char *id_str;
1156 err = got_object_id_str(&id_str, id);
1157 if (err)
1158 return err;
1159 printf("%s: %s\n", refname, id_str);
1160 free(id_str);
1163 return NULL;
1166 static const struct got_error *
1167 create_ref(const char *refname, struct got_object_id *id,
1168 int verbosity, struct got_repository *repo)
1170 const struct got_error *err = NULL;
1171 struct got_reference *ref;
1172 char *id_str;
1174 err = got_object_id_str(&id_str, id);
1175 if (err)
1176 return err;
1178 err = got_ref_alloc(&ref, refname, id);
1179 if (err)
1180 goto done;
1182 err = got_ref_write(ref, repo);
1183 got_ref_close(ref);
1185 if (err == NULL && verbosity >= 0)
1186 printf("Created reference %s: %s\n", refname, id_str);
1187 done:
1188 free(id_str);
1189 return err;
1192 static int
1193 match_wanted_ref(const char *refname, const char *wanted_ref)
1195 if (strncmp(refname, "refs/", 5) != 0)
1196 return 0;
1197 refname += 5;
1200 * Prevent fetching of references that won't make any
1201 * sense outside of the remote repository's context.
1203 if (strncmp(refname, "got/", 4) == 0)
1204 return 0;
1205 if (strncmp(refname, "remotes/", 8) == 0)
1206 return 0;
1208 if (strncmp(wanted_ref, "refs/", 5) == 0)
1209 wanted_ref += 5;
1211 /* Allow prefix match. */
1212 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1213 return 1;
1215 /* Allow exact match. */
1216 return (strcmp(refname, wanted_ref) == 0);
1219 static int
1220 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1222 struct got_pathlist_entry *pe;
1224 TAILQ_FOREACH(pe, wanted_refs, entry) {
1225 if (match_wanted_ref(refname, pe->path))
1226 return 1;
1229 return 0;
1232 static const struct got_error *
1233 create_wanted_ref(const char *refname, struct got_object_id *id,
1234 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1236 const struct got_error *err;
1237 char *remote_refname;
1239 if (strncmp("refs/", refname, 5) == 0)
1240 refname += 5;
1242 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1243 remote_repo_name, refname) == -1)
1244 return got_error_from_errno("asprintf");
1246 err = create_ref(remote_refname, id, verbosity, repo);
1247 free(remote_refname);
1248 return err;
1251 static const struct got_error *
1252 create_gotconfig(const char *proto, const char *host, const char *port,
1253 const char *remote_repo_path, const char *default_branch,
1254 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1255 struct got_pathlist_head *wanted_refs, int mirror_references,
1256 struct got_repository *repo)
1258 const struct got_error *err = NULL;
1259 char *gotconfig_path = NULL;
1260 char *gotconfig = NULL;
1261 FILE *gotconfig_file = NULL;
1262 const char *branchname = NULL;
1263 char *branches = NULL, *refs = NULL;
1264 ssize_t n;
1266 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1267 struct got_pathlist_entry *pe;
1268 TAILQ_FOREACH(pe, wanted_branches, entry) {
1269 char *s;
1270 branchname = pe->path;
1271 if (strncmp(branchname, "refs/heads/", 11) == 0)
1272 branchname += 11;
1273 if (asprintf(&s, "%s\"%s\" ",
1274 branches ? branches : "", branchname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1278 free(branches);
1279 branches = s;
1281 } else if (!fetch_all_branches && default_branch) {
1282 branchname = default_branch;
1283 if (strncmp(branchname, "refs/heads/", 11) == 0)
1284 branchname += 11;
1285 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1286 err = got_error_from_errno("asprintf");
1287 goto done;
1290 if (!TAILQ_EMPTY(wanted_refs)) {
1291 struct got_pathlist_entry *pe;
1292 TAILQ_FOREACH(pe, wanted_refs, entry) {
1293 char *s;
1294 const char *refname = pe->path;
1295 if (strncmp(refname, "refs/", 5) == 0)
1296 branchname += 5;
1297 if (asprintf(&s, "%s\"%s\" ",
1298 refs ? refs : "", refname) == -1) {
1299 err = got_error_from_errno("asprintf");
1300 goto done;
1302 free(refs);
1303 refs = s;
1307 /* Create got.conf(5). */
1308 gotconfig_path = got_repo_get_path_gotconfig(repo);
1309 if (gotconfig_path == NULL) {
1310 err = got_error_from_errno("got_repo_get_path_gotconfig");
1311 goto done;
1313 gotconfig_file = fopen(gotconfig_path, "ae");
1314 if (gotconfig_file == NULL) {
1315 err = got_error_from_errno2("fopen", gotconfig_path);
1316 goto done;
1318 if (asprintf(&gotconfig,
1319 "remote \"%s\" {\n"
1320 "\tserver %s\n"
1321 "\tprotocol %s\n"
1322 "%s%s%s"
1323 "\trepository \"%s\"\n"
1324 "%s%s%s"
1325 "%s%s%s"
1326 "%s"
1327 "%s"
1328 "}\n",
1329 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1330 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1331 remote_repo_path, branches ? "\tbranch { " : "",
1332 branches ? branches : "", branches ? "}\n" : "",
1333 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1334 mirror_references ? "\tmirror_references yes\n" : "",
1335 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1336 err = got_error_from_errno("asprintf");
1337 goto done;
1339 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1340 if (n != strlen(gotconfig)) {
1341 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1342 goto done;
1345 done:
1346 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1347 err = got_error_from_errno2("fclose", gotconfig_path);
1348 free(gotconfig_path);
1349 free(branches);
1350 return err;
1353 static const struct got_error *
1354 create_gitconfig(const char *git_url, const char *default_branch,
1355 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1356 struct got_pathlist_head *wanted_refs, int mirror_references,
1357 struct got_repository *repo)
1359 const struct got_error *err = NULL;
1360 char *gitconfig_path = NULL;
1361 char *gitconfig = NULL;
1362 FILE *gitconfig_file = NULL;
1363 char *branches = NULL, *refs = NULL;
1364 const char *branchname;
1365 ssize_t n;
1367 /* Create a config file Git can understand. */
1368 gitconfig_path = got_repo_get_path_gitconfig(repo);
1369 if (gitconfig_path == NULL) {
1370 err = got_error_from_errno("got_repo_get_path_gitconfig");
1371 goto done;
1373 gitconfig_file = fopen(gitconfig_path, "ae");
1374 if (gitconfig_file == NULL) {
1375 err = got_error_from_errno2("fopen", gitconfig_path);
1376 goto done;
1378 if (fetch_all_branches) {
1379 if (mirror_references) {
1380 if (asprintf(&branches,
1381 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1382 err = got_error_from_errno("asprintf");
1383 goto done;
1385 } else if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1387 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1388 err = got_error_from_errno("asprintf");
1389 goto done;
1391 } else if (!TAILQ_EMPTY(wanted_branches)) {
1392 struct got_pathlist_entry *pe;
1393 TAILQ_FOREACH(pe, wanted_branches, entry) {
1394 char *s;
1395 branchname = pe->path;
1396 if (strncmp(branchname, "refs/heads/", 11) == 0)
1397 branchname += 11;
1398 if (mirror_references) {
1399 if (asprintf(&s,
1400 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1401 branches ? branches : "",
1402 branchname, branchname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 } else if (asprintf(&s,
1407 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1408 branches ? branches : "",
1409 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1410 branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 free(branches);
1415 branches = s;
1417 } else {
1419 * If the server specified a default branch, use just that one.
1420 * Otherwise fall back to fetching all branches on next fetch.
1422 if (default_branch) {
1423 branchname = default_branch;
1424 if (strncmp(branchname, "refs/heads/", 11) == 0)
1425 branchname += 11;
1426 } else
1427 branchname = "*"; /* fall back to all branches */
1428 if (mirror_references) {
1429 if (asprintf(&branches,
1430 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1431 branchname, branchname) == -1) {
1432 err = got_error_from_errno("asprintf");
1433 goto done;
1435 } else if (asprintf(&branches,
1436 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1437 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1438 branchname) == -1) {
1439 err = got_error_from_errno("asprintf");
1440 goto done;
1443 if (!TAILQ_EMPTY(wanted_refs)) {
1444 struct got_pathlist_entry *pe;
1445 TAILQ_FOREACH(pe, wanted_refs, entry) {
1446 char *s;
1447 const char *refname = pe->path;
1448 if (strncmp(refname, "refs/", 5) == 0)
1449 refname += 5;
1450 if (mirror_references) {
1451 if (asprintf(&s,
1452 "%s\tfetch = refs/%s:refs/%s\n",
1453 refs ? refs : "", refname, refname) == -1) {
1454 err = got_error_from_errno("asprintf");
1455 goto done;
1457 } else if (asprintf(&s,
1458 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1459 refs ? refs : "",
1460 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1461 refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 free(refs);
1466 refs = s;
1470 if (asprintf(&gitconfig,
1471 "[remote \"%s\"]\n"
1472 "\turl = %s\n"
1473 "%s"
1474 "%s"
1475 "\tfetch = refs/tags/*:refs/tags/*\n",
1476 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1477 refs ? refs : "") == -1) {
1478 err = got_error_from_errno("asprintf");
1479 goto done;
1481 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1482 if (n != strlen(gitconfig)) {
1483 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1484 goto done;
1486 done:
1487 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1488 err = got_error_from_errno2("fclose", gitconfig_path);
1489 free(gitconfig_path);
1490 free(branches);
1491 return err;
1494 static const struct got_error *
1495 create_config_files(const char *proto, const char *host, const char *port,
1496 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1497 int mirror_references, struct got_pathlist_head *symrefs,
1498 struct got_pathlist_head *wanted_branches,
1499 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1501 const struct got_error *err = NULL;
1502 const char *default_branch = NULL;
1503 struct got_pathlist_entry *pe;
1506 * If we asked for a set of wanted branches then use the first
1507 * one of those.
1509 if (!TAILQ_EMPTY(wanted_branches)) {
1510 pe = TAILQ_FIRST(wanted_branches);
1511 default_branch = pe->path;
1512 } else {
1513 /* First HEAD ref listed by server is the default branch. */
1514 TAILQ_FOREACH(pe, symrefs, entry) {
1515 const char *refname = pe->path;
1516 const char *target = pe->data;
1518 if (strcmp(refname, GOT_REF_HEAD) != 0)
1519 continue;
1521 default_branch = target;
1522 break;
1526 /* Create got.conf(5). */
1527 err = create_gotconfig(proto, host, port, remote_repo_path,
1528 default_branch, fetch_all_branches, wanted_branches,
1529 wanted_refs, mirror_references, repo);
1530 if (err)
1531 return err;
1533 /* Create a config file Git can understand. */
1534 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1535 wanted_branches, wanted_refs, mirror_references, repo);
1538 static const struct got_error *
1539 cmd_clone(int argc, char *argv[])
1541 const struct got_error *error = NULL;
1542 const char *uri, *dirname;
1543 char *proto, *host, *port, *repo_name, *server_path;
1544 char *default_destdir = NULL, *id_str = NULL;
1545 const char *repo_path;
1546 struct got_repository *repo = NULL;
1547 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1548 struct got_pathlist_entry *pe;
1549 struct got_object_id *pack_hash = NULL;
1550 int ch, fetchfd = -1, fetchstatus;
1551 pid_t fetchpid = -1;
1552 struct got_fetch_progress_arg fpa;
1553 char *git_url = NULL;
1554 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1555 int list_refs_only = 0;
1556 int *pack_fds = NULL;
1558 TAILQ_INIT(&refs);
1559 TAILQ_INIT(&symrefs);
1560 TAILQ_INIT(&wanted_branches);
1561 TAILQ_INIT(&wanted_refs);
1563 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1564 switch (ch) {
1565 case 'a':
1566 fetch_all_branches = 1;
1567 break;
1568 case 'b':
1569 error = got_pathlist_append(&wanted_branches,
1570 optarg, NULL);
1571 if (error)
1572 return error;
1573 break;
1574 case 'l':
1575 list_refs_only = 1;
1576 break;
1577 case 'm':
1578 mirror_references = 1;
1579 break;
1580 case 'q':
1581 verbosity = -1;
1582 break;
1583 case 'R':
1584 error = got_pathlist_append(&wanted_refs,
1585 optarg, NULL);
1586 if (error)
1587 return error;
1588 break;
1589 case 'v':
1590 if (verbosity < 0)
1591 verbosity = 0;
1592 else if (verbosity < 3)
1593 verbosity++;
1594 break;
1595 default:
1596 usage_clone();
1597 break;
1600 argc -= optind;
1601 argv += optind;
1603 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1604 option_conflict('a', 'b');
1605 if (list_refs_only) {
1606 if (!TAILQ_EMPTY(&wanted_branches))
1607 option_conflict('l', 'b');
1608 if (fetch_all_branches)
1609 option_conflict('l', 'a');
1610 if (mirror_references)
1611 option_conflict('l', 'm');
1612 if (!TAILQ_EMPTY(&wanted_refs))
1613 option_conflict('l', 'R');
1616 uri = argv[0];
1618 if (argc == 1)
1619 dirname = NULL;
1620 else if (argc == 2)
1621 dirname = argv[1];
1622 else
1623 usage_clone();
1625 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1626 &repo_name, uri);
1627 if (error)
1628 goto done;
1630 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1631 host, port ? ":" : "", port ? port : "",
1632 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1633 error = got_error_from_errno("asprintf");
1634 goto done;
1637 if (strcmp(proto, "git") == 0) {
1638 #ifndef PROFILE
1639 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1640 "sendfd dns inet unveil", NULL) == -1)
1641 err(1, "pledge");
1642 #endif
1643 } else if (strcmp(proto, "git+ssh") == 0 ||
1644 strcmp(proto, "ssh") == 0) {
1645 #ifndef PROFILE
1646 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1647 "sendfd unveil", NULL) == -1)
1648 err(1, "pledge");
1649 #endif
1650 } else if (strcmp(proto, "http") == 0 ||
1651 strcmp(proto, "git+http") == 0) {
1652 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1653 goto done;
1654 } else {
1655 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1656 goto done;
1658 if (dirname == NULL) {
1659 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1660 error = got_error_from_errno("asprintf");
1661 goto done;
1663 repo_path = default_destdir;
1664 } else
1665 repo_path = dirname;
1667 if (!list_refs_only) {
1668 error = got_path_mkdir(repo_path);
1669 if (error &&
1670 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1671 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1672 goto done;
1673 if (!got_path_dir_is_empty(repo_path)) {
1674 error = got_error_path(repo_path,
1675 GOT_ERR_DIR_NOT_EMPTY);
1676 goto done;
1680 error = got_dial_apply_unveil(proto);
1681 if (error)
1682 goto done;
1684 error = apply_unveil(repo_path, 0, NULL);
1685 if (error)
1686 goto done;
1688 if (verbosity >= 0)
1689 printf("Connecting to %s\n", git_url);
1691 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1692 server_path, verbosity);
1693 if (error)
1694 goto done;
1696 if (!list_refs_only) {
1697 error = got_repo_init(repo_path, NULL);
1698 if (error)
1699 goto done;
1700 error = got_repo_pack_fds_open(&pack_fds);
1701 if (error != NULL)
1702 goto done;
1703 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1704 if (error)
1705 goto done;
1708 fpa.last_scaled_size[0] = '\0';
1709 fpa.last_p_indexed = -1;
1710 fpa.last_p_resolved = -1;
1711 fpa.verbosity = verbosity;
1712 fpa.create_configs = 1;
1713 fpa.configs_created = 0;
1714 fpa.repo = repo;
1715 fpa.config_info.symrefs = &symrefs;
1716 fpa.config_info.wanted_branches = &wanted_branches;
1717 fpa.config_info.wanted_refs = &wanted_refs;
1718 fpa.config_info.proto = proto;
1719 fpa.config_info.host = host;
1720 fpa.config_info.port = port;
1721 fpa.config_info.remote_repo_path = server_path;
1722 fpa.config_info.git_url = git_url;
1723 fpa.config_info.fetch_all_branches = fetch_all_branches;
1724 fpa.config_info.mirror_references = mirror_references;
1725 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1726 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1727 fetch_all_branches, &wanted_branches, &wanted_refs,
1728 list_refs_only, verbosity, fetchfd, repo,
1729 fetch_progress, &fpa);
1730 if (error)
1731 goto done;
1733 if (list_refs_only) {
1734 error = list_remote_refs(&symrefs, &refs);
1735 goto done;
1738 if (pack_hash == NULL) {
1739 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1740 "server sent an empty pack file");
1741 goto done;
1743 error = got_object_id_str(&id_str, pack_hash);
1744 if (error)
1745 goto done;
1746 if (verbosity >= 0)
1747 printf("\nFetched %s.pack\n", id_str);
1748 free(id_str);
1750 /* Set up references provided with the pack file. */
1751 TAILQ_FOREACH(pe, &refs, entry) {
1752 const char *refname = pe->path;
1753 struct got_object_id *id = pe->data;
1754 char *remote_refname;
1756 if (is_wanted_ref(&wanted_refs, refname) &&
1757 !mirror_references) {
1758 error = create_wanted_ref(refname, id,
1759 GOT_FETCH_DEFAULT_REMOTE_NAME,
1760 verbosity - 1, repo);
1761 if (error)
1762 goto done;
1763 continue;
1766 error = create_ref(refname, id, verbosity - 1, repo);
1767 if (error)
1768 goto done;
1770 if (mirror_references)
1771 continue;
1773 if (strncmp("refs/heads/", refname, 11) != 0)
1774 continue;
1776 if (asprintf(&remote_refname,
1777 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1778 refname + 11) == -1) {
1779 error = got_error_from_errno("asprintf");
1780 goto done;
1782 error = create_ref(remote_refname, id, verbosity - 1, repo);
1783 free(remote_refname);
1784 if (error)
1785 goto done;
1788 /* Set the HEAD reference if the server provided one. */
1789 TAILQ_FOREACH(pe, &symrefs, entry) {
1790 struct got_reference *target_ref;
1791 const char *refname = pe->path;
1792 const char *target = pe->data;
1793 char *remote_refname = NULL, *remote_target = NULL;
1795 if (strcmp(refname, GOT_REF_HEAD) != 0)
1796 continue;
1798 error = got_ref_open(&target_ref, repo, target, 0);
1799 if (error) {
1800 if (error->code == GOT_ERR_NOT_REF) {
1801 error = NULL;
1802 continue;
1804 goto done;
1807 error = create_symref(refname, target_ref, verbosity, repo);
1808 got_ref_close(target_ref);
1809 if (error)
1810 goto done;
1812 if (mirror_references)
1813 continue;
1815 if (strncmp("refs/heads/", target, 11) != 0)
1816 continue;
1818 if (asprintf(&remote_refname,
1819 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1820 refname) == -1) {
1821 error = got_error_from_errno("asprintf");
1822 goto done;
1824 if (asprintf(&remote_target,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 target + 11) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 free(remote_refname);
1829 goto done;
1831 error = got_ref_open(&target_ref, repo, remote_target, 0);
1832 if (error) {
1833 free(remote_refname);
1834 free(remote_target);
1835 if (error->code == GOT_ERR_NOT_REF) {
1836 error = NULL;
1837 continue;
1839 goto done;
1841 error = create_symref(remote_refname, target_ref,
1842 verbosity - 1, repo);
1843 free(remote_refname);
1844 free(remote_target);
1845 got_ref_close(target_ref);
1846 if (error)
1847 goto done;
1849 if (pe == NULL) {
1851 * We failed to set the HEAD reference. If we asked for
1852 * a set of wanted branches use the first of one of those
1853 * which could be fetched instead.
1855 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1856 const char *target = pe->path;
1857 struct got_reference *target_ref;
1859 error = got_ref_open(&target_ref, repo, target, 0);
1860 if (error) {
1861 if (error->code == GOT_ERR_NOT_REF) {
1862 error = NULL;
1863 continue;
1865 goto done;
1868 error = create_symref(GOT_REF_HEAD, target_ref,
1869 verbosity, repo);
1870 got_ref_close(target_ref);
1871 if (error)
1872 goto done;
1873 break;
1876 if (!fpa.configs_created && pe != NULL) {
1877 error = create_config_files(fpa.config_info.proto,
1878 fpa.config_info.host, fpa.config_info.port,
1879 fpa.config_info.remote_repo_path,
1880 fpa.config_info.git_url,
1881 fpa.config_info.fetch_all_branches,
1882 fpa.config_info.mirror_references,
1883 fpa.config_info.symrefs,
1884 fpa.config_info.wanted_branches,
1885 fpa.config_info.wanted_refs, fpa.repo);
1886 if (error)
1887 goto done;
1891 if (verbosity >= 0)
1892 printf("Created %s repository '%s'\n",
1893 mirror_references ? "mirrored" : "cloned", repo_path);
1894 done:
1895 if (pack_fds) {
1896 const struct got_error *pack_err =
1897 got_repo_pack_fds_close(pack_fds);
1898 if (error == NULL)
1899 error = pack_err;
1901 if (fetchpid > 0) {
1902 if (kill(fetchpid, SIGTERM) == -1)
1903 error = got_error_from_errno("kill");
1904 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1905 error = got_error_from_errno("waitpid");
1907 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1908 error = got_error_from_errno("close");
1909 if (repo) {
1910 const struct got_error *close_err = got_repo_close(repo);
1911 if (error == NULL)
1912 error = close_err;
1914 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1915 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1916 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1917 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1918 free(pack_hash);
1919 free(proto);
1920 free(host);
1921 free(port);
1922 free(server_path);
1923 free(repo_name);
1924 free(default_destdir);
1925 free(git_url);
1926 return error;
1929 static const struct got_error *
1930 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1931 int replace_tags, int verbosity, struct got_repository *repo)
1933 const struct got_error *err = NULL;
1934 char *new_id_str = NULL;
1935 struct got_object_id *old_id = NULL;
1937 err = got_object_id_str(&new_id_str, new_id);
1938 if (err)
1939 goto done;
1941 if (!replace_tags &&
1942 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1943 err = got_ref_resolve(&old_id, repo, ref);
1944 if (err)
1945 goto done;
1946 if (got_object_id_cmp(old_id, new_id) == 0)
1947 goto done;
1948 if (verbosity >= 0) {
1949 printf("Rejecting update of existing tag %s: %s\n",
1950 got_ref_get_name(ref), new_id_str);
1952 goto done;
1955 if (got_ref_is_symbolic(ref)) {
1956 if (verbosity >= 0) {
1957 printf("Replacing reference %s: %s\n",
1958 got_ref_get_name(ref),
1959 got_ref_get_symref_target(ref));
1961 err = got_ref_change_symref_to_ref(ref, new_id);
1962 if (err)
1963 goto done;
1964 err = got_ref_write(ref, repo);
1965 if (err)
1966 goto done;
1967 } else {
1968 err = got_ref_resolve(&old_id, repo, ref);
1969 if (err)
1970 goto done;
1971 if (got_object_id_cmp(old_id, new_id) == 0)
1972 goto done;
1974 err = got_ref_change_ref(ref, new_id);
1975 if (err)
1976 goto done;
1977 err = got_ref_write(ref, repo);
1978 if (err)
1979 goto done;
1982 if (verbosity >= 0)
1983 printf("Updated %s: %s\n", got_ref_get_name(ref),
1984 new_id_str);
1985 done:
1986 free(old_id);
1987 free(new_id_str);
1988 return err;
1991 static const struct got_error *
1992 update_symref(const char *refname, struct got_reference *target_ref,
1993 int verbosity, struct got_repository *repo)
1995 const struct got_error *err = NULL, *unlock_err;
1996 struct got_reference *symref;
1997 int symref_is_locked = 0;
1999 err = got_ref_open(&symref, repo, refname, 1);
2000 if (err) {
2001 if (err->code != GOT_ERR_NOT_REF)
2002 return err;
2003 err = got_ref_alloc_symref(&symref, refname, target_ref);
2004 if (err)
2005 goto done;
2007 err = got_ref_write(symref, repo);
2008 if (err)
2009 goto done;
2011 if (verbosity >= 0)
2012 printf("Created reference %s: %s\n",
2013 got_ref_get_name(symref),
2014 got_ref_get_symref_target(symref));
2015 } else {
2016 symref_is_locked = 1;
2018 if (strcmp(got_ref_get_symref_target(symref),
2019 got_ref_get_name(target_ref)) == 0)
2020 goto done;
2022 err = got_ref_change_symref(symref,
2023 got_ref_get_name(target_ref));
2024 if (err)
2025 goto done;
2027 err = got_ref_write(symref, repo);
2028 if (err)
2029 goto done;
2031 if (verbosity >= 0)
2032 printf("Updated %s: %s\n", got_ref_get_name(symref),
2033 got_ref_get_symref_target(symref));
2036 done:
2037 if (symref_is_locked) {
2038 unlock_err = got_ref_unlock(symref);
2039 if (unlock_err && err == NULL)
2040 err = unlock_err;
2042 got_ref_close(symref);
2043 return err;
2046 __dead static void
2047 usage_fetch(void)
2049 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2050 "[-R reference] [-r repository-path] [remote-repository]\n",
2051 getprogname());
2052 exit(1);
2055 static const struct got_error *
2056 delete_missing_ref(struct got_reference *ref,
2057 int verbosity, struct got_repository *repo)
2059 const struct got_error *err = NULL;
2060 struct got_object_id *id = NULL;
2061 char *id_str = NULL;
2063 if (got_ref_is_symbolic(ref)) {
2064 err = got_ref_delete(ref, repo);
2065 if (err)
2066 return err;
2067 if (verbosity >= 0) {
2068 printf("Deleted %s: %s\n",
2069 got_ref_get_name(ref),
2070 got_ref_get_symref_target(ref));
2072 } else {
2073 err = got_ref_resolve(&id, repo, ref);
2074 if (err)
2075 return err;
2076 err = got_object_id_str(&id_str, id);
2077 if (err)
2078 goto done;
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 goto done;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref), id_str);
2088 done:
2089 free(id);
2090 free(id_str);
2091 return NULL;
2094 static const struct got_error *
2095 delete_missing_refs(struct got_pathlist_head *their_refs,
2096 struct got_pathlist_head *their_symrefs,
2097 const struct got_remote_repo *remote,
2098 int verbosity, struct got_repository *repo)
2100 const struct got_error *err = NULL, *unlock_err;
2101 struct got_reflist_head my_refs;
2102 struct got_reflist_entry *re;
2103 struct got_pathlist_entry *pe;
2104 char *remote_namespace = NULL;
2105 char *local_refname = NULL;
2107 TAILQ_INIT(&my_refs);
2109 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2110 == -1)
2111 return got_error_from_errno("asprintf");
2113 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2114 if (err)
2115 goto done;
2117 TAILQ_FOREACH(re, &my_refs, entry) {
2118 const char *refname = got_ref_get_name(re->ref);
2119 const char *their_refname;
2121 if (remote->mirror_references) {
2122 their_refname = refname;
2123 } else {
2124 if (strncmp(refname, remote_namespace,
2125 strlen(remote_namespace)) == 0) {
2126 if (strcmp(refname + strlen(remote_namespace),
2127 GOT_REF_HEAD) == 0)
2128 continue;
2129 if (asprintf(&local_refname, "refs/heads/%s",
2130 refname + strlen(remote_namespace)) == -1) {
2131 err = got_error_from_errno("asprintf");
2132 goto done;
2134 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2135 continue;
2137 their_refname = local_refname;
2140 TAILQ_FOREACH(pe, their_refs, entry) {
2141 if (strcmp(their_refname, pe->path) == 0)
2142 break;
2144 if (pe != NULL)
2145 continue;
2147 TAILQ_FOREACH(pe, their_symrefs, entry) {
2148 if (strcmp(their_refname, pe->path) == 0)
2149 break;
2151 if (pe != NULL)
2152 continue;
2154 err = delete_missing_ref(re->ref, verbosity, repo);
2155 if (err)
2156 break;
2158 if (local_refname) {
2159 struct got_reference *ref;
2160 err = got_ref_open(&ref, repo, local_refname, 1);
2161 if (err) {
2162 if (err->code != GOT_ERR_NOT_REF)
2163 break;
2164 free(local_refname);
2165 local_refname = NULL;
2166 continue;
2168 err = delete_missing_ref(ref, verbosity, repo);
2169 if (err)
2170 break;
2171 unlock_err = got_ref_unlock(ref);
2172 got_ref_close(ref);
2173 if (unlock_err && err == NULL) {
2174 err = unlock_err;
2175 break;
2178 free(local_refname);
2179 local_refname = NULL;
2182 done:
2183 got_ref_list_free(&my_refs);
2184 free(remote_namespace);
2185 free(local_refname);
2186 return err;
2189 static const struct got_error *
2190 update_wanted_ref(const char *refname, struct got_object_id *id,
2191 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2193 const struct got_error *err, *unlock_err;
2194 char *remote_refname;
2195 struct got_reference *ref;
2197 if (strncmp("refs/", refname, 5) == 0)
2198 refname += 5;
2200 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2201 remote_repo_name, refname) == -1)
2202 return got_error_from_errno("asprintf");
2204 err = got_ref_open(&ref, repo, remote_refname, 1);
2205 if (err) {
2206 if (err->code != GOT_ERR_NOT_REF)
2207 goto done;
2208 err = create_ref(remote_refname, id, verbosity, repo);
2209 } else {
2210 err = update_ref(ref, id, 0, verbosity, repo);
2211 unlock_err = got_ref_unlock(ref);
2212 if (unlock_err && err == NULL)
2213 err = unlock_err;
2214 got_ref_close(ref);
2216 done:
2217 free(remote_refname);
2218 return err;
2221 static const struct got_error *
2222 delete_ref(struct got_repository *repo, struct got_reference *ref)
2224 const struct got_error *err = NULL;
2225 struct got_object_id *id = NULL;
2226 char *id_str = NULL;
2227 const char *target;
2229 if (got_ref_is_symbolic(ref)) {
2230 target = got_ref_get_symref_target(ref);
2231 } else {
2232 err = got_ref_resolve(&id, repo, ref);
2233 if (err)
2234 goto done;
2235 err = got_object_id_str(&id_str, id);
2236 if (err)
2237 goto done;
2238 target = id_str;
2241 err = got_ref_delete(ref, repo);
2242 if (err)
2243 goto done;
2245 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2246 done:
2247 free(id);
2248 free(id_str);
2249 return err;
2252 static const struct got_error *
2253 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2255 const struct got_error *err = NULL;
2256 struct got_reflist_head refs;
2257 struct got_reflist_entry *re;
2258 char *prefix;
2260 TAILQ_INIT(&refs);
2262 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2263 err = got_error_from_errno("asprintf");
2264 goto done;
2266 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2267 if (err)
2268 goto done;
2270 TAILQ_FOREACH(re, &refs, entry)
2271 delete_ref(repo, re->ref);
2272 done:
2273 got_ref_list_free(&refs);
2274 return err;
2277 static const struct got_error *
2278 cmd_fetch(int argc, char *argv[])
2280 const struct got_error *error = NULL, *unlock_err;
2281 char *cwd = NULL, *repo_path = NULL;
2282 const char *remote_name;
2283 char *proto = NULL, *host = NULL, *port = NULL;
2284 char *repo_name = NULL, *server_path = NULL;
2285 const struct got_remote_repo *remotes, *remote = NULL;
2286 int nremotes;
2287 char *id_str = NULL;
2288 struct got_repository *repo = NULL;
2289 struct got_worktree *worktree = NULL;
2290 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2291 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2292 struct got_pathlist_entry *pe;
2293 struct got_object_id *pack_hash = NULL;
2294 int i, ch, fetchfd = -1, fetchstatus;
2295 pid_t fetchpid = -1;
2296 struct got_fetch_progress_arg fpa;
2297 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2298 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2299 int *pack_fds = NULL;
2301 TAILQ_INIT(&refs);
2302 TAILQ_INIT(&symrefs);
2303 TAILQ_INIT(&wanted_branches);
2304 TAILQ_INIT(&wanted_refs);
2306 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2307 switch (ch) {
2308 case 'a':
2309 fetch_all_branches = 1;
2310 break;
2311 case 'b':
2312 error = got_pathlist_append(&wanted_branches,
2313 optarg, NULL);
2314 if (error)
2315 return error;
2316 break;
2317 case 'd':
2318 delete_refs = 1;
2319 break;
2320 case 'l':
2321 list_refs_only = 1;
2322 break;
2323 case 'q':
2324 verbosity = -1;
2325 break;
2326 case 'R':
2327 error = got_pathlist_append(&wanted_refs,
2328 optarg, NULL);
2329 if (error)
2330 return error;
2331 break;
2332 case 'r':
2333 repo_path = realpath(optarg, NULL);
2334 if (repo_path == NULL)
2335 return got_error_from_errno2("realpath",
2336 optarg);
2337 got_path_strip_trailing_slashes(repo_path);
2338 break;
2339 case 't':
2340 replace_tags = 1;
2341 break;
2342 case 'v':
2343 if (verbosity < 0)
2344 verbosity = 0;
2345 else if (verbosity < 3)
2346 verbosity++;
2347 break;
2348 case 'X':
2349 delete_remote = 1;
2350 break;
2351 default:
2352 usage_fetch();
2353 break;
2356 argc -= optind;
2357 argv += optind;
2359 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2360 option_conflict('a', 'b');
2361 if (list_refs_only) {
2362 if (!TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('l', 'b');
2364 if (fetch_all_branches)
2365 option_conflict('l', 'a');
2366 if (delete_refs)
2367 option_conflict('l', 'd');
2368 if (delete_remote)
2369 option_conflict('l', 'X');
2371 if (delete_remote) {
2372 if (fetch_all_branches)
2373 option_conflict('X', 'a');
2374 if (!TAILQ_EMPTY(&wanted_branches))
2375 option_conflict('X', 'b');
2376 if (delete_refs)
2377 option_conflict('X', 'd');
2378 if (replace_tags)
2379 option_conflict('X', 't');
2380 if (!TAILQ_EMPTY(&wanted_refs))
2381 option_conflict('X', 'R');
2384 if (argc == 0) {
2385 if (delete_remote)
2386 errx(1, "-X option requires a remote name");
2387 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2388 } else if (argc == 1)
2389 remote_name = argv[0];
2390 else
2391 usage_fetch();
2393 cwd = getcwd(NULL, 0);
2394 if (cwd == NULL) {
2395 error = got_error_from_errno("getcwd");
2396 goto done;
2399 error = got_repo_pack_fds_open(&pack_fds);
2400 if (error != NULL)
2401 goto done;
2403 if (repo_path == NULL) {
2404 error = got_worktree_open(&worktree, cwd);
2405 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2406 goto done;
2407 else
2408 error = NULL;
2409 if (worktree) {
2410 repo_path =
2411 strdup(got_worktree_get_repo_path(worktree));
2412 if (repo_path == NULL)
2413 error = got_error_from_errno("strdup");
2414 if (error)
2415 goto done;
2416 } else {
2417 repo_path = strdup(cwd);
2418 if (repo_path == NULL) {
2419 error = got_error_from_errno("strdup");
2420 goto done;
2425 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2426 if (error)
2427 goto done;
2429 if (delete_remote) {
2430 error = delete_refs_for_remote(repo, remote_name);
2431 goto done; /* nothing else to do */
2434 if (worktree) {
2435 worktree_conf = got_worktree_get_gotconfig(worktree);
2436 if (worktree_conf) {
2437 got_gotconfig_get_remotes(&nremotes, &remotes,
2438 worktree_conf);
2439 for (i = 0; i < nremotes; i++) {
2440 if (strcmp(remotes[i].name, remote_name) == 0) {
2441 remote = &remotes[i];
2442 break;
2447 if (remote == NULL) {
2448 repo_conf = got_repo_get_gotconfig(repo);
2449 if (repo_conf) {
2450 got_gotconfig_get_remotes(&nremotes, &remotes,
2451 repo_conf);
2452 for (i = 0; i < nremotes; i++) {
2453 if (strcmp(remotes[i].name, remote_name) == 0) {
2454 remote = &remotes[i];
2455 break;
2460 if (remote == NULL) {
2461 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2469 if (remote == NULL) {
2470 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2471 goto done;
2474 if (TAILQ_EMPTY(&wanted_branches)) {
2475 if (!fetch_all_branches)
2476 fetch_all_branches = remote->fetch_all_branches;
2477 for (i = 0; i < remote->nfetch_branches; i++) {
2478 error = got_pathlist_append(&wanted_branches,
2479 remote->fetch_branches[i], NULL);
2480 if (error)
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_refs)) {
2485 for (i = 0; i < remote->nfetch_refs; i++) {
2486 error = got_pathlist_append(&wanted_refs,
2487 remote->fetch_refs[i], NULL);
2488 if (error)
2489 goto done;
2493 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2494 &repo_name, remote->fetch_url);
2495 if (error)
2496 goto done;
2498 if (strcmp(proto, "git") == 0) {
2499 #ifndef PROFILE
2500 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2501 "sendfd dns inet unveil", NULL) == -1)
2502 err(1, "pledge");
2503 #endif
2504 } else if (strcmp(proto, "git+ssh") == 0 ||
2505 strcmp(proto, "ssh") == 0) {
2506 #ifndef PROFILE
2507 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2508 "sendfd unveil", NULL) == -1)
2509 err(1, "pledge");
2510 #endif
2511 } else if (strcmp(proto, "http") == 0 ||
2512 strcmp(proto, "git+http") == 0) {
2513 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2514 goto done;
2515 } else {
2516 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2517 goto done;
2520 error = got_dial_apply_unveil(proto);
2521 if (error)
2522 goto done;
2524 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2525 if (error)
2526 goto done;
2528 if (verbosity >= 0) {
2529 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2530 remote->name, proto, host,
2531 port ? ":" : "", port ? port : "",
2532 *server_path == '/' ? "" : "/", server_path);
2535 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2536 server_path, verbosity);
2537 if (error)
2538 goto done;
2540 fpa.last_scaled_size[0] = '\0';
2541 fpa.last_p_indexed = -1;
2542 fpa.last_p_resolved = -1;
2543 fpa.verbosity = verbosity;
2544 fpa.repo = repo;
2545 fpa.create_configs = 0;
2546 fpa.configs_created = 0;
2547 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2548 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2549 remote->mirror_references, fetch_all_branches, &wanted_branches,
2550 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2551 fetch_progress, &fpa);
2552 if (error)
2553 goto done;
2555 if (list_refs_only) {
2556 error = list_remote_refs(&symrefs, &refs);
2557 goto done;
2560 if (pack_hash == NULL) {
2561 if (verbosity >= 0)
2562 printf("Already up-to-date\n");
2563 } else if (verbosity >= 0) {
2564 error = got_object_id_str(&id_str, pack_hash);
2565 if (error)
2566 goto done;
2567 printf("\nFetched %s.pack\n", id_str);
2568 free(id_str);
2569 id_str = NULL;
2572 /* Update references provided with the pack file. */
2573 TAILQ_FOREACH(pe, &refs, entry) {
2574 const char *refname = pe->path;
2575 struct got_object_id *id = pe->data;
2576 struct got_reference *ref;
2577 char *remote_refname;
2579 if (is_wanted_ref(&wanted_refs, refname) &&
2580 !remote->mirror_references) {
2581 error = update_wanted_ref(refname, id,
2582 remote->name, verbosity, repo);
2583 if (error)
2584 goto done;
2585 continue;
2588 if (remote->mirror_references ||
2589 strncmp("refs/tags/", refname, 10) == 0) {
2590 error = got_ref_open(&ref, repo, refname, 1);
2591 if (error) {
2592 if (error->code != GOT_ERR_NOT_REF)
2593 goto done;
2594 error = create_ref(refname, id, verbosity,
2595 repo);
2596 if (error)
2597 goto done;
2598 } else {
2599 error = update_ref(ref, id, replace_tags,
2600 verbosity, repo);
2601 unlock_err = got_ref_unlock(ref);
2602 if (unlock_err && error == NULL)
2603 error = unlock_err;
2604 got_ref_close(ref);
2605 if (error)
2606 goto done;
2608 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2609 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2610 remote_name, refname + 11) == -1) {
2611 error = got_error_from_errno("asprintf");
2612 goto done;
2615 error = got_ref_open(&ref, repo, remote_refname, 1);
2616 if (error) {
2617 if (error->code != GOT_ERR_NOT_REF)
2618 goto done;
2619 error = create_ref(remote_refname, id,
2620 verbosity, repo);
2621 if (error)
2622 goto done;
2623 } else {
2624 error = update_ref(ref, id, replace_tags,
2625 verbosity, repo);
2626 unlock_err = got_ref_unlock(ref);
2627 if (unlock_err && error == NULL)
2628 error = unlock_err;
2629 got_ref_close(ref);
2630 if (error)
2631 goto done;
2634 /* Also create a local branch if none exists yet. */
2635 error = got_ref_open(&ref, repo, refname, 1);
2636 if (error) {
2637 if (error->code != GOT_ERR_NOT_REF)
2638 goto done;
2639 error = create_ref(refname, id, verbosity,
2640 repo);
2641 if (error)
2642 goto done;
2643 } else {
2644 unlock_err = got_ref_unlock(ref);
2645 if (unlock_err && error == NULL)
2646 error = unlock_err;
2647 got_ref_close(ref);
2651 if (delete_refs) {
2652 error = delete_missing_refs(&refs, &symrefs, remote,
2653 verbosity, repo);
2654 if (error)
2655 goto done;
2658 if (!remote->mirror_references) {
2659 /* Update remote HEAD reference if the server provided one. */
2660 TAILQ_FOREACH(pe, &symrefs, entry) {
2661 struct got_reference *target_ref;
2662 const char *refname = pe->path;
2663 const char *target = pe->data;
2664 char *remote_refname = NULL, *remote_target = NULL;
2666 if (strcmp(refname, GOT_REF_HEAD) != 0)
2667 continue;
2669 if (strncmp("refs/heads/", target, 11) != 0)
2670 continue;
2672 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2673 remote->name, refname) == -1) {
2674 error = got_error_from_errno("asprintf");
2675 goto done;
2677 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2678 remote->name, target + 11) == -1) {
2679 error = got_error_from_errno("asprintf");
2680 free(remote_refname);
2681 goto done;
2684 error = got_ref_open(&target_ref, repo, remote_target,
2685 0);
2686 if (error) {
2687 free(remote_refname);
2688 free(remote_target);
2689 if (error->code == GOT_ERR_NOT_REF) {
2690 error = NULL;
2691 continue;
2693 goto done;
2695 error = update_symref(remote_refname, target_ref,
2696 verbosity, repo);
2697 free(remote_refname);
2698 free(remote_target);
2699 got_ref_close(target_ref);
2700 if (error)
2701 goto done;
2704 done:
2705 if (fetchpid > 0) {
2706 if (kill(fetchpid, SIGTERM) == -1)
2707 error = got_error_from_errno("kill");
2708 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2709 error = got_error_from_errno("waitpid");
2711 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2712 error = got_error_from_errno("close");
2713 if (repo) {
2714 const struct got_error *close_err = got_repo_close(repo);
2715 if (error == NULL)
2716 error = close_err;
2718 if (worktree)
2719 got_worktree_close(worktree);
2720 if (pack_fds) {
2721 const struct got_error *pack_err =
2722 got_repo_pack_fds_close(pack_fds);
2723 if (error == NULL)
2724 error = pack_err;
2726 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2727 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2728 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2729 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2730 free(id_str);
2731 free(cwd);
2732 free(repo_path);
2733 free(pack_hash);
2734 free(proto);
2735 free(host);
2736 free(port);
2737 free(server_path);
2738 free(repo_name);
2739 return error;
2743 __dead static void
2744 usage_checkout(void)
2746 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2747 "[-p path-prefix] repository-path [work-tree-path]\n",
2748 getprogname());
2749 exit(1);
2752 static void
2753 show_worktree_base_ref_warning(void)
2755 fprintf(stderr, "%s: warning: could not create a reference "
2756 "to the work tree's base commit; the commit could be "
2757 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2758 "repository writable and running 'got update' will prevent this\n",
2759 getprogname());
2762 struct got_checkout_progress_arg {
2763 const char *worktree_path;
2764 int had_base_commit_ref_error;
2765 int verbosity;
2768 static const struct got_error *
2769 checkout_progress(void *arg, unsigned char status, const char *path)
2771 struct got_checkout_progress_arg *a = arg;
2773 /* Base commit bump happens silently. */
2774 if (status == GOT_STATUS_BUMP_BASE)
2775 return NULL;
2777 if (status == GOT_STATUS_BASE_REF_ERR) {
2778 a->had_base_commit_ref_error = 1;
2779 return NULL;
2782 while (path[0] == '/')
2783 path++;
2785 if (a->verbosity >= 0)
2786 printf("%c %s/%s\n", status, a->worktree_path, path);
2788 return NULL;
2791 static const struct got_error *
2792 check_cancelled(void *arg)
2794 if (sigint_received || sigpipe_received)
2795 return got_error(GOT_ERR_CANCELLED);
2796 return NULL;
2799 static const struct got_error *
2800 check_linear_ancestry(struct got_object_id *commit_id,
2801 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2802 struct got_repository *repo)
2804 const struct got_error *err = NULL;
2805 struct got_object_id *yca_id;
2807 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2808 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2809 if (err)
2810 return err;
2812 if (yca_id == NULL)
2813 return got_error(GOT_ERR_ANCESTRY);
2816 * Require a straight line of history between the target commit
2817 * and the work tree's base commit.
2819 * Non-linear situations such as this require a rebase:
2821 * (commit) D F (base_commit)
2822 * \ /
2823 * C E
2824 * \ /
2825 * B (yca)
2826 * |
2827 * A
2829 * 'got update' only handles linear cases:
2830 * Update forwards in time: A (base/yca) - B - C - D (commit)
2831 * Update backwards in time: D (base) - C - B - A (commit/yca)
2833 if (allow_forwards_in_time_only) {
2834 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2835 return got_error(GOT_ERR_ANCESTRY);
2836 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2837 got_object_id_cmp(base_commit_id, yca_id) != 0)
2838 return got_error(GOT_ERR_ANCESTRY);
2840 free(yca_id);
2841 return NULL;
2844 static const struct got_error *
2845 check_same_branch(struct got_object_id *commit_id,
2846 struct got_reference *head_ref, struct got_object_id *yca_id,
2847 struct got_repository *repo)
2849 const struct got_error *err = NULL;
2850 struct got_commit_graph *graph = NULL;
2851 struct got_object_id *head_commit_id = NULL;
2852 int is_same_branch = 0;
2854 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2855 if (err)
2856 goto done;
2858 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2859 is_same_branch = 1;
2860 goto done;
2862 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2863 is_same_branch = 1;
2864 goto done;
2867 err = got_commit_graph_open(&graph, "/", 1);
2868 if (err)
2869 goto done;
2871 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2872 check_cancelled, NULL);
2873 if (err)
2874 goto done;
2876 for (;;) {
2877 struct got_object_id id;
2879 err = got_commit_graph_iter_next(&id, graph, repo,
2880 check_cancelled, NULL);
2881 if (err) {
2882 if (err->code == GOT_ERR_ITER_COMPLETED)
2883 err = NULL;
2884 break;
2887 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2888 break;
2889 if (got_object_id_cmp(&id, commit_id) == 0) {
2890 is_same_branch = 1;
2891 break;
2894 done:
2895 if (graph)
2896 got_commit_graph_close(graph);
2897 free(head_commit_id);
2898 if (!err && !is_same_branch)
2899 err = got_error(GOT_ERR_ANCESTRY);
2900 return err;
2903 static const struct got_error *
2904 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2906 static char msg[512];
2907 const char *branch_name;
2909 if (got_ref_is_symbolic(ref))
2910 branch_name = got_ref_get_symref_target(ref);
2911 else
2912 branch_name = got_ref_get_name(ref);
2914 if (strncmp("refs/heads/", branch_name, 11) == 0)
2915 branch_name += 11;
2917 snprintf(msg, sizeof(msg),
2918 "target commit is not contained in branch '%s'; "
2919 "the branch to use must be specified with -b; "
2920 "if necessary a new branch can be created for "
2921 "this commit with 'got branch -c %s BRANCH_NAME'",
2922 branch_name, commit_id_str);
2924 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2927 static const struct got_error *
2928 cmd_checkout(int argc, char *argv[])
2930 const struct got_error *error = NULL;
2931 struct got_repository *repo = NULL;
2932 struct got_reference *head_ref = NULL, *ref = NULL;
2933 struct got_worktree *worktree = NULL;
2934 char *repo_path = NULL;
2935 char *worktree_path = NULL;
2936 const char *path_prefix = "";
2937 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2938 char *commit_id_str = NULL;
2939 struct got_object_id *commit_id = NULL;
2940 char *cwd = NULL;
2941 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2942 struct got_pathlist_head paths;
2943 struct got_checkout_progress_arg cpa;
2944 int *pack_fds = NULL;
2946 TAILQ_INIT(&paths);
2948 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2949 switch (ch) {
2950 case 'b':
2951 branch_name = optarg;
2952 break;
2953 case 'c':
2954 commit_id_str = strdup(optarg);
2955 if (commit_id_str == NULL)
2956 return got_error_from_errno("strdup");
2957 break;
2958 case 'E':
2959 allow_nonempty = 1;
2960 break;
2961 case 'p':
2962 path_prefix = optarg;
2963 break;
2964 case 'q':
2965 verbosity = -1;
2966 break;
2967 default:
2968 usage_checkout();
2969 /* NOTREACHED */
2973 argc -= optind;
2974 argv += optind;
2976 #ifndef PROFILE
2977 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2978 "unveil", NULL) == -1)
2979 err(1, "pledge");
2980 #endif
2981 if (argc == 1) {
2982 char *base, *dotgit;
2983 const char *path;
2984 repo_path = realpath(argv[0], NULL);
2985 if (repo_path == NULL)
2986 return got_error_from_errno2("realpath", argv[0]);
2987 cwd = getcwd(NULL, 0);
2988 if (cwd == NULL) {
2989 error = got_error_from_errno("getcwd");
2990 goto done;
2992 if (path_prefix[0])
2993 path = path_prefix;
2994 else
2995 path = repo_path;
2996 error = got_path_basename(&base, path);
2997 if (error)
2998 goto done;
2999 dotgit = strstr(base, ".git");
3000 if (dotgit)
3001 *dotgit = '\0';
3002 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3003 error = got_error_from_errno("asprintf");
3004 free(base);
3005 goto done;
3007 free(base);
3008 } else if (argc == 2) {
3009 repo_path = realpath(argv[0], NULL);
3010 if (repo_path == NULL) {
3011 error = got_error_from_errno2("realpath", argv[0]);
3012 goto done;
3014 worktree_path = realpath(argv[1], NULL);
3015 if (worktree_path == NULL) {
3016 if (errno != ENOENT) {
3017 error = got_error_from_errno2("realpath",
3018 argv[1]);
3019 goto done;
3021 worktree_path = strdup(argv[1]);
3022 if (worktree_path == NULL) {
3023 error = got_error_from_errno("strdup");
3024 goto done;
3027 } else
3028 usage_checkout();
3030 got_path_strip_trailing_slashes(repo_path);
3031 got_path_strip_trailing_slashes(worktree_path);
3033 error = got_repo_pack_fds_open(&pack_fds);
3034 if (error != NULL)
3035 goto done;
3037 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3038 if (error != NULL)
3039 goto done;
3041 /* Pre-create work tree path for unveil(2) */
3042 error = got_path_mkdir(worktree_path);
3043 if (error) {
3044 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3045 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3046 goto done;
3047 if (!allow_nonempty &&
3048 !got_path_dir_is_empty(worktree_path)) {
3049 error = got_error_path(worktree_path,
3050 GOT_ERR_DIR_NOT_EMPTY);
3051 goto done;
3055 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3056 if (error)
3057 goto done;
3059 error = got_ref_open(&head_ref, repo, branch_name, 0);
3060 if (error != NULL)
3061 goto done;
3063 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3064 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3065 goto done;
3067 error = got_worktree_open(&worktree, worktree_path);
3068 if (error != NULL)
3069 goto done;
3071 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3072 path_prefix);
3073 if (error != NULL)
3074 goto done;
3075 if (!same_path_prefix) {
3076 error = got_error(GOT_ERR_PATH_PREFIX);
3077 goto done;
3080 if (commit_id_str) {
3081 struct got_reflist_head refs;
3082 TAILQ_INIT(&refs);
3083 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3084 NULL);
3085 if (error)
3086 goto done;
3087 error = got_repo_match_object_id(&commit_id, NULL,
3088 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3089 got_ref_list_free(&refs);
3090 if (error)
3091 goto done;
3092 error = check_linear_ancestry(commit_id,
3093 got_worktree_get_base_commit_id(worktree), 0, repo);
3094 if (error != NULL) {
3095 if (error->code == GOT_ERR_ANCESTRY) {
3096 error = checkout_ancestry_error(
3097 head_ref, commit_id_str);
3099 goto done;
3101 error = check_same_branch(commit_id, head_ref, NULL, repo);
3102 if (error) {
3103 if (error->code == GOT_ERR_ANCESTRY) {
3104 error = checkout_ancestry_error(
3105 head_ref, commit_id_str);
3107 goto done;
3109 error = got_worktree_set_base_commit_id(worktree, repo,
3110 commit_id);
3111 if (error)
3112 goto done;
3113 /* Expand potentially abbreviated commit ID string. */
3114 free(commit_id_str);
3115 error = got_object_id_str(&commit_id_str, commit_id);
3116 if (error)
3117 goto done;
3118 } else {
3119 commit_id = got_object_id_dup(
3120 got_worktree_get_base_commit_id(worktree));
3121 if (commit_id == NULL) {
3122 error = got_error_from_errno("got_object_id_dup");
3123 goto done;
3125 error = got_object_id_str(&commit_id_str, commit_id);
3126 if (error)
3127 goto done;
3130 error = got_pathlist_append(&paths, "", NULL);
3131 if (error)
3132 goto done;
3133 cpa.worktree_path = worktree_path;
3134 cpa.had_base_commit_ref_error = 0;
3135 cpa.verbosity = verbosity;
3136 error = got_worktree_checkout_files(worktree, &paths, repo,
3137 checkout_progress, &cpa, check_cancelled, NULL);
3138 if (error != NULL)
3139 goto done;
3141 if (got_ref_is_symbolic(head_ref)) {
3142 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3143 if (error)
3144 goto done;
3145 refname = got_ref_get_name(ref);
3146 } else
3147 refname = got_ref_get_name(head_ref);
3148 printf("Checked out %s: %s\n", refname, commit_id_str);
3149 printf("Now shut up and hack\n");
3150 if (cpa.had_base_commit_ref_error)
3151 show_worktree_base_ref_warning();
3152 done:
3153 if (pack_fds) {
3154 const struct got_error *pack_err =
3155 got_repo_pack_fds_close(pack_fds);
3156 if (error == NULL)
3157 error = pack_err;
3159 if (head_ref)
3160 got_ref_close(head_ref);
3161 if (ref)
3162 got_ref_close(ref);
3163 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3164 free(commit_id_str);
3165 free(commit_id);
3166 free(repo_path);
3167 free(worktree_path);
3168 free(cwd);
3169 return error;
3172 struct got_update_progress_arg {
3173 int did_something;
3174 int conflicts;
3175 int obstructed;
3176 int not_updated;
3177 int missing;
3178 int not_deleted;
3179 int unversioned;
3180 int verbosity;
3183 static void
3184 print_update_progress_stats(struct got_update_progress_arg *upa)
3186 if (!upa->did_something)
3187 return;
3189 if (upa->conflicts > 0)
3190 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3191 if (upa->obstructed > 0)
3192 printf("File paths obstructed by a non-regular file: %d\n",
3193 upa->obstructed);
3194 if (upa->not_updated > 0)
3195 printf("Files not updated because of existing merge "
3196 "conflicts: %d\n", upa->not_updated);
3200 * The meaning of some status codes differs between merge-style operations and
3201 * update operations. For example, the ! status code means "file was missing"
3202 * if changes were merged into the work tree, and "missing file was restored"
3203 * if the work tree was updated. This function should be used by any operation
3204 * which merges changes into the work tree without updating the work tree.
3206 static void
3207 print_merge_progress_stats(struct got_update_progress_arg *upa)
3209 if (!upa->did_something)
3210 return;
3212 if (upa->conflicts > 0)
3213 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3214 if (upa->obstructed > 0)
3215 printf("File paths obstructed by a non-regular file: %d\n",
3216 upa->obstructed);
3217 if (upa->missing > 0)
3218 printf("Files which had incoming changes but could not be "
3219 "found in the work tree: %d\n", upa->missing);
3220 if (upa->not_deleted > 0)
3221 printf("Files not deleted due to differences in deleted "
3222 "content: %d\n", upa->not_deleted);
3223 if (upa->unversioned > 0)
3224 printf("Files not merged because an unversioned file was "
3225 "found in the work tree: %d\n", upa->unversioned);
3228 __dead static void
3229 usage_update(void)
3231 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3232 "[path ...]\n", getprogname());
3233 exit(1);
3236 static const struct got_error *
3237 update_progress(void *arg, unsigned char status, const char *path)
3239 struct got_update_progress_arg *upa = arg;
3241 if (status == GOT_STATUS_EXISTS ||
3242 status == GOT_STATUS_BASE_REF_ERR)
3243 return NULL;
3245 upa->did_something = 1;
3247 /* Base commit bump happens silently. */
3248 if (status == GOT_STATUS_BUMP_BASE)
3249 return NULL;
3251 if (status == GOT_STATUS_CONFLICT)
3252 upa->conflicts++;
3253 if (status == GOT_STATUS_OBSTRUCTED)
3254 upa->obstructed++;
3255 if (status == GOT_STATUS_CANNOT_UPDATE)
3256 upa->not_updated++;
3257 if (status == GOT_STATUS_MISSING)
3258 upa->missing++;
3259 if (status == GOT_STATUS_CANNOT_DELETE)
3260 upa->not_deleted++;
3261 if (status == GOT_STATUS_UNVERSIONED)
3262 upa->unversioned++;
3264 while (path[0] == '/')
3265 path++;
3266 if (upa->verbosity >= 0)
3267 printf("%c %s\n", status, path);
3269 return NULL;
3272 static const struct got_error *
3273 switch_head_ref(struct got_reference *head_ref,
3274 struct got_object_id *commit_id, struct got_worktree *worktree,
3275 struct got_repository *repo)
3277 const struct got_error *err = NULL;
3278 char *base_id_str;
3279 int ref_has_moved = 0;
3281 /* Trivial case: switching between two different references. */
3282 if (strcmp(got_ref_get_name(head_ref),
3283 got_worktree_get_head_ref_name(worktree)) != 0) {
3284 printf("Switching work tree from %s to %s\n",
3285 got_worktree_get_head_ref_name(worktree),
3286 got_ref_get_name(head_ref));
3287 return got_worktree_set_head_ref(worktree, head_ref);
3290 err = check_linear_ancestry(commit_id,
3291 got_worktree_get_base_commit_id(worktree), 0, repo);
3292 if (err) {
3293 if (err->code != GOT_ERR_ANCESTRY)
3294 return err;
3295 ref_has_moved = 1;
3297 if (!ref_has_moved)
3298 return NULL;
3300 /* Switching to a rebased branch with the same reference name. */
3301 err = got_object_id_str(&base_id_str,
3302 got_worktree_get_base_commit_id(worktree));
3303 if (err)
3304 return err;
3305 printf("Reference %s now points at a different branch\n",
3306 got_worktree_get_head_ref_name(worktree));
3307 printf("Switching work tree from %s to %s\n", base_id_str,
3308 got_worktree_get_head_ref_name(worktree));
3309 return NULL;
3312 static const struct got_error *
3313 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3315 const struct got_error *err;
3316 int in_progress;
3318 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3319 if (err)
3320 return err;
3321 if (in_progress)
3322 return got_error(GOT_ERR_REBASING);
3324 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3325 if (err)
3326 return err;
3327 if (in_progress)
3328 return got_error(GOT_ERR_HISTEDIT_BUSY);
3330 return NULL;
3333 static const struct got_error *
3334 check_merge_in_progress(struct got_worktree *worktree,
3335 struct got_repository *repo)
3337 const struct got_error *err;
3338 int in_progress;
3340 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3341 if (err)
3342 return err;
3343 if (in_progress)
3344 return got_error(GOT_ERR_MERGE_BUSY);
3346 return NULL;
3349 static const struct got_error *
3350 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3351 char *argv[], struct got_worktree *worktree)
3353 const struct got_error *err = NULL;
3354 char *path;
3355 struct got_pathlist_entry *new;
3356 int i;
3358 if (argc == 0) {
3359 path = strdup("");
3360 if (path == NULL)
3361 return got_error_from_errno("strdup");
3362 return got_pathlist_append(paths, path, NULL);
3365 for (i = 0; i < argc; i++) {
3366 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3367 if (err)
3368 break;
3369 err = got_pathlist_insert(&new, paths, path, NULL);
3370 if (err || new == NULL /* duplicate */) {
3371 free(path);
3372 if (err)
3373 break;
3377 return err;
3380 static const struct got_error *
3381 wrap_not_worktree_error(const struct got_error *orig_err,
3382 const char *cmdname, const char *path)
3384 const struct got_error *err;
3385 struct got_repository *repo;
3386 static char msg[512];
3387 int *pack_fds = NULL;
3389 err = got_repo_pack_fds_open(&pack_fds);
3390 if (err)
3391 return err;
3393 err = got_repo_open(&repo, path, NULL, pack_fds);
3394 if (err)
3395 return orig_err;
3397 snprintf(msg, sizeof(msg),
3398 "'got %s' needs a work tree in addition to a git repository\n"
3399 "Work trees can be checked out from this Git repository with "
3400 "'got checkout'.\n"
3401 "The got(1) manual page contains more information.", cmdname);
3402 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3403 got_repo_close(repo);
3404 if (pack_fds) {
3405 const struct got_error *pack_err =
3406 got_repo_pack_fds_close(pack_fds);
3407 if (err == NULL)
3408 err = pack_err;
3410 return err;
3413 static const struct got_error *
3414 cmd_update(int argc, char *argv[])
3416 const struct got_error *error = NULL;
3417 struct got_repository *repo = NULL;
3418 struct got_worktree *worktree = NULL;
3419 char *worktree_path = NULL;
3420 struct got_object_id *commit_id = NULL;
3421 char *commit_id_str = NULL;
3422 const char *branch_name = NULL;
3423 struct got_reference *head_ref = NULL;
3424 struct got_pathlist_head paths;
3425 struct got_pathlist_entry *pe;
3426 int ch, verbosity = 0;
3427 struct got_update_progress_arg upa;
3428 int *pack_fds = NULL;
3430 TAILQ_INIT(&paths);
3432 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3433 switch (ch) {
3434 case 'b':
3435 branch_name = optarg;
3436 break;
3437 case 'c':
3438 commit_id_str = strdup(optarg);
3439 if (commit_id_str == NULL)
3440 return got_error_from_errno("strdup");
3441 break;
3442 case 'q':
3443 verbosity = -1;
3444 break;
3445 default:
3446 usage_update();
3447 /* NOTREACHED */
3451 argc -= optind;
3452 argv += optind;
3454 #ifndef PROFILE
3455 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3456 "unveil", NULL) == -1)
3457 err(1, "pledge");
3458 #endif
3459 worktree_path = getcwd(NULL, 0);
3460 if (worktree_path == NULL) {
3461 error = got_error_from_errno("getcwd");
3462 goto done;
3465 error = got_repo_pack_fds_open(&pack_fds);
3466 if (error != NULL)
3467 goto done;
3469 error = got_worktree_open(&worktree, worktree_path);
3470 if (error) {
3471 if (error->code == GOT_ERR_NOT_WORKTREE)
3472 error = wrap_not_worktree_error(error, "update",
3473 worktree_path);
3474 goto done;
3477 error = check_rebase_or_histedit_in_progress(worktree);
3478 if (error)
3479 goto done;
3481 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3482 NULL, pack_fds);
3483 if (error != NULL)
3484 goto done;
3486 error = apply_unveil(got_repo_get_path(repo), 0,
3487 got_worktree_get_root_path(worktree));
3488 if (error)
3489 goto done;
3491 error = check_merge_in_progress(worktree, repo);
3492 if (error)
3493 goto done;
3495 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3496 if (error)
3497 goto done;
3499 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3500 got_worktree_get_head_ref_name(worktree), 0);
3501 if (error != NULL)
3502 goto done;
3503 if (commit_id_str == NULL) {
3504 error = got_ref_resolve(&commit_id, repo, head_ref);
3505 if (error != NULL)
3506 goto done;
3507 error = got_object_id_str(&commit_id_str, commit_id);
3508 if (error != NULL)
3509 goto done;
3510 } else {
3511 struct got_reflist_head refs;
3512 TAILQ_INIT(&refs);
3513 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3514 NULL);
3515 if (error)
3516 goto done;
3517 error = got_repo_match_object_id(&commit_id, NULL,
3518 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3519 got_ref_list_free(&refs);
3520 free(commit_id_str);
3521 commit_id_str = NULL;
3522 if (error)
3523 goto done;
3524 error = got_object_id_str(&commit_id_str, commit_id);
3525 if (error)
3526 goto done;
3529 if (branch_name) {
3530 struct got_object_id *head_commit_id;
3531 TAILQ_FOREACH(pe, &paths, entry) {
3532 if (pe->path_len == 0)
3533 continue;
3534 error = got_error_msg(GOT_ERR_BAD_PATH,
3535 "switching between branches requires that "
3536 "the entire work tree gets updated");
3537 goto done;
3539 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3540 if (error)
3541 goto done;
3542 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3543 repo);
3544 free(head_commit_id);
3545 if (error != NULL)
3546 goto done;
3547 error = check_same_branch(commit_id, head_ref, NULL, repo);
3548 if (error)
3549 goto done;
3550 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3551 if (error)
3552 goto done;
3553 } else {
3554 error = check_linear_ancestry(commit_id,
3555 got_worktree_get_base_commit_id(worktree), 0, repo);
3556 if (error != NULL) {
3557 if (error->code == GOT_ERR_ANCESTRY)
3558 error = got_error(GOT_ERR_BRANCH_MOVED);
3559 goto done;
3561 error = check_same_branch(commit_id, head_ref, NULL, repo);
3562 if (error)
3563 goto done;
3566 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3567 commit_id) != 0) {
3568 error = got_worktree_set_base_commit_id(worktree, repo,
3569 commit_id);
3570 if (error)
3571 goto done;
3574 memset(&upa, 0, sizeof(upa));
3575 upa.verbosity = verbosity;
3576 error = got_worktree_checkout_files(worktree, &paths, repo,
3577 update_progress, &upa, check_cancelled, NULL);
3578 if (error != NULL)
3579 goto done;
3581 if (upa.did_something) {
3582 printf("Updated to %s: %s\n",
3583 got_worktree_get_head_ref_name(worktree), commit_id_str);
3584 } else
3585 printf("Already up-to-date\n");
3587 print_update_progress_stats(&upa);
3588 done:
3589 if (pack_fds) {
3590 const struct got_error *pack_err =
3591 got_repo_pack_fds_close(pack_fds);
3592 if (error == NULL)
3593 error = pack_err;
3595 free(worktree_path);
3596 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3597 free(commit_id);
3598 free(commit_id_str);
3599 return error;
3602 static const struct got_error *
3603 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3604 const char *path, int diff_context, int ignore_whitespace,
3605 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3606 struct got_repository *repo, FILE *outfile)
3608 const struct got_error *err = NULL;
3609 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3610 FILE *f1 = NULL, *f2 = NULL;
3611 int fd1 = -1, fd2 = -1;
3613 fd1 = got_opentempfd();
3614 if (fd1 == -1)
3615 return got_error_from_errno("got_opentempfd");
3616 fd2 = got_opentempfd();
3617 if (fd2 == -1) {
3618 err = got_error_from_errno("got_opentempfd");
3619 goto done;
3622 if (blob_id1) {
3623 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3624 fd1);
3625 if (err)
3626 goto done;
3629 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3630 if (err)
3631 goto done;
3633 f1 = got_opentemp();
3634 if (f1 == NULL) {
3635 err = got_error_from_errno("got_opentemp");
3636 goto done;
3638 f2 = got_opentemp();
3639 if (f2 == NULL) {
3640 err = got_error_from_errno("got_opentemp");
3641 goto done;
3644 while (path[0] == '/')
3645 path++;
3646 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3647 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3648 force_text_diff, dsa, outfile);
3649 done:
3650 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3651 err = got_error_from_errno("close");
3652 if (blob1)
3653 got_object_blob_close(blob1);
3654 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3655 err = got_error_from_errno("close");
3656 got_object_blob_close(blob2);
3657 if (f1 && fclose(f1) == EOF && err == NULL)
3658 err = got_error_from_errno("fclose");
3659 if (f2 && fclose(f2) == EOF && err == NULL)
3660 err = got_error_from_errno("fclose");
3661 return err;
3664 static const struct got_error *
3665 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3666 const char *path, int diff_context, int ignore_whitespace,
3667 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3668 struct got_repository *repo, FILE *outfile)
3670 const struct got_error *err = NULL;
3671 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3672 struct got_diff_blob_output_unidiff_arg arg;
3673 FILE *f1 = NULL, *f2 = NULL;
3674 int fd1 = -1, fd2 = -1;
3676 if (tree_id1) {
3677 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3678 if (err)
3679 goto done;
3680 fd1 = got_opentempfd();
3681 if (fd1 == -1) {
3682 err = got_error_from_errno("got_opentempfd");
3683 goto done;
3687 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3688 if (err)
3689 goto done;
3691 f1 = got_opentemp();
3692 if (f1 == NULL) {
3693 err = got_error_from_errno("got_opentemp");
3694 goto done;
3697 f2 = got_opentemp();
3698 if (f2 == NULL) {
3699 err = got_error_from_errno("got_opentemp");
3700 goto done;
3702 fd2 = got_opentempfd();
3703 if (fd2 == -1) {
3704 err = got_error_from_errno("got_opentempfd");
3705 goto done;
3707 arg.diff_context = diff_context;
3708 arg.ignore_whitespace = ignore_whitespace;
3709 arg.force_text_diff = force_text_diff;
3710 arg.diffstat = dsa;
3711 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3712 arg.outfile = outfile;
3713 arg.lines = NULL;
3714 arg.nlines = 0;
3715 while (path[0] == '/')
3716 path++;
3717 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3718 got_diff_blob_output_unidiff, &arg, 1);
3719 done:
3720 if (tree1)
3721 got_object_tree_close(tree1);
3722 if (tree2)
3723 got_object_tree_close(tree2);
3724 if (f1 && fclose(f1) == EOF && err == NULL)
3725 err = got_error_from_errno("fclose");
3726 if (f2 && fclose(f2) == EOF && err == NULL)
3727 err = got_error_from_errno("fclose");
3728 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3729 err = got_error_from_errno("close");
3730 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3731 err = got_error_from_errno("close");
3732 return err;
3735 static const struct got_error *
3736 get_changed_paths(struct got_pathlist_head *paths,
3737 struct got_commit_object *commit, struct got_repository *repo,
3738 struct got_diffstat_cb_arg *dsa)
3740 const struct got_error *err = NULL;
3741 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3742 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3743 struct got_object_qid *qid;
3744 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3745 FILE *f1 = NULL, *f2 = NULL;
3746 int fd1 = -1, fd2 = -1;
3748 if (dsa) {
3749 cb = got_diff_tree_compute_diffstat;
3751 f1 = got_opentemp();
3752 if (f1 == NULL) {
3753 err = got_error_from_errno("got_opentemp");
3754 goto done;
3756 f2 = got_opentemp();
3757 if (f2 == NULL) {
3758 err = got_error_from_errno("got_opentemp");
3759 goto done;
3761 fd1 = got_opentempfd();
3762 if (fd1 == -1) {
3763 err = got_error_from_errno("got_opentempfd");
3764 goto done;
3766 fd2 = got_opentempfd();
3767 if (fd2 == -1) {
3768 err = got_error_from_errno("got_opentempfd");
3769 goto done;
3773 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3774 if (qid != NULL) {
3775 struct got_commit_object *pcommit;
3776 err = got_object_open_as_commit(&pcommit, repo,
3777 &qid->id);
3778 if (err)
3779 return err;
3781 tree_id1 = got_object_id_dup(
3782 got_object_commit_get_tree_id(pcommit));
3783 if (tree_id1 == NULL) {
3784 got_object_commit_close(pcommit);
3785 return got_error_from_errno("got_object_id_dup");
3787 got_object_commit_close(pcommit);
3791 if (tree_id1) {
3792 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3793 if (err)
3794 goto done;
3797 tree_id2 = got_object_commit_get_tree_id(commit);
3798 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3799 if (err)
3800 goto done;
3802 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3803 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3804 done:
3805 if (tree1)
3806 got_object_tree_close(tree1);
3807 if (tree2)
3808 got_object_tree_close(tree2);
3809 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3810 err = got_error_from_errno("close");
3811 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3812 err = got_error_from_errno("close");
3813 if (f1 && fclose(f1) == EOF && err == NULL)
3814 err = got_error_from_errno("fclose");
3815 if (f2 && fclose(f2) == EOF && err == NULL)
3816 err = got_error_from_errno("fclose");
3817 free(tree_id1);
3818 return err;
3821 static const struct got_error *
3822 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3823 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3824 struct got_repository *repo, FILE *outfile)
3826 const struct got_error *err = NULL;
3827 struct got_commit_object *pcommit = NULL;
3828 char *id_str1 = NULL, *id_str2 = NULL;
3829 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3830 struct got_object_qid *qid;
3832 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3833 if (qid != NULL) {
3834 err = got_object_open_as_commit(&pcommit, repo,
3835 &qid->id);
3836 if (err)
3837 return err;
3838 err = got_object_id_str(&id_str1, &qid->id);
3839 if (err)
3840 goto done;
3843 err = got_object_id_str(&id_str2, id);
3844 if (err)
3845 goto done;
3847 if (path && path[0] != '\0') {
3848 int obj_type;
3849 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3850 if (err)
3851 goto done;
3852 if (pcommit) {
3853 err = got_object_id_by_path(&obj_id1, repo,
3854 pcommit, path);
3855 if (err) {
3856 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3857 free(obj_id2);
3858 goto done;
3862 err = got_object_get_type(&obj_type, repo, obj_id2);
3863 if (err) {
3864 free(obj_id2);
3865 goto done;
3867 fprintf(outfile,
3868 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3869 fprintf(outfile, "commit - %s\n",
3870 id_str1 ? id_str1 : "/dev/null");
3871 fprintf(outfile, "commit + %s\n", id_str2);
3872 switch (obj_type) {
3873 case GOT_OBJ_TYPE_BLOB:
3874 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3875 0, 0, dsa, repo, outfile);
3876 break;
3877 case GOT_OBJ_TYPE_TREE:
3878 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3879 0, 0, dsa, repo, outfile);
3880 break;
3881 default:
3882 err = got_error(GOT_ERR_OBJ_TYPE);
3883 break;
3885 free(obj_id1);
3886 free(obj_id2);
3887 } else {
3888 obj_id2 = got_object_commit_get_tree_id(commit);
3889 if (pcommit)
3890 obj_id1 = got_object_commit_get_tree_id(pcommit);
3891 fprintf(outfile,
3892 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3893 fprintf(outfile, "commit - %s\n",
3894 id_str1 ? id_str1 : "/dev/null");
3895 fprintf(outfile, "commit + %s\n", id_str2);
3896 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3897 dsa, repo, outfile);
3899 done:
3900 free(id_str1);
3901 free(id_str2);
3902 if (pcommit)
3903 got_object_commit_close(pcommit);
3904 return err;
3907 static char *
3908 get_datestr(time_t *time, char *datebuf)
3910 struct tm mytm, *tm;
3911 char *p, *s;
3913 tm = gmtime_r(time, &mytm);
3914 if (tm == NULL)
3915 return NULL;
3916 s = asctime_r(tm, datebuf);
3917 if (s == NULL)
3918 return NULL;
3919 p = strchr(s, '\n');
3920 if (p)
3921 *p = '\0';
3922 return s;
3925 static const struct got_error *
3926 match_commit(int *have_match, struct got_object_id *id,
3927 struct got_commit_object *commit, regex_t *regex)
3929 const struct got_error *err = NULL;
3930 regmatch_t regmatch;
3931 char *id_str = NULL, *logmsg = NULL;
3933 *have_match = 0;
3935 err = got_object_id_str(&id_str, id);
3936 if (err)
3937 return err;
3939 err = got_object_commit_get_logmsg(&logmsg, commit);
3940 if (err)
3941 goto done;
3943 if (regexec(regex, got_object_commit_get_author(commit), 1,
3944 &regmatch, 0) == 0 ||
3945 regexec(regex, got_object_commit_get_committer(commit), 1,
3946 &regmatch, 0) == 0 ||
3947 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3948 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3949 *have_match = 1;
3950 done:
3951 free(id_str);
3952 free(logmsg);
3953 return err;
3956 static void
3957 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3958 regex_t *regex)
3960 regmatch_t regmatch;
3961 struct got_pathlist_entry *pe;
3963 *have_match = 0;
3965 TAILQ_FOREACH(pe, changed_paths, entry) {
3966 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3967 *have_match = 1;
3968 break;
3973 static const struct got_error *
3974 match_patch(int *have_match, struct got_commit_object *commit,
3975 struct got_object_id *id, const char *path, int diff_context,
3976 struct got_repository *repo, regex_t *regex, FILE *f)
3978 const struct got_error *err = NULL;
3979 char *line = NULL;
3980 size_t linesize = 0;
3981 regmatch_t regmatch;
3983 *have_match = 0;
3985 err = got_opentemp_truncate(f);
3986 if (err)
3987 return err;
3989 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3990 if (err)
3991 goto done;
3993 if (fseeko(f, 0L, SEEK_SET) == -1) {
3994 err = got_error_from_errno("fseeko");
3995 goto done;
3998 while (getline(&line, &linesize, f) != -1) {
3999 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4000 *have_match = 1;
4001 break;
4004 done:
4005 free(line);
4006 return err;
4009 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4011 static const struct got_error*
4012 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4013 struct got_object_id *id, struct got_repository *repo,
4014 int local_only)
4016 static const struct got_error *err = NULL;
4017 struct got_reflist_entry *re;
4018 char *s;
4019 const char *name;
4021 *refs_str = NULL;
4023 TAILQ_FOREACH(re, refs, entry) {
4024 struct got_tag_object *tag = NULL;
4025 struct got_object_id *ref_id;
4026 int cmp;
4028 name = got_ref_get_name(re->ref);
4029 if (strcmp(name, GOT_REF_HEAD) == 0)
4030 continue;
4031 if (strncmp(name, "refs/", 5) == 0)
4032 name += 5;
4033 if (strncmp(name, "got/", 4) == 0)
4034 continue;
4035 if (strncmp(name, "heads/", 6) == 0)
4036 name += 6;
4037 if (strncmp(name, "remotes/", 8) == 0) {
4038 if (local_only)
4039 continue;
4040 name += 8;
4041 s = strstr(name, "/" GOT_REF_HEAD);
4042 if (s != NULL && s[strlen(s)] == '\0')
4043 continue;
4045 err = got_ref_resolve(&ref_id, repo, re->ref);
4046 if (err)
4047 break;
4048 if (strncmp(name, "tags/", 5) == 0) {
4049 err = got_object_open_as_tag(&tag, repo, ref_id);
4050 if (err) {
4051 if (err->code != GOT_ERR_OBJ_TYPE) {
4052 free(ref_id);
4053 break;
4055 /* Ref points at something other than a tag. */
4056 err = NULL;
4057 tag = NULL;
4060 cmp = got_object_id_cmp(tag ?
4061 got_object_tag_get_object_id(tag) : ref_id, id);
4062 free(ref_id);
4063 if (tag)
4064 got_object_tag_close(tag);
4065 if (cmp != 0)
4066 continue;
4067 s = *refs_str;
4068 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4069 s ? ", " : "", name) == -1) {
4070 err = got_error_from_errno("asprintf");
4071 free(s);
4072 *refs_str = NULL;
4073 break;
4075 free(s);
4078 return err;
4081 static const struct got_error *
4082 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4083 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4085 const struct got_error *err = NULL;
4086 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4087 char *comma, *s, *nl;
4088 struct got_reflist_head *refs;
4089 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4090 struct tm tm;
4091 time_t committer_time;
4093 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4094 if (refs) {
4095 err = build_refs_str(&ref_str, refs, id, repo, 1);
4096 if (err)
4097 return err;
4099 /* Display the first matching ref only. */
4100 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4101 *comma = '\0';
4104 if (ref_str == NULL) {
4105 err = got_object_id_str(&id_str, id);
4106 if (err)
4107 return err;
4110 committer_time = got_object_commit_get_committer_time(commit);
4111 if (gmtime_r(&committer_time, &tm) == NULL) {
4112 err = got_error_from_errno("gmtime_r");
4113 goto done;
4115 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4116 err = got_error(GOT_ERR_NO_SPACE);
4117 goto done;
4120 err = got_object_commit_get_logmsg(&logmsg0, commit);
4121 if (err)
4122 goto done;
4124 s = logmsg0;
4125 while (isspace((unsigned char)s[0]))
4126 s++;
4128 nl = strchr(s, '\n');
4129 if (nl) {
4130 *nl = '\0';
4133 if (ref_str)
4134 printf("%s%-7s %s\n", datebuf, ref_str, s);
4135 else
4136 printf("%s%.7s %s\n", datebuf, id_str, s);
4138 if (fflush(stdout) != 0 && err == NULL)
4139 err = got_error_from_errno("fflush");
4140 done:
4141 free(id_str);
4142 free(ref_str);
4143 free(logmsg0);
4144 return err;
4147 static const struct got_error *
4148 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4150 struct got_pathlist_entry *pe;
4152 if (header != NULL)
4153 printf("%s\n", header);
4155 TAILQ_FOREACH(pe, dsa->paths, entry) {
4156 struct got_diff_changed_path *cp = pe->data;
4157 int pad = dsa->max_path_len - pe->path_len + 1;
4159 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4160 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4162 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4163 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4164 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4166 if (fflush(stdout) != 0)
4167 return got_error_from_errno("fflush");
4169 return NULL;
4172 static const struct got_error *
4173 printfile(FILE *f)
4175 char buf[8192];
4176 size_t r;
4178 if (fseeko(f, 0L, SEEK_SET) == -1)
4179 return got_error_from_errno("fseek");
4181 for (;;) {
4182 r = fread(buf, 1, sizeof(buf), f);
4183 if (r == 0) {
4184 if (ferror(f))
4185 return got_error_from_errno("fread");
4186 if (feof(f))
4187 break;
4189 if (fwrite(buf, 1, r, stdout) != r)
4190 return got_ferror(stdout, GOT_ERR_IO);
4193 return NULL;
4196 static const struct got_error *
4197 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4198 struct got_repository *repo, const char *path,
4199 struct got_pathlist_head *changed_paths,
4200 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4201 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4203 const struct got_error *err = NULL;
4204 FILE *f = NULL;
4205 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4206 char datebuf[26];
4207 time_t committer_time;
4208 const char *author, *committer;
4209 char *refs_str = NULL;
4211 err = got_object_id_str(&id_str, id);
4212 if (err)
4213 return err;
4215 if (custom_refs_str == NULL) {
4216 struct got_reflist_head *refs;
4217 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4218 if (refs) {
4219 err = build_refs_str(&refs_str, refs, id, repo, 0);
4220 if (err)
4221 goto done;
4225 printf(GOT_COMMIT_SEP_STR);
4226 if (custom_refs_str)
4227 printf("commit %s (%s)\n", id_str, custom_refs_str);
4228 else
4229 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4230 refs_str ? refs_str : "", refs_str ? ")" : "");
4231 free(id_str);
4232 id_str = NULL;
4233 free(refs_str);
4234 refs_str = NULL;
4235 printf("from: %s\n", got_object_commit_get_author(commit));
4236 author = got_object_commit_get_author(commit);
4237 committer = got_object_commit_get_committer(commit);
4238 if (strcmp(author, committer) != 0)
4239 printf("via: %s\n", committer);
4240 committer_time = got_object_commit_get_committer_time(commit);
4241 datestr = get_datestr(&committer_time, datebuf);
4242 if (datestr)
4243 printf("date: %s UTC\n", datestr);
4244 if (got_object_commit_get_nparents(commit) > 1) {
4245 const struct got_object_id_queue *parent_ids;
4246 struct got_object_qid *qid;
4247 int n = 1;
4248 parent_ids = got_object_commit_get_parent_ids(commit);
4249 STAILQ_FOREACH(qid, parent_ids, entry) {
4250 err = got_object_id_str(&id_str, &qid->id);
4251 if (err)
4252 goto done;
4253 printf("parent %d: %s\n", n++, id_str);
4254 free(id_str);
4255 id_str = NULL;
4259 err = got_object_commit_get_logmsg(&logmsg0, commit);
4260 if (err)
4261 goto done;
4263 logmsg = logmsg0;
4264 do {
4265 line = strsep(&logmsg, "\n");
4266 if (line)
4267 printf(" %s\n", line);
4268 } while (line);
4269 free(logmsg0);
4271 if (changed_paths && diffstat == NULL) {
4272 struct got_pathlist_entry *pe;
4274 TAILQ_FOREACH(pe, changed_paths, entry) {
4275 struct got_diff_changed_path *cp = pe->data;
4277 printf(" %c %s\n", cp->status, pe->path);
4279 printf("\n");
4281 if (show_patch) {
4282 if (diffstat) {
4283 f = got_opentemp();
4284 if (f == NULL) {
4285 err = got_error_from_errno("got_opentemp");
4286 goto done;
4290 err = print_patch(commit, id, path, diff_context, diffstat,
4291 repo, diffstat == NULL ? stdout : f);
4292 if (err)
4293 goto done;
4295 if (diffstat) {
4296 err = print_diffstat(diffstat, NULL);
4297 if (err)
4298 goto done;
4299 if (show_patch) {
4300 err = printfile(f);
4301 if (err)
4302 goto done;
4305 if (show_patch)
4306 printf("\n");
4308 if (fflush(stdout) != 0 && err == NULL)
4309 err = got_error_from_errno("fflush");
4310 done:
4311 if (f && fclose(f) == EOF && err == NULL)
4312 err = got_error_from_errno("fclose");
4313 free(id_str);
4314 free(refs_str);
4315 return err;
4318 static const struct got_error *
4319 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4320 struct got_repository *repo, const char *path, int show_changed_paths,
4321 int show_diffstat, int show_patch, const char *search_pattern,
4322 int diff_context, int limit, int log_branches, int reverse_display_order,
4323 struct got_reflist_object_id_map *refs_idmap, int one_line,
4324 FILE *tmpfile)
4326 const struct got_error *err;
4327 struct got_commit_graph *graph;
4328 regex_t regex;
4329 int have_match;
4330 struct got_object_id_queue reversed_commits;
4331 struct got_object_qid *qid;
4332 struct got_commit_object *commit;
4333 struct got_pathlist_head changed_paths;
4335 STAILQ_INIT(&reversed_commits);
4336 TAILQ_INIT(&changed_paths);
4338 if (search_pattern && regcomp(&regex, search_pattern,
4339 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4340 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4342 err = got_commit_graph_open(&graph, path, !log_branches);
4343 if (err)
4344 return err;
4345 err = got_commit_graph_iter_start(graph, root_id, repo,
4346 check_cancelled, NULL);
4347 if (err)
4348 goto done;
4349 for (;;) {
4350 struct got_object_id id;
4351 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4352 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4354 if (sigint_received || sigpipe_received)
4355 break;
4357 err = got_commit_graph_iter_next(&id, graph, repo,
4358 check_cancelled, NULL);
4359 if (err) {
4360 if (err->code == GOT_ERR_ITER_COMPLETED)
4361 err = NULL;
4362 break;
4365 err = got_object_open_as_commit(&commit, repo, &id);
4366 if (err)
4367 break;
4369 if ((show_changed_paths || (show_diffstat && !show_patch))
4370 && !reverse_display_order) {
4371 err = get_changed_paths(&changed_paths, commit, repo,
4372 show_diffstat ? &dsa : NULL);
4373 if (err)
4374 break;
4377 if (search_pattern) {
4378 err = match_commit(&have_match, &id, commit, &regex);
4379 if (err) {
4380 got_object_commit_close(commit);
4381 break;
4383 if (have_match == 0 && show_changed_paths)
4384 match_changed_paths(&have_match,
4385 &changed_paths, &regex);
4386 if (have_match == 0 && show_patch) {
4387 err = match_patch(&have_match, commit, &id,
4388 path, diff_context, repo, &regex, tmpfile);
4389 if (err)
4390 break;
4392 if (have_match == 0) {
4393 got_object_commit_close(commit);
4394 got_pathlist_free(&changed_paths,
4395 GOT_PATHLIST_FREE_ALL);
4396 continue;
4400 if (reverse_display_order) {
4401 err = got_object_qid_alloc(&qid, &id);
4402 if (err)
4403 break;
4404 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4405 got_object_commit_close(commit);
4406 } else {
4407 if (one_line)
4408 err = print_commit_oneline(commit, &id,
4409 repo, refs_idmap);
4410 else
4411 err = print_commit(commit, &id, repo, path,
4412 (show_changed_paths || show_diffstat) ?
4413 &changed_paths : NULL,
4414 show_diffstat ? &dsa : NULL, show_patch,
4415 diff_context, refs_idmap, NULL);
4416 got_object_commit_close(commit);
4417 if (err)
4418 break;
4420 if ((limit && --limit == 0) ||
4421 (end_id && got_object_id_cmp(&id, end_id) == 0))
4422 break;
4424 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4426 if (reverse_display_order) {
4427 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4428 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4429 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4431 err = got_object_open_as_commit(&commit, repo,
4432 &qid->id);
4433 if (err)
4434 break;
4435 if (show_changed_paths ||
4436 (show_diffstat && !show_patch)) {
4437 err = get_changed_paths(&changed_paths, commit,
4438 repo, show_diffstat ? &dsa : NULL);
4439 if (err)
4440 break;
4442 if (one_line)
4443 err = print_commit_oneline(commit, &qid->id,
4444 repo, refs_idmap);
4445 else
4446 err = print_commit(commit, &qid->id, repo, path,
4447 (show_changed_paths || show_diffstat) ?
4448 &changed_paths : NULL,
4449 show_diffstat ? &dsa : NULL, show_patch,
4450 diff_context, refs_idmap, NULL);
4451 got_object_commit_close(commit);
4452 if (err)
4453 break;
4454 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4457 done:
4458 while (!STAILQ_EMPTY(&reversed_commits)) {
4459 qid = STAILQ_FIRST(&reversed_commits);
4460 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4461 got_object_qid_free(qid);
4463 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4464 if (search_pattern)
4465 regfree(&regex);
4466 got_commit_graph_close(graph);
4467 return err;
4470 __dead static void
4471 usage_log(void)
4473 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4474 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4475 "[path]\n", getprogname());
4476 exit(1);
4479 static int
4480 get_default_log_limit(void)
4482 const char *got_default_log_limit;
4483 long long n;
4484 const char *errstr;
4486 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4487 if (got_default_log_limit == NULL)
4488 return 0;
4489 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4490 if (errstr != NULL)
4491 return 0;
4492 return n;
4495 static const struct got_error *
4496 cmd_log(int argc, char *argv[])
4498 const struct got_error *error;
4499 struct got_repository *repo = NULL;
4500 struct got_worktree *worktree = NULL;
4501 struct got_object_id *start_id = NULL, *end_id = NULL;
4502 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4503 const char *start_commit = NULL, *end_commit = NULL;
4504 const char *search_pattern = NULL;
4505 int diff_context = -1, ch;
4506 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4507 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4508 const char *errstr;
4509 struct got_reflist_head refs;
4510 struct got_reflist_object_id_map *refs_idmap = NULL;
4511 FILE *tmpfile = NULL;
4512 int *pack_fds = NULL;
4514 TAILQ_INIT(&refs);
4516 #ifndef PROFILE
4517 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4518 NULL)
4519 == -1)
4520 err(1, "pledge");
4521 #endif
4523 limit = get_default_log_limit();
4525 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4526 switch (ch) {
4527 case 'b':
4528 log_branches = 1;
4529 break;
4530 case 'C':
4531 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4532 &errstr);
4533 if (errstr != NULL)
4534 errx(1, "number of context lines is %s: %s",
4535 errstr, optarg);
4536 break;
4537 case 'c':
4538 start_commit = optarg;
4539 break;
4540 case 'd':
4541 show_diffstat = 1;
4542 break;
4543 case 'l':
4544 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4545 if (errstr != NULL)
4546 errx(1, "number of commits is %s: %s",
4547 errstr, optarg);
4548 break;
4549 case 'P':
4550 show_changed_paths = 1;
4551 break;
4552 case 'p':
4553 show_patch = 1;
4554 break;
4555 case 'R':
4556 reverse_display_order = 1;
4557 break;
4558 case 'r':
4559 repo_path = realpath(optarg, NULL);
4560 if (repo_path == NULL)
4561 return got_error_from_errno2("realpath",
4562 optarg);
4563 got_path_strip_trailing_slashes(repo_path);
4564 break;
4565 case 'S':
4566 search_pattern = optarg;
4567 break;
4568 case 's':
4569 one_line = 1;
4570 break;
4571 case 'x':
4572 end_commit = optarg;
4573 break;
4574 default:
4575 usage_log();
4576 /* NOTREACHED */
4580 argc -= optind;
4581 argv += optind;
4583 if (diff_context == -1)
4584 diff_context = 3;
4585 else if (!show_patch)
4586 errx(1, "-C requires -p");
4588 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4589 errx(1, "cannot use -s with -d, -p or -P");
4591 cwd = getcwd(NULL, 0);
4592 if (cwd == NULL) {
4593 error = got_error_from_errno("getcwd");
4594 goto done;
4597 error = got_repo_pack_fds_open(&pack_fds);
4598 if (error != NULL)
4599 goto done;
4601 if (repo_path == NULL) {
4602 error = got_worktree_open(&worktree, cwd);
4603 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4604 goto done;
4605 error = NULL;
4608 if (argc == 1) {
4609 if (worktree) {
4610 error = got_worktree_resolve_path(&path, worktree,
4611 argv[0]);
4612 if (error)
4613 goto done;
4614 } else {
4615 path = strdup(argv[0]);
4616 if (path == NULL) {
4617 error = got_error_from_errno("strdup");
4618 goto done;
4621 } else if (argc != 0)
4622 usage_log();
4624 if (repo_path == NULL) {
4625 repo_path = worktree ?
4626 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4628 if (repo_path == NULL) {
4629 error = got_error_from_errno("strdup");
4630 goto done;
4633 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4634 if (error != NULL)
4635 goto done;
4637 error = apply_unveil(got_repo_get_path(repo), 1,
4638 worktree ? got_worktree_get_root_path(worktree) : NULL);
4639 if (error)
4640 goto done;
4642 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4643 if (error)
4644 goto done;
4646 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4647 if (error)
4648 goto done;
4650 if (start_commit == NULL) {
4651 struct got_reference *head_ref;
4652 struct got_commit_object *commit = NULL;
4653 error = got_ref_open(&head_ref, repo,
4654 worktree ? got_worktree_get_head_ref_name(worktree)
4655 : GOT_REF_HEAD, 0);
4656 if (error != NULL)
4657 goto done;
4658 error = got_ref_resolve(&start_id, repo, head_ref);
4659 got_ref_close(head_ref);
4660 if (error != NULL)
4661 goto done;
4662 error = got_object_open_as_commit(&commit, repo,
4663 start_id);
4664 if (error != NULL)
4665 goto done;
4666 got_object_commit_close(commit);
4667 } else {
4668 error = got_repo_match_object_id(&start_id, NULL,
4669 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4670 if (error != NULL)
4671 goto done;
4673 if (end_commit != NULL) {
4674 error = got_repo_match_object_id(&end_id, NULL,
4675 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4676 if (error != NULL)
4677 goto done;
4680 if (worktree) {
4682 * If a path was specified on the command line it was resolved
4683 * to a path in the work tree above. Prepend the work tree's
4684 * path prefix to obtain the corresponding in-repository path.
4686 if (path) {
4687 const char *prefix;
4688 prefix = got_worktree_get_path_prefix(worktree);
4689 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4690 (path[0] != '\0') ? "/" : "", path) == -1) {
4691 error = got_error_from_errno("asprintf");
4692 goto done;
4695 } else
4696 error = got_repo_map_path(&in_repo_path, repo,
4697 path ? path : "");
4698 if (error != NULL)
4699 goto done;
4700 if (in_repo_path) {
4701 free(path);
4702 path = in_repo_path;
4705 if (worktree) {
4706 /* Release work tree lock. */
4707 got_worktree_close(worktree);
4708 worktree = NULL;
4711 if (search_pattern && show_patch) {
4712 tmpfile = got_opentemp();
4713 if (tmpfile == NULL) {
4714 error = got_error_from_errno("got_opentemp");
4715 goto done;
4719 error = print_commits(start_id, end_id, repo, path ? path : "",
4720 show_changed_paths, show_diffstat, show_patch, search_pattern,
4721 diff_context, limit, log_branches, reverse_display_order,
4722 refs_idmap, one_line, tmpfile);
4723 done:
4724 free(path);
4725 free(repo_path);
4726 free(cwd);
4727 if (worktree)
4728 got_worktree_close(worktree);
4729 if (repo) {
4730 const struct got_error *close_err = got_repo_close(repo);
4731 if (error == NULL)
4732 error = close_err;
4734 if (pack_fds) {
4735 const struct got_error *pack_err =
4736 got_repo_pack_fds_close(pack_fds);
4737 if (error == NULL)
4738 error = pack_err;
4740 if (refs_idmap)
4741 got_reflist_object_id_map_free(refs_idmap);
4742 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4743 error = got_error_from_errno("fclose");
4744 got_ref_list_free(&refs);
4745 return error;
4748 __dead static void
4749 usage_diff(void)
4751 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4752 "[-r repository-path] [object1 object2 | path ...]\n",
4753 getprogname());
4754 exit(1);
4757 struct print_diff_arg {
4758 struct got_repository *repo;
4759 struct got_worktree *worktree;
4760 struct got_diffstat_cb_arg *diffstat;
4761 int diff_context;
4762 const char *id_str;
4763 int header_shown;
4764 int diff_staged;
4765 enum got_diff_algorithm diff_algo;
4766 int ignore_whitespace;
4767 int force_text_diff;
4768 FILE *f1;
4769 FILE *f2;
4770 FILE *outfile;
4774 * Create a file which contains the target path of a symlink so we can feed
4775 * it as content to the diff engine.
4777 static const struct got_error *
4778 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4779 const char *abspath)
4781 const struct got_error *err = NULL;
4782 char target_path[PATH_MAX];
4783 ssize_t target_len, outlen;
4785 *fd = -1;
4787 if (dirfd != -1) {
4788 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4789 if (target_len == -1)
4790 return got_error_from_errno2("readlinkat", abspath);
4791 } else {
4792 target_len = readlink(abspath, target_path, PATH_MAX);
4793 if (target_len == -1)
4794 return got_error_from_errno2("readlink", abspath);
4797 *fd = got_opentempfd();
4798 if (*fd == -1)
4799 return got_error_from_errno("got_opentempfd");
4801 outlen = write(*fd, target_path, target_len);
4802 if (outlen == -1) {
4803 err = got_error_from_errno("got_opentempfd");
4804 goto done;
4807 if (lseek(*fd, 0, SEEK_SET) == -1) {
4808 err = got_error_from_errno2("lseek", abspath);
4809 goto done;
4811 done:
4812 if (err) {
4813 close(*fd);
4814 *fd = -1;
4816 return err;
4819 static const struct got_error *
4820 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4821 const char *path, struct got_object_id *blob_id,
4822 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4823 int dirfd, const char *de_name)
4825 struct print_diff_arg *a = arg;
4826 const struct got_error *err = NULL;
4827 struct got_blob_object *blob1 = NULL;
4828 int fd = -1, fd1 = -1, fd2 = -1;
4829 FILE *f2 = NULL;
4830 char *abspath = NULL, *label1 = NULL;
4831 struct stat sb;
4832 off_t size1 = 0;
4833 int f2_exists = 0;
4835 memset(&sb, 0, sizeof(sb));
4837 if (a->diff_staged) {
4838 if (staged_status != GOT_STATUS_MODIFY &&
4839 staged_status != GOT_STATUS_ADD &&
4840 staged_status != GOT_STATUS_DELETE)
4841 return NULL;
4842 } else {
4843 if (staged_status == GOT_STATUS_DELETE)
4844 return NULL;
4845 if (status == GOT_STATUS_NONEXISTENT)
4846 return got_error_set_errno(ENOENT, path);
4847 if (status != GOT_STATUS_MODIFY &&
4848 status != GOT_STATUS_ADD &&
4849 status != GOT_STATUS_DELETE &&
4850 status != GOT_STATUS_CONFLICT)
4851 return NULL;
4854 err = got_opentemp_truncate(a->f1);
4855 if (err)
4856 return got_error_from_errno("got_opentemp_truncate");
4857 err = got_opentemp_truncate(a->f2);
4858 if (err)
4859 return got_error_from_errno("got_opentemp_truncate");
4861 if (!a->header_shown) {
4862 if (fprintf(a->outfile, "diff %s%s\n",
4863 a->diff_staged ? "-s " : "",
4864 got_worktree_get_root_path(a->worktree)) < 0) {
4865 err = got_error_from_errno("fprintf");
4866 goto done;
4868 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4869 err = got_error_from_errno("fprintf");
4870 goto done;
4872 if (fprintf(a->outfile, "path + %s%s\n",
4873 got_worktree_get_root_path(a->worktree),
4874 a->diff_staged ? " (staged changes)" : "") < 0) {
4875 err = got_error_from_errno("fprintf");
4876 goto done;
4878 a->header_shown = 1;
4881 if (a->diff_staged) {
4882 const char *label1 = NULL, *label2 = NULL;
4883 switch (staged_status) {
4884 case GOT_STATUS_MODIFY:
4885 label1 = path;
4886 label2 = path;
4887 break;
4888 case GOT_STATUS_ADD:
4889 label2 = path;
4890 break;
4891 case GOT_STATUS_DELETE:
4892 label1 = path;
4893 break;
4894 default:
4895 return got_error(GOT_ERR_FILE_STATUS);
4897 fd1 = got_opentempfd();
4898 if (fd1 == -1) {
4899 err = got_error_from_errno("got_opentempfd");
4900 goto done;
4902 fd2 = got_opentempfd();
4903 if (fd2 == -1) {
4904 err = got_error_from_errno("got_opentempfd");
4905 goto done;
4907 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4908 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4909 a->diff_algo, a->diff_context, a->ignore_whitespace,
4910 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4911 goto done;
4914 fd1 = got_opentempfd();
4915 if (fd1 == -1) {
4916 err = got_error_from_errno("got_opentempfd");
4917 goto done;
4920 if (staged_status == GOT_STATUS_ADD ||
4921 staged_status == GOT_STATUS_MODIFY) {
4922 char *id_str;
4923 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4924 8192, fd1);
4925 if (err)
4926 goto done;
4927 err = got_object_id_str(&id_str, staged_blob_id);
4928 if (err)
4929 goto done;
4930 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4931 err = got_error_from_errno("asprintf");
4932 free(id_str);
4933 goto done;
4935 free(id_str);
4936 } else if (status != GOT_STATUS_ADD) {
4937 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4938 fd1);
4939 if (err)
4940 goto done;
4943 if (status != GOT_STATUS_DELETE) {
4944 if (asprintf(&abspath, "%s/%s",
4945 got_worktree_get_root_path(a->worktree), path) == -1) {
4946 err = got_error_from_errno("asprintf");
4947 goto done;
4950 if (dirfd != -1) {
4951 fd = openat(dirfd, de_name,
4952 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4953 if (fd == -1) {
4954 if (!got_err_open_nofollow_on_symlink()) {
4955 err = got_error_from_errno2("openat",
4956 abspath);
4957 goto done;
4959 err = get_symlink_target_file(&fd, dirfd,
4960 de_name, abspath);
4961 if (err)
4962 goto done;
4964 } else {
4965 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4966 if (fd == -1) {
4967 if (!got_err_open_nofollow_on_symlink()) {
4968 err = got_error_from_errno2("open",
4969 abspath);
4970 goto done;
4972 err = get_symlink_target_file(&fd, dirfd,
4973 de_name, abspath);
4974 if (err)
4975 goto done;
4978 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4979 err = got_error_from_errno2("fstatat", abspath);
4980 goto done;
4982 f2 = fdopen(fd, "r");
4983 if (f2 == NULL) {
4984 err = got_error_from_errno2("fdopen", abspath);
4985 goto done;
4987 fd = -1;
4988 f2_exists = 1;
4991 if (blob1) {
4992 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4993 a->f1, blob1);
4994 if (err)
4995 goto done;
4998 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4999 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5000 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5001 done:
5002 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5003 err = got_error_from_errno("close");
5004 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5005 err = got_error_from_errno("close");
5006 if (blob1)
5007 got_object_blob_close(blob1);
5008 if (fd != -1 && close(fd) == -1 && err == NULL)
5009 err = got_error_from_errno("close");
5010 if (f2 && fclose(f2) == EOF && err == NULL)
5011 err = got_error_from_errno("fclose");
5012 free(abspath);
5013 return err;
5016 static const struct got_error *
5017 cmd_diff(int argc, char *argv[])
5019 const struct got_error *error;
5020 struct got_repository *repo = NULL;
5021 struct got_worktree *worktree = NULL;
5022 char *cwd = NULL, *repo_path = NULL;
5023 const char *commit_args[2] = { NULL, NULL };
5024 int ncommit_args = 0;
5025 struct got_object_id *ids[2] = { NULL, NULL };
5026 char *labels[2] = { NULL, NULL };
5027 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5028 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5029 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5030 const char *errstr;
5031 struct got_reflist_head refs;
5032 struct got_pathlist_head diffstat_paths, paths;
5033 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5034 int fd1 = -1, fd2 = -1;
5035 int *pack_fds = NULL;
5036 struct got_diffstat_cb_arg dsa;
5038 memset(&dsa, 0, sizeof(dsa));
5040 TAILQ_INIT(&refs);
5041 TAILQ_INIT(&paths);
5042 TAILQ_INIT(&diffstat_paths);
5044 #ifndef PROFILE
5045 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5046 NULL) == -1)
5047 err(1, "pledge");
5048 #endif
5050 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5051 switch (ch) {
5052 case 'a':
5053 force_text_diff = 1;
5054 break;
5055 case 'C':
5056 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5057 &errstr);
5058 if (errstr != NULL)
5059 errx(1, "number of context lines is %s: %s",
5060 errstr, optarg);
5061 break;
5062 case 'c':
5063 if (ncommit_args >= 2)
5064 errx(1, "too many -c options used");
5065 commit_args[ncommit_args++] = optarg;
5066 break;
5067 case 'd':
5068 show_diffstat = 1;
5069 break;
5070 case 'P':
5071 force_path = 1;
5072 break;
5073 case 'r':
5074 repo_path = realpath(optarg, NULL);
5075 if (repo_path == NULL)
5076 return got_error_from_errno2("realpath",
5077 optarg);
5078 got_path_strip_trailing_slashes(repo_path);
5079 rflag = 1;
5080 break;
5081 case 's':
5082 diff_staged = 1;
5083 break;
5084 case 'w':
5085 ignore_whitespace = 1;
5086 break;
5087 default:
5088 usage_diff();
5089 /* NOTREACHED */
5093 argc -= optind;
5094 argv += optind;
5096 cwd = getcwd(NULL, 0);
5097 if (cwd == NULL) {
5098 error = got_error_from_errno("getcwd");
5099 goto done;
5102 error = got_repo_pack_fds_open(&pack_fds);
5103 if (error != NULL)
5104 goto done;
5106 if (repo_path == NULL) {
5107 error = got_worktree_open(&worktree, cwd);
5108 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5109 goto done;
5110 else
5111 error = NULL;
5112 if (worktree) {
5113 repo_path =
5114 strdup(got_worktree_get_repo_path(worktree));
5115 if (repo_path == NULL) {
5116 error = got_error_from_errno("strdup");
5117 goto done;
5119 } else {
5120 repo_path = strdup(cwd);
5121 if (repo_path == NULL) {
5122 error = got_error_from_errno("strdup");
5123 goto done;
5128 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5129 free(repo_path);
5130 if (error != NULL)
5131 goto done;
5133 if (show_diffstat) {
5134 dsa.paths = &diffstat_paths;
5135 dsa.force_text = force_text_diff;
5136 dsa.ignore_ws = ignore_whitespace;
5137 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5140 if (rflag || worktree == NULL || ncommit_args > 0) {
5141 if (force_path) {
5142 error = got_error_msg(GOT_ERR_NOT_IMPL,
5143 "-P option can only be used when diffing "
5144 "a work tree");
5145 goto done;
5147 if (diff_staged) {
5148 error = got_error_msg(GOT_ERR_NOT_IMPL,
5149 "-s option can only be used when diffing "
5150 "a work tree");
5151 goto done;
5155 error = apply_unveil(got_repo_get_path(repo), 1,
5156 worktree ? got_worktree_get_root_path(worktree) : NULL);
5157 if (error)
5158 goto done;
5160 if ((!force_path && argc == 2) || ncommit_args > 0) {
5161 int obj_type = (ncommit_args > 0 ?
5162 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5163 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5164 NULL);
5165 if (error)
5166 goto done;
5167 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5168 const char *arg;
5169 if (ncommit_args > 0)
5170 arg = commit_args[i];
5171 else
5172 arg = argv[i];
5173 error = got_repo_match_object_id(&ids[i], &labels[i],
5174 arg, obj_type, &refs, repo);
5175 if (error) {
5176 if (error->code != GOT_ERR_NOT_REF &&
5177 error->code != GOT_ERR_NO_OBJ)
5178 goto done;
5179 if (ncommit_args > 0)
5180 goto done;
5181 error = NULL;
5182 break;
5187 f1 = got_opentemp();
5188 if (f1 == NULL) {
5189 error = got_error_from_errno("got_opentemp");
5190 goto done;
5193 f2 = got_opentemp();
5194 if (f2 == NULL) {
5195 error = got_error_from_errno("got_opentemp");
5196 goto done;
5199 outfile = got_opentemp();
5200 if (outfile == NULL) {
5201 error = got_error_from_errno("got_opentemp");
5202 goto done;
5205 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5206 struct print_diff_arg arg;
5207 char *id_str;
5209 if (worktree == NULL) {
5210 if (argc == 2 && ids[0] == NULL) {
5211 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5212 goto done;
5213 } else if (argc == 2 && ids[1] == NULL) {
5214 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5215 goto done;
5216 } else if (argc > 0) {
5217 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5218 "%s", "specified paths cannot be resolved");
5219 goto done;
5220 } else {
5221 error = got_error(GOT_ERR_NOT_WORKTREE);
5222 goto done;
5226 error = get_worktree_paths_from_argv(&paths, argc, argv,
5227 worktree);
5228 if (error)
5229 goto done;
5231 error = got_object_id_str(&id_str,
5232 got_worktree_get_base_commit_id(worktree));
5233 if (error)
5234 goto done;
5235 arg.repo = repo;
5236 arg.worktree = worktree;
5237 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5238 arg.diff_context = diff_context;
5239 arg.id_str = id_str;
5240 arg.header_shown = 0;
5241 arg.diff_staged = diff_staged;
5242 arg.ignore_whitespace = ignore_whitespace;
5243 arg.force_text_diff = force_text_diff;
5244 arg.diffstat = show_diffstat ? &dsa : NULL;
5245 arg.f1 = f1;
5246 arg.f2 = f2;
5247 arg.outfile = outfile;
5249 error = got_worktree_status(worktree, &paths, repo, 0,
5250 print_diff, &arg, check_cancelled, NULL);
5251 free(id_str);
5252 if (error)
5253 goto done;
5255 if (show_diffstat && dsa.nfiles > 0) {
5256 char *header;
5258 if (asprintf(&header, "diffstat %s%s",
5259 diff_staged ? "-s " : "",
5260 got_worktree_get_root_path(worktree)) == -1) {
5261 error = got_error_from_errno("asprintf");
5262 goto done;
5265 error = print_diffstat(&dsa, header);
5266 free(header);
5267 if (error)
5268 goto done;
5271 error = printfile(outfile);
5272 goto done;
5275 if (ncommit_args == 1) {
5276 struct got_commit_object *commit;
5277 error = got_object_open_as_commit(&commit, repo, ids[0]);
5278 if (error)
5279 goto done;
5281 labels[1] = labels[0];
5282 ids[1] = ids[0];
5283 if (got_object_commit_get_nparents(commit) > 0) {
5284 const struct got_object_id_queue *pids;
5285 struct got_object_qid *pid;
5286 pids = got_object_commit_get_parent_ids(commit);
5287 pid = STAILQ_FIRST(pids);
5288 ids[0] = got_object_id_dup(&pid->id);
5289 if (ids[0] == NULL) {
5290 error = got_error_from_errno(
5291 "got_object_id_dup");
5292 got_object_commit_close(commit);
5293 goto done;
5295 error = got_object_id_str(&labels[0], ids[0]);
5296 if (error) {
5297 got_object_commit_close(commit);
5298 goto done;
5300 } else {
5301 ids[0] = NULL;
5302 labels[0] = strdup("/dev/null");
5303 if (labels[0] == NULL) {
5304 error = got_error_from_errno("strdup");
5305 got_object_commit_close(commit);
5306 goto done;
5310 got_object_commit_close(commit);
5313 if (ncommit_args == 0 && argc > 2) {
5314 error = got_error_msg(GOT_ERR_BAD_PATH,
5315 "path arguments cannot be used when diffing two objects");
5316 goto done;
5319 if (ids[0]) {
5320 error = got_object_get_type(&type1, repo, ids[0]);
5321 if (error)
5322 goto done;
5325 error = got_object_get_type(&type2, repo, ids[1]);
5326 if (error)
5327 goto done;
5328 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5329 error = got_error(GOT_ERR_OBJ_TYPE);
5330 goto done;
5332 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5333 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5334 "path arguments cannot be used when diffing blobs");
5335 goto done;
5338 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5339 char *in_repo_path;
5340 struct got_pathlist_entry *new;
5341 if (worktree) {
5342 const char *prefix;
5343 char *p;
5344 error = got_worktree_resolve_path(&p, worktree,
5345 argv[i]);
5346 if (error)
5347 goto done;
5348 prefix = got_worktree_get_path_prefix(worktree);
5349 while (prefix[0] == '/')
5350 prefix++;
5351 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5352 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5353 p) == -1) {
5354 error = got_error_from_errno("asprintf");
5355 free(p);
5356 goto done;
5358 free(p);
5359 } else {
5360 char *mapped_path, *s;
5361 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5362 if (error)
5363 goto done;
5364 s = mapped_path;
5365 while (s[0] == '/')
5366 s++;
5367 in_repo_path = strdup(s);
5368 if (in_repo_path == NULL) {
5369 error = got_error_from_errno("asprintf");
5370 free(mapped_path);
5371 goto done;
5373 free(mapped_path);
5376 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5377 if (error || new == NULL /* duplicate */)
5378 free(in_repo_path);
5379 if (error)
5380 goto done;
5383 if (worktree) {
5384 /* Release work tree lock. */
5385 got_worktree_close(worktree);
5386 worktree = NULL;
5389 fd1 = got_opentempfd();
5390 if (fd1 == -1) {
5391 error = got_error_from_errno("got_opentempfd");
5392 goto done;
5395 fd2 = got_opentempfd();
5396 if (fd2 == -1) {
5397 error = got_error_from_errno("got_opentempfd");
5398 goto done;
5401 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5402 case GOT_OBJ_TYPE_BLOB:
5403 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5404 fd1, fd2, ids[0], ids[1], NULL, NULL,
5405 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5406 ignore_whitespace, force_text_diff,
5407 show_diffstat ? &dsa : NULL, repo, outfile);
5408 break;
5409 case GOT_OBJ_TYPE_TREE:
5410 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5411 ids[0], ids[1], &paths, "", "",
5412 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5413 ignore_whitespace, force_text_diff,
5414 show_diffstat ? &dsa : NULL, repo, outfile);
5415 break;
5416 case GOT_OBJ_TYPE_COMMIT:
5417 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5418 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5419 fd1, fd2, 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 default:
5425 error = got_error(GOT_ERR_OBJ_TYPE);
5427 if (error)
5428 goto done;
5430 if (show_diffstat && dsa.nfiles > 0) {
5431 char *header = NULL;
5433 if (asprintf(&header, "diffstat %s %s",
5434 labels[0], labels[1]) == -1) {
5435 error = got_error_from_errno("asprintf");
5436 goto done;
5439 error = print_diffstat(&dsa, header);
5440 free(header);
5441 if (error)
5442 goto done;
5445 error = printfile(outfile);
5447 done:
5448 free(labels[0]);
5449 free(labels[1]);
5450 free(ids[0]);
5451 free(ids[1]);
5452 if (worktree)
5453 got_worktree_close(worktree);
5454 if (repo) {
5455 const struct got_error *close_err = got_repo_close(repo);
5456 if (error == NULL)
5457 error = close_err;
5459 if (pack_fds) {
5460 const struct got_error *pack_err =
5461 got_repo_pack_fds_close(pack_fds);
5462 if (error == NULL)
5463 error = pack_err;
5465 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5466 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5467 got_ref_list_free(&refs);
5468 if (outfile && fclose(outfile) == EOF && error == NULL)
5469 error = got_error_from_errno("fclose");
5470 if (f1 && fclose(f1) == EOF && error == NULL)
5471 error = got_error_from_errno("fclose");
5472 if (f2 && fclose(f2) == EOF && error == NULL)
5473 error = got_error_from_errno("fclose");
5474 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5475 error = got_error_from_errno("close");
5476 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5477 error = got_error_from_errno("close");
5478 return error;
5481 __dead static void
5482 usage_blame(void)
5484 fprintf(stderr,
5485 "usage: %s blame [-c commit] [-r repository-path] path\n",
5486 getprogname());
5487 exit(1);
5490 struct blame_line {
5491 int annotated;
5492 char *id_str;
5493 char *committer;
5494 char datebuf[11]; /* YYYY-MM-DD + NUL */
5497 struct blame_cb_args {
5498 struct blame_line *lines;
5499 int nlines;
5500 int nlines_prec;
5501 int lineno_cur;
5502 off_t *line_offsets;
5503 FILE *f;
5504 struct got_repository *repo;
5507 static const struct got_error *
5508 blame_cb(void *arg, int nlines, int lineno,
5509 struct got_commit_object *commit, struct got_object_id *id)
5511 const struct got_error *err = NULL;
5512 struct blame_cb_args *a = arg;
5513 struct blame_line *bline;
5514 char *line = NULL;
5515 size_t linesize = 0;
5516 off_t offset;
5517 struct tm tm;
5518 time_t committer_time;
5520 if (nlines != a->nlines ||
5521 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5522 return got_error(GOT_ERR_RANGE);
5524 if (sigint_received)
5525 return got_error(GOT_ERR_ITER_COMPLETED);
5527 if (lineno == -1)
5528 return NULL; /* no change in this commit */
5530 /* Annotate this line. */
5531 bline = &a->lines[lineno - 1];
5532 if (bline->annotated)
5533 return NULL;
5534 err = got_object_id_str(&bline->id_str, id);
5535 if (err)
5536 return err;
5538 bline->committer = strdup(got_object_commit_get_committer(commit));
5539 if (bline->committer == NULL) {
5540 err = got_error_from_errno("strdup");
5541 goto done;
5544 committer_time = got_object_commit_get_committer_time(commit);
5545 if (gmtime_r(&committer_time, &tm) == NULL)
5546 return got_error_from_errno("gmtime_r");
5547 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5548 &tm) == 0) {
5549 err = got_error(GOT_ERR_NO_SPACE);
5550 goto done;
5552 bline->annotated = 1;
5554 /* Print lines annotated so far. */
5555 bline = &a->lines[a->lineno_cur - 1];
5556 if (!bline->annotated)
5557 goto done;
5559 offset = a->line_offsets[a->lineno_cur - 1];
5560 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5561 err = got_error_from_errno("fseeko");
5562 goto done;
5565 while (a->lineno_cur <= a->nlines && bline->annotated) {
5566 char *smallerthan, *at, *nl, *committer;
5567 size_t len;
5569 if (getline(&line, &linesize, a->f) == -1) {
5570 if (ferror(a->f))
5571 err = got_error_from_errno("getline");
5572 break;
5575 committer = bline->committer;
5576 smallerthan = strchr(committer, '<');
5577 if (smallerthan && smallerthan[1] != '\0')
5578 committer = smallerthan + 1;
5579 at = strchr(committer, '@');
5580 if (at)
5581 *at = '\0';
5582 len = strlen(committer);
5583 if (len >= 9)
5584 committer[8] = '\0';
5586 nl = strchr(line, '\n');
5587 if (nl)
5588 *nl = '\0';
5589 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5590 bline->id_str, bline->datebuf, committer, line);
5592 a->lineno_cur++;
5593 bline = &a->lines[a->lineno_cur - 1];
5595 done:
5596 free(line);
5597 return err;
5600 static const struct got_error *
5601 cmd_blame(int argc, char *argv[])
5603 const struct got_error *error;
5604 struct got_repository *repo = NULL;
5605 struct got_worktree *worktree = NULL;
5606 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5607 char *link_target = NULL;
5608 struct got_object_id *obj_id = NULL;
5609 struct got_object_id *commit_id = NULL;
5610 struct got_commit_object *commit = NULL;
5611 struct got_blob_object *blob = NULL;
5612 char *commit_id_str = NULL;
5613 struct blame_cb_args bca;
5614 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5615 off_t filesize;
5616 int *pack_fds = NULL;
5617 FILE *f1 = NULL, *f2 = NULL;
5619 fd1 = got_opentempfd();
5620 if (fd1 == -1)
5621 return got_error_from_errno("got_opentempfd");
5623 memset(&bca, 0, sizeof(bca));
5625 #ifndef PROFILE
5626 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5627 NULL) == -1)
5628 err(1, "pledge");
5629 #endif
5631 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5632 switch (ch) {
5633 case 'c':
5634 commit_id_str = optarg;
5635 break;
5636 case 'r':
5637 repo_path = realpath(optarg, NULL);
5638 if (repo_path == NULL)
5639 return got_error_from_errno2("realpath",
5640 optarg);
5641 got_path_strip_trailing_slashes(repo_path);
5642 break;
5643 default:
5644 usage_blame();
5645 /* NOTREACHED */
5649 argc -= optind;
5650 argv += optind;
5652 if (argc == 1)
5653 path = argv[0];
5654 else
5655 usage_blame();
5657 cwd = getcwd(NULL, 0);
5658 if (cwd == NULL) {
5659 error = got_error_from_errno("getcwd");
5660 goto done;
5663 error = got_repo_pack_fds_open(&pack_fds);
5664 if (error != NULL)
5665 goto done;
5667 if (repo_path == NULL) {
5668 error = got_worktree_open(&worktree, cwd);
5669 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5670 goto done;
5671 else
5672 error = NULL;
5673 if (worktree) {
5674 repo_path =
5675 strdup(got_worktree_get_repo_path(worktree));
5676 if (repo_path == NULL) {
5677 error = got_error_from_errno("strdup");
5678 if (error)
5679 goto done;
5681 } else {
5682 repo_path = strdup(cwd);
5683 if (repo_path == NULL) {
5684 error = got_error_from_errno("strdup");
5685 goto done;
5690 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5691 if (error != NULL)
5692 goto done;
5694 if (worktree) {
5695 const char *prefix = got_worktree_get_path_prefix(worktree);
5696 char *p;
5698 error = got_worktree_resolve_path(&p, worktree, path);
5699 if (error)
5700 goto done;
5701 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5702 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5703 p) == -1) {
5704 error = got_error_from_errno("asprintf");
5705 free(p);
5706 goto done;
5708 free(p);
5709 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5710 } else {
5711 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5712 if (error)
5713 goto done;
5714 error = got_repo_map_path(&in_repo_path, repo, path);
5716 if (error)
5717 goto done;
5719 if (commit_id_str == NULL) {
5720 struct got_reference *head_ref;
5721 error = got_ref_open(&head_ref, repo, worktree ?
5722 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5723 if (error != NULL)
5724 goto done;
5725 error = got_ref_resolve(&commit_id, repo, head_ref);
5726 got_ref_close(head_ref);
5727 if (error != NULL)
5728 goto done;
5729 } else {
5730 struct got_reflist_head refs;
5731 TAILQ_INIT(&refs);
5732 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5733 NULL);
5734 if (error)
5735 goto done;
5736 error = got_repo_match_object_id(&commit_id, NULL,
5737 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5738 got_ref_list_free(&refs);
5739 if (error)
5740 goto done;
5743 if (worktree) {
5744 /* Release work tree lock. */
5745 got_worktree_close(worktree);
5746 worktree = NULL;
5749 error = got_object_open_as_commit(&commit, repo, commit_id);
5750 if (error)
5751 goto done;
5753 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5754 commit, repo);
5755 if (error)
5756 goto done;
5758 error = got_object_id_by_path(&obj_id, repo, commit,
5759 link_target ? link_target : in_repo_path);
5760 if (error)
5761 goto done;
5763 error = got_object_get_type(&obj_type, repo, obj_id);
5764 if (error)
5765 goto done;
5767 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5768 error = got_error_path(link_target ? link_target : in_repo_path,
5769 GOT_ERR_OBJ_TYPE);
5770 goto done;
5773 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5774 if (error)
5775 goto done;
5776 bca.f = got_opentemp();
5777 if (bca.f == NULL) {
5778 error = got_error_from_errno("got_opentemp");
5779 goto done;
5781 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5782 &bca.line_offsets, bca.f, blob);
5783 if (error || bca.nlines == 0)
5784 goto done;
5786 /* Don't include \n at EOF in the blame line count. */
5787 if (bca.line_offsets[bca.nlines - 1] == filesize)
5788 bca.nlines--;
5790 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5791 if (bca.lines == NULL) {
5792 error = got_error_from_errno("calloc");
5793 goto done;
5795 bca.lineno_cur = 1;
5796 bca.nlines_prec = 0;
5797 i = bca.nlines;
5798 while (i > 0) {
5799 i /= 10;
5800 bca.nlines_prec++;
5802 bca.repo = repo;
5804 fd2 = got_opentempfd();
5805 if (fd2 == -1) {
5806 error = got_error_from_errno("got_opentempfd");
5807 goto done;
5809 fd3 = got_opentempfd();
5810 if (fd3 == -1) {
5811 error = got_error_from_errno("got_opentempfd");
5812 goto done;
5814 f1 = got_opentemp();
5815 if (f1 == NULL) {
5816 error = got_error_from_errno("got_opentemp");
5817 goto done;
5819 f2 = got_opentemp();
5820 if (f2 == NULL) {
5821 error = got_error_from_errno("got_opentemp");
5822 goto done;
5824 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5825 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5826 check_cancelled, NULL, fd2, fd3, f1, f2);
5827 done:
5828 free(in_repo_path);
5829 free(link_target);
5830 free(repo_path);
5831 free(cwd);
5832 free(commit_id);
5833 free(obj_id);
5834 if (commit)
5835 got_object_commit_close(commit);
5837 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5838 error = got_error_from_errno("close");
5839 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5840 error = got_error_from_errno("close");
5841 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5842 error = got_error_from_errno("close");
5843 if (f1 && fclose(f1) == EOF && error == NULL)
5844 error = got_error_from_errno("fclose");
5845 if (f2 && fclose(f2) == EOF && error == NULL)
5846 error = got_error_from_errno("fclose");
5848 if (blob)
5849 got_object_blob_close(blob);
5850 if (worktree)
5851 got_worktree_close(worktree);
5852 if (repo) {
5853 const struct got_error *close_err = got_repo_close(repo);
5854 if (error == NULL)
5855 error = close_err;
5857 if (pack_fds) {
5858 const struct got_error *pack_err =
5859 got_repo_pack_fds_close(pack_fds);
5860 if (error == NULL)
5861 error = pack_err;
5863 if (bca.lines) {
5864 for (i = 0; i < bca.nlines; i++) {
5865 struct blame_line *bline = &bca.lines[i];
5866 free(bline->id_str);
5867 free(bline->committer);
5869 free(bca.lines);
5871 free(bca.line_offsets);
5872 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5873 error = got_error_from_errno("fclose");
5874 return error;
5877 __dead static void
5878 usage_tree(void)
5880 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5881 "[path]\n", getprogname());
5882 exit(1);
5885 static const struct got_error *
5886 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5887 const char *root_path, struct got_repository *repo)
5889 const struct got_error *err = NULL;
5890 int is_root_path = (strcmp(path, root_path) == 0);
5891 const char *modestr = "";
5892 mode_t mode = got_tree_entry_get_mode(te);
5893 char *link_target = NULL;
5895 path += strlen(root_path);
5896 while (path[0] == '/')
5897 path++;
5899 if (got_object_tree_entry_is_submodule(te))
5900 modestr = "$";
5901 else if (S_ISLNK(mode)) {
5902 int i;
5904 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5905 if (err)
5906 return err;
5907 for (i = 0; i < strlen(link_target); i++) {
5908 if (!isprint((unsigned char)link_target[i]))
5909 link_target[i] = '?';
5912 modestr = "@";
5914 else if (S_ISDIR(mode))
5915 modestr = "/";
5916 else if (mode & S_IXUSR)
5917 modestr = "*";
5919 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5920 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5921 link_target ? " -> ": "", link_target ? link_target : "");
5923 free(link_target);
5924 return NULL;
5927 static const struct got_error *
5928 print_tree(const char *path, struct got_commit_object *commit,
5929 int show_ids, int recurse, const char *root_path,
5930 struct got_repository *repo)
5932 const struct got_error *err = NULL;
5933 struct got_object_id *tree_id = NULL;
5934 struct got_tree_object *tree = NULL;
5935 int nentries, i;
5937 err = got_object_id_by_path(&tree_id, repo, commit, path);
5938 if (err)
5939 goto done;
5941 err = got_object_open_as_tree(&tree, repo, tree_id);
5942 if (err)
5943 goto done;
5944 nentries = got_object_tree_get_nentries(tree);
5945 for (i = 0; i < nentries; i++) {
5946 struct got_tree_entry *te;
5947 char *id = NULL;
5949 if (sigint_received || sigpipe_received)
5950 break;
5952 te = got_object_tree_get_entry(tree, i);
5953 if (show_ids) {
5954 char *id_str;
5955 err = got_object_id_str(&id_str,
5956 got_tree_entry_get_id(te));
5957 if (err)
5958 goto done;
5959 if (asprintf(&id, "%s ", id_str) == -1) {
5960 err = got_error_from_errno("asprintf");
5961 free(id_str);
5962 goto done;
5964 free(id_str);
5966 err = print_entry(te, id, path, root_path, repo);
5967 free(id);
5968 if (err)
5969 goto done;
5971 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5972 char *child_path;
5973 if (asprintf(&child_path, "%s%s%s", path,
5974 path[0] == '/' && path[1] == '\0' ? "" : "/",
5975 got_tree_entry_get_name(te)) == -1) {
5976 err = got_error_from_errno("asprintf");
5977 goto done;
5979 err = print_tree(child_path, commit, show_ids, 1,
5980 root_path, repo);
5981 free(child_path);
5982 if (err)
5983 goto done;
5986 done:
5987 if (tree)
5988 got_object_tree_close(tree);
5989 free(tree_id);
5990 return err;
5993 static const struct got_error *
5994 cmd_tree(int argc, char *argv[])
5996 const struct got_error *error;
5997 struct got_repository *repo = NULL;
5998 struct got_worktree *worktree = NULL;
5999 const char *path, *refname = NULL;
6000 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6001 struct got_object_id *commit_id = NULL;
6002 struct got_commit_object *commit = NULL;
6003 char *commit_id_str = NULL;
6004 int show_ids = 0, recurse = 0;
6005 int ch;
6006 int *pack_fds = NULL;
6008 #ifndef PROFILE
6009 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6010 NULL) == -1)
6011 err(1, "pledge");
6012 #endif
6014 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6015 switch (ch) {
6016 case 'c':
6017 commit_id_str = optarg;
6018 break;
6019 case 'i':
6020 show_ids = 1;
6021 break;
6022 case 'R':
6023 recurse = 1;
6024 break;
6025 case 'r':
6026 repo_path = realpath(optarg, NULL);
6027 if (repo_path == NULL)
6028 return got_error_from_errno2("realpath",
6029 optarg);
6030 got_path_strip_trailing_slashes(repo_path);
6031 break;
6032 default:
6033 usage_tree();
6034 /* NOTREACHED */
6038 argc -= optind;
6039 argv += optind;
6041 if (argc == 1)
6042 path = argv[0];
6043 else if (argc > 1)
6044 usage_tree();
6045 else
6046 path = NULL;
6048 cwd = getcwd(NULL, 0);
6049 if (cwd == NULL) {
6050 error = got_error_from_errno("getcwd");
6051 goto done;
6054 error = got_repo_pack_fds_open(&pack_fds);
6055 if (error != NULL)
6056 goto done;
6058 if (repo_path == NULL) {
6059 error = got_worktree_open(&worktree, cwd);
6060 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6061 goto done;
6062 else
6063 error = NULL;
6064 if (worktree) {
6065 repo_path =
6066 strdup(got_worktree_get_repo_path(worktree));
6067 if (repo_path == NULL)
6068 error = got_error_from_errno("strdup");
6069 if (error)
6070 goto done;
6071 } else {
6072 repo_path = strdup(cwd);
6073 if (repo_path == NULL) {
6074 error = got_error_from_errno("strdup");
6075 goto done;
6080 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6081 if (error != NULL)
6082 goto done;
6084 if (worktree) {
6085 const char *prefix = got_worktree_get_path_prefix(worktree);
6086 char *p;
6088 if (path == NULL)
6089 path = "";
6090 error = got_worktree_resolve_path(&p, worktree, path);
6091 if (error)
6092 goto done;
6093 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6094 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6095 p) == -1) {
6096 error = got_error_from_errno("asprintf");
6097 free(p);
6098 goto done;
6100 free(p);
6101 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6102 if (error)
6103 goto done;
6104 } else {
6105 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6106 if (error)
6107 goto done;
6108 if (path == NULL)
6109 path = "/";
6110 error = got_repo_map_path(&in_repo_path, repo, path);
6111 if (error != NULL)
6112 goto done;
6115 if (commit_id_str == NULL) {
6116 struct got_reference *head_ref;
6117 if (worktree)
6118 refname = got_worktree_get_head_ref_name(worktree);
6119 else
6120 refname = GOT_REF_HEAD;
6121 error = got_ref_open(&head_ref, repo, refname, 0);
6122 if (error != NULL)
6123 goto done;
6124 error = got_ref_resolve(&commit_id, repo, head_ref);
6125 got_ref_close(head_ref);
6126 if (error != NULL)
6127 goto done;
6128 } else {
6129 struct got_reflist_head refs;
6130 TAILQ_INIT(&refs);
6131 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6132 NULL);
6133 if (error)
6134 goto done;
6135 error = got_repo_match_object_id(&commit_id, NULL,
6136 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6137 got_ref_list_free(&refs);
6138 if (error)
6139 goto done;
6142 if (worktree) {
6143 /* Release work tree lock. */
6144 got_worktree_close(worktree);
6145 worktree = NULL;
6148 error = got_object_open_as_commit(&commit, repo, commit_id);
6149 if (error)
6150 goto done;
6152 error = print_tree(in_repo_path, commit, show_ids, recurse,
6153 in_repo_path, repo);
6154 done:
6155 free(in_repo_path);
6156 free(repo_path);
6157 free(cwd);
6158 free(commit_id);
6159 if (commit)
6160 got_object_commit_close(commit);
6161 if (worktree)
6162 got_worktree_close(worktree);
6163 if (repo) {
6164 const struct got_error *close_err = got_repo_close(repo);
6165 if (error == NULL)
6166 error = close_err;
6168 if (pack_fds) {
6169 const struct got_error *pack_err =
6170 got_repo_pack_fds_close(pack_fds);
6171 if (error == NULL)
6172 error = pack_err;
6174 return error;
6177 __dead static void
6178 usage_status(void)
6180 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6181 "[-s status-codes] [path ...]\n", getprogname());
6182 exit(1);
6185 struct got_status_arg {
6186 char *status_codes;
6187 int suppress;
6190 static const struct got_error *
6191 print_status(void *arg, unsigned char status, unsigned char staged_status,
6192 const char *path, struct got_object_id *blob_id,
6193 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6194 int dirfd, const char *de_name)
6196 struct got_status_arg *st = arg;
6198 if (status == staged_status && (status == GOT_STATUS_DELETE))
6199 status = GOT_STATUS_NO_CHANGE;
6200 if (st != NULL && st->status_codes) {
6201 size_t ncodes = strlen(st->status_codes);
6202 int i, j = 0;
6204 for (i = 0; i < ncodes ; i++) {
6205 if (st->suppress) {
6206 if (status == st->status_codes[i] ||
6207 staged_status == st->status_codes[i]) {
6208 j++;
6209 continue;
6211 } else {
6212 if (status == st->status_codes[i] ||
6213 staged_status == st->status_codes[i])
6214 break;
6218 if (st->suppress && j == 0)
6219 goto print;
6221 if (i == ncodes)
6222 return NULL;
6224 print:
6225 printf("%c%c %s\n", status, staged_status, path);
6226 return NULL;
6229 static const struct got_error *
6230 cmd_status(int argc, char *argv[])
6232 const struct got_error *error = NULL;
6233 struct got_repository *repo = NULL;
6234 struct got_worktree *worktree = NULL;
6235 struct got_status_arg st;
6236 char *cwd = NULL;
6237 struct got_pathlist_head paths;
6238 int ch, i, no_ignores = 0;
6239 int *pack_fds = NULL;
6241 TAILQ_INIT(&paths);
6243 memset(&st, 0, sizeof(st));
6244 st.status_codes = NULL;
6245 st.suppress = 0;
6247 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6248 switch (ch) {
6249 case 'I':
6250 no_ignores = 1;
6251 break;
6252 case 'S':
6253 if (st.status_codes != NULL && st.suppress == 0)
6254 option_conflict('S', 's');
6255 st.suppress = 1;
6256 /* fallthrough */
6257 case 's':
6258 for (i = 0; i < strlen(optarg); i++) {
6259 switch (optarg[i]) {
6260 case GOT_STATUS_MODIFY:
6261 case GOT_STATUS_ADD:
6262 case GOT_STATUS_DELETE:
6263 case GOT_STATUS_CONFLICT:
6264 case GOT_STATUS_MISSING:
6265 case GOT_STATUS_OBSTRUCTED:
6266 case GOT_STATUS_UNVERSIONED:
6267 case GOT_STATUS_MODE_CHANGE:
6268 case GOT_STATUS_NONEXISTENT:
6269 break;
6270 default:
6271 errx(1, "invalid status code '%c'",
6272 optarg[i]);
6275 if (ch == 's' && st.suppress)
6276 option_conflict('s', 'S');
6277 st.status_codes = optarg;
6278 break;
6279 default:
6280 usage_status();
6281 /* NOTREACHED */
6285 argc -= optind;
6286 argv += optind;
6288 #ifndef PROFILE
6289 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6290 NULL) == -1)
6291 err(1, "pledge");
6292 #endif
6293 cwd = getcwd(NULL, 0);
6294 if (cwd == NULL) {
6295 error = got_error_from_errno("getcwd");
6296 goto done;
6299 error = got_repo_pack_fds_open(&pack_fds);
6300 if (error != NULL)
6301 goto done;
6303 error = got_worktree_open(&worktree, cwd);
6304 if (error) {
6305 if (error->code == GOT_ERR_NOT_WORKTREE)
6306 error = wrap_not_worktree_error(error, "status", cwd);
6307 goto done;
6310 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6311 NULL, pack_fds);
6312 if (error != NULL)
6313 goto done;
6315 error = apply_unveil(got_repo_get_path(repo), 1,
6316 got_worktree_get_root_path(worktree));
6317 if (error)
6318 goto done;
6320 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6321 if (error)
6322 goto done;
6324 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6325 print_status, &st, check_cancelled, NULL);
6326 done:
6327 if (pack_fds) {
6328 const struct got_error *pack_err =
6329 got_repo_pack_fds_close(pack_fds);
6330 if (error == NULL)
6331 error = pack_err;
6334 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6335 free(cwd);
6336 return error;
6339 __dead static void
6340 usage_ref(void)
6342 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6343 "[-s reference] [name]\n", getprogname());
6344 exit(1);
6347 static const struct got_error *
6348 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6350 static const struct got_error *err = NULL;
6351 struct got_reflist_head refs;
6352 struct got_reflist_entry *re;
6354 TAILQ_INIT(&refs);
6355 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6356 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6357 repo);
6358 if (err)
6359 return err;
6361 TAILQ_FOREACH(re, &refs, entry) {
6362 char *refstr;
6363 refstr = got_ref_to_str(re->ref);
6364 if (refstr == NULL) {
6365 err = got_error_from_errno("got_ref_to_str");
6366 break;
6368 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6369 free(refstr);
6372 got_ref_list_free(&refs);
6373 return err;
6376 static const struct got_error *
6377 delete_ref_by_name(struct got_repository *repo, const char *refname)
6379 const struct got_error *err;
6380 struct got_reference *ref;
6382 err = got_ref_open(&ref, repo, refname, 0);
6383 if (err)
6384 return err;
6386 err = delete_ref(repo, ref);
6387 got_ref_close(ref);
6388 return err;
6391 static const struct got_error *
6392 add_ref(struct got_repository *repo, const char *refname, const char *target)
6394 const struct got_error *err = NULL;
6395 struct got_object_id *id = NULL;
6396 struct got_reference *ref = NULL;
6397 struct got_reflist_head refs;
6400 * Don't let the user create a reference name with a leading '-'.
6401 * While technically a valid reference name, this case is usually
6402 * an unintended typo.
6404 if (refname[0] == '-')
6405 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6407 TAILQ_INIT(&refs);
6408 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6409 if (err)
6410 goto done;
6411 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6412 &refs, repo);
6413 got_ref_list_free(&refs);
6414 if (err)
6415 goto done;
6417 err = got_ref_alloc(&ref, refname, id);
6418 if (err)
6419 goto done;
6421 err = got_ref_write(ref, repo);
6422 done:
6423 if (ref)
6424 got_ref_close(ref);
6425 free(id);
6426 return err;
6429 static const struct got_error *
6430 add_symref(struct got_repository *repo, const char *refname, const char *target)
6432 const struct got_error *err = NULL;
6433 struct got_reference *ref = NULL;
6434 struct got_reference *target_ref = NULL;
6437 * Don't let the user create a reference name with a leading '-'.
6438 * While technically a valid reference name, this case is usually
6439 * an unintended typo.
6441 if (refname[0] == '-')
6442 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6444 err = got_ref_open(&target_ref, repo, target, 0);
6445 if (err)
6446 return err;
6448 err = got_ref_alloc_symref(&ref, refname, target_ref);
6449 if (err)
6450 goto done;
6452 err = got_ref_write(ref, repo);
6453 done:
6454 if (target_ref)
6455 got_ref_close(target_ref);
6456 if (ref)
6457 got_ref_close(ref);
6458 return err;
6461 static const struct got_error *
6462 cmd_ref(int argc, char *argv[])
6464 const struct got_error *error = NULL;
6465 struct got_repository *repo = NULL;
6466 struct got_worktree *worktree = NULL;
6467 char *cwd = NULL, *repo_path = NULL;
6468 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6469 const char *obj_arg = NULL, *symref_target= NULL;
6470 char *refname = NULL;
6471 int *pack_fds = NULL;
6473 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6474 switch (ch) {
6475 case 'c':
6476 obj_arg = optarg;
6477 break;
6478 case 'd':
6479 do_delete = 1;
6480 break;
6481 case 'l':
6482 do_list = 1;
6483 break;
6484 case 'r':
6485 repo_path = realpath(optarg, NULL);
6486 if (repo_path == NULL)
6487 return got_error_from_errno2("realpath",
6488 optarg);
6489 got_path_strip_trailing_slashes(repo_path);
6490 break;
6491 case 's':
6492 symref_target = optarg;
6493 break;
6494 case 't':
6495 sort_by_time = 1;
6496 break;
6497 default:
6498 usage_ref();
6499 /* NOTREACHED */
6503 if (obj_arg && do_list)
6504 option_conflict('c', 'l');
6505 if (obj_arg && do_delete)
6506 option_conflict('c', 'd');
6507 if (obj_arg && symref_target)
6508 option_conflict('c', 's');
6509 if (symref_target && do_delete)
6510 option_conflict('s', 'd');
6511 if (symref_target && do_list)
6512 option_conflict('s', 'l');
6513 if (do_delete && do_list)
6514 option_conflict('d', 'l');
6515 if (sort_by_time && !do_list)
6516 errx(1, "-t option requires -l option");
6518 argc -= optind;
6519 argv += optind;
6521 if (do_list) {
6522 if (argc != 0 && argc != 1)
6523 usage_ref();
6524 if (argc == 1) {
6525 refname = strdup(argv[0]);
6526 if (refname == NULL) {
6527 error = got_error_from_errno("strdup");
6528 goto done;
6531 } else {
6532 if (argc != 1)
6533 usage_ref();
6534 refname = strdup(argv[0]);
6535 if (refname == NULL) {
6536 error = got_error_from_errno("strdup");
6537 goto done;
6541 if (refname)
6542 got_path_strip_trailing_slashes(refname);
6544 #ifndef PROFILE
6545 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6546 "sendfd unveil", NULL) == -1)
6547 err(1, "pledge");
6548 #endif
6549 cwd = getcwd(NULL, 0);
6550 if (cwd == NULL) {
6551 error = got_error_from_errno("getcwd");
6552 goto done;
6555 error = got_repo_pack_fds_open(&pack_fds);
6556 if (error != NULL)
6557 goto done;
6559 if (repo_path == NULL) {
6560 error = got_worktree_open(&worktree, cwd);
6561 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6562 goto done;
6563 else
6564 error = NULL;
6565 if (worktree) {
6566 repo_path =
6567 strdup(got_worktree_get_repo_path(worktree));
6568 if (repo_path == NULL)
6569 error = got_error_from_errno("strdup");
6570 if (error)
6571 goto done;
6572 } else {
6573 repo_path = strdup(cwd);
6574 if (repo_path == NULL) {
6575 error = got_error_from_errno("strdup");
6576 goto done;
6581 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6582 if (error != NULL)
6583 goto done;
6585 #ifndef PROFILE
6586 if (do_list) {
6587 /* Remove "cpath" promise. */
6588 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6589 NULL) == -1)
6590 err(1, "pledge");
6592 #endif
6594 error = apply_unveil(got_repo_get_path(repo), do_list,
6595 worktree ? got_worktree_get_root_path(worktree) : NULL);
6596 if (error)
6597 goto done;
6599 if (do_list)
6600 error = list_refs(repo, refname, sort_by_time);
6601 else if (do_delete)
6602 error = delete_ref_by_name(repo, refname);
6603 else if (symref_target)
6604 error = add_symref(repo, refname, symref_target);
6605 else {
6606 if (obj_arg == NULL)
6607 usage_ref();
6608 error = add_ref(repo, refname, obj_arg);
6610 done:
6611 free(refname);
6612 if (repo) {
6613 const struct got_error *close_err = got_repo_close(repo);
6614 if (error == NULL)
6615 error = close_err;
6617 if (worktree)
6618 got_worktree_close(worktree);
6619 if (pack_fds) {
6620 const struct got_error *pack_err =
6621 got_repo_pack_fds_close(pack_fds);
6622 if (error == NULL)
6623 error = pack_err;
6625 free(cwd);
6626 free(repo_path);
6627 return error;
6630 __dead static void
6631 usage_branch(void)
6633 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6634 "[-r repository-path] [name]\n", getprogname());
6635 exit(1);
6638 static const struct got_error *
6639 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6640 struct got_reference *ref)
6642 const struct got_error *err = NULL;
6643 const char *refname, *marker = " ";
6644 char *refstr;
6646 refname = got_ref_get_name(ref);
6647 if (worktree && strcmp(refname,
6648 got_worktree_get_head_ref_name(worktree)) == 0) {
6649 struct got_object_id *id = NULL;
6651 err = got_ref_resolve(&id, repo, ref);
6652 if (err)
6653 return err;
6654 if (got_object_id_cmp(id,
6655 got_worktree_get_base_commit_id(worktree)) == 0)
6656 marker = "* ";
6657 else
6658 marker = "~ ";
6659 free(id);
6662 if (strncmp(refname, "refs/heads/", 11) == 0)
6663 refname += 11;
6664 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6665 refname += 18;
6666 if (strncmp(refname, "refs/remotes/", 13) == 0)
6667 refname += 13;
6669 refstr = got_ref_to_str(ref);
6670 if (refstr == NULL)
6671 return got_error_from_errno("got_ref_to_str");
6673 printf("%s%s: %s\n", marker, refname, refstr);
6674 free(refstr);
6675 return NULL;
6678 static const struct got_error *
6679 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6681 const char *refname;
6683 if (worktree == NULL)
6684 return got_error(GOT_ERR_NOT_WORKTREE);
6686 refname = got_worktree_get_head_ref_name(worktree);
6688 if (strncmp(refname, "refs/heads/", 11) == 0)
6689 refname += 11;
6690 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6691 refname += 18;
6693 printf("%s\n", refname);
6695 return NULL;
6698 static const struct got_error *
6699 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6700 int sort_by_time)
6702 static const struct got_error *err = NULL;
6703 struct got_reflist_head refs;
6704 struct got_reflist_entry *re;
6705 struct got_reference *temp_ref = NULL;
6706 int rebase_in_progress, histedit_in_progress;
6708 TAILQ_INIT(&refs);
6710 if (worktree) {
6711 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6712 worktree);
6713 if (err)
6714 return err;
6716 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6717 worktree);
6718 if (err)
6719 return err;
6721 if (rebase_in_progress || histedit_in_progress) {
6722 err = got_ref_open(&temp_ref, repo,
6723 got_worktree_get_head_ref_name(worktree), 0);
6724 if (err)
6725 return err;
6726 list_branch(repo, worktree, temp_ref);
6727 got_ref_close(temp_ref);
6731 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6732 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6733 repo);
6734 if (err)
6735 return err;
6737 TAILQ_FOREACH(re, &refs, entry)
6738 list_branch(repo, worktree, re->ref);
6740 got_ref_list_free(&refs);
6742 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6743 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6744 repo);
6745 if (err)
6746 return err;
6748 TAILQ_FOREACH(re, &refs, entry)
6749 list_branch(repo, worktree, re->ref);
6751 got_ref_list_free(&refs);
6753 return NULL;
6756 static const struct got_error *
6757 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6758 const char *branch_name)
6760 const struct got_error *err = NULL;
6761 struct got_reference *ref = NULL;
6762 char *refname, *remote_refname = NULL;
6764 if (strncmp(branch_name, "refs/", 5) == 0)
6765 branch_name += 5;
6766 if (strncmp(branch_name, "heads/", 6) == 0)
6767 branch_name += 6;
6768 else if (strncmp(branch_name, "remotes/", 8) == 0)
6769 branch_name += 8;
6771 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6772 return got_error_from_errno("asprintf");
6774 if (asprintf(&remote_refname, "refs/remotes/%s",
6775 branch_name) == -1) {
6776 err = got_error_from_errno("asprintf");
6777 goto done;
6780 err = got_ref_open(&ref, repo, refname, 0);
6781 if (err) {
6782 const struct got_error *err2;
6783 if (err->code != GOT_ERR_NOT_REF)
6784 goto done;
6786 * Keep 'err' intact such that if neither branch exists
6787 * we report "refs/heads" rather than "refs/remotes" in
6788 * our error message.
6790 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6791 if (err2)
6792 goto done;
6793 err = NULL;
6796 if (worktree &&
6797 strcmp(got_worktree_get_head_ref_name(worktree),
6798 got_ref_get_name(ref)) == 0) {
6799 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6800 "will not delete this work tree's current branch");
6801 goto done;
6804 err = delete_ref(repo, ref);
6805 done:
6806 if (ref)
6807 got_ref_close(ref);
6808 free(refname);
6809 free(remote_refname);
6810 return err;
6813 static const struct got_error *
6814 add_branch(struct got_repository *repo, const char *branch_name,
6815 struct got_object_id *base_commit_id)
6817 const struct got_error *err = NULL;
6818 struct got_reference *ref = NULL;
6819 char *refname = NULL;
6822 * Don't let the user create a branch name with a leading '-'.
6823 * While technically a valid reference name, this case is usually
6824 * an unintended typo.
6826 if (branch_name[0] == '-')
6827 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6829 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6830 branch_name += 11;
6832 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6833 err = got_error_from_errno("asprintf");
6834 goto done;
6837 err = got_ref_open(&ref, repo, refname, 0);
6838 if (err == NULL) {
6839 err = got_error(GOT_ERR_BRANCH_EXISTS);
6840 goto done;
6841 } else if (err->code != GOT_ERR_NOT_REF)
6842 goto done;
6844 err = got_ref_alloc(&ref, refname, base_commit_id);
6845 if (err)
6846 goto done;
6848 err = got_ref_write(ref, repo);
6849 done:
6850 if (ref)
6851 got_ref_close(ref);
6852 free(refname);
6853 return err;
6856 static const struct got_error *
6857 cmd_branch(int argc, char *argv[])
6859 const struct got_error *error = NULL;
6860 struct got_repository *repo = NULL;
6861 struct got_worktree *worktree = NULL;
6862 char *cwd = NULL, *repo_path = NULL;
6863 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6864 const char *delref = NULL, *commit_id_arg = NULL;
6865 struct got_reference *ref = NULL;
6866 struct got_pathlist_head paths;
6867 struct got_object_id *commit_id = NULL;
6868 char *commit_id_str = NULL;
6869 int *pack_fds = NULL;
6871 TAILQ_INIT(&paths);
6873 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6874 switch (ch) {
6875 case 'c':
6876 commit_id_arg = optarg;
6877 break;
6878 case 'd':
6879 delref = optarg;
6880 break;
6881 case 'l':
6882 do_list = 1;
6883 break;
6884 case 'n':
6885 do_update = 0;
6886 break;
6887 case 'r':
6888 repo_path = realpath(optarg, NULL);
6889 if (repo_path == NULL)
6890 return got_error_from_errno2("realpath",
6891 optarg);
6892 got_path_strip_trailing_slashes(repo_path);
6893 break;
6894 case 't':
6895 sort_by_time = 1;
6896 break;
6897 default:
6898 usage_branch();
6899 /* NOTREACHED */
6903 if (do_list && delref)
6904 option_conflict('l', 'd');
6905 if (sort_by_time && !do_list)
6906 errx(1, "-t option requires -l option");
6908 argc -= optind;
6909 argv += optind;
6911 if (!do_list && !delref && argc == 0)
6912 do_show = 1;
6914 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6915 errx(1, "-c option can only be used when creating a branch");
6917 if (do_list || delref) {
6918 if (argc > 0)
6919 usage_branch();
6920 } else if (!do_show && argc != 1)
6921 usage_branch();
6923 #ifndef PROFILE
6924 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6925 "sendfd unveil", NULL) == -1)
6926 err(1, "pledge");
6927 #endif
6928 cwd = getcwd(NULL, 0);
6929 if (cwd == NULL) {
6930 error = got_error_from_errno("getcwd");
6931 goto done;
6934 error = got_repo_pack_fds_open(&pack_fds);
6935 if (error != NULL)
6936 goto done;
6938 if (repo_path == NULL) {
6939 error = got_worktree_open(&worktree, cwd);
6940 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6941 goto done;
6942 else
6943 error = NULL;
6944 if (worktree) {
6945 repo_path =
6946 strdup(got_worktree_get_repo_path(worktree));
6947 if (repo_path == NULL)
6948 error = got_error_from_errno("strdup");
6949 if (error)
6950 goto done;
6951 } else {
6952 repo_path = strdup(cwd);
6953 if (repo_path == NULL) {
6954 error = got_error_from_errno("strdup");
6955 goto done;
6960 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6961 if (error != NULL)
6962 goto done;
6964 #ifndef PROFILE
6965 if (do_list || do_show) {
6966 /* Remove "cpath" promise. */
6967 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6968 NULL) == -1)
6969 err(1, "pledge");
6971 #endif
6973 error = apply_unveil(got_repo_get_path(repo), do_list,
6974 worktree ? got_worktree_get_root_path(worktree) : NULL);
6975 if (error)
6976 goto done;
6978 if (do_show)
6979 error = show_current_branch(repo, worktree);
6980 else if (do_list)
6981 error = list_branches(repo, worktree, sort_by_time);
6982 else if (delref)
6983 error = delete_branch(repo, worktree, delref);
6984 else {
6985 struct got_reflist_head refs;
6986 TAILQ_INIT(&refs);
6987 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6988 NULL);
6989 if (error)
6990 goto done;
6991 if (commit_id_arg == NULL)
6992 commit_id_arg = worktree ?
6993 got_worktree_get_head_ref_name(worktree) :
6994 GOT_REF_HEAD;
6995 error = got_repo_match_object_id(&commit_id, NULL,
6996 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6997 got_ref_list_free(&refs);
6998 if (error)
6999 goto done;
7000 error = add_branch(repo, argv[0], commit_id);
7001 if (error)
7002 goto done;
7003 if (worktree && do_update) {
7004 struct got_update_progress_arg upa;
7005 char *branch_refname = NULL;
7007 error = got_object_id_str(&commit_id_str, commit_id);
7008 if (error)
7009 goto done;
7010 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7011 worktree);
7012 if (error)
7013 goto done;
7014 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7015 == -1) {
7016 error = got_error_from_errno("asprintf");
7017 goto done;
7019 error = got_ref_open(&ref, repo, branch_refname, 0);
7020 free(branch_refname);
7021 if (error)
7022 goto done;
7023 error = switch_head_ref(ref, commit_id, worktree,
7024 repo);
7025 if (error)
7026 goto done;
7027 error = got_worktree_set_base_commit_id(worktree, repo,
7028 commit_id);
7029 if (error)
7030 goto done;
7031 memset(&upa, 0, sizeof(upa));
7032 error = got_worktree_checkout_files(worktree, &paths,
7033 repo, update_progress, &upa, check_cancelled,
7034 NULL);
7035 if (error)
7036 goto done;
7037 if (upa.did_something) {
7038 printf("Updated to %s: %s\n",
7039 got_worktree_get_head_ref_name(worktree),
7040 commit_id_str);
7042 print_update_progress_stats(&upa);
7045 done:
7046 if (ref)
7047 got_ref_close(ref);
7048 if (repo) {
7049 const struct got_error *close_err = got_repo_close(repo);
7050 if (error == NULL)
7051 error = close_err;
7053 if (worktree)
7054 got_worktree_close(worktree);
7055 if (pack_fds) {
7056 const struct got_error *pack_err =
7057 got_repo_pack_fds_close(pack_fds);
7058 if (error == NULL)
7059 error = pack_err;
7061 free(cwd);
7062 free(repo_path);
7063 free(commit_id);
7064 free(commit_id_str);
7065 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7066 return error;
7070 __dead static void
7071 usage_tag(void)
7073 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7074 "[-r repository-path] [-s signer-id] name\n", getprogname());
7075 exit(1);
7078 #if 0
7079 static const struct got_error *
7080 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7082 const struct got_error *err = NULL;
7083 struct got_reflist_entry *re, *se, *new;
7084 struct got_object_id *re_id, *se_id;
7085 struct got_tag_object *re_tag, *se_tag;
7086 time_t re_time, se_time;
7088 STAILQ_FOREACH(re, tags, entry) {
7089 se = STAILQ_FIRST(sorted);
7090 if (se == NULL) {
7091 err = got_reflist_entry_dup(&new, re);
7092 if (err)
7093 return err;
7094 STAILQ_INSERT_HEAD(sorted, new, entry);
7095 continue;
7096 } else {
7097 err = got_ref_resolve(&re_id, repo, re->ref);
7098 if (err)
7099 break;
7100 err = got_object_open_as_tag(&re_tag, repo, re_id);
7101 free(re_id);
7102 if (err)
7103 break;
7104 re_time = got_object_tag_get_tagger_time(re_tag);
7105 got_object_tag_close(re_tag);
7108 while (se) {
7109 err = got_ref_resolve(&se_id, repo, re->ref);
7110 if (err)
7111 break;
7112 err = got_object_open_as_tag(&se_tag, repo, se_id);
7113 free(se_id);
7114 if (err)
7115 break;
7116 se_time = got_object_tag_get_tagger_time(se_tag);
7117 got_object_tag_close(se_tag);
7119 if (se_time > re_time) {
7120 err = got_reflist_entry_dup(&new, re);
7121 if (err)
7122 return err;
7123 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7124 break;
7126 se = STAILQ_NEXT(se, entry);
7127 continue;
7130 done:
7131 return err;
7133 #endif
7135 static const struct got_error *
7136 get_tag_refname(char **refname, const char *tag_name)
7138 const struct got_error *err;
7140 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7141 *refname = strdup(tag_name);
7142 if (*refname == NULL)
7143 return got_error_from_errno("strdup");
7144 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7145 err = got_error_from_errno("asprintf");
7146 *refname = NULL;
7147 return err;
7150 return NULL;
7153 static const struct got_error *
7154 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7155 const char *allowed_signers, const char *revoked_signers, int verbosity)
7157 static const struct got_error *err = NULL;
7158 struct got_reflist_head refs;
7159 struct got_reflist_entry *re;
7160 char *wanted_refname = NULL;
7161 int bad_sigs = 0;
7163 TAILQ_INIT(&refs);
7165 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7166 if (err)
7167 return err;
7169 if (tag_name) {
7170 struct got_reference *ref;
7171 err = get_tag_refname(&wanted_refname, tag_name);
7172 if (err)
7173 goto done;
7174 /* Wanted tag reference should exist. */
7175 err = got_ref_open(&ref, repo, wanted_refname, 0);
7176 if (err)
7177 goto done;
7178 got_ref_close(ref);
7181 TAILQ_FOREACH(re, &refs, entry) {
7182 const char *refname;
7183 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7184 char datebuf[26];
7185 const char *tagger, *ssh_sig = NULL;
7186 char *sig_msg = NULL;
7187 time_t tagger_time;
7188 struct got_object_id *id;
7189 struct got_tag_object *tag;
7190 struct got_commit_object *commit = NULL;
7192 refname = got_ref_get_name(re->ref);
7193 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7194 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7195 continue;
7196 refname += 10;
7197 refstr = got_ref_to_str(re->ref);
7198 if (refstr == NULL) {
7199 err = got_error_from_errno("got_ref_to_str");
7200 break;
7203 err = got_ref_resolve(&id, repo, re->ref);
7204 if (err)
7205 break;
7206 err = got_object_open_as_tag(&tag, repo, id);
7207 if (err) {
7208 if (err->code != GOT_ERR_OBJ_TYPE) {
7209 free(id);
7210 break;
7212 /* "lightweight" tag */
7213 err = got_object_open_as_commit(&commit, repo, id);
7214 if (err) {
7215 free(id);
7216 break;
7218 tagger = got_object_commit_get_committer(commit);
7219 tagger_time =
7220 got_object_commit_get_committer_time(commit);
7221 err = got_object_id_str(&id_str, id);
7222 free(id);
7223 if (err)
7224 break;
7225 } else {
7226 free(id);
7227 tagger = got_object_tag_get_tagger(tag);
7228 tagger_time = got_object_tag_get_tagger_time(tag);
7229 err = got_object_id_str(&id_str,
7230 got_object_tag_get_object_id(tag));
7231 if (err)
7232 break;
7235 if (tag && verify_tags) {
7236 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7237 got_object_tag_get_message(tag));
7238 if (ssh_sig && allowed_signers == NULL) {
7239 err = got_error_msg(
7240 GOT_ERR_VERIFY_TAG_SIGNATURE,
7241 "SSH signature verification requires "
7242 "setting allowed_signers in "
7243 "got.conf(5)");
7244 break;
7248 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7249 free(refstr);
7250 printf("from: %s\n", tagger);
7251 datestr = get_datestr(&tagger_time, datebuf);
7252 if (datestr)
7253 printf("date: %s UTC\n", datestr);
7254 if (commit)
7255 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7256 else {
7257 switch (got_object_tag_get_object_type(tag)) {
7258 case GOT_OBJ_TYPE_BLOB:
7259 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7260 id_str);
7261 break;
7262 case GOT_OBJ_TYPE_TREE:
7263 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7264 id_str);
7265 break;
7266 case GOT_OBJ_TYPE_COMMIT:
7267 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7268 id_str);
7269 break;
7270 case GOT_OBJ_TYPE_TAG:
7271 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7272 id_str);
7273 break;
7274 default:
7275 break;
7278 free(id_str);
7280 if (ssh_sig) {
7281 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7282 allowed_signers, revoked_signers, verbosity);
7283 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7284 bad_sigs = 1;
7285 else if (err)
7286 break;
7287 printf("signature: %s", sig_msg);
7288 free(sig_msg);
7289 sig_msg = NULL;
7292 if (commit) {
7293 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7294 if (err)
7295 break;
7296 got_object_commit_close(commit);
7297 } else {
7298 tagmsg0 = strdup(got_object_tag_get_message(tag));
7299 got_object_tag_close(tag);
7300 if (tagmsg0 == NULL) {
7301 err = got_error_from_errno("strdup");
7302 break;
7306 tagmsg = tagmsg0;
7307 do {
7308 line = strsep(&tagmsg, "\n");
7309 if (line)
7310 printf(" %s\n", line);
7311 } while (line);
7312 free(tagmsg0);
7314 done:
7315 got_ref_list_free(&refs);
7316 free(wanted_refname);
7318 if (err == NULL && bad_sigs)
7319 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7320 return err;
7323 static const struct got_error *
7324 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7325 const char *tag_name, const char *repo_path)
7327 const struct got_error *err = NULL;
7328 char *template = NULL, *initial_content = NULL;
7329 char *editor = NULL;
7330 int initial_content_len;
7331 int fd = -1;
7333 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7334 err = got_error_from_errno("asprintf");
7335 goto done;
7338 initial_content_len = asprintf(&initial_content,
7339 "\n# tagging commit %s as %s\n",
7340 commit_id_str, tag_name);
7341 if (initial_content_len == -1) {
7342 err = got_error_from_errno("asprintf");
7343 goto done;
7346 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7347 if (err)
7348 goto done;
7350 if (write(fd, initial_content, initial_content_len) == -1) {
7351 err = got_error_from_errno2("write", *tagmsg_path);
7352 goto done;
7355 err = get_editor(&editor);
7356 if (err)
7357 goto done;
7358 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7359 initial_content_len, 1);
7360 done:
7361 free(initial_content);
7362 free(template);
7363 free(editor);
7365 if (fd != -1 && close(fd) == -1 && err == NULL)
7366 err = got_error_from_errno2("close", *tagmsg_path);
7368 if (err) {
7369 free(*tagmsg);
7370 *tagmsg = NULL;
7372 return err;
7375 static const struct got_error *
7376 add_tag(struct got_repository *repo, const char *tagger,
7377 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7378 const char *signer_id, int verbosity)
7380 const struct got_error *err = NULL;
7381 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7382 char *label = NULL, *commit_id_str = NULL;
7383 struct got_reference *ref = NULL;
7384 char *refname = NULL, *tagmsg = NULL;
7385 char *tagmsg_path = NULL, *tag_id_str = NULL;
7386 int preserve_tagmsg = 0;
7387 struct got_reflist_head refs;
7389 TAILQ_INIT(&refs);
7392 * Don't let the user create a tag name with a leading '-'.
7393 * While technically a valid reference name, this case is usually
7394 * an unintended typo.
7396 if (tag_name[0] == '-')
7397 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7399 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7400 if (err)
7401 goto done;
7403 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7404 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7405 if (err)
7406 goto done;
7408 err = got_object_id_str(&commit_id_str, commit_id);
7409 if (err)
7410 goto done;
7412 err = get_tag_refname(&refname, tag_name);
7413 if (err)
7414 goto done;
7415 if (strncmp("refs/tags/", tag_name, 10) == 0)
7416 tag_name += 10;
7418 err = got_ref_open(&ref, repo, refname, 0);
7419 if (err == NULL) {
7420 err = got_error(GOT_ERR_TAG_EXISTS);
7421 goto done;
7422 } else if (err->code != GOT_ERR_NOT_REF)
7423 goto done;
7425 if (tagmsg_arg == NULL) {
7426 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7427 tag_name, got_repo_get_path(repo));
7428 if (err) {
7429 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7430 tagmsg_path != NULL)
7431 preserve_tagmsg = 1;
7432 goto done;
7434 /* Editor is done; we can now apply unveil(2) */
7435 err = got_sigs_apply_unveil();
7436 if (err)
7437 goto done;
7438 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7439 if (err)
7440 goto done;
7443 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7444 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7445 verbosity);
7446 if (err) {
7447 if (tagmsg_path)
7448 preserve_tagmsg = 1;
7449 goto done;
7452 err = got_ref_alloc(&ref, refname, tag_id);
7453 if (err) {
7454 if (tagmsg_path)
7455 preserve_tagmsg = 1;
7456 goto done;
7459 err = got_ref_write(ref, repo);
7460 if (err) {
7461 if (tagmsg_path)
7462 preserve_tagmsg = 1;
7463 goto done;
7466 err = got_object_id_str(&tag_id_str, tag_id);
7467 if (err) {
7468 if (tagmsg_path)
7469 preserve_tagmsg = 1;
7470 goto done;
7472 printf("Created tag %s\n", tag_id_str);
7473 done:
7474 if (preserve_tagmsg) {
7475 fprintf(stderr, "%s: tag message preserved in %s\n",
7476 getprogname(), tagmsg_path);
7477 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7478 err = got_error_from_errno2("unlink", tagmsg_path);
7479 free(tag_id_str);
7480 if (ref)
7481 got_ref_close(ref);
7482 free(commit_id);
7483 free(commit_id_str);
7484 free(refname);
7485 free(tagmsg);
7486 free(tagmsg_path);
7487 got_ref_list_free(&refs);
7488 return err;
7491 static const struct got_error *
7492 cmd_tag(int argc, char *argv[])
7494 const struct got_error *error = NULL;
7495 struct got_repository *repo = NULL;
7496 struct got_worktree *worktree = NULL;
7497 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7498 char *gitconfig_path = NULL, *tagger = NULL;
7499 char *allowed_signers = NULL, *revoked_signers = NULL;
7500 const char *signer_id = NULL;
7501 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7502 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7503 int *pack_fds = NULL;
7505 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7506 switch (ch) {
7507 case 'c':
7508 commit_id_arg = optarg;
7509 break;
7510 case 'l':
7511 do_list = 1;
7512 break;
7513 case 'm':
7514 tagmsg = optarg;
7515 break;
7516 case 'r':
7517 repo_path = realpath(optarg, NULL);
7518 if (repo_path == NULL) {
7519 error = got_error_from_errno2("realpath",
7520 optarg);
7521 goto done;
7523 got_path_strip_trailing_slashes(repo_path);
7524 break;
7525 case 's':
7526 signer_id = optarg;
7527 break;
7528 case 'V':
7529 verify_tags = 1;
7530 break;
7531 case 'v':
7532 if (verbosity < 0)
7533 verbosity = 0;
7534 else if (verbosity < 3)
7535 verbosity++;
7536 break;
7537 default:
7538 usage_tag();
7539 /* NOTREACHED */
7543 argc -= optind;
7544 argv += optind;
7546 if (do_list || verify_tags) {
7547 if (commit_id_arg != NULL)
7548 errx(1,
7549 "-c option can only be used when creating a tag");
7550 if (tagmsg) {
7551 if (do_list)
7552 option_conflict('l', 'm');
7553 else
7554 option_conflict('V', 'm');
7556 if (signer_id) {
7557 if (do_list)
7558 option_conflict('l', 's');
7559 else
7560 option_conflict('V', 's');
7562 if (argc > 1)
7563 usage_tag();
7564 } else if (argc != 1)
7565 usage_tag();
7567 if (argc == 1)
7568 tag_name = argv[0];
7570 #ifndef PROFILE
7571 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7572 "sendfd unveil", NULL) == -1)
7573 err(1, "pledge");
7574 #endif
7575 cwd = getcwd(NULL, 0);
7576 if (cwd == NULL) {
7577 error = got_error_from_errno("getcwd");
7578 goto done;
7581 error = got_repo_pack_fds_open(&pack_fds);
7582 if (error != NULL)
7583 goto done;
7585 if (repo_path == NULL) {
7586 error = got_worktree_open(&worktree, cwd);
7587 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7588 goto done;
7589 else
7590 error = NULL;
7591 if (worktree) {
7592 repo_path =
7593 strdup(got_worktree_get_repo_path(worktree));
7594 if (repo_path == NULL)
7595 error = got_error_from_errno("strdup");
7596 if (error)
7597 goto done;
7598 } else {
7599 repo_path = strdup(cwd);
7600 if (repo_path == NULL) {
7601 error = got_error_from_errno("strdup");
7602 goto done;
7607 if (do_list || verify_tags) {
7608 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7609 if (error != NULL)
7610 goto done;
7611 error = get_allowed_signers(&allowed_signers, repo, worktree);
7612 if (error)
7613 goto done;
7614 error = get_revoked_signers(&revoked_signers, repo, worktree);
7615 if (error)
7616 goto done;
7617 if (worktree) {
7618 /* Release work tree lock. */
7619 got_worktree_close(worktree);
7620 worktree = NULL;
7624 * Remove "cpath" promise unless needed for signature tmpfile
7625 * creation.
7627 if (verify_tags)
7628 got_sigs_apply_unveil();
7629 else {
7630 #ifndef PROFILE
7631 if (pledge("stdio rpath wpath flock proc exec sendfd "
7632 "unveil", NULL) == -1)
7633 err(1, "pledge");
7634 #endif
7636 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7637 if (error)
7638 goto done;
7639 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7640 revoked_signers, verbosity);
7641 } else {
7642 error = get_gitconfig_path(&gitconfig_path);
7643 if (error)
7644 goto done;
7645 error = got_repo_open(&repo, repo_path, gitconfig_path,
7646 pack_fds);
7647 if (error != NULL)
7648 goto done;
7650 error = get_author(&tagger, repo, worktree);
7651 if (error)
7652 goto done;
7653 if (signer_id == NULL)
7654 signer_id = get_signer_id(repo, worktree);
7656 if (tagmsg) {
7657 if (signer_id) {
7658 error = got_sigs_apply_unveil();
7659 if (error)
7660 goto done;
7662 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7663 if (error)
7664 goto done;
7667 if (commit_id_arg == NULL) {
7668 struct got_reference *head_ref;
7669 struct got_object_id *commit_id;
7670 error = got_ref_open(&head_ref, repo,
7671 worktree ? got_worktree_get_head_ref_name(worktree)
7672 : GOT_REF_HEAD, 0);
7673 if (error)
7674 goto done;
7675 error = got_ref_resolve(&commit_id, repo, head_ref);
7676 got_ref_close(head_ref);
7677 if (error)
7678 goto done;
7679 error = got_object_id_str(&commit_id_str, commit_id);
7680 free(commit_id);
7681 if (error)
7682 goto done;
7685 if (worktree) {
7686 /* Release work tree lock. */
7687 got_worktree_close(worktree);
7688 worktree = NULL;
7691 error = add_tag(repo, tagger, tag_name,
7692 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7693 signer_id, verbosity);
7695 done:
7696 if (repo) {
7697 const struct got_error *close_err = got_repo_close(repo);
7698 if (error == NULL)
7699 error = close_err;
7701 if (worktree)
7702 got_worktree_close(worktree);
7703 if (pack_fds) {
7704 const struct got_error *pack_err =
7705 got_repo_pack_fds_close(pack_fds);
7706 if (error == NULL)
7707 error = pack_err;
7709 free(cwd);
7710 free(repo_path);
7711 free(gitconfig_path);
7712 free(commit_id_str);
7713 free(tagger);
7714 free(allowed_signers);
7715 free(revoked_signers);
7716 return error;
7719 __dead static void
7720 usage_add(void)
7722 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7723 exit(1);
7726 static const struct got_error *
7727 add_progress(void *arg, unsigned char status, const char *path)
7729 while (path[0] == '/')
7730 path++;
7731 printf("%c %s\n", status, path);
7732 return NULL;
7735 static const struct got_error *
7736 cmd_add(int argc, char *argv[])
7738 const struct got_error *error = NULL;
7739 struct got_repository *repo = NULL;
7740 struct got_worktree *worktree = NULL;
7741 char *cwd = NULL;
7742 struct got_pathlist_head paths;
7743 struct got_pathlist_entry *pe;
7744 int ch, can_recurse = 0, no_ignores = 0;
7745 int *pack_fds = NULL;
7747 TAILQ_INIT(&paths);
7749 while ((ch = getopt(argc, argv, "IR")) != -1) {
7750 switch (ch) {
7751 case 'I':
7752 no_ignores = 1;
7753 break;
7754 case 'R':
7755 can_recurse = 1;
7756 break;
7757 default:
7758 usage_add();
7759 /* NOTREACHED */
7763 argc -= optind;
7764 argv += optind;
7766 #ifndef PROFILE
7767 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7768 NULL) == -1)
7769 err(1, "pledge");
7770 #endif
7771 if (argc < 1)
7772 usage_add();
7774 cwd = getcwd(NULL, 0);
7775 if (cwd == NULL) {
7776 error = got_error_from_errno("getcwd");
7777 goto done;
7780 error = got_repo_pack_fds_open(&pack_fds);
7781 if (error != NULL)
7782 goto done;
7784 error = got_worktree_open(&worktree, cwd);
7785 if (error) {
7786 if (error->code == GOT_ERR_NOT_WORKTREE)
7787 error = wrap_not_worktree_error(error, "add", cwd);
7788 goto done;
7791 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7792 NULL, pack_fds);
7793 if (error != NULL)
7794 goto done;
7796 error = apply_unveil(got_repo_get_path(repo), 1,
7797 got_worktree_get_root_path(worktree));
7798 if (error)
7799 goto done;
7801 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7802 if (error)
7803 goto done;
7805 if (!can_recurse) {
7806 char *ondisk_path;
7807 struct stat sb;
7808 TAILQ_FOREACH(pe, &paths, entry) {
7809 if (asprintf(&ondisk_path, "%s/%s",
7810 got_worktree_get_root_path(worktree),
7811 pe->path) == -1) {
7812 error = got_error_from_errno("asprintf");
7813 goto done;
7815 if (lstat(ondisk_path, &sb) == -1) {
7816 if (errno == ENOENT) {
7817 free(ondisk_path);
7818 continue;
7820 error = got_error_from_errno2("lstat",
7821 ondisk_path);
7822 free(ondisk_path);
7823 goto done;
7825 free(ondisk_path);
7826 if (S_ISDIR(sb.st_mode)) {
7827 error = got_error_msg(GOT_ERR_BAD_PATH,
7828 "adding directories requires -R option");
7829 goto done;
7834 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7835 NULL, repo, no_ignores);
7836 done:
7837 if (repo) {
7838 const struct got_error *close_err = got_repo_close(repo);
7839 if (error == NULL)
7840 error = close_err;
7842 if (worktree)
7843 got_worktree_close(worktree);
7844 if (pack_fds) {
7845 const struct got_error *pack_err =
7846 got_repo_pack_fds_close(pack_fds);
7847 if (error == NULL)
7848 error = pack_err;
7850 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7851 free(cwd);
7852 return error;
7855 __dead static void
7856 usage_remove(void)
7858 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7859 getprogname());
7860 exit(1);
7863 static const struct got_error *
7864 print_remove_status(void *arg, unsigned char status,
7865 unsigned char staged_status, const char *path)
7867 while (path[0] == '/')
7868 path++;
7869 if (status == GOT_STATUS_NONEXISTENT)
7870 return NULL;
7871 if (status == staged_status && (status == GOT_STATUS_DELETE))
7872 status = GOT_STATUS_NO_CHANGE;
7873 printf("%c%c %s\n", status, staged_status, path);
7874 return NULL;
7877 static const struct got_error *
7878 cmd_remove(int argc, char *argv[])
7880 const struct got_error *error = NULL;
7881 struct got_worktree *worktree = NULL;
7882 struct got_repository *repo = NULL;
7883 const char *status_codes = NULL;
7884 char *cwd = NULL;
7885 struct got_pathlist_head paths;
7886 struct got_pathlist_entry *pe;
7887 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7888 int ignore_missing_paths = 0;
7889 int *pack_fds = NULL;
7891 TAILQ_INIT(&paths);
7893 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7894 switch (ch) {
7895 case 'f':
7896 delete_local_mods = 1;
7897 ignore_missing_paths = 1;
7898 break;
7899 case 'k':
7900 keep_on_disk = 1;
7901 break;
7902 case 'R':
7903 can_recurse = 1;
7904 break;
7905 case 's':
7906 for (i = 0; i < strlen(optarg); i++) {
7907 switch (optarg[i]) {
7908 case GOT_STATUS_MODIFY:
7909 delete_local_mods = 1;
7910 break;
7911 case GOT_STATUS_MISSING:
7912 ignore_missing_paths = 1;
7913 break;
7914 default:
7915 errx(1, "invalid status code '%c'",
7916 optarg[i]);
7919 status_codes = optarg;
7920 break;
7921 default:
7922 usage_remove();
7923 /* NOTREACHED */
7927 argc -= optind;
7928 argv += optind;
7930 #ifndef PROFILE
7931 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7932 NULL) == -1)
7933 err(1, "pledge");
7934 #endif
7935 if (argc < 1)
7936 usage_remove();
7938 cwd = getcwd(NULL, 0);
7939 if (cwd == NULL) {
7940 error = got_error_from_errno("getcwd");
7941 goto done;
7944 error = got_repo_pack_fds_open(&pack_fds);
7945 if (error != NULL)
7946 goto done;
7948 error = got_worktree_open(&worktree, cwd);
7949 if (error) {
7950 if (error->code == GOT_ERR_NOT_WORKTREE)
7951 error = wrap_not_worktree_error(error, "remove", cwd);
7952 goto done;
7955 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7956 NULL, pack_fds);
7957 if (error)
7958 goto done;
7960 error = apply_unveil(got_repo_get_path(repo), 1,
7961 got_worktree_get_root_path(worktree));
7962 if (error)
7963 goto done;
7965 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7966 if (error)
7967 goto done;
7969 if (!can_recurse) {
7970 char *ondisk_path;
7971 struct stat sb;
7972 TAILQ_FOREACH(pe, &paths, entry) {
7973 if (asprintf(&ondisk_path, "%s/%s",
7974 got_worktree_get_root_path(worktree),
7975 pe->path) == -1) {
7976 error = got_error_from_errno("asprintf");
7977 goto done;
7979 if (lstat(ondisk_path, &sb) == -1) {
7980 if (errno == ENOENT) {
7981 free(ondisk_path);
7982 continue;
7984 error = got_error_from_errno2("lstat",
7985 ondisk_path);
7986 free(ondisk_path);
7987 goto done;
7989 free(ondisk_path);
7990 if (S_ISDIR(sb.st_mode)) {
7991 error = got_error_msg(GOT_ERR_BAD_PATH,
7992 "removing directories requires -R option");
7993 goto done;
7998 error = got_worktree_schedule_delete(worktree, &paths,
7999 delete_local_mods, status_codes, print_remove_status, NULL,
8000 repo, keep_on_disk, ignore_missing_paths);
8001 done:
8002 if (repo) {
8003 const struct got_error *close_err = got_repo_close(repo);
8004 if (error == NULL)
8005 error = close_err;
8007 if (worktree)
8008 got_worktree_close(worktree);
8009 if (pack_fds) {
8010 const struct got_error *pack_err =
8011 got_repo_pack_fds_close(pack_fds);
8012 if (error == NULL)
8013 error = pack_err;
8015 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8016 free(cwd);
8017 return error;
8020 __dead static void
8021 usage_patch(void)
8023 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8024 "[patchfile]\n", getprogname());
8025 exit(1);
8028 static const struct got_error *
8029 patch_from_stdin(int *patchfd)
8031 const struct got_error *err = NULL;
8032 ssize_t r;
8033 char buf[BUFSIZ];
8034 sig_t sighup, sigint, sigquit;
8036 *patchfd = got_opentempfd();
8037 if (*patchfd == -1)
8038 return got_error_from_errno("got_opentempfd");
8040 sighup = signal(SIGHUP, SIG_DFL);
8041 sigint = signal(SIGINT, SIG_DFL);
8042 sigquit = signal(SIGQUIT, SIG_DFL);
8044 for (;;) {
8045 r = read(0, buf, sizeof(buf));
8046 if (r == -1) {
8047 err = got_error_from_errno("read");
8048 break;
8050 if (r == 0)
8051 break;
8052 if (write(*patchfd, buf, r) == -1) {
8053 err = got_error_from_errno("write");
8054 break;
8058 signal(SIGHUP, sighup);
8059 signal(SIGINT, sigint);
8060 signal(SIGQUIT, sigquit);
8062 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8063 err = got_error_from_errno("lseek");
8065 if (err != NULL) {
8066 close(*patchfd);
8067 *patchfd = -1;
8070 return err;
8073 static const struct got_error *
8074 patch_progress(void *arg, const char *old, const char *new,
8075 unsigned char status, const struct got_error *error, int old_from,
8076 int old_lines, int new_from, int new_lines, int offset,
8077 int ws_mangled, const struct got_error *hunk_err)
8079 const char *path = new == NULL ? old : new;
8081 while (*path == '/')
8082 path++;
8084 if (status != 0)
8085 printf("%c %s\n", status, path);
8087 if (error != NULL)
8088 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8090 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8091 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8092 old_lines, new_from, new_lines);
8093 if (hunk_err != NULL)
8094 printf("%s\n", hunk_err->msg);
8095 else if (offset != 0)
8096 printf("applied with offset %d\n", offset);
8097 else
8098 printf("hunk contains mangled whitespace\n");
8101 return NULL;
8104 static const struct got_error *
8105 cmd_patch(int argc, char *argv[])
8107 const struct got_error *error = NULL, *close_error = NULL;
8108 struct got_worktree *worktree = NULL;
8109 struct got_repository *repo = NULL;
8110 struct got_reflist_head refs;
8111 struct got_object_id *commit_id = NULL;
8112 const char *commit_id_str = NULL;
8113 struct stat sb;
8114 const char *errstr;
8115 char *cwd = NULL;
8116 int ch, nop = 0, strip = -1, reverse = 0;
8117 int patchfd;
8118 int *pack_fds = NULL;
8120 TAILQ_INIT(&refs);
8122 #ifndef PROFILE
8123 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8124 "unveil", NULL) == -1)
8125 err(1, "pledge");
8126 #endif
8128 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8129 switch (ch) {
8130 case 'c':
8131 commit_id_str = optarg;
8132 break;
8133 case 'n':
8134 nop = 1;
8135 break;
8136 case 'p':
8137 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8138 if (errstr != NULL)
8139 errx(1, "pathname strip count is %s: %s",
8140 errstr, optarg);
8141 break;
8142 case 'R':
8143 reverse = 1;
8144 break;
8145 default:
8146 usage_patch();
8147 /* NOTREACHED */
8151 argc -= optind;
8152 argv += optind;
8154 if (argc == 0) {
8155 error = patch_from_stdin(&patchfd);
8156 if (error)
8157 return error;
8158 } else if (argc == 1) {
8159 patchfd = open(argv[0], O_RDONLY);
8160 if (patchfd == -1) {
8161 error = got_error_from_errno2("open", argv[0]);
8162 return error;
8164 if (fstat(patchfd, &sb) == -1) {
8165 error = got_error_from_errno2("fstat", argv[0]);
8166 goto done;
8168 if (!S_ISREG(sb.st_mode)) {
8169 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8170 goto done;
8172 } else
8173 usage_patch();
8175 if ((cwd = getcwd(NULL, 0)) == NULL) {
8176 error = got_error_from_errno("getcwd");
8177 goto done;
8180 error = got_repo_pack_fds_open(&pack_fds);
8181 if (error != NULL)
8182 goto done;
8184 error = got_worktree_open(&worktree, cwd);
8185 if (error != NULL)
8186 goto done;
8188 const char *repo_path = got_worktree_get_repo_path(worktree);
8189 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8190 if (error != NULL)
8191 goto done;
8193 error = apply_unveil(got_repo_get_path(repo), 0,
8194 got_worktree_get_root_path(worktree));
8195 if (error != NULL)
8196 goto done;
8198 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8199 if (error)
8200 goto done;
8202 if (commit_id_str != NULL) {
8203 error = got_repo_match_object_id(&commit_id, NULL,
8204 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8205 if (error)
8206 goto done;
8209 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8210 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8212 done:
8213 got_ref_list_free(&refs);
8214 free(commit_id);
8215 if (repo) {
8216 close_error = got_repo_close(repo);
8217 if (error == NULL)
8218 error = close_error;
8220 if (worktree != NULL) {
8221 close_error = got_worktree_close(worktree);
8222 if (error == NULL)
8223 error = close_error;
8225 if (pack_fds) {
8226 const struct got_error *pack_err =
8227 got_repo_pack_fds_close(pack_fds);
8228 if (error == NULL)
8229 error = pack_err;
8231 free(cwd);
8232 return error;
8235 __dead static void
8236 usage_revert(void)
8238 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8239 getprogname());
8240 exit(1);
8243 static const struct got_error *
8244 revert_progress(void *arg, unsigned char status, const char *path)
8246 if (status == GOT_STATUS_UNVERSIONED)
8247 return NULL;
8249 while (path[0] == '/')
8250 path++;
8251 printf("%c %s\n", status, path);
8252 return NULL;
8255 struct choose_patch_arg {
8256 FILE *patch_script_file;
8257 const char *action;
8260 static const struct got_error *
8261 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8262 int nchanges, const char *action)
8264 const struct got_error *err;
8265 char *line = NULL;
8266 size_t linesize = 0;
8267 ssize_t linelen;
8269 switch (status) {
8270 case GOT_STATUS_ADD:
8271 printf("A %s\n%s this addition? [y/n] ", path, action);
8272 break;
8273 case GOT_STATUS_DELETE:
8274 printf("D %s\n%s this deletion? [y/n] ", path, action);
8275 break;
8276 case GOT_STATUS_MODIFY:
8277 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8278 return got_error_from_errno("fseek");
8279 printf(GOT_COMMIT_SEP_STR);
8280 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8281 printf("%s", line);
8282 if (linelen == -1 && ferror(patch_file)) {
8283 err = got_error_from_errno("getline");
8284 free(line);
8285 return err;
8287 free(line);
8288 printf(GOT_COMMIT_SEP_STR);
8289 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8290 path, n, nchanges, action);
8291 break;
8292 default:
8293 return got_error_path(path, GOT_ERR_FILE_STATUS);
8296 fflush(stdout);
8297 return NULL;
8300 static const struct got_error *
8301 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8302 FILE *patch_file, int n, int nchanges)
8304 const struct got_error *err = NULL;
8305 char *line = NULL;
8306 size_t linesize = 0;
8307 ssize_t linelen;
8308 int resp = ' ';
8309 struct choose_patch_arg *a = arg;
8311 *choice = GOT_PATCH_CHOICE_NONE;
8313 if (a->patch_script_file) {
8314 char *nl;
8315 err = show_change(status, path, patch_file, n, nchanges,
8316 a->action);
8317 if (err)
8318 return err;
8319 linelen = getline(&line, &linesize, a->patch_script_file);
8320 if (linelen == -1) {
8321 if (ferror(a->patch_script_file))
8322 return got_error_from_errno("getline");
8323 return NULL;
8325 nl = strchr(line, '\n');
8326 if (nl)
8327 *nl = '\0';
8328 if (strcmp(line, "y") == 0) {
8329 *choice = GOT_PATCH_CHOICE_YES;
8330 printf("y\n");
8331 } else if (strcmp(line, "n") == 0) {
8332 *choice = GOT_PATCH_CHOICE_NO;
8333 printf("n\n");
8334 } else if (strcmp(line, "q") == 0 &&
8335 status == GOT_STATUS_MODIFY) {
8336 *choice = GOT_PATCH_CHOICE_QUIT;
8337 printf("q\n");
8338 } else
8339 printf("invalid response '%s'\n", line);
8340 free(line);
8341 return NULL;
8344 while (resp != 'y' && resp != 'n' && resp != 'q') {
8345 err = show_change(status, path, patch_file, n, nchanges,
8346 a->action);
8347 if (err)
8348 return err;
8349 resp = getchar();
8350 if (resp == '\n')
8351 resp = getchar();
8352 if (status == GOT_STATUS_MODIFY) {
8353 if (resp != 'y' && resp != 'n' && resp != 'q') {
8354 printf("invalid response '%c'\n", resp);
8355 resp = ' ';
8357 } else if (resp != 'y' && resp != 'n') {
8358 printf("invalid response '%c'\n", resp);
8359 resp = ' ';
8363 if (resp == 'y')
8364 *choice = GOT_PATCH_CHOICE_YES;
8365 else if (resp == 'n')
8366 *choice = GOT_PATCH_CHOICE_NO;
8367 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8368 *choice = GOT_PATCH_CHOICE_QUIT;
8370 return NULL;
8374 * Shortcut work tree status callback to determine if the set of
8375 * paths scanned has at least one versioned path that is modified.
8376 * Set arg and return GOT_ERR_FILE_MODIFIED as soon as a path is
8377 * passed with a status that is neither unchanged nor unversioned.
8379 static const struct got_error *
8380 worktree_has_changed_path(void *arg, unsigned char status,
8381 unsigned char staged_status, const char *path,
8382 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8383 struct got_object_id *commit_id, int dirfd, const char *de_name)
8385 int *has_changes = arg;
8387 if (status == staged_status && (status == GOT_STATUS_DELETE))
8388 status = GOT_STATUS_NO_CHANGE;
8390 if (!(status == GOT_STATUS_NO_CHANGE ||
8391 status == GOT_STATUS_UNVERSIONED) ||
8392 staged_status != GOT_STATUS_NO_CHANGE) {
8393 *has_changes = 1;
8394 return got_error(GOT_ERR_FILE_MODIFIED);
8397 return NULL;
8401 * Check that the changeset of the commit identified by id is
8402 * comprised of at least one path that is modified in the work tree.
8404 static const struct got_error *
8405 commit_path_changed_in_worktree(int *add_logmsg, struct got_object_id *id,
8406 struct got_worktree *worktree, struct got_repository *repo)
8408 const struct got_error *err;
8409 struct got_pathlist_head paths;
8410 struct got_commit_object *commit = NULL, *pcommit = NULL;
8411 struct got_tree_object *tree = NULL, *ptree = NULL;
8412 struct got_object_qid *pid;
8414 TAILQ_INIT(&paths);
8416 err = got_object_open_as_commit(&commit, repo, id);
8417 if (err)
8418 goto done;
8420 err = got_object_open_as_tree(&tree, repo,
8421 got_object_commit_get_tree_id(commit));
8422 if (err)
8423 goto done;
8425 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8426 if (pid != NULL) {
8427 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8428 if (err)
8429 goto done;
8431 err = got_object_open_as_tree(&ptree, repo,
8432 got_object_commit_get_tree_id(pcommit));
8433 if (err)
8434 goto done;
8437 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8438 got_diff_tree_collect_changed_paths, &paths, 0);
8439 if (err)
8440 goto done;
8442 err = got_worktree_status(worktree, &paths, repo, 0,
8443 worktree_has_changed_path, add_logmsg, check_cancelled, NULL);
8444 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8446 * At least one changed path in the referenced commit is
8447 * modified in the work tree, that's all we need to know!
8449 err = NULL;
8452 done:
8453 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8454 if (commit)
8455 got_object_commit_close(commit);
8456 if (pcommit)
8457 got_object_commit_close(pcommit);
8458 if (tree)
8459 got_object_tree_close(tree);
8460 if (ptree)
8461 got_object_tree_close(ptree);
8462 return err;
8466 * Remove any "logmsg" reference comprised entirely of paths that have
8467 * been reverted in this work tree. If any path in the logmsg ref changeset
8468 * remains in a changed state in the worktree, do not remove the reference.
8470 static const struct got_error *
8471 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8473 const struct got_error *err;
8474 struct got_reflist_head refs;
8475 struct got_reflist_entry *re;
8476 struct got_commit_object *commit = NULL;
8477 struct got_object_id *commit_id = NULL;
8478 char *uuidstr = NULL;
8480 TAILQ_INIT(&refs);
8482 err = got_worktree_get_uuid(&uuidstr, worktree);
8483 if (err)
8484 goto done;
8486 err = got_ref_list(&refs, repo, "refs/got/worktree",
8487 got_ref_cmp_by_name, repo);
8488 if (err)
8489 goto done;
8491 TAILQ_FOREACH(re, &refs, entry) {
8492 const char *refname;
8493 int has_changes = 0;
8495 refname = got_ref_get_name(re->ref);
8497 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8498 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8499 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8500 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8501 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8502 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8503 else
8504 continue;
8506 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8507 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8508 else
8509 continue;
8511 err = got_repo_match_object_id(&commit_id, NULL, refname,
8512 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8513 if (err)
8514 goto done;
8516 err = got_object_open_as_commit(&commit, repo, commit_id);
8517 if (err)
8518 goto done;
8520 err = commit_path_changed_in_worktree(&has_changes, commit_id,
8521 worktree, repo);
8522 if (err)
8523 goto done;
8525 if (!has_changes) {
8526 err = got_ref_delete(re->ref, repo);
8527 if (err)
8528 goto done;
8531 got_object_commit_close(commit);
8532 commit = NULL;
8533 free(commit_id);
8534 commit_id = NULL;
8537 done:
8538 free(uuidstr);
8539 free(commit_id);
8540 got_ref_list_free(&refs);
8541 if (commit)
8542 got_object_commit_close(commit);
8543 return err;
8546 static const struct got_error *
8547 cmd_revert(int argc, char *argv[])
8549 const struct got_error *error = NULL;
8550 struct got_worktree *worktree = NULL;
8551 struct got_repository *repo = NULL;
8552 char *cwd = NULL, *path = NULL;
8553 struct got_pathlist_head paths;
8554 struct got_pathlist_entry *pe;
8555 int ch, can_recurse = 0, pflag = 0;
8556 FILE *patch_script_file = NULL;
8557 const char *patch_script_path = NULL;
8558 struct choose_patch_arg cpa;
8559 int *pack_fds = NULL;
8561 TAILQ_INIT(&paths);
8563 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8564 switch (ch) {
8565 case 'F':
8566 patch_script_path = optarg;
8567 break;
8568 case 'p':
8569 pflag = 1;
8570 break;
8571 case 'R':
8572 can_recurse = 1;
8573 break;
8574 default:
8575 usage_revert();
8576 /* NOTREACHED */
8580 argc -= optind;
8581 argv += optind;
8583 #ifndef PROFILE
8584 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8585 "unveil", NULL) == -1)
8586 err(1, "pledge");
8587 #endif
8588 if (argc < 1)
8589 usage_revert();
8590 if (patch_script_path && !pflag)
8591 errx(1, "-F option can only be used together with -p option");
8593 cwd = getcwd(NULL, 0);
8594 if (cwd == NULL) {
8595 error = got_error_from_errno("getcwd");
8596 goto done;
8599 error = got_repo_pack_fds_open(&pack_fds);
8600 if (error != NULL)
8601 goto done;
8603 error = got_worktree_open(&worktree, cwd);
8604 if (error) {
8605 if (error->code == GOT_ERR_NOT_WORKTREE)
8606 error = wrap_not_worktree_error(error, "revert", cwd);
8607 goto done;
8610 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8611 NULL, pack_fds);
8612 if (error != NULL)
8613 goto done;
8615 if (patch_script_path) {
8616 patch_script_file = fopen(patch_script_path, "re");
8617 if (patch_script_file == NULL) {
8618 error = got_error_from_errno2("fopen",
8619 patch_script_path);
8620 goto done;
8625 * XXX "c" perm needed on repo dir to delete merge references.
8627 error = apply_unveil(got_repo_get_path(repo), 0,
8628 got_worktree_get_root_path(worktree));
8629 if (error)
8630 goto done;
8632 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8633 if (error)
8634 goto done;
8636 if (!can_recurse) {
8637 char *ondisk_path;
8638 struct stat sb;
8639 TAILQ_FOREACH(pe, &paths, entry) {
8640 if (asprintf(&ondisk_path, "%s/%s",
8641 got_worktree_get_root_path(worktree),
8642 pe->path) == -1) {
8643 error = got_error_from_errno("asprintf");
8644 goto done;
8646 if (lstat(ondisk_path, &sb) == -1) {
8647 if (errno == ENOENT) {
8648 free(ondisk_path);
8649 continue;
8651 error = got_error_from_errno2("lstat",
8652 ondisk_path);
8653 free(ondisk_path);
8654 goto done;
8656 free(ondisk_path);
8657 if (S_ISDIR(sb.st_mode)) {
8658 error = got_error_msg(GOT_ERR_BAD_PATH,
8659 "reverting directories requires -R option");
8660 goto done;
8665 cpa.patch_script_file = patch_script_file;
8666 cpa.action = "revert";
8667 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8668 pflag ? choose_patch : NULL, &cpa, repo);
8670 error = rm_logmsg_ref(worktree, repo);
8671 done:
8672 if (patch_script_file && fclose(patch_script_file) == EOF &&
8673 error == NULL)
8674 error = got_error_from_errno2("fclose", patch_script_path);
8675 if (repo) {
8676 const struct got_error *close_err = got_repo_close(repo);
8677 if (error == NULL)
8678 error = close_err;
8680 if (worktree)
8681 got_worktree_close(worktree);
8682 if (pack_fds) {
8683 const struct got_error *pack_err =
8684 got_repo_pack_fds_close(pack_fds);
8685 if (error == NULL)
8686 error = pack_err;
8688 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8689 free(path);
8690 free(cwd);
8691 return error;
8694 __dead static void
8695 usage_commit(void)
8697 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8698 "[-m message] [path ...]\n", getprogname());
8699 exit(1);
8702 struct collect_commit_logmsg_arg {
8703 const char *cmdline_log;
8704 const char *prepared_log;
8705 int non_interactive;
8706 const char *editor;
8707 const char *worktree_path;
8708 const char *branch_name;
8709 const char *repo_path;
8710 char *logmsg_path;
8714 static const struct got_error *
8715 read_prepared_logmsg(char **logmsg, const char *path)
8717 const struct got_error *err = NULL;
8718 FILE *f = NULL;
8719 struct stat sb;
8720 size_t r;
8722 *logmsg = NULL;
8723 memset(&sb, 0, sizeof(sb));
8725 f = fopen(path, "re");
8726 if (f == NULL)
8727 return got_error_from_errno2("fopen", path);
8729 if (fstat(fileno(f), &sb) == -1) {
8730 err = got_error_from_errno2("fstat", path);
8731 goto done;
8733 if (sb.st_size == 0) {
8734 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8735 goto done;
8738 *logmsg = malloc(sb.st_size + 1);
8739 if (*logmsg == NULL) {
8740 err = got_error_from_errno("malloc");
8741 goto done;
8744 r = fread(*logmsg, 1, sb.st_size, f);
8745 if (r != sb.st_size) {
8746 if (ferror(f))
8747 err = got_error_from_errno2("fread", path);
8748 else
8749 err = got_error(GOT_ERR_IO);
8750 goto done;
8752 (*logmsg)[sb.st_size] = '\0';
8753 done:
8754 if (fclose(f) == EOF && err == NULL)
8755 err = got_error_from_errno2("fclose", path);
8756 if (err) {
8757 free(*logmsg);
8758 *logmsg = NULL;
8760 return err;
8763 static const struct got_error *
8764 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8765 const char *diff_path, char **logmsg, void *arg)
8767 char *initial_content = NULL;
8768 struct got_pathlist_entry *pe;
8769 const struct got_error *err = NULL;
8770 char *template = NULL;
8771 struct collect_commit_logmsg_arg *a = arg;
8772 int initial_content_len;
8773 int fd = -1;
8774 size_t len;
8776 /* if a message was specified on the command line, just use it */
8777 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8778 len = strlen(a->cmdline_log) + 1;
8779 *logmsg = malloc(len + 1);
8780 if (*logmsg == NULL)
8781 return got_error_from_errno("malloc");
8782 strlcpy(*logmsg, a->cmdline_log, len);
8783 return NULL;
8784 } else if (a->prepared_log != NULL && a->non_interactive)
8785 return read_prepared_logmsg(logmsg, a->prepared_log);
8787 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8788 return got_error_from_errno("asprintf");
8790 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8791 if (err)
8792 goto done;
8794 if (a->prepared_log) {
8795 char *msg;
8796 err = read_prepared_logmsg(&msg, a->prepared_log);
8797 if (err)
8798 goto done;
8799 if (write(fd, msg, strlen(msg)) == -1) {
8800 err = got_error_from_errno2("write", a->logmsg_path);
8801 free(msg);
8802 goto done;
8804 free(msg);
8807 initial_content_len = asprintf(&initial_content,
8808 "\n# changes to be committed on branch %s:\n",
8809 a->branch_name);
8810 if (initial_content_len == -1) {
8811 err = got_error_from_errno("asprintf");
8812 goto done;
8815 if (write(fd, initial_content, initial_content_len) == -1) {
8816 err = got_error_from_errno2("write", a->logmsg_path);
8817 goto done;
8820 TAILQ_FOREACH(pe, commitable_paths, entry) {
8821 struct got_commitable *ct = pe->data;
8822 dprintf(fd, "# %c %s\n",
8823 got_commitable_get_status(ct),
8824 got_commitable_get_path(ct));
8827 if (diff_path) {
8828 dprintf(fd, "# detailed changes can be viewed in %s\n",
8829 diff_path);
8832 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8833 initial_content_len, a->prepared_log ? 0 : 1);
8834 done:
8835 free(initial_content);
8836 free(template);
8838 if (fd != -1 && close(fd) == -1 && err == NULL)
8839 err = got_error_from_errno2("close", a->logmsg_path);
8841 /* Editor is done; we can now apply unveil(2) */
8842 if (err == NULL)
8843 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8844 if (err) {
8845 free(*logmsg);
8846 *logmsg = NULL;
8848 return err;
8851 static const struct got_error *
8852 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8853 const char *type, int has_content)
8855 const struct got_error *err = NULL;
8856 char *logmsg = NULL;
8858 err = got_object_commit_get_logmsg(&logmsg, commit);
8859 if (err)
8860 return err;
8862 if (fprintf(f, "%s# log message of %s commit %s:%s",
8863 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8864 err = got_ferror(f, GOT_ERR_IO);
8866 free(logmsg);
8867 return err;
8871 * Lookup "logmsg" references of backed-out and cherrypicked commits
8872 * belonging to the current work tree. If found, and the worktree has
8873 * at least one modified file that was changed in the referenced commit,
8874 * add its log message to *logmsg. Add all refs found to matched_refs
8875 * to be scheduled for removal on successful commit.
8877 static const struct got_error *
8878 lookup_logmsg_ref(char **logmsg, struct got_reflist_head *matched_refs,
8879 struct got_worktree *worktree, struct got_repository *repo)
8881 const struct got_error *err;
8882 struct got_commit_object *commit = NULL;
8883 struct got_object_id *id = NULL;
8884 struct got_reflist_head refs;
8885 struct got_reflist_entry *re, *re_match;
8886 FILE *f = NULL;
8887 char *uuidstr = NULL;
8888 int added_logmsg = 0;
8890 TAILQ_INIT(&refs);
8892 err = got_opentemp_named(logmsg, &f, "got-commit-logmsg", "");
8893 if (err)
8894 goto done;
8896 err = got_worktree_get_uuid(&uuidstr, worktree);
8897 if (err)
8898 goto done;
8900 err = got_ref_list(&refs, repo, "refs/got/worktree",
8901 got_ref_cmp_by_name, repo);
8902 if (err)
8903 goto done;
8905 TAILQ_FOREACH(re, &refs, entry) {
8906 const char *refname, *type;
8907 int add_logmsg = 0;
8909 refname = got_ref_get_name(re->ref);
8911 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8912 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8913 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8914 type = "cherrypicked";
8915 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8916 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8917 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8918 type = "backed-out";
8919 } else
8920 continue;
8922 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8923 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8924 else
8925 continue;
8927 err = got_repo_match_object_id(&id, NULL, refname,
8928 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8929 if (err)
8930 goto done;
8932 err = got_object_open_as_commit(&commit, repo, id);
8933 if (err)
8934 goto done;
8936 err = commit_path_changed_in_worktree(&add_logmsg, id,
8937 worktree, repo);
8938 if (err)
8939 goto done;
8941 if (add_logmsg) {
8942 err = cat_logmsg(f, commit, refname, type,
8943 added_logmsg);
8944 if (err)
8945 goto done;
8946 if (!added_logmsg)
8947 ++added_logmsg;
8949 err = got_reflist_entry_dup(&re_match, re);
8950 if (err)
8951 goto done;
8952 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
8955 got_object_commit_close(commit);
8956 commit = NULL;
8957 free(id);
8958 id = NULL;
8961 done:
8962 free(id);
8963 free(uuidstr);
8964 got_ref_list_free(&refs);
8965 if (commit)
8966 got_object_commit_close(commit);
8967 if (f && fclose(f) == EOF && err == NULL)
8968 err = got_error_from_errno("fclose");
8969 if (!added_logmsg) {
8970 if (*logmsg && unlink(*logmsg) != 0 && err == NULL)
8971 err = got_error_from_errno2("unlink", *logmsg);
8972 *logmsg = NULL;
8974 return err;
8977 static const struct got_error *
8978 cmd_commit(int argc, char *argv[])
8980 const struct got_error *error = NULL;
8981 struct got_worktree *worktree = NULL;
8982 struct got_repository *repo = NULL;
8983 char *cwd = NULL, *id_str = NULL;
8984 struct got_object_id *id = NULL;
8985 const char *logmsg = NULL;
8986 char *prepared_logmsg = NULL;
8987 struct collect_commit_logmsg_arg cl_arg;
8988 const char *author = NULL;
8989 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8990 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8991 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8992 int show_diff = 1;
8993 struct got_pathlist_head paths;
8994 struct got_reflist_head refs;
8995 struct got_reflist_entry *re;
8996 int *pack_fds = NULL;
8998 TAILQ_INIT(&refs);
8999 TAILQ_INIT(&paths);
9000 cl_arg.logmsg_path = NULL;
9002 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9003 switch (ch) {
9004 case 'A':
9005 author = optarg;
9006 error = valid_author(author);
9007 if (error)
9008 return error;
9009 break;
9010 case 'F':
9011 if (logmsg != NULL)
9012 option_conflict('F', 'm');
9013 prepared_logmsg = realpath(optarg, NULL);
9014 if (prepared_logmsg == NULL)
9015 return got_error_from_errno2("realpath",
9016 optarg);
9017 break;
9018 case 'm':
9019 if (prepared_logmsg)
9020 option_conflict('m', 'F');
9021 logmsg = optarg;
9022 break;
9023 case 'N':
9024 non_interactive = 1;
9025 break;
9026 case 'n':
9027 show_diff = 0;
9028 break;
9029 case 'S':
9030 allow_bad_symlinks = 1;
9031 break;
9032 default:
9033 usage_commit();
9034 /* NOTREACHED */
9038 argc -= optind;
9039 argv += optind;
9041 #ifndef PROFILE
9042 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9043 "unveil", NULL) == -1)
9044 err(1, "pledge");
9045 #endif
9046 cwd = getcwd(NULL, 0);
9047 if (cwd == NULL) {
9048 error = got_error_from_errno("getcwd");
9049 goto done;
9052 error = got_repo_pack_fds_open(&pack_fds);
9053 if (error != NULL)
9054 goto done;
9056 error = got_worktree_open(&worktree, cwd);
9057 if (error) {
9058 if (error->code == GOT_ERR_NOT_WORKTREE)
9059 error = wrap_not_worktree_error(error, "commit", cwd);
9060 goto done;
9063 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9064 if (error)
9065 goto done;
9066 if (rebase_in_progress) {
9067 error = got_error(GOT_ERR_REBASING);
9068 goto done;
9071 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9072 worktree);
9073 if (error)
9074 goto done;
9076 error = get_gitconfig_path(&gitconfig_path);
9077 if (error)
9078 goto done;
9079 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9080 gitconfig_path, pack_fds);
9081 if (error != NULL)
9082 goto done;
9084 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9085 if (error)
9086 goto done;
9087 if (merge_in_progress) {
9088 error = got_error(GOT_ERR_MERGE_BUSY);
9089 goto done;
9092 error = get_author(&committer, repo, worktree);
9093 if (error)
9094 goto done;
9096 if (author != NULL && !strcmp(committer, author)) {
9097 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9098 goto done;
9101 if (author == NULL)
9102 author = committer;
9105 * unveil(2) traverses exec(2); if an editor is used we have
9106 * to apply unveil after the log message has been written.
9108 if (logmsg == NULL || strlen(logmsg) == 0)
9109 error = get_editor(&editor);
9110 else
9111 error = apply_unveil(got_repo_get_path(repo), 0,
9112 got_worktree_get_root_path(worktree));
9113 if (error)
9114 goto done;
9116 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9117 if (error)
9118 goto done;
9120 if (prepared_logmsg == NULL) {
9121 error = lookup_logmsg_ref(&prepared_logmsg, &refs,
9122 worktree, repo);
9123 if (error)
9124 goto done;
9127 cl_arg.editor = editor;
9128 cl_arg.cmdline_log = logmsg;
9129 cl_arg.prepared_log = prepared_logmsg;
9130 cl_arg.non_interactive = non_interactive;
9131 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9132 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9133 if (!histedit_in_progress) {
9134 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9135 error = got_error(GOT_ERR_COMMIT_BRANCH);
9136 goto done;
9138 cl_arg.branch_name += 11;
9140 cl_arg.repo_path = got_repo_get_path(repo);
9141 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9142 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9143 print_status, NULL, repo);
9144 if (error) {
9145 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9146 cl_arg.logmsg_path != NULL)
9147 preserve_logmsg = 1;
9148 goto done;
9151 error = got_object_id_str(&id_str, id);
9152 if (error)
9153 goto done;
9154 printf("Created commit %s\n", id_str);
9156 TAILQ_FOREACH(re, &refs, entry) {
9157 error = got_ref_delete(re->ref, repo);
9158 if (error)
9159 goto done;
9162 done:
9163 if (preserve_logmsg) {
9164 fprintf(stderr, "%s: log message preserved in %s\n",
9165 getprogname(), cl_arg.logmsg_path);
9166 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9167 error == NULL)
9168 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9169 free(cl_arg.logmsg_path);
9170 if (repo) {
9171 const struct got_error *close_err = got_repo_close(repo);
9172 if (error == NULL)
9173 error = close_err;
9175 if (worktree)
9176 got_worktree_close(worktree);
9177 if (pack_fds) {
9178 const struct got_error *pack_err =
9179 got_repo_pack_fds_close(pack_fds);
9180 if (error == NULL)
9181 error = pack_err;
9183 got_ref_list_free(&refs);
9184 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9185 free(cwd);
9186 free(id_str);
9187 free(gitconfig_path);
9188 free(editor);
9189 free(committer);
9190 free(prepared_logmsg);
9191 return error;
9194 __dead static void
9195 usage_send(void)
9197 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9198 "[-r repository-path] [-t tag] [remote-repository]\n",
9199 getprogname());
9200 exit(1);
9203 static void
9204 print_load_info(int print_colored, int print_found, int print_trees,
9205 int ncolored, int nfound, int ntrees)
9207 if (print_colored) {
9208 printf("%d commit%s colored", ncolored,
9209 ncolored == 1 ? "" : "s");
9211 if (print_found) {
9212 printf("%s%d object%s found",
9213 ncolored > 0 ? "; " : "",
9214 nfound, nfound == 1 ? "" : "s");
9216 if (print_trees) {
9217 printf("; %d tree%s scanned", ntrees,
9218 ntrees == 1 ? "" : "s");
9222 struct got_send_progress_arg {
9223 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9224 int verbosity;
9225 int last_ncolored;
9226 int last_nfound;
9227 int last_ntrees;
9228 int loading_done;
9229 int last_ncommits;
9230 int last_nobj_total;
9231 int last_p_deltify;
9232 int last_p_written;
9233 int last_p_sent;
9234 int printed_something;
9235 int sent_something;
9236 struct got_pathlist_head *delete_branches;
9239 static const struct got_error *
9240 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9241 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9242 int nobj_written, off_t bytes_sent, const char *refname,
9243 const char *errmsg, int success)
9245 struct got_send_progress_arg *a = arg;
9246 char scaled_packsize[FMT_SCALED_STRSIZE];
9247 char scaled_sent[FMT_SCALED_STRSIZE];
9248 int p_deltify = 0, p_written = 0, p_sent = 0;
9249 int print_colored = 0, print_found = 0, print_trees = 0;
9250 int print_searching = 0, print_total = 0;
9251 int print_deltify = 0, print_written = 0, print_sent = 0;
9253 if (a->verbosity < 0)
9254 return NULL;
9256 if (refname) {
9257 const char *status = success ? "accepted" : "rejected";
9259 if (success) {
9260 struct got_pathlist_entry *pe;
9261 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9262 const char *branchname = pe->path;
9263 if (got_path_cmp(branchname, refname,
9264 strlen(branchname), strlen(refname)) == 0) {
9265 status = "deleted";
9266 a->sent_something = 1;
9267 break;
9272 if (a->printed_something)
9273 putchar('\n');
9274 printf("Server has %s %s", status, refname);
9275 if (errmsg)
9276 printf(": %s", errmsg);
9277 a->printed_something = 1;
9278 return NULL;
9281 if (a->last_ncolored != ncolored) {
9282 print_colored = 1;
9283 a->last_ncolored = ncolored;
9286 if (a->last_nfound != nfound) {
9287 print_colored = 1;
9288 print_found = 1;
9289 a->last_nfound = nfound;
9292 if (a->last_ntrees != ntrees) {
9293 print_colored = 1;
9294 print_found = 1;
9295 print_trees = 1;
9296 a->last_ntrees = ntrees;
9299 if ((print_colored || print_found || print_trees) &&
9300 !a->loading_done) {
9301 printf("\r");
9302 print_load_info(print_colored, print_found, print_trees,
9303 ncolored, nfound, ntrees);
9304 a->printed_something = 1;
9305 fflush(stdout);
9306 return NULL;
9307 } else if (!a->loading_done) {
9308 printf("\r");
9309 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9310 printf("\n");
9311 a->loading_done = 1;
9314 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9315 return got_error_from_errno("fmt_scaled");
9316 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9317 return got_error_from_errno("fmt_scaled");
9319 if (a->last_ncommits != ncommits) {
9320 print_searching = 1;
9321 a->last_ncommits = ncommits;
9324 if (a->last_nobj_total != nobj_total) {
9325 print_searching = 1;
9326 print_total = 1;
9327 a->last_nobj_total = nobj_total;
9330 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9331 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9332 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9333 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9334 return got_error(GOT_ERR_NO_SPACE);
9337 if (nobj_deltify > 0 || nobj_written > 0) {
9338 if (nobj_deltify > 0) {
9339 p_deltify = (nobj_deltify * 100) / nobj_total;
9340 if (p_deltify != a->last_p_deltify) {
9341 a->last_p_deltify = p_deltify;
9342 print_searching = 1;
9343 print_total = 1;
9344 print_deltify = 1;
9347 if (nobj_written > 0) {
9348 p_written = (nobj_written * 100) / nobj_total;
9349 if (p_written != a->last_p_written) {
9350 a->last_p_written = p_written;
9351 print_searching = 1;
9352 print_total = 1;
9353 print_deltify = 1;
9354 print_written = 1;
9359 if (bytes_sent > 0) {
9360 p_sent = (bytes_sent * 100) / packfile_size;
9361 if (p_sent != a->last_p_sent) {
9362 a->last_p_sent = p_sent;
9363 print_searching = 1;
9364 print_total = 1;
9365 print_deltify = 1;
9366 print_written = 1;
9367 print_sent = 1;
9369 a->sent_something = 1;
9372 if (print_searching || print_total || print_deltify || print_written ||
9373 print_sent)
9374 printf("\r");
9375 if (print_searching)
9376 printf("packing %d reference%s", ncommits,
9377 ncommits == 1 ? "" : "s");
9378 if (print_total)
9379 printf("; %d object%s", nobj_total,
9380 nobj_total == 1 ? "" : "s");
9381 if (print_deltify)
9382 printf("; deltify: %d%%", p_deltify);
9383 if (print_sent)
9384 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9385 scaled_packsize, p_sent);
9386 else if (print_written)
9387 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9388 scaled_packsize, p_written);
9389 if (print_searching || print_total || print_deltify ||
9390 print_written || print_sent) {
9391 a->printed_something = 1;
9392 fflush(stdout);
9394 return NULL;
9397 static const struct got_error *
9398 cmd_send(int argc, char *argv[])
9400 const struct got_error *error = NULL;
9401 char *cwd = NULL, *repo_path = NULL;
9402 const char *remote_name;
9403 char *proto = NULL, *host = NULL, *port = NULL;
9404 char *repo_name = NULL, *server_path = NULL;
9405 const struct got_remote_repo *remotes, *remote = NULL;
9406 int nremotes, nbranches = 0, ndelete_branches = 0;
9407 struct got_repository *repo = NULL;
9408 struct got_worktree *worktree = NULL;
9409 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9410 struct got_pathlist_head branches;
9411 struct got_pathlist_head tags;
9412 struct got_reflist_head all_branches;
9413 struct got_reflist_head all_tags;
9414 struct got_pathlist_head delete_args;
9415 struct got_pathlist_head delete_branches;
9416 struct got_reflist_entry *re;
9417 struct got_pathlist_entry *pe;
9418 int i, ch, sendfd = -1, sendstatus;
9419 pid_t sendpid = -1;
9420 struct got_send_progress_arg spa;
9421 int verbosity = 0, overwrite_refs = 0;
9422 int send_all_branches = 0, send_all_tags = 0;
9423 struct got_reference *ref = NULL;
9424 int *pack_fds = NULL;
9426 TAILQ_INIT(&branches);
9427 TAILQ_INIT(&tags);
9428 TAILQ_INIT(&all_branches);
9429 TAILQ_INIT(&all_tags);
9430 TAILQ_INIT(&delete_args);
9431 TAILQ_INIT(&delete_branches);
9433 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9434 switch (ch) {
9435 case 'a':
9436 send_all_branches = 1;
9437 break;
9438 case 'b':
9439 error = got_pathlist_append(&branches, optarg, NULL);
9440 if (error)
9441 return error;
9442 nbranches++;
9443 break;
9444 case 'd':
9445 error = got_pathlist_append(&delete_args, optarg, NULL);
9446 if (error)
9447 return error;
9448 break;
9449 case 'f':
9450 overwrite_refs = 1;
9451 break;
9452 case 'q':
9453 verbosity = -1;
9454 break;
9455 case 'r':
9456 repo_path = realpath(optarg, NULL);
9457 if (repo_path == NULL)
9458 return got_error_from_errno2("realpath",
9459 optarg);
9460 got_path_strip_trailing_slashes(repo_path);
9461 break;
9462 case 'T':
9463 send_all_tags = 1;
9464 break;
9465 case 't':
9466 error = got_pathlist_append(&tags, optarg, NULL);
9467 if (error)
9468 return error;
9469 break;
9470 case 'v':
9471 if (verbosity < 0)
9472 verbosity = 0;
9473 else if (verbosity < 3)
9474 verbosity++;
9475 break;
9476 default:
9477 usage_send();
9478 /* NOTREACHED */
9481 argc -= optind;
9482 argv += optind;
9484 if (send_all_branches && !TAILQ_EMPTY(&branches))
9485 option_conflict('a', 'b');
9486 if (send_all_tags && !TAILQ_EMPTY(&tags))
9487 option_conflict('T', 't');
9490 if (argc == 0)
9491 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9492 else if (argc == 1)
9493 remote_name = argv[0];
9494 else
9495 usage_send();
9497 cwd = getcwd(NULL, 0);
9498 if (cwd == NULL) {
9499 error = got_error_from_errno("getcwd");
9500 goto done;
9503 error = got_repo_pack_fds_open(&pack_fds);
9504 if (error != NULL)
9505 goto done;
9507 if (repo_path == NULL) {
9508 error = got_worktree_open(&worktree, cwd);
9509 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9510 goto done;
9511 else
9512 error = NULL;
9513 if (worktree) {
9514 repo_path =
9515 strdup(got_worktree_get_repo_path(worktree));
9516 if (repo_path == NULL)
9517 error = got_error_from_errno("strdup");
9518 if (error)
9519 goto done;
9520 } else {
9521 repo_path = strdup(cwd);
9522 if (repo_path == NULL) {
9523 error = got_error_from_errno("strdup");
9524 goto done;
9529 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9530 if (error)
9531 goto done;
9533 if (worktree) {
9534 worktree_conf = got_worktree_get_gotconfig(worktree);
9535 if (worktree_conf) {
9536 got_gotconfig_get_remotes(&nremotes, &remotes,
9537 worktree_conf);
9538 for (i = 0; i < nremotes; i++) {
9539 if (strcmp(remotes[i].name, remote_name) == 0) {
9540 remote = &remotes[i];
9541 break;
9546 if (remote == NULL) {
9547 repo_conf = got_repo_get_gotconfig(repo);
9548 if (repo_conf) {
9549 got_gotconfig_get_remotes(&nremotes, &remotes,
9550 repo_conf);
9551 for (i = 0; i < nremotes; i++) {
9552 if (strcmp(remotes[i].name, remote_name) == 0) {
9553 remote = &remotes[i];
9554 break;
9559 if (remote == NULL) {
9560 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9561 for (i = 0; i < nremotes; i++) {
9562 if (strcmp(remotes[i].name, remote_name) == 0) {
9563 remote = &remotes[i];
9564 break;
9568 if (remote == NULL) {
9569 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9570 goto done;
9573 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9574 &repo_name, remote->send_url);
9575 if (error)
9576 goto done;
9578 if (strcmp(proto, "git") == 0) {
9579 #ifndef PROFILE
9580 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9581 "sendfd dns inet unveil", NULL) == -1)
9582 err(1, "pledge");
9583 #endif
9584 } else if (strcmp(proto, "git+ssh") == 0 ||
9585 strcmp(proto, "ssh") == 0) {
9586 #ifndef PROFILE
9587 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9588 "sendfd unveil", NULL) == -1)
9589 err(1, "pledge");
9590 #endif
9591 } else if (strcmp(proto, "http") == 0 ||
9592 strcmp(proto, "git+http") == 0) {
9593 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9594 goto done;
9595 } else {
9596 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9597 goto done;
9600 error = got_dial_apply_unveil(proto);
9601 if (error)
9602 goto done;
9604 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9605 if (error)
9606 goto done;
9608 if (send_all_branches) {
9609 error = got_ref_list(&all_branches, repo, "refs/heads",
9610 got_ref_cmp_by_name, NULL);
9611 if (error)
9612 goto done;
9613 TAILQ_FOREACH(re, &all_branches, entry) {
9614 const char *branchname = got_ref_get_name(re->ref);
9615 error = got_pathlist_append(&branches,
9616 branchname, NULL);
9617 if (error)
9618 goto done;
9619 nbranches++;
9621 } else if (nbranches == 0) {
9622 for (i = 0; i < remote->nsend_branches; i++) {
9623 error = got_pathlist_append(&branches,
9624 remote->send_branches[i], NULL);
9625 if (error)
9626 goto done;
9630 if (send_all_tags) {
9631 error = got_ref_list(&all_tags, repo, "refs/tags",
9632 got_ref_cmp_by_name, NULL);
9633 if (error)
9634 goto done;
9635 TAILQ_FOREACH(re, &all_tags, entry) {
9636 const char *tagname = got_ref_get_name(re->ref);
9637 error = got_pathlist_append(&tags,
9638 tagname, NULL);
9639 if (error)
9640 goto done;
9645 * To prevent accidents only branches in refs/heads/ can be deleted
9646 * with 'got send -d'.
9647 * Deleting anything else requires local repository access or Git.
9649 TAILQ_FOREACH(pe, &delete_args, entry) {
9650 const char *branchname = pe->path;
9651 char *s;
9652 struct got_pathlist_entry *new;
9653 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9654 s = strdup(branchname);
9655 if (s == NULL) {
9656 error = got_error_from_errno("strdup");
9657 goto done;
9659 } else {
9660 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9661 error = got_error_from_errno("asprintf");
9662 goto done;
9665 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9666 if (error || new == NULL /* duplicate */)
9667 free(s);
9668 if (error)
9669 goto done;
9670 ndelete_branches++;
9673 if (nbranches == 0 && ndelete_branches == 0) {
9674 struct got_reference *head_ref;
9675 if (worktree)
9676 error = got_ref_open(&head_ref, repo,
9677 got_worktree_get_head_ref_name(worktree), 0);
9678 else
9679 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9680 if (error)
9681 goto done;
9682 if (got_ref_is_symbolic(head_ref)) {
9683 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9684 got_ref_close(head_ref);
9685 if (error)
9686 goto done;
9687 } else
9688 ref = head_ref;
9689 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9690 NULL);
9691 if (error)
9692 goto done;
9693 nbranches++;
9696 if (verbosity >= 0) {
9697 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9698 remote->name, proto, host,
9699 port ? ":" : "", port ? port : "",
9700 *server_path == '/' ? "" : "/", server_path);
9703 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9704 server_path, verbosity);
9705 if (error)
9706 goto done;
9708 memset(&spa, 0, sizeof(spa));
9709 spa.last_scaled_packsize[0] = '\0';
9710 spa.last_p_deltify = -1;
9711 spa.last_p_written = -1;
9712 spa.verbosity = verbosity;
9713 spa.delete_branches = &delete_branches;
9714 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9715 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9716 check_cancelled, NULL);
9717 if (spa.printed_something)
9718 putchar('\n');
9719 if (error)
9720 goto done;
9721 if (!spa.sent_something && verbosity >= 0)
9722 printf("Already up-to-date\n");
9723 done:
9724 if (sendpid > 0) {
9725 if (kill(sendpid, SIGTERM) == -1)
9726 error = got_error_from_errno("kill");
9727 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9728 error = got_error_from_errno("waitpid");
9730 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9731 error = got_error_from_errno("close");
9732 if (repo) {
9733 const struct got_error *close_err = got_repo_close(repo);
9734 if (error == NULL)
9735 error = close_err;
9737 if (worktree)
9738 got_worktree_close(worktree);
9739 if (pack_fds) {
9740 const struct got_error *pack_err =
9741 got_repo_pack_fds_close(pack_fds);
9742 if (error == NULL)
9743 error = pack_err;
9745 if (ref)
9746 got_ref_close(ref);
9747 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9748 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9749 got_ref_list_free(&all_branches);
9750 got_ref_list_free(&all_tags);
9751 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9752 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9753 free(cwd);
9754 free(repo_path);
9755 free(proto);
9756 free(host);
9757 free(port);
9758 free(server_path);
9759 free(repo_name);
9760 return error;
9764 * Print and if delete is set delete all ref_prefix references.
9765 * If wanted_ref is not NULL, only print or delete this reference.
9767 static const struct got_error *
9768 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9769 const char *wanted_ref, int delete, struct got_worktree *worktree,
9770 struct got_repository *repo)
9772 const struct got_error *err;
9773 struct got_pathlist_head paths;
9774 struct got_reflist_head refs;
9775 struct got_reflist_entry *re;
9776 struct got_reflist_object_id_map *refs_idmap = NULL;
9777 struct got_commit_object *commit = NULL;
9778 struct got_object_id *id = NULL;
9779 char *uuidstr = NULL;
9780 int found = 0;
9782 TAILQ_INIT(&refs);
9783 TAILQ_INIT(&paths);
9785 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9786 if (err)
9787 goto done;
9789 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9790 if (err)
9791 goto done;
9793 if (worktree != NULL) {
9794 err = got_worktree_get_uuid(&uuidstr, worktree);
9795 if (err)
9796 goto done;
9799 if (wanted_ref) {
9800 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9801 wanted_ref += 11;
9804 TAILQ_FOREACH(re, &refs, entry) {
9805 const char *refname;
9807 refname = got_ref_get_name(re->ref);
9809 err = check_cancelled(NULL);
9810 if (err)
9811 goto done;
9813 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9814 refname += prefix_len + 1; /* skip '-' delimiter */
9815 else
9816 continue;
9818 if (worktree == NULL || strncmp(refname, uuidstr,
9819 GOT_WORKTREE_UUID_STRLEN) == 0)
9820 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9821 else
9822 continue;
9824 err = got_repo_match_object_id(&id, NULL, refname,
9825 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9826 if (err)
9827 goto done;
9829 err = got_object_open_as_commit(&commit, repo, id);
9830 if (err)
9831 goto done;
9833 if (wanted_ref)
9834 found = strncmp(wanted_ref, refname,
9835 strlen(wanted_ref)) == 0;
9836 if (wanted_ref && !found) {
9837 struct got_reflist_head *ci_refs;
9839 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9840 id);
9842 if (ci_refs) {
9843 char *refs_str = NULL;
9844 char const *r = NULL;
9846 err = build_refs_str(&refs_str, ci_refs, id,
9847 repo, 1);
9848 if (err)
9849 goto done;
9851 r = refs_str;
9852 while (r) {
9853 if (strncmp(r, wanted_ref,
9854 strlen(wanted_ref)) == 0) {
9855 found = 1;
9856 break;
9858 r = strchr(r, ' ');
9859 if (r)
9860 ++r;
9862 free(refs_str);
9866 if (wanted_ref == NULL || found) {
9867 if (delete) {
9868 err = got_ref_delete(re->ref, repo);
9869 if (err)
9870 goto done;
9871 printf("deleted: ");
9872 err = print_commit_oneline(commit, id, repo,
9873 refs_idmap);
9874 } else {
9876 * Print paths modified by commit to help
9877 * associate commits with worktree changes.
9879 err = get_changed_paths(&paths, commit,
9880 repo, NULL);
9881 if (err)
9882 goto done;
9884 err = print_commit(commit, id, repo, NULL,
9885 &paths, NULL, 0, 0, refs_idmap, NULL);
9886 got_pathlist_free(&paths,
9887 GOT_PATHLIST_FREE_ALL);
9889 if (err || found)
9890 goto done;
9893 got_object_commit_close(commit);
9894 commit = NULL;
9895 free(id);
9896 id = NULL;
9899 if (wanted_ref != NULL && !found)
9900 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9902 done:
9903 free(id);
9904 free(uuidstr);
9905 got_ref_list_free(&refs);
9906 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9907 if (refs_idmap)
9908 got_reflist_object_id_map_free(refs_idmap);
9909 if (commit)
9910 got_object_commit_close(commit);
9911 return err;
9915 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9916 * identified by id for log messages to prepopulate the editor on commit.
9918 static const struct got_error *
9919 logmsg_ref(struct got_object_id *id, const char *prefix,
9920 struct got_worktree *worktree, struct got_repository *repo)
9922 const struct got_error *err = NULL;
9923 char *idstr, *ref = NULL, *refname = NULL;
9924 int histedit_in_progress;
9925 int rebase_in_progress, merge_in_progress;
9928 * Silenty refuse to create merge reference if any histedit, merge,
9929 * or rebase operation is in progress.
9931 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9932 worktree);
9933 if (err)
9934 return err;
9935 if (histedit_in_progress)
9936 return NULL;
9938 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9939 if (err)
9940 return err;
9941 if (rebase_in_progress)
9942 return NULL;
9944 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
9945 repo);
9946 if (err)
9947 return err;
9948 if (merge_in_progress)
9949 return NULL;
9951 err = got_object_id_str(&idstr, id);
9952 if (err)
9953 return err;
9955 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
9956 if (err)
9957 goto done;
9959 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
9960 err = got_error_from_errno("asprintf");
9961 goto done;
9964 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
9965 -1, repo);
9966 done:
9967 free(ref);
9968 free(idstr);
9969 free(refname);
9970 return err;
9973 __dead static void
9974 usage_cherrypick(void)
9976 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
9977 getprogname());
9978 exit(1);
9981 static const struct got_error *
9982 cmd_cherrypick(int argc, char *argv[])
9984 const struct got_error *error = NULL;
9985 struct got_worktree *worktree = NULL;
9986 struct got_repository *repo = NULL;
9987 char *cwd = NULL, *commit_id_str = NULL;
9988 struct got_object_id *commit_id = NULL;
9989 struct got_commit_object *commit = NULL;
9990 struct got_object_qid *pid;
9991 int ch, list_refs = 0, remove_refs = 0;
9992 struct got_update_progress_arg upa;
9993 int *pack_fds = NULL;
9995 while ((ch = getopt(argc, argv, "lX")) != -1) {
9996 switch (ch) {
9997 case 'l':
9998 list_refs = 1;
9999 break;
10000 case 'X':
10001 remove_refs = 1;
10002 break;
10003 default:
10004 usage_cherrypick();
10005 /* NOTREACHED */
10009 argc -= optind;
10010 argv += optind;
10012 #ifndef PROFILE
10013 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10014 "unveil", NULL) == -1)
10015 err(1, "pledge");
10016 #endif
10017 if (list_refs || remove_refs) {
10018 if (argc != 0 && argc != 1)
10019 usage_cherrypick();
10020 } else if (argc != 1)
10021 usage_cherrypick();
10022 if (list_refs && remove_refs)
10023 option_conflict('l', 'X');
10025 cwd = getcwd(NULL, 0);
10026 if (cwd == NULL) {
10027 error = got_error_from_errno("getcwd");
10028 goto done;
10031 error = got_repo_pack_fds_open(&pack_fds);
10032 if (error != NULL)
10033 goto done;
10035 error = got_worktree_open(&worktree, cwd);
10036 if (error) {
10037 if (list_refs || remove_refs) {
10038 if (error->code != GOT_ERR_NOT_WORKTREE)
10039 goto done;
10040 } else {
10041 if (error->code == GOT_ERR_NOT_WORKTREE)
10042 error = wrap_not_worktree_error(error,
10043 "cherrypick", cwd);
10044 goto done;
10048 error = got_repo_open(&repo,
10049 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10050 NULL, pack_fds);
10051 if (error != NULL)
10052 goto done;
10054 error = apply_unveil(got_repo_get_path(repo), 0,
10055 worktree ? got_worktree_get_root_path(worktree) : NULL);
10056 if (error)
10057 goto done;
10059 if (list_refs || remove_refs) {
10060 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10061 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10062 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10063 goto done;
10066 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10067 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10068 if (error)
10069 goto done;
10070 error = got_object_id_str(&commit_id_str, commit_id);
10071 if (error)
10072 goto done;
10074 error = got_object_open_as_commit(&commit, repo, commit_id);
10075 if (error)
10076 goto done;
10077 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10078 memset(&upa, 0, sizeof(upa));
10079 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10080 commit_id, repo, update_progress, &upa, check_cancelled,
10081 NULL);
10082 if (error != NULL)
10083 goto done;
10085 if (upa.did_something) {
10086 error = logmsg_ref(commit_id,
10087 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10088 if (error)
10089 goto done;
10090 printf("Merged commit %s\n", commit_id_str);
10092 print_merge_progress_stats(&upa);
10093 done:
10094 if (commit)
10095 got_object_commit_close(commit);
10096 free(commit_id_str);
10097 if (worktree)
10098 got_worktree_close(worktree);
10099 if (repo) {
10100 const struct got_error *close_err = got_repo_close(repo);
10101 if (error == NULL)
10102 error = close_err;
10104 if (pack_fds) {
10105 const struct got_error *pack_err =
10106 got_repo_pack_fds_close(pack_fds);
10107 if (error == NULL)
10108 error = pack_err;
10111 return error;
10114 __dead static void
10115 usage_backout(void)
10117 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10118 exit(1);
10121 static const struct got_error *
10122 cmd_backout(int argc, char *argv[])
10124 const struct got_error *error = NULL;
10125 struct got_worktree *worktree = NULL;
10126 struct got_repository *repo = NULL;
10127 char *cwd = NULL, *commit_id_str = NULL;
10128 struct got_object_id *commit_id = NULL;
10129 struct got_commit_object *commit = NULL;
10130 struct got_object_qid *pid;
10131 int ch, list_refs = 0, remove_refs = 0;
10132 struct got_update_progress_arg upa;
10133 int *pack_fds = NULL;
10135 while ((ch = getopt(argc, argv, "lX")) != -1) {
10136 switch (ch) {
10137 case 'l':
10138 list_refs = 1;
10139 break;
10140 case 'X':
10141 remove_refs = 1;
10142 break;
10143 default:
10144 usage_backout();
10145 /* NOTREACHED */
10149 argc -= optind;
10150 argv += optind;
10152 #ifndef PROFILE
10153 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10154 "unveil", NULL) == -1)
10155 err(1, "pledge");
10156 #endif
10157 if (list_refs || remove_refs) {
10158 if (argc != 0 && argc != 1)
10159 usage_backout();
10160 } else if (argc != 1)
10161 usage_backout();
10162 if (list_refs && remove_refs)
10163 option_conflict('l', 'X');
10165 cwd = getcwd(NULL, 0);
10166 if (cwd == NULL) {
10167 error = got_error_from_errno("getcwd");
10168 goto done;
10171 error = got_repo_pack_fds_open(&pack_fds);
10172 if (error != NULL)
10173 goto done;
10175 error = got_worktree_open(&worktree, cwd);
10176 if (error) {
10177 if (list_refs || remove_refs) {
10178 if (error->code != GOT_ERR_NOT_WORKTREE)
10179 goto done;
10180 } else {
10181 if (error->code == GOT_ERR_NOT_WORKTREE)
10182 error = wrap_not_worktree_error(error,
10183 "backout", cwd);
10184 goto done;
10188 error = got_repo_open(&repo,
10189 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10190 NULL, pack_fds);
10191 if (error != NULL)
10192 goto done;
10194 error = apply_unveil(got_repo_get_path(repo), 0,
10195 worktree ? got_worktree_get_root_path(worktree) : NULL);
10196 if (error)
10197 goto done;
10199 if (list_refs || remove_refs) {
10200 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10201 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10202 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10203 goto done;
10206 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10207 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10208 if (error)
10209 goto done;
10210 error = got_object_id_str(&commit_id_str, commit_id);
10211 if (error)
10212 goto done;
10214 error = got_object_open_as_commit(&commit, repo, commit_id);
10215 if (error)
10216 goto done;
10217 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10218 if (pid == NULL) {
10219 error = got_error(GOT_ERR_ROOT_COMMIT);
10220 goto done;
10223 memset(&upa, 0, sizeof(upa));
10224 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10225 repo, update_progress, &upa, check_cancelled, NULL);
10226 if (error != NULL)
10227 goto done;
10229 if (upa.did_something) {
10230 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10231 worktree, repo);
10232 if (error)
10233 goto done;
10234 printf("Backed out commit %s\n", commit_id_str);
10236 print_merge_progress_stats(&upa);
10237 done:
10238 if (commit)
10239 got_object_commit_close(commit);
10240 free(commit_id_str);
10241 if (worktree)
10242 got_worktree_close(worktree);
10243 if (repo) {
10244 const struct got_error *close_err = got_repo_close(repo);
10245 if (error == NULL)
10246 error = close_err;
10248 if (pack_fds) {
10249 const struct got_error *pack_err =
10250 got_repo_pack_fds_close(pack_fds);
10251 if (error == NULL)
10252 error = pack_err;
10254 return error;
10257 __dead static void
10258 usage_rebase(void)
10260 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10261 exit(1);
10264 static void
10265 trim_logmsg(char *logmsg, int limit)
10267 char *nl;
10268 size_t len;
10270 len = strlen(logmsg);
10271 if (len > limit)
10272 len = limit;
10273 logmsg[len] = '\0';
10274 nl = strchr(logmsg, '\n');
10275 if (nl)
10276 *nl = '\0';
10279 static const struct got_error *
10280 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10282 const struct got_error *err;
10283 char *logmsg0 = NULL;
10284 const char *s;
10286 err = got_object_commit_get_logmsg(&logmsg0, commit);
10287 if (err)
10288 return err;
10290 s = logmsg0;
10291 while (isspace((unsigned char)s[0]))
10292 s++;
10294 *logmsg = strdup(s);
10295 if (*logmsg == NULL) {
10296 err = got_error_from_errno("strdup");
10297 goto done;
10300 trim_logmsg(*logmsg, limit);
10301 done:
10302 free(logmsg0);
10303 return err;
10306 static const struct got_error *
10307 show_rebase_merge_conflict(struct got_object_id *id,
10308 struct got_repository *repo)
10310 const struct got_error *err;
10311 struct got_commit_object *commit = NULL;
10312 char *id_str = NULL, *logmsg = NULL;
10314 err = got_object_open_as_commit(&commit, repo, id);
10315 if (err)
10316 return err;
10318 err = got_object_id_str(&id_str, id);
10319 if (err)
10320 goto done;
10322 id_str[12] = '\0';
10324 err = get_short_logmsg(&logmsg, 42, commit);
10325 if (err)
10326 goto done;
10328 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10329 done:
10330 free(id_str);
10331 got_object_commit_close(commit);
10332 free(logmsg);
10333 return err;
10336 static const struct got_error *
10337 show_rebase_progress(struct got_commit_object *commit,
10338 struct got_object_id *old_id, struct got_object_id *new_id)
10340 const struct got_error *err;
10341 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10343 err = got_object_id_str(&old_id_str, old_id);
10344 if (err)
10345 goto done;
10347 if (new_id) {
10348 err = got_object_id_str(&new_id_str, new_id);
10349 if (err)
10350 goto done;
10353 old_id_str[12] = '\0';
10354 if (new_id_str)
10355 new_id_str[12] = '\0';
10357 err = get_short_logmsg(&logmsg, 42, commit);
10358 if (err)
10359 goto done;
10361 printf("%s -> %s: %s\n", old_id_str,
10362 new_id_str ? new_id_str : "no-op change", logmsg);
10363 done:
10364 free(old_id_str);
10365 free(new_id_str);
10366 free(logmsg);
10367 return err;
10370 static const struct got_error *
10371 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10372 struct got_reference *branch, struct got_reference *new_base_branch,
10373 struct got_reference *tmp_branch, struct got_repository *repo,
10374 int create_backup)
10376 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10377 return got_worktree_rebase_complete(worktree, fileindex,
10378 new_base_branch, tmp_branch, branch, repo, create_backup);
10381 static const struct got_error *
10382 rebase_commit(struct got_pathlist_head *merged_paths,
10383 struct got_worktree *worktree, struct got_fileindex *fileindex,
10384 struct got_reference *tmp_branch, const char *committer,
10385 struct got_object_id *commit_id, struct got_repository *repo)
10387 const struct got_error *error;
10388 struct got_commit_object *commit;
10389 struct got_object_id *new_commit_id;
10391 error = got_object_open_as_commit(&commit, repo, commit_id);
10392 if (error)
10393 return error;
10395 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10396 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10397 repo);
10398 if (error) {
10399 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10400 goto done;
10401 error = show_rebase_progress(commit, commit_id, NULL);
10402 } else {
10403 error = show_rebase_progress(commit, commit_id, new_commit_id);
10404 free(new_commit_id);
10406 done:
10407 got_object_commit_close(commit);
10408 return error;
10411 struct check_path_prefix_arg {
10412 const char *path_prefix;
10413 size_t len;
10414 int errcode;
10417 static const struct got_error *
10418 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10419 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10420 struct got_object_id *id1, struct got_object_id *id2,
10421 const char *path1, const char *path2,
10422 mode_t mode1, mode_t mode2, struct got_repository *repo)
10424 struct check_path_prefix_arg *a = arg;
10426 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10427 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10428 return got_error(a->errcode);
10430 return NULL;
10433 static const struct got_error *
10434 check_path_prefix(struct got_object_id *parent_id,
10435 struct got_object_id *commit_id, const char *path_prefix,
10436 int errcode, struct got_repository *repo)
10438 const struct got_error *err;
10439 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10440 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10441 struct check_path_prefix_arg cpp_arg;
10443 if (got_path_is_root_dir(path_prefix))
10444 return NULL;
10446 err = got_object_open_as_commit(&commit, repo, commit_id);
10447 if (err)
10448 goto done;
10450 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10451 if (err)
10452 goto done;
10454 err = got_object_open_as_tree(&tree1, repo,
10455 got_object_commit_get_tree_id(parent_commit));
10456 if (err)
10457 goto done;
10459 err = got_object_open_as_tree(&tree2, repo,
10460 got_object_commit_get_tree_id(commit));
10461 if (err)
10462 goto done;
10464 cpp_arg.path_prefix = path_prefix;
10465 while (cpp_arg.path_prefix[0] == '/')
10466 cpp_arg.path_prefix++;
10467 cpp_arg.len = strlen(cpp_arg.path_prefix);
10468 cpp_arg.errcode = errcode;
10469 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10470 check_path_prefix_in_diff, &cpp_arg, 0);
10471 done:
10472 if (tree1)
10473 got_object_tree_close(tree1);
10474 if (tree2)
10475 got_object_tree_close(tree2);
10476 if (commit)
10477 got_object_commit_close(commit);
10478 if (parent_commit)
10479 got_object_commit_close(parent_commit);
10480 return err;
10483 static const struct got_error *
10484 collect_commits(struct got_object_id_queue *commits,
10485 struct got_object_id *initial_commit_id,
10486 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10487 const char *path_prefix, int path_prefix_errcode,
10488 struct got_repository *repo)
10490 const struct got_error *err = NULL;
10491 struct got_commit_graph *graph = NULL;
10492 struct got_object_id parent_id, commit_id;
10493 struct got_object_qid *qid;
10495 err = got_commit_graph_open(&graph, "/", 1);
10496 if (err)
10497 return err;
10499 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10500 check_cancelled, NULL);
10501 if (err)
10502 goto done;
10504 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10505 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10506 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10507 check_cancelled, NULL);
10508 if (err) {
10509 if (err->code == GOT_ERR_ITER_COMPLETED) {
10510 err = got_error_msg(GOT_ERR_ANCESTRY,
10511 "ran out of commits to rebase before "
10512 "youngest common ancestor commit has "
10513 "been reached?!?");
10515 goto done;
10516 } else {
10517 err = check_path_prefix(&parent_id, &commit_id,
10518 path_prefix, path_prefix_errcode, repo);
10519 if (err)
10520 goto done;
10522 err = got_object_qid_alloc(&qid, &commit_id);
10523 if (err)
10524 goto done;
10525 STAILQ_INSERT_HEAD(commits, qid, entry);
10527 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10530 done:
10531 got_commit_graph_close(graph);
10532 return err;
10535 static const struct got_error *
10536 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10538 const struct got_error *err = NULL;
10539 time_t committer_time;
10540 struct tm tm;
10541 char datebuf[11]; /* YYYY-MM-DD + NUL */
10542 char *author0 = NULL, *author, *smallerthan;
10543 char *logmsg0 = NULL, *logmsg, *newline;
10545 committer_time = got_object_commit_get_committer_time(commit);
10546 if (gmtime_r(&committer_time, &tm) == NULL)
10547 return got_error_from_errno("gmtime_r");
10548 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10549 return got_error(GOT_ERR_NO_SPACE);
10551 author0 = strdup(got_object_commit_get_author(commit));
10552 if (author0 == NULL)
10553 return got_error_from_errno("strdup");
10554 author = author0;
10555 smallerthan = strchr(author, '<');
10556 if (smallerthan && smallerthan[1] != '\0')
10557 author = smallerthan + 1;
10558 author[strcspn(author, "@>")] = '\0';
10560 err = got_object_commit_get_logmsg(&logmsg0, commit);
10561 if (err)
10562 goto done;
10563 logmsg = logmsg0;
10564 while (*logmsg == '\n')
10565 logmsg++;
10566 newline = strchr(logmsg, '\n');
10567 if (newline)
10568 *newline = '\0';
10570 if (asprintf(brief_str, "%s %s %s",
10571 datebuf, author, logmsg) == -1)
10572 err = got_error_from_errno("asprintf");
10573 done:
10574 free(author0);
10575 free(logmsg0);
10576 return err;
10579 static const struct got_error *
10580 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10581 struct got_repository *repo)
10583 const struct got_error *err;
10584 char *id_str;
10586 err = got_object_id_str(&id_str, id);
10587 if (err)
10588 return err;
10590 err = got_ref_delete(ref, repo);
10591 if (err)
10592 goto done;
10594 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10595 done:
10596 free(id_str);
10597 return err;
10600 static const struct got_error *
10601 print_backup_ref(const char *branch_name, const char *new_id_str,
10602 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10603 struct got_reflist_object_id_map *refs_idmap,
10604 struct got_repository *repo)
10606 const struct got_error *err = NULL;
10607 struct got_reflist_head *refs;
10608 char *refs_str = NULL;
10609 struct got_object_id *new_commit_id = NULL;
10610 struct got_commit_object *new_commit = NULL;
10611 char *new_commit_brief_str = NULL;
10612 struct got_object_id *yca_id = NULL;
10613 struct got_commit_object *yca_commit = NULL;
10614 char *yca_id_str = NULL, *yca_brief_str = NULL;
10615 char *custom_refs_str;
10617 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10618 return got_error_from_errno("asprintf");
10620 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10621 0, 0, refs_idmap, custom_refs_str);
10622 if (err)
10623 goto done;
10625 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10626 if (err)
10627 goto done;
10629 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10630 if (refs) {
10631 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10632 if (err)
10633 goto done;
10636 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10637 if (err)
10638 goto done;
10640 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10641 if (err)
10642 goto done;
10644 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10645 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10646 if (err)
10647 goto done;
10649 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10650 refs_str ? " (" : "", refs_str ? refs_str : "",
10651 refs_str ? ")" : "", new_commit_brief_str);
10652 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10653 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10654 free(refs_str);
10655 refs_str = NULL;
10657 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10658 if (err)
10659 goto done;
10661 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10662 if (err)
10663 goto done;
10665 err = got_object_id_str(&yca_id_str, yca_id);
10666 if (err)
10667 goto done;
10669 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10670 if (refs) {
10671 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10672 if (err)
10673 goto done;
10675 printf("history forked at %s%s%s%s\n %s\n",
10676 yca_id_str,
10677 refs_str ? " (" : "", refs_str ? refs_str : "",
10678 refs_str ? ")" : "", yca_brief_str);
10680 done:
10681 free(custom_refs_str);
10682 free(new_commit_id);
10683 free(refs_str);
10684 free(yca_id);
10685 free(yca_id_str);
10686 free(yca_brief_str);
10687 if (new_commit)
10688 got_object_commit_close(new_commit);
10689 if (yca_commit)
10690 got_object_commit_close(yca_commit);
10692 return NULL;
10695 static const struct got_error *
10696 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10697 struct got_repository *repo)
10699 const struct got_error *err;
10700 struct got_reflist_head refs;
10701 struct got_reflist_entry *re;
10702 char *uuidstr = NULL;
10703 static char msg[160];
10705 TAILQ_INIT(&refs);
10707 err = got_worktree_get_uuid(&uuidstr, worktree);
10708 if (err)
10709 goto done;
10711 err = got_ref_list(&refs, repo, "refs/got/worktree",
10712 got_ref_cmp_by_name, repo);
10713 if (err)
10714 goto done;
10716 TAILQ_FOREACH(re, &refs, entry) {
10717 const char *cmd, *refname, *type;
10719 refname = got_ref_get_name(re->ref);
10721 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10722 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10723 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10724 cmd = "cherrypick";
10725 type = "cherrypicked";
10726 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10727 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10728 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10729 cmd = "backout";
10730 type = "backed-out";
10731 } else
10732 continue;
10734 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10735 continue;
10737 snprintf(msg, sizeof(msg),
10738 "work tree has references created by %s commits which "
10739 "must be removed with 'got %s -X' before running the %s "
10740 "command", type, cmd, caller);
10741 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10742 goto done;
10745 done:
10746 free(uuidstr);
10747 got_ref_list_free(&refs);
10748 return err;
10751 static const struct got_error *
10752 process_backup_refs(const char *backup_ref_prefix,
10753 const char *wanted_branch_name,
10754 int delete, struct got_repository *repo)
10756 const struct got_error *err;
10757 struct got_reflist_head refs, backup_refs;
10758 struct got_reflist_entry *re;
10759 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10760 struct got_object_id *old_commit_id = NULL;
10761 char *branch_name = NULL;
10762 struct got_commit_object *old_commit = NULL;
10763 struct got_reflist_object_id_map *refs_idmap = NULL;
10764 int wanted_branch_found = 0;
10766 TAILQ_INIT(&refs);
10767 TAILQ_INIT(&backup_refs);
10769 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10770 if (err)
10771 return err;
10773 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10774 if (err)
10775 goto done;
10777 if (wanted_branch_name) {
10778 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10779 wanted_branch_name += 11;
10782 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10783 got_ref_cmp_by_commit_timestamp_descending, repo);
10784 if (err)
10785 goto done;
10787 TAILQ_FOREACH(re, &backup_refs, entry) {
10788 const char *refname = got_ref_get_name(re->ref);
10789 char *slash;
10791 err = check_cancelled(NULL);
10792 if (err)
10793 break;
10795 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10796 if (err)
10797 break;
10799 err = got_object_open_as_commit(&old_commit, repo,
10800 old_commit_id);
10801 if (err)
10802 break;
10804 if (strncmp(backup_ref_prefix, refname,
10805 backup_ref_prefix_len) == 0)
10806 refname += backup_ref_prefix_len;
10808 while (refname[0] == '/')
10809 refname++;
10811 branch_name = strdup(refname);
10812 if (branch_name == NULL) {
10813 err = got_error_from_errno("strdup");
10814 break;
10816 slash = strrchr(branch_name, '/');
10817 if (slash) {
10818 *slash = '\0';
10819 refname += strlen(branch_name) + 1;
10822 if (wanted_branch_name == NULL ||
10823 strcmp(wanted_branch_name, branch_name) == 0) {
10824 wanted_branch_found = 1;
10825 if (delete) {
10826 err = delete_backup_ref(re->ref,
10827 old_commit_id, repo);
10828 } else {
10829 err = print_backup_ref(branch_name, refname,
10830 old_commit_id, old_commit, refs_idmap,
10831 repo);
10833 if (err)
10834 break;
10837 free(old_commit_id);
10838 old_commit_id = NULL;
10839 free(branch_name);
10840 branch_name = NULL;
10841 got_object_commit_close(old_commit);
10842 old_commit = NULL;
10845 if (wanted_branch_name && !wanted_branch_found) {
10846 err = got_error_fmt(GOT_ERR_NOT_REF,
10847 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10849 done:
10850 if (refs_idmap)
10851 got_reflist_object_id_map_free(refs_idmap);
10852 got_ref_list_free(&refs);
10853 got_ref_list_free(&backup_refs);
10854 free(old_commit_id);
10855 free(branch_name);
10856 if (old_commit)
10857 got_object_commit_close(old_commit);
10858 return err;
10861 static const struct got_error *
10862 abort_progress(void *arg, unsigned char status, const char *path)
10865 * Unversioned files should not clutter progress output when
10866 * an operation is aborted.
10868 if (status == GOT_STATUS_UNVERSIONED)
10869 return NULL;
10871 return update_progress(arg, status, path);
10874 static const struct got_error *
10875 cmd_rebase(int argc, char *argv[])
10877 const struct got_error *error = NULL;
10878 struct got_worktree *worktree = NULL;
10879 struct got_repository *repo = NULL;
10880 struct got_fileindex *fileindex = NULL;
10881 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10882 struct got_reference *branch = NULL;
10883 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10884 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10885 struct got_object_id *resume_commit_id = NULL;
10886 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10887 struct got_object_id *head_commit_id = NULL;
10888 struct got_reference *head_ref = NULL;
10889 struct got_commit_object *commit = NULL;
10890 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10891 int histedit_in_progress = 0, merge_in_progress = 0;
10892 int create_backup = 1, list_backups = 0, delete_backups = 0;
10893 struct got_object_id_queue commits;
10894 struct got_pathlist_head merged_paths;
10895 const struct got_object_id_queue *parent_ids;
10896 struct got_object_qid *qid, *pid;
10897 struct got_update_progress_arg upa;
10898 int *pack_fds = NULL;
10900 STAILQ_INIT(&commits);
10901 TAILQ_INIT(&merged_paths);
10902 memset(&upa, 0, sizeof(upa));
10904 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10905 switch (ch) {
10906 case 'a':
10907 abort_rebase = 1;
10908 break;
10909 case 'c':
10910 continue_rebase = 1;
10911 break;
10912 case 'l':
10913 list_backups = 1;
10914 break;
10915 case 'X':
10916 delete_backups = 1;
10917 break;
10918 default:
10919 usage_rebase();
10920 /* NOTREACHED */
10924 argc -= optind;
10925 argv += optind;
10927 #ifndef PROFILE
10928 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10929 "unveil", NULL) == -1)
10930 err(1, "pledge");
10931 #endif
10932 if (list_backups) {
10933 if (abort_rebase)
10934 option_conflict('l', 'a');
10935 if (continue_rebase)
10936 option_conflict('l', 'c');
10937 if (delete_backups)
10938 option_conflict('l', 'X');
10939 if (argc != 0 && argc != 1)
10940 usage_rebase();
10941 } else if (delete_backups) {
10942 if (abort_rebase)
10943 option_conflict('X', 'a');
10944 if (continue_rebase)
10945 option_conflict('X', 'c');
10946 if (list_backups)
10947 option_conflict('l', 'X');
10948 if (argc != 0 && argc != 1)
10949 usage_rebase();
10950 } else {
10951 if (abort_rebase && continue_rebase)
10952 usage_rebase();
10953 else if (abort_rebase || continue_rebase) {
10954 if (argc != 0)
10955 usage_rebase();
10956 } else if (argc != 1)
10957 usage_rebase();
10960 cwd = getcwd(NULL, 0);
10961 if (cwd == NULL) {
10962 error = got_error_from_errno("getcwd");
10963 goto done;
10966 error = got_repo_pack_fds_open(&pack_fds);
10967 if (error != NULL)
10968 goto done;
10970 error = got_worktree_open(&worktree, cwd);
10971 if (error) {
10972 if (list_backups || delete_backups) {
10973 if (error->code != GOT_ERR_NOT_WORKTREE)
10974 goto done;
10975 } else {
10976 if (error->code == GOT_ERR_NOT_WORKTREE)
10977 error = wrap_not_worktree_error(error,
10978 "rebase", cwd);
10979 goto done;
10983 error = get_gitconfig_path(&gitconfig_path);
10984 if (error)
10985 goto done;
10986 error = got_repo_open(&repo,
10987 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10988 gitconfig_path, pack_fds);
10989 if (error != NULL)
10990 goto done;
10992 if (worktree != NULL && !list_backups && !delete_backups) {
10993 error = worktree_has_logmsg_ref("rebase", worktree, repo);
10994 if (error)
10995 goto done;
10998 error = get_author(&committer, repo, worktree);
10999 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11000 goto done;
11002 error = apply_unveil(got_repo_get_path(repo), 0,
11003 worktree ? got_worktree_get_root_path(worktree) : NULL);
11004 if (error)
11005 goto done;
11007 if (list_backups || delete_backups) {
11008 error = process_backup_refs(
11009 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11010 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11011 goto done; /* nothing else to do */
11014 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11015 worktree);
11016 if (error)
11017 goto done;
11018 if (histedit_in_progress) {
11019 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11020 goto done;
11023 error = got_worktree_merge_in_progress(&merge_in_progress,
11024 worktree, repo);
11025 if (error)
11026 goto done;
11027 if (merge_in_progress) {
11028 error = got_error(GOT_ERR_MERGE_BUSY);
11029 goto done;
11032 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11033 if (error)
11034 goto done;
11036 if (abort_rebase) {
11037 if (!rebase_in_progress) {
11038 error = got_error(GOT_ERR_NOT_REBASING);
11039 goto done;
11041 error = got_worktree_rebase_continue(&resume_commit_id,
11042 &new_base_branch, &tmp_branch, &branch, &fileindex,
11043 worktree, repo);
11044 if (error)
11045 goto done;
11046 printf("Switching work tree to %s\n",
11047 got_ref_get_symref_target(new_base_branch));
11048 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11049 new_base_branch, abort_progress, &upa);
11050 if (error)
11051 goto done;
11052 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11053 print_merge_progress_stats(&upa);
11054 goto done; /* nothing else to do */
11057 if (continue_rebase) {
11058 if (!rebase_in_progress) {
11059 error = got_error(GOT_ERR_NOT_REBASING);
11060 goto done;
11062 error = got_worktree_rebase_continue(&resume_commit_id,
11063 &new_base_branch, &tmp_branch, &branch, &fileindex,
11064 worktree, repo);
11065 if (error)
11066 goto done;
11068 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11069 committer, resume_commit_id, repo);
11070 if (error)
11071 goto done;
11073 yca_id = got_object_id_dup(resume_commit_id);
11074 if (yca_id == NULL) {
11075 error = got_error_from_errno("got_object_id_dup");
11076 goto done;
11078 } else {
11079 error = got_ref_open(&branch, repo, argv[0], 0);
11080 if (error != NULL)
11081 goto done;
11082 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11083 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11084 "will not rebase a branch which lives outside "
11085 "the \"refs/heads/\" reference namespace");
11086 goto done;
11090 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11091 if (error)
11092 goto done;
11094 if (!continue_rebase) {
11095 struct got_object_id *base_commit_id;
11097 error = got_ref_open(&head_ref, repo,
11098 got_worktree_get_head_ref_name(worktree), 0);
11099 if (error)
11100 goto done;
11101 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11102 if (error)
11103 goto done;
11104 base_commit_id = got_worktree_get_base_commit_id(worktree);
11105 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11106 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11107 goto done;
11110 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11111 base_commit_id, branch_head_commit_id, 1, repo,
11112 check_cancelled, NULL);
11113 if (error)
11114 goto done;
11115 if (yca_id == NULL) {
11116 error = got_error_msg(GOT_ERR_ANCESTRY,
11117 "specified branch shares no common ancestry "
11118 "with work tree's branch");
11119 goto done;
11122 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11123 if (error) {
11124 if (error->code != GOT_ERR_ANCESTRY)
11125 goto done;
11126 error = NULL;
11127 } else {
11128 struct got_pathlist_head paths;
11129 printf("%s is already based on %s\n",
11130 got_ref_get_name(branch),
11131 got_worktree_get_head_ref_name(worktree));
11132 error = switch_head_ref(branch, branch_head_commit_id,
11133 worktree, repo);
11134 if (error)
11135 goto done;
11136 error = got_worktree_set_base_commit_id(worktree, repo,
11137 branch_head_commit_id);
11138 if (error)
11139 goto done;
11140 TAILQ_INIT(&paths);
11141 error = got_pathlist_append(&paths, "", NULL);
11142 if (error)
11143 goto done;
11144 error = got_worktree_checkout_files(worktree,
11145 &paths, repo, update_progress, &upa,
11146 check_cancelled, NULL);
11147 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11148 if (error)
11149 goto done;
11150 if (upa.did_something) {
11151 char *id_str;
11152 error = got_object_id_str(&id_str,
11153 branch_head_commit_id);
11154 if (error)
11155 goto done;
11156 printf("Updated to %s: %s\n",
11157 got_worktree_get_head_ref_name(worktree),
11158 id_str);
11159 free(id_str);
11160 } else
11161 printf("Already up-to-date\n");
11162 print_update_progress_stats(&upa);
11163 goto done;
11167 commit_id = branch_head_commit_id;
11168 error = got_object_open_as_commit(&commit, repo, commit_id);
11169 if (error)
11170 goto done;
11172 parent_ids = got_object_commit_get_parent_ids(commit);
11173 pid = STAILQ_FIRST(parent_ids);
11174 if (pid == NULL) {
11175 error = got_error(GOT_ERR_EMPTY_REBASE);
11176 goto done;
11178 error = collect_commits(&commits, commit_id, &pid->id,
11179 yca_id, got_worktree_get_path_prefix(worktree),
11180 GOT_ERR_REBASE_PATH, repo);
11181 got_object_commit_close(commit);
11182 commit = NULL;
11183 if (error)
11184 goto done;
11186 if (!continue_rebase) {
11187 error = got_worktree_rebase_prepare(&new_base_branch,
11188 &tmp_branch, &fileindex, worktree, branch, repo);
11189 if (error)
11190 goto done;
11193 if (STAILQ_EMPTY(&commits)) {
11194 if (continue_rebase) {
11195 error = rebase_complete(worktree, fileindex,
11196 branch, new_base_branch, tmp_branch, repo,
11197 create_backup);
11198 goto done;
11199 } else {
11200 /* Fast-forward the reference of the branch. */
11201 struct got_object_id *new_head_commit_id;
11202 char *id_str;
11203 error = got_ref_resolve(&new_head_commit_id, repo,
11204 new_base_branch);
11205 if (error)
11206 goto done;
11207 error = got_object_id_str(&id_str, new_head_commit_id);
11208 if (error)
11209 goto done;
11210 printf("Forwarding %s to commit %s\n",
11211 got_ref_get_name(branch), id_str);
11212 free(id_str);
11213 error = got_ref_change_ref(branch,
11214 new_head_commit_id);
11215 if (error)
11216 goto done;
11217 /* No backup needed since objects did not change. */
11218 create_backup = 0;
11222 pid = NULL;
11223 STAILQ_FOREACH(qid, &commits, entry) {
11225 commit_id = &qid->id;
11226 parent_id = pid ? &pid->id : yca_id;
11227 pid = qid;
11229 memset(&upa, 0, sizeof(upa));
11230 error = got_worktree_rebase_merge_files(&merged_paths,
11231 worktree, fileindex, parent_id, commit_id, repo,
11232 update_progress, &upa, check_cancelled, NULL);
11233 if (error)
11234 goto done;
11236 print_merge_progress_stats(&upa);
11237 if (upa.conflicts > 0 || upa.missing > 0 ||
11238 upa.not_deleted > 0 || upa.unversioned > 0) {
11239 if (upa.conflicts > 0) {
11240 error = show_rebase_merge_conflict(&qid->id,
11241 repo);
11242 if (error)
11243 goto done;
11245 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11246 break;
11249 error = rebase_commit(&merged_paths, worktree, fileindex,
11250 tmp_branch, committer, commit_id, repo);
11251 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11252 if (error)
11253 goto done;
11256 if (upa.conflicts > 0 || upa.missing > 0 ||
11257 upa.not_deleted > 0 || upa.unversioned > 0) {
11258 error = got_worktree_rebase_postpone(worktree, fileindex);
11259 if (error)
11260 goto done;
11261 if (upa.conflicts > 0 && upa.missing == 0 &&
11262 upa.not_deleted == 0 && upa.unversioned == 0) {
11263 error = got_error_msg(GOT_ERR_CONFLICTS,
11264 "conflicts must be resolved before rebasing "
11265 "can continue");
11266 } else if (upa.conflicts > 0) {
11267 error = got_error_msg(GOT_ERR_CONFLICTS,
11268 "conflicts must be resolved before rebasing "
11269 "can continue; changes destined for some "
11270 "files were not yet merged and should be "
11271 "merged manually if required before the "
11272 "rebase operation is continued");
11273 } else {
11274 error = got_error_msg(GOT_ERR_CONFLICTS,
11275 "changes destined for some files were not "
11276 "yet merged and should be merged manually "
11277 "if required before the rebase operation "
11278 "is continued");
11280 } else
11281 error = rebase_complete(worktree, fileindex, branch,
11282 new_base_branch, tmp_branch, repo, create_backup);
11283 done:
11284 free(cwd);
11285 free(committer);
11286 free(gitconfig_path);
11287 got_object_id_queue_free(&commits);
11288 free(branch_head_commit_id);
11289 free(resume_commit_id);
11290 free(head_commit_id);
11291 free(yca_id);
11292 if (commit)
11293 got_object_commit_close(commit);
11294 if (branch)
11295 got_ref_close(branch);
11296 if (new_base_branch)
11297 got_ref_close(new_base_branch);
11298 if (tmp_branch)
11299 got_ref_close(tmp_branch);
11300 if (head_ref)
11301 got_ref_close(head_ref);
11302 if (worktree)
11303 got_worktree_close(worktree);
11304 if (repo) {
11305 const struct got_error *close_err = got_repo_close(repo);
11306 if (error == NULL)
11307 error = close_err;
11309 if (pack_fds) {
11310 const struct got_error *pack_err =
11311 got_repo_pack_fds_close(pack_fds);
11312 if (error == NULL)
11313 error = pack_err;
11315 return error;
11318 __dead static void
11319 usage_histedit(void)
11321 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
11322 "[branch]\n", getprogname());
11323 exit(1);
11326 #define GOT_HISTEDIT_PICK 'p'
11327 #define GOT_HISTEDIT_EDIT 'e'
11328 #define GOT_HISTEDIT_FOLD 'f'
11329 #define GOT_HISTEDIT_DROP 'd'
11330 #define GOT_HISTEDIT_MESG 'm'
11332 static const struct got_histedit_cmd {
11333 unsigned char code;
11334 const char *name;
11335 const char *desc;
11336 } got_histedit_cmds[] = {
11337 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11338 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11339 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11340 "be used" },
11341 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11342 { GOT_HISTEDIT_MESG, "mesg",
11343 "single-line log message for commit above (open editor if empty)" },
11346 struct got_histedit_list_entry {
11347 TAILQ_ENTRY(got_histedit_list_entry) entry;
11348 struct got_object_id *commit_id;
11349 const struct got_histedit_cmd *cmd;
11350 char *logmsg;
11352 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11354 static const struct got_error *
11355 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11356 FILE *f, struct got_repository *repo)
11358 const struct got_error *err = NULL;
11359 char *logmsg = NULL, *id_str = NULL;
11360 struct got_commit_object *commit = NULL;
11361 int n;
11363 err = got_object_open_as_commit(&commit, repo, commit_id);
11364 if (err)
11365 goto done;
11367 err = get_short_logmsg(&logmsg, 34, commit);
11368 if (err)
11369 goto done;
11371 err = got_object_id_str(&id_str, commit_id);
11372 if (err)
11373 goto done;
11375 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11376 if (n < 0)
11377 err = got_ferror(f, GOT_ERR_IO);
11378 done:
11379 if (commit)
11380 got_object_commit_close(commit);
11381 free(id_str);
11382 free(logmsg);
11383 return err;
11386 static const struct got_error *
11387 histedit_write_commit_list(struct got_object_id_queue *commits,
11388 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
11389 struct got_repository *repo)
11391 const struct got_error *err = NULL;
11392 struct got_object_qid *qid;
11393 const char *histedit_cmd = NULL;
11395 if (STAILQ_EMPTY(commits))
11396 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11398 STAILQ_FOREACH(qid, commits, entry) {
11399 histedit_cmd = got_histedit_cmds[0].name;
11400 if (edit_only)
11401 histedit_cmd = "edit";
11402 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11403 histedit_cmd = "fold";
11404 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11405 if (err)
11406 break;
11407 if (edit_logmsg_only) {
11408 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11409 if (n < 0) {
11410 err = got_ferror(f, GOT_ERR_IO);
11411 break;
11416 return err;
11419 static const struct got_error *
11420 write_cmd_list(FILE *f, const char *branch_name,
11421 struct got_object_id_queue *commits)
11423 const struct got_error *err = NULL;
11424 size_t i;
11425 int n;
11426 char *id_str;
11427 struct got_object_qid *qid;
11429 qid = STAILQ_FIRST(commits);
11430 err = got_object_id_str(&id_str, &qid->id);
11431 if (err)
11432 return err;
11434 n = fprintf(f,
11435 "# Editing the history of branch '%s' starting at\n"
11436 "# commit %s\n"
11437 "# Commits will be processed in order from top to "
11438 "bottom of this file.\n", branch_name, id_str);
11439 if (n < 0) {
11440 err = got_ferror(f, GOT_ERR_IO);
11441 goto done;
11444 n = fprintf(f, "# Available histedit commands:\n");
11445 if (n < 0) {
11446 err = got_ferror(f, GOT_ERR_IO);
11447 goto done;
11450 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11451 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11452 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11453 cmd->desc);
11454 if (n < 0) {
11455 err = got_ferror(f, GOT_ERR_IO);
11456 break;
11459 done:
11460 free(id_str);
11461 return err;
11464 static const struct got_error *
11465 histedit_syntax_error(int lineno)
11467 static char msg[42];
11468 int ret;
11470 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11471 lineno);
11472 if (ret < 0 || (size_t)ret >= sizeof(msg))
11473 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11475 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11478 static const struct got_error *
11479 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11480 char *logmsg, struct got_repository *repo)
11482 const struct got_error *err;
11483 struct got_commit_object *folded_commit = NULL;
11484 char *id_str, *folded_logmsg = NULL;
11486 err = got_object_id_str(&id_str, hle->commit_id);
11487 if (err)
11488 return err;
11490 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11491 if (err)
11492 goto done;
11494 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11495 if (err)
11496 goto done;
11497 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11498 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11499 folded_logmsg) == -1) {
11500 err = got_error_from_errno("asprintf");
11502 done:
11503 if (folded_commit)
11504 got_object_commit_close(folded_commit);
11505 free(id_str);
11506 free(folded_logmsg);
11507 return err;
11510 static struct got_histedit_list_entry *
11511 get_folded_commits(struct got_histedit_list_entry *hle)
11513 struct got_histedit_list_entry *prev, *folded = NULL;
11515 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11516 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11517 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11518 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11519 folded = prev;
11520 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11523 return folded;
11526 static const struct got_error *
11527 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11528 struct got_repository *repo)
11530 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11531 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11532 const struct got_error *err = NULL;
11533 struct got_commit_object *commit = NULL;
11534 int logmsg_len;
11535 int fd;
11536 struct got_histedit_list_entry *folded = NULL;
11538 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11539 if (err)
11540 return err;
11542 folded = get_folded_commits(hle);
11543 if (folded) {
11544 while (folded != hle) {
11545 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11546 folded = TAILQ_NEXT(folded, entry);
11547 continue;
11549 err = append_folded_commit_msg(&new_msg, folded,
11550 logmsg, repo);
11551 if (err)
11552 goto done;
11553 free(logmsg);
11554 logmsg = new_msg;
11555 folded = TAILQ_NEXT(folded, entry);
11559 err = got_object_id_str(&id_str, hle->commit_id);
11560 if (err)
11561 goto done;
11562 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11563 if (err)
11564 goto done;
11565 logmsg_len = asprintf(&new_msg,
11566 "%s\n# original log message of commit %s: %s",
11567 logmsg ? logmsg : "", id_str, orig_logmsg);
11568 if (logmsg_len == -1) {
11569 err = got_error_from_errno("asprintf");
11570 goto done;
11572 free(logmsg);
11573 logmsg = new_msg;
11575 err = got_object_id_str(&id_str, hle->commit_id);
11576 if (err)
11577 goto done;
11579 err = got_opentemp_named_fd(&logmsg_path, &fd,
11580 GOT_TMPDIR_STR "/got-logmsg", "");
11581 if (err)
11582 goto done;
11584 write(fd, logmsg, logmsg_len);
11585 close(fd);
11587 err = get_editor(&editor);
11588 if (err)
11589 goto done;
11591 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11592 logmsg_len, 0);
11593 if (err) {
11594 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11595 goto done;
11596 err = NULL;
11597 hle->logmsg = strdup(new_msg);
11598 if (hle->logmsg == NULL)
11599 err = got_error_from_errno("strdup");
11601 done:
11602 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11603 err = got_error_from_errno2("unlink", logmsg_path);
11604 free(logmsg_path);
11605 free(logmsg);
11606 free(orig_logmsg);
11607 free(editor);
11608 if (commit)
11609 got_object_commit_close(commit);
11610 return err;
11613 static const struct got_error *
11614 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11615 FILE *f, struct got_repository *repo)
11617 const struct got_error *err = NULL;
11618 char *line = NULL, *p, *end;
11619 size_t i, size;
11620 ssize_t len;
11621 int lineno = 0, lastcmd = -1;
11622 const struct got_histedit_cmd *cmd;
11623 struct got_object_id *commit_id = NULL;
11624 struct got_histedit_list_entry *hle = NULL;
11626 for (;;) {
11627 len = getline(&line, &size, f);
11628 if (len == -1) {
11629 const struct got_error *getline_err;
11630 if (feof(f))
11631 break;
11632 getline_err = got_error_from_errno("getline");
11633 err = got_ferror(f, getline_err->code);
11634 break;
11636 lineno++;
11637 p = line;
11638 while (isspace((unsigned char)p[0]))
11639 p++;
11640 if (p[0] == '#' || p[0] == '\0') {
11641 free(line);
11642 line = NULL;
11643 continue;
11645 cmd = NULL;
11646 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11647 cmd = &got_histedit_cmds[i];
11648 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11649 isspace((unsigned char)p[strlen(cmd->name)])) {
11650 p += strlen(cmd->name);
11651 break;
11653 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11654 p++;
11655 break;
11658 if (i == nitems(got_histedit_cmds)) {
11659 err = histedit_syntax_error(lineno);
11660 break;
11662 while (isspace((unsigned char)p[0]))
11663 p++;
11664 if (cmd->code == GOT_HISTEDIT_MESG) {
11665 if (lastcmd != GOT_HISTEDIT_PICK &&
11666 lastcmd != GOT_HISTEDIT_EDIT) {
11667 err = got_error(GOT_ERR_HISTEDIT_CMD);
11668 break;
11670 if (p[0] == '\0') {
11671 err = histedit_edit_logmsg(hle, repo);
11672 if (err)
11673 break;
11674 } else {
11675 hle->logmsg = strdup(p);
11676 if (hle->logmsg == NULL) {
11677 err = got_error_from_errno("strdup");
11678 break;
11681 free(line);
11682 line = NULL;
11683 lastcmd = cmd->code;
11684 continue;
11685 } else {
11686 end = p;
11687 while (end[0] && !isspace((unsigned char)end[0]))
11688 end++;
11689 *end = '\0';
11691 err = got_object_resolve_id_str(&commit_id, repo, p);
11692 if (err) {
11693 /* override error code */
11694 err = histedit_syntax_error(lineno);
11695 break;
11698 hle = malloc(sizeof(*hle));
11699 if (hle == NULL) {
11700 err = got_error_from_errno("malloc");
11701 break;
11703 hle->cmd = cmd;
11704 hle->commit_id = commit_id;
11705 hle->logmsg = NULL;
11706 commit_id = NULL;
11707 free(line);
11708 line = NULL;
11709 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11710 lastcmd = cmd->code;
11713 free(line);
11714 free(commit_id);
11715 return err;
11718 static const struct got_error *
11719 histedit_check_script(struct got_histedit_list *histedit_cmds,
11720 struct got_object_id_queue *commits, struct got_repository *repo)
11722 const struct got_error *err = NULL;
11723 struct got_object_qid *qid;
11724 struct got_histedit_list_entry *hle;
11725 static char msg[92];
11726 char *id_str;
11728 if (TAILQ_EMPTY(histedit_cmds))
11729 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11730 "histedit script contains no commands");
11731 if (STAILQ_EMPTY(commits))
11732 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11734 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11735 struct got_histedit_list_entry *hle2;
11736 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11737 if (hle == hle2)
11738 continue;
11739 if (got_object_id_cmp(hle->commit_id,
11740 hle2->commit_id) != 0)
11741 continue;
11742 err = got_object_id_str(&id_str, hle->commit_id);
11743 if (err)
11744 return err;
11745 snprintf(msg, sizeof(msg), "commit %s is listed "
11746 "more than once in histedit script", id_str);
11747 free(id_str);
11748 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11752 STAILQ_FOREACH(qid, commits, entry) {
11753 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11754 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11755 break;
11757 if (hle == NULL) {
11758 err = got_object_id_str(&id_str, &qid->id);
11759 if (err)
11760 return err;
11761 snprintf(msg, sizeof(msg),
11762 "commit %s missing from histedit script", id_str);
11763 free(id_str);
11764 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11768 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11769 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11770 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11771 "last commit in histedit script cannot be folded");
11773 return NULL;
11776 static const struct got_error *
11777 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11778 const char *path, struct got_object_id_queue *commits,
11779 struct got_repository *repo)
11781 const struct got_error *err = NULL;
11782 char *editor;
11783 FILE *f = NULL;
11785 err = get_editor(&editor);
11786 if (err)
11787 return err;
11789 if (spawn_editor(editor, path) == -1) {
11790 err = got_error_from_errno("failed spawning editor");
11791 goto done;
11794 f = fopen(path, "re");
11795 if (f == NULL) {
11796 err = got_error_from_errno("fopen");
11797 goto done;
11799 err = histedit_parse_list(histedit_cmds, f, repo);
11800 if (err)
11801 goto done;
11803 err = histedit_check_script(histedit_cmds, commits, repo);
11804 done:
11805 if (f && fclose(f) == EOF && err == NULL)
11806 err = got_error_from_errno("fclose");
11807 free(editor);
11808 return err;
11811 static const struct got_error *
11812 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11813 struct got_object_id_queue *, const char *, const char *,
11814 struct got_repository *);
11816 static const struct got_error *
11817 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11818 struct got_object_id_queue *commits, const char *branch_name,
11819 int edit_logmsg_only, int fold_only, int edit_only,
11820 struct got_repository *repo)
11822 const struct got_error *err;
11823 FILE *f = NULL;
11824 char *path = NULL;
11826 err = got_opentemp_named(&path, &f, "got-histedit", "");
11827 if (err)
11828 return err;
11830 err = write_cmd_list(f, branch_name, commits);
11831 if (err)
11832 goto done;
11834 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11835 fold_only, edit_only, repo);
11836 if (err)
11837 goto done;
11839 if (edit_logmsg_only || fold_only || edit_only) {
11840 rewind(f);
11841 err = histedit_parse_list(histedit_cmds, f, repo);
11842 } else {
11843 if (fclose(f) == EOF) {
11844 err = got_error_from_errno("fclose");
11845 goto done;
11847 f = NULL;
11848 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11849 if (err) {
11850 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11851 err->code != GOT_ERR_HISTEDIT_CMD)
11852 goto done;
11853 err = histedit_edit_list_retry(histedit_cmds, err,
11854 commits, path, branch_name, repo);
11857 done:
11858 if (f && fclose(f) == EOF && err == NULL)
11859 err = got_error_from_errno("fclose");
11860 if (path && unlink(path) != 0 && err == NULL)
11861 err = got_error_from_errno2("unlink", path);
11862 free(path);
11863 return err;
11866 static const struct got_error *
11867 histedit_save_list(struct got_histedit_list *histedit_cmds,
11868 struct got_worktree *worktree, struct got_repository *repo)
11870 const struct got_error *err = NULL;
11871 char *path = NULL;
11872 FILE *f = NULL;
11873 struct got_histedit_list_entry *hle;
11874 struct got_commit_object *commit = NULL;
11876 err = got_worktree_get_histedit_script_path(&path, worktree);
11877 if (err)
11878 return err;
11880 f = fopen(path, "we");
11881 if (f == NULL) {
11882 err = got_error_from_errno2("fopen", path);
11883 goto done;
11885 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11886 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11887 repo);
11888 if (err)
11889 break;
11891 if (hle->logmsg) {
11892 int n = fprintf(f, "%c %s\n",
11893 GOT_HISTEDIT_MESG, hle->logmsg);
11894 if (n < 0) {
11895 err = got_ferror(f, GOT_ERR_IO);
11896 break;
11900 done:
11901 if (f && fclose(f) == EOF && err == NULL)
11902 err = got_error_from_errno("fclose");
11903 free(path);
11904 if (commit)
11905 got_object_commit_close(commit);
11906 return err;
11909 static void
11910 histedit_free_list(struct got_histedit_list *histedit_cmds)
11912 struct got_histedit_list_entry *hle;
11914 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11915 TAILQ_REMOVE(histedit_cmds, hle, entry);
11916 free(hle);
11920 static const struct got_error *
11921 histedit_load_list(struct got_histedit_list *histedit_cmds,
11922 const char *path, struct got_repository *repo)
11924 const struct got_error *err = NULL;
11925 FILE *f = NULL;
11927 f = fopen(path, "re");
11928 if (f == NULL) {
11929 err = got_error_from_errno2("fopen", path);
11930 goto done;
11933 err = histedit_parse_list(histedit_cmds, f, repo);
11934 done:
11935 if (f && fclose(f) == EOF && err == NULL)
11936 err = got_error_from_errno("fclose");
11937 return err;
11940 static const struct got_error *
11941 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11942 const struct got_error *edit_err, struct got_object_id_queue *commits,
11943 const char *path, const char *branch_name, struct got_repository *repo)
11945 const struct got_error *err = NULL, *prev_err = edit_err;
11946 int resp = ' ';
11948 while (resp != 'c' && resp != 'r' && resp != 'a') {
11949 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11950 "or (a)bort: ", getprogname(), prev_err->msg);
11951 resp = getchar();
11952 if (resp == '\n')
11953 resp = getchar();
11954 if (resp == 'c') {
11955 histedit_free_list(histedit_cmds);
11956 err = histedit_run_editor(histedit_cmds, path, commits,
11957 repo);
11958 if (err) {
11959 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11960 err->code != GOT_ERR_HISTEDIT_CMD)
11961 break;
11962 prev_err = err;
11963 resp = ' ';
11964 continue;
11966 break;
11967 } else if (resp == 'r') {
11968 histedit_free_list(histedit_cmds);
11969 err = histedit_edit_script(histedit_cmds,
11970 commits, branch_name, 0, 0, 0, repo);
11971 if (err) {
11972 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11973 err->code != GOT_ERR_HISTEDIT_CMD)
11974 break;
11975 prev_err = err;
11976 resp = ' ';
11977 continue;
11979 break;
11980 } else if (resp == 'a') {
11981 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11982 break;
11983 } else
11984 printf("invalid response '%c'\n", resp);
11987 return err;
11990 static const struct got_error *
11991 histedit_complete(struct got_worktree *worktree,
11992 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11993 struct got_reference *branch, struct got_repository *repo)
11995 printf("Switching work tree to %s\n",
11996 got_ref_get_symref_target(branch));
11997 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11998 branch, repo);
12001 static const struct got_error *
12002 show_histedit_progress(struct got_commit_object *commit,
12003 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12005 const struct got_error *err;
12006 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12008 err = got_object_id_str(&old_id_str, hle->commit_id);
12009 if (err)
12010 goto done;
12012 if (new_id) {
12013 err = got_object_id_str(&new_id_str, new_id);
12014 if (err)
12015 goto done;
12018 old_id_str[12] = '\0';
12019 if (new_id_str)
12020 new_id_str[12] = '\0';
12022 if (hle->logmsg) {
12023 logmsg = strdup(hle->logmsg);
12024 if (logmsg == NULL) {
12025 err = got_error_from_errno("strdup");
12026 goto done;
12028 trim_logmsg(logmsg, 42);
12029 } else {
12030 err = get_short_logmsg(&logmsg, 42, commit);
12031 if (err)
12032 goto done;
12035 switch (hle->cmd->code) {
12036 case GOT_HISTEDIT_PICK:
12037 case GOT_HISTEDIT_EDIT:
12038 printf("%s -> %s: %s\n", old_id_str,
12039 new_id_str ? new_id_str : "no-op change", logmsg);
12040 break;
12041 case GOT_HISTEDIT_DROP:
12042 case GOT_HISTEDIT_FOLD:
12043 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12044 logmsg);
12045 break;
12046 default:
12047 break;
12049 done:
12050 free(old_id_str);
12051 free(new_id_str);
12052 return err;
12055 static const struct got_error *
12056 histedit_commit(struct got_pathlist_head *merged_paths,
12057 struct got_worktree *worktree, struct got_fileindex *fileindex,
12058 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12059 const char *committer, struct got_repository *repo)
12061 const struct got_error *err;
12062 struct got_commit_object *commit;
12063 struct got_object_id *new_commit_id;
12065 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12066 && hle->logmsg == NULL) {
12067 err = histedit_edit_logmsg(hle, repo);
12068 if (err)
12069 return err;
12072 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12073 if (err)
12074 return err;
12076 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12077 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12078 hle->logmsg, repo);
12079 if (err) {
12080 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12081 goto done;
12082 err = show_histedit_progress(commit, hle, NULL);
12083 } else {
12084 err = show_histedit_progress(commit, hle, new_commit_id);
12085 free(new_commit_id);
12087 done:
12088 got_object_commit_close(commit);
12089 return err;
12092 static const struct got_error *
12093 histedit_skip_commit(struct got_histedit_list_entry *hle,
12094 struct got_worktree *worktree, struct got_repository *repo)
12096 const struct got_error *error;
12097 struct got_commit_object *commit;
12099 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12100 repo);
12101 if (error)
12102 return error;
12104 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12105 if (error)
12106 return error;
12108 error = show_histedit_progress(commit, hle, NULL);
12109 got_object_commit_close(commit);
12110 return error;
12113 static const struct got_error *
12114 check_local_changes(void *arg, unsigned char status,
12115 unsigned char staged_status, const char *path,
12116 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12117 struct got_object_id *commit_id, int dirfd, const char *de_name)
12119 int *have_local_changes = arg;
12121 switch (status) {
12122 case GOT_STATUS_ADD:
12123 case GOT_STATUS_DELETE:
12124 case GOT_STATUS_MODIFY:
12125 case GOT_STATUS_CONFLICT:
12126 *have_local_changes = 1;
12127 return got_error(GOT_ERR_CANCELLED);
12128 default:
12129 break;
12132 switch (staged_status) {
12133 case GOT_STATUS_ADD:
12134 case GOT_STATUS_DELETE:
12135 case GOT_STATUS_MODIFY:
12136 *have_local_changes = 1;
12137 return got_error(GOT_ERR_CANCELLED);
12138 default:
12139 break;
12142 return NULL;
12145 static const struct got_error *
12146 cmd_histedit(int argc, char *argv[])
12148 const struct got_error *error = NULL;
12149 struct got_worktree *worktree = NULL;
12150 struct got_fileindex *fileindex = NULL;
12151 struct got_repository *repo = NULL;
12152 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12153 struct got_reference *branch = NULL;
12154 struct got_reference *tmp_branch = NULL;
12155 struct got_object_id *resume_commit_id = NULL;
12156 struct got_object_id *base_commit_id = NULL;
12157 struct got_object_id *head_commit_id = NULL;
12158 struct got_commit_object *commit = NULL;
12159 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12160 struct got_update_progress_arg upa;
12161 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12162 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12163 int list_backups = 0, delete_backups = 0;
12164 const char *edit_script_path = NULL;
12165 struct got_object_id_queue commits;
12166 struct got_pathlist_head merged_paths;
12167 const struct got_object_id_queue *parent_ids;
12168 struct got_object_qid *pid;
12169 struct got_histedit_list histedit_cmds;
12170 struct got_histedit_list_entry *hle;
12171 int *pack_fds = NULL;
12173 STAILQ_INIT(&commits);
12174 TAILQ_INIT(&histedit_cmds);
12175 TAILQ_INIT(&merged_paths);
12176 memset(&upa, 0, sizeof(upa));
12178 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
12179 switch (ch) {
12180 case 'a':
12181 abort_edit = 1;
12182 break;
12183 case 'c':
12184 continue_edit = 1;
12185 break;
12186 case 'e':
12187 edit_only = 1;
12188 break;
12189 case 'F':
12190 edit_script_path = optarg;
12191 break;
12192 case 'f':
12193 fold_only = 1;
12194 break;
12195 case 'l':
12196 list_backups = 1;
12197 break;
12198 case 'm':
12199 edit_logmsg_only = 1;
12200 break;
12201 case 'X':
12202 delete_backups = 1;
12203 break;
12204 default:
12205 usage_histedit();
12206 /* NOTREACHED */
12210 argc -= optind;
12211 argv += optind;
12213 #ifndef PROFILE
12214 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12215 "unveil", NULL) == -1)
12216 err(1, "pledge");
12217 #endif
12218 if (abort_edit && continue_edit)
12219 option_conflict('a', 'c');
12220 if (edit_script_path && edit_logmsg_only)
12221 option_conflict('F', 'm');
12222 if (abort_edit && edit_logmsg_only)
12223 option_conflict('a', 'm');
12224 if (continue_edit && edit_logmsg_only)
12225 option_conflict('c', 'm');
12226 if (abort_edit && fold_only)
12227 option_conflict('a', 'f');
12228 if (continue_edit && fold_only)
12229 option_conflict('c', 'f');
12230 if (fold_only && edit_logmsg_only)
12231 option_conflict('f', 'm');
12232 if (edit_script_path && fold_only)
12233 option_conflict('F', 'f');
12234 if (abort_edit && edit_only)
12235 option_conflict('a', 'e');
12236 if (continue_edit && edit_only)
12237 option_conflict('c', 'e');
12238 if (edit_only && edit_logmsg_only)
12239 option_conflict('e', 'm');
12240 if (edit_script_path && edit_only)
12241 option_conflict('F', 'e');
12242 if (list_backups) {
12243 if (abort_edit)
12244 option_conflict('l', 'a');
12245 if (continue_edit)
12246 option_conflict('l', 'c');
12247 if (edit_script_path)
12248 option_conflict('l', 'F');
12249 if (edit_logmsg_only)
12250 option_conflict('l', 'm');
12251 if (fold_only)
12252 option_conflict('l', 'f');
12253 if (edit_only)
12254 option_conflict('l', 'e');
12255 if (delete_backups)
12256 option_conflict('l', 'X');
12257 if (argc != 0 && argc != 1)
12258 usage_histedit();
12259 } else if (delete_backups) {
12260 if (abort_edit)
12261 option_conflict('X', 'a');
12262 if (continue_edit)
12263 option_conflict('X', 'c');
12264 if (edit_script_path)
12265 option_conflict('X', 'F');
12266 if (edit_logmsg_only)
12267 option_conflict('X', 'm');
12268 if (fold_only)
12269 option_conflict('X', 'f');
12270 if (edit_only)
12271 option_conflict('X', 'e');
12272 if (list_backups)
12273 option_conflict('X', 'l');
12274 if (argc != 0 && argc != 1)
12275 usage_histedit();
12276 } else if (argc != 0)
12277 usage_histedit();
12280 * This command cannot apply unveil(2) in all cases because the
12281 * user may choose to run an editor to edit the histedit script
12282 * and to edit individual commit log messages.
12283 * unveil(2) traverses exec(2); if an editor is used we have to
12284 * apply unveil after edit script and log messages have been written.
12285 * XXX TODO: Make use of unveil(2) where possible.
12288 cwd = getcwd(NULL, 0);
12289 if (cwd == NULL) {
12290 error = got_error_from_errno("getcwd");
12291 goto done;
12294 error = got_repo_pack_fds_open(&pack_fds);
12295 if (error != NULL)
12296 goto done;
12298 error = got_worktree_open(&worktree, cwd);
12299 if (error) {
12300 if (list_backups || delete_backups) {
12301 if (error->code != GOT_ERR_NOT_WORKTREE)
12302 goto done;
12303 } else {
12304 if (error->code == GOT_ERR_NOT_WORKTREE)
12305 error = wrap_not_worktree_error(error,
12306 "histedit", cwd);
12307 goto done;
12311 if (list_backups || delete_backups) {
12312 error = got_repo_open(&repo,
12313 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12314 NULL, pack_fds);
12315 if (error != NULL)
12316 goto done;
12317 error = apply_unveil(got_repo_get_path(repo), 0,
12318 worktree ? got_worktree_get_root_path(worktree) : NULL);
12319 if (error)
12320 goto done;
12321 error = process_backup_refs(
12322 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12323 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12324 goto done; /* nothing else to do */
12327 error = get_gitconfig_path(&gitconfig_path);
12328 if (error)
12329 goto done;
12330 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12331 gitconfig_path, pack_fds);
12332 if (error != NULL)
12333 goto done;
12335 if (worktree != NULL && !list_backups && !delete_backups) {
12336 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12337 if (error)
12338 goto done;
12341 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12342 if (error)
12343 goto done;
12344 if (rebase_in_progress) {
12345 error = got_error(GOT_ERR_REBASING);
12346 goto done;
12349 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12350 repo);
12351 if (error)
12352 goto done;
12353 if (merge_in_progress) {
12354 error = got_error(GOT_ERR_MERGE_BUSY);
12355 goto done;
12358 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12359 if (error)
12360 goto done;
12362 if (edit_in_progress && edit_logmsg_only) {
12363 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12364 "histedit operation is in progress in this "
12365 "work tree and must be continued or aborted "
12366 "before the -m option can be used");
12367 goto done;
12369 if (edit_in_progress && fold_only) {
12370 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12371 "histedit operation is in progress in this "
12372 "work tree and must be continued or aborted "
12373 "before the -f option can be used");
12374 goto done;
12376 if (edit_in_progress && edit_only) {
12377 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12378 "histedit operation is in progress in this "
12379 "work tree and must be continued or aborted "
12380 "before the -e option can be used");
12381 goto done;
12384 if (edit_in_progress && abort_edit) {
12385 error = got_worktree_histedit_continue(&resume_commit_id,
12386 &tmp_branch, &branch, &base_commit_id, &fileindex,
12387 worktree, repo);
12388 if (error)
12389 goto done;
12390 printf("Switching work tree to %s\n",
12391 got_ref_get_symref_target(branch));
12392 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12393 branch, base_commit_id, abort_progress, &upa);
12394 if (error)
12395 goto done;
12396 printf("Histedit of %s aborted\n",
12397 got_ref_get_symref_target(branch));
12398 print_merge_progress_stats(&upa);
12399 goto done; /* nothing else to do */
12400 } else if (abort_edit) {
12401 error = got_error(GOT_ERR_NOT_HISTEDIT);
12402 goto done;
12405 error = get_author(&committer, repo, worktree);
12406 if (error)
12407 goto done;
12409 if (continue_edit) {
12410 char *path;
12412 if (!edit_in_progress) {
12413 error = got_error(GOT_ERR_NOT_HISTEDIT);
12414 goto done;
12417 error = got_worktree_get_histedit_script_path(&path, worktree);
12418 if (error)
12419 goto done;
12421 error = histedit_load_list(&histedit_cmds, path, repo);
12422 free(path);
12423 if (error)
12424 goto done;
12426 error = got_worktree_histedit_continue(&resume_commit_id,
12427 &tmp_branch, &branch, &base_commit_id, &fileindex,
12428 worktree, repo);
12429 if (error)
12430 goto done;
12432 error = got_ref_resolve(&head_commit_id, repo, branch);
12433 if (error)
12434 goto done;
12436 error = got_object_open_as_commit(&commit, repo,
12437 head_commit_id);
12438 if (error)
12439 goto done;
12440 parent_ids = got_object_commit_get_parent_ids(commit);
12441 pid = STAILQ_FIRST(parent_ids);
12442 if (pid == NULL) {
12443 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12444 goto done;
12446 error = collect_commits(&commits, head_commit_id, &pid->id,
12447 base_commit_id, got_worktree_get_path_prefix(worktree),
12448 GOT_ERR_HISTEDIT_PATH, repo);
12449 got_object_commit_close(commit);
12450 commit = NULL;
12451 if (error)
12452 goto done;
12453 } else {
12454 if (edit_in_progress) {
12455 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12456 goto done;
12459 error = got_ref_open(&branch, repo,
12460 got_worktree_get_head_ref_name(worktree), 0);
12461 if (error != NULL)
12462 goto done;
12464 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12465 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12466 "will not edit commit history of a branch outside "
12467 "the \"refs/heads/\" reference namespace");
12468 goto done;
12471 error = got_ref_resolve(&head_commit_id, repo, branch);
12472 got_ref_close(branch);
12473 branch = NULL;
12474 if (error)
12475 goto done;
12477 error = got_object_open_as_commit(&commit, repo,
12478 head_commit_id);
12479 if (error)
12480 goto done;
12481 parent_ids = got_object_commit_get_parent_ids(commit);
12482 pid = STAILQ_FIRST(parent_ids);
12483 if (pid == NULL) {
12484 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12485 goto done;
12487 error = collect_commits(&commits, head_commit_id, &pid->id,
12488 got_worktree_get_base_commit_id(worktree),
12489 got_worktree_get_path_prefix(worktree),
12490 GOT_ERR_HISTEDIT_PATH, repo);
12491 got_object_commit_close(commit);
12492 commit = NULL;
12493 if (error)
12494 goto done;
12496 if (STAILQ_EMPTY(&commits)) {
12497 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12498 goto done;
12501 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12502 &base_commit_id, &fileindex, worktree, repo);
12503 if (error)
12504 goto done;
12506 if (edit_script_path) {
12507 error = histedit_load_list(&histedit_cmds,
12508 edit_script_path, repo);
12509 if (error) {
12510 got_worktree_histedit_abort(worktree, fileindex,
12511 repo, branch, base_commit_id,
12512 abort_progress, &upa);
12513 print_merge_progress_stats(&upa);
12514 goto done;
12516 } else {
12517 const char *branch_name;
12518 branch_name = got_ref_get_symref_target(branch);
12519 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12520 branch_name += 11;
12521 error = histedit_edit_script(&histedit_cmds, &commits,
12522 branch_name, edit_logmsg_only, fold_only,
12523 edit_only, repo);
12524 if (error) {
12525 got_worktree_histedit_abort(worktree, fileindex,
12526 repo, branch, base_commit_id,
12527 abort_progress, &upa);
12528 print_merge_progress_stats(&upa);
12529 goto done;
12534 error = histedit_save_list(&histedit_cmds, worktree,
12535 repo);
12536 if (error) {
12537 got_worktree_histedit_abort(worktree, fileindex,
12538 repo, branch, base_commit_id,
12539 abort_progress, &upa);
12540 print_merge_progress_stats(&upa);
12541 goto done;
12546 error = histedit_check_script(&histedit_cmds, &commits, repo);
12547 if (error)
12548 goto done;
12550 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12551 if (resume_commit_id) {
12552 if (got_object_id_cmp(hle->commit_id,
12553 resume_commit_id) != 0)
12554 continue;
12556 resume_commit_id = NULL;
12557 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12558 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12559 error = histedit_skip_commit(hle, worktree,
12560 repo);
12561 if (error)
12562 goto done;
12563 } else {
12564 struct got_pathlist_head paths;
12565 int have_changes = 0;
12567 TAILQ_INIT(&paths);
12568 error = got_pathlist_append(&paths, "", NULL);
12569 if (error)
12570 goto done;
12571 error = got_worktree_status(worktree, &paths,
12572 repo, 0, check_local_changes, &have_changes,
12573 check_cancelled, NULL);
12574 got_pathlist_free(&paths,
12575 GOT_PATHLIST_FREE_NONE);
12576 if (error) {
12577 if (error->code != GOT_ERR_CANCELLED)
12578 goto done;
12579 if (sigint_received || sigpipe_received)
12580 goto done;
12582 if (have_changes) {
12583 error = histedit_commit(NULL, worktree,
12584 fileindex, tmp_branch, hle,
12585 committer, repo);
12586 if (error)
12587 goto done;
12588 } else {
12589 error = got_object_open_as_commit(
12590 &commit, repo, hle->commit_id);
12591 if (error)
12592 goto done;
12593 error = show_histedit_progress(commit,
12594 hle, NULL);
12595 got_object_commit_close(commit);
12596 commit = NULL;
12597 if (error)
12598 goto done;
12601 continue;
12604 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12605 error = histedit_skip_commit(hle, worktree, repo);
12606 if (error)
12607 goto done;
12608 continue;
12611 error = got_object_open_as_commit(&commit, repo,
12612 hle->commit_id);
12613 if (error)
12614 goto done;
12615 parent_ids = got_object_commit_get_parent_ids(commit);
12616 pid = STAILQ_FIRST(parent_ids);
12618 error = got_worktree_histedit_merge_files(&merged_paths,
12619 worktree, fileindex, &pid->id, hle->commit_id, repo,
12620 update_progress, &upa, check_cancelled, NULL);
12621 if (error)
12622 goto done;
12623 got_object_commit_close(commit);
12624 commit = NULL;
12626 print_merge_progress_stats(&upa);
12627 if (upa.conflicts > 0 || upa.missing > 0 ||
12628 upa.not_deleted > 0 || upa.unversioned > 0) {
12629 if (upa.conflicts > 0) {
12630 error = show_rebase_merge_conflict(
12631 hle->commit_id, repo);
12632 if (error)
12633 goto done;
12635 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12636 break;
12639 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12640 char *id_str;
12641 error = got_object_id_str(&id_str, hle->commit_id);
12642 if (error)
12643 goto done;
12644 printf("Stopping histedit for amending commit %s\n",
12645 id_str);
12646 free(id_str);
12647 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12648 error = got_worktree_histedit_postpone(worktree,
12649 fileindex);
12650 goto done;
12653 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12654 error = histedit_skip_commit(hle, worktree, repo);
12655 if (error)
12656 goto done;
12657 continue;
12660 error = histedit_commit(&merged_paths, worktree, fileindex,
12661 tmp_branch, hle, committer, repo);
12662 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12663 if (error)
12664 goto done;
12667 if (upa.conflicts > 0 || upa.missing > 0 ||
12668 upa.not_deleted > 0 || upa.unversioned > 0) {
12669 error = got_worktree_histedit_postpone(worktree, fileindex);
12670 if (error)
12671 goto done;
12672 if (upa.conflicts > 0 && upa.missing == 0 &&
12673 upa.not_deleted == 0 && upa.unversioned == 0) {
12674 error = got_error_msg(GOT_ERR_CONFLICTS,
12675 "conflicts must be resolved before histedit "
12676 "can continue");
12677 } else if (upa.conflicts > 0) {
12678 error = got_error_msg(GOT_ERR_CONFLICTS,
12679 "conflicts must be resolved before histedit "
12680 "can continue; changes destined for some "
12681 "files were not yet merged and should be "
12682 "merged manually if required before the "
12683 "histedit operation is continued");
12684 } else {
12685 error = got_error_msg(GOT_ERR_CONFLICTS,
12686 "changes destined for some files were not "
12687 "yet merged and should be merged manually "
12688 "if required before the histedit operation "
12689 "is continued");
12691 } else
12692 error = histedit_complete(worktree, fileindex, tmp_branch,
12693 branch, repo);
12694 done:
12695 free(cwd);
12696 free(committer);
12697 free(gitconfig_path);
12698 got_object_id_queue_free(&commits);
12699 histedit_free_list(&histedit_cmds);
12700 free(head_commit_id);
12701 free(base_commit_id);
12702 free(resume_commit_id);
12703 if (commit)
12704 got_object_commit_close(commit);
12705 if (branch)
12706 got_ref_close(branch);
12707 if (tmp_branch)
12708 got_ref_close(tmp_branch);
12709 if (worktree)
12710 got_worktree_close(worktree);
12711 if (repo) {
12712 const struct got_error *close_err = got_repo_close(repo);
12713 if (error == NULL)
12714 error = close_err;
12716 if (pack_fds) {
12717 const struct got_error *pack_err =
12718 got_repo_pack_fds_close(pack_fds);
12719 if (error == NULL)
12720 error = pack_err;
12722 return error;
12725 __dead static void
12726 usage_integrate(void)
12728 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12729 exit(1);
12732 static const struct got_error *
12733 cmd_integrate(int argc, char *argv[])
12735 const struct got_error *error = NULL;
12736 struct got_repository *repo = NULL;
12737 struct got_worktree *worktree = NULL;
12738 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12739 const char *branch_arg = NULL;
12740 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12741 struct got_fileindex *fileindex = NULL;
12742 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12743 int ch;
12744 struct got_update_progress_arg upa;
12745 int *pack_fds = NULL;
12747 while ((ch = getopt(argc, argv, "")) != -1) {
12748 switch (ch) {
12749 default:
12750 usage_integrate();
12751 /* NOTREACHED */
12755 argc -= optind;
12756 argv += optind;
12758 if (argc != 1)
12759 usage_integrate();
12760 branch_arg = argv[0];
12761 #ifndef PROFILE
12762 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12763 "unveil", NULL) == -1)
12764 err(1, "pledge");
12765 #endif
12766 cwd = getcwd(NULL, 0);
12767 if (cwd == NULL) {
12768 error = got_error_from_errno("getcwd");
12769 goto done;
12772 error = got_repo_pack_fds_open(&pack_fds);
12773 if (error != NULL)
12774 goto done;
12776 error = got_worktree_open(&worktree, cwd);
12777 if (error) {
12778 if (error->code == GOT_ERR_NOT_WORKTREE)
12779 error = wrap_not_worktree_error(error, "integrate",
12780 cwd);
12781 goto done;
12784 error = check_rebase_or_histedit_in_progress(worktree);
12785 if (error)
12786 goto done;
12788 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12789 NULL, pack_fds);
12790 if (error != NULL)
12791 goto done;
12793 error = apply_unveil(got_repo_get_path(repo), 0,
12794 got_worktree_get_root_path(worktree));
12795 if (error)
12796 goto done;
12798 error = check_merge_in_progress(worktree, repo);
12799 if (error)
12800 goto done;
12802 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12803 error = got_error_from_errno("asprintf");
12804 goto done;
12807 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12808 &base_branch_ref, worktree, refname, repo);
12809 if (error)
12810 goto done;
12812 refname = strdup(got_ref_get_name(branch_ref));
12813 if (refname == NULL) {
12814 error = got_error_from_errno("strdup");
12815 got_worktree_integrate_abort(worktree, fileindex, repo,
12816 branch_ref, base_branch_ref);
12817 goto done;
12819 base_refname = strdup(got_ref_get_name(base_branch_ref));
12820 if (base_refname == NULL) {
12821 error = got_error_from_errno("strdup");
12822 got_worktree_integrate_abort(worktree, fileindex, repo,
12823 branch_ref, base_branch_ref);
12824 goto done;
12826 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12827 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12828 got_worktree_integrate_abort(worktree, fileindex, repo,
12829 branch_ref, base_branch_ref);
12830 goto done;
12833 error = got_ref_resolve(&commit_id, repo, branch_ref);
12834 if (error)
12835 goto done;
12837 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12838 if (error)
12839 goto done;
12841 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12842 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12843 "specified branch has already been integrated");
12844 got_worktree_integrate_abort(worktree, fileindex, repo,
12845 branch_ref, base_branch_ref);
12846 goto done;
12849 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12850 if (error) {
12851 if (error->code == GOT_ERR_ANCESTRY)
12852 error = got_error(GOT_ERR_REBASE_REQUIRED);
12853 got_worktree_integrate_abort(worktree, fileindex, repo,
12854 branch_ref, base_branch_ref);
12855 goto done;
12858 memset(&upa, 0, sizeof(upa));
12859 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12860 branch_ref, base_branch_ref, update_progress, &upa,
12861 check_cancelled, NULL);
12862 if (error)
12863 goto done;
12865 printf("Integrated %s into %s\n", refname, base_refname);
12866 print_update_progress_stats(&upa);
12867 done:
12868 if (repo) {
12869 const struct got_error *close_err = got_repo_close(repo);
12870 if (error == NULL)
12871 error = close_err;
12873 if (worktree)
12874 got_worktree_close(worktree);
12875 if (pack_fds) {
12876 const struct got_error *pack_err =
12877 got_repo_pack_fds_close(pack_fds);
12878 if (error == NULL)
12879 error = pack_err;
12881 free(cwd);
12882 free(base_commit_id);
12883 free(commit_id);
12884 free(refname);
12885 free(base_refname);
12886 return error;
12889 __dead static void
12890 usage_merge(void)
12892 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12893 exit(1);
12896 static const struct got_error *
12897 cmd_merge(int argc, char *argv[])
12899 const struct got_error *error = NULL;
12900 struct got_worktree *worktree = NULL;
12901 struct got_repository *repo = NULL;
12902 struct got_fileindex *fileindex = NULL;
12903 char *cwd = NULL, *id_str = NULL, *author = NULL;
12904 struct got_reference *branch = NULL, *wt_branch = NULL;
12905 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12906 struct got_object_id *wt_branch_tip = NULL;
12907 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12908 int interrupt_merge = 0;
12909 struct got_update_progress_arg upa;
12910 struct got_object_id *merge_commit_id = NULL;
12911 char *branch_name = NULL;
12912 int *pack_fds = NULL;
12914 memset(&upa, 0, sizeof(upa));
12916 while ((ch = getopt(argc, argv, "acn")) != -1) {
12917 switch (ch) {
12918 case 'a':
12919 abort_merge = 1;
12920 break;
12921 case 'c':
12922 continue_merge = 1;
12923 break;
12924 case 'n':
12925 interrupt_merge = 1;
12926 break;
12927 default:
12928 usage_merge();
12929 /* NOTREACHED */
12933 argc -= optind;
12934 argv += optind;
12936 #ifndef PROFILE
12937 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12938 "unveil", NULL) == -1)
12939 err(1, "pledge");
12940 #endif
12942 if (abort_merge && continue_merge)
12943 option_conflict('a', 'c');
12944 if (abort_merge || continue_merge) {
12945 if (argc != 0)
12946 usage_merge();
12947 } else if (argc != 1)
12948 usage_merge();
12950 cwd = getcwd(NULL, 0);
12951 if (cwd == NULL) {
12952 error = got_error_from_errno("getcwd");
12953 goto done;
12956 error = got_repo_pack_fds_open(&pack_fds);
12957 if (error != NULL)
12958 goto done;
12960 error = got_worktree_open(&worktree, cwd);
12961 if (error) {
12962 if (error->code == GOT_ERR_NOT_WORKTREE)
12963 error = wrap_not_worktree_error(error,
12964 "merge", cwd);
12965 goto done;
12968 error = got_repo_open(&repo,
12969 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12970 pack_fds);
12971 if (error != NULL)
12972 goto done;
12974 if (worktree != NULL) {
12975 error = worktree_has_logmsg_ref("merge", worktree, repo);
12976 if (error)
12977 goto done;
12980 error = apply_unveil(got_repo_get_path(repo), 0,
12981 worktree ? got_worktree_get_root_path(worktree) : NULL);
12982 if (error)
12983 goto done;
12985 error = check_rebase_or_histedit_in_progress(worktree);
12986 if (error)
12987 goto done;
12989 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12990 repo);
12991 if (error)
12992 goto done;
12994 if (abort_merge) {
12995 if (!merge_in_progress) {
12996 error = got_error(GOT_ERR_NOT_MERGING);
12997 goto done;
12999 error = got_worktree_merge_continue(&branch_name,
13000 &branch_tip, &fileindex, worktree, repo);
13001 if (error)
13002 goto done;
13003 error = got_worktree_merge_abort(worktree, fileindex, repo,
13004 abort_progress, &upa);
13005 if (error)
13006 goto done;
13007 printf("Merge of %s aborted\n", branch_name);
13008 goto done; /* nothing else to do */
13011 error = get_author(&author, repo, worktree);
13012 if (error)
13013 goto done;
13015 if (continue_merge) {
13016 if (!merge_in_progress) {
13017 error = got_error(GOT_ERR_NOT_MERGING);
13018 goto done;
13020 error = got_worktree_merge_continue(&branch_name,
13021 &branch_tip, &fileindex, worktree, repo);
13022 if (error)
13023 goto done;
13024 } else {
13025 error = got_ref_open(&branch, repo, argv[0], 0);
13026 if (error != NULL)
13027 goto done;
13028 branch_name = strdup(got_ref_get_name(branch));
13029 if (branch_name == NULL) {
13030 error = got_error_from_errno("strdup");
13031 goto done;
13033 error = got_ref_resolve(&branch_tip, repo, branch);
13034 if (error)
13035 goto done;
13038 error = got_ref_open(&wt_branch, repo,
13039 got_worktree_get_head_ref_name(worktree), 0);
13040 if (error)
13041 goto done;
13042 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13043 if (error)
13044 goto done;
13045 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13046 wt_branch_tip, branch_tip, 0, repo,
13047 check_cancelled, NULL);
13048 if (error && error->code != GOT_ERR_ANCESTRY)
13049 goto done;
13051 if (!continue_merge) {
13052 error = check_path_prefix(wt_branch_tip, branch_tip,
13053 got_worktree_get_path_prefix(worktree),
13054 GOT_ERR_MERGE_PATH, repo);
13055 if (error)
13056 goto done;
13057 if (yca_id) {
13058 error = check_same_branch(wt_branch_tip, branch,
13059 yca_id, repo);
13060 if (error) {
13061 if (error->code != GOT_ERR_ANCESTRY)
13062 goto done;
13063 error = NULL;
13064 } else {
13065 static char msg[512];
13066 snprintf(msg, sizeof(msg),
13067 "cannot create a merge commit because "
13068 "%s is based on %s; %s can be integrated "
13069 "with 'got integrate' instead", branch_name,
13070 got_worktree_get_head_ref_name(worktree),
13071 branch_name);
13072 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13073 goto done;
13076 error = got_worktree_merge_prepare(&fileindex, worktree,
13077 branch, repo);
13078 if (error)
13079 goto done;
13081 error = got_worktree_merge_branch(worktree, fileindex,
13082 yca_id, branch_tip, repo, update_progress, &upa,
13083 check_cancelled, NULL);
13084 if (error)
13085 goto done;
13086 print_merge_progress_stats(&upa);
13087 if (!upa.did_something) {
13088 error = got_worktree_merge_abort(worktree, fileindex,
13089 repo, abort_progress, &upa);
13090 if (error)
13091 goto done;
13092 printf("Already up-to-date\n");
13093 goto done;
13097 if (interrupt_merge) {
13098 error = got_worktree_merge_postpone(worktree, fileindex);
13099 if (error)
13100 goto done;
13101 printf("Merge of %s interrupted on request\n", branch_name);
13102 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13103 upa.not_deleted > 0 || upa.unversioned > 0) {
13104 error = got_worktree_merge_postpone(worktree, fileindex);
13105 if (error)
13106 goto done;
13107 if (upa.conflicts > 0 && upa.missing == 0 &&
13108 upa.not_deleted == 0 && upa.unversioned == 0) {
13109 error = got_error_msg(GOT_ERR_CONFLICTS,
13110 "conflicts must be resolved before merging "
13111 "can continue");
13112 } else if (upa.conflicts > 0) {
13113 error = got_error_msg(GOT_ERR_CONFLICTS,
13114 "conflicts must be resolved before merging "
13115 "can continue; changes destined for some "
13116 "files were not yet merged and "
13117 "should be merged manually if required before the "
13118 "merge operation is continued");
13119 } else {
13120 error = got_error_msg(GOT_ERR_CONFLICTS,
13121 "changes destined for some "
13122 "files were not yet merged and should be "
13123 "merged manually if required before the "
13124 "merge operation is continued");
13126 goto done;
13127 } else {
13128 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13129 fileindex, author, NULL, 1, branch_tip, branch_name,
13130 repo, continue_merge ? print_status : NULL, NULL);
13131 if (error)
13132 goto done;
13133 error = got_worktree_merge_complete(worktree, fileindex, repo);
13134 if (error)
13135 goto done;
13136 error = got_object_id_str(&id_str, merge_commit_id);
13137 if (error)
13138 goto done;
13139 printf("Merged %s into %s: %s\n", branch_name,
13140 got_worktree_get_head_ref_name(worktree),
13141 id_str);
13144 done:
13145 free(id_str);
13146 free(merge_commit_id);
13147 free(author);
13148 free(branch_tip);
13149 free(branch_name);
13150 free(yca_id);
13151 if (branch)
13152 got_ref_close(branch);
13153 if (wt_branch)
13154 got_ref_close(wt_branch);
13155 if (worktree)
13156 got_worktree_close(worktree);
13157 if (repo) {
13158 const struct got_error *close_err = got_repo_close(repo);
13159 if (error == NULL)
13160 error = close_err;
13162 if (pack_fds) {
13163 const struct got_error *pack_err =
13164 got_repo_pack_fds_close(pack_fds);
13165 if (error == NULL)
13166 error = pack_err;
13168 return error;
13171 __dead static void
13172 usage_stage(void)
13174 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13175 "[path ...]\n", getprogname());
13176 exit(1);
13179 static const struct got_error *
13180 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13181 const char *path, struct got_object_id *blob_id,
13182 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13183 int dirfd, const char *de_name)
13185 const struct got_error *err = NULL;
13186 char *id_str = NULL;
13188 if (staged_status != GOT_STATUS_ADD &&
13189 staged_status != GOT_STATUS_MODIFY &&
13190 staged_status != GOT_STATUS_DELETE)
13191 return NULL;
13193 if (staged_status == GOT_STATUS_ADD ||
13194 staged_status == GOT_STATUS_MODIFY)
13195 err = got_object_id_str(&id_str, staged_blob_id);
13196 else
13197 err = got_object_id_str(&id_str, blob_id);
13198 if (err)
13199 return err;
13201 printf("%s %c %s\n", id_str, staged_status, path);
13202 free(id_str);
13203 return NULL;
13206 static const struct got_error *
13207 cmd_stage(int argc, char *argv[])
13209 const struct got_error *error = NULL;
13210 struct got_repository *repo = NULL;
13211 struct got_worktree *worktree = NULL;
13212 char *cwd = NULL;
13213 struct got_pathlist_head paths;
13214 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13215 FILE *patch_script_file = NULL;
13216 const char *patch_script_path = NULL;
13217 struct choose_patch_arg cpa;
13218 int *pack_fds = NULL;
13220 TAILQ_INIT(&paths);
13222 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13223 switch (ch) {
13224 case 'F':
13225 patch_script_path = optarg;
13226 break;
13227 case 'l':
13228 list_stage = 1;
13229 break;
13230 case 'p':
13231 pflag = 1;
13232 break;
13233 case 'S':
13234 allow_bad_symlinks = 1;
13235 break;
13236 default:
13237 usage_stage();
13238 /* NOTREACHED */
13242 argc -= optind;
13243 argv += optind;
13245 #ifndef PROFILE
13246 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13247 "unveil", NULL) == -1)
13248 err(1, "pledge");
13249 #endif
13250 if (list_stage && (pflag || patch_script_path))
13251 errx(1, "-l option cannot be used with other options");
13252 if (patch_script_path && !pflag)
13253 errx(1, "-F option can only be used together with -p option");
13255 cwd = getcwd(NULL, 0);
13256 if (cwd == NULL) {
13257 error = got_error_from_errno("getcwd");
13258 goto done;
13261 error = got_repo_pack_fds_open(&pack_fds);
13262 if (error != NULL)
13263 goto done;
13265 error = got_worktree_open(&worktree, cwd);
13266 if (error) {
13267 if (error->code == GOT_ERR_NOT_WORKTREE)
13268 error = wrap_not_worktree_error(error, "stage", cwd);
13269 goto done;
13272 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13273 NULL, pack_fds);
13274 if (error != NULL)
13275 goto done;
13277 if (patch_script_path) {
13278 patch_script_file = fopen(patch_script_path, "re");
13279 if (patch_script_file == NULL) {
13280 error = got_error_from_errno2("fopen",
13281 patch_script_path);
13282 goto done;
13285 error = apply_unveil(got_repo_get_path(repo), 0,
13286 got_worktree_get_root_path(worktree));
13287 if (error)
13288 goto done;
13290 error = check_merge_in_progress(worktree, repo);
13291 if (error)
13292 goto done;
13294 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13295 if (error)
13296 goto done;
13298 if (list_stage)
13299 error = got_worktree_status(worktree, &paths, repo, 0,
13300 print_stage, NULL, check_cancelled, NULL);
13301 else {
13302 cpa.patch_script_file = patch_script_file;
13303 cpa.action = "stage";
13304 error = got_worktree_stage(worktree, &paths,
13305 pflag ? NULL : print_status, NULL,
13306 pflag ? choose_patch : NULL, &cpa,
13307 allow_bad_symlinks, repo);
13309 done:
13310 if (patch_script_file && fclose(patch_script_file) == EOF &&
13311 error == NULL)
13312 error = got_error_from_errno2("fclose", patch_script_path);
13313 if (repo) {
13314 const struct got_error *close_err = got_repo_close(repo);
13315 if (error == NULL)
13316 error = close_err;
13318 if (worktree)
13319 got_worktree_close(worktree);
13320 if (pack_fds) {
13321 const struct got_error *pack_err =
13322 got_repo_pack_fds_close(pack_fds);
13323 if (error == NULL)
13324 error = pack_err;
13326 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13327 free(cwd);
13328 return error;
13331 __dead static void
13332 usage_unstage(void)
13334 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13335 "[path ...]\n", getprogname());
13336 exit(1);
13340 static const struct got_error *
13341 cmd_unstage(int argc, char *argv[])
13343 const struct got_error *error = NULL;
13344 struct got_repository *repo = NULL;
13345 struct got_worktree *worktree = NULL;
13346 char *cwd = NULL;
13347 struct got_pathlist_head paths;
13348 int ch, pflag = 0;
13349 struct got_update_progress_arg upa;
13350 FILE *patch_script_file = NULL;
13351 const char *patch_script_path = NULL;
13352 struct choose_patch_arg cpa;
13353 int *pack_fds = NULL;
13355 TAILQ_INIT(&paths);
13357 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13358 switch (ch) {
13359 case 'F':
13360 patch_script_path = optarg;
13361 break;
13362 case 'p':
13363 pflag = 1;
13364 break;
13365 default:
13366 usage_unstage();
13367 /* NOTREACHED */
13371 argc -= optind;
13372 argv += optind;
13374 #ifndef PROFILE
13375 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13376 "unveil", NULL) == -1)
13377 err(1, "pledge");
13378 #endif
13379 if (patch_script_path && !pflag)
13380 errx(1, "-F option can only be used together with -p option");
13382 cwd = getcwd(NULL, 0);
13383 if (cwd == NULL) {
13384 error = got_error_from_errno("getcwd");
13385 goto done;
13388 error = got_repo_pack_fds_open(&pack_fds);
13389 if (error != NULL)
13390 goto done;
13392 error = got_worktree_open(&worktree, cwd);
13393 if (error) {
13394 if (error->code == GOT_ERR_NOT_WORKTREE)
13395 error = wrap_not_worktree_error(error, "unstage", cwd);
13396 goto done;
13399 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13400 NULL, pack_fds);
13401 if (error != NULL)
13402 goto done;
13404 if (patch_script_path) {
13405 patch_script_file = fopen(patch_script_path, "re");
13406 if (patch_script_file == NULL) {
13407 error = got_error_from_errno2("fopen",
13408 patch_script_path);
13409 goto done;
13413 error = apply_unveil(got_repo_get_path(repo), 0,
13414 got_worktree_get_root_path(worktree));
13415 if (error)
13416 goto done;
13418 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13419 if (error)
13420 goto done;
13422 cpa.patch_script_file = patch_script_file;
13423 cpa.action = "unstage";
13424 memset(&upa, 0, sizeof(upa));
13425 error = got_worktree_unstage(worktree, &paths, update_progress,
13426 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13427 if (!error)
13428 print_merge_progress_stats(&upa);
13429 done:
13430 if (patch_script_file && fclose(patch_script_file) == EOF &&
13431 error == NULL)
13432 error = got_error_from_errno2("fclose", patch_script_path);
13433 if (repo) {
13434 const struct got_error *close_err = got_repo_close(repo);
13435 if (error == NULL)
13436 error = close_err;
13438 if (worktree)
13439 got_worktree_close(worktree);
13440 if (pack_fds) {
13441 const struct got_error *pack_err =
13442 got_repo_pack_fds_close(pack_fds);
13443 if (error == NULL)
13444 error = pack_err;
13446 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13447 free(cwd);
13448 return error;
13451 __dead static void
13452 usage_cat(void)
13454 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13455 "arg ...\n", getprogname());
13456 exit(1);
13459 static const struct got_error *
13460 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13462 const struct got_error *err;
13463 struct got_blob_object *blob;
13464 int fd = -1;
13466 fd = got_opentempfd();
13467 if (fd == -1)
13468 return got_error_from_errno("got_opentempfd");
13470 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13471 if (err)
13472 goto done;
13474 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13475 done:
13476 if (fd != -1 && close(fd) == -1 && err == NULL)
13477 err = got_error_from_errno("close");
13478 if (blob)
13479 got_object_blob_close(blob);
13480 return err;
13483 static const struct got_error *
13484 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13486 const struct got_error *err;
13487 struct got_tree_object *tree;
13488 int nentries, i;
13490 err = got_object_open_as_tree(&tree, repo, id);
13491 if (err)
13492 return err;
13494 nentries = got_object_tree_get_nentries(tree);
13495 for (i = 0; i < nentries; i++) {
13496 struct got_tree_entry *te;
13497 char *id_str;
13498 if (sigint_received || sigpipe_received)
13499 break;
13500 te = got_object_tree_get_entry(tree, i);
13501 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13502 if (err)
13503 break;
13504 fprintf(outfile, "%s %.7o %s\n", id_str,
13505 got_tree_entry_get_mode(te),
13506 got_tree_entry_get_name(te));
13507 free(id_str);
13510 got_object_tree_close(tree);
13511 return err;
13514 static const struct got_error *
13515 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13517 const struct got_error *err;
13518 struct got_commit_object *commit;
13519 const struct got_object_id_queue *parent_ids;
13520 struct got_object_qid *pid;
13521 char *id_str = NULL;
13522 const char *logmsg = NULL;
13523 char gmtoff[6];
13525 err = got_object_open_as_commit(&commit, repo, id);
13526 if (err)
13527 return err;
13529 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13530 if (err)
13531 goto done;
13533 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13534 parent_ids = got_object_commit_get_parent_ids(commit);
13535 fprintf(outfile, "numparents %d\n",
13536 got_object_commit_get_nparents(commit));
13537 STAILQ_FOREACH(pid, parent_ids, entry) {
13538 char *pid_str;
13539 err = got_object_id_str(&pid_str, &pid->id);
13540 if (err)
13541 goto done;
13542 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13543 free(pid_str);
13545 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13546 got_object_commit_get_author_gmtoff(commit));
13547 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13548 got_object_commit_get_author(commit),
13549 (long long)got_object_commit_get_author_time(commit),
13550 gmtoff);
13552 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13553 got_object_commit_get_committer_gmtoff(commit));
13554 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13555 got_object_commit_get_committer(commit),
13556 (long long)got_object_commit_get_committer_time(commit),
13557 gmtoff);
13559 logmsg = got_object_commit_get_logmsg_raw(commit);
13560 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13561 fprintf(outfile, "%s", logmsg);
13562 done:
13563 free(id_str);
13564 got_object_commit_close(commit);
13565 return err;
13568 static const struct got_error *
13569 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13571 const struct got_error *err;
13572 struct got_tag_object *tag;
13573 char *id_str = NULL;
13574 const char *tagmsg = NULL;
13575 char gmtoff[6];
13577 err = got_object_open_as_tag(&tag, repo, id);
13578 if (err)
13579 return err;
13581 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13582 if (err)
13583 goto done;
13585 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13587 switch (got_object_tag_get_object_type(tag)) {
13588 case GOT_OBJ_TYPE_BLOB:
13589 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13590 GOT_OBJ_LABEL_BLOB);
13591 break;
13592 case GOT_OBJ_TYPE_TREE:
13593 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13594 GOT_OBJ_LABEL_TREE);
13595 break;
13596 case GOT_OBJ_TYPE_COMMIT:
13597 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13598 GOT_OBJ_LABEL_COMMIT);
13599 break;
13600 case GOT_OBJ_TYPE_TAG:
13601 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13602 GOT_OBJ_LABEL_TAG);
13603 break;
13604 default:
13605 break;
13608 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13609 got_object_tag_get_name(tag));
13611 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13612 got_object_tag_get_tagger_gmtoff(tag));
13613 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13614 got_object_tag_get_tagger(tag),
13615 (long long)got_object_tag_get_tagger_time(tag),
13616 gmtoff);
13618 tagmsg = got_object_tag_get_message(tag);
13619 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13620 fprintf(outfile, "%s", tagmsg);
13621 done:
13622 free(id_str);
13623 got_object_tag_close(tag);
13624 return err;
13627 static const struct got_error *
13628 cmd_cat(int argc, char *argv[])
13630 const struct got_error *error;
13631 struct got_repository *repo = NULL;
13632 struct got_worktree *worktree = NULL;
13633 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13634 const char *commit_id_str = NULL;
13635 struct got_object_id *id = NULL, *commit_id = NULL;
13636 struct got_commit_object *commit = NULL;
13637 int ch, obj_type, i, force_path = 0;
13638 struct got_reflist_head refs;
13639 int *pack_fds = NULL;
13641 TAILQ_INIT(&refs);
13643 #ifndef PROFILE
13644 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13645 NULL) == -1)
13646 err(1, "pledge");
13647 #endif
13649 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13650 switch (ch) {
13651 case 'c':
13652 commit_id_str = optarg;
13653 break;
13654 case 'P':
13655 force_path = 1;
13656 break;
13657 case 'r':
13658 repo_path = realpath(optarg, NULL);
13659 if (repo_path == NULL)
13660 return got_error_from_errno2("realpath",
13661 optarg);
13662 got_path_strip_trailing_slashes(repo_path);
13663 break;
13664 default:
13665 usage_cat();
13666 /* NOTREACHED */
13670 argc -= optind;
13671 argv += optind;
13673 cwd = getcwd(NULL, 0);
13674 if (cwd == NULL) {
13675 error = got_error_from_errno("getcwd");
13676 goto done;
13679 error = got_repo_pack_fds_open(&pack_fds);
13680 if (error != NULL)
13681 goto done;
13683 if (repo_path == NULL) {
13684 error = got_worktree_open(&worktree, cwd);
13685 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13686 goto done;
13687 if (worktree) {
13688 repo_path = strdup(
13689 got_worktree_get_repo_path(worktree));
13690 if (repo_path == NULL) {
13691 error = got_error_from_errno("strdup");
13692 goto done;
13695 /* Release work tree lock. */
13696 got_worktree_close(worktree);
13697 worktree = NULL;
13701 if (repo_path == NULL) {
13702 repo_path = strdup(cwd);
13703 if (repo_path == NULL)
13704 return got_error_from_errno("strdup");
13707 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13708 free(repo_path);
13709 if (error != NULL)
13710 goto done;
13712 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13713 if (error)
13714 goto done;
13716 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13717 if (error)
13718 goto done;
13720 if (commit_id_str == NULL)
13721 commit_id_str = GOT_REF_HEAD;
13722 error = got_repo_match_object_id(&commit_id, NULL,
13723 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13724 if (error)
13725 goto done;
13727 error = got_object_open_as_commit(&commit, repo, commit_id);
13728 if (error)
13729 goto done;
13731 for (i = 0; i < argc; i++) {
13732 if (force_path) {
13733 error = got_object_id_by_path(&id, repo, commit,
13734 argv[i]);
13735 if (error)
13736 break;
13737 } else {
13738 error = got_repo_match_object_id(&id, &label, argv[i],
13739 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13740 repo);
13741 if (error) {
13742 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13743 error->code != GOT_ERR_NOT_REF)
13744 break;
13745 error = got_object_id_by_path(&id, repo,
13746 commit, argv[i]);
13747 if (error)
13748 break;
13752 error = got_object_get_type(&obj_type, repo, id);
13753 if (error)
13754 break;
13756 switch (obj_type) {
13757 case GOT_OBJ_TYPE_BLOB:
13758 error = cat_blob(id, repo, stdout);
13759 break;
13760 case GOT_OBJ_TYPE_TREE:
13761 error = cat_tree(id, repo, stdout);
13762 break;
13763 case GOT_OBJ_TYPE_COMMIT:
13764 error = cat_commit(id, repo, stdout);
13765 break;
13766 case GOT_OBJ_TYPE_TAG:
13767 error = cat_tag(id, repo, stdout);
13768 break;
13769 default:
13770 error = got_error(GOT_ERR_OBJ_TYPE);
13771 break;
13773 if (error)
13774 break;
13775 free(label);
13776 label = NULL;
13777 free(id);
13778 id = NULL;
13780 done:
13781 free(label);
13782 free(id);
13783 free(commit_id);
13784 if (commit)
13785 got_object_commit_close(commit);
13786 if (worktree)
13787 got_worktree_close(worktree);
13788 if (repo) {
13789 const struct got_error *close_err = got_repo_close(repo);
13790 if (error == NULL)
13791 error = close_err;
13793 if (pack_fds) {
13794 const struct got_error *pack_err =
13795 got_repo_pack_fds_close(pack_fds);
13796 if (error == NULL)
13797 error = pack_err;
13800 got_ref_list_free(&refs);
13801 return error;
13804 __dead static void
13805 usage_info(void)
13807 fprintf(stderr, "usage: %s info [path ...]\n",
13808 getprogname());
13809 exit(1);
13812 static const struct got_error *
13813 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13814 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13815 struct got_object_id *commit_id)
13817 const struct got_error *err = NULL;
13818 char *id_str = NULL;
13819 char datebuf[128];
13820 struct tm mytm, *tm;
13821 struct got_pathlist_head *paths = arg;
13822 struct got_pathlist_entry *pe;
13825 * Clear error indication from any of the path arguments which
13826 * would cause this file index entry to be displayed.
13828 TAILQ_FOREACH(pe, paths, entry) {
13829 if (got_path_cmp(path, pe->path, strlen(path),
13830 pe->path_len) == 0 ||
13831 got_path_is_child(path, pe->path, pe->path_len))
13832 pe->data = NULL; /* no error */
13835 printf(GOT_COMMIT_SEP_STR);
13836 if (S_ISLNK(mode))
13837 printf("symlink: %s\n", path);
13838 else if (S_ISREG(mode)) {
13839 printf("file: %s\n", path);
13840 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13841 } else if (S_ISDIR(mode))
13842 printf("directory: %s\n", path);
13843 else
13844 printf("something: %s\n", path);
13846 tm = localtime_r(&mtime, &mytm);
13847 if (tm == NULL)
13848 return NULL;
13849 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13850 return got_error(GOT_ERR_NO_SPACE);
13851 printf("timestamp: %s\n", datebuf);
13853 if (blob_id) {
13854 err = got_object_id_str(&id_str, blob_id);
13855 if (err)
13856 return err;
13857 printf("based on blob: %s\n", id_str);
13858 free(id_str);
13861 if (staged_blob_id) {
13862 err = got_object_id_str(&id_str, staged_blob_id);
13863 if (err)
13864 return err;
13865 printf("based on staged blob: %s\n", id_str);
13866 free(id_str);
13869 if (commit_id) {
13870 err = got_object_id_str(&id_str, commit_id);
13871 if (err)
13872 return err;
13873 printf("based on commit: %s\n", id_str);
13874 free(id_str);
13877 return NULL;
13880 static const struct got_error *
13881 cmd_info(int argc, char *argv[])
13883 const struct got_error *error = NULL;
13884 struct got_worktree *worktree = NULL;
13885 char *cwd = NULL, *id_str = NULL;
13886 struct got_pathlist_head paths;
13887 char *uuidstr = NULL;
13888 int ch, show_files = 0;
13890 TAILQ_INIT(&paths);
13892 while ((ch = getopt(argc, argv, "")) != -1) {
13893 switch (ch) {
13894 default:
13895 usage_info();
13896 /* NOTREACHED */
13900 argc -= optind;
13901 argv += optind;
13903 #ifndef PROFILE
13904 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13905 NULL) == -1)
13906 err(1, "pledge");
13907 #endif
13908 cwd = getcwd(NULL, 0);
13909 if (cwd == NULL) {
13910 error = got_error_from_errno("getcwd");
13911 goto done;
13914 error = got_worktree_open(&worktree, cwd);
13915 if (error) {
13916 if (error->code == GOT_ERR_NOT_WORKTREE)
13917 error = wrap_not_worktree_error(error, "info", cwd);
13918 goto done;
13921 #ifndef PROFILE
13922 /* Remove "wpath cpath proc exec sendfd" promises. */
13923 if (pledge("stdio rpath flock unveil", NULL) == -1)
13924 err(1, "pledge");
13925 #endif
13926 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13927 if (error)
13928 goto done;
13930 if (argc >= 1) {
13931 error = get_worktree_paths_from_argv(&paths, argc, argv,
13932 worktree);
13933 if (error)
13934 goto done;
13935 show_files = 1;
13938 error = got_object_id_str(&id_str,
13939 got_worktree_get_base_commit_id(worktree));
13940 if (error)
13941 goto done;
13943 error = got_worktree_get_uuid(&uuidstr, worktree);
13944 if (error)
13945 goto done;
13947 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13948 printf("work tree base commit: %s\n", id_str);
13949 printf("work tree path prefix: %s\n",
13950 got_worktree_get_path_prefix(worktree));
13951 printf("work tree branch reference: %s\n",
13952 got_worktree_get_head_ref_name(worktree));
13953 printf("work tree UUID: %s\n", uuidstr);
13954 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13956 if (show_files) {
13957 struct got_pathlist_entry *pe;
13958 TAILQ_FOREACH(pe, &paths, entry) {
13959 if (pe->path_len == 0)
13960 continue;
13962 * Assume this path will fail. This will be corrected
13963 * in print_path_info() in case the path does suceeed.
13965 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13967 error = got_worktree_path_info(worktree, &paths,
13968 print_path_info, &paths, check_cancelled, NULL);
13969 if (error)
13970 goto done;
13971 TAILQ_FOREACH(pe, &paths, entry) {
13972 if (pe->data != NULL) {
13973 const struct got_error *perr;
13975 perr = pe->data;
13976 error = got_error_fmt(perr->code, "%s",
13977 pe->path);
13978 break;
13982 done:
13983 if (worktree)
13984 got_worktree_close(worktree);
13985 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13986 free(cwd);
13987 free(id_str);
13988 free(uuidstr);
13989 return error;