Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const struct got_error *
713 get_signer_id(char **signer_id, struct got_repository *repo,
714 struct got_worktree *worktree)
716 const char *got_signer_id = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 *signer_id = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 if (got_signer_id) {
738 *signer_id = strdup(got_signer_id);
739 if (*signer_id == NULL)
740 return got_error_from_errno("strdup");
742 return NULL;
745 static const struct got_error *
746 get_gitconfig_path(char **gitconfig_path)
748 const char *homedir = getenv("HOME");
750 *gitconfig_path = NULL;
751 if (homedir) {
752 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
753 return got_error_from_errno("asprintf");
756 return NULL;
759 static const struct got_error *
760 cmd_import(int argc, char *argv[])
762 const struct got_error *error = NULL;
763 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
764 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
765 const char *branch_name = NULL;
766 char *id_str = NULL, *logmsg_path = NULL;
767 char refname[PATH_MAX] = "refs/heads/";
768 struct got_repository *repo = NULL;
769 struct got_reference *branch_ref = NULL, *head_ref = NULL;
770 struct got_object_id *new_commit_id = NULL;
771 int ch, n = 0;
772 struct got_pathlist_head ignores;
773 struct got_pathlist_entry *pe;
774 int preserve_logmsg = 0;
775 int *pack_fds = NULL;
777 TAILQ_INIT(&ignores);
779 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
780 switch (ch) {
781 case 'b':
782 branch_name = optarg;
783 break;
784 case 'I':
785 if (optarg[0] == '\0')
786 break;
787 error = got_pathlist_insert(&pe, &ignores, optarg,
788 NULL);
789 if (error)
790 goto done;
791 break;
792 case 'm':
793 logmsg = strdup(optarg);
794 if (logmsg == NULL) {
795 error = got_error_from_errno("strdup");
796 goto done;
798 break;
799 case 'r':
800 repo_path = realpath(optarg, NULL);
801 if (repo_path == NULL) {
802 error = got_error_from_errno2("realpath",
803 optarg);
804 goto done;
806 break;
807 default:
808 usage_import();
809 /* NOTREACHED */
813 argc -= optind;
814 argv += optind;
816 #ifndef PROFILE
817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
818 "unveil",
819 NULL) == -1)
820 err(1, "pledge");
821 #endif
822 if (argc != 1)
823 usage_import();
825 if (repo_path == NULL) {
826 repo_path = getcwd(NULL, 0);
827 if (repo_path == NULL)
828 return got_error_from_errno("getcwd");
830 got_path_strip_trailing_slashes(repo_path);
831 error = get_gitconfig_path(&gitconfig_path);
832 if (error)
833 goto done;
834 error = got_repo_pack_fds_open(&pack_fds);
835 if (error != NULL)
836 goto done;
837 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
838 if (error)
839 goto done;
841 error = get_author(&author, repo, NULL);
842 if (error)
843 return error;
845 /*
846 * Don't let the user create a branch name with a leading '-'.
847 * While technically a valid reference name, this case is usually
848 * an unintended typo.
849 */
850 if (branch_name && branch_name[0] == '-')
851 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
854 if (error && error->code != GOT_ERR_NOT_REF)
855 goto done;
857 if (branch_name)
858 n = strlcat(refname, branch_name, sizeof(refname));
859 else if (head_ref && got_ref_is_symbolic(head_ref))
860 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
861 sizeof(refname));
862 else
863 n = strlcat(refname, "main", sizeof(refname));
864 if (n >= sizeof(refname)) {
865 error = got_error(GOT_ERR_NO_SPACE);
866 goto done;
869 error = got_ref_open(&branch_ref, repo, refname, 0);
870 if (error) {
871 if (error->code != GOT_ERR_NOT_REF)
872 goto done;
873 } else {
874 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
875 "import target branch already exists");
876 goto done;
879 path_dir = realpath(argv[0], NULL);
880 if (path_dir == NULL) {
881 error = got_error_from_errno2("realpath", argv[0]);
882 goto done;
884 got_path_strip_trailing_slashes(path_dir);
886 /*
887 * unveil(2) traverses exec(2); if an editor is used we have
888 * to apply unveil after the log message has been written.
889 */
890 if (logmsg == NULL || strlen(logmsg) == 0) {
891 error = get_editor(&editor);
892 if (error)
893 goto done;
894 free(logmsg);
895 error = collect_import_msg(&logmsg, &logmsg_path, editor,
896 path_dir, refname);
897 if (error) {
898 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
899 logmsg_path != NULL)
900 preserve_logmsg = 1;
901 goto done;
905 if (unveil(path_dir, "r") != 0) {
906 error = got_error_from_errno2("unveil", path_dir);
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_repo_import(&new_commit_id, path_dir, logmsg,
920 author, &ignores, repo, import_progress, NULL);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_write(branch_ref, repo);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_object_id_str(&id_str, new_commit_id);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
949 if (error) {
950 if (error->code != GOT_ERR_NOT_REF) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
957 branch_ref);
958 if (error) {
959 if (logmsg_path)
960 preserve_logmsg = 1;
961 goto done;
964 error = got_ref_write(head_ref, repo);
965 if (error) {
966 if (logmsg_path)
967 preserve_logmsg = 1;
968 goto done;
972 printf("Created branch %s with commit %s\n",
973 got_ref_get_name(branch_ref), id_str);
974 done:
975 if (pack_fds) {
976 const struct got_error *pack_err =
977 got_repo_pack_fds_close(pack_fds);
978 if (error == NULL)
979 error = pack_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 break;
1582 case 'l':
1583 list_refs_only = 1;
1584 break;
1585 case 'm':
1586 mirror_references = 1;
1587 break;
1588 case 'q':
1589 verbosity = -1;
1590 break;
1591 case 'R':
1592 error = got_pathlist_append(&wanted_refs,
1593 optarg, NULL);
1594 if (error)
1595 return error;
1596 break;
1597 case 'v':
1598 if (verbosity < 0)
1599 verbosity = 0;
1600 else if (verbosity < 3)
1601 verbosity++;
1602 break;
1603 default:
1604 usage_clone();
1605 break;
1608 argc -= optind;
1609 argv += optind;
1611 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('a', 'b');
1613 if (list_refs_only) {
1614 if (!TAILQ_EMPTY(&wanted_branches))
1615 option_conflict('l', 'b');
1616 if (fetch_all_branches)
1617 option_conflict('l', 'a');
1618 if (mirror_references)
1619 option_conflict('l', 'm');
1620 if (!TAILQ_EMPTY(&wanted_refs))
1621 option_conflict('l', 'R');
1624 uri = argv[0];
1626 if (argc == 1)
1627 dirname = NULL;
1628 else if (argc == 2)
1629 dirname = argv[1];
1630 else
1631 usage_clone();
1633 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1634 &repo_name, uri);
1635 if (error)
1636 goto done;
1638 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1639 host, port ? ":" : "", port ? port : "",
1640 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1641 error = got_error_from_errno("asprintf");
1642 goto done;
1645 if (strcmp(proto, "git") == 0) {
1646 #ifndef PROFILE
1647 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1648 "sendfd dns inet unveil", NULL) == -1)
1649 err(1, "pledge");
1650 #endif
1651 } else if (strcmp(proto, "git+ssh") == 0 ||
1652 strcmp(proto, "ssh") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
1658 } else if (strcmp(proto, "http") == 0 ||
1659 strcmp(proto, "git+http") == 0) {
1660 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1661 goto done;
1662 } else {
1663 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1664 goto done;
1666 if (dirname == NULL) {
1667 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1668 error = got_error_from_errno("asprintf");
1669 goto done;
1671 repo_path = default_destdir;
1672 } else
1673 repo_path = dirname;
1675 if (!list_refs_only) {
1676 error = got_path_mkdir(repo_path);
1677 if (error &&
1678 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1679 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1680 goto done;
1681 if (!got_path_dir_is_empty(repo_path)) {
1682 error = got_error_path(repo_path,
1683 GOT_ERR_DIR_NOT_EMPTY);
1684 goto done;
1688 error = got_dial_apply_unveil(proto);
1689 if (error)
1690 goto done;
1692 error = apply_unveil(repo_path, 0, NULL);
1693 if (error)
1694 goto done;
1696 if (verbosity >= 0)
1697 printf("Connecting to %s\n", git_url);
1699 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1700 server_path, verbosity);
1701 if (error)
1702 goto done;
1704 if (!list_refs_only) {
1705 error = got_repo_init(repo_path, NULL);
1706 if (error)
1707 goto done;
1708 error = got_repo_pack_fds_open(&pack_fds);
1709 if (error != NULL)
1710 goto done;
1711 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1712 if (error)
1713 goto done;
1716 fpa.last_scaled_size[0] = '\0';
1717 fpa.last_p_indexed = -1;
1718 fpa.last_p_resolved = -1;
1719 fpa.verbosity = verbosity;
1720 fpa.create_configs = 1;
1721 fpa.configs_created = 0;
1722 fpa.repo = repo;
1723 fpa.config_info.symrefs = &symrefs;
1724 fpa.config_info.wanted_branches = &wanted_branches;
1725 fpa.config_info.wanted_refs = &wanted_refs;
1726 fpa.config_info.proto = proto;
1727 fpa.config_info.host = host;
1728 fpa.config_info.port = port;
1729 fpa.config_info.remote_repo_path = server_path;
1730 fpa.config_info.git_url = git_url;
1731 fpa.config_info.fetch_all_branches = fetch_all_branches;
1732 fpa.config_info.mirror_references = mirror_references;
1733 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1734 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1735 fetch_all_branches, &wanted_branches, &wanted_refs,
1736 list_refs_only, verbosity, fetchfd, repo,
1737 fetch_progress, &fpa);
1738 if (error)
1739 goto done;
1741 if (list_refs_only) {
1742 error = list_remote_refs(&symrefs, &refs);
1743 goto done;
1746 if (pack_hash == NULL) {
1747 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1748 "server sent an empty pack file");
1749 goto done;
1751 error = got_object_id_str(&id_str, pack_hash);
1752 if (error)
1753 goto done;
1754 if (verbosity >= 0)
1755 printf("\nFetched %s.pack\n", id_str);
1756 free(id_str);
1758 /* Set up references provided with the pack file. */
1759 TAILQ_FOREACH(pe, &refs, entry) {
1760 const char *refname = pe->path;
1761 struct got_object_id *id = pe->data;
1762 char *remote_refname;
1764 if (is_wanted_ref(&wanted_refs, refname) &&
1765 !mirror_references) {
1766 error = create_wanted_ref(refname, id,
1767 GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 verbosity - 1, repo);
1769 if (error)
1770 goto done;
1771 continue;
1774 error = create_ref(refname, id, verbosity - 1, repo);
1775 if (error)
1776 goto done;
1778 if (mirror_references)
1779 continue;
1781 if (strncmp("refs/heads/", refname, 11) != 0)
1782 continue;
1784 if (asprintf(&remote_refname,
1785 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1786 refname + 11) == -1) {
1787 error = got_error_from_errno("asprintf");
1788 goto done;
1790 error = create_ref(remote_refname, id, verbosity - 1, repo);
1791 free(remote_refname);
1792 if (error)
1793 goto done;
1796 /* Set the HEAD reference if the server provided one. */
1797 TAILQ_FOREACH(pe, &symrefs, entry) {
1798 struct got_reference *target_ref;
1799 const char *refname = pe->path;
1800 const char *target = pe->data;
1801 char *remote_refname = NULL, *remote_target = NULL;
1803 if (strcmp(refname, GOT_REF_HEAD) != 0)
1804 continue;
1806 error = got_ref_open(&target_ref, repo, target, 0);
1807 if (error) {
1808 if (error->code == GOT_ERR_NOT_REF) {
1809 error = NULL;
1810 continue;
1812 goto done;
1815 error = create_symref(refname, target_ref, verbosity, repo);
1816 got_ref_close(target_ref);
1817 if (error)
1818 goto done;
1820 if (mirror_references)
1821 continue;
1823 if (strncmp("refs/heads/", target, 11) != 0)
1824 continue;
1826 if (asprintf(&remote_refname,
1827 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1828 refname) == -1) {
1829 error = got_error_from_errno("asprintf");
1830 goto done;
1832 if (asprintf(&remote_target,
1833 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1834 target + 11) == -1) {
1835 error = got_error_from_errno("asprintf");
1836 free(remote_refname);
1837 goto done;
1839 error = got_ref_open(&target_ref, repo, remote_target, 0);
1840 if (error) {
1841 free(remote_refname);
1842 free(remote_target);
1843 if (error->code == GOT_ERR_NOT_REF) {
1844 error = NULL;
1845 continue;
1847 goto done;
1849 error = create_symref(remote_refname, target_ref,
1850 verbosity - 1, repo);
1851 free(remote_refname);
1852 free(remote_target);
1853 got_ref_close(target_ref);
1854 if (error)
1855 goto done;
1857 if (pe == NULL) {
1859 * We failed to set the HEAD reference. If we asked for
1860 * a set of wanted branches use the first of one of those
1861 * which could be fetched instead.
1863 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1864 const char *target = pe->path;
1865 struct got_reference *target_ref;
1867 error = got_ref_open(&target_ref, repo, target, 0);
1868 if (error) {
1869 if (error->code == GOT_ERR_NOT_REF) {
1870 error = NULL;
1871 continue;
1873 goto done;
1876 error = create_symref(GOT_REF_HEAD, target_ref,
1877 verbosity, repo);
1878 got_ref_close(target_ref);
1879 if (error)
1880 goto done;
1881 break;
1884 if (!fpa.configs_created && pe != NULL) {
1885 error = create_config_files(fpa.config_info.proto,
1886 fpa.config_info.host, fpa.config_info.port,
1887 fpa.config_info.remote_repo_path,
1888 fpa.config_info.git_url,
1889 fpa.config_info.fetch_all_branches,
1890 fpa.config_info.mirror_references,
1891 fpa.config_info.symrefs,
1892 fpa.config_info.wanted_branches,
1893 fpa.config_info.wanted_refs, fpa.repo);
1894 if (error)
1895 goto done;
1899 if (verbosity >= 0)
1900 printf("Created %s repository '%s'\n",
1901 mirror_references ? "mirrored" : "cloned", repo_path);
1902 done:
1903 if (pack_fds) {
1904 const struct got_error *pack_err =
1905 got_repo_pack_fds_close(pack_fds);
1906 if (error == NULL)
1907 error = pack_err;
1909 if (fetchpid > 0) {
1910 if (kill(fetchpid, SIGTERM) == -1)
1911 error = got_error_from_errno("kill");
1912 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1913 error = got_error_from_errno("waitpid");
1915 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1916 error = got_error_from_errno("close");
1917 if (repo) {
1918 const struct got_error *close_err = got_repo_close(repo);
1919 if (error == NULL)
1920 error = close_err;
1922 TAILQ_FOREACH(pe, &refs, entry) {
1923 free((void *)pe->path);
1924 free(pe->data);
1926 got_pathlist_free(&refs);
1927 TAILQ_FOREACH(pe, &symrefs, entry) {
1928 free((void *)pe->path);
1929 free(pe->data);
1931 got_pathlist_free(&symrefs);
1932 got_pathlist_free(&wanted_branches);
1933 got_pathlist_free(&wanted_refs);
1934 free(pack_hash);
1935 free(proto);
1936 free(host);
1937 free(port);
1938 free(server_path);
1939 free(repo_name);
1940 free(default_destdir);
1941 free(git_url);
1942 return error;
1945 static const struct got_error *
1946 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1947 int replace_tags, int verbosity, struct got_repository *repo)
1949 const struct got_error *err = NULL;
1950 char *new_id_str = NULL;
1951 struct got_object_id *old_id = NULL;
1953 err = got_object_id_str(&new_id_str, new_id);
1954 if (err)
1955 goto done;
1957 if (!replace_tags &&
1958 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1959 err = got_ref_resolve(&old_id, repo, ref);
1960 if (err)
1961 goto done;
1962 if (got_object_id_cmp(old_id, new_id) == 0)
1963 goto done;
1964 if (verbosity >= 0) {
1965 printf("Rejecting update of existing tag %s: %s\n",
1966 got_ref_get_name(ref), new_id_str);
1968 goto done;
1971 if (got_ref_is_symbolic(ref)) {
1972 if (verbosity >= 0) {
1973 printf("Replacing reference %s: %s\n",
1974 got_ref_get_name(ref),
1975 got_ref_get_symref_target(ref));
1977 err = got_ref_change_symref_to_ref(ref, new_id);
1978 if (err)
1979 goto done;
1980 err = got_ref_write(ref, repo);
1981 if (err)
1982 goto done;
1983 } else {
1984 err = got_ref_resolve(&old_id, repo, ref);
1985 if (err)
1986 goto done;
1987 if (got_object_id_cmp(old_id, new_id) == 0)
1988 goto done;
1990 err = got_ref_change_ref(ref, new_id);
1991 if (err)
1992 goto done;
1993 err = got_ref_write(ref, repo);
1994 if (err)
1995 goto done;
1998 if (verbosity >= 0)
1999 printf("Updated %s: %s\n", got_ref_get_name(ref),
2000 new_id_str);
2001 done:
2002 free(old_id);
2003 free(new_id_str);
2004 return err;
2007 static const struct got_error *
2008 update_symref(const char *refname, struct got_reference *target_ref,
2009 int verbosity, struct got_repository *repo)
2011 const struct got_error *err = NULL, *unlock_err;
2012 struct got_reference *symref;
2013 int symref_is_locked = 0;
2015 err = got_ref_open(&symref, repo, refname, 1);
2016 if (err) {
2017 if (err->code != GOT_ERR_NOT_REF)
2018 return err;
2019 err = got_ref_alloc_symref(&symref, refname, target_ref);
2020 if (err)
2021 goto done;
2023 err = got_ref_write(symref, repo);
2024 if (err)
2025 goto done;
2027 if (verbosity >= 0)
2028 printf("Created reference %s: %s\n",
2029 got_ref_get_name(symref),
2030 got_ref_get_symref_target(symref));
2031 } else {
2032 symref_is_locked = 1;
2034 if (strcmp(got_ref_get_symref_target(symref),
2035 got_ref_get_name(target_ref)) == 0)
2036 goto done;
2038 err = got_ref_change_symref(symref,
2039 got_ref_get_name(target_ref));
2040 if (err)
2041 goto done;
2043 err = got_ref_write(symref, repo);
2044 if (err)
2045 goto done;
2047 if (verbosity >= 0)
2048 printf("Updated %s: %s\n", got_ref_get_name(symref),
2049 got_ref_get_symref_target(symref));
2052 done:
2053 if (symref_is_locked) {
2054 unlock_err = got_ref_unlock(symref);
2055 if (unlock_err && err == NULL)
2056 err = unlock_err;
2058 got_ref_close(symref);
2059 return err;
2062 __dead static void
2063 usage_fetch(void)
2065 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2066 "[-R reference] [-r repository-path] [remote-repository]\n",
2067 getprogname());
2068 exit(1);
2071 static const struct got_error *
2072 delete_missing_ref(struct got_reference *ref,
2073 int verbosity, struct got_repository *repo)
2075 const struct got_error *err = NULL;
2076 struct got_object_id *id = NULL;
2077 char *id_str = NULL;
2079 if (got_ref_is_symbolic(ref)) {
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 return err;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref),
2086 got_ref_get_symref_target(ref));
2088 } else {
2089 err = got_ref_resolve(&id, repo, ref);
2090 if (err)
2091 return err;
2092 err = got_object_id_str(&id_str, id);
2093 if (err)
2094 goto done;
2096 err = got_ref_delete(ref, repo);
2097 if (err)
2098 goto done;
2099 if (verbosity >= 0) {
2100 printf("Deleted %s: %s\n",
2101 got_ref_get_name(ref), id_str);
2104 done:
2105 free(id);
2106 free(id_str);
2107 return NULL;
2110 static const struct got_error *
2111 delete_missing_refs(struct got_pathlist_head *their_refs,
2112 struct got_pathlist_head *their_symrefs,
2113 const struct got_remote_repo *remote,
2114 int verbosity, struct got_repository *repo)
2116 const struct got_error *err = NULL, *unlock_err;
2117 struct got_reflist_head my_refs;
2118 struct got_reflist_entry *re;
2119 struct got_pathlist_entry *pe;
2120 char *remote_namespace = NULL;
2121 char *local_refname = NULL;
2123 TAILQ_INIT(&my_refs);
2125 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2126 == -1)
2127 return got_error_from_errno("asprintf");
2129 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2130 if (err)
2131 goto done;
2133 TAILQ_FOREACH(re, &my_refs, entry) {
2134 const char *refname = got_ref_get_name(re->ref);
2135 const char *their_refname;
2137 if (remote->mirror_references) {
2138 their_refname = refname;
2139 } else {
2140 if (strncmp(refname, remote_namespace,
2141 strlen(remote_namespace)) == 0) {
2142 if (strcmp(refname + strlen(remote_namespace),
2143 GOT_REF_HEAD) == 0)
2144 continue;
2145 if (asprintf(&local_refname, "refs/heads/%s",
2146 refname + strlen(remote_namespace)) == -1) {
2147 err = got_error_from_errno("asprintf");
2148 goto done;
2150 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2151 continue;
2153 their_refname = local_refname;
2156 TAILQ_FOREACH(pe, their_refs, entry) {
2157 if (strcmp(their_refname, pe->path) == 0)
2158 break;
2160 if (pe != NULL)
2161 continue;
2163 TAILQ_FOREACH(pe, their_symrefs, entry) {
2164 if (strcmp(their_refname, pe->path) == 0)
2165 break;
2167 if (pe != NULL)
2168 continue;
2170 err = delete_missing_ref(re->ref, verbosity, repo);
2171 if (err)
2172 break;
2174 if (local_refname) {
2175 struct got_reference *ref;
2176 err = got_ref_open(&ref, repo, local_refname, 1);
2177 if (err) {
2178 if (err->code != GOT_ERR_NOT_REF)
2179 break;
2180 free(local_refname);
2181 local_refname = NULL;
2182 continue;
2184 err = delete_missing_ref(ref, verbosity, repo);
2185 if (err)
2186 break;
2187 unlock_err = got_ref_unlock(ref);
2188 got_ref_close(ref);
2189 if (unlock_err && err == NULL) {
2190 err = unlock_err;
2191 break;
2194 free(local_refname);
2195 local_refname = NULL;
2198 done:
2199 got_ref_list_free(&my_refs);
2200 free(remote_namespace);
2201 free(local_refname);
2202 return err;
2205 static const struct got_error *
2206 update_wanted_ref(const char *refname, struct got_object_id *id,
2207 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2209 const struct got_error *err, *unlock_err;
2210 char *remote_refname;
2211 struct got_reference *ref;
2213 if (strncmp("refs/", refname, 5) == 0)
2214 refname += 5;
2216 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2217 remote_repo_name, refname) == -1)
2218 return got_error_from_errno("asprintf");
2220 err = got_ref_open(&ref, repo, remote_refname, 1);
2221 if (err) {
2222 if (err->code != GOT_ERR_NOT_REF)
2223 goto done;
2224 err = create_ref(remote_refname, id, verbosity, repo);
2225 } else {
2226 err = update_ref(ref, id, 0, verbosity, repo);
2227 unlock_err = got_ref_unlock(ref);
2228 if (unlock_err && err == NULL)
2229 err = unlock_err;
2230 got_ref_close(ref);
2232 done:
2233 free(remote_refname);
2234 return err;
2237 static const struct got_error *
2238 delete_ref(struct got_repository *repo, struct got_reference *ref)
2240 const struct got_error *err = NULL;
2241 struct got_object_id *id = NULL;
2242 char *id_str = NULL;
2243 const char *target;
2245 if (got_ref_is_symbolic(ref)) {
2246 target = got_ref_get_symref_target(ref);
2247 } else {
2248 err = got_ref_resolve(&id, repo, ref);
2249 if (err)
2250 goto done;
2251 err = got_object_id_str(&id_str, id);
2252 if (err)
2253 goto done;
2254 target = id_str;
2257 err = got_ref_delete(ref, repo);
2258 if (err)
2259 goto done;
2261 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2262 done:
2263 free(id);
2264 free(id_str);
2265 return err;
2268 static const struct got_error *
2269 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2271 const struct got_error *err = NULL;
2272 struct got_reflist_head refs;
2273 struct got_reflist_entry *re;
2274 char *prefix;
2276 TAILQ_INIT(&refs);
2278 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2279 err = got_error_from_errno("asprintf");
2280 goto done;
2282 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2283 if (err)
2284 goto done;
2286 TAILQ_FOREACH(re, &refs, entry)
2287 delete_ref(repo, re->ref);
2288 done:
2289 got_ref_list_free(&refs);
2290 return err;
2293 static const struct got_error *
2294 cmd_fetch(int argc, char *argv[])
2296 const struct got_error *error = NULL, *unlock_err;
2297 char *cwd = NULL, *repo_path = NULL;
2298 const char *remote_name;
2299 char *proto = NULL, *host = NULL, *port = NULL;
2300 char *repo_name = NULL, *server_path = NULL;
2301 const struct got_remote_repo *remotes, *remote = NULL;
2302 int nremotes;
2303 char *id_str = NULL;
2304 struct got_repository *repo = NULL;
2305 struct got_worktree *worktree = NULL;
2306 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2307 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2308 struct got_pathlist_entry *pe;
2309 struct got_object_id *pack_hash = NULL;
2310 int i, ch, fetchfd = -1, fetchstatus;
2311 pid_t fetchpid = -1;
2312 struct got_fetch_progress_arg fpa;
2313 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2314 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2315 int *pack_fds = NULL;
2317 TAILQ_INIT(&refs);
2318 TAILQ_INIT(&symrefs);
2319 TAILQ_INIT(&wanted_branches);
2320 TAILQ_INIT(&wanted_refs);
2322 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2323 switch (ch) {
2324 case 'a':
2325 fetch_all_branches = 1;
2326 break;
2327 case 'b':
2328 error = got_pathlist_append(&wanted_branches,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 break;
2333 case 'd':
2334 delete_refs = 1;
2335 break;
2336 case 'l':
2337 list_refs_only = 1;
2338 break;
2339 case 'q':
2340 verbosity = -1;
2341 break;
2342 case 'R':
2343 error = got_pathlist_append(&wanted_refs,
2344 optarg, NULL);
2345 if (error)
2346 return error;
2347 break;
2348 case 'r':
2349 repo_path = realpath(optarg, NULL);
2350 if (repo_path == NULL)
2351 return got_error_from_errno2("realpath",
2352 optarg);
2353 got_path_strip_trailing_slashes(repo_path);
2354 break;
2355 case 't':
2356 replace_tags = 1;
2357 break;
2358 case 'v':
2359 if (verbosity < 0)
2360 verbosity = 0;
2361 else if (verbosity < 3)
2362 verbosity++;
2363 break;
2364 case 'X':
2365 delete_remote = 1;
2366 break;
2367 default:
2368 usage_fetch();
2369 break;
2372 argc -= optind;
2373 argv += optind;
2375 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('a', 'b');
2377 if (list_refs_only) {
2378 if (!TAILQ_EMPTY(&wanted_branches))
2379 option_conflict('l', 'b');
2380 if (fetch_all_branches)
2381 option_conflict('l', 'a');
2382 if (delete_refs)
2383 option_conflict('l', 'd');
2384 if (delete_remote)
2385 option_conflict('l', 'X');
2387 if (delete_remote) {
2388 if (fetch_all_branches)
2389 option_conflict('X', 'a');
2390 if (!TAILQ_EMPTY(&wanted_branches))
2391 option_conflict('X', 'b');
2392 if (delete_refs)
2393 option_conflict('X', 'd');
2394 if (replace_tags)
2395 option_conflict('X', 't');
2396 if (!TAILQ_EMPTY(&wanted_refs))
2397 option_conflict('X', 'R');
2400 if (argc == 0) {
2401 if (delete_remote)
2402 errx(1, "-X option requires a remote name");
2403 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2404 } else if (argc == 1)
2405 remote_name = argv[0];
2406 else
2407 usage_fetch();
2409 cwd = getcwd(NULL, 0);
2410 if (cwd == NULL) {
2411 error = got_error_from_errno("getcwd");
2412 goto done;
2415 error = got_repo_pack_fds_open(&pack_fds);
2416 if (error != NULL)
2417 goto done;
2419 if (repo_path == NULL) {
2420 error = got_worktree_open(&worktree, cwd);
2421 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2422 goto done;
2423 else
2424 error = NULL;
2425 if (worktree) {
2426 repo_path =
2427 strdup(got_worktree_get_repo_path(worktree));
2428 if (repo_path == NULL)
2429 error = got_error_from_errno("strdup");
2430 if (error)
2431 goto done;
2432 } else {
2433 repo_path = strdup(cwd);
2434 if (repo_path == NULL) {
2435 error = got_error_from_errno("strdup");
2436 goto done;
2441 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2442 if (error)
2443 goto done;
2445 if (delete_remote) {
2446 error = delete_refs_for_remote(repo, remote_name);
2447 goto done; /* nothing else to do */
2450 if (worktree) {
2451 worktree_conf = got_worktree_get_gotconfig(worktree);
2452 if (worktree_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 worktree_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 remote = &remotes[i];
2458 break;
2463 if (remote == NULL) {
2464 repo_conf = got_repo_get_gotconfig(repo);
2465 if (repo_conf) {
2466 got_gotconfig_get_remotes(&nremotes, &remotes,
2467 repo_conf);
2468 for (i = 0; i < nremotes; i++) {
2469 if (strcmp(remotes[i].name, remote_name) == 0) {
2470 remote = &remotes[i];
2471 break;
2476 if (remote == NULL) {
2477 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2478 for (i = 0; i < nremotes; i++) {
2479 if (strcmp(remotes[i].name, remote_name) == 0) {
2480 remote = &remotes[i];
2481 break;
2485 if (remote == NULL) {
2486 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2487 goto done;
2490 if (TAILQ_EMPTY(&wanted_branches)) {
2491 if (!fetch_all_branches)
2492 fetch_all_branches = remote->fetch_all_branches;
2493 for (i = 0; i < remote->nfetch_branches; i++) {
2494 got_pathlist_append(&wanted_branches,
2495 remote->fetch_branches[i], NULL);
2498 if (TAILQ_EMPTY(&wanted_refs)) {
2499 for (i = 0; i < remote->nfetch_refs; i++) {
2500 got_pathlist_append(&wanted_refs,
2501 remote->fetch_refs[i], NULL);
2505 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2506 &repo_name, remote->fetch_url);
2507 if (error)
2508 goto done;
2510 if (strcmp(proto, "git") == 0) {
2511 #ifndef PROFILE
2512 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2513 "sendfd dns inet unveil", NULL) == -1)
2514 err(1, "pledge");
2515 #endif
2516 } else if (strcmp(proto, "git+ssh") == 0 ||
2517 strcmp(proto, "ssh") == 0) {
2518 #ifndef PROFILE
2519 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2520 "sendfd unveil", NULL) == -1)
2521 err(1, "pledge");
2522 #endif
2523 } else if (strcmp(proto, "http") == 0 ||
2524 strcmp(proto, "git+http") == 0) {
2525 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2526 goto done;
2527 } else {
2528 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2529 goto done;
2532 error = got_dial_apply_unveil(proto);
2533 if (error)
2534 goto done;
2536 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2537 if (error)
2538 goto done;
2540 if (verbosity >= 0) {
2541 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2542 remote->name, proto, host,
2543 port ? ":" : "", port ? port : "",
2544 *server_path == '/' ? "" : "/", server_path);
2547 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2548 server_path, verbosity);
2549 if (error)
2550 goto done;
2552 fpa.last_scaled_size[0] = '\0';
2553 fpa.last_p_indexed = -1;
2554 fpa.last_p_resolved = -1;
2555 fpa.verbosity = verbosity;
2556 fpa.repo = repo;
2557 fpa.create_configs = 0;
2558 fpa.configs_created = 0;
2559 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2560 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2561 remote->mirror_references, fetch_all_branches, &wanted_branches,
2562 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2563 fetch_progress, &fpa);
2564 if (error)
2565 goto done;
2567 if (list_refs_only) {
2568 error = list_remote_refs(&symrefs, &refs);
2569 goto done;
2572 if (pack_hash == NULL) {
2573 if (verbosity >= 0)
2574 printf("Already up-to-date\n");
2575 } else if (verbosity >= 0) {
2576 error = got_object_id_str(&id_str, pack_hash);
2577 if (error)
2578 goto done;
2579 printf("\nFetched %s.pack\n", id_str);
2580 free(id_str);
2581 id_str = NULL;
2584 /* Update references provided with the pack file. */
2585 TAILQ_FOREACH(pe, &refs, entry) {
2586 const char *refname = pe->path;
2587 struct got_object_id *id = pe->data;
2588 struct got_reference *ref;
2589 char *remote_refname;
2591 if (is_wanted_ref(&wanted_refs, refname) &&
2592 !remote->mirror_references) {
2593 error = update_wanted_ref(refname, id,
2594 remote->name, verbosity, repo);
2595 if (error)
2596 goto done;
2597 continue;
2600 if (remote->mirror_references ||
2601 strncmp("refs/tags/", refname, 10) == 0) {
2602 error = got_ref_open(&ref, repo, refname, 1);
2603 if (error) {
2604 if (error->code != GOT_ERR_NOT_REF)
2605 goto done;
2606 error = create_ref(refname, id, verbosity,
2607 repo);
2608 if (error)
2609 goto done;
2610 } else {
2611 error = update_ref(ref, id, replace_tags,
2612 verbosity, repo);
2613 unlock_err = got_ref_unlock(ref);
2614 if (unlock_err && error == NULL)
2615 error = unlock_err;
2616 got_ref_close(ref);
2617 if (error)
2618 goto done;
2620 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2621 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2622 remote_name, refname + 11) == -1) {
2623 error = got_error_from_errno("asprintf");
2624 goto done;
2627 error = got_ref_open(&ref, repo, remote_refname, 1);
2628 if (error) {
2629 if (error->code != GOT_ERR_NOT_REF)
2630 goto done;
2631 error = create_ref(remote_refname, id,
2632 verbosity, repo);
2633 if (error)
2634 goto done;
2635 } else {
2636 error = update_ref(ref, id, replace_tags,
2637 verbosity, repo);
2638 unlock_err = got_ref_unlock(ref);
2639 if (unlock_err && error == NULL)
2640 error = unlock_err;
2641 got_ref_close(ref);
2642 if (error)
2643 goto done;
2646 /* Also create a local branch if none exists yet. */
2647 error = got_ref_open(&ref, repo, refname, 1);
2648 if (error) {
2649 if (error->code != GOT_ERR_NOT_REF)
2650 goto done;
2651 error = create_ref(refname, id, verbosity,
2652 repo);
2653 if (error)
2654 goto done;
2655 } else {
2656 unlock_err = got_ref_unlock(ref);
2657 if (unlock_err && error == NULL)
2658 error = unlock_err;
2659 got_ref_close(ref);
2663 if (delete_refs) {
2664 error = delete_missing_refs(&refs, &symrefs, remote,
2665 verbosity, repo);
2666 if (error)
2667 goto done;
2670 if (!remote->mirror_references) {
2671 /* Update remote HEAD reference if the server provided one. */
2672 TAILQ_FOREACH(pe, &symrefs, entry) {
2673 struct got_reference *target_ref;
2674 const char *refname = pe->path;
2675 const char *target = pe->data;
2676 char *remote_refname = NULL, *remote_target = NULL;
2678 if (strcmp(refname, GOT_REF_HEAD) != 0)
2679 continue;
2681 if (strncmp("refs/heads/", target, 11) != 0)
2682 continue;
2684 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2685 remote->name, refname) == -1) {
2686 error = got_error_from_errno("asprintf");
2687 goto done;
2689 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2690 remote->name, target + 11) == -1) {
2691 error = got_error_from_errno("asprintf");
2692 free(remote_refname);
2693 goto done;
2696 error = got_ref_open(&target_ref, repo, remote_target,
2697 0);
2698 if (error) {
2699 free(remote_refname);
2700 free(remote_target);
2701 if (error->code == GOT_ERR_NOT_REF) {
2702 error = NULL;
2703 continue;
2705 goto done;
2707 error = update_symref(remote_refname, target_ref,
2708 verbosity, repo);
2709 free(remote_refname);
2710 free(remote_target);
2711 got_ref_close(target_ref);
2712 if (error)
2713 goto done;
2716 done:
2717 if (fetchpid > 0) {
2718 if (kill(fetchpid, SIGTERM) == -1)
2719 error = got_error_from_errno("kill");
2720 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2721 error = got_error_from_errno("waitpid");
2723 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2724 error = got_error_from_errno("close");
2725 if (repo) {
2726 const struct got_error *close_err = got_repo_close(repo);
2727 if (error == NULL)
2728 error = close_err;
2730 if (worktree)
2731 got_worktree_close(worktree);
2732 if (pack_fds) {
2733 const struct got_error *pack_err =
2734 got_repo_pack_fds_close(pack_fds);
2735 if (error == NULL)
2736 error = pack_err;
2738 TAILQ_FOREACH(pe, &refs, entry) {
2739 free((void *)pe->path);
2740 free(pe->data);
2742 got_pathlist_free(&refs);
2743 TAILQ_FOREACH(pe, &symrefs, entry) {
2744 free((void *)pe->path);
2745 free(pe->data);
2747 got_pathlist_free(&symrefs);
2748 got_pathlist_free(&wanted_branches);
2749 got_pathlist_free(&wanted_refs);
2750 free(id_str);
2751 free(cwd);
2752 free(repo_path);
2753 free(pack_hash);
2754 free(proto);
2755 free(host);
2756 free(port);
2757 free(server_path);
2758 free(repo_name);
2759 return error;
2763 __dead static void
2764 usage_checkout(void)
2766 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2767 "[-p path-prefix] repository-path [work-tree-path]\n",
2768 getprogname());
2769 exit(1);
2772 static void
2773 show_worktree_base_ref_warning(void)
2775 fprintf(stderr, "%s: warning: could not create a reference "
2776 "to the work tree's base commit; the commit could be "
2777 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2778 "repository writable and running 'got update' will prevent this\n",
2779 getprogname());
2782 struct got_checkout_progress_arg {
2783 const char *worktree_path;
2784 int had_base_commit_ref_error;
2785 int verbosity;
2788 static const struct got_error *
2789 checkout_progress(void *arg, unsigned char status, const char *path)
2791 struct got_checkout_progress_arg *a = arg;
2793 /* Base commit bump happens silently. */
2794 if (status == GOT_STATUS_BUMP_BASE)
2795 return NULL;
2797 if (status == GOT_STATUS_BASE_REF_ERR) {
2798 a->had_base_commit_ref_error = 1;
2799 return NULL;
2802 while (path[0] == '/')
2803 path++;
2805 if (a->verbosity >= 0)
2806 printf("%c %s/%s\n", status, a->worktree_path, path);
2808 return NULL;
2811 static const struct got_error *
2812 check_cancelled(void *arg)
2814 if (sigint_received || sigpipe_received)
2815 return got_error(GOT_ERR_CANCELLED);
2816 return NULL;
2819 static const struct got_error *
2820 check_linear_ancestry(struct got_object_id *commit_id,
2821 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2822 struct got_repository *repo)
2824 const struct got_error *err = NULL;
2825 struct got_object_id *yca_id;
2827 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2828 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2829 if (err)
2830 return err;
2832 if (yca_id == NULL)
2833 return got_error(GOT_ERR_ANCESTRY);
2836 * Require a straight line of history between the target commit
2837 * and the work tree's base commit.
2839 * Non-linear situations such as this require a rebase:
2841 * (commit) D F (base_commit)
2842 * \ /
2843 * C E
2844 * \ /
2845 * B (yca)
2846 * |
2847 * A
2849 * 'got update' only handles linear cases:
2850 * Update forwards in time: A (base/yca) - B - C - D (commit)
2851 * Update backwards in time: D (base) - C - B - A (commit/yca)
2853 if (allow_forwards_in_time_only) {
2854 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2855 return got_error(GOT_ERR_ANCESTRY);
2856 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2857 got_object_id_cmp(base_commit_id, yca_id) != 0)
2858 return got_error(GOT_ERR_ANCESTRY);
2860 free(yca_id);
2861 return NULL;
2864 static const struct got_error *
2865 check_same_branch(struct got_object_id *commit_id,
2866 struct got_reference *head_ref, struct got_object_id *yca_id,
2867 struct got_repository *repo)
2869 const struct got_error *err = NULL;
2870 struct got_commit_graph *graph = NULL;
2871 struct got_object_id *head_commit_id = NULL;
2872 int is_same_branch = 0;
2874 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2875 if (err)
2876 goto done;
2878 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2879 is_same_branch = 1;
2880 goto done;
2882 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2883 is_same_branch = 1;
2884 goto done;
2887 err = got_commit_graph_open(&graph, "/", 1);
2888 if (err)
2889 goto done;
2891 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2892 check_cancelled, NULL);
2893 if (err)
2894 goto done;
2896 for (;;) {
2897 struct got_object_id id;
2899 err = got_commit_graph_iter_next(&id, graph, repo,
2900 check_cancelled, NULL);
2901 if (err) {
2902 if (err->code == GOT_ERR_ITER_COMPLETED)
2903 err = NULL;
2904 break;
2907 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2908 break;
2909 if (got_object_id_cmp(&id, commit_id) == 0) {
2910 is_same_branch = 1;
2911 break;
2914 done:
2915 if (graph)
2916 got_commit_graph_close(graph);
2917 free(head_commit_id);
2918 if (!err && !is_same_branch)
2919 err = got_error(GOT_ERR_ANCESTRY);
2920 return err;
2923 static const struct got_error *
2924 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2926 static char msg[512];
2927 const char *branch_name;
2929 if (got_ref_is_symbolic(ref))
2930 branch_name = got_ref_get_symref_target(ref);
2931 else
2932 branch_name = got_ref_get_name(ref);
2934 if (strncmp("refs/heads/", branch_name, 11) == 0)
2935 branch_name += 11;
2937 snprintf(msg, sizeof(msg),
2938 "target commit is not contained in branch '%s'; "
2939 "the branch to use must be specified with -b; "
2940 "if necessary a new branch can be created for "
2941 "this commit with 'got branch -c %s BRANCH_NAME'",
2942 branch_name, commit_id_str);
2944 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2947 static const struct got_error *
2948 cmd_checkout(int argc, char *argv[])
2950 const struct got_error *error = NULL;
2951 struct got_repository *repo = NULL;
2952 struct got_reference *head_ref = NULL, *ref = NULL;
2953 struct got_worktree *worktree = NULL;
2954 char *repo_path = NULL;
2955 char *worktree_path = NULL;
2956 const char *path_prefix = "";
2957 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2958 char *commit_id_str = NULL;
2959 struct got_object_id *commit_id = NULL;
2960 char *cwd = NULL;
2961 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2962 struct got_pathlist_head paths;
2963 struct got_checkout_progress_arg cpa;
2964 int *pack_fds = NULL;
2966 TAILQ_INIT(&paths);
2968 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2969 switch (ch) {
2970 case 'b':
2971 branch_name = optarg;
2972 break;
2973 case 'c':
2974 commit_id_str = strdup(optarg);
2975 if (commit_id_str == NULL)
2976 return got_error_from_errno("strdup");
2977 break;
2978 case 'E':
2979 allow_nonempty = 1;
2980 break;
2981 case 'p':
2982 path_prefix = optarg;
2983 break;
2984 case 'q':
2985 verbosity = -1;
2986 break;
2987 default:
2988 usage_checkout();
2989 /* NOTREACHED */
2993 argc -= optind;
2994 argv += optind;
2996 #ifndef PROFILE
2997 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2998 "unveil", NULL) == -1)
2999 err(1, "pledge");
3000 #endif
3001 if (argc == 1) {
3002 char *base, *dotgit;
3003 const char *path;
3004 repo_path = realpath(argv[0], NULL);
3005 if (repo_path == NULL)
3006 return got_error_from_errno2("realpath", argv[0]);
3007 cwd = getcwd(NULL, 0);
3008 if (cwd == NULL) {
3009 error = got_error_from_errno("getcwd");
3010 goto done;
3012 if (path_prefix[0])
3013 path = path_prefix;
3014 else
3015 path = repo_path;
3016 error = got_path_basename(&base, path);
3017 if (error)
3018 goto done;
3019 dotgit = strstr(base, ".git");
3020 if (dotgit)
3021 *dotgit = '\0';
3022 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3023 error = got_error_from_errno("asprintf");
3024 free(base);
3025 goto done;
3027 free(base);
3028 } else if (argc == 2) {
3029 repo_path = realpath(argv[0], NULL);
3030 if (repo_path == NULL) {
3031 error = got_error_from_errno2("realpath", argv[0]);
3032 goto done;
3034 worktree_path = realpath(argv[1], NULL);
3035 if (worktree_path == NULL) {
3036 if (errno != ENOENT) {
3037 error = got_error_from_errno2("realpath",
3038 argv[1]);
3039 goto done;
3041 worktree_path = strdup(argv[1]);
3042 if (worktree_path == NULL) {
3043 error = got_error_from_errno("strdup");
3044 goto done;
3047 } else
3048 usage_checkout();
3050 got_path_strip_trailing_slashes(repo_path);
3051 got_path_strip_trailing_slashes(worktree_path);
3053 error = got_repo_pack_fds_open(&pack_fds);
3054 if (error != NULL)
3055 goto done;
3057 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3058 if (error != NULL)
3059 goto done;
3061 /* Pre-create work tree path for unveil(2) */
3062 error = got_path_mkdir(worktree_path);
3063 if (error) {
3064 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3065 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3066 goto done;
3067 if (!allow_nonempty &&
3068 !got_path_dir_is_empty(worktree_path)) {
3069 error = got_error_path(worktree_path,
3070 GOT_ERR_DIR_NOT_EMPTY);
3071 goto done;
3075 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3076 if (error)
3077 goto done;
3079 error = got_ref_open(&head_ref, repo, branch_name, 0);
3080 if (error != NULL)
3081 goto done;
3083 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3084 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3085 goto done;
3087 error = got_worktree_open(&worktree, worktree_path);
3088 if (error != NULL)
3089 goto done;
3091 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3092 path_prefix);
3093 if (error != NULL)
3094 goto done;
3095 if (!same_path_prefix) {
3096 error = got_error(GOT_ERR_PATH_PREFIX);
3097 goto done;
3100 if (commit_id_str) {
3101 struct got_reflist_head refs;
3102 TAILQ_INIT(&refs);
3103 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3104 NULL);
3105 if (error)
3106 goto done;
3107 error = got_repo_match_object_id(&commit_id, NULL,
3108 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3109 got_ref_list_free(&refs);
3110 if (error)
3111 goto done;
3112 error = check_linear_ancestry(commit_id,
3113 got_worktree_get_base_commit_id(worktree), 0, repo);
3114 if (error != NULL) {
3115 if (error->code == GOT_ERR_ANCESTRY) {
3116 error = checkout_ancestry_error(
3117 head_ref, commit_id_str);
3119 goto done;
3121 error = check_same_branch(commit_id, head_ref, NULL, repo);
3122 if (error) {
3123 if (error->code == GOT_ERR_ANCESTRY) {
3124 error = checkout_ancestry_error(
3125 head_ref, commit_id_str);
3127 goto done;
3129 error = got_worktree_set_base_commit_id(worktree, repo,
3130 commit_id);
3131 if (error)
3132 goto done;
3133 /* Expand potentially abbreviated commit ID string. */
3134 free(commit_id_str);
3135 error = got_object_id_str(&commit_id_str, commit_id);
3136 if (error)
3137 goto done;
3138 } else {
3139 commit_id = got_object_id_dup(
3140 got_worktree_get_base_commit_id(worktree));
3141 if (commit_id == NULL) {
3142 error = got_error_from_errno("got_object_id_dup");
3143 goto done;
3145 error = got_object_id_str(&commit_id_str, commit_id);
3146 if (error)
3147 goto done;
3150 error = got_pathlist_append(&paths, "", NULL);
3151 if (error)
3152 goto done;
3153 cpa.worktree_path = worktree_path;
3154 cpa.had_base_commit_ref_error = 0;
3155 cpa.verbosity = verbosity;
3156 error = got_worktree_checkout_files(worktree, &paths, repo,
3157 checkout_progress, &cpa, check_cancelled, NULL);
3158 if (error != NULL)
3159 goto done;
3161 if (got_ref_is_symbolic(head_ref)) {
3162 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3163 if (error)
3164 goto done;
3165 refname = got_ref_get_name(ref);
3166 } else
3167 refname = got_ref_get_name(head_ref);
3168 printf("Checked out %s: %s\n", refname, commit_id_str);
3169 printf("Now shut up and hack\n");
3170 if (cpa.had_base_commit_ref_error)
3171 show_worktree_base_ref_warning();
3172 done:
3173 if (pack_fds) {
3174 const struct got_error *pack_err =
3175 got_repo_pack_fds_close(pack_fds);
3176 if (error == NULL)
3177 error = pack_err;
3179 if (head_ref)
3180 got_ref_close(head_ref);
3181 if (ref)
3182 got_ref_close(ref);
3183 got_pathlist_free(&paths);
3184 free(commit_id_str);
3185 free(commit_id);
3186 free(repo_path);
3187 free(worktree_path);
3188 free(cwd);
3189 return error;
3192 struct got_update_progress_arg {
3193 int did_something;
3194 int conflicts;
3195 int obstructed;
3196 int not_updated;
3197 int missing;
3198 int not_deleted;
3199 int unversioned;
3200 int verbosity;
3203 static void
3204 print_update_progress_stats(struct got_update_progress_arg *upa)
3206 if (!upa->did_something)
3207 return;
3209 if (upa->conflicts > 0)
3210 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3211 if (upa->obstructed > 0)
3212 printf("File paths obstructed by a non-regular file: %d\n",
3213 upa->obstructed);
3214 if (upa->not_updated > 0)
3215 printf("Files not updated because of existing merge "
3216 "conflicts: %d\n", upa->not_updated);
3220 * The meaning of some status codes differs between merge-style operations and
3221 * update operations. For example, the ! status code means "file was missing"
3222 * if changes were merged into the work tree, and "missing file was restored"
3223 * if the work tree was updated. This function should be used by any operation
3224 * which merges changes into the work tree without updating the work tree.
3226 static void
3227 print_merge_progress_stats(struct got_update_progress_arg *upa)
3229 if (!upa->did_something)
3230 return;
3232 if (upa->conflicts > 0)
3233 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3234 if (upa->obstructed > 0)
3235 printf("File paths obstructed by a non-regular file: %d\n",
3236 upa->obstructed);
3237 if (upa->missing > 0)
3238 printf("Files which had incoming changes but could not be "
3239 "found in the work tree: %d\n", upa->missing);
3240 if (upa->not_deleted > 0)
3241 printf("Files not deleted due to differences in deleted "
3242 "content: %d\n", upa->not_deleted);
3243 if (upa->unversioned > 0)
3244 printf("Files not merged because an unversioned file was "
3245 "found in the work tree: %d\n", upa->unversioned);
3248 __dead static void
3249 usage_update(void)
3251 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3252 "[path ...]\n", getprogname());
3253 exit(1);
3256 static const struct got_error *
3257 update_progress(void *arg, unsigned char status, const char *path)
3259 struct got_update_progress_arg *upa = arg;
3261 if (status == GOT_STATUS_EXISTS ||
3262 status == GOT_STATUS_BASE_REF_ERR)
3263 return NULL;
3265 upa->did_something = 1;
3267 /* Base commit bump happens silently. */
3268 if (status == GOT_STATUS_BUMP_BASE)
3269 return NULL;
3271 if (status == GOT_STATUS_CONFLICT)
3272 upa->conflicts++;
3273 if (status == GOT_STATUS_OBSTRUCTED)
3274 upa->obstructed++;
3275 if (status == GOT_STATUS_CANNOT_UPDATE)
3276 upa->not_updated++;
3277 if (status == GOT_STATUS_MISSING)
3278 upa->missing++;
3279 if (status == GOT_STATUS_CANNOT_DELETE)
3280 upa->not_deleted++;
3281 if (status == GOT_STATUS_UNVERSIONED)
3282 upa->unversioned++;
3284 while (path[0] == '/')
3285 path++;
3286 if (upa->verbosity >= 0)
3287 printf("%c %s\n", status, path);
3289 return NULL;
3292 static const struct got_error *
3293 switch_head_ref(struct got_reference *head_ref,
3294 struct got_object_id *commit_id, struct got_worktree *worktree,
3295 struct got_repository *repo)
3297 const struct got_error *err = NULL;
3298 char *base_id_str;
3299 int ref_has_moved = 0;
3301 /* Trivial case: switching between two different references. */
3302 if (strcmp(got_ref_get_name(head_ref),
3303 got_worktree_get_head_ref_name(worktree)) != 0) {
3304 printf("Switching work tree from %s to %s\n",
3305 got_worktree_get_head_ref_name(worktree),
3306 got_ref_get_name(head_ref));
3307 return got_worktree_set_head_ref(worktree, head_ref);
3310 err = check_linear_ancestry(commit_id,
3311 got_worktree_get_base_commit_id(worktree), 0, repo);
3312 if (err) {
3313 if (err->code != GOT_ERR_ANCESTRY)
3314 return err;
3315 ref_has_moved = 1;
3317 if (!ref_has_moved)
3318 return NULL;
3320 /* Switching to a rebased branch with the same reference name. */
3321 err = got_object_id_str(&base_id_str,
3322 got_worktree_get_base_commit_id(worktree));
3323 if (err)
3324 return err;
3325 printf("Reference %s now points at a different branch\n",
3326 got_worktree_get_head_ref_name(worktree));
3327 printf("Switching work tree from %s to %s\n", base_id_str,
3328 got_worktree_get_head_ref_name(worktree));
3329 return NULL;
3332 static const struct got_error *
3333 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3335 const struct got_error *err;
3336 int in_progress;
3338 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3339 if (err)
3340 return err;
3341 if (in_progress)
3342 return got_error(GOT_ERR_REBASING);
3344 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3345 if (err)
3346 return err;
3347 if (in_progress)
3348 return got_error(GOT_ERR_HISTEDIT_BUSY);
3350 return NULL;
3353 static const struct got_error *
3354 check_merge_in_progress(struct got_worktree *worktree,
3355 struct got_repository *repo)
3357 const struct got_error *err;
3358 int in_progress;
3360 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3361 if (err)
3362 return err;
3363 if (in_progress)
3364 return got_error(GOT_ERR_MERGE_BUSY);
3366 return NULL;
3369 static const struct got_error *
3370 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3371 char *argv[], struct got_worktree *worktree)
3373 const struct got_error *err = NULL;
3374 char *path;
3375 struct got_pathlist_entry *new;
3376 int i;
3378 if (argc == 0) {
3379 path = strdup("");
3380 if (path == NULL)
3381 return got_error_from_errno("strdup");
3382 return got_pathlist_append(paths, path, NULL);
3385 for (i = 0; i < argc; i++) {
3386 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3387 if (err)
3388 break;
3389 err = got_pathlist_insert(&new, paths, path, NULL);
3390 if (err || new == NULL /* duplicate */) {
3391 free(path);
3392 if (err)
3393 break;
3397 return err;
3400 static const struct got_error *
3401 wrap_not_worktree_error(const struct got_error *orig_err,
3402 const char *cmdname, const char *path)
3404 const struct got_error *err;
3405 struct got_repository *repo;
3406 static char msg[512];
3407 int *pack_fds = NULL;
3409 err = got_repo_pack_fds_open(&pack_fds);
3410 if (err)
3411 return err;
3413 err = got_repo_open(&repo, path, NULL, pack_fds);
3414 if (err)
3415 return orig_err;
3417 snprintf(msg, sizeof(msg),
3418 "'got %s' needs a work tree in addition to a git repository\n"
3419 "Work trees can be checked out from this Git repository with "
3420 "'got checkout'.\n"
3421 "The got(1) manual page contains more information.", cmdname);
3422 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3423 got_repo_close(repo);
3424 if (pack_fds) {
3425 const struct got_error *pack_err =
3426 got_repo_pack_fds_close(pack_fds);
3427 if (err == NULL)
3428 err = pack_err;
3430 return err;
3433 static const struct got_error *
3434 cmd_update(int argc, char *argv[])
3436 const struct got_error *error = NULL;
3437 struct got_repository *repo = NULL;
3438 struct got_worktree *worktree = NULL;
3439 char *worktree_path = NULL;
3440 struct got_object_id *commit_id = NULL;
3441 char *commit_id_str = NULL;
3442 const char *branch_name = NULL;
3443 struct got_reference *head_ref = NULL;
3444 struct got_pathlist_head paths;
3445 struct got_pathlist_entry *pe;
3446 int ch, verbosity = 0;
3447 struct got_update_progress_arg upa;
3448 int *pack_fds = NULL;
3450 TAILQ_INIT(&paths);
3452 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3453 switch (ch) {
3454 case 'b':
3455 branch_name = optarg;
3456 break;
3457 case 'c':
3458 commit_id_str = strdup(optarg);
3459 if (commit_id_str == NULL)
3460 return got_error_from_errno("strdup");
3461 break;
3462 case 'q':
3463 verbosity = -1;
3464 break;
3465 default:
3466 usage_update();
3467 /* NOTREACHED */
3471 argc -= optind;
3472 argv += optind;
3474 #ifndef PROFILE
3475 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3476 "unveil", NULL) == -1)
3477 err(1, "pledge");
3478 #endif
3479 worktree_path = getcwd(NULL, 0);
3480 if (worktree_path == NULL) {
3481 error = got_error_from_errno("getcwd");
3482 goto done;
3485 error = got_repo_pack_fds_open(&pack_fds);
3486 if (error != NULL)
3487 goto done;
3489 error = got_worktree_open(&worktree, worktree_path);
3490 if (error) {
3491 if (error->code == GOT_ERR_NOT_WORKTREE)
3492 error = wrap_not_worktree_error(error, "update",
3493 worktree_path);
3494 goto done;
3497 error = check_rebase_or_histedit_in_progress(worktree);
3498 if (error)
3499 goto done;
3501 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3502 NULL, pack_fds);
3503 if (error != NULL)
3504 goto done;
3506 error = apply_unveil(got_repo_get_path(repo), 0,
3507 got_worktree_get_root_path(worktree));
3508 if (error)
3509 goto done;
3511 error = check_merge_in_progress(worktree, repo);
3512 if (error)
3513 goto done;
3515 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3516 if (error)
3517 goto done;
3519 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3520 got_worktree_get_head_ref_name(worktree), 0);
3521 if (error != NULL)
3522 goto done;
3523 if (commit_id_str == NULL) {
3524 error = got_ref_resolve(&commit_id, repo, head_ref);
3525 if (error != NULL)
3526 goto done;
3527 error = got_object_id_str(&commit_id_str, commit_id);
3528 if (error != NULL)
3529 goto done;
3530 } else {
3531 struct got_reflist_head refs;
3532 TAILQ_INIT(&refs);
3533 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3534 NULL);
3535 if (error)
3536 goto done;
3537 error = got_repo_match_object_id(&commit_id, NULL,
3538 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3539 got_ref_list_free(&refs);
3540 free(commit_id_str);
3541 commit_id_str = NULL;
3542 if (error)
3543 goto done;
3544 error = got_object_id_str(&commit_id_str, commit_id);
3545 if (error)
3546 goto done;
3549 if (branch_name) {
3550 struct got_object_id *head_commit_id;
3551 TAILQ_FOREACH(pe, &paths, entry) {
3552 if (pe->path_len == 0)
3553 continue;
3554 error = got_error_msg(GOT_ERR_BAD_PATH,
3555 "switching between branches requires that "
3556 "the entire work tree gets updated");
3557 goto done;
3559 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3560 if (error)
3561 goto done;
3562 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3563 repo);
3564 free(head_commit_id);
3565 if (error != NULL)
3566 goto done;
3567 error = check_same_branch(commit_id, head_ref, NULL, repo);
3568 if (error)
3569 goto done;
3570 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3571 if (error)
3572 goto done;
3573 } else {
3574 error = check_linear_ancestry(commit_id,
3575 got_worktree_get_base_commit_id(worktree), 0, repo);
3576 if (error != NULL) {
3577 if (error->code == GOT_ERR_ANCESTRY)
3578 error = got_error(GOT_ERR_BRANCH_MOVED);
3579 goto done;
3581 error = check_same_branch(commit_id, head_ref, NULL, repo);
3582 if (error)
3583 goto done;
3586 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3587 commit_id) != 0) {
3588 error = got_worktree_set_base_commit_id(worktree, repo,
3589 commit_id);
3590 if (error)
3591 goto done;
3594 memset(&upa, 0, sizeof(upa));
3595 upa.verbosity = verbosity;
3596 error = got_worktree_checkout_files(worktree, &paths, repo,
3597 update_progress, &upa, check_cancelled, NULL);
3598 if (error != NULL)
3599 goto done;
3601 if (upa.did_something) {
3602 printf("Updated to %s: %s\n",
3603 got_worktree_get_head_ref_name(worktree), commit_id_str);
3604 } else
3605 printf("Already up-to-date\n");
3607 print_update_progress_stats(&upa);
3608 done:
3609 if (pack_fds) {
3610 const struct got_error *pack_err =
3611 got_repo_pack_fds_close(pack_fds);
3612 if (error == NULL)
3613 error = pack_err;
3615 free(worktree_path);
3616 TAILQ_FOREACH(pe, &paths, entry)
3617 free((char *)pe->path);
3618 got_pathlist_free(&paths);
3619 free(commit_id);
3620 free(commit_id_str);
3621 return error;
3624 static const struct got_error *
3625 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3626 const char *path, int diff_context, int ignore_whitespace,
3627 int force_text_diff, struct got_repository *repo, FILE *outfile)
3629 const struct got_error *err = NULL;
3630 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3631 FILE *f1 = NULL, *f2 = NULL;
3632 int fd1 = -1, fd2 = -1;
3634 fd1 = got_opentempfd();
3635 if (fd1 == -1)
3636 return got_error_from_errno("got_opentempfd");
3637 fd2 = got_opentempfd();
3638 if (fd2 == -1) {
3639 err = got_error_from_errno("got_opentempfd");
3640 goto done;
3643 if (blob_id1) {
3644 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3645 fd1);
3646 if (err)
3647 goto done;
3650 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3651 if (err)
3652 goto done;
3654 f1 = got_opentemp();
3655 if (f1 == NULL) {
3656 err = got_error_from_errno("got_opentemp");
3657 goto done;
3659 f2 = got_opentemp();
3660 if (f2 == NULL) {
3661 err = got_error_from_errno("got_opentemp");
3662 goto done;
3665 while (path[0] == '/')
3666 path++;
3667 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3668 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3669 force_text_diff, outfile);
3670 done:
3671 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3672 err = got_error_from_errno("close");
3673 if (blob1)
3674 got_object_blob_close(blob1);
3675 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3676 err = got_error_from_errno("close");
3677 got_object_blob_close(blob2);
3678 if (f1 && fclose(f1) == EOF && err == NULL)
3679 err = got_error_from_errno("fclose");
3680 if (f2 && fclose(f2) == EOF && err == NULL)
3681 err = got_error_from_errno("fclose");
3682 return err;
3685 static const struct got_error *
3686 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3687 const char *path, int diff_context, int ignore_whitespace,
3688 int force_text_diff, struct got_repository *repo, FILE *outfile)
3690 const struct got_error *err = NULL;
3691 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3692 struct got_diff_blob_output_unidiff_arg arg;
3693 FILE *f1 = NULL, *f2 = NULL;
3694 int fd1 = -1, fd2 = -1;
3696 if (tree_id1) {
3697 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3698 if (err)
3699 goto done;
3700 fd1 = got_opentempfd();
3701 if (fd1 == -1) {
3702 err = got_error_from_errno("got_opentempfd");
3703 goto done;
3707 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3708 if (err)
3709 goto done;
3711 f1 = got_opentemp();
3712 if (f1 == NULL) {
3713 err = got_error_from_errno("got_opentemp");
3714 goto done;
3717 f2 = got_opentemp();
3718 if (f2 == NULL) {
3719 err = got_error_from_errno("got_opentemp");
3720 goto done;
3722 fd2 = got_opentempfd();
3723 if (fd2 == -1) {
3724 err = got_error_from_errno("got_opentempfd");
3725 goto done;
3727 arg.diff_context = diff_context;
3728 arg.ignore_whitespace = ignore_whitespace;
3729 arg.force_text_diff = force_text_diff;
3730 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3731 arg.outfile = outfile;
3732 arg.lines = NULL;
3733 arg.nlines = 0;
3734 while (path[0] == '/')
3735 path++;
3736 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3737 got_diff_blob_output_unidiff, &arg, 1);
3738 done:
3739 if (tree1)
3740 got_object_tree_close(tree1);
3741 if (tree2)
3742 got_object_tree_close(tree2);
3743 if (f1 && fclose(f1) == EOF && err == NULL)
3744 err = got_error_from_errno("fclose");
3745 if (f2 && fclose(f2) == EOF && err == NULL)
3746 err = got_error_from_errno("fclose");
3747 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3748 err = got_error_from_errno("close");
3749 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3750 err = got_error_from_errno("close");
3751 return err;
3754 static const struct got_error *
3755 get_changed_paths(struct got_pathlist_head *paths,
3756 struct got_commit_object *commit, struct got_repository *repo)
3758 const struct got_error *err = NULL;
3759 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3760 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3761 struct got_object_qid *qid;
3763 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3764 if (qid != NULL) {
3765 struct got_commit_object *pcommit;
3766 err = got_object_open_as_commit(&pcommit, repo,
3767 &qid->id);
3768 if (err)
3769 return err;
3771 tree_id1 = got_object_id_dup(
3772 got_object_commit_get_tree_id(pcommit));
3773 if (tree_id1 == NULL) {
3774 got_object_commit_close(pcommit);
3775 return got_error_from_errno("got_object_id_dup");
3777 got_object_commit_close(pcommit);
3781 if (tree_id1) {
3782 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3783 if (err)
3784 goto done;
3787 tree_id2 = got_object_commit_get_tree_id(commit);
3788 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3789 if (err)
3790 goto done;
3792 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3793 got_diff_tree_collect_changed_paths, paths, 0);
3794 done:
3795 if (tree1)
3796 got_object_tree_close(tree1);
3797 if (tree2)
3798 got_object_tree_close(tree2);
3799 free(tree_id1);
3800 return err;
3803 static const struct got_error *
3804 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3805 const char *path, int diff_context, struct got_repository *repo,
3806 FILE *outfile)
3808 const struct got_error *err = NULL;
3809 struct got_commit_object *pcommit = NULL;
3810 char *id_str1 = NULL, *id_str2 = NULL;
3811 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3812 struct got_object_qid *qid;
3814 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3815 if (qid != NULL) {
3816 err = got_object_open_as_commit(&pcommit, repo,
3817 &qid->id);
3818 if (err)
3819 return err;
3820 err = got_object_id_str(&id_str1, &qid->id);
3821 if (err)
3822 goto done;
3825 err = got_object_id_str(&id_str2, id);
3826 if (err)
3827 goto done;
3829 if (path && path[0] != '\0') {
3830 int obj_type;
3831 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3832 if (err)
3833 goto done;
3834 if (pcommit) {
3835 err = got_object_id_by_path(&obj_id1, repo,
3836 pcommit, path);
3837 if (err) {
3838 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3839 free(obj_id2);
3840 goto done;
3844 err = got_object_get_type(&obj_type, repo, obj_id2);
3845 if (err) {
3846 free(obj_id2);
3847 goto done;
3849 fprintf(outfile,
3850 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3851 fprintf(outfile, "commit - %s\n",
3852 id_str1 ? id_str1 : "/dev/null");
3853 fprintf(outfile, "commit + %s\n", id_str2);
3854 switch (obj_type) {
3855 case GOT_OBJ_TYPE_BLOB:
3856 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3857 0, 0, repo, outfile);
3858 break;
3859 case GOT_OBJ_TYPE_TREE:
3860 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3861 0, 0, repo, outfile);
3862 break;
3863 default:
3864 err = got_error(GOT_ERR_OBJ_TYPE);
3865 break;
3867 free(obj_id1);
3868 free(obj_id2);
3869 } else {
3870 obj_id2 = got_object_commit_get_tree_id(commit);
3871 if (pcommit)
3872 obj_id1 = got_object_commit_get_tree_id(pcommit);
3873 fprintf(outfile,
3874 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3875 fprintf(outfile, "commit - %s\n",
3876 id_str1 ? id_str1 : "/dev/null");
3877 fprintf(outfile, "commit + %s\n", id_str2);
3878 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3879 repo, outfile);
3881 done:
3882 free(id_str1);
3883 free(id_str2);
3884 if (pcommit)
3885 got_object_commit_close(pcommit);
3886 return err;
3889 static char *
3890 get_datestr(time_t *time, char *datebuf)
3892 struct tm mytm, *tm;
3893 char *p, *s;
3895 tm = gmtime_r(time, &mytm);
3896 if (tm == NULL)
3897 return NULL;
3898 s = asctime_r(tm, datebuf);
3899 if (s == NULL)
3900 return NULL;
3901 p = strchr(s, '\n');
3902 if (p)
3903 *p = '\0';
3904 return s;
3907 static const struct got_error *
3908 match_commit(int *have_match, struct got_object_id *id,
3909 struct got_commit_object *commit, regex_t *regex)
3911 const struct got_error *err = NULL;
3912 regmatch_t regmatch;
3913 char *id_str = NULL, *logmsg = NULL;
3915 *have_match = 0;
3917 err = got_object_id_str(&id_str, id);
3918 if (err)
3919 return err;
3921 err = got_object_commit_get_logmsg(&logmsg, commit);
3922 if (err)
3923 goto done;
3925 if (regexec(regex, got_object_commit_get_author(commit), 1,
3926 &regmatch, 0) == 0 ||
3927 regexec(regex, got_object_commit_get_committer(commit), 1,
3928 &regmatch, 0) == 0 ||
3929 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3930 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3931 *have_match = 1;
3932 done:
3933 free(id_str);
3934 free(logmsg);
3935 return err;
3938 static void
3939 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3940 regex_t *regex)
3942 regmatch_t regmatch;
3943 struct got_pathlist_entry *pe;
3945 *have_match = 0;
3947 TAILQ_FOREACH(pe, changed_paths, entry) {
3948 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3949 *have_match = 1;
3950 break;
3955 static const struct got_error *
3956 match_patch(int *have_match, struct got_commit_object *commit,
3957 struct got_object_id *id, const char *path, int diff_context,
3958 struct got_repository *repo, regex_t *regex, FILE *f)
3960 const struct got_error *err = NULL;
3961 char *line = NULL;
3962 size_t linesize = 0;
3963 regmatch_t regmatch;
3965 *have_match = 0;
3967 err = got_opentemp_truncate(f);
3968 if (err)
3969 return err;
3971 err = print_patch(commit, id, path, diff_context, repo, f);
3972 if (err)
3973 goto done;
3975 if (fseeko(f, 0L, SEEK_SET) == -1) {
3976 err = got_error_from_errno("fseeko");
3977 goto done;
3980 while (getline(&line, &linesize, f) != -1) {
3981 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3982 *have_match = 1;
3983 break;
3986 done:
3987 free(line);
3988 return err;
3991 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3993 static const struct got_error*
3994 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3995 struct got_object_id *id, struct got_repository *repo,
3996 int local_only)
3998 static const struct got_error *err = NULL;
3999 struct got_reflist_entry *re;
4000 char *s;
4001 const char *name;
4003 *refs_str = NULL;
4005 TAILQ_FOREACH(re, refs, entry) {
4006 struct got_tag_object *tag = NULL;
4007 struct got_object_id *ref_id;
4008 int cmp;
4010 name = got_ref_get_name(re->ref);
4011 if (strcmp(name, GOT_REF_HEAD) == 0)
4012 continue;
4013 if (strncmp(name, "refs/", 5) == 0)
4014 name += 5;
4015 if (strncmp(name, "got/", 4) == 0)
4016 continue;
4017 if (strncmp(name, "heads/", 6) == 0)
4018 name += 6;
4019 if (strncmp(name, "remotes/", 8) == 0) {
4020 if (local_only)
4021 continue;
4022 name += 8;
4023 s = strstr(name, "/" GOT_REF_HEAD);
4024 if (s != NULL && s[strlen(s)] == '\0')
4025 continue;
4027 err = got_ref_resolve(&ref_id, repo, re->ref);
4028 if (err)
4029 break;
4030 if (strncmp(name, "tags/", 5) == 0) {
4031 err = got_object_open_as_tag(&tag, repo, ref_id);
4032 if (err) {
4033 if (err->code != GOT_ERR_OBJ_TYPE) {
4034 free(ref_id);
4035 break;
4037 /* Ref points at something other than a tag. */
4038 err = NULL;
4039 tag = NULL;
4042 cmp = got_object_id_cmp(tag ?
4043 got_object_tag_get_object_id(tag) : ref_id, id);
4044 free(ref_id);
4045 if (tag)
4046 got_object_tag_close(tag);
4047 if (cmp != 0)
4048 continue;
4049 s = *refs_str;
4050 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4051 s ? ", " : "", name) == -1) {
4052 err = got_error_from_errno("asprintf");
4053 free(s);
4054 *refs_str = NULL;
4055 break;
4057 free(s);
4060 return err;
4063 static const struct got_error *
4064 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4065 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4067 const struct got_error *err = NULL;
4068 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4069 char *comma, *s, *nl;
4070 struct got_reflist_head *refs;
4071 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4072 struct tm tm;
4073 time_t committer_time;
4075 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4076 if (refs) {
4077 err = build_refs_str(&ref_str, refs, id, repo, 1);
4078 if (err)
4079 return err;
4081 /* Display the first matching ref only. */
4082 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4083 *comma = '\0';
4086 if (ref_str == NULL) {
4087 err = got_object_id_str(&id_str, id);
4088 if (err)
4089 return err;
4092 committer_time = got_object_commit_get_committer_time(commit);
4093 if (gmtime_r(&committer_time, &tm) == NULL) {
4094 err = got_error_from_errno("gmtime_r");
4095 goto done;
4097 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4098 err = got_error(GOT_ERR_NO_SPACE);
4099 goto done;
4102 err = got_object_commit_get_logmsg(&logmsg0, commit);
4103 if (err)
4104 goto done;
4106 s = logmsg0;
4107 while (isspace((unsigned char)s[0]))
4108 s++;
4110 nl = strchr(s, '\n');
4111 if (nl) {
4112 *nl = '\0';
4115 if (ref_str)
4116 printf("%s%-7s %s\n", datebuf, ref_str, s);
4117 else
4118 printf("%s%.7s %s\n", datebuf, id_str, s);
4120 if (fflush(stdout) != 0 && err == NULL)
4121 err = got_error_from_errno("fflush");
4122 done:
4123 free(id_str);
4124 free(ref_str);
4125 free(logmsg0);
4126 return err;
4129 static const struct got_error *
4130 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4131 struct got_repository *repo, const char *path,
4132 struct got_pathlist_head *changed_paths, int show_patch,
4133 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4134 const char *custom_refs_str)
4136 const struct got_error *err = NULL;
4137 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4138 char datebuf[26];
4139 time_t committer_time;
4140 const char *author, *committer;
4141 char *refs_str = NULL;
4143 err = got_object_id_str(&id_str, id);
4144 if (err)
4145 return err;
4147 if (custom_refs_str == NULL) {
4148 struct got_reflist_head *refs;
4149 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4150 if (refs) {
4151 err = build_refs_str(&refs_str, refs, id, repo, 0);
4152 if (err)
4153 goto done;
4157 printf(GOT_COMMIT_SEP_STR);
4158 if (custom_refs_str)
4159 printf("commit %s (%s)\n", id_str, custom_refs_str);
4160 else
4161 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4162 refs_str ? refs_str : "", refs_str ? ")" : "");
4163 free(id_str);
4164 id_str = NULL;
4165 free(refs_str);
4166 refs_str = NULL;
4167 printf("from: %s\n", got_object_commit_get_author(commit));
4168 committer_time = got_object_commit_get_committer_time(commit);
4169 datestr = get_datestr(&committer_time, datebuf);
4170 if (datestr)
4171 printf("date: %s UTC\n", datestr);
4172 author = got_object_commit_get_author(commit);
4173 committer = got_object_commit_get_committer(commit);
4174 if (strcmp(author, committer) != 0)
4175 printf("via: %s\n", committer);
4176 if (got_object_commit_get_nparents(commit) > 1) {
4177 const struct got_object_id_queue *parent_ids;
4178 struct got_object_qid *qid;
4179 int n = 1;
4180 parent_ids = got_object_commit_get_parent_ids(commit);
4181 STAILQ_FOREACH(qid, parent_ids, entry) {
4182 err = got_object_id_str(&id_str, &qid->id);
4183 if (err)
4184 goto done;
4185 printf("parent %d: %s\n", n++, id_str);
4186 free(id_str);
4187 id_str = NULL;
4191 err = got_object_commit_get_logmsg(&logmsg0, commit);
4192 if (err)
4193 goto done;
4195 logmsg = logmsg0;
4196 do {
4197 line = strsep(&logmsg, "\n");
4198 if (line)
4199 printf(" %s\n", line);
4200 } while (line);
4201 free(logmsg0);
4203 if (changed_paths) {
4204 struct got_pathlist_entry *pe;
4205 TAILQ_FOREACH(pe, changed_paths, entry) {
4206 struct got_diff_changed_path *cp = pe->data;
4207 printf(" %c %s\n", cp->status, pe->path);
4209 printf("\n");
4211 if (show_patch) {
4212 err = print_patch(commit, id, path, diff_context, repo, stdout);
4213 if (err == 0)
4214 printf("\n");
4217 if (fflush(stdout) != 0 && err == NULL)
4218 err = got_error_from_errno("fflush");
4219 done:
4220 free(id_str);
4221 free(refs_str);
4222 return err;
4225 static const struct got_error *
4226 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4227 struct got_repository *repo, const char *path, int show_changed_paths,
4228 int show_patch, const char *search_pattern, int diff_context, int limit,
4229 int log_branches, int reverse_display_order,
4230 struct got_reflist_object_id_map *refs_idmap, int one_line,
4231 FILE *tmpfile)
4233 const struct got_error *err;
4234 struct got_commit_graph *graph;
4235 regex_t regex;
4236 int have_match;
4237 struct got_object_id_queue reversed_commits;
4238 struct got_object_qid *qid;
4239 struct got_commit_object *commit;
4240 struct got_pathlist_head changed_paths;
4241 struct got_pathlist_entry *pe;
4243 STAILQ_INIT(&reversed_commits);
4244 TAILQ_INIT(&changed_paths);
4246 if (search_pattern && regcomp(&regex, search_pattern,
4247 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4248 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4250 err = got_commit_graph_open(&graph, path, !log_branches);
4251 if (err)
4252 return err;
4253 err = got_commit_graph_iter_start(graph, root_id, repo,
4254 check_cancelled, NULL);
4255 if (err)
4256 goto done;
4257 for (;;) {
4258 struct got_object_id id;
4260 if (sigint_received || sigpipe_received)
4261 break;
4263 err = got_commit_graph_iter_next(&id, graph, repo,
4264 check_cancelled, NULL);
4265 if (err) {
4266 if (err->code == GOT_ERR_ITER_COMPLETED)
4267 err = NULL;
4268 break;
4271 err = got_object_open_as_commit(&commit, repo, &id);
4272 if (err)
4273 break;
4275 if (show_changed_paths && !reverse_display_order) {
4276 err = get_changed_paths(&changed_paths, commit, repo);
4277 if (err)
4278 break;
4281 if (search_pattern) {
4282 err = match_commit(&have_match, &id, commit, &regex);
4283 if (err) {
4284 got_object_commit_close(commit);
4285 break;
4287 if (have_match == 0 && show_changed_paths)
4288 match_changed_paths(&have_match,
4289 &changed_paths, &regex);
4290 if (have_match == 0 && show_patch) {
4291 err = match_patch(&have_match, commit, &id,
4292 path, diff_context, repo, &regex,
4293 tmpfile);
4294 if (err)
4295 break;
4297 if (have_match == 0) {
4298 got_object_commit_close(commit);
4299 TAILQ_FOREACH(pe, &changed_paths, entry) {
4300 free((char *)pe->path);
4301 free(pe->data);
4303 got_pathlist_free(&changed_paths);
4304 continue;
4308 if (reverse_display_order) {
4309 err = got_object_qid_alloc(&qid, &id);
4310 if (err)
4311 break;
4312 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4313 got_object_commit_close(commit);
4314 } else {
4315 if (one_line)
4316 err = print_commit_oneline(commit, &id,
4317 repo, refs_idmap);
4318 else
4319 err = print_commit(commit, &id, repo, path,
4320 show_changed_paths ? &changed_paths : NULL,
4321 show_patch, diff_context, refs_idmap, NULL);
4322 got_object_commit_close(commit);
4323 if (err)
4324 break;
4326 if ((limit && --limit == 0) ||
4327 (end_id && got_object_id_cmp(&id, end_id) == 0))
4328 break;
4330 TAILQ_FOREACH(pe, &changed_paths, entry) {
4331 free((char *)pe->path);
4332 free(pe->data);
4334 got_pathlist_free(&changed_paths);
4336 if (reverse_display_order) {
4337 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4338 err = got_object_open_as_commit(&commit, repo,
4339 &qid->id);
4340 if (err)
4341 break;
4342 if (show_changed_paths) {
4343 err = get_changed_paths(&changed_paths,
4344 commit, repo);
4345 if (err)
4346 break;
4348 if (one_line)
4349 err = print_commit_oneline(commit, &qid->id,
4350 repo, refs_idmap);
4351 else
4352 err = print_commit(commit, &qid->id, repo, path,
4353 show_changed_paths ? &changed_paths : NULL,
4354 show_patch, diff_context, refs_idmap, NULL);
4355 got_object_commit_close(commit);
4356 if (err)
4357 break;
4358 TAILQ_FOREACH(pe, &changed_paths, entry) {
4359 free((char *)pe->path);
4360 free(pe->data);
4362 got_pathlist_free(&changed_paths);
4365 done:
4366 while (!STAILQ_EMPTY(&reversed_commits)) {
4367 qid = STAILQ_FIRST(&reversed_commits);
4368 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4369 got_object_qid_free(qid);
4371 TAILQ_FOREACH(pe, &changed_paths, entry) {
4372 free((char *)pe->path);
4373 free(pe->data);
4375 got_pathlist_free(&changed_paths);
4376 if (search_pattern)
4377 regfree(&regex);
4378 got_commit_graph_close(graph);
4379 return err;
4382 __dead static void
4383 usage_log(void)
4385 fprintf(stderr, "usage: %s log [-bPpRs] [-C number] [-c commit] [-l N] "
4386 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4387 getprogname());
4388 exit(1);
4391 static int
4392 get_default_log_limit(void)
4394 const char *got_default_log_limit;
4395 long long n;
4396 const char *errstr;
4398 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4399 if (got_default_log_limit == NULL)
4400 return 0;
4401 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4402 if (errstr != NULL)
4403 return 0;
4404 return n;
4407 static const struct got_error *
4408 cmd_log(int argc, char *argv[])
4410 const struct got_error *error;
4411 struct got_repository *repo = NULL;
4412 struct got_worktree *worktree = NULL;
4413 struct got_object_id *start_id = NULL, *end_id = NULL;
4414 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4415 const char *start_commit = NULL, *end_commit = NULL;
4416 const char *search_pattern = NULL;
4417 int diff_context = -1, ch;
4418 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4419 int reverse_display_order = 0, one_line = 0;
4420 const char *errstr;
4421 struct got_reflist_head refs;
4422 struct got_reflist_object_id_map *refs_idmap = NULL;
4423 FILE *tmpfile = NULL;
4424 int *pack_fds = NULL;
4426 TAILQ_INIT(&refs);
4428 #ifndef PROFILE
4429 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4430 NULL)
4431 == -1)
4432 err(1, "pledge");
4433 #endif
4435 limit = get_default_log_limit();
4437 while ((ch = getopt(argc, argv, "bC:c:l:PpRr:S:sx:")) != -1) {
4438 switch (ch) {
4439 case 'b':
4440 log_branches = 1;
4441 break;
4442 case 'C':
4443 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4444 &errstr);
4445 if (errstr != NULL)
4446 errx(1, "number of context lines is %s: %s",
4447 errstr, optarg);
4448 break;
4449 case 'c':
4450 start_commit = optarg;
4451 break;
4452 case 'l':
4453 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4454 if (errstr != NULL)
4455 errx(1, "number of commits is %s: %s",
4456 errstr, optarg);
4457 break;
4458 case 'P':
4459 show_changed_paths = 1;
4460 break;
4461 case 'p':
4462 show_patch = 1;
4463 break;
4464 case 'R':
4465 reverse_display_order = 1;
4466 break;
4467 case 'r':
4468 repo_path = realpath(optarg, NULL);
4469 if (repo_path == NULL)
4470 return got_error_from_errno2("realpath",
4471 optarg);
4472 got_path_strip_trailing_slashes(repo_path);
4473 break;
4474 case 'S':
4475 search_pattern = optarg;
4476 break;
4477 case 's':
4478 one_line = 1;
4479 break;
4480 case 'x':
4481 end_commit = optarg;
4482 break;
4483 default:
4484 usage_log();
4485 /* NOTREACHED */
4489 argc -= optind;
4490 argv += optind;
4492 if (diff_context == -1)
4493 diff_context = 3;
4494 else if (!show_patch)
4495 errx(1, "-C requires -p");
4497 if (one_line && (show_patch || show_changed_paths))
4498 errx(1, "cannot use -s with -p or -P");
4500 cwd = getcwd(NULL, 0);
4501 if (cwd == NULL) {
4502 error = got_error_from_errno("getcwd");
4503 goto done;
4506 error = got_repo_pack_fds_open(&pack_fds);
4507 if (error != NULL)
4508 goto done;
4510 if (repo_path == NULL) {
4511 error = got_worktree_open(&worktree, cwd);
4512 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4513 goto done;
4514 error = NULL;
4517 if (argc == 1) {
4518 if (worktree) {
4519 error = got_worktree_resolve_path(&path, worktree,
4520 argv[0]);
4521 if (error)
4522 goto done;
4523 } else {
4524 path = strdup(argv[0]);
4525 if (path == NULL) {
4526 error = got_error_from_errno("strdup");
4527 goto done;
4530 } else if (argc != 0)
4531 usage_log();
4533 if (repo_path == NULL) {
4534 repo_path = worktree ?
4535 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4537 if (repo_path == NULL) {
4538 error = got_error_from_errno("strdup");
4539 goto done;
4542 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4543 if (error != NULL)
4544 goto done;
4546 error = apply_unveil(got_repo_get_path(repo), 1,
4547 worktree ? got_worktree_get_root_path(worktree) : NULL);
4548 if (error)
4549 goto done;
4551 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4552 if (error)
4553 goto done;
4555 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4556 if (error)
4557 goto done;
4559 if (start_commit == NULL) {
4560 struct got_reference *head_ref;
4561 struct got_commit_object *commit = NULL;
4562 error = got_ref_open(&head_ref, repo,
4563 worktree ? got_worktree_get_head_ref_name(worktree)
4564 : GOT_REF_HEAD, 0);
4565 if (error != NULL)
4566 goto done;
4567 error = got_ref_resolve(&start_id, repo, head_ref);
4568 got_ref_close(head_ref);
4569 if (error != NULL)
4570 goto done;
4571 error = got_object_open_as_commit(&commit, repo,
4572 start_id);
4573 if (error != NULL)
4574 goto done;
4575 got_object_commit_close(commit);
4576 } else {
4577 error = got_repo_match_object_id(&start_id, NULL,
4578 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4579 if (error != NULL)
4580 goto done;
4582 if (end_commit != NULL) {
4583 error = got_repo_match_object_id(&end_id, NULL,
4584 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4585 if (error != NULL)
4586 goto done;
4589 if (worktree) {
4591 * If a path was specified on the command line it was resolved
4592 * to a path in the work tree above. Prepend the work tree's
4593 * path prefix to obtain the corresponding in-repository path.
4595 if (path) {
4596 const char *prefix;
4597 prefix = got_worktree_get_path_prefix(worktree);
4598 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4599 (path[0] != '\0') ? "/" : "", path) == -1) {
4600 error = got_error_from_errno("asprintf");
4601 goto done;
4604 } else
4605 error = got_repo_map_path(&in_repo_path, repo,
4606 path ? path : "");
4607 if (error != NULL)
4608 goto done;
4609 if (in_repo_path) {
4610 free(path);
4611 path = in_repo_path;
4614 if (worktree) {
4615 /* Release work tree lock. */
4616 got_worktree_close(worktree);
4617 worktree = NULL;
4620 if (search_pattern && show_patch) {
4621 tmpfile = got_opentemp();
4622 if (tmpfile == NULL) {
4623 error = got_error_from_errno("got_opentemp");
4624 goto done;
4628 error = print_commits(start_id, end_id, repo, path ? path : "",
4629 show_changed_paths, show_patch, search_pattern, diff_context,
4630 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4631 tmpfile);
4632 done:
4633 free(path);
4634 free(repo_path);
4635 free(cwd);
4636 if (worktree)
4637 got_worktree_close(worktree);
4638 if (repo) {
4639 const struct got_error *close_err = got_repo_close(repo);
4640 if (error == NULL)
4641 error = close_err;
4643 if (pack_fds) {
4644 const struct got_error *pack_err =
4645 got_repo_pack_fds_close(pack_fds);
4646 if (error == NULL)
4647 error = pack_err;
4649 if (refs_idmap)
4650 got_reflist_object_id_map_free(refs_idmap);
4651 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4652 error = got_error_from_errno("fclose");
4653 got_ref_list_free(&refs);
4654 return error;
4657 __dead static void
4658 usage_diff(void)
4660 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4661 "[-r repository-path] [object1 object2 | path ...]\n",
4662 getprogname());
4663 exit(1);
4666 struct print_diff_arg {
4667 struct got_repository *repo;
4668 struct got_worktree *worktree;
4669 int diff_context;
4670 const char *id_str;
4671 int header_shown;
4672 int diff_staged;
4673 enum got_diff_algorithm diff_algo;
4674 int ignore_whitespace;
4675 int force_text_diff;
4676 FILE *f1;
4677 FILE *f2;
4681 * Create a file which contains the target path of a symlink so we can feed
4682 * it as content to the diff engine.
4684 static const struct got_error *
4685 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4686 const char *abspath)
4688 const struct got_error *err = NULL;
4689 char target_path[PATH_MAX];
4690 ssize_t target_len, outlen;
4692 *fd = -1;
4694 if (dirfd != -1) {
4695 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4696 if (target_len == -1)
4697 return got_error_from_errno2("readlinkat", abspath);
4698 } else {
4699 target_len = readlink(abspath, target_path, PATH_MAX);
4700 if (target_len == -1)
4701 return got_error_from_errno2("readlink", abspath);
4704 *fd = got_opentempfd();
4705 if (*fd == -1)
4706 return got_error_from_errno("got_opentempfd");
4708 outlen = write(*fd, target_path, target_len);
4709 if (outlen == -1) {
4710 err = got_error_from_errno("got_opentempfd");
4711 goto done;
4714 if (lseek(*fd, 0, SEEK_SET) == -1) {
4715 err = got_error_from_errno2("lseek", abspath);
4716 goto done;
4718 done:
4719 if (err) {
4720 close(*fd);
4721 *fd = -1;
4723 return err;
4726 static const struct got_error *
4727 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4728 const char *path, struct got_object_id *blob_id,
4729 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4730 int dirfd, const char *de_name)
4732 struct print_diff_arg *a = arg;
4733 const struct got_error *err = NULL;
4734 struct got_blob_object *blob1 = NULL;
4735 int fd = -1, fd1 = -1, fd2 = -1;
4736 FILE *f2 = NULL;
4737 char *abspath = NULL, *label1 = NULL;
4738 struct stat sb;
4739 off_t size1 = 0;
4740 int f2_exists = 0;
4742 memset(&sb, 0, sizeof(sb));
4744 if (a->diff_staged) {
4745 if (staged_status != GOT_STATUS_MODIFY &&
4746 staged_status != GOT_STATUS_ADD &&
4747 staged_status != GOT_STATUS_DELETE)
4748 return NULL;
4749 } else {
4750 if (staged_status == GOT_STATUS_DELETE)
4751 return NULL;
4752 if (status == GOT_STATUS_NONEXISTENT)
4753 return got_error_set_errno(ENOENT, path);
4754 if (status != GOT_STATUS_MODIFY &&
4755 status != GOT_STATUS_ADD &&
4756 status != GOT_STATUS_DELETE &&
4757 status != GOT_STATUS_CONFLICT)
4758 return NULL;
4761 err = got_opentemp_truncate(a->f1);
4762 if (err)
4763 return got_error_from_errno("got_opentemp_truncate");
4764 err = got_opentemp_truncate(a->f2);
4765 if (err)
4766 return got_error_from_errno("got_opentemp_truncate");
4768 if (!a->header_shown) {
4769 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4770 got_worktree_get_root_path(a->worktree));
4771 printf("commit - %s\n", a->id_str);
4772 printf("path + %s%s\n",
4773 got_worktree_get_root_path(a->worktree),
4774 a->diff_staged ? " (staged changes)" : "");
4775 a->header_shown = 1;
4778 if (a->diff_staged) {
4779 const char *label1 = NULL, *label2 = NULL;
4780 switch (staged_status) {
4781 case GOT_STATUS_MODIFY:
4782 label1 = path;
4783 label2 = path;
4784 break;
4785 case GOT_STATUS_ADD:
4786 label2 = path;
4787 break;
4788 case GOT_STATUS_DELETE:
4789 label1 = path;
4790 break;
4791 default:
4792 return got_error(GOT_ERR_FILE_STATUS);
4794 fd1 = got_opentempfd();
4795 if (fd1 == -1) {
4796 err = got_error_from_errno("got_opentempfd");
4797 goto done;
4799 fd2 = got_opentempfd();
4800 if (fd2 == -1) {
4801 err = got_error_from_errno("got_opentempfd");
4802 goto done;
4804 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4805 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4806 a->diff_algo, a->diff_context, a->ignore_whitespace,
4807 a->force_text_diff, a->repo, stdout);
4808 goto done;
4811 fd1 = got_opentempfd();
4812 if (fd1 == -1) {
4813 err = got_error_from_errno("got_opentempfd");
4814 goto done;
4817 if (staged_status == GOT_STATUS_ADD ||
4818 staged_status == GOT_STATUS_MODIFY) {
4819 char *id_str;
4820 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4821 8192, fd1);
4822 if (err)
4823 goto done;
4824 err = got_object_id_str(&id_str, staged_blob_id);
4825 if (err)
4826 goto done;
4827 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4828 err = got_error_from_errno("asprintf");
4829 free(id_str);
4830 goto done;
4832 free(id_str);
4833 } else if (status != GOT_STATUS_ADD) {
4834 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4835 fd1);
4836 if (err)
4837 goto done;
4840 if (status != GOT_STATUS_DELETE) {
4841 if (asprintf(&abspath, "%s/%s",
4842 got_worktree_get_root_path(a->worktree), path) == -1) {
4843 err = got_error_from_errno("asprintf");
4844 goto done;
4847 if (dirfd != -1) {
4848 fd = openat(dirfd, de_name,
4849 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4850 if (fd == -1) {
4851 if (!got_err_open_nofollow_on_symlink()) {
4852 err = got_error_from_errno2("openat",
4853 abspath);
4854 goto done;
4856 err = get_symlink_target_file(&fd, dirfd,
4857 de_name, abspath);
4858 if (err)
4859 goto done;
4861 } else {
4862 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4863 if (fd == -1) {
4864 if (!got_err_open_nofollow_on_symlink()) {
4865 err = got_error_from_errno2("open",
4866 abspath);
4867 goto done;
4869 err = get_symlink_target_file(&fd, dirfd,
4870 de_name, abspath);
4871 if (err)
4872 goto done;
4875 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4876 err = got_error_from_errno2("fstatat", abspath);
4877 goto done;
4879 f2 = fdopen(fd, "r");
4880 if (f2 == NULL) {
4881 err = got_error_from_errno2("fdopen", abspath);
4882 goto done;
4884 fd = -1;
4885 f2_exists = 1;
4888 if (blob1) {
4889 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4890 a->f1, blob1);
4891 if (err)
4892 goto done;
4895 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4896 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4897 a->ignore_whitespace, a->force_text_diff, stdout);
4898 done:
4899 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4900 err = got_error_from_errno("close");
4901 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4902 err = got_error_from_errno("close");
4903 if (blob1)
4904 got_object_blob_close(blob1);
4905 if (fd != -1 && close(fd) == -1 && err == NULL)
4906 err = got_error_from_errno("close");
4907 if (f2 && fclose(f2) == EOF && err == NULL)
4908 err = got_error_from_errno("fclose");
4909 free(abspath);
4910 return err;
4913 static const struct got_error *
4914 cmd_diff(int argc, char *argv[])
4916 const struct got_error *error;
4917 struct got_repository *repo = NULL;
4918 struct got_worktree *worktree = NULL;
4919 char *cwd = NULL, *repo_path = NULL;
4920 const char *commit_args[2] = { NULL, NULL };
4921 int ncommit_args = 0;
4922 struct got_object_id *ids[2] = { NULL, NULL };
4923 char *labels[2] = { NULL, NULL };
4924 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4925 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4926 int force_text_diff = 0, force_path = 0, rflag = 0;
4927 const char *errstr;
4928 struct got_reflist_head refs;
4929 struct got_pathlist_head paths;
4930 struct got_pathlist_entry *pe;
4931 FILE *f1 = NULL, *f2 = NULL;
4932 int fd1 = -1, fd2 = -1;
4933 int *pack_fds = NULL;
4935 TAILQ_INIT(&refs);
4936 TAILQ_INIT(&paths);
4938 #ifndef PROFILE
4939 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4940 NULL) == -1)
4941 err(1, "pledge");
4942 #endif
4944 while ((ch = getopt(argc, argv, "aC:c:Pr:sw")) != -1) {
4945 switch (ch) {
4946 case 'a':
4947 force_text_diff = 1;
4948 break;
4949 case 'C':
4950 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4951 &errstr);
4952 if (errstr != NULL)
4953 errx(1, "number of context lines is %s: %s",
4954 errstr, optarg);
4955 break;
4956 case 'c':
4957 if (ncommit_args >= 2)
4958 errx(1, "too many -c options used");
4959 commit_args[ncommit_args++] = optarg;
4960 break;
4961 case 'P':
4962 force_path = 1;
4963 break;
4964 case 'r':
4965 repo_path = realpath(optarg, NULL);
4966 if (repo_path == NULL)
4967 return got_error_from_errno2("realpath",
4968 optarg);
4969 got_path_strip_trailing_slashes(repo_path);
4970 rflag = 1;
4971 break;
4972 case 's':
4973 diff_staged = 1;
4974 break;
4975 case 'w':
4976 ignore_whitespace = 1;
4977 break;
4978 default:
4979 usage_diff();
4980 /* NOTREACHED */
4984 argc -= optind;
4985 argv += optind;
4987 cwd = getcwd(NULL, 0);
4988 if (cwd == NULL) {
4989 error = got_error_from_errno("getcwd");
4990 goto done;
4993 error = got_repo_pack_fds_open(&pack_fds);
4994 if (error != NULL)
4995 goto done;
4997 if (repo_path == NULL) {
4998 error = got_worktree_open(&worktree, cwd);
4999 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5000 goto done;
5001 else
5002 error = NULL;
5003 if (worktree) {
5004 repo_path =
5005 strdup(got_worktree_get_repo_path(worktree));
5006 if (repo_path == NULL) {
5007 error = got_error_from_errno("strdup");
5008 goto done;
5010 } else {
5011 repo_path = strdup(cwd);
5012 if (repo_path == NULL) {
5013 error = got_error_from_errno("strdup");
5014 goto done;
5019 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5020 free(repo_path);
5021 if (error != NULL)
5022 goto done;
5024 if (rflag || worktree == NULL || ncommit_args > 0) {
5025 if (force_path) {
5026 error = got_error_msg(GOT_ERR_NOT_IMPL,
5027 "-P option can only be used when diffing "
5028 "a work tree");
5029 goto done;
5031 if (diff_staged) {
5032 error = got_error_msg(GOT_ERR_NOT_IMPL,
5033 "-s option can only be used when diffing "
5034 "a work tree");
5035 goto done;
5039 error = apply_unveil(got_repo_get_path(repo), 1,
5040 worktree ? got_worktree_get_root_path(worktree) : NULL);
5041 if (error)
5042 goto done;
5044 if ((!force_path && argc == 2) || ncommit_args > 0) {
5045 int obj_type = (ncommit_args > 0 ?
5046 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5047 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5048 NULL);
5049 if (error)
5050 goto done;
5051 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5052 const char *arg;
5053 if (ncommit_args > 0)
5054 arg = commit_args[i];
5055 else
5056 arg = argv[i];
5057 error = got_repo_match_object_id(&ids[i], &labels[i],
5058 arg, obj_type, &refs, repo);
5059 if (error) {
5060 if (error->code != GOT_ERR_NOT_REF &&
5061 error->code != GOT_ERR_NO_OBJ)
5062 goto done;
5063 if (ncommit_args > 0)
5064 goto done;
5065 error = NULL;
5066 break;
5071 f1 = got_opentemp();
5072 if (f1 == NULL) {
5073 error = got_error_from_errno("got_opentemp");
5074 goto done;
5077 f2 = got_opentemp();
5078 if (f2 == NULL) {
5079 error = got_error_from_errno("got_opentemp");
5080 goto done;
5083 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5084 struct print_diff_arg arg;
5085 char *id_str;
5087 if (worktree == NULL) {
5088 if (argc == 2 && ids[0] == NULL) {
5089 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5090 goto done;
5091 } else if (argc == 2 && ids[1] == NULL) {
5092 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5093 goto done;
5094 } else if (argc > 0) {
5095 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5096 "%s", "specified paths cannot be resolved");
5097 goto done;
5098 } else {
5099 error = got_error(GOT_ERR_NOT_WORKTREE);
5100 goto done;
5104 error = get_worktree_paths_from_argv(&paths, argc, argv,
5105 worktree);
5106 if (error)
5107 goto done;
5109 error = got_object_id_str(&id_str,
5110 got_worktree_get_base_commit_id(worktree));
5111 if (error)
5112 goto done;
5113 arg.repo = repo;
5114 arg.worktree = worktree;
5115 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5116 arg.diff_context = diff_context;
5117 arg.id_str = id_str;
5118 arg.header_shown = 0;
5119 arg.diff_staged = diff_staged;
5120 arg.ignore_whitespace = ignore_whitespace;
5121 arg.force_text_diff = force_text_diff;
5122 arg.f1 = f1;
5123 arg.f2 = f2;
5125 error = got_worktree_status(worktree, &paths, repo, 0,
5126 print_diff, &arg, check_cancelled, NULL);
5127 free(id_str);
5128 goto done;
5131 if (ncommit_args == 1) {
5132 struct got_commit_object *commit;
5133 error = got_object_open_as_commit(&commit, repo, ids[0]);
5134 if (error)
5135 goto done;
5137 labels[1] = labels[0];
5138 ids[1] = ids[0];
5139 if (got_object_commit_get_nparents(commit) > 0) {
5140 const struct got_object_id_queue *pids;
5141 struct got_object_qid *pid;
5142 pids = got_object_commit_get_parent_ids(commit);
5143 pid = STAILQ_FIRST(pids);
5144 ids[0] = got_object_id_dup(&pid->id);
5145 if (ids[0] == NULL) {
5146 error = got_error_from_errno(
5147 "got_object_id_dup");
5148 got_object_commit_close(commit);
5149 goto done;
5151 error = got_object_id_str(&labels[0], ids[0]);
5152 if (error) {
5153 got_object_commit_close(commit);
5154 goto done;
5156 } else {
5157 ids[0] = NULL;
5158 labels[0] = strdup("/dev/null");
5159 if (labels[0] == NULL) {
5160 error = got_error_from_errno("strdup");
5161 got_object_commit_close(commit);
5162 goto done;
5166 got_object_commit_close(commit);
5169 if (ncommit_args == 0 && argc > 2) {
5170 error = got_error_msg(GOT_ERR_BAD_PATH,
5171 "path arguments cannot be used when diffing two objects");
5172 goto done;
5175 if (ids[0]) {
5176 error = got_object_get_type(&type1, repo, ids[0]);
5177 if (error)
5178 goto done;
5181 error = got_object_get_type(&type2, repo, ids[1]);
5182 if (error)
5183 goto done;
5184 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5185 error = got_error(GOT_ERR_OBJ_TYPE);
5186 goto done;
5188 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5189 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5190 "path arguments cannot be used when diffing blobs");
5191 goto done;
5194 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5195 char *in_repo_path;
5196 struct got_pathlist_entry *new;
5197 if (worktree) {
5198 const char *prefix;
5199 char *p;
5200 error = got_worktree_resolve_path(&p, worktree,
5201 argv[i]);
5202 if (error)
5203 goto done;
5204 prefix = got_worktree_get_path_prefix(worktree);
5205 while (prefix[0] == '/')
5206 prefix++;
5207 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5208 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5209 p) == -1) {
5210 error = got_error_from_errno("asprintf");
5211 free(p);
5212 goto done;
5214 free(p);
5215 } else {
5216 char *mapped_path, *s;
5217 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5218 if (error)
5219 goto done;
5220 s = mapped_path;
5221 while (s[0] == '/')
5222 s++;
5223 in_repo_path = strdup(s);
5224 if (in_repo_path == NULL) {
5225 error = got_error_from_errno("asprintf");
5226 free(mapped_path);
5227 goto done;
5229 free(mapped_path);
5232 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5233 if (error || new == NULL /* duplicate */)
5234 free(in_repo_path);
5235 if (error)
5236 goto done;
5239 if (worktree) {
5240 /* Release work tree lock. */
5241 got_worktree_close(worktree);
5242 worktree = NULL;
5245 fd1 = got_opentempfd();
5246 if (fd1 == -1) {
5247 error = got_error_from_errno("got_opentempfd");
5248 goto done;
5251 fd2 = got_opentempfd();
5252 if (fd2 == -1) {
5253 error = got_error_from_errno("got_opentempfd");
5254 goto done;
5257 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5258 case GOT_OBJ_TYPE_BLOB:
5259 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5260 fd1, fd2, ids[0], ids[1], NULL, NULL,
5261 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5262 ignore_whitespace, force_text_diff, repo, stdout);
5263 break;
5264 case GOT_OBJ_TYPE_TREE:
5265 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5266 ids[0], ids[1], &paths, "", "",
5267 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5268 ignore_whitespace, force_text_diff, repo, stdout);
5269 break;
5270 case GOT_OBJ_TYPE_COMMIT:
5271 printf("diff %s %s\n", labels[0], labels[1]);
5272 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5273 fd1, fd2, ids[0], ids[1], &paths,
5274 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5275 ignore_whitespace, force_text_diff, repo, stdout);
5276 break;
5277 default:
5278 error = got_error(GOT_ERR_OBJ_TYPE);
5280 done:
5281 free(labels[0]);
5282 free(labels[1]);
5283 free(ids[0]);
5284 free(ids[1]);
5285 if (worktree)
5286 got_worktree_close(worktree);
5287 if (repo) {
5288 const struct got_error *close_err = got_repo_close(repo);
5289 if (error == NULL)
5290 error = close_err;
5292 if (pack_fds) {
5293 const struct got_error *pack_err =
5294 got_repo_pack_fds_close(pack_fds);
5295 if (error == NULL)
5296 error = pack_err;
5298 TAILQ_FOREACH(pe, &paths, entry)
5299 free((char *)pe->path);
5300 got_pathlist_free(&paths);
5301 got_ref_list_free(&refs);
5302 if (f1 && fclose(f1) == EOF && error == NULL)
5303 error = got_error_from_errno("fclose");
5304 if (f2 && fclose(f2) == EOF && error == NULL)
5305 error = got_error_from_errno("fclose");
5306 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5307 error = got_error_from_errno("close");
5308 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5309 error = got_error_from_errno("close");
5310 return error;
5313 __dead static void
5314 usage_blame(void)
5316 fprintf(stderr,
5317 "usage: %s blame [-c commit] [-r repository-path] path\n",
5318 getprogname());
5319 exit(1);
5322 struct blame_line {
5323 int annotated;
5324 char *id_str;
5325 char *committer;
5326 char datebuf[11]; /* YYYY-MM-DD + NUL */
5329 struct blame_cb_args {
5330 struct blame_line *lines;
5331 int nlines;
5332 int nlines_prec;
5333 int lineno_cur;
5334 off_t *line_offsets;
5335 FILE *f;
5336 struct got_repository *repo;
5339 static const struct got_error *
5340 blame_cb(void *arg, int nlines, int lineno,
5341 struct got_commit_object *commit, struct got_object_id *id)
5343 const struct got_error *err = NULL;
5344 struct blame_cb_args *a = arg;
5345 struct blame_line *bline;
5346 char *line = NULL;
5347 size_t linesize = 0;
5348 off_t offset;
5349 struct tm tm;
5350 time_t committer_time;
5352 if (nlines != a->nlines ||
5353 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5354 return got_error(GOT_ERR_RANGE);
5356 if (sigint_received)
5357 return got_error(GOT_ERR_ITER_COMPLETED);
5359 if (lineno == -1)
5360 return NULL; /* no change in this commit */
5362 /* Annotate this line. */
5363 bline = &a->lines[lineno - 1];
5364 if (bline->annotated)
5365 return NULL;
5366 err = got_object_id_str(&bline->id_str, id);
5367 if (err)
5368 return err;
5370 bline->committer = strdup(got_object_commit_get_committer(commit));
5371 if (bline->committer == NULL) {
5372 err = got_error_from_errno("strdup");
5373 goto done;
5376 committer_time = got_object_commit_get_committer_time(commit);
5377 if (gmtime_r(&committer_time, &tm) == NULL)
5378 return got_error_from_errno("gmtime_r");
5379 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5380 &tm) == 0) {
5381 err = got_error(GOT_ERR_NO_SPACE);
5382 goto done;
5384 bline->annotated = 1;
5386 /* Print lines annotated so far. */
5387 bline = &a->lines[a->lineno_cur - 1];
5388 if (!bline->annotated)
5389 goto done;
5391 offset = a->line_offsets[a->lineno_cur - 1];
5392 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5393 err = got_error_from_errno("fseeko");
5394 goto done;
5397 while (a->lineno_cur <= a->nlines && bline->annotated) {
5398 char *smallerthan, *at, *nl, *committer;
5399 size_t len;
5401 if (getline(&line, &linesize, a->f) == -1) {
5402 if (ferror(a->f))
5403 err = got_error_from_errno("getline");
5404 break;
5407 committer = bline->committer;
5408 smallerthan = strchr(committer, '<');
5409 if (smallerthan && smallerthan[1] != '\0')
5410 committer = smallerthan + 1;
5411 at = strchr(committer, '@');
5412 if (at)
5413 *at = '\0';
5414 len = strlen(committer);
5415 if (len >= 9)
5416 committer[8] = '\0';
5418 nl = strchr(line, '\n');
5419 if (nl)
5420 *nl = '\0';
5421 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5422 bline->id_str, bline->datebuf, committer, line);
5424 a->lineno_cur++;
5425 bline = &a->lines[a->lineno_cur - 1];
5427 done:
5428 free(line);
5429 return err;
5432 static const struct got_error *
5433 cmd_blame(int argc, char *argv[])
5435 const struct got_error *error;
5436 struct got_repository *repo = NULL;
5437 struct got_worktree *worktree = NULL;
5438 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5439 char *link_target = NULL;
5440 struct got_object_id *obj_id = NULL;
5441 struct got_object_id *commit_id = NULL;
5442 struct got_commit_object *commit = NULL;
5443 struct got_blob_object *blob = NULL;
5444 char *commit_id_str = NULL;
5445 struct blame_cb_args bca;
5446 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5447 off_t filesize;
5448 int *pack_fds = NULL;
5449 FILE *f1 = NULL, *f2 = NULL;
5451 fd1 = got_opentempfd();
5452 if (fd1 == -1)
5453 return got_error_from_errno("got_opentempfd");
5455 memset(&bca, 0, sizeof(bca));
5457 #ifndef PROFILE
5458 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5459 NULL) == -1)
5460 err(1, "pledge");
5461 #endif
5463 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5464 switch (ch) {
5465 case 'c':
5466 commit_id_str = optarg;
5467 break;
5468 case 'r':
5469 repo_path = realpath(optarg, NULL);
5470 if (repo_path == NULL)
5471 return got_error_from_errno2("realpath",
5472 optarg);
5473 got_path_strip_trailing_slashes(repo_path);
5474 break;
5475 default:
5476 usage_blame();
5477 /* NOTREACHED */
5481 argc -= optind;
5482 argv += optind;
5484 if (argc == 1)
5485 path = argv[0];
5486 else
5487 usage_blame();
5489 cwd = getcwd(NULL, 0);
5490 if (cwd == NULL) {
5491 error = got_error_from_errno("getcwd");
5492 goto done;
5495 error = got_repo_pack_fds_open(&pack_fds);
5496 if (error != NULL)
5497 goto done;
5499 if (repo_path == NULL) {
5500 error = got_worktree_open(&worktree, cwd);
5501 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5502 goto done;
5503 else
5504 error = NULL;
5505 if (worktree) {
5506 repo_path =
5507 strdup(got_worktree_get_repo_path(worktree));
5508 if (repo_path == NULL) {
5509 error = got_error_from_errno("strdup");
5510 if (error)
5511 goto done;
5513 } else {
5514 repo_path = strdup(cwd);
5515 if (repo_path == NULL) {
5516 error = got_error_from_errno("strdup");
5517 goto done;
5522 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5523 if (error != NULL)
5524 goto done;
5526 if (worktree) {
5527 const char *prefix = got_worktree_get_path_prefix(worktree);
5528 char *p;
5530 error = got_worktree_resolve_path(&p, worktree, path);
5531 if (error)
5532 goto done;
5533 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5534 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5535 p) == -1) {
5536 error = got_error_from_errno("asprintf");
5537 free(p);
5538 goto done;
5540 free(p);
5541 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5542 } else {
5543 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5544 if (error)
5545 goto done;
5546 error = got_repo_map_path(&in_repo_path, repo, path);
5548 if (error)
5549 goto done;
5551 if (commit_id_str == NULL) {
5552 struct got_reference *head_ref;
5553 error = got_ref_open(&head_ref, repo, worktree ?
5554 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5555 if (error != NULL)
5556 goto done;
5557 error = got_ref_resolve(&commit_id, repo, head_ref);
5558 got_ref_close(head_ref);
5559 if (error != NULL)
5560 goto done;
5561 } else {
5562 struct got_reflist_head refs;
5563 TAILQ_INIT(&refs);
5564 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5565 NULL);
5566 if (error)
5567 goto done;
5568 error = got_repo_match_object_id(&commit_id, NULL,
5569 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5570 got_ref_list_free(&refs);
5571 if (error)
5572 goto done;
5575 if (worktree) {
5576 /* Release work tree lock. */
5577 got_worktree_close(worktree);
5578 worktree = NULL;
5581 error = got_object_open_as_commit(&commit, repo, commit_id);
5582 if (error)
5583 goto done;
5585 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5586 commit, repo);
5587 if (error)
5588 goto done;
5590 error = got_object_id_by_path(&obj_id, repo, commit,
5591 link_target ? link_target : in_repo_path);
5592 if (error)
5593 goto done;
5595 error = got_object_get_type(&obj_type, repo, obj_id);
5596 if (error)
5597 goto done;
5599 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5600 error = got_error_path(link_target ? link_target : in_repo_path,
5601 GOT_ERR_OBJ_TYPE);
5602 goto done;
5605 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5606 if (error)
5607 goto done;
5608 bca.f = got_opentemp();
5609 if (bca.f == NULL) {
5610 error = got_error_from_errno("got_opentemp");
5611 goto done;
5613 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5614 &bca.line_offsets, bca.f, blob);
5615 if (error || bca.nlines == 0)
5616 goto done;
5618 /* Don't include \n at EOF in the blame line count. */
5619 if (bca.line_offsets[bca.nlines - 1] == filesize)
5620 bca.nlines--;
5622 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5623 if (bca.lines == NULL) {
5624 error = got_error_from_errno("calloc");
5625 goto done;
5627 bca.lineno_cur = 1;
5628 bca.nlines_prec = 0;
5629 i = bca.nlines;
5630 while (i > 0) {
5631 i /= 10;
5632 bca.nlines_prec++;
5634 bca.repo = repo;
5636 fd2 = got_opentempfd();
5637 if (fd2 == -1) {
5638 error = got_error_from_errno("got_opentempfd");
5639 goto done;
5641 fd3 = got_opentempfd();
5642 if (fd3 == -1) {
5643 error = got_error_from_errno("got_opentempfd");
5644 goto done;
5646 f1 = got_opentemp();
5647 if (f1 == NULL) {
5648 error = got_error_from_errno("got_opentemp");
5649 goto done;
5651 f2 = got_opentemp();
5652 if (f2 == NULL) {
5653 error = got_error_from_errno("got_opentemp");
5654 goto done;
5656 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5657 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5658 check_cancelled, NULL, fd2, fd3, f1, f2);
5659 done:
5660 free(in_repo_path);
5661 free(link_target);
5662 free(repo_path);
5663 free(cwd);
5664 free(commit_id);
5665 free(obj_id);
5666 if (commit)
5667 got_object_commit_close(commit);
5669 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5670 error = got_error_from_errno("close");
5671 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5672 error = got_error_from_errno("close");
5673 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5674 error = got_error_from_errno("close");
5675 if (f1 && fclose(f1) == EOF && error == NULL)
5676 error = got_error_from_errno("fclose");
5677 if (f2 && fclose(f2) == EOF && error == NULL)
5678 error = got_error_from_errno("fclose");
5680 if (blob)
5681 got_object_blob_close(blob);
5682 if (worktree)
5683 got_worktree_close(worktree);
5684 if (repo) {
5685 const struct got_error *close_err = got_repo_close(repo);
5686 if (error == NULL)
5687 error = close_err;
5689 if (pack_fds) {
5690 const struct got_error *pack_err =
5691 got_repo_pack_fds_close(pack_fds);
5692 if (error == NULL)
5693 error = pack_err;
5695 if (bca.lines) {
5696 for (i = 0; i < bca.nlines; i++) {
5697 struct blame_line *bline = &bca.lines[i];
5698 free(bline->id_str);
5699 free(bline->committer);
5701 free(bca.lines);
5703 free(bca.line_offsets);
5704 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5705 error = got_error_from_errno("fclose");
5706 return error;
5709 __dead static void
5710 usage_tree(void)
5712 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5713 "[path]\n", getprogname());
5714 exit(1);
5717 static const struct got_error *
5718 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5719 const char *root_path, struct got_repository *repo)
5721 const struct got_error *err = NULL;
5722 int is_root_path = (strcmp(path, root_path) == 0);
5723 const char *modestr = "";
5724 mode_t mode = got_tree_entry_get_mode(te);
5725 char *link_target = NULL;
5727 path += strlen(root_path);
5728 while (path[0] == '/')
5729 path++;
5731 if (got_object_tree_entry_is_submodule(te))
5732 modestr = "$";
5733 else if (S_ISLNK(mode)) {
5734 int i;
5736 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5737 if (err)
5738 return err;
5739 for (i = 0; i < strlen(link_target); i++) {
5740 if (!isprint((unsigned char)link_target[i]))
5741 link_target[i] = '?';
5744 modestr = "@";
5746 else if (S_ISDIR(mode))
5747 modestr = "/";
5748 else if (mode & S_IXUSR)
5749 modestr = "*";
5751 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5752 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5753 link_target ? " -> ": "", link_target ? link_target : "");
5755 free(link_target);
5756 return NULL;
5759 static const struct got_error *
5760 print_tree(const char *path, struct got_commit_object *commit,
5761 int show_ids, int recurse, const char *root_path,
5762 struct got_repository *repo)
5764 const struct got_error *err = NULL;
5765 struct got_object_id *tree_id = NULL;
5766 struct got_tree_object *tree = NULL;
5767 int nentries, i;
5769 err = got_object_id_by_path(&tree_id, repo, commit, path);
5770 if (err)
5771 goto done;
5773 err = got_object_open_as_tree(&tree, repo, tree_id);
5774 if (err)
5775 goto done;
5776 nentries = got_object_tree_get_nentries(tree);
5777 for (i = 0; i < nentries; i++) {
5778 struct got_tree_entry *te;
5779 char *id = NULL;
5781 if (sigint_received || sigpipe_received)
5782 break;
5784 te = got_object_tree_get_entry(tree, i);
5785 if (show_ids) {
5786 char *id_str;
5787 err = got_object_id_str(&id_str,
5788 got_tree_entry_get_id(te));
5789 if (err)
5790 goto done;
5791 if (asprintf(&id, "%s ", id_str) == -1) {
5792 err = got_error_from_errno("asprintf");
5793 free(id_str);
5794 goto done;
5796 free(id_str);
5798 err = print_entry(te, id, path, root_path, repo);
5799 free(id);
5800 if (err)
5801 goto done;
5803 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5804 char *child_path;
5805 if (asprintf(&child_path, "%s%s%s", path,
5806 path[0] == '/' && path[1] == '\0' ? "" : "/",
5807 got_tree_entry_get_name(te)) == -1) {
5808 err = got_error_from_errno("asprintf");
5809 goto done;
5811 err = print_tree(child_path, commit, show_ids, 1,
5812 root_path, repo);
5813 free(child_path);
5814 if (err)
5815 goto done;
5818 done:
5819 if (tree)
5820 got_object_tree_close(tree);
5821 free(tree_id);
5822 return err;
5825 static const struct got_error *
5826 cmd_tree(int argc, char *argv[])
5828 const struct got_error *error;
5829 struct got_repository *repo = NULL;
5830 struct got_worktree *worktree = NULL;
5831 const char *path, *refname = NULL;
5832 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5833 struct got_object_id *commit_id = NULL;
5834 struct got_commit_object *commit = NULL;
5835 char *commit_id_str = NULL;
5836 int show_ids = 0, recurse = 0;
5837 int ch;
5838 int *pack_fds = NULL;
5840 #ifndef PROFILE
5841 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5842 NULL) == -1)
5843 err(1, "pledge");
5844 #endif
5846 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5847 switch (ch) {
5848 case 'c':
5849 commit_id_str = optarg;
5850 break;
5851 case 'i':
5852 show_ids = 1;
5853 break;
5854 case 'R':
5855 recurse = 1;
5856 break;
5857 case 'r':
5858 repo_path = realpath(optarg, NULL);
5859 if (repo_path == NULL)
5860 return got_error_from_errno2("realpath",
5861 optarg);
5862 got_path_strip_trailing_slashes(repo_path);
5863 break;
5864 default:
5865 usage_tree();
5866 /* NOTREACHED */
5870 argc -= optind;
5871 argv += optind;
5873 if (argc == 1)
5874 path = argv[0];
5875 else if (argc > 1)
5876 usage_tree();
5877 else
5878 path = NULL;
5880 cwd = getcwd(NULL, 0);
5881 if (cwd == NULL) {
5882 error = got_error_from_errno("getcwd");
5883 goto done;
5886 error = got_repo_pack_fds_open(&pack_fds);
5887 if (error != NULL)
5888 goto done;
5890 if (repo_path == NULL) {
5891 error = got_worktree_open(&worktree, cwd);
5892 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5893 goto done;
5894 else
5895 error = NULL;
5896 if (worktree) {
5897 repo_path =
5898 strdup(got_worktree_get_repo_path(worktree));
5899 if (repo_path == NULL)
5900 error = got_error_from_errno("strdup");
5901 if (error)
5902 goto done;
5903 } else {
5904 repo_path = strdup(cwd);
5905 if (repo_path == NULL) {
5906 error = got_error_from_errno("strdup");
5907 goto done;
5912 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5913 if (error != NULL)
5914 goto done;
5916 if (worktree) {
5917 const char *prefix = got_worktree_get_path_prefix(worktree);
5918 char *p;
5920 if (path == NULL)
5921 path = "";
5922 error = got_worktree_resolve_path(&p, worktree, path);
5923 if (error)
5924 goto done;
5925 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5926 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5927 p) == -1) {
5928 error = got_error_from_errno("asprintf");
5929 free(p);
5930 goto done;
5932 free(p);
5933 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5934 if (error)
5935 goto done;
5936 } else {
5937 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5938 if (error)
5939 goto done;
5940 if (path == NULL)
5941 path = "/";
5942 error = got_repo_map_path(&in_repo_path, repo, path);
5943 if (error != NULL)
5944 goto done;
5947 if (commit_id_str == NULL) {
5948 struct got_reference *head_ref;
5949 if (worktree)
5950 refname = got_worktree_get_head_ref_name(worktree);
5951 else
5952 refname = GOT_REF_HEAD;
5953 error = got_ref_open(&head_ref, repo, refname, 0);
5954 if (error != NULL)
5955 goto done;
5956 error = got_ref_resolve(&commit_id, repo, head_ref);
5957 got_ref_close(head_ref);
5958 if (error != NULL)
5959 goto done;
5960 } else {
5961 struct got_reflist_head refs;
5962 TAILQ_INIT(&refs);
5963 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5964 NULL);
5965 if (error)
5966 goto done;
5967 error = got_repo_match_object_id(&commit_id, NULL,
5968 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5969 got_ref_list_free(&refs);
5970 if (error)
5971 goto done;
5974 if (worktree) {
5975 /* Release work tree lock. */
5976 got_worktree_close(worktree);
5977 worktree = NULL;
5980 error = got_object_open_as_commit(&commit, repo, commit_id);
5981 if (error)
5982 goto done;
5984 error = print_tree(in_repo_path, commit, show_ids, recurse,
5985 in_repo_path, repo);
5986 done:
5987 free(in_repo_path);
5988 free(repo_path);
5989 free(cwd);
5990 free(commit_id);
5991 if (commit)
5992 got_object_commit_close(commit);
5993 if (worktree)
5994 got_worktree_close(worktree);
5995 if (repo) {
5996 const struct got_error *close_err = got_repo_close(repo);
5997 if (error == NULL)
5998 error = close_err;
6000 if (pack_fds) {
6001 const struct got_error *pack_err =
6002 got_repo_pack_fds_close(pack_fds);
6003 if (error == NULL)
6004 error = pack_err;
6006 return error;
6009 __dead static void
6010 usage_status(void)
6012 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6013 "[-s status-codes] [path ...]\n", getprogname());
6014 exit(1);
6017 struct got_status_arg {
6018 char *status_codes;
6019 int suppress;
6022 static const struct got_error *
6023 print_status(void *arg, unsigned char status, unsigned char staged_status,
6024 const char *path, struct got_object_id *blob_id,
6025 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6026 int dirfd, const char *de_name)
6028 struct got_status_arg *st = arg;
6030 if (status == staged_status && (status == GOT_STATUS_DELETE))
6031 status = GOT_STATUS_NO_CHANGE;
6032 if (st != NULL && st->status_codes) {
6033 size_t ncodes = strlen(st->status_codes);
6034 int i, j = 0;
6036 for (i = 0; i < ncodes ; i++) {
6037 if (st->suppress) {
6038 if (status == st->status_codes[i] ||
6039 staged_status == st->status_codes[i]) {
6040 j++;
6041 continue;
6043 } else {
6044 if (status == st->status_codes[i] ||
6045 staged_status == st->status_codes[i])
6046 break;
6050 if (st->suppress && j == 0)
6051 goto print;
6053 if (i == ncodes)
6054 return NULL;
6056 print:
6057 printf("%c%c %s\n", status, staged_status, path);
6058 return NULL;
6061 static const struct got_error *
6062 cmd_status(int argc, char *argv[])
6064 const struct got_error *error = NULL;
6065 struct got_repository *repo = NULL;
6066 struct got_worktree *worktree = NULL;
6067 struct got_status_arg st;
6068 char *cwd = NULL;
6069 struct got_pathlist_head paths;
6070 struct got_pathlist_entry *pe;
6071 int ch, i, no_ignores = 0;
6072 int *pack_fds = NULL;
6074 TAILQ_INIT(&paths);
6076 memset(&st, 0, sizeof(st));
6077 st.status_codes = NULL;
6078 st.suppress = 0;
6080 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6081 switch (ch) {
6082 case 'I':
6083 no_ignores = 1;
6084 break;
6085 case 'S':
6086 if (st.status_codes != NULL && st.suppress == 0)
6087 option_conflict('S', 's');
6088 st.suppress = 1;
6089 /* fallthrough */
6090 case 's':
6091 for (i = 0; i < strlen(optarg); i++) {
6092 switch (optarg[i]) {
6093 case GOT_STATUS_MODIFY:
6094 case GOT_STATUS_ADD:
6095 case GOT_STATUS_DELETE:
6096 case GOT_STATUS_CONFLICT:
6097 case GOT_STATUS_MISSING:
6098 case GOT_STATUS_OBSTRUCTED:
6099 case GOT_STATUS_UNVERSIONED:
6100 case GOT_STATUS_MODE_CHANGE:
6101 case GOT_STATUS_NONEXISTENT:
6102 break;
6103 default:
6104 errx(1, "invalid status code '%c'",
6105 optarg[i]);
6108 if (ch == 's' && st.suppress)
6109 option_conflict('s', 'S');
6110 st.status_codes = optarg;
6111 break;
6112 default:
6113 usage_status();
6114 /* NOTREACHED */
6118 argc -= optind;
6119 argv += optind;
6121 #ifndef PROFILE
6122 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6123 NULL) == -1)
6124 err(1, "pledge");
6125 #endif
6126 cwd = getcwd(NULL, 0);
6127 if (cwd == NULL) {
6128 error = got_error_from_errno("getcwd");
6129 goto done;
6132 error = got_repo_pack_fds_open(&pack_fds);
6133 if (error != NULL)
6134 goto done;
6136 error = got_worktree_open(&worktree, cwd);
6137 if (error) {
6138 if (error->code == GOT_ERR_NOT_WORKTREE)
6139 error = wrap_not_worktree_error(error, "status", cwd);
6140 goto done;
6143 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6144 NULL, pack_fds);
6145 if (error != NULL)
6146 goto done;
6148 error = apply_unveil(got_repo_get_path(repo), 1,
6149 got_worktree_get_root_path(worktree));
6150 if (error)
6151 goto done;
6153 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6154 if (error)
6155 goto done;
6157 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6158 print_status, &st, check_cancelled, NULL);
6159 done:
6160 if (pack_fds) {
6161 const struct got_error *pack_err =
6162 got_repo_pack_fds_close(pack_fds);
6163 if (error == NULL)
6164 error = pack_err;
6167 TAILQ_FOREACH(pe, &paths, entry)
6168 free((char *)pe->path);
6169 got_pathlist_free(&paths);
6170 free(cwd);
6171 return error;
6174 __dead static void
6175 usage_ref(void)
6177 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6178 "[-s reference] [name]\n", getprogname());
6179 exit(1);
6182 static const struct got_error *
6183 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6185 static const struct got_error *err = NULL;
6186 struct got_reflist_head refs;
6187 struct got_reflist_entry *re;
6189 TAILQ_INIT(&refs);
6190 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6191 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6192 repo);
6193 if (err)
6194 return err;
6196 TAILQ_FOREACH(re, &refs, entry) {
6197 char *refstr;
6198 refstr = got_ref_to_str(re->ref);
6199 if (refstr == NULL) {
6200 err = got_error_from_errno("got_ref_to_str");
6201 break;
6203 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6204 free(refstr);
6207 got_ref_list_free(&refs);
6208 return err;
6211 static const struct got_error *
6212 delete_ref_by_name(struct got_repository *repo, const char *refname)
6214 const struct got_error *err;
6215 struct got_reference *ref;
6217 err = got_ref_open(&ref, repo, refname, 0);
6218 if (err)
6219 return err;
6221 err = delete_ref(repo, ref);
6222 got_ref_close(ref);
6223 return err;
6226 static const struct got_error *
6227 add_ref(struct got_repository *repo, const char *refname, const char *target)
6229 const struct got_error *err = NULL;
6230 struct got_object_id *id = NULL;
6231 struct got_reference *ref = NULL;
6232 struct got_reflist_head refs;
6235 * Don't let the user create a reference name with a leading '-'.
6236 * While technically a valid reference name, this case is usually
6237 * an unintended typo.
6239 if (refname[0] == '-')
6240 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6242 TAILQ_INIT(&refs);
6243 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6244 if (err)
6245 goto done;
6246 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6247 &refs, repo);
6248 got_ref_list_free(&refs);
6249 if (err)
6250 goto done;
6252 err = got_ref_alloc(&ref, refname, id);
6253 if (err)
6254 goto done;
6256 err = got_ref_write(ref, repo);
6257 done:
6258 if (ref)
6259 got_ref_close(ref);
6260 free(id);
6261 return err;
6264 static const struct got_error *
6265 add_symref(struct got_repository *repo, const char *refname, const char *target)
6267 const struct got_error *err = NULL;
6268 struct got_reference *ref = NULL;
6269 struct got_reference *target_ref = NULL;
6272 * Don't let the user create a reference name with a leading '-'.
6273 * While technically a valid reference name, this case is usually
6274 * an unintended typo.
6276 if (refname[0] == '-')
6277 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6279 err = got_ref_open(&target_ref, repo, target, 0);
6280 if (err)
6281 return err;
6283 err = got_ref_alloc_symref(&ref, refname, target_ref);
6284 if (err)
6285 goto done;
6287 err = got_ref_write(ref, repo);
6288 done:
6289 if (target_ref)
6290 got_ref_close(target_ref);
6291 if (ref)
6292 got_ref_close(ref);
6293 return err;
6296 static const struct got_error *
6297 cmd_ref(int argc, char *argv[])
6299 const struct got_error *error = NULL;
6300 struct got_repository *repo = NULL;
6301 struct got_worktree *worktree = NULL;
6302 char *cwd = NULL, *repo_path = NULL;
6303 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6304 const char *obj_arg = NULL, *symref_target= NULL;
6305 char *refname = NULL;
6306 int *pack_fds = NULL;
6308 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6309 switch (ch) {
6310 case 'c':
6311 obj_arg = optarg;
6312 break;
6313 case 'd':
6314 do_delete = 1;
6315 break;
6316 case 'l':
6317 do_list = 1;
6318 break;
6319 case 'r':
6320 repo_path = realpath(optarg, NULL);
6321 if (repo_path == NULL)
6322 return got_error_from_errno2("realpath",
6323 optarg);
6324 got_path_strip_trailing_slashes(repo_path);
6325 break;
6326 case 's':
6327 symref_target = optarg;
6328 break;
6329 case 't':
6330 sort_by_time = 1;
6331 break;
6332 default:
6333 usage_ref();
6334 /* NOTREACHED */
6338 if (obj_arg && do_list)
6339 option_conflict('c', 'l');
6340 if (obj_arg && do_delete)
6341 option_conflict('c', 'd');
6342 if (obj_arg && symref_target)
6343 option_conflict('c', 's');
6344 if (symref_target && do_delete)
6345 option_conflict('s', 'd');
6346 if (symref_target && do_list)
6347 option_conflict('s', 'l');
6348 if (do_delete && do_list)
6349 option_conflict('d', 'l');
6350 if (sort_by_time && !do_list)
6351 errx(1, "-t option requires -l option");
6353 argc -= optind;
6354 argv += optind;
6356 if (do_list) {
6357 if (argc != 0 && argc != 1)
6358 usage_ref();
6359 if (argc == 1) {
6360 refname = strdup(argv[0]);
6361 if (refname == NULL) {
6362 error = got_error_from_errno("strdup");
6363 goto done;
6366 } else {
6367 if (argc != 1)
6368 usage_ref();
6369 refname = strdup(argv[0]);
6370 if (refname == NULL) {
6371 error = got_error_from_errno("strdup");
6372 goto done;
6376 if (refname)
6377 got_path_strip_trailing_slashes(refname);
6379 #ifndef PROFILE
6380 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6381 "sendfd unveil", NULL) == -1)
6382 err(1, "pledge");
6383 #endif
6384 cwd = getcwd(NULL, 0);
6385 if (cwd == NULL) {
6386 error = got_error_from_errno("getcwd");
6387 goto done;
6390 error = got_repo_pack_fds_open(&pack_fds);
6391 if (error != NULL)
6392 goto done;
6394 if (repo_path == NULL) {
6395 error = got_worktree_open(&worktree, cwd);
6396 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6397 goto done;
6398 else
6399 error = NULL;
6400 if (worktree) {
6401 repo_path =
6402 strdup(got_worktree_get_repo_path(worktree));
6403 if (repo_path == NULL)
6404 error = got_error_from_errno("strdup");
6405 if (error)
6406 goto done;
6407 } else {
6408 repo_path = strdup(cwd);
6409 if (repo_path == NULL) {
6410 error = got_error_from_errno("strdup");
6411 goto done;
6416 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6417 if (error != NULL)
6418 goto done;
6420 #ifndef PROFILE
6421 if (do_list) {
6422 /* Remove "cpath" promise. */
6423 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6424 NULL) == -1)
6425 err(1, "pledge");
6427 #endif
6429 error = apply_unveil(got_repo_get_path(repo), do_list,
6430 worktree ? got_worktree_get_root_path(worktree) : NULL);
6431 if (error)
6432 goto done;
6434 if (do_list)
6435 error = list_refs(repo, refname, sort_by_time);
6436 else if (do_delete)
6437 error = delete_ref_by_name(repo, refname);
6438 else if (symref_target)
6439 error = add_symref(repo, refname, symref_target);
6440 else {
6441 if (obj_arg == NULL)
6442 usage_ref();
6443 error = add_ref(repo, refname, obj_arg);
6445 done:
6446 free(refname);
6447 if (repo) {
6448 const struct got_error *close_err = got_repo_close(repo);
6449 if (error == NULL)
6450 error = close_err;
6452 if (worktree)
6453 got_worktree_close(worktree);
6454 if (pack_fds) {
6455 const struct got_error *pack_err =
6456 got_repo_pack_fds_close(pack_fds);
6457 if (error == NULL)
6458 error = pack_err;
6460 free(cwd);
6461 free(repo_path);
6462 return error;
6465 __dead static void
6466 usage_branch(void)
6468 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6469 "[-r repository-path] [name]\n", getprogname());
6470 exit(1);
6473 static const struct got_error *
6474 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6475 struct got_reference *ref)
6477 const struct got_error *err = NULL;
6478 const char *refname, *marker = " ";
6479 char *refstr;
6481 refname = got_ref_get_name(ref);
6482 if (worktree && strcmp(refname,
6483 got_worktree_get_head_ref_name(worktree)) == 0) {
6484 struct got_object_id *id = NULL;
6486 err = got_ref_resolve(&id, repo, ref);
6487 if (err)
6488 return err;
6489 if (got_object_id_cmp(id,
6490 got_worktree_get_base_commit_id(worktree)) == 0)
6491 marker = "* ";
6492 else
6493 marker = "~ ";
6494 free(id);
6497 if (strncmp(refname, "refs/heads/", 11) == 0)
6498 refname += 11;
6499 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6500 refname += 18;
6501 if (strncmp(refname, "refs/remotes/", 13) == 0)
6502 refname += 13;
6504 refstr = got_ref_to_str(ref);
6505 if (refstr == NULL)
6506 return got_error_from_errno("got_ref_to_str");
6508 printf("%s%s: %s\n", marker, refname, refstr);
6509 free(refstr);
6510 return NULL;
6513 static const struct got_error *
6514 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6516 const char *refname;
6518 if (worktree == NULL)
6519 return got_error(GOT_ERR_NOT_WORKTREE);
6521 refname = got_worktree_get_head_ref_name(worktree);
6523 if (strncmp(refname, "refs/heads/", 11) == 0)
6524 refname += 11;
6525 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6526 refname += 18;
6528 printf("%s\n", refname);
6530 return NULL;
6533 static const struct got_error *
6534 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6535 int sort_by_time)
6537 static const struct got_error *err = NULL;
6538 struct got_reflist_head refs;
6539 struct got_reflist_entry *re;
6540 struct got_reference *temp_ref = NULL;
6541 int rebase_in_progress, histedit_in_progress;
6543 TAILQ_INIT(&refs);
6545 if (worktree) {
6546 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6547 worktree);
6548 if (err)
6549 return err;
6551 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6552 worktree);
6553 if (err)
6554 return err;
6556 if (rebase_in_progress || histedit_in_progress) {
6557 err = got_ref_open(&temp_ref, repo,
6558 got_worktree_get_head_ref_name(worktree), 0);
6559 if (err)
6560 return err;
6561 list_branch(repo, worktree, temp_ref);
6562 got_ref_close(temp_ref);
6566 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6567 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6568 repo);
6569 if (err)
6570 return err;
6572 TAILQ_FOREACH(re, &refs, entry)
6573 list_branch(repo, worktree, re->ref);
6575 got_ref_list_free(&refs);
6577 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6578 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6579 repo);
6580 if (err)
6581 return err;
6583 TAILQ_FOREACH(re, &refs, entry)
6584 list_branch(repo, worktree, re->ref);
6586 got_ref_list_free(&refs);
6588 return NULL;
6591 static const struct got_error *
6592 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6593 const char *branch_name)
6595 const struct got_error *err = NULL;
6596 struct got_reference *ref = NULL;
6597 char *refname, *remote_refname = NULL;
6599 if (strncmp(branch_name, "refs/", 5) == 0)
6600 branch_name += 5;
6601 if (strncmp(branch_name, "heads/", 6) == 0)
6602 branch_name += 6;
6603 else if (strncmp(branch_name, "remotes/", 8) == 0)
6604 branch_name += 8;
6606 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6607 return got_error_from_errno("asprintf");
6609 if (asprintf(&remote_refname, "refs/remotes/%s",
6610 branch_name) == -1) {
6611 err = got_error_from_errno("asprintf");
6612 goto done;
6615 err = got_ref_open(&ref, repo, refname, 0);
6616 if (err) {
6617 const struct got_error *err2;
6618 if (err->code != GOT_ERR_NOT_REF)
6619 goto done;
6621 * Keep 'err' intact such that if neither branch exists
6622 * we report "refs/heads" rather than "refs/remotes" in
6623 * our error message.
6625 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6626 if (err2)
6627 goto done;
6628 err = NULL;
6631 if (worktree &&
6632 strcmp(got_worktree_get_head_ref_name(worktree),
6633 got_ref_get_name(ref)) == 0) {
6634 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6635 "will not delete this work tree's current branch");
6636 goto done;
6639 err = delete_ref(repo, ref);
6640 done:
6641 if (ref)
6642 got_ref_close(ref);
6643 free(refname);
6644 free(remote_refname);
6645 return err;
6648 static const struct got_error *
6649 add_branch(struct got_repository *repo, const char *branch_name,
6650 struct got_object_id *base_commit_id)
6652 const struct got_error *err = NULL;
6653 struct got_reference *ref = NULL;
6654 char *base_refname = NULL, *refname = NULL;
6657 * Don't let the user create a branch name with a leading '-'.
6658 * While technically a valid reference name, this case is usually
6659 * an unintended typo.
6661 if (branch_name[0] == '-')
6662 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6664 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6665 branch_name += 11;
6667 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6668 err = got_error_from_errno("asprintf");
6669 goto done;
6672 err = got_ref_open(&ref, repo, refname, 0);
6673 if (err == NULL) {
6674 err = got_error(GOT_ERR_BRANCH_EXISTS);
6675 goto done;
6676 } else if (err->code != GOT_ERR_NOT_REF)
6677 goto done;
6679 err = got_ref_alloc(&ref, refname, base_commit_id);
6680 if (err)
6681 goto done;
6683 err = got_ref_write(ref, repo);
6684 done:
6685 if (ref)
6686 got_ref_close(ref);
6687 free(base_refname);
6688 free(refname);
6689 return err;
6692 static const struct got_error *
6693 cmd_branch(int argc, char *argv[])
6695 const struct got_error *error = NULL;
6696 struct got_repository *repo = NULL;
6697 struct got_worktree *worktree = NULL;
6698 char *cwd = NULL, *repo_path = NULL;
6699 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6700 const char *delref = NULL, *commit_id_arg = NULL;
6701 struct got_reference *ref = NULL;
6702 struct got_pathlist_head paths;
6703 struct got_pathlist_entry *pe;
6704 struct got_object_id *commit_id = NULL;
6705 char *commit_id_str = NULL;
6706 int *pack_fds = NULL;
6708 TAILQ_INIT(&paths);
6710 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6711 switch (ch) {
6712 case 'c':
6713 commit_id_arg = optarg;
6714 break;
6715 case 'd':
6716 delref = optarg;
6717 break;
6718 case 'l':
6719 do_list = 1;
6720 break;
6721 case 'n':
6722 do_update = 0;
6723 break;
6724 case 'r':
6725 repo_path = realpath(optarg, NULL);
6726 if (repo_path == NULL)
6727 return got_error_from_errno2("realpath",
6728 optarg);
6729 got_path_strip_trailing_slashes(repo_path);
6730 break;
6731 case 't':
6732 sort_by_time = 1;
6733 break;
6734 default:
6735 usage_branch();
6736 /* NOTREACHED */
6740 if (do_list && delref)
6741 option_conflict('l', 'd');
6742 if (sort_by_time && !do_list)
6743 errx(1, "-t option requires -l option");
6745 argc -= optind;
6746 argv += optind;
6748 if (!do_list && !delref && argc == 0)
6749 do_show = 1;
6751 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6752 errx(1, "-c option can only be used when creating a branch");
6754 if (do_list || delref) {
6755 if (argc > 0)
6756 usage_branch();
6757 } else if (!do_show && argc != 1)
6758 usage_branch();
6760 #ifndef PROFILE
6761 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6762 "sendfd unveil", NULL) == -1)
6763 err(1, "pledge");
6764 #endif
6765 cwd = getcwd(NULL, 0);
6766 if (cwd == NULL) {
6767 error = got_error_from_errno("getcwd");
6768 goto done;
6771 error = got_repo_pack_fds_open(&pack_fds);
6772 if (error != NULL)
6773 goto done;
6775 if (repo_path == NULL) {
6776 error = got_worktree_open(&worktree, cwd);
6777 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6778 goto done;
6779 else
6780 error = NULL;
6781 if (worktree) {
6782 repo_path =
6783 strdup(got_worktree_get_repo_path(worktree));
6784 if (repo_path == NULL)
6785 error = got_error_from_errno("strdup");
6786 if (error)
6787 goto done;
6788 } else {
6789 repo_path = strdup(cwd);
6790 if (repo_path == NULL) {
6791 error = got_error_from_errno("strdup");
6792 goto done;
6797 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6798 if (error != NULL)
6799 goto done;
6801 #ifndef PROFILE
6802 if (do_list || do_show) {
6803 /* Remove "cpath" promise. */
6804 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6805 NULL) == -1)
6806 err(1, "pledge");
6808 #endif
6810 error = apply_unveil(got_repo_get_path(repo), do_list,
6811 worktree ? got_worktree_get_root_path(worktree) : NULL);
6812 if (error)
6813 goto done;
6815 if (do_show)
6816 error = show_current_branch(repo, worktree);
6817 else if (do_list)
6818 error = list_branches(repo, worktree, sort_by_time);
6819 else if (delref)
6820 error = delete_branch(repo, worktree, delref);
6821 else {
6822 struct got_reflist_head refs;
6823 TAILQ_INIT(&refs);
6824 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6825 NULL);
6826 if (error)
6827 goto done;
6828 if (commit_id_arg == NULL)
6829 commit_id_arg = worktree ?
6830 got_worktree_get_head_ref_name(worktree) :
6831 GOT_REF_HEAD;
6832 error = got_repo_match_object_id(&commit_id, NULL,
6833 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6834 got_ref_list_free(&refs);
6835 if (error)
6836 goto done;
6837 error = add_branch(repo, argv[0], commit_id);
6838 if (error)
6839 goto done;
6840 if (worktree && do_update) {
6841 struct got_update_progress_arg upa;
6842 char *branch_refname = NULL;
6844 error = got_object_id_str(&commit_id_str, commit_id);
6845 if (error)
6846 goto done;
6847 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6848 worktree);
6849 if (error)
6850 goto done;
6851 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6852 == -1) {
6853 error = got_error_from_errno("asprintf");
6854 goto done;
6856 error = got_ref_open(&ref, repo, branch_refname, 0);
6857 free(branch_refname);
6858 if (error)
6859 goto done;
6860 error = switch_head_ref(ref, commit_id, worktree,
6861 repo);
6862 if (error)
6863 goto done;
6864 error = got_worktree_set_base_commit_id(worktree, repo,
6865 commit_id);
6866 if (error)
6867 goto done;
6868 memset(&upa, 0, sizeof(upa));
6869 error = got_worktree_checkout_files(worktree, &paths,
6870 repo, update_progress, &upa, check_cancelled,
6871 NULL);
6872 if (error)
6873 goto done;
6874 if (upa.did_something) {
6875 printf("Updated to %s: %s\n",
6876 got_worktree_get_head_ref_name(worktree),
6877 commit_id_str);
6879 print_update_progress_stats(&upa);
6882 done:
6883 if (ref)
6884 got_ref_close(ref);
6885 if (repo) {
6886 const struct got_error *close_err = got_repo_close(repo);
6887 if (error == NULL)
6888 error = close_err;
6890 if (worktree)
6891 got_worktree_close(worktree);
6892 if (pack_fds) {
6893 const struct got_error *pack_err =
6894 got_repo_pack_fds_close(pack_fds);
6895 if (error == NULL)
6896 error = pack_err;
6898 free(cwd);
6899 free(repo_path);
6900 free(commit_id);
6901 free(commit_id_str);
6902 TAILQ_FOREACH(pe, &paths, entry)
6903 free((char *)pe->path);
6904 got_pathlist_free(&paths);
6905 return error;
6909 __dead static void
6910 usage_tag(void)
6912 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6913 "[-r repository-path] [-s signer-id] name\n", getprogname());
6914 exit(1);
6917 #if 0
6918 static const struct got_error *
6919 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6921 const struct got_error *err = NULL;
6922 struct got_reflist_entry *re, *se, *new;
6923 struct got_object_id *re_id, *se_id;
6924 struct got_tag_object *re_tag, *se_tag;
6925 time_t re_time, se_time;
6927 STAILQ_FOREACH(re, tags, entry) {
6928 se = STAILQ_FIRST(sorted);
6929 if (se == NULL) {
6930 err = got_reflist_entry_dup(&new, re);
6931 if (err)
6932 return err;
6933 STAILQ_INSERT_HEAD(sorted, new, entry);
6934 continue;
6935 } else {
6936 err = got_ref_resolve(&re_id, repo, re->ref);
6937 if (err)
6938 break;
6939 err = got_object_open_as_tag(&re_tag, repo, re_id);
6940 free(re_id);
6941 if (err)
6942 break;
6943 re_time = got_object_tag_get_tagger_time(re_tag);
6944 got_object_tag_close(re_tag);
6947 while (se) {
6948 err = got_ref_resolve(&se_id, repo, re->ref);
6949 if (err)
6950 break;
6951 err = got_object_open_as_tag(&se_tag, repo, se_id);
6952 free(se_id);
6953 if (err)
6954 break;
6955 se_time = got_object_tag_get_tagger_time(se_tag);
6956 got_object_tag_close(se_tag);
6958 if (se_time > re_time) {
6959 err = got_reflist_entry_dup(&new, re);
6960 if (err)
6961 return err;
6962 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6963 break;
6965 se = STAILQ_NEXT(se, entry);
6966 continue;
6969 done:
6970 return err;
6972 #endif
6974 static const struct got_error *
6975 get_tag_refname(char **refname, const char *tag_name)
6977 const struct got_error *err;
6979 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6980 *refname = strdup(tag_name);
6981 if (*refname == NULL)
6982 return got_error_from_errno("strdup");
6983 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6984 err = got_error_from_errno("asprintf");
6985 *refname = NULL;
6986 return err;
6989 return NULL;
6992 static const struct got_error *
6993 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6994 const char *allowed_signers, const char *revoked_signers, int verbosity)
6996 static const struct got_error *err = NULL;
6997 struct got_reflist_head refs;
6998 struct got_reflist_entry *re;
6999 char *wanted_refname = NULL;
7000 int bad_sigs = 0;
7002 TAILQ_INIT(&refs);
7004 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7005 if (err)
7006 return err;
7008 if (tag_name) {
7009 struct got_reference *ref;
7010 err = get_tag_refname(&wanted_refname, tag_name);
7011 if (err)
7012 goto done;
7013 /* Wanted tag reference should exist. */
7014 err = got_ref_open(&ref, repo, wanted_refname, 0);
7015 if (err)
7016 goto done;
7017 got_ref_close(ref);
7020 TAILQ_FOREACH(re, &refs, entry) {
7021 const char *refname;
7022 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7023 char datebuf[26];
7024 const char *tagger, *ssh_sig = NULL;
7025 char *sig_msg = NULL;
7026 time_t tagger_time;
7027 struct got_object_id *id;
7028 struct got_tag_object *tag;
7029 struct got_commit_object *commit = NULL;
7031 refname = got_ref_get_name(re->ref);
7032 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7033 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7034 continue;
7035 refname += 10;
7036 refstr = got_ref_to_str(re->ref);
7037 if (refstr == NULL) {
7038 err = got_error_from_errno("got_ref_to_str");
7039 break;
7042 err = got_ref_resolve(&id, repo, re->ref);
7043 if (err)
7044 break;
7045 err = got_object_open_as_tag(&tag, repo, id);
7046 if (err) {
7047 if (err->code != GOT_ERR_OBJ_TYPE) {
7048 free(id);
7049 break;
7051 /* "lightweight" tag */
7052 err = got_object_open_as_commit(&commit, repo, id);
7053 if (err) {
7054 free(id);
7055 break;
7057 tagger = got_object_commit_get_committer(commit);
7058 tagger_time =
7059 got_object_commit_get_committer_time(commit);
7060 err = got_object_id_str(&id_str, id);
7061 free(id);
7062 if (err)
7063 break;
7064 } else {
7065 free(id);
7066 tagger = got_object_tag_get_tagger(tag);
7067 tagger_time = got_object_tag_get_tagger_time(tag);
7068 err = got_object_id_str(&id_str,
7069 got_object_tag_get_object_id(tag));
7070 if (err)
7071 break;
7074 if (tag && verify_tags) {
7075 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7076 got_object_tag_get_message(tag));
7077 if (ssh_sig && allowed_signers == NULL) {
7078 err = got_error_msg(
7079 GOT_ERR_VERIFY_TAG_SIGNATURE,
7080 "SSH signature verification requires "
7081 "setting allowed_signers in "
7082 "got.conf(5)");
7083 break;
7087 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7088 free(refstr);
7089 printf("from: %s\n", tagger);
7090 datestr = get_datestr(&tagger_time, datebuf);
7091 if (datestr)
7092 printf("date: %s UTC\n", datestr);
7093 if (commit)
7094 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7095 else {
7096 switch (got_object_tag_get_object_type(tag)) {
7097 case GOT_OBJ_TYPE_BLOB:
7098 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7099 id_str);
7100 break;
7101 case GOT_OBJ_TYPE_TREE:
7102 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7103 id_str);
7104 break;
7105 case GOT_OBJ_TYPE_COMMIT:
7106 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7107 id_str);
7108 break;
7109 case GOT_OBJ_TYPE_TAG:
7110 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7111 id_str);
7112 break;
7113 default:
7114 break;
7117 free(id_str);
7119 if (ssh_sig) {
7120 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7121 allowed_signers, revoked_signers, verbosity);
7122 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7123 bad_sigs = 1;
7124 else if (err)
7125 break;
7126 printf("signature: %s", sig_msg);
7127 free(sig_msg);
7128 sig_msg = NULL;
7131 if (commit) {
7132 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7133 if (err)
7134 break;
7135 got_object_commit_close(commit);
7136 } else {
7137 tagmsg0 = strdup(got_object_tag_get_message(tag));
7138 got_object_tag_close(tag);
7139 if (tagmsg0 == NULL) {
7140 err = got_error_from_errno("strdup");
7141 break;
7145 tagmsg = tagmsg0;
7146 do {
7147 line = strsep(&tagmsg, "\n");
7148 if (line)
7149 printf(" %s\n", line);
7150 } while (line);
7151 free(tagmsg0);
7153 done:
7154 got_ref_list_free(&refs);
7155 free(wanted_refname);
7157 if (err == NULL && bad_sigs)
7158 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7159 return err;
7162 static const struct got_error *
7163 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7164 const char *tag_name, const char *repo_path)
7166 const struct got_error *err = NULL;
7167 char *template = NULL, *initial_content = NULL;
7168 char *editor = NULL;
7169 int initial_content_len;
7170 int fd = -1;
7172 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7173 err = got_error_from_errno("asprintf");
7174 goto done;
7177 initial_content_len = asprintf(&initial_content,
7178 "\n# tagging commit %s as %s\n",
7179 commit_id_str, tag_name);
7180 if (initial_content_len == -1) {
7181 err = got_error_from_errno("asprintf");
7182 goto done;
7185 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7186 if (err)
7187 goto done;
7189 if (write(fd, initial_content, initial_content_len) == -1) {
7190 err = got_error_from_errno2("write", *tagmsg_path);
7191 goto done;
7194 err = get_editor(&editor);
7195 if (err)
7196 goto done;
7197 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7198 initial_content_len, 1);
7199 done:
7200 free(initial_content);
7201 free(template);
7202 free(editor);
7204 if (fd != -1 && close(fd) == -1 && err == NULL)
7205 err = got_error_from_errno2("close", *tagmsg_path);
7207 if (err) {
7208 free(*tagmsg);
7209 *tagmsg = NULL;
7211 return err;
7214 static const struct got_error *
7215 add_tag(struct got_repository *repo, const char *tagger,
7216 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7217 const char *signer_id, int verbosity)
7219 const struct got_error *err = NULL;
7220 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7221 char *label = NULL, *commit_id_str = NULL;
7222 struct got_reference *ref = NULL;
7223 char *refname = NULL, *tagmsg = NULL;
7224 char *tagmsg_path = NULL, *tag_id_str = NULL;
7225 int preserve_tagmsg = 0;
7226 struct got_reflist_head refs;
7228 TAILQ_INIT(&refs);
7231 * Don't let the user create a tag name with a leading '-'.
7232 * While technically a valid reference name, this case is usually
7233 * an unintended typo.
7235 if (tag_name[0] == '-')
7236 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7238 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7239 if (err)
7240 goto done;
7242 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7243 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7244 if (err)
7245 goto done;
7247 err = got_object_id_str(&commit_id_str, commit_id);
7248 if (err)
7249 goto done;
7251 err = get_tag_refname(&refname, tag_name);
7252 if (err)
7253 goto done;
7254 if (strncmp("refs/tags/", tag_name, 10) == 0)
7255 tag_name += 10;
7257 err = got_ref_open(&ref, repo, refname, 0);
7258 if (err == NULL) {
7259 err = got_error(GOT_ERR_TAG_EXISTS);
7260 goto done;
7261 } else if (err->code != GOT_ERR_NOT_REF)
7262 goto done;
7264 if (tagmsg_arg == NULL) {
7265 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7266 tag_name, got_repo_get_path(repo));
7267 if (err) {
7268 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7269 tagmsg_path != NULL)
7270 preserve_tagmsg = 1;
7271 goto done;
7273 /* Editor is done; we can now apply unveil(2) */
7274 err = got_sigs_apply_unveil();
7275 if (err)
7276 goto done;
7277 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7278 if (err)
7279 goto done;
7282 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7283 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7284 verbosity);
7285 if (err) {
7286 if (tagmsg_path)
7287 preserve_tagmsg = 1;
7288 goto done;
7291 err = got_ref_alloc(&ref, refname, tag_id);
7292 if (err) {
7293 if (tagmsg_path)
7294 preserve_tagmsg = 1;
7295 goto done;
7298 err = got_ref_write(ref, repo);
7299 if (err) {
7300 if (tagmsg_path)
7301 preserve_tagmsg = 1;
7302 goto done;
7305 err = got_object_id_str(&tag_id_str, tag_id);
7306 if (err) {
7307 if (tagmsg_path)
7308 preserve_tagmsg = 1;
7309 goto done;
7311 printf("Created tag %s\n", tag_id_str);
7312 done:
7313 if (preserve_tagmsg) {
7314 fprintf(stderr, "%s: tag message preserved in %s\n",
7315 getprogname(), tagmsg_path);
7316 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7317 err = got_error_from_errno2("unlink", tagmsg_path);
7318 free(tag_id_str);
7319 if (ref)
7320 got_ref_close(ref);
7321 free(commit_id);
7322 free(commit_id_str);
7323 free(refname);
7324 free(tagmsg);
7325 free(tagmsg_path);
7326 got_ref_list_free(&refs);
7327 return err;
7330 static const struct got_error *
7331 cmd_tag(int argc, char *argv[])
7333 const struct got_error *error = NULL;
7334 struct got_repository *repo = NULL;
7335 struct got_worktree *worktree = NULL;
7336 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7337 char *gitconfig_path = NULL, *tagger = NULL;
7338 char *allowed_signers = NULL, *revoked_signers = NULL;
7339 char *signer_id = NULL;
7340 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7341 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7342 int *pack_fds = NULL;
7344 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7345 switch (ch) {
7346 case 'c':
7347 commit_id_arg = optarg;
7348 break;
7349 case 'l':
7350 do_list = 1;
7351 break;
7352 case 'm':
7353 tagmsg = optarg;
7354 break;
7355 case 'r':
7356 repo_path = realpath(optarg, NULL);
7357 if (repo_path == NULL) {
7358 error = got_error_from_errno2("realpath",
7359 optarg);
7360 goto done;
7362 got_path_strip_trailing_slashes(repo_path);
7363 break;
7364 case 's':
7365 signer_id = strdup(optarg);
7366 if (signer_id == NULL) {
7367 error = got_error_from_errno("strdup");
7368 goto done;
7370 break;
7371 case 'V':
7372 verify_tags = 1;
7373 break;
7374 case 'v':
7375 if (verbosity < 0)
7376 verbosity = 0;
7377 else if (verbosity < 3)
7378 verbosity++;
7379 break;
7380 default:
7381 usage_tag();
7382 /* NOTREACHED */
7386 argc -= optind;
7387 argv += optind;
7389 if (do_list || verify_tags) {
7390 if (commit_id_arg != NULL)
7391 errx(1,
7392 "-c option can only be used when creating a tag");
7393 if (tagmsg) {
7394 if (do_list)
7395 option_conflict('l', 'm');
7396 else
7397 option_conflict('V', 'm');
7399 if (signer_id) {
7400 if (do_list)
7401 option_conflict('l', 's');
7402 else
7403 option_conflict('V', 's');
7405 if (argc > 1)
7406 usage_tag();
7407 } else if (argc != 1)
7408 usage_tag();
7410 if (argc == 1)
7411 tag_name = argv[0];
7413 #ifndef PROFILE
7414 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7415 "sendfd unveil", NULL) == -1)
7416 err(1, "pledge");
7417 #endif
7418 cwd = getcwd(NULL, 0);
7419 if (cwd == NULL) {
7420 error = got_error_from_errno("getcwd");
7421 goto done;
7424 error = got_repo_pack_fds_open(&pack_fds);
7425 if (error != NULL)
7426 goto done;
7428 if (repo_path == NULL) {
7429 error = got_worktree_open(&worktree, cwd);
7430 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7431 goto done;
7432 else
7433 error = NULL;
7434 if (worktree) {
7435 repo_path =
7436 strdup(got_worktree_get_repo_path(worktree));
7437 if (repo_path == NULL)
7438 error = got_error_from_errno("strdup");
7439 if (error)
7440 goto done;
7441 } else {
7442 repo_path = strdup(cwd);
7443 if (repo_path == NULL) {
7444 error = got_error_from_errno("strdup");
7445 goto done;
7450 if (do_list || verify_tags) {
7451 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7452 if (error != NULL)
7453 goto done;
7454 error = get_allowed_signers(&allowed_signers, repo, worktree);
7455 if (error)
7456 goto done;
7457 error = get_revoked_signers(&revoked_signers, repo, worktree);
7458 if (error)
7459 goto done;
7460 if (worktree) {
7461 /* Release work tree lock. */
7462 got_worktree_close(worktree);
7463 worktree = NULL;
7467 * Remove "cpath" promise unless needed for signature tmpfile
7468 * creation.
7470 if (verify_tags)
7471 got_sigs_apply_unveil();
7472 else {
7473 #ifndef PROFILE
7474 if (pledge("stdio rpath wpath flock proc exec sendfd "
7475 "unveil", NULL) == -1)
7476 err(1, "pledge");
7477 #endif
7479 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7480 if (error)
7481 goto done;
7482 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7483 revoked_signers, verbosity);
7484 } else {
7485 error = get_gitconfig_path(&gitconfig_path);
7486 if (error)
7487 goto done;
7488 error = got_repo_open(&repo, repo_path, gitconfig_path,
7489 pack_fds);
7490 if (error != NULL)
7491 goto done;
7493 error = get_author(&tagger, repo, worktree);
7494 if (error)
7495 goto done;
7496 if (signer_id == NULL) {
7497 error = get_signer_id(&signer_id, repo, worktree);
7498 if (error)
7499 goto done;
7502 if (tagmsg) {
7503 if (signer_id) {
7504 error = got_sigs_apply_unveil();
7505 if (error)
7506 goto done;
7508 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7509 if (error)
7510 goto done;
7513 if (commit_id_arg == NULL) {
7514 struct got_reference *head_ref;
7515 struct got_object_id *commit_id;
7516 error = got_ref_open(&head_ref, repo,
7517 worktree ? got_worktree_get_head_ref_name(worktree)
7518 : GOT_REF_HEAD, 0);
7519 if (error)
7520 goto done;
7521 error = got_ref_resolve(&commit_id, repo, head_ref);
7522 got_ref_close(head_ref);
7523 if (error)
7524 goto done;
7525 error = got_object_id_str(&commit_id_str, commit_id);
7526 free(commit_id);
7527 if (error)
7528 goto done;
7531 if (worktree) {
7532 /* Release work tree lock. */
7533 got_worktree_close(worktree);
7534 worktree = NULL;
7537 error = add_tag(repo, tagger, tag_name,
7538 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7539 signer_id, verbosity);
7541 done:
7542 if (repo) {
7543 const struct got_error *close_err = got_repo_close(repo);
7544 if (error == NULL)
7545 error = close_err;
7547 if (worktree)
7548 got_worktree_close(worktree);
7549 if (pack_fds) {
7550 const struct got_error *pack_err =
7551 got_repo_pack_fds_close(pack_fds);
7552 if (error == NULL)
7553 error = pack_err;
7555 free(cwd);
7556 free(repo_path);
7557 free(gitconfig_path);
7558 free(commit_id_str);
7559 free(tagger);
7560 free(allowed_signers);
7561 free(revoked_signers);
7562 free(signer_id);
7563 return error;
7566 __dead static void
7567 usage_add(void)
7569 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7570 exit(1);
7573 static const struct got_error *
7574 add_progress(void *arg, unsigned char status, const char *path)
7576 while (path[0] == '/')
7577 path++;
7578 printf("%c %s\n", status, path);
7579 return NULL;
7582 static const struct got_error *
7583 cmd_add(int argc, char *argv[])
7585 const struct got_error *error = NULL;
7586 struct got_repository *repo = NULL;
7587 struct got_worktree *worktree = NULL;
7588 char *cwd = NULL;
7589 struct got_pathlist_head paths;
7590 struct got_pathlist_entry *pe;
7591 int ch, can_recurse = 0, no_ignores = 0;
7592 int *pack_fds = NULL;
7594 TAILQ_INIT(&paths);
7596 while ((ch = getopt(argc, argv, "IR")) != -1) {
7597 switch (ch) {
7598 case 'I':
7599 no_ignores = 1;
7600 break;
7601 case 'R':
7602 can_recurse = 1;
7603 break;
7604 default:
7605 usage_add();
7606 /* NOTREACHED */
7610 argc -= optind;
7611 argv += optind;
7613 #ifndef PROFILE
7614 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7615 NULL) == -1)
7616 err(1, "pledge");
7617 #endif
7618 if (argc < 1)
7619 usage_add();
7621 cwd = getcwd(NULL, 0);
7622 if (cwd == NULL) {
7623 error = got_error_from_errno("getcwd");
7624 goto done;
7627 error = got_repo_pack_fds_open(&pack_fds);
7628 if (error != NULL)
7629 goto done;
7631 error = got_worktree_open(&worktree, cwd);
7632 if (error) {
7633 if (error->code == GOT_ERR_NOT_WORKTREE)
7634 error = wrap_not_worktree_error(error, "add", cwd);
7635 goto done;
7638 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7639 NULL, pack_fds);
7640 if (error != NULL)
7641 goto done;
7643 error = apply_unveil(got_repo_get_path(repo), 1,
7644 got_worktree_get_root_path(worktree));
7645 if (error)
7646 goto done;
7648 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7649 if (error)
7650 goto done;
7652 if (!can_recurse) {
7653 char *ondisk_path;
7654 struct stat sb;
7655 TAILQ_FOREACH(pe, &paths, entry) {
7656 if (asprintf(&ondisk_path, "%s/%s",
7657 got_worktree_get_root_path(worktree),
7658 pe->path) == -1) {
7659 error = got_error_from_errno("asprintf");
7660 goto done;
7662 if (lstat(ondisk_path, &sb) == -1) {
7663 if (errno == ENOENT) {
7664 free(ondisk_path);
7665 continue;
7667 error = got_error_from_errno2("lstat",
7668 ondisk_path);
7669 free(ondisk_path);
7670 goto done;
7672 free(ondisk_path);
7673 if (S_ISDIR(sb.st_mode)) {
7674 error = got_error_msg(GOT_ERR_BAD_PATH,
7675 "adding directories requires -R option");
7676 goto done;
7681 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7682 NULL, repo, no_ignores);
7683 done:
7684 if (repo) {
7685 const struct got_error *close_err = got_repo_close(repo);
7686 if (error == NULL)
7687 error = close_err;
7689 if (worktree)
7690 got_worktree_close(worktree);
7691 if (pack_fds) {
7692 const struct got_error *pack_err =
7693 got_repo_pack_fds_close(pack_fds);
7694 if (error == NULL)
7695 error = pack_err;
7697 TAILQ_FOREACH(pe, &paths, entry)
7698 free((char *)pe->path);
7699 got_pathlist_free(&paths);
7700 free(cwd);
7701 return error;
7704 __dead static void
7705 usage_remove(void)
7707 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7708 getprogname());
7709 exit(1);
7712 static const struct got_error *
7713 print_remove_status(void *arg, unsigned char status,
7714 unsigned char staged_status, const char *path)
7716 while (path[0] == '/')
7717 path++;
7718 if (status == GOT_STATUS_NONEXISTENT)
7719 return NULL;
7720 if (status == staged_status && (status == GOT_STATUS_DELETE))
7721 status = GOT_STATUS_NO_CHANGE;
7722 printf("%c%c %s\n", status, staged_status, path);
7723 return NULL;
7726 static const struct got_error *
7727 cmd_remove(int argc, char *argv[])
7729 const struct got_error *error = NULL;
7730 struct got_worktree *worktree = NULL;
7731 struct got_repository *repo = NULL;
7732 const char *status_codes = NULL;
7733 char *cwd = NULL;
7734 struct got_pathlist_head paths;
7735 struct got_pathlist_entry *pe;
7736 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7737 int ignore_missing_paths = 0;
7738 int *pack_fds = NULL;
7740 TAILQ_INIT(&paths);
7742 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7743 switch (ch) {
7744 case 'f':
7745 delete_local_mods = 1;
7746 ignore_missing_paths = 1;
7747 break;
7748 case 'k':
7749 keep_on_disk = 1;
7750 break;
7751 case 'R':
7752 can_recurse = 1;
7753 break;
7754 case 's':
7755 for (i = 0; i < strlen(optarg); i++) {
7756 switch (optarg[i]) {
7757 case GOT_STATUS_MODIFY:
7758 delete_local_mods = 1;
7759 break;
7760 case GOT_STATUS_MISSING:
7761 ignore_missing_paths = 1;
7762 break;
7763 default:
7764 errx(1, "invalid status code '%c'",
7765 optarg[i]);
7768 status_codes = optarg;
7769 break;
7770 default:
7771 usage_remove();
7772 /* NOTREACHED */
7776 argc -= optind;
7777 argv += optind;
7779 #ifndef PROFILE
7780 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7781 NULL) == -1)
7782 err(1, "pledge");
7783 #endif
7784 if (argc < 1)
7785 usage_remove();
7787 cwd = getcwd(NULL, 0);
7788 if (cwd == NULL) {
7789 error = got_error_from_errno("getcwd");
7790 goto done;
7793 error = got_repo_pack_fds_open(&pack_fds);
7794 if (error != NULL)
7795 goto done;
7797 error = got_worktree_open(&worktree, cwd);
7798 if (error) {
7799 if (error->code == GOT_ERR_NOT_WORKTREE)
7800 error = wrap_not_worktree_error(error, "remove", cwd);
7801 goto done;
7804 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7805 NULL, pack_fds);
7806 if (error)
7807 goto done;
7809 error = apply_unveil(got_repo_get_path(repo), 1,
7810 got_worktree_get_root_path(worktree));
7811 if (error)
7812 goto done;
7814 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7815 if (error)
7816 goto done;
7818 if (!can_recurse) {
7819 char *ondisk_path;
7820 struct stat sb;
7821 TAILQ_FOREACH(pe, &paths, entry) {
7822 if (asprintf(&ondisk_path, "%s/%s",
7823 got_worktree_get_root_path(worktree),
7824 pe->path) == -1) {
7825 error = got_error_from_errno("asprintf");
7826 goto done;
7828 if (lstat(ondisk_path, &sb) == -1) {
7829 if (errno == ENOENT) {
7830 free(ondisk_path);
7831 continue;
7833 error = got_error_from_errno2("lstat",
7834 ondisk_path);
7835 free(ondisk_path);
7836 goto done;
7838 free(ondisk_path);
7839 if (S_ISDIR(sb.st_mode)) {
7840 error = got_error_msg(GOT_ERR_BAD_PATH,
7841 "removing directories requires -R option");
7842 goto done;
7847 error = got_worktree_schedule_delete(worktree, &paths,
7848 delete_local_mods, status_codes, print_remove_status, NULL,
7849 repo, keep_on_disk, ignore_missing_paths);
7850 done:
7851 if (repo) {
7852 const struct got_error *close_err = got_repo_close(repo);
7853 if (error == NULL)
7854 error = close_err;
7856 if (worktree)
7857 got_worktree_close(worktree);
7858 if (pack_fds) {
7859 const struct got_error *pack_err =
7860 got_repo_pack_fds_close(pack_fds);
7861 if (error == NULL)
7862 error = pack_err;
7864 TAILQ_FOREACH(pe, &paths, entry)
7865 free((char *)pe->path);
7866 got_pathlist_free(&paths);
7867 free(cwd);
7868 return error;
7871 __dead static void
7872 usage_patch(void)
7874 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7875 "[patchfile]\n", getprogname());
7876 exit(1);
7879 static const struct got_error *
7880 patch_from_stdin(int *patchfd)
7882 const struct got_error *err = NULL;
7883 ssize_t r;
7884 char buf[BUFSIZ];
7885 sig_t sighup, sigint, sigquit;
7887 *patchfd = got_opentempfd();
7888 if (*patchfd == -1)
7889 return got_error_from_errno("got_opentempfd");
7891 sighup = signal(SIGHUP, SIG_DFL);
7892 sigint = signal(SIGINT, SIG_DFL);
7893 sigquit = signal(SIGQUIT, SIG_DFL);
7895 for (;;) {
7896 r = read(0, buf, sizeof(buf));
7897 if (r == -1) {
7898 err = got_error_from_errno("read");
7899 break;
7901 if (r == 0)
7902 break;
7903 if (write(*patchfd, buf, r) == -1) {
7904 err = got_error_from_errno("write");
7905 break;
7909 signal(SIGHUP, sighup);
7910 signal(SIGINT, sigint);
7911 signal(SIGQUIT, sigquit);
7913 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7914 err = got_error_from_errno("lseek");
7916 if (err != NULL) {
7917 close(*patchfd);
7918 *patchfd = -1;
7921 return err;
7924 static const struct got_error *
7925 patch_progress(void *arg, const char *old, const char *new,
7926 unsigned char status, const struct got_error *error, int old_from,
7927 int old_lines, int new_from, int new_lines, int offset,
7928 int ws_mangled, const struct got_error *hunk_err)
7930 const char *path = new == NULL ? old : new;
7932 while (*path == '/')
7933 path++;
7935 if (status != 0)
7936 printf("%c %s\n", status, path);
7938 if (error != NULL)
7939 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7941 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7942 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7943 old_lines, new_from, new_lines);
7944 if (hunk_err != NULL)
7945 printf("%s\n", hunk_err->msg);
7946 else if (offset != 0)
7947 printf("applied with offset %d\n", offset);
7948 else
7949 printf("hunk contains mangled whitespace\n");
7952 return NULL;
7955 static const struct got_error *
7956 cmd_patch(int argc, char *argv[])
7958 const struct got_error *error = NULL, *close_error = NULL;
7959 struct got_worktree *worktree = NULL;
7960 struct got_repository *repo = NULL;
7961 struct got_reflist_head refs;
7962 struct got_object_id *commit_id = NULL;
7963 const char *commit_id_str = NULL;
7964 struct stat sb;
7965 const char *errstr;
7966 char *cwd = NULL;
7967 int ch, nop = 0, strip = -1, reverse = 0;
7968 int patchfd;
7969 int *pack_fds = NULL;
7971 TAILQ_INIT(&refs);
7973 #ifndef PROFILE
7974 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7975 "unveil", NULL) == -1)
7976 err(1, "pledge");
7977 #endif
7979 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7980 switch (ch) {
7981 case 'c':
7982 commit_id_str = optarg;
7983 break;
7984 case 'n':
7985 nop = 1;
7986 break;
7987 case 'p':
7988 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7989 if (errstr != NULL)
7990 errx(1, "pathname strip count is %s: %s",
7991 errstr, optarg);
7992 break;
7993 case 'R':
7994 reverse = 1;
7995 break;
7996 default:
7997 usage_patch();
7998 /* NOTREACHED */
8002 argc -= optind;
8003 argv += optind;
8005 if (argc == 0) {
8006 error = patch_from_stdin(&patchfd);
8007 if (error)
8008 return error;
8009 } else if (argc == 1) {
8010 patchfd = open(argv[0], O_RDONLY);
8011 if (patchfd == -1) {
8012 error = got_error_from_errno2("open", argv[0]);
8013 return error;
8015 if (fstat(patchfd, &sb) == -1) {
8016 error = got_error_from_errno2("fstat", argv[0]);
8017 goto done;
8019 if (!S_ISREG(sb.st_mode)) {
8020 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8021 goto done;
8023 } else
8024 usage_patch();
8026 if ((cwd = getcwd(NULL, 0)) == NULL) {
8027 error = got_error_from_errno("getcwd");
8028 goto done;
8031 error = got_repo_pack_fds_open(&pack_fds);
8032 if (error != NULL)
8033 goto done;
8035 error = got_worktree_open(&worktree, cwd);
8036 if (error != NULL)
8037 goto done;
8039 const char *repo_path = got_worktree_get_repo_path(worktree);
8040 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8041 if (error != NULL)
8042 goto done;
8044 error = apply_unveil(got_repo_get_path(repo), 0,
8045 got_worktree_get_root_path(worktree));
8046 if (error != NULL)
8047 goto done;
8049 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8050 if (error)
8051 goto done;
8053 if (commit_id_str != NULL) {
8054 error = got_repo_match_object_id(&commit_id, NULL,
8055 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8056 if (error)
8057 goto done;
8060 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8061 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8063 done:
8064 got_ref_list_free(&refs);
8065 free(commit_id);
8066 if (repo) {
8067 close_error = got_repo_close(repo);
8068 if (error == NULL)
8069 error = close_error;
8071 if (worktree != NULL) {
8072 close_error = got_worktree_close(worktree);
8073 if (error == NULL)
8074 error = close_error;
8076 if (pack_fds) {
8077 const struct got_error *pack_err =
8078 got_repo_pack_fds_close(pack_fds);
8079 if (error == NULL)
8080 error = pack_err;
8082 free(cwd);
8083 return error;
8086 __dead static void
8087 usage_revert(void)
8089 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8090 getprogname());
8091 exit(1);
8094 static const struct got_error *
8095 revert_progress(void *arg, unsigned char status, const char *path)
8097 if (status == GOT_STATUS_UNVERSIONED)
8098 return NULL;
8100 while (path[0] == '/')
8101 path++;
8102 printf("%c %s\n", status, path);
8103 return NULL;
8106 struct choose_patch_arg {
8107 FILE *patch_script_file;
8108 const char *action;
8111 static const struct got_error *
8112 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8113 int nchanges, const char *action)
8115 const struct got_error *err;
8116 char *line = NULL;
8117 size_t linesize = 0;
8118 ssize_t linelen;
8120 switch (status) {
8121 case GOT_STATUS_ADD:
8122 printf("A %s\n%s this addition? [y/n] ", path, action);
8123 break;
8124 case GOT_STATUS_DELETE:
8125 printf("D %s\n%s this deletion? [y/n] ", path, action);
8126 break;
8127 case GOT_STATUS_MODIFY:
8128 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8129 return got_error_from_errno("fseek");
8130 printf(GOT_COMMIT_SEP_STR);
8131 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8132 printf("%s", line);
8133 if (linelen == -1 && ferror(patch_file)) {
8134 err = got_error_from_errno("getline");
8135 free(line);
8136 return err;
8138 free(line);
8139 printf(GOT_COMMIT_SEP_STR);
8140 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8141 path, n, nchanges, action);
8142 break;
8143 default:
8144 return got_error_path(path, GOT_ERR_FILE_STATUS);
8147 fflush(stdout);
8148 return NULL;
8151 static const struct got_error *
8152 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8153 FILE *patch_file, int n, int nchanges)
8155 const struct got_error *err = NULL;
8156 char *line = NULL;
8157 size_t linesize = 0;
8158 ssize_t linelen;
8159 int resp = ' ';
8160 struct choose_patch_arg *a = arg;
8162 *choice = GOT_PATCH_CHOICE_NONE;
8164 if (a->patch_script_file) {
8165 char *nl;
8166 err = show_change(status, path, patch_file, n, nchanges,
8167 a->action);
8168 if (err)
8169 return err;
8170 linelen = getline(&line, &linesize, a->patch_script_file);
8171 if (linelen == -1) {
8172 if (ferror(a->patch_script_file))
8173 return got_error_from_errno("getline");
8174 return NULL;
8176 nl = strchr(line, '\n');
8177 if (nl)
8178 *nl = '\0';
8179 if (strcmp(line, "y") == 0) {
8180 *choice = GOT_PATCH_CHOICE_YES;
8181 printf("y\n");
8182 } else if (strcmp(line, "n") == 0) {
8183 *choice = GOT_PATCH_CHOICE_NO;
8184 printf("n\n");
8185 } else if (strcmp(line, "q") == 0 &&
8186 status == GOT_STATUS_MODIFY) {
8187 *choice = GOT_PATCH_CHOICE_QUIT;
8188 printf("q\n");
8189 } else
8190 printf("invalid response '%s'\n", line);
8191 free(line);
8192 return NULL;
8195 while (resp != 'y' && resp != 'n' && resp != 'q') {
8196 err = show_change(status, path, patch_file, n, nchanges,
8197 a->action);
8198 if (err)
8199 return err;
8200 resp = getchar();
8201 if (resp == '\n')
8202 resp = getchar();
8203 if (status == GOT_STATUS_MODIFY) {
8204 if (resp != 'y' && resp != 'n' && resp != 'q') {
8205 printf("invalid response '%c'\n", resp);
8206 resp = ' ';
8208 } else if (resp != 'y' && resp != 'n') {
8209 printf("invalid response '%c'\n", resp);
8210 resp = ' ';
8214 if (resp == 'y')
8215 *choice = GOT_PATCH_CHOICE_YES;
8216 else if (resp == 'n')
8217 *choice = GOT_PATCH_CHOICE_NO;
8218 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8219 *choice = GOT_PATCH_CHOICE_QUIT;
8221 return NULL;
8224 static const struct got_error *
8225 cmd_revert(int argc, char *argv[])
8227 const struct got_error *error = NULL;
8228 struct got_worktree *worktree = NULL;
8229 struct got_repository *repo = NULL;
8230 char *cwd = NULL, *path = NULL;
8231 struct got_pathlist_head paths;
8232 struct got_pathlist_entry *pe;
8233 int ch, can_recurse = 0, pflag = 0;
8234 FILE *patch_script_file = NULL;
8235 const char *patch_script_path = NULL;
8236 struct choose_patch_arg cpa;
8237 int *pack_fds = NULL;
8239 TAILQ_INIT(&paths);
8241 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8242 switch (ch) {
8243 case 'F':
8244 patch_script_path = optarg;
8245 break;
8246 case 'p':
8247 pflag = 1;
8248 break;
8249 case 'R':
8250 can_recurse = 1;
8251 break;
8252 default:
8253 usage_revert();
8254 /* NOTREACHED */
8258 argc -= optind;
8259 argv += optind;
8261 #ifndef PROFILE
8262 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8263 "unveil", NULL) == -1)
8264 err(1, "pledge");
8265 #endif
8266 if (argc < 1)
8267 usage_revert();
8268 if (patch_script_path && !pflag)
8269 errx(1, "-F option can only be used together with -p option");
8271 cwd = getcwd(NULL, 0);
8272 if (cwd == NULL) {
8273 error = got_error_from_errno("getcwd");
8274 goto done;
8277 error = got_repo_pack_fds_open(&pack_fds);
8278 if (error != NULL)
8279 goto done;
8281 error = got_worktree_open(&worktree, cwd);
8282 if (error) {
8283 if (error->code == GOT_ERR_NOT_WORKTREE)
8284 error = wrap_not_worktree_error(error, "revert", cwd);
8285 goto done;
8288 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8289 NULL, pack_fds);
8290 if (error != NULL)
8291 goto done;
8293 if (patch_script_path) {
8294 patch_script_file = fopen(patch_script_path, "re");
8295 if (patch_script_file == NULL) {
8296 error = got_error_from_errno2("fopen",
8297 patch_script_path);
8298 goto done;
8301 error = apply_unveil(got_repo_get_path(repo), 1,
8302 got_worktree_get_root_path(worktree));
8303 if (error)
8304 goto done;
8306 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8307 if (error)
8308 goto done;
8310 if (!can_recurse) {
8311 char *ondisk_path;
8312 struct stat sb;
8313 TAILQ_FOREACH(pe, &paths, entry) {
8314 if (asprintf(&ondisk_path, "%s/%s",
8315 got_worktree_get_root_path(worktree),
8316 pe->path) == -1) {
8317 error = got_error_from_errno("asprintf");
8318 goto done;
8320 if (lstat(ondisk_path, &sb) == -1) {
8321 if (errno == ENOENT) {
8322 free(ondisk_path);
8323 continue;
8325 error = got_error_from_errno2("lstat",
8326 ondisk_path);
8327 free(ondisk_path);
8328 goto done;
8330 free(ondisk_path);
8331 if (S_ISDIR(sb.st_mode)) {
8332 error = got_error_msg(GOT_ERR_BAD_PATH,
8333 "reverting directories requires -R option");
8334 goto done;
8339 cpa.patch_script_file = patch_script_file;
8340 cpa.action = "revert";
8341 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8342 pflag ? choose_patch : NULL, &cpa, repo);
8343 done:
8344 if (patch_script_file && fclose(patch_script_file) == EOF &&
8345 error == NULL)
8346 error = got_error_from_errno2("fclose", patch_script_path);
8347 if (repo) {
8348 const struct got_error *close_err = got_repo_close(repo);
8349 if (error == NULL)
8350 error = close_err;
8352 if (worktree)
8353 got_worktree_close(worktree);
8354 if (pack_fds) {
8355 const struct got_error *pack_err =
8356 got_repo_pack_fds_close(pack_fds);
8357 if (error == NULL)
8358 error = pack_err;
8360 free(path);
8361 free(cwd);
8362 return error;
8365 __dead static void
8366 usage_commit(void)
8368 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8369 "[-m message] [path ...]\n", getprogname());
8370 exit(1);
8373 struct collect_commit_logmsg_arg {
8374 const char *cmdline_log;
8375 const char *prepared_log;
8376 int non_interactive;
8377 const char *editor;
8378 const char *worktree_path;
8379 const char *branch_name;
8380 const char *repo_path;
8381 char *logmsg_path;
8385 static const struct got_error *
8386 read_prepared_logmsg(char **logmsg, const char *path)
8388 const struct got_error *err = NULL;
8389 FILE *f = NULL;
8390 struct stat sb;
8391 size_t r;
8393 *logmsg = NULL;
8394 memset(&sb, 0, sizeof(sb));
8396 f = fopen(path, "re");
8397 if (f == NULL)
8398 return got_error_from_errno2("fopen", path);
8400 if (fstat(fileno(f), &sb) == -1) {
8401 err = got_error_from_errno2("fstat", path);
8402 goto done;
8404 if (sb.st_size == 0) {
8405 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8406 goto done;
8409 *logmsg = malloc(sb.st_size + 1);
8410 if (*logmsg == NULL) {
8411 err = got_error_from_errno("malloc");
8412 goto done;
8415 r = fread(*logmsg, 1, sb.st_size, f);
8416 if (r != sb.st_size) {
8417 if (ferror(f))
8418 err = got_error_from_errno2("fread", path);
8419 else
8420 err = got_error(GOT_ERR_IO);
8421 goto done;
8423 (*logmsg)[sb.st_size] = '\0';
8424 done:
8425 if (fclose(f) == EOF && err == NULL)
8426 err = got_error_from_errno2("fclose", path);
8427 if (err) {
8428 free(*logmsg);
8429 *logmsg = NULL;
8431 return err;
8434 static const struct got_error *
8435 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8436 const char *diff_path, char **logmsg, void *arg)
8438 char *initial_content = NULL;
8439 struct got_pathlist_entry *pe;
8440 const struct got_error *err = NULL;
8441 char *template = NULL;
8442 struct collect_commit_logmsg_arg *a = arg;
8443 int initial_content_len;
8444 int fd = -1;
8445 size_t len;
8447 /* if a message was specified on the command line, just use it */
8448 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8449 len = strlen(a->cmdline_log) + 1;
8450 *logmsg = malloc(len + 1);
8451 if (*logmsg == NULL)
8452 return got_error_from_errno("malloc");
8453 strlcpy(*logmsg, a->cmdline_log, len);
8454 return NULL;
8455 } else if (a->prepared_log != NULL && a->non_interactive)
8456 return read_prepared_logmsg(logmsg, a->prepared_log);
8458 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8459 return got_error_from_errno("asprintf");
8461 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8462 if (err)
8463 goto done;
8465 if (a->prepared_log) {
8466 char *msg;
8467 err = read_prepared_logmsg(&msg, a->prepared_log);
8468 if (err)
8469 goto done;
8470 if (write(fd, msg, strlen(msg)) == -1) {
8471 err = got_error_from_errno2("write", a->logmsg_path);
8472 free(msg);
8473 goto done;
8475 free(msg);
8478 initial_content_len = asprintf(&initial_content,
8479 "\n# changes to be committed on branch %s:\n",
8480 a->branch_name);
8481 if (initial_content_len == -1) {
8482 err = got_error_from_errno("asprintf");
8483 goto done;
8486 if (write(fd, initial_content, initial_content_len) == -1) {
8487 err = got_error_from_errno2("write", a->logmsg_path);
8488 goto done;
8491 TAILQ_FOREACH(pe, commitable_paths, entry) {
8492 struct got_commitable *ct = pe->data;
8493 dprintf(fd, "# %c %s\n",
8494 got_commitable_get_status(ct),
8495 got_commitable_get_path(ct));
8498 if (diff_path) {
8499 dprintf(fd, "# detailed changes can be viewed in %s\n",
8500 diff_path);
8503 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8504 initial_content_len, a->prepared_log ? 0 : 1);
8505 done:
8506 free(initial_content);
8507 free(template);
8509 if (fd != -1 && close(fd) == -1 && err == NULL)
8510 err = got_error_from_errno2("close", a->logmsg_path);
8512 /* Editor is done; we can now apply unveil(2) */
8513 if (err == NULL)
8514 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8515 if (err) {
8516 free(*logmsg);
8517 *logmsg = NULL;
8519 return err;
8522 static const struct got_error *
8523 cmd_commit(int argc, char *argv[])
8525 const struct got_error *error = NULL;
8526 struct got_worktree *worktree = NULL;
8527 struct got_repository *repo = NULL;
8528 char *cwd = NULL, *id_str = NULL;
8529 struct got_object_id *id = NULL;
8530 const char *logmsg = NULL;
8531 char *prepared_logmsg = NULL;
8532 struct collect_commit_logmsg_arg cl_arg;
8533 const char *author = NULL;
8534 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8535 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8536 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8537 int show_diff = 1;
8538 struct got_pathlist_head paths;
8539 int *pack_fds = NULL;
8541 TAILQ_INIT(&paths);
8542 cl_arg.logmsg_path = NULL;
8544 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8545 switch (ch) {
8546 case 'A':
8547 author = optarg;
8548 error = valid_author(author);
8549 if (error)
8550 return error;
8551 break;
8552 case 'F':
8553 if (logmsg != NULL)
8554 option_conflict('F', 'm');
8555 prepared_logmsg = realpath(optarg, NULL);
8556 if (prepared_logmsg == NULL)
8557 return got_error_from_errno2("realpath",
8558 optarg);
8559 break;
8560 case 'm':
8561 if (prepared_logmsg)
8562 option_conflict('m', 'F');
8563 logmsg = optarg;
8564 break;
8565 case 'N':
8566 non_interactive = 1;
8567 break;
8568 case 'n':
8569 show_diff = 0;
8570 break;
8571 case 'S':
8572 allow_bad_symlinks = 1;
8573 break;
8574 default:
8575 usage_commit();
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 cwd = getcwd(NULL, 0);
8589 if (cwd == NULL) {
8590 error = got_error_from_errno("getcwd");
8591 goto done;
8594 error = got_repo_pack_fds_open(&pack_fds);
8595 if (error != NULL)
8596 goto done;
8598 error = got_worktree_open(&worktree, cwd);
8599 if (error) {
8600 if (error->code == GOT_ERR_NOT_WORKTREE)
8601 error = wrap_not_worktree_error(error, "commit", cwd);
8602 goto done;
8605 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8606 if (error)
8607 goto done;
8608 if (rebase_in_progress) {
8609 error = got_error(GOT_ERR_REBASING);
8610 goto done;
8613 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8614 worktree);
8615 if (error)
8616 goto done;
8618 error = get_gitconfig_path(&gitconfig_path);
8619 if (error)
8620 goto done;
8621 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8622 gitconfig_path, pack_fds);
8623 if (error != NULL)
8624 goto done;
8626 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8627 if (error)
8628 goto done;
8629 if (merge_in_progress) {
8630 error = got_error(GOT_ERR_MERGE_BUSY);
8631 goto done;
8634 error = get_author(&committer, repo, worktree);
8635 if (error)
8636 goto done;
8638 if (author != NULL && !strcmp(committer, author)) {
8639 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8640 goto done;
8643 if (author == NULL)
8644 author = committer;
8647 * unveil(2) traverses exec(2); if an editor is used we have
8648 * to apply unveil after the log message has been written.
8650 if (logmsg == NULL || strlen(logmsg) == 0)
8651 error = get_editor(&editor);
8652 else
8653 error = apply_unveil(got_repo_get_path(repo), 0,
8654 got_worktree_get_root_path(worktree));
8655 if (error)
8656 goto done;
8658 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8659 if (error)
8660 goto done;
8662 cl_arg.editor = editor;
8663 cl_arg.cmdline_log = logmsg;
8664 cl_arg.prepared_log = prepared_logmsg;
8665 cl_arg.non_interactive = non_interactive;
8666 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8667 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8668 if (!histedit_in_progress) {
8669 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8670 error = got_error(GOT_ERR_COMMIT_BRANCH);
8671 goto done;
8673 cl_arg.branch_name += 11;
8675 cl_arg.repo_path = got_repo_get_path(repo);
8676 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8677 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8678 print_status, NULL, repo);
8679 if (error) {
8680 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8681 cl_arg.logmsg_path != NULL)
8682 preserve_logmsg = 1;
8683 goto done;
8686 error = got_object_id_str(&id_str, id);
8687 if (error)
8688 goto done;
8689 printf("Created commit %s\n", id_str);
8690 done:
8691 if (preserve_logmsg) {
8692 fprintf(stderr, "%s: log message preserved in %s\n",
8693 getprogname(), cl_arg.logmsg_path);
8694 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8695 error == NULL)
8696 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8697 free(cl_arg.logmsg_path);
8698 if (repo) {
8699 const struct got_error *close_err = got_repo_close(repo);
8700 if (error == NULL)
8701 error = close_err;
8703 if (worktree)
8704 got_worktree_close(worktree);
8705 if (pack_fds) {
8706 const struct got_error *pack_err =
8707 got_repo_pack_fds_close(pack_fds);
8708 if (error == NULL)
8709 error = pack_err;
8711 free(cwd);
8712 free(id_str);
8713 free(gitconfig_path);
8714 free(editor);
8715 free(committer);
8716 free(prepared_logmsg);
8717 return error;
8720 __dead static void
8721 usage_send(void)
8723 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8724 "[-r repository-path] [-t tag] [remote-repository]\n",
8725 getprogname());
8726 exit(1);
8729 static void
8730 print_load_info(int print_colored, int print_found, int print_trees,
8731 int ncolored, int nfound, int ntrees)
8733 if (print_colored) {
8734 printf("%d commit%s colored", ncolored,
8735 ncolored == 1 ? "" : "s");
8737 if (print_found) {
8738 printf("%s%d object%s found",
8739 ncolored > 0 ? "; " : "",
8740 nfound, nfound == 1 ? "" : "s");
8742 if (print_trees) {
8743 printf("; %d tree%s scanned", ntrees,
8744 ntrees == 1 ? "" : "s");
8748 struct got_send_progress_arg {
8749 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8750 int verbosity;
8751 int last_ncolored;
8752 int last_nfound;
8753 int last_ntrees;
8754 int loading_done;
8755 int last_ncommits;
8756 int last_nobj_total;
8757 int last_p_deltify;
8758 int last_p_written;
8759 int last_p_sent;
8760 int printed_something;
8761 int sent_something;
8762 struct got_pathlist_head *delete_branches;
8765 static const struct got_error *
8766 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8767 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8768 int nobj_written, off_t bytes_sent, const char *refname,
8769 const char *errmsg, int success)
8771 struct got_send_progress_arg *a = arg;
8772 char scaled_packsize[FMT_SCALED_STRSIZE];
8773 char scaled_sent[FMT_SCALED_STRSIZE];
8774 int p_deltify = 0, p_written = 0, p_sent = 0;
8775 int print_colored = 0, print_found = 0, print_trees = 0;
8776 int print_searching = 0, print_total = 0;
8777 int print_deltify = 0, print_written = 0, print_sent = 0;
8779 if (a->verbosity < 0)
8780 return NULL;
8782 if (refname) {
8783 const char *status = success ? "accepted" : "rejected";
8785 if (success) {
8786 struct got_pathlist_entry *pe;
8787 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8788 const char *branchname = pe->path;
8789 if (got_path_cmp(branchname, refname,
8790 strlen(branchname), strlen(refname)) == 0) {
8791 status = "deleted";
8792 a->sent_something = 1;
8793 break;
8798 if (a->printed_something)
8799 putchar('\n');
8800 printf("Server has %s %s", status, refname);
8801 if (errmsg)
8802 printf(": %s", errmsg);
8803 a->printed_something = 1;
8804 return NULL;
8807 if (a->last_ncolored != ncolored) {
8808 print_colored = 1;
8809 a->last_ncolored = ncolored;
8812 if (a->last_nfound != nfound) {
8813 print_colored = 1;
8814 print_found = 1;
8815 a->last_nfound = nfound;
8818 if (a->last_ntrees != ntrees) {
8819 print_colored = 1;
8820 print_found = 1;
8821 print_trees = 1;
8822 a->last_ntrees = ntrees;
8825 if ((print_colored || print_found || print_trees) &&
8826 !a->loading_done) {
8827 printf("\r");
8828 print_load_info(print_colored, print_found, print_trees,
8829 ncolored, nfound, ntrees);
8830 a->printed_something = 1;
8831 fflush(stdout);
8832 return NULL;
8833 } else if (!a->loading_done) {
8834 printf("\r");
8835 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8836 printf("\n");
8837 a->loading_done = 1;
8840 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8841 return got_error_from_errno("fmt_scaled");
8842 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8843 return got_error_from_errno("fmt_scaled");
8845 if (a->last_ncommits != ncommits) {
8846 print_searching = 1;
8847 a->last_ncommits = ncommits;
8850 if (a->last_nobj_total != nobj_total) {
8851 print_searching = 1;
8852 print_total = 1;
8853 a->last_nobj_total = nobj_total;
8856 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8857 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8858 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8859 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8860 return got_error(GOT_ERR_NO_SPACE);
8863 if (nobj_deltify > 0 || nobj_written > 0) {
8864 if (nobj_deltify > 0) {
8865 p_deltify = (nobj_deltify * 100) / nobj_total;
8866 if (p_deltify != a->last_p_deltify) {
8867 a->last_p_deltify = p_deltify;
8868 print_searching = 1;
8869 print_total = 1;
8870 print_deltify = 1;
8873 if (nobj_written > 0) {
8874 p_written = (nobj_written * 100) / nobj_total;
8875 if (p_written != a->last_p_written) {
8876 a->last_p_written = p_written;
8877 print_searching = 1;
8878 print_total = 1;
8879 print_deltify = 1;
8880 print_written = 1;
8885 if (bytes_sent > 0) {
8886 p_sent = (bytes_sent * 100) / packfile_size;
8887 if (p_sent != a->last_p_sent) {
8888 a->last_p_sent = p_sent;
8889 print_searching = 1;
8890 print_total = 1;
8891 print_deltify = 1;
8892 print_written = 1;
8893 print_sent = 1;
8895 a->sent_something = 1;
8898 if (print_searching || print_total || print_deltify || print_written ||
8899 print_sent)
8900 printf("\r");
8901 if (print_searching)
8902 printf("packing %d reference%s", ncommits,
8903 ncommits == 1 ? "" : "s");
8904 if (print_total)
8905 printf("; %d object%s", nobj_total,
8906 nobj_total == 1 ? "" : "s");
8907 if (print_deltify)
8908 printf("; deltify: %d%%", p_deltify);
8909 if (print_sent)
8910 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8911 scaled_packsize, p_sent);
8912 else if (print_written)
8913 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8914 scaled_packsize, p_written);
8915 if (print_searching || print_total || print_deltify ||
8916 print_written || print_sent) {
8917 a->printed_something = 1;
8918 fflush(stdout);
8920 return NULL;
8923 static const struct got_error *
8924 cmd_send(int argc, char *argv[])
8926 const struct got_error *error = NULL;
8927 char *cwd = NULL, *repo_path = NULL;
8928 const char *remote_name;
8929 char *proto = NULL, *host = NULL, *port = NULL;
8930 char *repo_name = NULL, *server_path = NULL;
8931 const struct got_remote_repo *remotes, *remote = NULL;
8932 int nremotes, nbranches = 0, ndelete_branches = 0;
8933 struct got_repository *repo = NULL;
8934 struct got_worktree *worktree = NULL;
8935 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8936 struct got_pathlist_head branches;
8937 struct got_pathlist_head tags;
8938 struct got_reflist_head all_branches;
8939 struct got_reflist_head all_tags;
8940 struct got_pathlist_head delete_args;
8941 struct got_pathlist_head delete_branches;
8942 struct got_reflist_entry *re;
8943 struct got_pathlist_entry *pe;
8944 int i, ch, sendfd = -1, sendstatus;
8945 pid_t sendpid = -1;
8946 struct got_send_progress_arg spa;
8947 int verbosity = 0, overwrite_refs = 0;
8948 int send_all_branches = 0, send_all_tags = 0;
8949 struct got_reference *ref = NULL;
8950 int *pack_fds = NULL;
8952 TAILQ_INIT(&branches);
8953 TAILQ_INIT(&tags);
8954 TAILQ_INIT(&all_branches);
8955 TAILQ_INIT(&all_tags);
8956 TAILQ_INIT(&delete_args);
8957 TAILQ_INIT(&delete_branches);
8959 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
8960 switch (ch) {
8961 case 'a':
8962 send_all_branches = 1;
8963 break;
8964 case 'b':
8965 error = got_pathlist_append(&branches, optarg, NULL);
8966 if (error)
8967 return error;
8968 nbranches++;
8969 break;
8970 case 'd':
8971 error = got_pathlist_append(&delete_args, optarg, NULL);
8972 if (error)
8973 return error;
8974 break;
8975 case 'f':
8976 overwrite_refs = 1;
8977 break;
8978 case 'q':
8979 verbosity = -1;
8980 break;
8981 case 'r':
8982 repo_path = realpath(optarg, NULL);
8983 if (repo_path == NULL)
8984 return got_error_from_errno2("realpath",
8985 optarg);
8986 got_path_strip_trailing_slashes(repo_path);
8987 break;
8988 case 'T':
8989 send_all_tags = 1;
8990 break;
8991 case 't':
8992 error = got_pathlist_append(&tags, optarg, NULL);
8993 if (error)
8994 return error;
8995 break;
8996 case 'v':
8997 if (verbosity < 0)
8998 verbosity = 0;
8999 else if (verbosity < 3)
9000 verbosity++;
9001 break;
9002 default:
9003 usage_send();
9004 /* NOTREACHED */
9007 argc -= optind;
9008 argv += optind;
9010 if (send_all_branches && !TAILQ_EMPTY(&branches))
9011 option_conflict('a', 'b');
9012 if (send_all_tags && !TAILQ_EMPTY(&tags))
9013 option_conflict('T', 't');
9016 if (argc == 0)
9017 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9018 else if (argc == 1)
9019 remote_name = argv[0];
9020 else
9021 usage_send();
9023 cwd = getcwd(NULL, 0);
9024 if (cwd == NULL) {
9025 error = got_error_from_errno("getcwd");
9026 goto done;
9029 error = got_repo_pack_fds_open(&pack_fds);
9030 if (error != NULL)
9031 goto done;
9033 if (repo_path == NULL) {
9034 error = got_worktree_open(&worktree, cwd);
9035 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9036 goto done;
9037 else
9038 error = NULL;
9039 if (worktree) {
9040 repo_path =
9041 strdup(got_worktree_get_repo_path(worktree));
9042 if (repo_path == NULL)
9043 error = got_error_from_errno("strdup");
9044 if (error)
9045 goto done;
9046 } else {
9047 repo_path = strdup(cwd);
9048 if (repo_path == NULL) {
9049 error = got_error_from_errno("strdup");
9050 goto done;
9055 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9056 if (error)
9057 goto done;
9059 if (worktree) {
9060 worktree_conf = got_worktree_get_gotconfig(worktree);
9061 if (worktree_conf) {
9062 got_gotconfig_get_remotes(&nremotes, &remotes,
9063 worktree_conf);
9064 for (i = 0; i < nremotes; i++) {
9065 if (strcmp(remotes[i].name, remote_name) == 0) {
9066 remote = &remotes[i];
9067 break;
9072 if (remote == NULL) {
9073 repo_conf = got_repo_get_gotconfig(repo);
9074 if (repo_conf) {
9075 got_gotconfig_get_remotes(&nremotes, &remotes,
9076 repo_conf);
9077 for (i = 0; i < nremotes; i++) {
9078 if (strcmp(remotes[i].name, remote_name) == 0) {
9079 remote = &remotes[i];
9080 break;
9085 if (remote == NULL) {
9086 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9087 for (i = 0; i < nremotes; i++) {
9088 if (strcmp(remotes[i].name, remote_name) == 0) {
9089 remote = &remotes[i];
9090 break;
9094 if (remote == NULL) {
9095 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9096 goto done;
9099 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9100 &repo_name, remote->send_url);
9101 if (error)
9102 goto done;
9104 if (strcmp(proto, "git") == 0) {
9105 #ifndef PROFILE
9106 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9107 "sendfd dns inet unveil", NULL) == -1)
9108 err(1, "pledge");
9109 #endif
9110 } else if (strcmp(proto, "git+ssh") == 0 ||
9111 strcmp(proto, "ssh") == 0) {
9112 #ifndef PROFILE
9113 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9114 "sendfd unveil", NULL) == -1)
9115 err(1, "pledge");
9116 #endif
9117 } else if (strcmp(proto, "http") == 0 ||
9118 strcmp(proto, "git+http") == 0) {
9119 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9120 goto done;
9121 } else {
9122 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9123 goto done;
9126 error = got_dial_apply_unveil(proto);
9127 if (error)
9128 goto done;
9130 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9131 if (error)
9132 goto done;
9134 if (send_all_branches) {
9135 error = got_ref_list(&all_branches, repo, "refs/heads",
9136 got_ref_cmp_by_name, NULL);
9137 if (error)
9138 goto done;
9139 TAILQ_FOREACH(re, &all_branches, entry) {
9140 const char *branchname = got_ref_get_name(re->ref);
9141 error = got_pathlist_append(&branches,
9142 branchname, NULL);
9143 if (error)
9144 goto done;
9145 nbranches++;
9147 } else if (nbranches == 0) {
9148 for (i = 0; i < remote->nsend_branches; i++) {
9149 got_pathlist_append(&branches,
9150 remote->send_branches[i], NULL);
9154 if (send_all_tags) {
9155 error = got_ref_list(&all_tags, repo, "refs/tags",
9156 got_ref_cmp_by_name, NULL);
9157 if (error)
9158 goto done;
9159 TAILQ_FOREACH(re, &all_tags, entry) {
9160 const char *tagname = got_ref_get_name(re->ref);
9161 error = got_pathlist_append(&tags,
9162 tagname, NULL);
9163 if (error)
9164 goto done;
9169 * To prevent accidents only branches in refs/heads/ can be deleted
9170 * with 'got send -d'.
9171 * Deleting anything else requires local repository access or Git.
9173 TAILQ_FOREACH(pe, &delete_args, entry) {
9174 const char *branchname = pe->path;
9175 char *s;
9176 struct got_pathlist_entry *new;
9177 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9178 s = strdup(branchname);
9179 if (s == NULL) {
9180 error = got_error_from_errno("strdup");
9181 goto done;
9183 } else {
9184 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9185 error = got_error_from_errno("asprintf");
9186 goto done;
9189 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9190 if (error || new == NULL /* duplicate */)
9191 free(s);
9192 if (error)
9193 goto done;
9194 ndelete_branches++;
9197 if (nbranches == 0 && ndelete_branches == 0) {
9198 struct got_reference *head_ref;
9199 if (worktree)
9200 error = got_ref_open(&head_ref, repo,
9201 got_worktree_get_head_ref_name(worktree), 0);
9202 else
9203 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9204 if (error)
9205 goto done;
9206 if (got_ref_is_symbolic(head_ref)) {
9207 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9208 got_ref_close(head_ref);
9209 if (error)
9210 goto done;
9211 } else
9212 ref = head_ref;
9213 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9214 NULL);
9215 if (error)
9216 goto done;
9217 nbranches++;
9220 if (verbosity >= 0) {
9221 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9222 remote->name, proto, host,
9223 port ? ":" : "", port ? port : "",
9224 *server_path == '/' ? "" : "/", server_path);
9227 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9228 server_path, verbosity);
9229 if (error)
9230 goto done;
9232 memset(&spa, 0, sizeof(spa));
9233 spa.last_scaled_packsize[0] = '\0';
9234 spa.last_p_deltify = -1;
9235 spa.last_p_written = -1;
9236 spa.verbosity = verbosity;
9237 spa.delete_branches = &delete_branches;
9238 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9239 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9240 check_cancelled, NULL);
9241 if (spa.printed_something)
9242 putchar('\n');
9243 if (error)
9244 goto done;
9245 if (!spa.sent_something && verbosity >= 0)
9246 printf("Already up-to-date\n");
9247 done:
9248 if (sendpid > 0) {
9249 if (kill(sendpid, SIGTERM) == -1)
9250 error = got_error_from_errno("kill");
9251 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9252 error = got_error_from_errno("waitpid");
9254 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9255 error = got_error_from_errno("close");
9256 if (repo) {
9257 const struct got_error *close_err = got_repo_close(repo);
9258 if (error == NULL)
9259 error = close_err;
9261 if (worktree)
9262 got_worktree_close(worktree);
9263 if (pack_fds) {
9264 const struct got_error *pack_err =
9265 got_repo_pack_fds_close(pack_fds);
9266 if (error == NULL)
9267 error = pack_err;
9269 if (ref)
9270 got_ref_close(ref);
9271 got_pathlist_free(&branches);
9272 got_pathlist_free(&tags);
9273 got_ref_list_free(&all_branches);
9274 got_ref_list_free(&all_tags);
9275 got_pathlist_free(&delete_args);
9276 TAILQ_FOREACH(pe, &delete_branches, entry)
9277 free((char *)pe->path);
9278 got_pathlist_free(&delete_branches);
9279 free(cwd);
9280 free(repo_path);
9281 free(proto);
9282 free(host);
9283 free(port);
9284 free(server_path);
9285 free(repo_name);
9286 return error;
9289 __dead static void
9290 usage_cherrypick(void)
9292 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9293 exit(1);
9296 static const struct got_error *
9297 cmd_cherrypick(int argc, char *argv[])
9299 const struct got_error *error = NULL;
9300 struct got_worktree *worktree = NULL;
9301 struct got_repository *repo = NULL;
9302 char *cwd = NULL, *commit_id_str = NULL;
9303 struct got_object_id *commit_id = NULL;
9304 struct got_commit_object *commit = NULL;
9305 struct got_object_qid *pid;
9306 int ch;
9307 struct got_update_progress_arg upa;
9308 int *pack_fds = NULL;
9310 while ((ch = getopt(argc, argv, "")) != -1) {
9311 switch (ch) {
9312 default:
9313 usage_cherrypick();
9314 /* NOTREACHED */
9318 argc -= optind;
9319 argv += optind;
9321 #ifndef PROFILE
9322 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9323 "unveil", NULL) == -1)
9324 err(1, "pledge");
9325 #endif
9326 if (argc != 1)
9327 usage_cherrypick();
9329 cwd = getcwd(NULL, 0);
9330 if (cwd == NULL) {
9331 error = got_error_from_errno("getcwd");
9332 goto done;
9335 error = got_repo_pack_fds_open(&pack_fds);
9336 if (error != NULL)
9337 goto done;
9339 error = got_worktree_open(&worktree, cwd);
9340 if (error) {
9341 if (error->code == GOT_ERR_NOT_WORKTREE)
9342 error = wrap_not_worktree_error(error, "cherrypick",
9343 cwd);
9344 goto done;
9347 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9348 NULL, pack_fds);
9349 if (error != NULL)
9350 goto done;
9352 error = apply_unveil(got_repo_get_path(repo), 0,
9353 got_worktree_get_root_path(worktree));
9354 if (error)
9355 goto done;
9357 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9358 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9359 if (error)
9360 goto done;
9361 error = got_object_id_str(&commit_id_str, commit_id);
9362 if (error)
9363 goto done;
9365 error = got_object_open_as_commit(&commit, repo, commit_id);
9366 if (error)
9367 goto done;
9368 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9369 memset(&upa, 0, sizeof(upa));
9370 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9371 commit_id, repo, update_progress, &upa, check_cancelled,
9372 NULL);
9373 if (error != NULL)
9374 goto done;
9376 if (upa.did_something)
9377 printf("Merged commit %s\n", commit_id_str);
9378 print_merge_progress_stats(&upa);
9379 done:
9380 if (commit)
9381 got_object_commit_close(commit);
9382 free(commit_id_str);
9383 if (worktree)
9384 got_worktree_close(worktree);
9385 if (repo) {
9386 const struct got_error *close_err = got_repo_close(repo);
9387 if (error == NULL)
9388 error = close_err;
9390 if (pack_fds) {
9391 const struct got_error *pack_err =
9392 got_repo_pack_fds_close(pack_fds);
9393 if (error == NULL)
9394 error = pack_err;
9397 return error;
9400 __dead static void
9401 usage_backout(void)
9403 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9404 exit(1);
9407 static const struct got_error *
9408 cmd_backout(int argc, char *argv[])
9410 const struct got_error *error = NULL;
9411 struct got_worktree *worktree = NULL;
9412 struct got_repository *repo = NULL;
9413 char *cwd = NULL, *commit_id_str = NULL;
9414 struct got_object_id *commit_id = NULL;
9415 struct got_commit_object *commit = NULL;
9416 struct got_object_qid *pid;
9417 int ch;
9418 struct got_update_progress_arg upa;
9419 int *pack_fds = NULL;
9421 while ((ch = getopt(argc, argv, "")) != -1) {
9422 switch (ch) {
9423 default:
9424 usage_backout();
9425 /* NOTREACHED */
9429 argc -= optind;
9430 argv += optind;
9432 #ifndef PROFILE
9433 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9434 "unveil", NULL) == -1)
9435 err(1, "pledge");
9436 #endif
9437 if (argc != 1)
9438 usage_backout();
9440 cwd = getcwd(NULL, 0);
9441 if (cwd == NULL) {
9442 error = got_error_from_errno("getcwd");
9443 goto done;
9446 error = got_repo_pack_fds_open(&pack_fds);
9447 if (error != NULL)
9448 goto done;
9450 error = got_worktree_open(&worktree, cwd);
9451 if (error) {
9452 if (error->code == GOT_ERR_NOT_WORKTREE)
9453 error = wrap_not_worktree_error(error, "backout", cwd);
9454 goto done;
9457 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9458 NULL, pack_fds);
9459 if (error != NULL)
9460 goto done;
9462 error = apply_unveil(got_repo_get_path(repo), 0,
9463 got_worktree_get_root_path(worktree));
9464 if (error)
9465 goto done;
9467 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9468 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9469 if (error)
9470 goto done;
9471 error = got_object_id_str(&commit_id_str, commit_id);
9472 if (error)
9473 goto done;
9475 error = got_object_open_as_commit(&commit, repo, commit_id);
9476 if (error)
9477 goto done;
9478 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9479 if (pid == NULL) {
9480 error = got_error(GOT_ERR_ROOT_COMMIT);
9481 goto done;
9484 memset(&upa, 0, sizeof(upa));
9485 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9486 repo, update_progress, &upa, check_cancelled, NULL);
9487 if (error != NULL)
9488 goto done;
9490 if (upa.did_something)
9491 printf("Backed out commit %s\n", commit_id_str);
9492 print_merge_progress_stats(&upa);
9493 done:
9494 if (commit)
9495 got_object_commit_close(commit);
9496 free(commit_id_str);
9497 if (worktree)
9498 got_worktree_close(worktree);
9499 if (repo) {
9500 const struct got_error *close_err = got_repo_close(repo);
9501 if (error == NULL)
9502 error = close_err;
9504 if (pack_fds) {
9505 const struct got_error *pack_err =
9506 got_repo_pack_fds_close(pack_fds);
9507 if (error == NULL)
9508 error = pack_err;
9510 return error;
9513 __dead static void
9514 usage_rebase(void)
9516 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9517 exit(1);
9520 static void
9521 trim_logmsg(char *logmsg, int limit)
9523 char *nl;
9524 size_t len;
9526 len = strlen(logmsg);
9527 if (len > limit)
9528 len = limit;
9529 logmsg[len] = '\0';
9530 nl = strchr(logmsg, '\n');
9531 if (nl)
9532 *nl = '\0';
9535 static const struct got_error *
9536 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9538 const struct got_error *err;
9539 char *logmsg0 = NULL;
9540 const char *s;
9542 err = got_object_commit_get_logmsg(&logmsg0, commit);
9543 if (err)
9544 return err;
9546 s = logmsg0;
9547 while (isspace((unsigned char)s[0]))
9548 s++;
9550 *logmsg = strdup(s);
9551 if (*logmsg == NULL) {
9552 err = got_error_from_errno("strdup");
9553 goto done;
9556 trim_logmsg(*logmsg, limit);
9557 done:
9558 free(logmsg0);
9559 return err;
9562 static const struct got_error *
9563 show_rebase_merge_conflict(struct got_object_id *id,
9564 struct got_repository *repo)
9566 const struct got_error *err;
9567 struct got_commit_object *commit = NULL;
9568 char *id_str = NULL, *logmsg = NULL;
9570 err = got_object_open_as_commit(&commit, repo, id);
9571 if (err)
9572 return err;
9574 err = got_object_id_str(&id_str, id);
9575 if (err)
9576 goto done;
9578 id_str[12] = '\0';
9580 err = get_short_logmsg(&logmsg, 42, commit);
9581 if (err)
9582 goto done;
9584 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9585 done:
9586 free(id_str);
9587 got_object_commit_close(commit);
9588 free(logmsg);
9589 return err;
9592 static const struct got_error *
9593 show_rebase_progress(struct got_commit_object *commit,
9594 struct got_object_id *old_id, struct got_object_id *new_id)
9596 const struct got_error *err;
9597 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9599 err = got_object_id_str(&old_id_str, old_id);
9600 if (err)
9601 goto done;
9603 if (new_id) {
9604 err = got_object_id_str(&new_id_str, new_id);
9605 if (err)
9606 goto done;
9609 old_id_str[12] = '\0';
9610 if (new_id_str)
9611 new_id_str[12] = '\0';
9613 err = get_short_logmsg(&logmsg, 42, commit);
9614 if (err)
9615 goto done;
9617 printf("%s -> %s: %s\n", old_id_str,
9618 new_id_str ? new_id_str : "no-op change", logmsg);
9619 done:
9620 free(old_id_str);
9621 free(new_id_str);
9622 free(logmsg);
9623 return err;
9626 static const struct got_error *
9627 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9628 struct got_reference *branch, struct got_reference *new_base_branch,
9629 struct got_reference *tmp_branch, struct got_repository *repo,
9630 int create_backup)
9632 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9633 return got_worktree_rebase_complete(worktree, fileindex,
9634 new_base_branch, tmp_branch, branch, repo, create_backup);
9637 static const struct got_error *
9638 rebase_commit(struct got_pathlist_head *merged_paths,
9639 struct got_worktree *worktree, struct got_fileindex *fileindex,
9640 struct got_reference *tmp_branch, const char *committer,
9641 struct got_object_id *commit_id, struct got_repository *repo)
9643 const struct got_error *error;
9644 struct got_commit_object *commit;
9645 struct got_object_id *new_commit_id;
9647 error = got_object_open_as_commit(&commit, repo, commit_id);
9648 if (error)
9649 return error;
9651 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9652 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9653 repo);
9654 if (error) {
9655 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9656 goto done;
9657 error = show_rebase_progress(commit, commit_id, NULL);
9658 } else {
9659 error = show_rebase_progress(commit, commit_id, new_commit_id);
9660 free(new_commit_id);
9662 done:
9663 got_object_commit_close(commit);
9664 return error;
9667 struct check_path_prefix_arg {
9668 const char *path_prefix;
9669 size_t len;
9670 int errcode;
9673 static const struct got_error *
9674 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9675 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9676 struct got_object_id *id1, struct got_object_id *id2,
9677 const char *path1, const char *path2,
9678 mode_t mode1, mode_t mode2, struct got_repository *repo)
9680 struct check_path_prefix_arg *a = arg;
9682 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9683 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9684 return got_error(a->errcode);
9686 return NULL;
9689 static const struct got_error *
9690 check_path_prefix(struct got_object_id *parent_id,
9691 struct got_object_id *commit_id, const char *path_prefix,
9692 int errcode, struct got_repository *repo)
9694 const struct got_error *err;
9695 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9696 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9697 struct check_path_prefix_arg cpp_arg;
9699 if (got_path_is_root_dir(path_prefix))
9700 return NULL;
9702 err = got_object_open_as_commit(&commit, repo, commit_id);
9703 if (err)
9704 goto done;
9706 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9707 if (err)
9708 goto done;
9710 err = got_object_open_as_tree(&tree1, repo,
9711 got_object_commit_get_tree_id(parent_commit));
9712 if (err)
9713 goto done;
9715 err = got_object_open_as_tree(&tree2, repo,
9716 got_object_commit_get_tree_id(commit));
9717 if (err)
9718 goto done;
9720 cpp_arg.path_prefix = path_prefix;
9721 while (cpp_arg.path_prefix[0] == '/')
9722 cpp_arg.path_prefix++;
9723 cpp_arg.len = strlen(cpp_arg.path_prefix);
9724 cpp_arg.errcode = errcode;
9725 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9726 check_path_prefix_in_diff, &cpp_arg, 0);
9727 done:
9728 if (tree1)
9729 got_object_tree_close(tree1);
9730 if (tree2)
9731 got_object_tree_close(tree2);
9732 if (commit)
9733 got_object_commit_close(commit);
9734 if (parent_commit)
9735 got_object_commit_close(parent_commit);
9736 return err;
9739 static const struct got_error *
9740 collect_commits(struct got_object_id_queue *commits,
9741 struct got_object_id *initial_commit_id,
9742 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9743 const char *path_prefix, int path_prefix_errcode,
9744 struct got_repository *repo)
9746 const struct got_error *err = NULL;
9747 struct got_commit_graph *graph = NULL;
9748 struct got_object_id parent_id, commit_id;
9749 struct got_object_qid *qid;
9751 err = got_commit_graph_open(&graph, "/", 1);
9752 if (err)
9753 return err;
9755 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9756 check_cancelled, NULL);
9757 if (err)
9758 goto done;
9760 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9761 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9762 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9763 check_cancelled, NULL);
9764 if (err) {
9765 if (err->code == GOT_ERR_ITER_COMPLETED) {
9766 err = got_error_msg(GOT_ERR_ANCESTRY,
9767 "ran out of commits to rebase before "
9768 "youngest common ancestor commit has "
9769 "been reached?!?");
9771 goto done;
9772 } else {
9773 err = check_path_prefix(&parent_id, &commit_id,
9774 path_prefix, path_prefix_errcode, repo);
9775 if (err)
9776 goto done;
9778 err = got_object_qid_alloc(&qid, &commit_id);
9779 if (err)
9780 goto done;
9781 STAILQ_INSERT_HEAD(commits, qid, entry);
9783 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9786 done:
9787 got_commit_graph_close(graph);
9788 return err;
9791 static const struct got_error *
9792 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9794 const struct got_error *err = NULL;
9795 time_t committer_time;
9796 struct tm tm;
9797 char datebuf[11]; /* YYYY-MM-DD + NUL */
9798 char *author0 = NULL, *author, *smallerthan;
9799 char *logmsg0 = NULL, *logmsg, *newline;
9801 committer_time = got_object_commit_get_committer_time(commit);
9802 if (gmtime_r(&committer_time, &tm) == NULL)
9803 return got_error_from_errno("gmtime_r");
9804 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9805 return got_error(GOT_ERR_NO_SPACE);
9807 author0 = strdup(got_object_commit_get_author(commit));
9808 if (author0 == NULL)
9809 return got_error_from_errno("strdup");
9810 author = author0;
9811 smallerthan = strchr(author, '<');
9812 if (smallerthan && smallerthan[1] != '\0')
9813 author = smallerthan + 1;
9814 author[strcspn(author, "@>")] = '\0';
9816 err = got_object_commit_get_logmsg(&logmsg0, commit);
9817 if (err)
9818 goto done;
9819 logmsg = logmsg0;
9820 while (*logmsg == '\n')
9821 logmsg++;
9822 newline = strchr(logmsg, '\n');
9823 if (newline)
9824 *newline = '\0';
9826 if (asprintf(brief_str, "%s %s %s",
9827 datebuf, author, logmsg) == -1)
9828 err = got_error_from_errno("asprintf");
9829 done:
9830 free(author0);
9831 free(logmsg0);
9832 return err;
9835 static const struct got_error *
9836 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9837 struct got_repository *repo)
9839 const struct got_error *err;
9840 char *id_str;
9842 err = got_object_id_str(&id_str, id);
9843 if (err)
9844 return err;
9846 err = got_ref_delete(ref, repo);
9847 if (err)
9848 goto done;
9850 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9851 done:
9852 free(id_str);
9853 return err;
9856 static const struct got_error *
9857 print_backup_ref(const char *branch_name, const char *new_id_str,
9858 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9859 struct got_reflist_object_id_map *refs_idmap,
9860 struct got_repository *repo)
9862 const struct got_error *err = NULL;
9863 struct got_reflist_head *refs;
9864 char *refs_str = NULL;
9865 struct got_object_id *new_commit_id = NULL;
9866 struct got_commit_object *new_commit = NULL;
9867 char *new_commit_brief_str = NULL;
9868 struct got_object_id *yca_id = NULL;
9869 struct got_commit_object *yca_commit = NULL;
9870 char *yca_id_str = NULL, *yca_brief_str = NULL;
9871 char *custom_refs_str;
9873 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9874 return got_error_from_errno("asprintf");
9876 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9877 0, 0, refs_idmap, custom_refs_str);
9878 if (err)
9879 goto done;
9881 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9882 if (err)
9883 goto done;
9885 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9886 if (refs) {
9887 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9888 if (err)
9889 goto done;
9892 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9893 if (err)
9894 goto done;
9896 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9897 if (err)
9898 goto done;
9900 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9901 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9902 if (err)
9903 goto done;
9905 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9906 refs_str ? " (" : "", refs_str ? refs_str : "",
9907 refs_str ? ")" : "", new_commit_brief_str);
9908 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9909 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9910 free(refs_str);
9911 refs_str = NULL;
9913 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9914 if (err)
9915 goto done;
9917 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9918 if (err)
9919 goto done;
9921 err = got_object_id_str(&yca_id_str, yca_id);
9922 if (err)
9923 goto done;
9925 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9926 if (refs) {
9927 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9928 if (err)
9929 goto done;
9931 printf("history forked at %s%s%s%s\n %s\n",
9932 yca_id_str,
9933 refs_str ? " (" : "", refs_str ? refs_str : "",
9934 refs_str ? ")" : "", yca_brief_str);
9936 done:
9937 free(custom_refs_str);
9938 free(new_commit_id);
9939 free(refs_str);
9940 free(yca_id);
9941 free(yca_id_str);
9942 free(yca_brief_str);
9943 if (new_commit)
9944 got_object_commit_close(new_commit);
9945 if (yca_commit)
9946 got_object_commit_close(yca_commit);
9948 return NULL;
9951 static const struct got_error *
9952 process_backup_refs(const char *backup_ref_prefix,
9953 const char *wanted_branch_name,
9954 int delete, struct got_repository *repo)
9956 const struct got_error *err;
9957 struct got_reflist_head refs, backup_refs;
9958 struct got_reflist_entry *re;
9959 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9960 struct got_object_id *old_commit_id = NULL;
9961 char *branch_name = NULL;
9962 struct got_commit_object *old_commit = NULL;
9963 struct got_reflist_object_id_map *refs_idmap = NULL;
9964 int wanted_branch_found = 0;
9966 TAILQ_INIT(&refs);
9967 TAILQ_INIT(&backup_refs);
9969 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9970 if (err)
9971 return err;
9973 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9974 if (err)
9975 goto done;
9977 if (wanted_branch_name) {
9978 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9979 wanted_branch_name += 11;
9982 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9983 got_ref_cmp_by_commit_timestamp_descending, repo);
9984 if (err)
9985 goto done;
9987 TAILQ_FOREACH(re, &backup_refs, entry) {
9988 const char *refname = got_ref_get_name(re->ref);
9989 char *slash;
9991 err = check_cancelled(NULL);
9992 if (err)
9993 break;
9995 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9996 if (err)
9997 break;
9999 err = got_object_open_as_commit(&old_commit, repo,
10000 old_commit_id);
10001 if (err)
10002 break;
10004 if (strncmp(backup_ref_prefix, refname,
10005 backup_ref_prefix_len) == 0)
10006 refname += backup_ref_prefix_len;
10008 while (refname[0] == '/')
10009 refname++;
10011 branch_name = strdup(refname);
10012 if (branch_name == NULL) {
10013 err = got_error_from_errno("strdup");
10014 break;
10016 slash = strrchr(branch_name, '/');
10017 if (slash) {
10018 *slash = '\0';
10019 refname += strlen(branch_name) + 1;
10022 if (wanted_branch_name == NULL ||
10023 strcmp(wanted_branch_name, branch_name) == 0) {
10024 wanted_branch_found = 1;
10025 if (delete) {
10026 err = delete_backup_ref(re->ref,
10027 old_commit_id, repo);
10028 } else {
10029 err = print_backup_ref(branch_name, refname,
10030 old_commit_id, old_commit, refs_idmap,
10031 repo);
10033 if (err)
10034 break;
10037 free(old_commit_id);
10038 old_commit_id = NULL;
10039 free(branch_name);
10040 branch_name = NULL;
10041 got_object_commit_close(old_commit);
10042 old_commit = NULL;
10045 if (wanted_branch_name && !wanted_branch_found) {
10046 err = got_error_fmt(GOT_ERR_NOT_REF,
10047 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10049 done:
10050 if (refs_idmap)
10051 got_reflist_object_id_map_free(refs_idmap);
10052 got_ref_list_free(&refs);
10053 got_ref_list_free(&backup_refs);
10054 free(old_commit_id);
10055 free(branch_name);
10056 if (old_commit)
10057 got_object_commit_close(old_commit);
10058 return err;
10061 static const struct got_error *
10062 abort_progress(void *arg, unsigned char status, const char *path)
10065 * Unversioned files should not clutter progress output when
10066 * an operation is aborted.
10068 if (status == GOT_STATUS_UNVERSIONED)
10069 return NULL;
10071 return update_progress(arg, status, path);
10074 static const struct got_error *
10075 cmd_rebase(int argc, char *argv[])
10077 const struct got_error *error = NULL;
10078 struct got_worktree *worktree = NULL;
10079 struct got_repository *repo = NULL;
10080 struct got_fileindex *fileindex = NULL;
10081 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10082 struct got_reference *branch = NULL;
10083 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10084 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10085 struct got_object_id *resume_commit_id = NULL;
10086 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10087 struct got_commit_object *commit = NULL;
10088 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10089 int histedit_in_progress = 0, merge_in_progress = 0;
10090 int create_backup = 1, list_backups = 0, delete_backups = 0;
10091 struct got_object_id_queue commits;
10092 struct got_pathlist_head merged_paths;
10093 const struct got_object_id_queue *parent_ids;
10094 struct got_object_qid *qid, *pid;
10095 struct got_update_progress_arg upa;
10096 int *pack_fds = NULL;
10098 STAILQ_INIT(&commits);
10099 TAILQ_INIT(&merged_paths);
10100 memset(&upa, 0, sizeof(upa));
10102 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10103 switch (ch) {
10104 case 'a':
10105 abort_rebase = 1;
10106 break;
10107 case 'c':
10108 continue_rebase = 1;
10109 break;
10110 case 'l':
10111 list_backups = 1;
10112 break;
10113 case 'X':
10114 delete_backups = 1;
10115 break;
10116 default:
10117 usage_rebase();
10118 /* NOTREACHED */
10122 argc -= optind;
10123 argv += optind;
10125 #ifndef PROFILE
10126 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10127 "unveil", NULL) == -1)
10128 err(1, "pledge");
10129 #endif
10130 if (list_backups) {
10131 if (abort_rebase)
10132 option_conflict('l', 'a');
10133 if (continue_rebase)
10134 option_conflict('l', 'c');
10135 if (delete_backups)
10136 option_conflict('l', 'X');
10137 if (argc != 0 && argc != 1)
10138 usage_rebase();
10139 } else if (delete_backups) {
10140 if (abort_rebase)
10141 option_conflict('X', 'a');
10142 if (continue_rebase)
10143 option_conflict('X', 'c');
10144 if (list_backups)
10145 option_conflict('l', 'X');
10146 if (argc != 0 && argc != 1)
10147 usage_rebase();
10148 } else {
10149 if (abort_rebase && continue_rebase)
10150 usage_rebase();
10151 else if (abort_rebase || continue_rebase) {
10152 if (argc != 0)
10153 usage_rebase();
10154 } else if (argc != 1)
10155 usage_rebase();
10158 cwd = getcwd(NULL, 0);
10159 if (cwd == NULL) {
10160 error = got_error_from_errno("getcwd");
10161 goto done;
10164 error = got_repo_pack_fds_open(&pack_fds);
10165 if (error != NULL)
10166 goto done;
10168 error = got_worktree_open(&worktree, cwd);
10169 if (error) {
10170 if (list_backups || delete_backups) {
10171 if (error->code != GOT_ERR_NOT_WORKTREE)
10172 goto done;
10173 } else {
10174 if (error->code == GOT_ERR_NOT_WORKTREE)
10175 error = wrap_not_worktree_error(error,
10176 "rebase", cwd);
10177 goto done;
10181 error = get_gitconfig_path(&gitconfig_path);
10182 if (error)
10183 goto done;
10184 error = got_repo_open(&repo,
10185 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10186 gitconfig_path, pack_fds);
10187 if (error != NULL)
10188 goto done;
10190 error = get_author(&committer, repo, worktree);
10191 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
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_backups || delete_backups) {
10200 error = process_backup_refs(
10201 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10202 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10203 goto done; /* nothing else to do */
10206 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10207 worktree);
10208 if (error)
10209 goto done;
10210 if (histedit_in_progress) {
10211 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10212 goto done;
10215 error = got_worktree_merge_in_progress(&merge_in_progress,
10216 worktree, repo);
10217 if (error)
10218 goto done;
10219 if (merge_in_progress) {
10220 error = got_error(GOT_ERR_MERGE_BUSY);
10221 goto done;
10224 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10225 if (error)
10226 goto done;
10228 if (abort_rebase) {
10229 if (!rebase_in_progress) {
10230 error = got_error(GOT_ERR_NOT_REBASING);
10231 goto done;
10233 error = got_worktree_rebase_continue(&resume_commit_id,
10234 &new_base_branch, &tmp_branch, &branch, &fileindex,
10235 worktree, repo);
10236 if (error)
10237 goto done;
10238 printf("Switching work tree to %s\n",
10239 got_ref_get_symref_target(new_base_branch));
10240 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10241 new_base_branch, abort_progress, &upa);
10242 if (error)
10243 goto done;
10244 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10245 print_merge_progress_stats(&upa);
10246 goto done; /* nothing else to do */
10249 if (continue_rebase) {
10250 if (!rebase_in_progress) {
10251 error = got_error(GOT_ERR_NOT_REBASING);
10252 goto done;
10254 error = got_worktree_rebase_continue(&resume_commit_id,
10255 &new_base_branch, &tmp_branch, &branch, &fileindex,
10256 worktree, repo);
10257 if (error)
10258 goto done;
10260 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10261 committer, resume_commit_id, repo);
10262 if (error)
10263 goto done;
10265 yca_id = got_object_id_dup(resume_commit_id);
10266 if (yca_id == NULL) {
10267 error = got_error_from_errno("got_object_id_dup");
10268 goto done;
10270 } else {
10271 error = got_ref_open(&branch, repo, argv[0], 0);
10272 if (error != NULL)
10273 goto done;
10274 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10275 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10276 "will not rebase a branch which lives outside "
10277 "the \"refs/heads/\" reference namespace");
10278 goto done;
10282 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10283 if (error)
10284 goto done;
10286 if (!continue_rebase) {
10287 struct got_object_id *base_commit_id;
10289 base_commit_id = got_worktree_get_base_commit_id(worktree);
10290 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10291 base_commit_id, branch_head_commit_id, 1, repo,
10292 check_cancelled, NULL);
10293 if (error)
10294 goto done;
10295 if (yca_id == NULL) {
10296 error = got_error_msg(GOT_ERR_ANCESTRY,
10297 "specified branch shares no common ancestry "
10298 "with work tree's branch");
10299 goto done;
10302 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10303 if (error) {
10304 if (error->code != GOT_ERR_ANCESTRY)
10305 goto done;
10306 error = NULL;
10307 } else {
10308 struct got_pathlist_head paths;
10309 printf("%s is already based on %s\n",
10310 got_ref_get_name(branch),
10311 got_worktree_get_head_ref_name(worktree));
10312 error = switch_head_ref(branch, branch_head_commit_id,
10313 worktree, repo);
10314 if (error)
10315 goto done;
10316 error = got_worktree_set_base_commit_id(worktree, repo,
10317 branch_head_commit_id);
10318 if (error)
10319 goto done;
10320 TAILQ_INIT(&paths);
10321 error = got_pathlist_append(&paths, "", NULL);
10322 if (error)
10323 goto done;
10324 error = got_worktree_checkout_files(worktree,
10325 &paths, repo, update_progress, &upa,
10326 check_cancelled, NULL);
10327 got_pathlist_free(&paths);
10328 if (error)
10329 goto done;
10330 if (upa.did_something) {
10331 char *id_str;
10332 error = got_object_id_str(&id_str,
10333 branch_head_commit_id);
10334 if (error)
10335 goto done;
10336 printf("Updated to %s: %s\n",
10337 got_worktree_get_head_ref_name(worktree),
10338 id_str);
10339 free(id_str);
10340 } else
10341 printf("Already up-to-date\n");
10342 print_update_progress_stats(&upa);
10343 goto done;
10347 commit_id = branch_head_commit_id;
10348 error = got_object_open_as_commit(&commit, repo, commit_id);
10349 if (error)
10350 goto done;
10352 parent_ids = got_object_commit_get_parent_ids(commit);
10353 pid = STAILQ_FIRST(parent_ids);
10354 if (pid == NULL) {
10355 error = got_error(GOT_ERR_EMPTY_REBASE);
10356 goto done;
10358 error = collect_commits(&commits, commit_id, &pid->id,
10359 yca_id, got_worktree_get_path_prefix(worktree),
10360 GOT_ERR_REBASE_PATH, repo);
10361 got_object_commit_close(commit);
10362 commit = NULL;
10363 if (error)
10364 goto done;
10366 if (!continue_rebase) {
10367 error = got_worktree_rebase_prepare(&new_base_branch,
10368 &tmp_branch, &fileindex, worktree, branch, repo);
10369 if (error)
10370 goto done;
10373 if (STAILQ_EMPTY(&commits)) {
10374 if (continue_rebase) {
10375 error = rebase_complete(worktree, fileindex,
10376 branch, new_base_branch, tmp_branch, repo,
10377 create_backup);
10378 goto done;
10379 } else {
10380 /* Fast-forward the reference of the branch. */
10381 struct got_object_id *new_head_commit_id;
10382 char *id_str;
10383 error = got_ref_resolve(&new_head_commit_id, repo,
10384 new_base_branch);
10385 if (error)
10386 goto done;
10387 error = got_object_id_str(&id_str, new_head_commit_id);
10388 if (error)
10389 goto done;
10390 printf("Forwarding %s to commit %s\n",
10391 got_ref_get_name(branch), id_str);
10392 free(id_str);
10393 error = got_ref_change_ref(branch,
10394 new_head_commit_id);
10395 if (error)
10396 goto done;
10397 /* No backup needed since objects did not change. */
10398 create_backup = 0;
10402 pid = NULL;
10403 STAILQ_FOREACH(qid, &commits, entry) {
10405 commit_id = &qid->id;
10406 parent_id = pid ? &pid->id : yca_id;
10407 pid = qid;
10409 memset(&upa, 0, sizeof(upa));
10410 error = got_worktree_rebase_merge_files(&merged_paths,
10411 worktree, fileindex, parent_id, commit_id, repo,
10412 update_progress, &upa, check_cancelled, NULL);
10413 if (error)
10414 goto done;
10416 print_merge_progress_stats(&upa);
10417 if (upa.conflicts > 0 || upa.missing > 0 ||
10418 upa.not_deleted > 0 || upa.unversioned > 0) {
10419 if (upa.conflicts > 0) {
10420 error = show_rebase_merge_conflict(&qid->id,
10421 repo);
10422 if (error)
10423 goto done;
10425 got_worktree_rebase_pathlist_free(&merged_paths);
10426 break;
10429 error = rebase_commit(&merged_paths, worktree, fileindex,
10430 tmp_branch, committer, commit_id, repo);
10431 got_worktree_rebase_pathlist_free(&merged_paths);
10432 if (error)
10433 goto done;
10436 if (upa.conflicts > 0 || upa.missing > 0 ||
10437 upa.not_deleted > 0 || upa.unversioned > 0) {
10438 error = got_worktree_rebase_postpone(worktree, fileindex);
10439 if (error)
10440 goto done;
10441 if (upa.conflicts > 0 && upa.missing == 0 &&
10442 upa.not_deleted == 0 && upa.unversioned == 0) {
10443 error = got_error_msg(GOT_ERR_CONFLICTS,
10444 "conflicts must be resolved before rebasing "
10445 "can continue");
10446 } else if (upa.conflicts > 0) {
10447 error = got_error_msg(GOT_ERR_CONFLICTS,
10448 "conflicts must be resolved before rebasing "
10449 "can continue; changes destined for some "
10450 "files were not yet merged and should be "
10451 "merged manually if required before the "
10452 "rebase operation is continued");
10453 } else {
10454 error = got_error_msg(GOT_ERR_CONFLICTS,
10455 "changes destined for some files were not "
10456 "yet merged and should be merged manually "
10457 "if required before the rebase operation "
10458 "is continued");
10460 } else
10461 error = rebase_complete(worktree, fileindex, branch,
10462 new_base_branch, tmp_branch, repo, create_backup);
10463 done:
10464 free(cwd);
10465 free(committer);
10466 free(gitconfig_path);
10467 got_object_id_queue_free(&commits);
10468 free(branch_head_commit_id);
10469 free(resume_commit_id);
10470 free(yca_id);
10471 if (commit)
10472 got_object_commit_close(commit);
10473 if (branch)
10474 got_ref_close(branch);
10475 if (new_base_branch)
10476 got_ref_close(new_base_branch);
10477 if (tmp_branch)
10478 got_ref_close(tmp_branch);
10479 if (worktree)
10480 got_worktree_close(worktree);
10481 if (repo) {
10482 const struct got_error *close_err = got_repo_close(repo);
10483 if (error == NULL)
10484 error = close_err;
10486 if (pack_fds) {
10487 const struct got_error *pack_err =
10488 got_repo_pack_fds_close(pack_fds);
10489 if (error == NULL)
10490 error = pack_err;
10492 return error;
10495 __dead static void
10496 usage_histedit(void)
10498 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10499 "[branch]\n", getprogname());
10500 exit(1);
10503 #define GOT_HISTEDIT_PICK 'p'
10504 #define GOT_HISTEDIT_EDIT 'e'
10505 #define GOT_HISTEDIT_FOLD 'f'
10506 #define GOT_HISTEDIT_DROP 'd'
10507 #define GOT_HISTEDIT_MESG 'm'
10509 static const struct got_histedit_cmd {
10510 unsigned char code;
10511 const char *name;
10512 const char *desc;
10513 } got_histedit_cmds[] = {
10514 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10515 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10516 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10517 "be used" },
10518 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10519 { GOT_HISTEDIT_MESG, "mesg",
10520 "single-line log message for commit above (open editor if empty)" },
10523 struct got_histedit_list_entry {
10524 TAILQ_ENTRY(got_histedit_list_entry) entry;
10525 struct got_object_id *commit_id;
10526 const struct got_histedit_cmd *cmd;
10527 char *logmsg;
10529 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10531 static const struct got_error *
10532 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10533 FILE *f, struct got_repository *repo)
10535 const struct got_error *err = NULL;
10536 char *logmsg = NULL, *id_str = NULL;
10537 struct got_commit_object *commit = NULL;
10538 int n;
10540 err = got_object_open_as_commit(&commit, repo, commit_id);
10541 if (err)
10542 goto done;
10544 err = get_short_logmsg(&logmsg, 34, commit);
10545 if (err)
10546 goto done;
10548 err = got_object_id_str(&id_str, commit_id);
10549 if (err)
10550 goto done;
10552 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10553 if (n < 0)
10554 err = got_ferror(f, GOT_ERR_IO);
10555 done:
10556 if (commit)
10557 got_object_commit_close(commit);
10558 free(id_str);
10559 free(logmsg);
10560 return err;
10563 static const struct got_error *
10564 histedit_write_commit_list(struct got_object_id_queue *commits,
10565 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10566 struct got_repository *repo)
10568 const struct got_error *err = NULL;
10569 struct got_object_qid *qid;
10570 const char *histedit_cmd = NULL;
10572 if (STAILQ_EMPTY(commits))
10573 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10575 STAILQ_FOREACH(qid, commits, entry) {
10576 histedit_cmd = got_histedit_cmds[0].name;
10577 if (edit_only)
10578 histedit_cmd = "edit";
10579 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10580 histedit_cmd = "fold";
10581 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10582 if (err)
10583 break;
10584 if (edit_logmsg_only) {
10585 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10586 if (n < 0) {
10587 err = got_ferror(f, GOT_ERR_IO);
10588 break;
10593 return err;
10596 static const struct got_error *
10597 write_cmd_list(FILE *f, const char *branch_name,
10598 struct got_object_id_queue *commits)
10600 const struct got_error *err = NULL;
10601 size_t i;
10602 int n;
10603 char *id_str;
10604 struct got_object_qid *qid;
10606 qid = STAILQ_FIRST(commits);
10607 err = got_object_id_str(&id_str, &qid->id);
10608 if (err)
10609 return err;
10611 n = fprintf(f,
10612 "# Editing the history of branch '%s' starting at\n"
10613 "# commit %s\n"
10614 "# Commits will be processed in order from top to "
10615 "bottom of this file.\n", branch_name, id_str);
10616 if (n < 0) {
10617 err = got_ferror(f, GOT_ERR_IO);
10618 goto done;
10621 n = fprintf(f, "# Available histedit commands:\n");
10622 if (n < 0) {
10623 err = got_ferror(f, GOT_ERR_IO);
10624 goto done;
10627 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10628 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10629 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10630 cmd->desc);
10631 if (n < 0) {
10632 err = got_ferror(f, GOT_ERR_IO);
10633 break;
10636 done:
10637 free(id_str);
10638 return err;
10641 static const struct got_error *
10642 histedit_syntax_error(int lineno)
10644 static char msg[42];
10645 int ret;
10647 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10648 lineno);
10649 if (ret < 0 || (size_t)ret >= sizeof(msg))
10650 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10652 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10655 static const struct got_error *
10656 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10657 char *logmsg, struct got_repository *repo)
10659 const struct got_error *err;
10660 struct got_commit_object *folded_commit = NULL;
10661 char *id_str, *folded_logmsg = NULL;
10663 err = got_object_id_str(&id_str, hle->commit_id);
10664 if (err)
10665 return err;
10667 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10668 if (err)
10669 goto done;
10671 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10672 if (err)
10673 goto done;
10674 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10675 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10676 folded_logmsg) == -1) {
10677 err = got_error_from_errno("asprintf");
10679 done:
10680 if (folded_commit)
10681 got_object_commit_close(folded_commit);
10682 free(id_str);
10683 free(folded_logmsg);
10684 return err;
10687 static struct got_histedit_list_entry *
10688 get_folded_commits(struct got_histedit_list_entry *hle)
10690 struct got_histedit_list_entry *prev, *folded = NULL;
10692 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10693 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10694 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10695 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10696 folded = prev;
10697 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10700 return folded;
10703 static const struct got_error *
10704 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10705 struct got_repository *repo)
10707 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10708 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10709 const struct got_error *err = NULL;
10710 struct got_commit_object *commit = NULL;
10711 int logmsg_len;
10712 int fd;
10713 struct got_histedit_list_entry *folded = NULL;
10715 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10716 if (err)
10717 return err;
10719 folded = get_folded_commits(hle);
10720 if (folded) {
10721 while (folded != hle) {
10722 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10723 folded = TAILQ_NEXT(folded, entry);
10724 continue;
10726 err = append_folded_commit_msg(&new_msg, folded,
10727 logmsg, repo);
10728 if (err)
10729 goto done;
10730 free(logmsg);
10731 logmsg = new_msg;
10732 folded = TAILQ_NEXT(folded, entry);
10736 err = got_object_id_str(&id_str, hle->commit_id);
10737 if (err)
10738 goto done;
10739 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10740 if (err)
10741 goto done;
10742 logmsg_len = asprintf(&new_msg,
10743 "%s\n# original log message of commit %s: %s",
10744 logmsg ? logmsg : "", id_str, orig_logmsg);
10745 if (logmsg_len == -1) {
10746 err = got_error_from_errno("asprintf");
10747 goto done;
10749 free(logmsg);
10750 logmsg = new_msg;
10752 err = got_object_id_str(&id_str, hle->commit_id);
10753 if (err)
10754 goto done;
10756 err = got_opentemp_named_fd(&logmsg_path, &fd,
10757 GOT_TMPDIR_STR "/got-logmsg", "");
10758 if (err)
10759 goto done;
10761 write(fd, logmsg, logmsg_len);
10762 close(fd);
10764 err = get_editor(&editor);
10765 if (err)
10766 goto done;
10768 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10769 logmsg_len, 0);
10770 if (err) {
10771 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10772 goto done;
10773 err = NULL;
10774 hle->logmsg = strdup(new_msg);
10775 if (hle->logmsg == NULL)
10776 err = got_error_from_errno("strdup");
10778 done:
10779 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10780 err = got_error_from_errno2("unlink", logmsg_path);
10781 free(logmsg_path);
10782 free(logmsg);
10783 free(orig_logmsg);
10784 free(editor);
10785 if (commit)
10786 got_object_commit_close(commit);
10787 return err;
10790 static const struct got_error *
10791 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10792 FILE *f, struct got_repository *repo)
10794 const struct got_error *err = NULL;
10795 char *line = NULL, *p, *end;
10796 size_t i, size;
10797 ssize_t len;
10798 int lineno = 0, lastcmd = -1;
10799 const struct got_histedit_cmd *cmd;
10800 struct got_object_id *commit_id = NULL;
10801 struct got_histedit_list_entry *hle = NULL;
10803 for (;;) {
10804 len = getline(&line, &size, f);
10805 if (len == -1) {
10806 const struct got_error *getline_err;
10807 if (feof(f))
10808 break;
10809 getline_err = got_error_from_errno("getline");
10810 err = got_ferror(f, getline_err->code);
10811 break;
10813 lineno++;
10814 p = line;
10815 while (isspace((unsigned char)p[0]))
10816 p++;
10817 if (p[0] == '#' || p[0] == '\0') {
10818 free(line);
10819 line = NULL;
10820 continue;
10822 cmd = NULL;
10823 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10824 cmd = &got_histedit_cmds[i];
10825 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10826 isspace((unsigned char)p[strlen(cmd->name)])) {
10827 p += strlen(cmd->name);
10828 break;
10830 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10831 p++;
10832 break;
10835 if (i == nitems(got_histedit_cmds)) {
10836 err = histedit_syntax_error(lineno);
10837 break;
10839 while (isspace((unsigned char)p[0]))
10840 p++;
10841 if (cmd->code == GOT_HISTEDIT_MESG) {
10842 if (lastcmd != GOT_HISTEDIT_PICK &&
10843 lastcmd != GOT_HISTEDIT_EDIT) {
10844 err = got_error(GOT_ERR_HISTEDIT_CMD);
10845 break;
10847 if (p[0] == '\0') {
10848 err = histedit_edit_logmsg(hle, repo);
10849 if (err)
10850 break;
10851 } else {
10852 hle->logmsg = strdup(p);
10853 if (hle->logmsg == NULL) {
10854 err = got_error_from_errno("strdup");
10855 break;
10858 free(line);
10859 line = NULL;
10860 lastcmd = cmd->code;
10861 continue;
10862 } else {
10863 end = p;
10864 while (end[0] && !isspace((unsigned char)end[0]))
10865 end++;
10866 *end = '\0';
10868 err = got_object_resolve_id_str(&commit_id, repo, p);
10869 if (err) {
10870 /* override error code */
10871 err = histedit_syntax_error(lineno);
10872 break;
10875 hle = malloc(sizeof(*hle));
10876 if (hle == NULL) {
10877 err = got_error_from_errno("malloc");
10878 break;
10880 hle->cmd = cmd;
10881 hle->commit_id = commit_id;
10882 hle->logmsg = NULL;
10883 commit_id = NULL;
10884 free(line);
10885 line = NULL;
10886 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10887 lastcmd = cmd->code;
10890 free(line);
10891 free(commit_id);
10892 return err;
10895 static const struct got_error *
10896 histedit_check_script(struct got_histedit_list *histedit_cmds,
10897 struct got_object_id_queue *commits, struct got_repository *repo)
10899 const struct got_error *err = NULL;
10900 struct got_object_qid *qid;
10901 struct got_histedit_list_entry *hle;
10902 static char msg[92];
10903 char *id_str;
10905 if (TAILQ_EMPTY(histedit_cmds))
10906 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10907 "histedit script contains no commands");
10908 if (STAILQ_EMPTY(commits))
10909 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10911 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10912 struct got_histedit_list_entry *hle2;
10913 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10914 if (hle == hle2)
10915 continue;
10916 if (got_object_id_cmp(hle->commit_id,
10917 hle2->commit_id) != 0)
10918 continue;
10919 err = got_object_id_str(&id_str, hle->commit_id);
10920 if (err)
10921 return err;
10922 snprintf(msg, sizeof(msg), "commit %s is listed "
10923 "more than once in histedit script", id_str);
10924 free(id_str);
10925 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10929 STAILQ_FOREACH(qid, commits, entry) {
10930 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10931 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10932 break;
10934 if (hle == NULL) {
10935 err = got_object_id_str(&id_str, &qid->id);
10936 if (err)
10937 return err;
10938 snprintf(msg, sizeof(msg),
10939 "commit %s missing from histedit script", id_str);
10940 free(id_str);
10941 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10945 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10946 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10947 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10948 "last commit in histedit script cannot be folded");
10950 return NULL;
10953 static const struct got_error *
10954 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10955 const char *path, struct got_object_id_queue *commits,
10956 struct got_repository *repo)
10958 const struct got_error *err = NULL;
10959 char *editor;
10960 FILE *f = NULL;
10962 err = get_editor(&editor);
10963 if (err)
10964 return err;
10966 if (spawn_editor(editor, path) == -1) {
10967 err = got_error_from_errno("failed spawning editor");
10968 goto done;
10971 f = fopen(path, "re");
10972 if (f == NULL) {
10973 err = got_error_from_errno("fopen");
10974 goto done;
10976 err = histedit_parse_list(histedit_cmds, f, repo);
10977 if (err)
10978 goto done;
10980 err = histedit_check_script(histedit_cmds, commits, repo);
10981 done:
10982 if (f && fclose(f) == EOF && err == NULL)
10983 err = got_error_from_errno("fclose");
10984 free(editor);
10985 return err;
10988 static const struct got_error *
10989 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10990 struct got_object_id_queue *, const char *, const char *,
10991 struct got_repository *);
10993 static const struct got_error *
10994 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10995 struct got_object_id_queue *commits, const char *branch_name,
10996 int edit_logmsg_only, int fold_only, int edit_only,
10997 struct got_repository *repo)
10999 const struct got_error *err;
11000 FILE *f = NULL;
11001 char *path = NULL;
11003 err = got_opentemp_named(&path, &f, "got-histedit", "");
11004 if (err)
11005 return err;
11007 err = write_cmd_list(f, branch_name, commits);
11008 if (err)
11009 goto done;
11011 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11012 fold_only, edit_only, repo);
11013 if (err)
11014 goto done;
11016 if (edit_logmsg_only || fold_only || edit_only) {
11017 rewind(f);
11018 err = histedit_parse_list(histedit_cmds, f, repo);
11019 } else {
11020 if (fclose(f) == EOF) {
11021 err = got_error_from_errno("fclose");
11022 goto done;
11024 f = NULL;
11025 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11026 if (err) {
11027 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11028 err->code != GOT_ERR_HISTEDIT_CMD)
11029 goto done;
11030 err = histedit_edit_list_retry(histedit_cmds, err,
11031 commits, path, branch_name, repo);
11034 done:
11035 if (f && fclose(f) == EOF && err == NULL)
11036 err = got_error_from_errno("fclose");
11037 if (path && unlink(path) != 0 && err == NULL)
11038 err = got_error_from_errno2("unlink", path);
11039 free(path);
11040 return err;
11043 static const struct got_error *
11044 histedit_save_list(struct got_histedit_list *histedit_cmds,
11045 struct got_worktree *worktree, struct got_repository *repo)
11047 const struct got_error *err = NULL;
11048 char *path = NULL;
11049 FILE *f = NULL;
11050 struct got_histedit_list_entry *hle;
11051 struct got_commit_object *commit = NULL;
11053 err = got_worktree_get_histedit_script_path(&path, worktree);
11054 if (err)
11055 return err;
11057 f = fopen(path, "we");
11058 if (f == NULL) {
11059 err = got_error_from_errno2("fopen", path);
11060 goto done;
11062 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11063 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11064 repo);
11065 if (err)
11066 break;
11068 if (hle->logmsg) {
11069 int n = fprintf(f, "%c %s\n",
11070 GOT_HISTEDIT_MESG, hle->logmsg);
11071 if (n < 0) {
11072 err = got_ferror(f, GOT_ERR_IO);
11073 break;
11077 done:
11078 if (f && fclose(f) == EOF && err == NULL)
11079 err = got_error_from_errno("fclose");
11080 free(path);
11081 if (commit)
11082 got_object_commit_close(commit);
11083 return err;
11086 static void
11087 histedit_free_list(struct got_histedit_list *histedit_cmds)
11089 struct got_histedit_list_entry *hle;
11091 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11092 TAILQ_REMOVE(histedit_cmds, hle, entry);
11093 free(hle);
11097 static const struct got_error *
11098 histedit_load_list(struct got_histedit_list *histedit_cmds,
11099 const char *path, struct got_repository *repo)
11101 const struct got_error *err = NULL;
11102 FILE *f = NULL;
11104 f = fopen(path, "re");
11105 if (f == NULL) {
11106 err = got_error_from_errno2("fopen", path);
11107 goto done;
11110 err = histedit_parse_list(histedit_cmds, f, repo);
11111 done:
11112 if (f && fclose(f) == EOF && err == NULL)
11113 err = got_error_from_errno("fclose");
11114 return err;
11117 static const struct got_error *
11118 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11119 const struct got_error *edit_err, struct got_object_id_queue *commits,
11120 const char *path, const char *branch_name, struct got_repository *repo)
11122 const struct got_error *err = NULL, *prev_err = edit_err;
11123 int resp = ' ';
11125 while (resp != 'c' && resp != 'r' && resp != 'a') {
11126 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11127 "or (a)bort: ", getprogname(), prev_err->msg);
11128 resp = getchar();
11129 if (resp == '\n')
11130 resp = getchar();
11131 if (resp == 'c') {
11132 histedit_free_list(histedit_cmds);
11133 err = histedit_run_editor(histedit_cmds, path, commits,
11134 repo);
11135 if (err) {
11136 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11137 err->code != GOT_ERR_HISTEDIT_CMD)
11138 break;
11139 prev_err = err;
11140 resp = ' ';
11141 continue;
11143 break;
11144 } else if (resp == 'r') {
11145 histedit_free_list(histedit_cmds);
11146 err = histedit_edit_script(histedit_cmds,
11147 commits, branch_name, 0, 0, 0, repo);
11148 if (err) {
11149 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11150 err->code != GOT_ERR_HISTEDIT_CMD)
11151 break;
11152 prev_err = err;
11153 resp = ' ';
11154 continue;
11156 break;
11157 } else if (resp == 'a') {
11158 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11159 break;
11160 } else
11161 printf("invalid response '%c'\n", resp);
11164 return err;
11167 static const struct got_error *
11168 histedit_complete(struct got_worktree *worktree,
11169 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11170 struct got_reference *branch, struct got_repository *repo)
11172 printf("Switching work tree to %s\n",
11173 got_ref_get_symref_target(branch));
11174 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11175 branch, repo);
11178 static const struct got_error *
11179 show_histedit_progress(struct got_commit_object *commit,
11180 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11182 const struct got_error *err;
11183 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11185 err = got_object_id_str(&old_id_str, hle->commit_id);
11186 if (err)
11187 goto done;
11189 if (new_id) {
11190 err = got_object_id_str(&new_id_str, new_id);
11191 if (err)
11192 goto done;
11195 old_id_str[12] = '\0';
11196 if (new_id_str)
11197 new_id_str[12] = '\0';
11199 if (hle->logmsg) {
11200 logmsg = strdup(hle->logmsg);
11201 if (logmsg == NULL) {
11202 err = got_error_from_errno("strdup");
11203 goto done;
11205 trim_logmsg(logmsg, 42);
11206 } else {
11207 err = get_short_logmsg(&logmsg, 42, commit);
11208 if (err)
11209 goto done;
11212 switch (hle->cmd->code) {
11213 case GOT_HISTEDIT_PICK:
11214 case GOT_HISTEDIT_EDIT:
11215 printf("%s -> %s: %s\n", old_id_str,
11216 new_id_str ? new_id_str : "no-op change", logmsg);
11217 break;
11218 case GOT_HISTEDIT_DROP:
11219 case GOT_HISTEDIT_FOLD:
11220 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11221 logmsg);
11222 break;
11223 default:
11224 break;
11226 done:
11227 free(old_id_str);
11228 free(new_id_str);
11229 return err;
11232 static const struct got_error *
11233 histedit_commit(struct got_pathlist_head *merged_paths,
11234 struct got_worktree *worktree, struct got_fileindex *fileindex,
11235 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11236 const char *committer, struct got_repository *repo)
11238 const struct got_error *err;
11239 struct got_commit_object *commit;
11240 struct got_object_id *new_commit_id;
11242 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11243 && hle->logmsg == NULL) {
11244 err = histedit_edit_logmsg(hle, repo);
11245 if (err)
11246 return err;
11249 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11250 if (err)
11251 return err;
11253 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11254 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11255 hle->logmsg, repo);
11256 if (err) {
11257 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11258 goto done;
11259 err = show_histedit_progress(commit, hle, NULL);
11260 } else {
11261 err = show_histedit_progress(commit, hle, new_commit_id);
11262 free(new_commit_id);
11264 done:
11265 got_object_commit_close(commit);
11266 return err;
11269 static const struct got_error *
11270 histedit_skip_commit(struct got_histedit_list_entry *hle,
11271 struct got_worktree *worktree, struct got_repository *repo)
11273 const struct got_error *error;
11274 struct got_commit_object *commit;
11276 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11277 repo);
11278 if (error)
11279 return error;
11281 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11282 if (error)
11283 return error;
11285 error = show_histedit_progress(commit, hle, NULL);
11286 got_object_commit_close(commit);
11287 return error;
11290 static const struct got_error *
11291 check_local_changes(void *arg, unsigned char status,
11292 unsigned char staged_status, const char *path,
11293 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11294 struct got_object_id *commit_id, int dirfd, const char *de_name)
11296 int *have_local_changes = arg;
11298 switch (status) {
11299 case GOT_STATUS_ADD:
11300 case GOT_STATUS_DELETE:
11301 case GOT_STATUS_MODIFY:
11302 case GOT_STATUS_CONFLICT:
11303 *have_local_changes = 1;
11304 return got_error(GOT_ERR_CANCELLED);
11305 default:
11306 break;
11309 switch (staged_status) {
11310 case GOT_STATUS_ADD:
11311 case GOT_STATUS_DELETE:
11312 case GOT_STATUS_MODIFY:
11313 *have_local_changes = 1;
11314 return got_error(GOT_ERR_CANCELLED);
11315 default:
11316 break;
11319 return NULL;
11322 static const struct got_error *
11323 cmd_histedit(int argc, char *argv[])
11325 const struct got_error *error = NULL;
11326 struct got_worktree *worktree = NULL;
11327 struct got_fileindex *fileindex = NULL;
11328 struct got_repository *repo = NULL;
11329 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11330 struct got_reference *branch = NULL;
11331 struct got_reference *tmp_branch = NULL;
11332 struct got_object_id *resume_commit_id = NULL;
11333 struct got_object_id *base_commit_id = NULL;
11334 struct got_object_id *head_commit_id = NULL;
11335 struct got_commit_object *commit = NULL;
11336 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11337 struct got_update_progress_arg upa;
11338 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11339 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11340 int list_backups = 0, delete_backups = 0;
11341 const char *edit_script_path = NULL;
11342 struct got_object_id_queue commits;
11343 struct got_pathlist_head merged_paths;
11344 const struct got_object_id_queue *parent_ids;
11345 struct got_object_qid *pid;
11346 struct got_histedit_list histedit_cmds;
11347 struct got_histedit_list_entry *hle;
11348 int *pack_fds = NULL;
11350 STAILQ_INIT(&commits);
11351 TAILQ_INIT(&histedit_cmds);
11352 TAILQ_INIT(&merged_paths);
11353 memset(&upa, 0, sizeof(upa));
11355 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11356 switch (ch) {
11357 case 'a':
11358 abort_edit = 1;
11359 break;
11360 case 'c':
11361 continue_edit = 1;
11362 break;
11363 case 'e':
11364 edit_only = 1;
11365 break;
11366 case 'F':
11367 edit_script_path = optarg;
11368 break;
11369 case 'f':
11370 fold_only = 1;
11371 break;
11372 case 'l':
11373 list_backups = 1;
11374 break;
11375 case 'm':
11376 edit_logmsg_only = 1;
11377 break;
11378 case 'X':
11379 delete_backups = 1;
11380 break;
11381 default:
11382 usage_histedit();
11383 /* NOTREACHED */
11387 argc -= optind;
11388 argv += optind;
11390 #ifndef PROFILE
11391 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11392 "unveil", NULL) == -1)
11393 err(1, "pledge");
11394 #endif
11395 if (abort_edit && continue_edit)
11396 option_conflict('a', 'c');
11397 if (edit_script_path && edit_logmsg_only)
11398 option_conflict('F', 'm');
11399 if (abort_edit && edit_logmsg_only)
11400 option_conflict('a', 'm');
11401 if (continue_edit && edit_logmsg_only)
11402 option_conflict('c', 'm');
11403 if (abort_edit && fold_only)
11404 option_conflict('a', 'f');
11405 if (continue_edit && fold_only)
11406 option_conflict('c', 'f');
11407 if (fold_only && edit_logmsg_only)
11408 option_conflict('f', 'm');
11409 if (edit_script_path && fold_only)
11410 option_conflict('F', 'f');
11411 if (abort_edit && edit_only)
11412 option_conflict('a', 'e');
11413 if (continue_edit && edit_only)
11414 option_conflict('c', 'e');
11415 if (edit_only && edit_logmsg_only)
11416 option_conflict('e', 'm');
11417 if (edit_script_path && edit_only)
11418 option_conflict('F', 'e');
11419 if (list_backups) {
11420 if (abort_edit)
11421 option_conflict('l', 'a');
11422 if (continue_edit)
11423 option_conflict('l', 'c');
11424 if (edit_script_path)
11425 option_conflict('l', 'F');
11426 if (edit_logmsg_only)
11427 option_conflict('l', 'm');
11428 if (fold_only)
11429 option_conflict('l', 'f');
11430 if (edit_only)
11431 option_conflict('l', 'e');
11432 if (delete_backups)
11433 option_conflict('l', 'X');
11434 if (argc != 0 && argc != 1)
11435 usage_histedit();
11436 } else if (delete_backups) {
11437 if (abort_edit)
11438 option_conflict('X', 'a');
11439 if (continue_edit)
11440 option_conflict('X', 'c');
11441 if (edit_script_path)
11442 option_conflict('X', 'F');
11443 if (edit_logmsg_only)
11444 option_conflict('X', 'm');
11445 if (fold_only)
11446 option_conflict('X', 'f');
11447 if (edit_only)
11448 option_conflict('X', 'e');
11449 if (list_backups)
11450 option_conflict('X', 'l');
11451 if (argc != 0 && argc != 1)
11452 usage_histedit();
11453 } else if (argc != 0)
11454 usage_histedit();
11457 * This command cannot apply unveil(2) in all cases because the
11458 * user may choose to run an editor to edit the histedit script
11459 * and to edit individual commit log messages.
11460 * unveil(2) traverses exec(2); if an editor is used we have to
11461 * apply unveil after edit script and log messages have been written.
11462 * XXX TODO: Make use of unveil(2) where possible.
11465 cwd = getcwd(NULL, 0);
11466 if (cwd == NULL) {
11467 error = got_error_from_errno("getcwd");
11468 goto done;
11471 error = got_repo_pack_fds_open(&pack_fds);
11472 if (error != NULL)
11473 goto done;
11475 error = got_worktree_open(&worktree, cwd);
11476 if (error) {
11477 if (list_backups || delete_backups) {
11478 if (error->code != GOT_ERR_NOT_WORKTREE)
11479 goto done;
11480 } else {
11481 if (error->code == GOT_ERR_NOT_WORKTREE)
11482 error = wrap_not_worktree_error(error,
11483 "histedit", cwd);
11484 goto done;
11488 if (list_backups || delete_backups) {
11489 error = got_repo_open(&repo,
11490 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11491 NULL, pack_fds);
11492 if (error != NULL)
11493 goto done;
11494 error = apply_unveil(got_repo_get_path(repo), 0,
11495 worktree ? got_worktree_get_root_path(worktree) : NULL);
11496 if (error)
11497 goto done;
11498 error = process_backup_refs(
11499 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11500 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11501 goto done; /* nothing else to do */
11504 error = get_gitconfig_path(&gitconfig_path);
11505 if (error)
11506 goto done;
11507 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11508 gitconfig_path, pack_fds);
11509 if (error != NULL)
11510 goto done;
11512 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11513 if (error)
11514 goto done;
11515 if (rebase_in_progress) {
11516 error = got_error(GOT_ERR_REBASING);
11517 goto done;
11520 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11521 repo);
11522 if (error)
11523 goto done;
11524 if (merge_in_progress) {
11525 error = got_error(GOT_ERR_MERGE_BUSY);
11526 goto done;
11529 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11530 if (error)
11531 goto done;
11533 if (edit_in_progress && edit_logmsg_only) {
11534 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11535 "histedit operation is in progress in this "
11536 "work tree and must be continued or aborted "
11537 "before the -m option can be used");
11538 goto done;
11540 if (edit_in_progress && fold_only) {
11541 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11542 "histedit operation is in progress in this "
11543 "work tree and must be continued or aborted "
11544 "before the -f option can be used");
11545 goto done;
11547 if (edit_in_progress && edit_only) {
11548 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11549 "histedit operation is in progress in this "
11550 "work tree and must be continued or aborted "
11551 "before the -e option can be used");
11552 goto done;
11555 if (edit_in_progress && abort_edit) {
11556 error = got_worktree_histedit_continue(&resume_commit_id,
11557 &tmp_branch, &branch, &base_commit_id, &fileindex,
11558 worktree, repo);
11559 if (error)
11560 goto done;
11561 printf("Switching work tree to %s\n",
11562 got_ref_get_symref_target(branch));
11563 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11564 branch, base_commit_id, abort_progress, &upa);
11565 if (error)
11566 goto done;
11567 printf("Histedit of %s aborted\n",
11568 got_ref_get_symref_target(branch));
11569 print_merge_progress_stats(&upa);
11570 goto done; /* nothing else to do */
11571 } else if (abort_edit) {
11572 error = got_error(GOT_ERR_NOT_HISTEDIT);
11573 goto done;
11576 error = get_author(&committer, repo, worktree);
11577 if (error)
11578 goto done;
11580 if (continue_edit) {
11581 char *path;
11583 if (!edit_in_progress) {
11584 error = got_error(GOT_ERR_NOT_HISTEDIT);
11585 goto done;
11588 error = got_worktree_get_histedit_script_path(&path, worktree);
11589 if (error)
11590 goto done;
11592 error = histedit_load_list(&histedit_cmds, path, repo);
11593 free(path);
11594 if (error)
11595 goto done;
11597 error = got_worktree_histedit_continue(&resume_commit_id,
11598 &tmp_branch, &branch, &base_commit_id, &fileindex,
11599 worktree, repo);
11600 if (error)
11601 goto done;
11603 error = got_ref_resolve(&head_commit_id, repo, branch);
11604 if (error)
11605 goto done;
11607 error = got_object_open_as_commit(&commit, repo,
11608 head_commit_id);
11609 if (error)
11610 goto done;
11611 parent_ids = got_object_commit_get_parent_ids(commit);
11612 pid = STAILQ_FIRST(parent_ids);
11613 if (pid == NULL) {
11614 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11615 goto done;
11617 error = collect_commits(&commits, head_commit_id, &pid->id,
11618 base_commit_id, got_worktree_get_path_prefix(worktree),
11619 GOT_ERR_HISTEDIT_PATH, repo);
11620 got_object_commit_close(commit);
11621 commit = NULL;
11622 if (error)
11623 goto done;
11624 } else {
11625 if (edit_in_progress) {
11626 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11627 goto done;
11630 error = got_ref_open(&branch, repo,
11631 got_worktree_get_head_ref_name(worktree), 0);
11632 if (error != NULL)
11633 goto done;
11635 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11636 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11637 "will not edit commit history of a branch outside "
11638 "the \"refs/heads/\" reference namespace");
11639 goto done;
11642 error = got_ref_resolve(&head_commit_id, repo, branch);
11643 got_ref_close(branch);
11644 branch = NULL;
11645 if (error)
11646 goto done;
11648 error = got_object_open_as_commit(&commit, repo,
11649 head_commit_id);
11650 if (error)
11651 goto done;
11652 parent_ids = got_object_commit_get_parent_ids(commit);
11653 pid = STAILQ_FIRST(parent_ids);
11654 if (pid == NULL) {
11655 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11656 goto done;
11658 error = collect_commits(&commits, head_commit_id, &pid->id,
11659 got_worktree_get_base_commit_id(worktree),
11660 got_worktree_get_path_prefix(worktree),
11661 GOT_ERR_HISTEDIT_PATH, repo);
11662 got_object_commit_close(commit);
11663 commit = NULL;
11664 if (error)
11665 goto done;
11667 if (STAILQ_EMPTY(&commits)) {
11668 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11669 goto done;
11672 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11673 &base_commit_id, &fileindex, worktree, repo);
11674 if (error)
11675 goto done;
11677 if (edit_script_path) {
11678 error = histedit_load_list(&histedit_cmds,
11679 edit_script_path, repo);
11680 if (error) {
11681 got_worktree_histedit_abort(worktree, fileindex,
11682 repo, branch, base_commit_id,
11683 abort_progress, &upa);
11684 print_merge_progress_stats(&upa);
11685 goto done;
11687 } else {
11688 const char *branch_name;
11689 branch_name = got_ref_get_symref_target(branch);
11690 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11691 branch_name += 11;
11692 error = histedit_edit_script(&histedit_cmds, &commits,
11693 branch_name, edit_logmsg_only, fold_only,
11694 edit_only, repo);
11695 if (error) {
11696 got_worktree_histedit_abort(worktree, fileindex,
11697 repo, branch, base_commit_id,
11698 abort_progress, &upa);
11699 print_merge_progress_stats(&upa);
11700 goto done;
11705 error = histedit_save_list(&histedit_cmds, worktree,
11706 repo);
11707 if (error) {
11708 got_worktree_histedit_abort(worktree, fileindex,
11709 repo, branch, base_commit_id,
11710 abort_progress, &upa);
11711 print_merge_progress_stats(&upa);
11712 goto done;
11717 error = histedit_check_script(&histedit_cmds, &commits, repo);
11718 if (error)
11719 goto done;
11721 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11722 if (resume_commit_id) {
11723 if (got_object_id_cmp(hle->commit_id,
11724 resume_commit_id) != 0)
11725 continue;
11727 resume_commit_id = NULL;
11728 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11729 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11730 error = histedit_skip_commit(hle, worktree,
11731 repo);
11732 if (error)
11733 goto done;
11734 } else {
11735 struct got_pathlist_head paths;
11736 int have_changes = 0;
11738 TAILQ_INIT(&paths);
11739 error = got_pathlist_append(&paths, "", NULL);
11740 if (error)
11741 goto done;
11742 error = got_worktree_status(worktree, &paths,
11743 repo, 0, check_local_changes, &have_changes,
11744 check_cancelled, NULL);
11745 got_pathlist_free(&paths);
11746 if (error) {
11747 if (error->code != GOT_ERR_CANCELLED)
11748 goto done;
11749 if (sigint_received || sigpipe_received)
11750 goto done;
11752 if (have_changes) {
11753 error = histedit_commit(NULL, worktree,
11754 fileindex, tmp_branch, hle,
11755 committer, repo);
11756 if (error)
11757 goto done;
11758 } else {
11759 error = got_object_open_as_commit(
11760 &commit, repo, hle->commit_id);
11761 if (error)
11762 goto done;
11763 error = show_histedit_progress(commit,
11764 hle, NULL);
11765 got_object_commit_close(commit);
11766 commit = NULL;
11767 if (error)
11768 goto done;
11771 continue;
11774 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11775 error = histedit_skip_commit(hle, worktree, repo);
11776 if (error)
11777 goto done;
11778 continue;
11781 error = got_object_open_as_commit(&commit, repo,
11782 hle->commit_id);
11783 if (error)
11784 goto done;
11785 parent_ids = got_object_commit_get_parent_ids(commit);
11786 pid = STAILQ_FIRST(parent_ids);
11788 error = got_worktree_histedit_merge_files(&merged_paths,
11789 worktree, fileindex, &pid->id, hle->commit_id, repo,
11790 update_progress, &upa, check_cancelled, NULL);
11791 if (error)
11792 goto done;
11793 got_object_commit_close(commit);
11794 commit = NULL;
11796 print_merge_progress_stats(&upa);
11797 if (upa.conflicts > 0 || upa.missing > 0 ||
11798 upa.not_deleted > 0 || upa.unversioned > 0) {
11799 if (upa.conflicts > 0) {
11800 error = show_rebase_merge_conflict(
11801 hle->commit_id, repo);
11802 if (error)
11803 goto done;
11805 got_worktree_rebase_pathlist_free(&merged_paths);
11806 break;
11809 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11810 char *id_str;
11811 error = got_object_id_str(&id_str, hle->commit_id);
11812 if (error)
11813 goto done;
11814 printf("Stopping histedit for amending commit %s\n",
11815 id_str);
11816 free(id_str);
11817 got_worktree_rebase_pathlist_free(&merged_paths);
11818 error = got_worktree_histedit_postpone(worktree,
11819 fileindex);
11820 goto done;
11823 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11824 error = histedit_skip_commit(hle, worktree, repo);
11825 if (error)
11826 goto done;
11827 continue;
11830 error = histedit_commit(&merged_paths, worktree, fileindex,
11831 tmp_branch, hle, committer, repo);
11832 got_worktree_rebase_pathlist_free(&merged_paths);
11833 if (error)
11834 goto done;
11837 if (upa.conflicts > 0 || upa.missing > 0 ||
11838 upa.not_deleted > 0 || upa.unversioned > 0) {
11839 error = got_worktree_histedit_postpone(worktree, fileindex);
11840 if (error)
11841 goto done;
11842 if (upa.conflicts > 0 && upa.missing == 0 &&
11843 upa.not_deleted == 0 && upa.unversioned == 0) {
11844 error = got_error_msg(GOT_ERR_CONFLICTS,
11845 "conflicts must be resolved before histedit "
11846 "can continue");
11847 } else if (upa.conflicts > 0) {
11848 error = got_error_msg(GOT_ERR_CONFLICTS,
11849 "conflicts must be resolved before histedit "
11850 "can continue; changes destined for some "
11851 "files were not yet merged and should be "
11852 "merged manually if required before the "
11853 "histedit operation is continued");
11854 } else {
11855 error = got_error_msg(GOT_ERR_CONFLICTS,
11856 "changes destined for some files were not "
11857 "yet merged and should be merged manually "
11858 "if required before the histedit operation "
11859 "is continued");
11861 } else
11862 error = histedit_complete(worktree, fileindex, tmp_branch,
11863 branch, repo);
11864 done:
11865 free(cwd);
11866 free(committer);
11867 free(gitconfig_path);
11868 got_object_id_queue_free(&commits);
11869 histedit_free_list(&histedit_cmds);
11870 free(head_commit_id);
11871 free(base_commit_id);
11872 free(resume_commit_id);
11873 if (commit)
11874 got_object_commit_close(commit);
11875 if (branch)
11876 got_ref_close(branch);
11877 if (tmp_branch)
11878 got_ref_close(tmp_branch);
11879 if (worktree)
11880 got_worktree_close(worktree);
11881 if (repo) {
11882 const struct got_error *close_err = got_repo_close(repo);
11883 if (error == NULL)
11884 error = close_err;
11886 if (pack_fds) {
11887 const struct got_error *pack_err =
11888 got_repo_pack_fds_close(pack_fds);
11889 if (error == NULL)
11890 error = pack_err;
11892 return error;
11895 __dead static void
11896 usage_integrate(void)
11898 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11899 exit(1);
11902 static const struct got_error *
11903 cmd_integrate(int argc, char *argv[])
11905 const struct got_error *error = NULL;
11906 struct got_repository *repo = NULL;
11907 struct got_worktree *worktree = NULL;
11908 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11909 const char *branch_arg = NULL;
11910 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11911 struct got_fileindex *fileindex = NULL;
11912 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11913 int ch;
11914 struct got_update_progress_arg upa;
11915 int *pack_fds = NULL;
11917 while ((ch = getopt(argc, argv, "")) != -1) {
11918 switch (ch) {
11919 default:
11920 usage_integrate();
11921 /* NOTREACHED */
11925 argc -= optind;
11926 argv += optind;
11928 if (argc != 1)
11929 usage_integrate();
11930 branch_arg = argv[0];
11931 #ifndef PROFILE
11932 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11933 "unveil", NULL) == -1)
11934 err(1, "pledge");
11935 #endif
11936 cwd = getcwd(NULL, 0);
11937 if (cwd == NULL) {
11938 error = got_error_from_errno("getcwd");
11939 goto done;
11942 error = got_repo_pack_fds_open(&pack_fds);
11943 if (error != NULL)
11944 goto done;
11946 error = got_worktree_open(&worktree, cwd);
11947 if (error) {
11948 if (error->code == GOT_ERR_NOT_WORKTREE)
11949 error = wrap_not_worktree_error(error, "integrate",
11950 cwd);
11951 goto done;
11954 error = check_rebase_or_histedit_in_progress(worktree);
11955 if (error)
11956 goto done;
11958 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11959 NULL, pack_fds);
11960 if (error != NULL)
11961 goto done;
11963 error = apply_unveil(got_repo_get_path(repo), 0,
11964 got_worktree_get_root_path(worktree));
11965 if (error)
11966 goto done;
11968 error = check_merge_in_progress(worktree, repo);
11969 if (error)
11970 goto done;
11972 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11973 error = got_error_from_errno("asprintf");
11974 goto done;
11977 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11978 &base_branch_ref, worktree, refname, repo);
11979 if (error)
11980 goto done;
11982 refname = strdup(got_ref_get_name(branch_ref));
11983 if (refname == NULL) {
11984 error = got_error_from_errno("strdup");
11985 got_worktree_integrate_abort(worktree, fileindex, repo,
11986 branch_ref, base_branch_ref);
11987 goto done;
11989 base_refname = strdup(got_ref_get_name(base_branch_ref));
11990 if (base_refname == NULL) {
11991 error = got_error_from_errno("strdup");
11992 got_worktree_integrate_abort(worktree, fileindex, repo,
11993 branch_ref, base_branch_ref);
11994 goto done;
11996 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
11997 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
11998 got_worktree_integrate_abort(worktree, fileindex, repo,
11999 branch_ref, base_branch_ref);
12000 goto done;
12003 error = got_ref_resolve(&commit_id, repo, branch_ref);
12004 if (error)
12005 goto done;
12007 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12008 if (error)
12009 goto done;
12011 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12012 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12013 "specified branch has already been integrated");
12014 got_worktree_integrate_abort(worktree, fileindex, repo,
12015 branch_ref, base_branch_ref);
12016 goto done;
12019 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12020 if (error) {
12021 if (error->code == GOT_ERR_ANCESTRY)
12022 error = got_error(GOT_ERR_REBASE_REQUIRED);
12023 got_worktree_integrate_abort(worktree, fileindex, repo,
12024 branch_ref, base_branch_ref);
12025 goto done;
12028 memset(&upa, 0, sizeof(upa));
12029 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12030 branch_ref, base_branch_ref, update_progress, &upa,
12031 check_cancelled, NULL);
12032 if (error)
12033 goto done;
12035 printf("Integrated %s into %s\n", refname, base_refname);
12036 print_update_progress_stats(&upa);
12037 done:
12038 if (repo) {
12039 const struct got_error *close_err = got_repo_close(repo);
12040 if (error == NULL)
12041 error = close_err;
12043 if (worktree)
12044 got_worktree_close(worktree);
12045 if (pack_fds) {
12046 const struct got_error *pack_err =
12047 got_repo_pack_fds_close(pack_fds);
12048 if (error == NULL)
12049 error = pack_err;
12051 free(cwd);
12052 free(base_commit_id);
12053 free(commit_id);
12054 free(refname);
12055 free(base_refname);
12056 return error;
12059 __dead static void
12060 usage_merge(void)
12062 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12063 exit(1);
12066 static const struct got_error *
12067 cmd_merge(int argc, char *argv[])
12069 const struct got_error *error = NULL;
12070 struct got_worktree *worktree = NULL;
12071 struct got_repository *repo = NULL;
12072 struct got_fileindex *fileindex = NULL;
12073 char *cwd = NULL, *id_str = NULL, *author = NULL;
12074 struct got_reference *branch = NULL, *wt_branch = NULL;
12075 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12076 struct got_object_id *wt_branch_tip = NULL;
12077 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12078 int interrupt_merge = 0;
12079 struct got_update_progress_arg upa;
12080 struct got_object_id *merge_commit_id = NULL;
12081 char *branch_name = NULL;
12082 int *pack_fds = NULL;
12084 memset(&upa, 0, sizeof(upa));
12086 while ((ch = getopt(argc, argv, "acn")) != -1) {
12087 switch (ch) {
12088 case 'a':
12089 abort_merge = 1;
12090 break;
12091 case 'c':
12092 continue_merge = 1;
12093 break;
12094 case 'n':
12095 interrupt_merge = 1;
12096 break;
12097 default:
12098 usage_rebase();
12099 /* NOTREACHED */
12103 argc -= optind;
12104 argv += optind;
12106 #ifndef PROFILE
12107 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12108 "unveil", NULL) == -1)
12109 err(1, "pledge");
12110 #endif
12112 if (abort_merge && continue_merge)
12113 option_conflict('a', 'c');
12114 if (abort_merge || continue_merge) {
12115 if (argc != 0)
12116 usage_merge();
12117 } else if (argc != 1)
12118 usage_merge();
12120 cwd = getcwd(NULL, 0);
12121 if (cwd == NULL) {
12122 error = got_error_from_errno("getcwd");
12123 goto done;
12126 error = got_repo_pack_fds_open(&pack_fds);
12127 if (error != NULL)
12128 goto done;
12130 error = got_worktree_open(&worktree, cwd);
12131 if (error) {
12132 if (error->code == GOT_ERR_NOT_WORKTREE)
12133 error = wrap_not_worktree_error(error,
12134 "merge", cwd);
12135 goto done;
12138 error = got_repo_open(&repo,
12139 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12140 pack_fds);
12141 if (error != NULL)
12142 goto done;
12144 error = apply_unveil(got_repo_get_path(repo), 0,
12145 worktree ? got_worktree_get_root_path(worktree) : NULL);
12146 if (error)
12147 goto done;
12149 error = check_rebase_or_histedit_in_progress(worktree);
12150 if (error)
12151 goto done;
12153 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12154 repo);
12155 if (error)
12156 goto done;
12158 if (abort_merge) {
12159 if (!merge_in_progress) {
12160 error = got_error(GOT_ERR_NOT_MERGING);
12161 goto done;
12163 error = got_worktree_merge_continue(&branch_name,
12164 &branch_tip, &fileindex, worktree, repo);
12165 if (error)
12166 goto done;
12167 error = got_worktree_merge_abort(worktree, fileindex, repo,
12168 abort_progress, &upa);
12169 if (error)
12170 goto done;
12171 printf("Merge of %s aborted\n", branch_name);
12172 goto done; /* nothing else to do */
12175 error = get_author(&author, repo, worktree);
12176 if (error)
12177 goto done;
12179 if (continue_merge) {
12180 if (!merge_in_progress) {
12181 error = got_error(GOT_ERR_NOT_MERGING);
12182 goto done;
12184 error = got_worktree_merge_continue(&branch_name,
12185 &branch_tip, &fileindex, worktree, repo);
12186 if (error)
12187 goto done;
12188 } else {
12189 error = got_ref_open(&branch, repo, argv[0], 0);
12190 if (error != NULL)
12191 goto done;
12192 branch_name = strdup(got_ref_get_name(branch));
12193 if (branch_name == NULL) {
12194 error = got_error_from_errno("strdup");
12195 goto done;
12197 error = got_ref_resolve(&branch_tip, repo, branch);
12198 if (error)
12199 goto done;
12202 error = got_ref_open(&wt_branch, repo,
12203 got_worktree_get_head_ref_name(worktree), 0);
12204 if (error)
12205 goto done;
12206 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12207 if (error)
12208 goto done;
12209 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12210 wt_branch_tip, branch_tip, 0, repo,
12211 check_cancelled, NULL);
12212 if (error && error->code != GOT_ERR_ANCESTRY)
12213 goto done;
12215 if (!continue_merge) {
12216 error = check_path_prefix(wt_branch_tip, branch_tip,
12217 got_worktree_get_path_prefix(worktree),
12218 GOT_ERR_MERGE_PATH, repo);
12219 if (error)
12220 goto done;
12221 if (yca_id) {
12222 error = check_same_branch(wt_branch_tip, branch,
12223 yca_id, repo);
12224 if (error) {
12225 if (error->code != GOT_ERR_ANCESTRY)
12226 goto done;
12227 error = NULL;
12228 } else {
12229 static char msg[512];
12230 snprintf(msg, sizeof(msg),
12231 "cannot create a merge commit because "
12232 "%s is based on %s; %s can be integrated "
12233 "with 'got integrate' instead", branch_name,
12234 got_worktree_get_head_ref_name(worktree),
12235 branch_name);
12236 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12237 goto done;
12240 error = got_worktree_merge_prepare(&fileindex, worktree,
12241 branch, repo);
12242 if (error)
12243 goto done;
12245 error = got_worktree_merge_branch(worktree, fileindex,
12246 yca_id, branch_tip, repo, update_progress, &upa,
12247 check_cancelled, NULL);
12248 if (error)
12249 goto done;
12250 print_merge_progress_stats(&upa);
12251 if (!upa.did_something) {
12252 error = got_worktree_merge_abort(worktree, fileindex,
12253 repo, abort_progress, &upa);
12254 if (error)
12255 goto done;
12256 printf("Already up-to-date\n");
12257 goto done;
12261 if (interrupt_merge) {
12262 error = got_worktree_merge_postpone(worktree, fileindex);
12263 if (error)
12264 goto done;
12265 printf("Merge of %s interrupted on request\n", branch_name);
12266 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12267 upa.not_deleted > 0 || upa.unversioned > 0) {
12268 error = got_worktree_merge_postpone(worktree, fileindex);
12269 if (error)
12270 goto done;
12271 if (upa.conflicts > 0 && upa.missing == 0 &&
12272 upa.not_deleted == 0 && upa.unversioned == 0) {
12273 error = got_error_msg(GOT_ERR_CONFLICTS,
12274 "conflicts must be resolved before merging "
12275 "can continue");
12276 } else if (upa.conflicts > 0) {
12277 error = got_error_msg(GOT_ERR_CONFLICTS,
12278 "conflicts must be resolved before merging "
12279 "can continue; changes destined for some "
12280 "files were not yet merged and "
12281 "should be merged manually if required before the "
12282 "merge operation is continued");
12283 } else {
12284 error = got_error_msg(GOT_ERR_CONFLICTS,
12285 "changes destined for some "
12286 "files were not yet merged and should be "
12287 "merged manually if required before the "
12288 "merge operation is continued");
12290 goto done;
12291 } else {
12292 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12293 fileindex, author, NULL, 1, branch_tip, branch_name,
12294 repo, continue_merge ? print_status : NULL, NULL);
12295 if (error)
12296 goto done;
12297 error = got_worktree_merge_complete(worktree, fileindex, repo);
12298 if (error)
12299 goto done;
12300 error = got_object_id_str(&id_str, merge_commit_id);
12301 if (error)
12302 goto done;
12303 printf("Merged %s into %s: %s\n", branch_name,
12304 got_worktree_get_head_ref_name(worktree),
12305 id_str);
12308 done:
12309 free(id_str);
12310 free(merge_commit_id);
12311 free(author);
12312 free(branch_tip);
12313 free(branch_name);
12314 free(yca_id);
12315 if (branch)
12316 got_ref_close(branch);
12317 if (wt_branch)
12318 got_ref_close(wt_branch);
12319 if (worktree)
12320 got_worktree_close(worktree);
12321 if (repo) {
12322 const struct got_error *close_err = got_repo_close(repo);
12323 if (error == NULL)
12324 error = close_err;
12326 if (pack_fds) {
12327 const struct got_error *pack_err =
12328 got_repo_pack_fds_close(pack_fds);
12329 if (error == NULL)
12330 error = pack_err;
12332 return error;
12335 __dead static void
12336 usage_stage(void)
12338 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12339 "[path ...]\n", getprogname());
12340 exit(1);
12343 static const struct got_error *
12344 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12345 const char *path, struct got_object_id *blob_id,
12346 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12347 int dirfd, const char *de_name)
12349 const struct got_error *err = NULL;
12350 char *id_str = NULL;
12352 if (staged_status != GOT_STATUS_ADD &&
12353 staged_status != GOT_STATUS_MODIFY &&
12354 staged_status != GOT_STATUS_DELETE)
12355 return NULL;
12357 if (staged_status == GOT_STATUS_ADD ||
12358 staged_status == GOT_STATUS_MODIFY)
12359 err = got_object_id_str(&id_str, staged_blob_id);
12360 else
12361 err = got_object_id_str(&id_str, blob_id);
12362 if (err)
12363 return err;
12365 printf("%s %c %s\n", id_str, staged_status, path);
12366 free(id_str);
12367 return NULL;
12370 static const struct got_error *
12371 cmd_stage(int argc, char *argv[])
12373 const struct got_error *error = NULL;
12374 struct got_repository *repo = NULL;
12375 struct got_worktree *worktree = NULL;
12376 char *cwd = NULL;
12377 struct got_pathlist_head paths;
12378 struct got_pathlist_entry *pe;
12379 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12380 FILE *patch_script_file = NULL;
12381 const char *patch_script_path = NULL;
12382 struct choose_patch_arg cpa;
12383 int *pack_fds = NULL;
12385 TAILQ_INIT(&paths);
12387 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12388 switch (ch) {
12389 case 'F':
12390 patch_script_path = optarg;
12391 break;
12392 case 'l':
12393 list_stage = 1;
12394 break;
12395 case 'p':
12396 pflag = 1;
12397 break;
12398 case 'S':
12399 allow_bad_symlinks = 1;
12400 break;
12401 default:
12402 usage_stage();
12403 /* NOTREACHED */
12407 argc -= optind;
12408 argv += optind;
12410 #ifndef PROFILE
12411 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12412 "unveil", NULL) == -1)
12413 err(1, "pledge");
12414 #endif
12415 if (list_stage && (pflag || patch_script_path))
12416 errx(1, "-l option cannot be used with other options");
12417 if (patch_script_path && !pflag)
12418 errx(1, "-F option can only be used together with -p option");
12420 cwd = getcwd(NULL, 0);
12421 if (cwd == NULL) {
12422 error = got_error_from_errno("getcwd");
12423 goto done;
12426 error = got_repo_pack_fds_open(&pack_fds);
12427 if (error != NULL)
12428 goto done;
12430 error = got_worktree_open(&worktree, cwd);
12431 if (error) {
12432 if (error->code == GOT_ERR_NOT_WORKTREE)
12433 error = wrap_not_worktree_error(error, "stage", cwd);
12434 goto done;
12437 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12438 NULL, pack_fds);
12439 if (error != NULL)
12440 goto done;
12442 if (patch_script_path) {
12443 patch_script_file = fopen(patch_script_path, "re");
12444 if (patch_script_file == NULL) {
12445 error = got_error_from_errno2("fopen",
12446 patch_script_path);
12447 goto done;
12450 error = apply_unveil(got_repo_get_path(repo), 0,
12451 got_worktree_get_root_path(worktree));
12452 if (error)
12453 goto done;
12455 error = check_merge_in_progress(worktree, repo);
12456 if (error)
12457 goto done;
12459 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12460 if (error)
12461 goto done;
12463 if (list_stage)
12464 error = got_worktree_status(worktree, &paths, repo, 0,
12465 print_stage, NULL, check_cancelled, NULL);
12466 else {
12467 cpa.patch_script_file = patch_script_file;
12468 cpa.action = "stage";
12469 error = got_worktree_stage(worktree, &paths,
12470 pflag ? NULL : print_status, NULL,
12471 pflag ? choose_patch : NULL, &cpa,
12472 allow_bad_symlinks, repo);
12474 done:
12475 if (patch_script_file && fclose(patch_script_file) == EOF &&
12476 error == NULL)
12477 error = got_error_from_errno2("fclose", patch_script_path);
12478 if (repo) {
12479 const struct got_error *close_err = got_repo_close(repo);
12480 if (error == NULL)
12481 error = close_err;
12483 if (worktree)
12484 got_worktree_close(worktree);
12485 if (pack_fds) {
12486 const struct got_error *pack_err =
12487 got_repo_pack_fds_close(pack_fds);
12488 if (error == NULL)
12489 error = pack_err;
12491 TAILQ_FOREACH(pe, &paths, entry)
12492 free((char *)pe->path);
12493 got_pathlist_free(&paths);
12494 free(cwd);
12495 return error;
12498 __dead static void
12499 usage_unstage(void)
12501 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12502 "[path ...]\n", getprogname());
12503 exit(1);
12507 static const struct got_error *
12508 cmd_unstage(int argc, char *argv[])
12510 const struct got_error *error = NULL;
12511 struct got_repository *repo = NULL;
12512 struct got_worktree *worktree = NULL;
12513 char *cwd = NULL;
12514 struct got_pathlist_head paths;
12515 struct got_pathlist_entry *pe;
12516 int ch, pflag = 0;
12517 struct got_update_progress_arg upa;
12518 FILE *patch_script_file = NULL;
12519 const char *patch_script_path = NULL;
12520 struct choose_patch_arg cpa;
12521 int *pack_fds = NULL;
12523 TAILQ_INIT(&paths);
12525 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12526 switch (ch) {
12527 case 'F':
12528 patch_script_path = optarg;
12529 break;
12530 case 'p':
12531 pflag = 1;
12532 break;
12533 default:
12534 usage_unstage();
12535 /* NOTREACHED */
12539 argc -= optind;
12540 argv += optind;
12542 #ifndef PROFILE
12543 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12544 "unveil", NULL) == -1)
12545 err(1, "pledge");
12546 #endif
12547 if (patch_script_path && !pflag)
12548 errx(1, "-F option can only be used together with -p option");
12550 cwd = getcwd(NULL, 0);
12551 if (cwd == NULL) {
12552 error = got_error_from_errno("getcwd");
12553 goto done;
12556 error = got_repo_pack_fds_open(&pack_fds);
12557 if (error != NULL)
12558 goto done;
12560 error = got_worktree_open(&worktree, cwd);
12561 if (error) {
12562 if (error->code == GOT_ERR_NOT_WORKTREE)
12563 error = wrap_not_worktree_error(error, "unstage", cwd);
12564 goto done;
12567 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12568 NULL, pack_fds);
12569 if (error != NULL)
12570 goto done;
12572 if (patch_script_path) {
12573 patch_script_file = fopen(patch_script_path, "re");
12574 if (patch_script_file == NULL) {
12575 error = got_error_from_errno2("fopen",
12576 patch_script_path);
12577 goto done;
12581 error = apply_unveil(got_repo_get_path(repo), 0,
12582 got_worktree_get_root_path(worktree));
12583 if (error)
12584 goto done;
12586 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12587 if (error)
12588 goto done;
12590 cpa.patch_script_file = patch_script_file;
12591 cpa.action = "unstage";
12592 memset(&upa, 0, sizeof(upa));
12593 error = got_worktree_unstage(worktree, &paths, update_progress,
12594 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12595 if (!error)
12596 print_merge_progress_stats(&upa);
12597 done:
12598 if (patch_script_file && fclose(patch_script_file) == EOF &&
12599 error == NULL)
12600 error = got_error_from_errno2("fclose", patch_script_path);
12601 if (repo) {
12602 const struct got_error *close_err = got_repo_close(repo);
12603 if (error == NULL)
12604 error = close_err;
12606 if (worktree)
12607 got_worktree_close(worktree);
12608 if (pack_fds) {
12609 const struct got_error *pack_err =
12610 got_repo_pack_fds_close(pack_fds);
12611 if (error == NULL)
12612 error = pack_err;
12614 TAILQ_FOREACH(pe, &paths, entry)
12615 free((char *)pe->path);
12616 got_pathlist_free(&paths);
12617 free(cwd);
12618 return error;
12621 __dead static void
12622 usage_cat(void)
12624 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12625 "arg ...\n", getprogname());
12626 exit(1);
12629 static const struct got_error *
12630 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12632 const struct got_error *err;
12633 struct got_blob_object *blob;
12634 int fd = -1;
12636 fd = got_opentempfd();
12637 if (fd == -1)
12638 return got_error_from_errno("got_opentempfd");
12640 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12641 if (err)
12642 goto done;
12644 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12645 done:
12646 if (fd != -1 && close(fd) == -1 && err == NULL)
12647 err = got_error_from_errno("close");
12648 if (blob)
12649 got_object_blob_close(blob);
12650 return err;
12653 static const struct got_error *
12654 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12656 const struct got_error *err;
12657 struct got_tree_object *tree;
12658 int nentries, i;
12660 err = got_object_open_as_tree(&tree, repo, id);
12661 if (err)
12662 return err;
12664 nentries = got_object_tree_get_nentries(tree);
12665 for (i = 0; i < nentries; i++) {
12666 struct got_tree_entry *te;
12667 char *id_str;
12668 if (sigint_received || sigpipe_received)
12669 break;
12670 te = got_object_tree_get_entry(tree, i);
12671 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12672 if (err)
12673 break;
12674 fprintf(outfile, "%s %.7o %s\n", id_str,
12675 got_tree_entry_get_mode(te),
12676 got_tree_entry_get_name(te));
12677 free(id_str);
12680 got_object_tree_close(tree);
12681 return err;
12684 static const struct got_error *
12685 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12687 const struct got_error *err;
12688 struct got_commit_object *commit;
12689 const struct got_object_id_queue *parent_ids;
12690 struct got_object_qid *pid;
12691 char *id_str = NULL;
12692 const char *logmsg = NULL;
12693 char gmtoff[6];
12695 err = got_object_open_as_commit(&commit, repo, id);
12696 if (err)
12697 return err;
12699 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12700 if (err)
12701 goto done;
12703 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12704 parent_ids = got_object_commit_get_parent_ids(commit);
12705 fprintf(outfile, "numparents %d\n",
12706 got_object_commit_get_nparents(commit));
12707 STAILQ_FOREACH(pid, parent_ids, entry) {
12708 char *pid_str;
12709 err = got_object_id_str(&pid_str, &pid->id);
12710 if (err)
12711 goto done;
12712 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12713 free(pid_str);
12715 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12716 got_object_commit_get_author_gmtoff(commit));
12717 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12718 got_object_commit_get_author(commit),
12719 (long long)got_object_commit_get_author_time(commit),
12720 gmtoff);
12722 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12723 got_object_commit_get_committer_gmtoff(commit));
12724 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12725 got_object_commit_get_committer(commit),
12726 (long long)got_object_commit_get_committer_time(commit),
12727 gmtoff);
12729 logmsg = got_object_commit_get_logmsg_raw(commit);
12730 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12731 fprintf(outfile, "%s", logmsg);
12732 done:
12733 free(id_str);
12734 got_object_commit_close(commit);
12735 return err;
12738 static const struct got_error *
12739 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12741 const struct got_error *err;
12742 struct got_tag_object *tag;
12743 char *id_str = NULL;
12744 const char *tagmsg = NULL;
12745 char gmtoff[6];
12747 err = got_object_open_as_tag(&tag, repo, id);
12748 if (err)
12749 return err;
12751 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12752 if (err)
12753 goto done;
12755 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12757 switch (got_object_tag_get_object_type(tag)) {
12758 case GOT_OBJ_TYPE_BLOB:
12759 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12760 GOT_OBJ_LABEL_BLOB);
12761 break;
12762 case GOT_OBJ_TYPE_TREE:
12763 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12764 GOT_OBJ_LABEL_TREE);
12765 break;
12766 case GOT_OBJ_TYPE_COMMIT:
12767 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12768 GOT_OBJ_LABEL_COMMIT);
12769 break;
12770 case GOT_OBJ_TYPE_TAG:
12771 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12772 GOT_OBJ_LABEL_TAG);
12773 break;
12774 default:
12775 break;
12778 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12779 got_object_tag_get_name(tag));
12781 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12782 got_object_tag_get_tagger_gmtoff(tag));
12783 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12784 got_object_tag_get_tagger(tag),
12785 (long long)got_object_tag_get_tagger_time(tag),
12786 gmtoff);
12788 tagmsg = got_object_tag_get_message(tag);
12789 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12790 fprintf(outfile, "%s", tagmsg);
12791 done:
12792 free(id_str);
12793 got_object_tag_close(tag);
12794 return err;
12797 static const struct got_error *
12798 cmd_cat(int argc, char *argv[])
12800 const struct got_error *error;
12801 struct got_repository *repo = NULL;
12802 struct got_worktree *worktree = NULL;
12803 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12804 const char *commit_id_str = NULL;
12805 struct got_object_id *id = NULL, *commit_id = NULL;
12806 struct got_commit_object *commit = NULL;
12807 int ch, obj_type, i, force_path = 0;
12808 struct got_reflist_head refs;
12809 int *pack_fds = NULL;
12811 TAILQ_INIT(&refs);
12813 #ifndef PROFILE
12814 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12815 NULL) == -1)
12816 err(1, "pledge");
12817 #endif
12819 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12820 switch (ch) {
12821 case 'c':
12822 commit_id_str = optarg;
12823 break;
12824 case 'P':
12825 force_path = 1;
12826 break;
12827 case 'r':
12828 repo_path = realpath(optarg, NULL);
12829 if (repo_path == NULL)
12830 return got_error_from_errno2("realpath",
12831 optarg);
12832 got_path_strip_trailing_slashes(repo_path);
12833 break;
12834 default:
12835 usage_cat();
12836 /* NOTREACHED */
12840 argc -= optind;
12841 argv += optind;
12843 cwd = getcwd(NULL, 0);
12844 if (cwd == NULL) {
12845 error = got_error_from_errno("getcwd");
12846 goto done;
12849 error = got_repo_pack_fds_open(&pack_fds);
12850 if (error != NULL)
12851 goto done;
12853 if (repo_path == NULL) {
12854 error = got_worktree_open(&worktree, cwd);
12855 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12856 goto done;
12857 if (worktree) {
12858 repo_path = strdup(
12859 got_worktree_get_repo_path(worktree));
12860 if (repo_path == NULL) {
12861 error = got_error_from_errno("strdup");
12862 goto done;
12865 /* Release work tree lock. */
12866 got_worktree_close(worktree);
12867 worktree = NULL;
12871 if (repo_path == NULL) {
12872 repo_path = strdup(cwd);
12873 if (repo_path == NULL)
12874 return got_error_from_errno("strdup");
12877 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12878 free(repo_path);
12879 if (error != NULL)
12880 goto done;
12882 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12883 if (error)
12884 goto done;
12886 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12887 if (error)
12888 goto done;
12890 if (commit_id_str == NULL)
12891 commit_id_str = GOT_REF_HEAD;
12892 error = got_repo_match_object_id(&commit_id, NULL,
12893 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12894 if (error)
12895 goto done;
12897 error = got_object_open_as_commit(&commit, repo, commit_id);
12898 if (error)
12899 goto done;
12901 for (i = 0; i < argc; i++) {
12902 if (force_path) {
12903 error = got_object_id_by_path(&id, repo, commit,
12904 argv[i]);
12905 if (error)
12906 break;
12907 } else {
12908 error = got_repo_match_object_id(&id, &label, argv[i],
12909 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12910 repo);
12911 if (error) {
12912 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12913 error->code != GOT_ERR_NOT_REF)
12914 break;
12915 error = got_object_id_by_path(&id, repo,
12916 commit, argv[i]);
12917 if (error)
12918 break;
12922 error = got_object_get_type(&obj_type, repo, id);
12923 if (error)
12924 break;
12926 switch (obj_type) {
12927 case GOT_OBJ_TYPE_BLOB:
12928 error = cat_blob(id, repo, stdout);
12929 break;
12930 case GOT_OBJ_TYPE_TREE:
12931 error = cat_tree(id, repo, stdout);
12932 break;
12933 case GOT_OBJ_TYPE_COMMIT:
12934 error = cat_commit(id, repo, stdout);
12935 break;
12936 case GOT_OBJ_TYPE_TAG:
12937 error = cat_tag(id, repo, stdout);
12938 break;
12939 default:
12940 error = got_error(GOT_ERR_OBJ_TYPE);
12941 break;
12943 if (error)
12944 break;
12945 free(label);
12946 label = NULL;
12947 free(id);
12948 id = NULL;
12950 done:
12951 free(label);
12952 free(id);
12953 free(commit_id);
12954 if (commit)
12955 got_object_commit_close(commit);
12956 if (worktree)
12957 got_worktree_close(worktree);
12958 if (repo) {
12959 const struct got_error *close_err = got_repo_close(repo);
12960 if (error == NULL)
12961 error = close_err;
12963 if (pack_fds) {
12964 const struct got_error *pack_err =
12965 got_repo_pack_fds_close(pack_fds);
12966 if (error == NULL)
12967 error = pack_err;
12970 got_ref_list_free(&refs);
12971 return error;
12974 __dead static void
12975 usage_info(void)
12977 fprintf(stderr, "usage: %s info [path ...]\n",
12978 getprogname());
12979 exit(1);
12982 static const struct got_error *
12983 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12984 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12985 struct got_object_id *commit_id)
12987 const struct got_error *err = NULL;
12988 char *id_str = NULL;
12989 char datebuf[128];
12990 struct tm mytm, *tm;
12991 struct got_pathlist_head *paths = arg;
12992 struct got_pathlist_entry *pe;
12995 * Clear error indication from any of the path arguments which
12996 * would cause this file index entry to be displayed.
12998 TAILQ_FOREACH(pe, paths, entry) {
12999 if (got_path_cmp(path, pe->path, strlen(path),
13000 pe->path_len) == 0 ||
13001 got_path_is_child(path, pe->path, pe->path_len))
13002 pe->data = NULL; /* no error */
13005 printf(GOT_COMMIT_SEP_STR);
13006 if (S_ISLNK(mode))
13007 printf("symlink: %s\n", path);
13008 else if (S_ISREG(mode)) {
13009 printf("file: %s\n", path);
13010 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13011 } else if (S_ISDIR(mode))
13012 printf("directory: %s\n", path);
13013 else
13014 printf("something: %s\n", path);
13016 tm = localtime_r(&mtime, &mytm);
13017 if (tm == NULL)
13018 return NULL;
13019 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13020 return got_error(GOT_ERR_NO_SPACE);
13021 printf("timestamp: %s\n", datebuf);
13023 if (blob_id) {
13024 err = got_object_id_str(&id_str, blob_id);
13025 if (err)
13026 return err;
13027 printf("based on blob: %s\n", id_str);
13028 free(id_str);
13031 if (staged_blob_id) {
13032 err = got_object_id_str(&id_str, staged_blob_id);
13033 if (err)
13034 return err;
13035 printf("based on staged blob: %s\n", id_str);
13036 free(id_str);
13039 if (commit_id) {
13040 err = got_object_id_str(&id_str, commit_id);
13041 if (err)
13042 return err;
13043 printf("based on commit: %s\n", id_str);
13044 free(id_str);
13047 return NULL;
13050 static const struct got_error *
13051 cmd_info(int argc, char *argv[])
13053 const struct got_error *error = NULL;
13054 struct got_worktree *worktree = NULL;
13055 char *cwd = NULL, *id_str = NULL;
13056 struct got_pathlist_head paths;
13057 struct got_pathlist_entry *pe;
13058 char *uuidstr = NULL;
13059 int ch, show_files = 0;
13061 TAILQ_INIT(&paths);
13063 while ((ch = getopt(argc, argv, "")) != -1) {
13064 switch (ch) {
13065 default:
13066 usage_info();
13067 /* NOTREACHED */
13071 argc -= optind;
13072 argv += optind;
13074 #ifndef PROFILE
13075 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13076 NULL) == -1)
13077 err(1, "pledge");
13078 #endif
13079 cwd = getcwd(NULL, 0);
13080 if (cwd == NULL) {
13081 error = got_error_from_errno("getcwd");
13082 goto done;
13085 error = got_worktree_open(&worktree, cwd);
13086 if (error) {
13087 if (error->code == GOT_ERR_NOT_WORKTREE)
13088 error = wrap_not_worktree_error(error, "info", cwd);
13089 goto done;
13092 #ifndef PROFILE
13093 /* Remove "wpath cpath proc exec sendfd" promises. */
13094 if (pledge("stdio rpath flock unveil", NULL) == -1)
13095 err(1, "pledge");
13096 #endif
13097 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13098 if (error)
13099 goto done;
13101 if (argc >= 1) {
13102 error = get_worktree_paths_from_argv(&paths, argc, argv,
13103 worktree);
13104 if (error)
13105 goto done;
13106 show_files = 1;
13109 error = got_object_id_str(&id_str,
13110 got_worktree_get_base_commit_id(worktree));
13111 if (error)
13112 goto done;
13114 error = got_worktree_get_uuid(&uuidstr, worktree);
13115 if (error)
13116 goto done;
13118 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13119 printf("work tree base commit: %s\n", id_str);
13120 printf("work tree path prefix: %s\n",
13121 got_worktree_get_path_prefix(worktree));
13122 printf("work tree branch reference: %s\n",
13123 got_worktree_get_head_ref_name(worktree));
13124 printf("work tree UUID: %s\n", uuidstr);
13125 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13127 if (show_files) {
13128 struct got_pathlist_entry *pe;
13129 TAILQ_FOREACH(pe, &paths, entry) {
13130 if (pe->path_len == 0)
13131 continue;
13133 * Assume this path will fail. This will be corrected
13134 * in print_path_info() in case the path does suceeed.
13136 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13138 error = got_worktree_path_info(worktree, &paths,
13139 print_path_info, &paths, check_cancelled, NULL);
13140 if (error)
13141 goto done;
13142 TAILQ_FOREACH(pe, &paths, entry) {
13143 if (pe->data != NULL) {
13144 const struct got_error *perr;
13146 perr = pe->data;
13147 error = got_error_fmt(perr->code, "%s",
13148 pe->path);
13149 break;
13153 done:
13154 if (worktree)
13155 got_worktree_close(worktree);
13156 TAILQ_FOREACH(pe, &paths, entry)
13157 free((char *)pe->path);
13158 got_pathlist_free(&paths);
13159 free(cwd);
13160 free(id_str);
13161 free(uuidstr);
13162 return error;