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 <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
42 #include "got_compat.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%s%s\n", host,
1698 port ? ":" : "", port ? port : "");
1700 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1701 server_path, verbosity);
1702 if (error)
1703 goto done;
1705 if (!list_refs_only) {
1706 error = got_repo_init(repo_path, NULL);
1707 if (error)
1708 goto done;
1709 error = got_repo_pack_fds_open(&pack_fds);
1710 if (error != NULL)
1711 goto done;
1712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1713 if (error)
1714 goto done;
1717 fpa.last_scaled_size[0] = '\0';
1718 fpa.last_p_indexed = -1;
1719 fpa.last_p_resolved = -1;
1720 fpa.verbosity = verbosity;
1721 fpa.create_configs = 1;
1722 fpa.configs_created = 0;
1723 fpa.repo = repo;
1724 fpa.config_info.symrefs = &symrefs;
1725 fpa.config_info.wanted_branches = &wanted_branches;
1726 fpa.config_info.wanted_refs = &wanted_refs;
1727 fpa.config_info.proto = proto;
1728 fpa.config_info.host = host;
1729 fpa.config_info.port = port;
1730 fpa.config_info.remote_repo_path = server_path;
1731 fpa.config_info.git_url = git_url;
1732 fpa.config_info.fetch_all_branches = fetch_all_branches;
1733 fpa.config_info.mirror_references = mirror_references;
1734 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1735 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1736 fetch_all_branches, &wanted_branches, &wanted_refs,
1737 list_refs_only, verbosity, fetchfd, repo,
1738 fetch_progress, &fpa);
1739 if (error)
1740 goto done;
1742 if (list_refs_only) {
1743 error = list_remote_refs(&symrefs, &refs);
1744 goto done;
1747 if (pack_hash == NULL) {
1748 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1749 "server sent an empty pack file");
1750 goto done;
1752 error = got_object_id_str(&id_str, pack_hash);
1753 if (error)
1754 goto done;
1755 if (verbosity >= 0)
1756 printf("\nFetched %s.pack\n", id_str);
1757 free(id_str);
1759 /* Set up references provided with the pack file. */
1760 TAILQ_FOREACH(pe, &refs, entry) {
1761 const char *refname = pe->path;
1762 struct got_object_id *id = pe->data;
1763 char *remote_refname;
1765 if (is_wanted_ref(&wanted_refs, refname) &&
1766 !mirror_references) {
1767 error = create_wanted_ref(refname, id,
1768 GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 verbosity - 1, repo);
1770 if (error)
1771 goto done;
1772 continue;
1775 error = create_ref(refname, id, verbosity - 1, repo);
1776 if (error)
1777 goto done;
1779 if (mirror_references)
1780 continue;
1782 if (strncmp("refs/heads/", refname, 11) != 0)
1783 continue;
1785 if (asprintf(&remote_refname,
1786 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1787 refname + 11) == -1) {
1788 error = got_error_from_errno("asprintf");
1789 goto done;
1791 error = create_ref(remote_refname, id, verbosity - 1, repo);
1792 free(remote_refname);
1793 if (error)
1794 goto done;
1797 /* Set the HEAD reference if the server provided one. */
1798 TAILQ_FOREACH(pe, &symrefs, entry) {
1799 struct got_reference *target_ref;
1800 const char *refname = pe->path;
1801 const char *target = pe->data;
1802 char *remote_refname = NULL, *remote_target = NULL;
1804 if (strcmp(refname, GOT_REF_HEAD) != 0)
1805 continue;
1807 error = got_ref_open(&target_ref, repo, target, 0);
1808 if (error) {
1809 if (error->code == GOT_ERR_NOT_REF) {
1810 error = NULL;
1811 continue;
1813 goto done;
1816 error = create_symref(refname, target_ref, verbosity, repo);
1817 got_ref_close(target_ref);
1818 if (error)
1819 goto done;
1821 if (mirror_references)
1822 continue;
1824 if (strncmp("refs/heads/", target, 11) != 0)
1825 continue;
1827 if (asprintf(&remote_refname,
1828 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1829 refname) == -1) {
1830 error = got_error_from_errno("asprintf");
1831 goto done;
1833 if (asprintf(&remote_target,
1834 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1835 target + 11) == -1) {
1836 error = got_error_from_errno("asprintf");
1837 free(remote_refname);
1838 goto done;
1840 error = got_ref_open(&target_ref, repo, remote_target, 0);
1841 if (error) {
1842 free(remote_refname);
1843 free(remote_target);
1844 if (error->code == GOT_ERR_NOT_REF) {
1845 error = NULL;
1846 continue;
1848 goto done;
1850 error = create_symref(remote_refname, target_ref,
1851 verbosity - 1, repo);
1852 free(remote_refname);
1853 free(remote_target);
1854 got_ref_close(target_ref);
1855 if (error)
1856 goto done;
1858 if (pe == NULL) {
1860 * We failed to set the HEAD reference. If we asked for
1861 * a set of wanted branches use the first of one of those
1862 * which could be fetched instead.
1864 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1865 const char *target = pe->path;
1866 struct got_reference *target_ref;
1868 error = got_ref_open(&target_ref, repo, target, 0);
1869 if (error) {
1870 if (error->code == GOT_ERR_NOT_REF) {
1871 error = NULL;
1872 continue;
1874 goto done;
1877 error = create_symref(GOT_REF_HEAD, target_ref,
1878 verbosity, repo);
1879 got_ref_close(target_ref);
1880 if (error)
1881 goto done;
1882 break;
1885 if (!fpa.configs_created && pe != NULL) {
1886 error = create_config_files(fpa.config_info.proto,
1887 fpa.config_info.host, fpa.config_info.port,
1888 fpa.config_info.remote_repo_path,
1889 fpa.config_info.git_url,
1890 fpa.config_info.fetch_all_branches,
1891 fpa.config_info.mirror_references,
1892 fpa.config_info.symrefs,
1893 fpa.config_info.wanted_branches,
1894 fpa.config_info.wanted_refs, fpa.repo);
1895 if (error)
1896 goto done;
1900 if (verbosity >= 0)
1901 printf("Created %s repository '%s'\n",
1902 mirror_references ? "mirrored" : "cloned", repo_path);
1903 done:
1904 if (pack_fds) {
1905 const struct got_error *pack_err =
1906 got_repo_pack_fds_close(pack_fds);
1907 if (error == NULL)
1908 error = pack_err;
1910 if (fetchpid > 0) {
1911 if (kill(fetchpid, SIGTERM) == -1)
1912 error = got_error_from_errno("kill");
1913 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1914 error = got_error_from_errno("waitpid");
1916 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1917 error = got_error_from_errno("close");
1918 if (repo) {
1919 const struct got_error *close_err = got_repo_close(repo);
1920 if (error == NULL)
1921 error = close_err;
1923 TAILQ_FOREACH(pe, &refs, entry) {
1924 free((void *)pe->path);
1925 free(pe->data);
1927 got_pathlist_free(&refs);
1928 TAILQ_FOREACH(pe, &symrefs, entry) {
1929 free((void *)pe->path);
1930 free(pe->data);
1932 got_pathlist_free(&symrefs);
1933 got_pathlist_free(&wanted_branches);
1934 got_pathlist_free(&wanted_refs);
1935 free(pack_hash);
1936 free(proto);
1937 free(host);
1938 free(port);
1939 free(server_path);
1940 free(repo_name);
1941 free(default_destdir);
1942 free(git_url);
1943 return error;
1946 static const struct got_error *
1947 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1948 int replace_tags, int verbosity, struct got_repository *repo)
1950 const struct got_error *err = NULL;
1951 char *new_id_str = NULL;
1952 struct got_object_id *old_id = NULL;
1954 err = got_object_id_str(&new_id_str, new_id);
1955 if (err)
1956 goto done;
1958 if (!replace_tags &&
1959 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1960 err = got_ref_resolve(&old_id, repo, ref);
1961 if (err)
1962 goto done;
1963 if (got_object_id_cmp(old_id, new_id) == 0)
1964 goto done;
1965 if (verbosity >= 0) {
1966 printf("Rejecting update of existing tag %s: %s\n",
1967 got_ref_get_name(ref), new_id_str);
1969 goto done;
1972 if (got_ref_is_symbolic(ref)) {
1973 if (verbosity >= 0) {
1974 printf("Replacing reference %s: %s\n",
1975 got_ref_get_name(ref),
1976 got_ref_get_symref_target(ref));
1978 err = got_ref_change_symref_to_ref(ref, new_id);
1979 if (err)
1980 goto done;
1981 err = got_ref_write(ref, repo);
1982 if (err)
1983 goto done;
1984 } else {
1985 err = got_ref_resolve(&old_id, repo, ref);
1986 if (err)
1987 goto done;
1988 if (got_object_id_cmp(old_id, new_id) == 0)
1989 goto done;
1991 err = got_ref_change_ref(ref, new_id);
1992 if (err)
1993 goto done;
1994 err = got_ref_write(ref, repo);
1995 if (err)
1996 goto done;
1999 if (verbosity >= 0)
2000 printf("Updated %s: %s\n", got_ref_get_name(ref),
2001 new_id_str);
2002 done:
2003 free(old_id);
2004 free(new_id_str);
2005 return err;
2008 static const struct got_error *
2009 update_symref(const char *refname, struct got_reference *target_ref,
2010 int verbosity, struct got_repository *repo)
2012 const struct got_error *err = NULL, *unlock_err;
2013 struct got_reference *symref;
2014 int symref_is_locked = 0;
2016 err = got_ref_open(&symref, repo, refname, 1);
2017 if (err) {
2018 if (err->code != GOT_ERR_NOT_REF)
2019 return err;
2020 err = got_ref_alloc_symref(&symref, refname, target_ref);
2021 if (err)
2022 goto done;
2024 err = got_ref_write(symref, repo);
2025 if (err)
2026 goto done;
2028 if (verbosity >= 0)
2029 printf("Created reference %s: %s\n",
2030 got_ref_get_name(symref),
2031 got_ref_get_symref_target(symref));
2032 } else {
2033 symref_is_locked = 1;
2035 if (strcmp(got_ref_get_symref_target(symref),
2036 got_ref_get_name(target_ref)) == 0)
2037 goto done;
2039 err = got_ref_change_symref(symref,
2040 got_ref_get_name(target_ref));
2041 if (err)
2042 goto done;
2044 err = got_ref_write(symref, repo);
2045 if (err)
2046 goto done;
2048 if (verbosity >= 0)
2049 printf("Updated %s: %s\n", got_ref_get_name(symref),
2050 got_ref_get_symref_target(symref));
2053 done:
2054 if (symref_is_locked) {
2055 unlock_err = got_ref_unlock(symref);
2056 if (unlock_err && err == NULL)
2057 err = unlock_err;
2059 got_ref_close(symref);
2060 return err;
2063 __dead static void
2064 usage_fetch(void)
2066 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2067 "[-R reference] [-r repository-path] [remote-repository]\n",
2068 getprogname());
2069 exit(1);
2072 static const struct got_error *
2073 delete_missing_ref(struct got_reference *ref,
2074 int verbosity, struct got_repository *repo)
2076 const struct got_error *err = NULL;
2077 struct got_object_id *id = NULL;
2078 char *id_str = NULL;
2080 if (got_ref_is_symbolic(ref)) {
2081 err = got_ref_delete(ref, repo);
2082 if (err)
2083 return err;
2084 if (verbosity >= 0) {
2085 printf("Deleted %s: %s\n",
2086 got_ref_get_name(ref),
2087 got_ref_get_symref_target(ref));
2089 } else {
2090 err = got_ref_resolve(&id, repo, ref);
2091 if (err)
2092 return err;
2093 err = got_object_id_str(&id_str, id);
2094 if (err)
2095 goto done;
2097 err = got_ref_delete(ref, repo);
2098 if (err)
2099 goto done;
2100 if (verbosity >= 0) {
2101 printf("Deleted %s: %s\n",
2102 got_ref_get_name(ref), id_str);
2105 done:
2106 free(id);
2107 free(id_str);
2108 return NULL;
2111 static const struct got_error *
2112 delete_missing_refs(struct got_pathlist_head *their_refs,
2113 struct got_pathlist_head *their_symrefs,
2114 const struct got_remote_repo *remote,
2115 int verbosity, struct got_repository *repo)
2117 const struct got_error *err = NULL, *unlock_err;
2118 struct got_reflist_head my_refs;
2119 struct got_reflist_entry *re;
2120 struct got_pathlist_entry *pe;
2121 char *remote_namespace = NULL;
2122 char *local_refname = NULL;
2124 TAILQ_INIT(&my_refs);
2126 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2127 == -1)
2128 return got_error_from_errno("asprintf");
2130 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2131 if (err)
2132 goto done;
2134 TAILQ_FOREACH(re, &my_refs, entry) {
2135 const char *refname = got_ref_get_name(re->ref);
2136 const char *their_refname;
2138 if (remote->mirror_references) {
2139 their_refname = refname;
2140 } else {
2141 if (strncmp(refname, remote_namespace,
2142 strlen(remote_namespace)) == 0) {
2143 if (strcmp(refname + strlen(remote_namespace),
2144 GOT_REF_HEAD) == 0)
2145 continue;
2146 if (asprintf(&local_refname, "refs/heads/%s",
2147 refname + strlen(remote_namespace)) == -1) {
2148 err = got_error_from_errno("asprintf");
2149 goto done;
2151 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2152 continue;
2154 their_refname = local_refname;
2157 TAILQ_FOREACH(pe, their_refs, entry) {
2158 if (strcmp(their_refname, pe->path) == 0)
2159 break;
2161 if (pe != NULL)
2162 continue;
2164 TAILQ_FOREACH(pe, their_symrefs, entry) {
2165 if (strcmp(their_refname, pe->path) == 0)
2166 break;
2168 if (pe != NULL)
2169 continue;
2171 err = delete_missing_ref(re->ref, verbosity, repo);
2172 if (err)
2173 break;
2175 if (local_refname) {
2176 struct got_reference *ref;
2177 err = got_ref_open(&ref, repo, local_refname, 1);
2178 if (err) {
2179 if (err->code != GOT_ERR_NOT_REF)
2180 break;
2181 free(local_refname);
2182 local_refname = NULL;
2183 continue;
2185 err = delete_missing_ref(ref, verbosity, repo);
2186 if (err)
2187 break;
2188 unlock_err = got_ref_unlock(ref);
2189 got_ref_close(ref);
2190 if (unlock_err && err == NULL) {
2191 err = unlock_err;
2192 break;
2195 free(local_refname);
2196 local_refname = NULL;
2199 done:
2200 got_ref_list_free(&my_refs);
2201 free(remote_namespace);
2202 free(local_refname);
2203 return err;
2206 static const struct got_error *
2207 update_wanted_ref(const char *refname, struct got_object_id *id,
2208 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2210 const struct got_error *err, *unlock_err;
2211 char *remote_refname;
2212 struct got_reference *ref;
2214 if (strncmp("refs/", refname, 5) == 0)
2215 refname += 5;
2217 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2218 remote_repo_name, refname) == -1)
2219 return got_error_from_errno("asprintf");
2221 err = got_ref_open(&ref, repo, remote_refname, 1);
2222 if (err) {
2223 if (err->code != GOT_ERR_NOT_REF)
2224 goto done;
2225 err = create_ref(remote_refname, id, verbosity, repo);
2226 } else {
2227 err = update_ref(ref, id, 0, verbosity, repo);
2228 unlock_err = got_ref_unlock(ref);
2229 if (unlock_err && err == NULL)
2230 err = unlock_err;
2231 got_ref_close(ref);
2233 done:
2234 free(remote_refname);
2235 return err;
2238 static const struct got_error *
2239 delete_ref(struct got_repository *repo, struct got_reference *ref)
2241 const struct got_error *err = NULL;
2242 struct got_object_id *id = NULL;
2243 char *id_str = NULL;
2244 const char *target;
2246 if (got_ref_is_symbolic(ref)) {
2247 target = got_ref_get_symref_target(ref);
2248 } else {
2249 err = got_ref_resolve(&id, repo, ref);
2250 if (err)
2251 goto done;
2252 err = got_object_id_str(&id_str, id);
2253 if (err)
2254 goto done;
2255 target = id_str;
2258 err = got_ref_delete(ref, repo);
2259 if (err)
2260 goto done;
2262 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2263 done:
2264 free(id);
2265 free(id_str);
2266 return err;
2269 static const struct got_error *
2270 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2272 const struct got_error *err = NULL;
2273 struct got_reflist_head refs;
2274 struct got_reflist_entry *re;
2275 char *prefix;
2277 TAILQ_INIT(&refs);
2279 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2280 err = got_error_from_errno("asprintf");
2281 goto done;
2283 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2284 if (err)
2285 goto done;
2287 TAILQ_FOREACH(re, &refs, entry)
2288 delete_ref(repo, re->ref);
2289 done:
2290 got_ref_list_free(&refs);
2291 return err;
2294 static const struct got_error *
2295 cmd_fetch(int argc, char *argv[])
2297 const struct got_error *error = NULL, *unlock_err;
2298 char *cwd = NULL, *repo_path = NULL;
2299 const char *remote_name;
2300 char *proto = NULL, *host = NULL, *port = NULL;
2301 char *repo_name = NULL, *server_path = NULL;
2302 const struct got_remote_repo *remotes, *remote = NULL;
2303 int nremotes;
2304 char *id_str = NULL;
2305 struct got_repository *repo = NULL;
2306 struct got_worktree *worktree = NULL;
2307 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2308 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2309 struct got_pathlist_entry *pe;
2310 struct got_object_id *pack_hash = NULL;
2311 int i, ch, fetchfd = -1, fetchstatus;
2312 pid_t fetchpid = -1;
2313 struct got_fetch_progress_arg fpa;
2314 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2315 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2316 int *pack_fds = NULL;
2318 TAILQ_INIT(&refs);
2319 TAILQ_INIT(&symrefs);
2320 TAILQ_INIT(&wanted_branches);
2321 TAILQ_INIT(&wanted_refs);
2323 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2324 switch (ch) {
2325 case 'a':
2326 fetch_all_branches = 1;
2327 break;
2328 case 'b':
2329 error = got_pathlist_append(&wanted_branches,
2330 optarg, NULL);
2331 if (error)
2332 return error;
2333 break;
2334 case 'd':
2335 delete_refs = 1;
2336 break;
2337 case 'l':
2338 list_refs_only = 1;
2339 break;
2340 case 'q':
2341 verbosity = -1;
2342 break;
2343 case 'R':
2344 error = got_pathlist_append(&wanted_refs,
2345 optarg, NULL);
2346 if (error)
2347 return error;
2348 break;
2349 case 'r':
2350 repo_path = realpath(optarg, NULL);
2351 if (repo_path == NULL)
2352 return got_error_from_errno2("realpath",
2353 optarg);
2354 got_path_strip_trailing_slashes(repo_path);
2355 break;
2356 case 't':
2357 replace_tags = 1;
2358 break;
2359 case 'v':
2360 if (verbosity < 0)
2361 verbosity = 0;
2362 else if (verbosity < 3)
2363 verbosity++;
2364 break;
2365 case 'X':
2366 delete_remote = 1;
2367 break;
2368 default:
2369 usage_fetch();
2370 break;
2373 argc -= optind;
2374 argv += optind;
2376 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2377 option_conflict('a', 'b');
2378 if (list_refs_only) {
2379 if (!TAILQ_EMPTY(&wanted_branches))
2380 option_conflict('l', 'b');
2381 if (fetch_all_branches)
2382 option_conflict('l', 'a');
2383 if (delete_refs)
2384 option_conflict('l', 'd');
2385 if (delete_remote)
2386 option_conflict('l', 'X');
2388 if (delete_remote) {
2389 if (fetch_all_branches)
2390 option_conflict('X', 'a');
2391 if (!TAILQ_EMPTY(&wanted_branches))
2392 option_conflict('X', 'b');
2393 if (delete_refs)
2394 option_conflict('X', 'd');
2395 if (replace_tags)
2396 option_conflict('X', 't');
2397 if (!TAILQ_EMPTY(&wanted_refs))
2398 option_conflict('X', 'R');
2401 if (argc == 0) {
2402 if (delete_remote)
2403 errx(1, "-X option requires a remote name");
2404 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2405 } else if (argc == 1)
2406 remote_name = argv[0];
2407 else
2408 usage_fetch();
2410 cwd = getcwd(NULL, 0);
2411 if (cwd == NULL) {
2412 error = got_error_from_errno("getcwd");
2413 goto done;
2416 error = got_repo_pack_fds_open(&pack_fds);
2417 if (error != NULL)
2418 goto done;
2420 if (repo_path == NULL) {
2421 error = got_worktree_open(&worktree, cwd);
2422 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2423 goto done;
2424 else
2425 error = NULL;
2426 if (worktree) {
2427 repo_path =
2428 strdup(got_worktree_get_repo_path(worktree));
2429 if (repo_path == NULL)
2430 error = got_error_from_errno("strdup");
2431 if (error)
2432 goto done;
2433 } else {
2434 repo_path = strdup(cwd);
2435 if (repo_path == NULL) {
2436 error = got_error_from_errno("strdup");
2437 goto done;
2442 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2443 if (error)
2444 goto done;
2446 if (delete_remote) {
2447 error = delete_refs_for_remote(repo, remote_name);
2448 goto done; /* nothing else to do */
2451 if (worktree) {
2452 worktree_conf = got_worktree_get_gotconfig(worktree);
2453 if (worktree_conf) {
2454 got_gotconfig_get_remotes(&nremotes, &remotes,
2455 worktree_conf);
2456 for (i = 0; i < nremotes; i++) {
2457 if (strcmp(remotes[i].name, remote_name) == 0) {
2458 remote = &remotes[i];
2459 break;
2464 if (remote == NULL) {
2465 repo_conf = got_repo_get_gotconfig(repo);
2466 if (repo_conf) {
2467 got_gotconfig_get_remotes(&nremotes, &remotes,
2468 repo_conf);
2469 for (i = 0; i < nremotes; i++) {
2470 if (strcmp(remotes[i].name, remote_name) == 0) {
2471 remote = &remotes[i];
2472 break;
2477 if (remote == NULL) {
2478 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2479 for (i = 0; i < nremotes; i++) {
2480 if (strcmp(remotes[i].name, remote_name) == 0) {
2481 remote = &remotes[i];
2482 break;
2486 if (remote == NULL) {
2487 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2488 goto done;
2491 if (TAILQ_EMPTY(&wanted_branches)) {
2492 if (!fetch_all_branches)
2493 fetch_all_branches = remote->fetch_all_branches;
2494 for (i = 0; i < remote->nfetch_branches; i++) {
2495 got_pathlist_append(&wanted_branches,
2496 remote->fetch_branches[i], NULL);
2499 if (TAILQ_EMPTY(&wanted_refs)) {
2500 for (i = 0; i < remote->nfetch_refs; i++) {
2501 got_pathlist_append(&wanted_refs,
2502 remote->fetch_refs[i], NULL);
2506 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2507 &repo_name, remote->fetch_url);
2508 if (error)
2509 goto done;
2511 if (strcmp(proto, "git") == 0) {
2512 #ifndef PROFILE
2513 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2514 "sendfd dns inet unveil", NULL) == -1)
2515 err(1, "pledge");
2516 #endif
2517 } else if (strcmp(proto, "git+ssh") == 0 ||
2518 strcmp(proto, "ssh") == 0) {
2519 #ifndef PROFILE
2520 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2521 "sendfd unveil", NULL) == -1)
2522 err(1, "pledge");
2523 #endif
2524 } else if (strcmp(proto, "http") == 0 ||
2525 strcmp(proto, "git+http") == 0) {
2526 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2527 goto done;
2528 } else {
2529 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2530 goto done;
2533 error = got_dial_apply_unveil(proto);
2534 if (error)
2535 goto done;
2537 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2538 if (error)
2539 goto done;
2541 if (verbosity >= 0)
2542 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2543 port ? ":" : "", port ? port : "");
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 fpa.last_scaled_size[0] = '\0';
2551 fpa.last_p_indexed = -1;
2552 fpa.last_p_resolved = -1;
2553 fpa.verbosity = verbosity;
2554 fpa.repo = repo;
2555 fpa.create_configs = 0;
2556 fpa.configs_created = 0;
2557 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2558 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2559 remote->mirror_references, fetch_all_branches, &wanted_branches,
2560 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2561 fetch_progress, &fpa);
2562 if (error)
2563 goto done;
2565 if (list_refs_only) {
2566 error = list_remote_refs(&symrefs, &refs);
2567 goto done;
2570 if (pack_hash == NULL) {
2571 if (verbosity >= 0)
2572 printf("Already up-to-date\n");
2573 } else if (verbosity >= 0) {
2574 error = got_object_id_str(&id_str, pack_hash);
2575 if (error)
2576 goto done;
2577 printf("\nFetched %s.pack\n", id_str);
2578 free(id_str);
2579 id_str = NULL;
2582 /* Update references provided with the pack file. */
2583 TAILQ_FOREACH(pe, &refs, entry) {
2584 const char *refname = pe->path;
2585 struct got_object_id *id = pe->data;
2586 struct got_reference *ref;
2587 char *remote_refname;
2589 if (is_wanted_ref(&wanted_refs, refname) &&
2590 !remote->mirror_references) {
2591 error = update_wanted_ref(refname, id,
2592 remote->name, verbosity, repo);
2593 if (error)
2594 goto done;
2595 continue;
2598 if (remote->mirror_references ||
2599 strncmp("refs/tags/", refname, 10) == 0) {
2600 error = got_ref_open(&ref, repo, refname, 1);
2601 if (error) {
2602 if (error->code != GOT_ERR_NOT_REF)
2603 goto done;
2604 error = create_ref(refname, id, verbosity,
2605 repo);
2606 if (error)
2607 goto done;
2608 } else {
2609 error = update_ref(ref, id, replace_tags,
2610 verbosity, repo);
2611 unlock_err = got_ref_unlock(ref);
2612 if (unlock_err && error == NULL)
2613 error = unlock_err;
2614 got_ref_close(ref);
2615 if (error)
2616 goto done;
2618 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2619 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2620 remote_name, refname + 11) == -1) {
2621 error = got_error_from_errno("asprintf");
2622 goto done;
2625 error = got_ref_open(&ref, repo, remote_refname, 1);
2626 if (error) {
2627 if (error->code != GOT_ERR_NOT_REF)
2628 goto done;
2629 error = create_ref(remote_refname, id,
2630 verbosity, repo);
2631 if (error)
2632 goto done;
2633 } else {
2634 error = update_ref(ref, id, replace_tags,
2635 verbosity, repo);
2636 unlock_err = got_ref_unlock(ref);
2637 if (unlock_err && error == NULL)
2638 error = unlock_err;
2639 got_ref_close(ref);
2640 if (error)
2641 goto done;
2644 /* Also create a local branch if none exists yet. */
2645 error = got_ref_open(&ref, repo, refname, 1);
2646 if (error) {
2647 if (error->code != GOT_ERR_NOT_REF)
2648 goto done;
2649 error = create_ref(refname, id, verbosity,
2650 repo);
2651 if (error)
2652 goto done;
2653 } else {
2654 unlock_err = got_ref_unlock(ref);
2655 if (unlock_err && error == NULL)
2656 error = unlock_err;
2657 got_ref_close(ref);
2661 if (delete_refs) {
2662 error = delete_missing_refs(&refs, &symrefs, remote,
2663 verbosity, repo);
2664 if (error)
2665 goto done;
2668 if (!remote->mirror_references) {
2669 /* Update remote HEAD reference if the server provided one. */
2670 TAILQ_FOREACH(pe, &symrefs, entry) {
2671 struct got_reference *target_ref;
2672 const char *refname = pe->path;
2673 const char *target = pe->data;
2674 char *remote_refname = NULL, *remote_target = NULL;
2676 if (strcmp(refname, GOT_REF_HEAD) != 0)
2677 continue;
2679 if (strncmp("refs/heads/", target, 11) != 0)
2680 continue;
2682 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2683 remote->name, refname) == -1) {
2684 error = got_error_from_errno("asprintf");
2685 goto done;
2687 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2688 remote->name, target + 11) == -1) {
2689 error = got_error_from_errno("asprintf");
2690 free(remote_refname);
2691 goto done;
2694 error = got_ref_open(&target_ref, repo, remote_target,
2695 0);
2696 if (error) {
2697 free(remote_refname);
2698 free(remote_target);
2699 if (error->code == GOT_ERR_NOT_REF) {
2700 error = NULL;
2701 continue;
2703 goto done;
2705 error = update_symref(remote_refname, target_ref,
2706 verbosity, repo);
2707 free(remote_refname);
2708 free(remote_target);
2709 got_ref_close(target_ref);
2710 if (error)
2711 goto done;
2714 done:
2715 if (fetchpid > 0) {
2716 if (kill(fetchpid, SIGTERM) == -1)
2717 error = got_error_from_errno("kill");
2718 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2719 error = got_error_from_errno("waitpid");
2721 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2722 error = got_error_from_errno("close");
2723 if (repo) {
2724 const struct got_error *close_err = got_repo_close(repo);
2725 if (error == NULL)
2726 error = close_err;
2728 if (worktree)
2729 got_worktree_close(worktree);
2730 if (pack_fds) {
2731 const struct got_error *pack_err =
2732 got_repo_pack_fds_close(pack_fds);
2733 if (error == NULL)
2734 error = pack_err;
2736 TAILQ_FOREACH(pe, &refs, entry) {
2737 free((void *)pe->path);
2738 free(pe->data);
2740 got_pathlist_free(&refs);
2741 TAILQ_FOREACH(pe, &symrefs, entry) {
2742 free((void *)pe->path);
2743 free(pe->data);
2745 got_pathlist_free(&symrefs);
2746 got_pathlist_free(&wanted_branches);
2747 got_pathlist_free(&wanted_refs);
2748 free(id_str);
2749 free(cwd);
2750 free(repo_path);
2751 free(pack_hash);
2752 free(proto);
2753 free(host);
2754 free(port);
2755 free(server_path);
2756 free(repo_name);
2757 return error;
2761 __dead static void
2762 usage_checkout(void)
2764 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2765 "[-p path-prefix] repository-path [work-tree-path]\n",
2766 getprogname());
2767 exit(1);
2770 static void
2771 show_worktree_base_ref_warning(void)
2773 fprintf(stderr, "%s: warning: could not create a reference "
2774 "to the work tree's base commit; the commit could be "
2775 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2776 "repository writable and running 'got update' will prevent this\n",
2777 getprogname());
2780 struct got_checkout_progress_arg {
2781 const char *worktree_path;
2782 int had_base_commit_ref_error;
2783 int verbosity;
2786 static const struct got_error *
2787 checkout_progress(void *arg, unsigned char status, const char *path)
2789 struct got_checkout_progress_arg *a = arg;
2791 /* Base commit bump happens silently. */
2792 if (status == GOT_STATUS_BUMP_BASE)
2793 return NULL;
2795 if (status == GOT_STATUS_BASE_REF_ERR) {
2796 a->had_base_commit_ref_error = 1;
2797 return NULL;
2800 while (path[0] == '/')
2801 path++;
2803 if (a->verbosity >= 0)
2804 printf("%c %s/%s\n", status, a->worktree_path, path);
2806 return NULL;
2809 static const struct got_error *
2810 check_cancelled(void *arg)
2812 if (sigint_received || sigpipe_received)
2813 return got_error(GOT_ERR_CANCELLED);
2814 return NULL;
2817 static const struct got_error *
2818 check_linear_ancestry(struct got_object_id *commit_id,
2819 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2820 struct got_repository *repo)
2822 const struct got_error *err = NULL;
2823 struct got_object_id *yca_id;
2825 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2826 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2827 if (err)
2828 return err;
2830 if (yca_id == NULL)
2831 return got_error(GOT_ERR_ANCESTRY);
2834 * Require a straight line of history between the target commit
2835 * and the work tree's base commit.
2837 * Non-linear situations such as this require a rebase:
2839 * (commit) D F (base_commit)
2840 * \ /
2841 * C E
2842 * \ /
2843 * B (yca)
2844 * |
2845 * A
2847 * 'got update' only handles linear cases:
2848 * Update forwards in time: A (base/yca) - B - C - D (commit)
2849 * Update backwards in time: D (base) - C - B - A (commit/yca)
2851 if (allow_forwards_in_time_only) {
2852 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2853 return got_error(GOT_ERR_ANCESTRY);
2854 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2855 got_object_id_cmp(base_commit_id, yca_id) != 0)
2856 return got_error(GOT_ERR_ANCESTRY);
2858 free(yca_id);
2859 return NULL;
2862 static const struct got_error *
2863 check_same_branch(struct got_object_id *commit_id,
2864 struct got_reference *head_ref, struct got_object_id *yca_id,
2865 struct got_repository *repo)
2867 const struct got_error *err = NULL;
2868 struct got_commit_graph *graph = NULL;
2869 struct got_object_id *head_commit_id = NULL;
2870 int is_same_branch = 0;
2872 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2873 if (err)
2874 goto done;
2876 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2877 is_same_branch = 1;
2878 goto done;
2880 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2881 is_same_branch = 1;
2882 goto done;
2885 err = got_commit_graph_open(&graph, "/", 1);
2886 if (err)
2887 goto done;
2889 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2890 check_cancelled, NULL);
2891 if (err)
2892 goto done;
2894 for (;;) {
2895 struct got_object_id id;
2897 err = got_commit_graph_iter_next(&id, graph, repo,
2898 check_cancelled, NULL);
2899 if (err) {
2900 if (err->code == GOT_ERR_ITER_COMPLETED)
2901 err = NULL;
2902 break;
2905 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2906 break;
2907 if (got_object_id_cmp(&id, commit_id) == 0) {
2908 is_same_branch = 1;
2909 break;
2912 done:
2913 if (graph)
2914 got_commit_graph_close(graph);
2915 free(head_commit_id);
2916 if (!err && !is_same_branch)
2917 err = got_error(GOT_ERR_ANCESTRY);
2918 return err;
2921 static const struct got_error *
2922 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2924 static char msg[512];
2925 const char *branch_name;
2927 if (got_ref_is_symbolic(ref))
2928 branch_name = got_ref_get_symref_target(ref);
2929 else
2930 branch_name = got_ref_get_name(ref);
2932 if (strncmp("refs/heads/", branch_name, 11) == 0)
2933 branch_name += 11;
2935 snprintf(msg, sizeof(msg),
2936 "target commit is not contained in branch '%s'; "
2937 "the branch to use must be specified with -b; "
2938 "if necessary a new branch can be created for "
2939 "this commit with 'got branch -c %s BRANCH_NAME'",
2940 branch_name, commit_id_str);
2942 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2945 static const struct got_error *
2946 cmd_checkout(int argc, char *argv[])
2948 const struct got_error *error = NULL;
2949 struct got_repository *repo = NULL;
2950 struct got_reference *head_ref = NULL, *ref = NULL;
2951 struct got_worktree *worktree = NULL;
2952 char *repo_path = NULL;
2953 char *worktree_path = NULL;
2954 const char *path_prefix = "";
2955 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2956 char *commit_id_str = NULL;
2957 struct got_object_id *commit_id = NULL;
2958 char *cwd = NULL;
2959 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2960 struct got_pathlist_head paths;
2961 struct got_checkout_progress_arg cpa;
2962 int *pack_fds = NULL;
2964 TAILQ_INIT(&paths);
2966 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2967 switch (ch) {
2968 case 'b':
2969 branch_name = optarg;
2970 break;
2971 case 'c':
2972 commit_id_str = strdup(optarg);
2973 if (commit_id_str == NULL)
2974 return got_error_from_errno("strdup");
2975 break;
2976 case 'E':
2977 allow_nonempty = 1;
2978 break;
2979 case 'p':
2980 path_prefix = optarg;
2981 break;
2982 case 'q':
2983 verbosity = -1;
2984 break;
2985 default:
2986 usage_checkout();
2987 /* NOTREACHED */
2991 argc -= optind;
2992 argv += optind;
2994 #ifndef PROFILE
2995 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2996 "unveil", NULL) == -1)
2997 err(1, "pledge");
2998 #endif
2999 if (argc == 1) {
3000 char *base, *dotgit;
3001 const char *path;
3002 repo_path = realpath(argv[0], NULL);
3003 if (repo_path == NULL)
3004 return got_error_from_errno2("realpath", argv[0]);
3005 cwd = getcwd(NULL, 0);
3006 if (cwd == NULL) {
3007 error = got_error_from_errno("getcwd");
3008 goto done;
3010 if (path_prefix[0])
3011 path = path_prefix;
3012 else
3013 path = repo_path;
3014 error = got_path_basename(&base, path);
3015 if (error)
3016 goto done;
3017 dotgit = strstr(base, ".git");
3018 if (dotgit)
3019 *dotgit = '\0';
3020 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3021 error = got_error_from_errno("asprintf");
3022 free(base);
3023 goto done;
3025 free(base);
3026 } else if (argc == 2) {
3027 repo_path = realpath(argv[0], NULL);
3028 if (repo_path == NULL) {
3029 error = got_error_from_errno2("realpath", argv[0]);
3030 goto done;
3032 worktree_path = realpath(argv[1], NULL);
3033 if (worktree_path == NULL) {
3034 if (errno != ENOENT) {
3035 error = got_error_from_errno2("realpath",
3036 argv[1]);
3037 goto done;
3039 worktree_path = strdup(argv[1]);
3040 if (worktree_path == NULL) {
3041 error = got_error_from_errno("strdup");
3042 goto done;
3045 } else
3046 usage_checkout();
3048 got_path_strip_trailing_slashes(repo_path);
3049 got_path_strip_trailing_slashes(worktree_path);
3051 error = got_repo_pack_fds_open(&pack_fds);
3052 if (error != NULL)
3053 goto done;
3055 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3056 if (error != NULL)
3057 goto done;
3059 /* Pre-create work tree path for unveil(2) */
3060 error = got_path_mkdir(worktree_path);
3061 if (error) {
3062 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3063 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3064 goto done;
3065 if (!allow_nonempty &&
3066 !got_path_dir_is_empty(worktree_path)) {
3067 error = got_error_path(worktree_path,
3068 GOT_ERR_DIR_NOT_EMPTY);
3069 goto done;
3073 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3074 if (error)
3075 goto done;
3077 error = got_ref_open(&head_ref, repo, branch_name, 0);
3078 if (error != NULL)
3079 goto done;
3081 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3082 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3083 goto done;
3085 error = got_worktree_open(&worktree, worktree_path);
3086 if (error != NULL)
3087 goto done;
3089 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3090 path_prefix);
3091 if (error != NULL)
3092 goto done;
3093 if (!same_path_prefix) {
3094 error = got_error(GOT_ERR_PATH_PREFIX);
3095 goto done;
3098 if (commit_id_str) {
3099 struct got_reflist_head refs;
3100 TAILQ_INIT(&refs);
3101 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3102 NULL);
3103 if (error)
3104 goto done;
3105 error = got_repo_match_object_id(&commit_id, NULL,
3106 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3107 got_ref_list_free(&refs);
3108 if (error)
3109 goto done;
3110 error = check_linear_ancestry(commit_id,
3111 got_worktree_get_base_commit_id(worktree), 0, repo);
3112 if (error != NULL) {
3113 if (error->code == GOT_ERR_ANCESTRY) {
3114 error = checkout_ancestry_error(
3115 head_ref, commit_id_str);
3117 goto done;
3119 error = check_same_branch(commit_id, head_ref, NULL, repo);
3120 if (error) {
3121 if (error->code == GOT_ERR_ANCESTRY) {
3122 error = checkout_ancestry_error(
3123 head_ref, commit_id_str);
3125 goto done;
3127 error = got_worktree_set_base_commit_id(worktree, repo,
3128 commit_id);
3129 if (error)
3130 goto done;
3131 /* Expand potentially abbreviated commit ID string. */
3132 free(commit_id_str);
3133 error = got_object_id_str(&commit_id_str, commit_id);
3134 if (error)
3135 goto done;
3136 } else {
3137 commit_id = got_object_id_dup(
3138 got_worktree_get_base_commit_id(worktree));
3139 if (commit_id == NULL) {
3140 error = got_error_from_errno("got_object_id_dup");
3141 goto done;
3143 error = got_object_id_str(&commit_id_str, commit_id);
3144 if (error)
3145 goto done;
3148 error = got_pathlist_append(&paths, "", NULL);
3149 if (error)
3150 goto done;
3151 cpa.worktree_path = worktree_path;
3152 cpa.had_base_commit_ref_error = 0;
3153 cpa.verbosity = verbosity;
3154 error = got_worktree_checkout_files(worktree, &paths, repo,
3155 checkout_progress, &cpa, check_cancelled, NULL);
3156 if (error != NULL)
3157 goto done;
3159 if (got_ref_is_symbolic(head_ref)) {
3160 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3161 if (error)
3162 goto done;
3163 refname = got_ref_get_name(ref);
3164 } else
3165 refname = got_ref_get_name(head_ref);
3166 printf("Checked out %s: %s\n", refname, commit_id_str);
3167 printf("Now shut up and hack\n");
3168 if (cpa.had_base_commit_ref_error)
3169 show_worktree_base_ref_warning();
3170 done:
3171 if (pack_fds) {
3172 const struct got_error *pack_err =
3173 got_repo_pack_fds_close(pack_fds);
3174 if (error == NULL)
3175 error = pack_err;
3177 if (head_ref)
3178 got_ref_close(head_ref);
3179 if (ref)
3180 got_ref_close(ref);
3181 got_pathlist_free(&paths);
3182 free(commit_id_str);
3183 free(commit_id);
3184 free(repo_path);
3185 free(worktree_path);
3186 free(cwd);
3187 return error;
3190 struct got_update_progress_arg {
3191 int did_something;
3192 int conflicts;
3193 int obstructed;
3194 int not_updated;
3195 int missing;
3196 int not_deleted;
3197 int unversioned;
3198 int verbosity;
3201 static void
3202 print_update_progress_stats(struct got_update_progress_arg *upa)
3204 if (!upa->did_something)
3205 return;
3207 if (upa->conflicts > 0)
3208 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3209 if (upa->obstructed > 0)
3210 printf("File paths obstructed by a non-regular file: %d\n",
3211 upa->obstructed);
3212 if (upa->not_updated > 0)
3213 printf("Files not updated because of existing merge "
3214 "conflicts: %d\n", upa->not_updated);
3218 * The meaning of some status codes differs between merge-style operations and
3219 * update operations. For example, the ! status code means "file was missing"
3220 * if changes were merged into the work tree, and "missing file was restored"
3221 * if the work tree was updated. This function should be used by any operation
3222 * which merges changes into the work tree without updating the work tree.
3224 static void
3225 print_merge_progress_stats(struct got_update_progress_arg *upa)
3227 if (!upa->did_something)
3228 return;
3230 if (upa->conflicts > 0)
3231 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3232 if (upa->obstructed > 0)
3233 printf("File paths obstructed by a non-regular file: %d\n",
3234 upa->obstructed);
3235 if (upa->missing > 0)
3236 printf("Files which had incoming changes but could not be "
3237 "found in the work tree: %d\n", upa->missing);
3238 if (upa->not_deleted > 0)
3239 printf("Files not deleted due to differences in deleted "
3240 "content: %d\n", upa->not_deleted);
3241 if (upa->unversioned > 0)
3242 printf("Files not merged because an unversioned file was "
3243 "found in the work tree: %d\n", upa->unversioned);
3246 __dead static void
3247 usage_update(void)
3249 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3250 "[path ...]\n", getprogname());
3251 exit(1);
3254 static const struct got_error *
3255 update_progress(void *arg, unsigned char status, const char *path)
3257 struct got_update_progress_arg *upa = arg;
3259 if (status == GOT_STATUS_EXISTS ||
3260 status == GOT_STATUS_BASE_REF_ERR)
3261 return NULL;
3263 upa->did_something = 1;
3265 /* Base commit bump happens silently. */
3266 if (status == GOT_STATUS_BUMP_BASE)
3267 return NULL;
3269 if (status == GOT_STATUS_CONFLICT)
3270 upa->conflicts++;
3271 if (status == GOT_STATUS_OBSTRUCTED)
3272 upa->obstructed++;
3273 if (status == GOT_STATUS_CANNOT_UPDATE)
3274 upa->not_updated++;
3275 if (status == GOT_STATUS_MISSING)
3276 upa->missing++;
3277 if (status == GOT_STATUS_CANNOT_DELETE)
3278 upa->not_deleted++;
3279 if (status == GOT_STATUS_UNVERSIONED)
3280 upa->unversioned++;
3282 while (path[0] == '/')
3283 path++;
3284 if (upa->verbosity >= 0)
3285 printf("%c %s\n", status, path);
3287 return NULL;
3290 static const struct got_error *
3291 switch_head_ref(struct got_reference *head_ref,
3292 struct got_object_id *commit_id, struct got_worktree *worktree,
3293 struct got_repository *repo)
3295 const struct got_error *err = NULL;
3296 char *base_id_str;
3297 int ref_has_moved = 0;
3299 /* Trivial case: switching between two different references. */
3300 if (strcmp(got_ref_get_name(head_ref),
3301 got_worktree_get_head_ref_name(worktree)) != 0) {
3302 printf("Switching work tree from %s to %s\n",
3303 got_worktree_get_head_ref_name(worktree),
3304 got_ref_get_name(head_ref));
3305 return got_worktree_set_head_ref(worktree, head_ref);
3308 err = check_linear_ancestry(commit_id,
3309 got_worktree_get_base_commit_id(worktree), 0, repo);
3310 if (err) {
3311 if (err->code != GOT_ERR_ANCESTRY)
3312 return err;
3313 ref_has_moved = 1;
3315 if (!ref_has_moved)
3316 return NULL;
3318 /* Switching to a rebased branch with the same reference name. */
3319 err = got_object_id_str(&base_id_str,
3320 got_worktree_get_base_commit_id(worktree));
3321 if (err)
3322 return err;
3323 printf("Reference %s now points at a different branch\n",
3324 got_worktree_get_head_ref_name(worktree));
3325 printf("Switching work tree from %s to %s\n", base_id_str,
3326 got_worktree_get_head_ref_name(worktree));
3327 return NULL;
3330 static const struct got_error *
3331 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3333 const struct got_error *err;
3334 int in_progress;
3336 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3337 if (err)
3338 return err;
3339 if (in_progress)
3340 return got_error(GOT_ERR_REBASING);
3342 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3343 if (err)
3344 return err;
3345 if (in_progress)
3346 return got_error(GOT_ERR_HISTEDIT_BUSY);
3348 return NULL;
3351 static const struct got_error *
3352 check_merge_in_progress(struct got_worktree *worktree,
3353 struct got_repository *repo)
3355 const struct got_error *err;
3356 int in_progress;
3358 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3359 if (err)
3360 return err;
3361 if (in_progress)
3362 return got_error(GOT_ERR_MERGE_BUSY);
3364 return NULL;
3367 static const struct got_error *
3368 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3369 char *argv[], struct got_worktree *worktree)
3371 const struct got_error *err = NULL;
3372 char *path;
3373 struct got_pathlist_entry *new;
3374 int i;
3376 if (argc == 0) {
3377 path = strdup("");
3378 if (path == NULL)
3379 return got_error_from_errno("strdup");
3380 return got_pathlist_append(paths, path, NULL);
3383 for (i = 0; i < argc; i++) {
3384 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3385 if (err)
3386 break;
3387 err = got_pathlist_insert(&new, paths, path, NULL);
3388 if (err || new == NULL /* duplicate */) {
3389 free(path);
3390 if (err)
3391 break;
3395 return err;
3398 static const struct got_error *
3399 wrap_not_worktree_error(const struct got_error *orig_err,
3400 const char *cmdname, const char *path)
3402 const struct got_error *err;
3403 struct got_repository *repo;
3404 static char msg[512];
3405 int *pack_fds = NULL;
3407 err = got_repo_pack_fds_open(&pack_fds);
3408 if (err)
3409 return err;
3411 err = got_repo_open(&repo, path, NULL, pack_fds);
3412 if (err)
3413 return orig_err;
3415 snprintf(msg, sizeof(msg),
3416 "'got %s' needs a work tree in addition to a git repository\n"
3417 "Work trees can be checked out from this Git repository with "
3418 "'got checkout'.\n"
3419 "The got(1) manual page contains more information.", cmdname);
3420 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3421 got_repo_close(repo);
3422 if (pack_fds) {
3423 const struct got_error *pack_err =
3424 got_repo_pack_fds_close(pack_fds);
3425 if (err == NULL)
3426 err = pack_err;
3428 return err;
3431 static const struct got_error *
3432 cmd_update(int argc, char *argv[])
3434 const struct got_error *error = NULL;
3435 struct got_repository *repo = NULL;
3436 struct got_worktree *worktree = NULL;
3437 char *worktree_path = NULL;
3438 struct got_object_id *commit_id = NULL;
3439 char *commit_id_str = NULL;
3440 const char *branch_name = NULL;
3441 struct got_reference *head_ref = NULL;
3442 struct got_pathlist_head paths;
3443 struct got_pathlist_entry *pe;
3444 int ch, verbosity = 0;
3445 struct got_update_progress_arg upa;
3446 int *pack_fds = NULL;
3448 TAILQ_INIT(&paths);
3450 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3451 switch (ch) {
3452 case 'b':
3453 branch_name = optarg;
3454 break;
3455 case 'c':
3456 commit_id_str = strdup(optarg);
3457 if (commit_id_str == NULL)
3458 return got_error_from_errno("strdup");
3459 break;
3460 case 'q':
3461 verbosity = -1;
3462 break;
3463 default:
3464 usage_update();
3465 /* NOTREACHED */
3469 argc -= optind;
3470 argv += optind;
3472 #ifndef PROFILE
3473 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3474 "unveil", NULL) == -1)
3475 err(1, "pledge");
3476 #endif
3477 worktree_path = getcwd(NULL, 0);
3478 if (worktree_path == NULL) {
3479 error = got_error_from_errno("getcwd");
3480 goto done;
3483 error = got_repo_pack_fds_open(&pack_fds);
3484 if (error != NULL)
3485 goto done;
3487 error = got_worktree_open(&worktree, worktree_path);
3488 if (error) {
3489 if (error->code == GOT_ERR_NOT_WORKTREE)
3490 error = wrap_not_worktree_error(error, "update",
3491 worktree_path);
3492 goto done;
3495 error = check_rebase_or_histedit_in_progress(worktree);
3496 if (error)
3497 goto done;
3499 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3500 NULL, pack_fds);
3501 if (error != NULL)
3502 goto done;
3504 error = apply_unveil(got_repo_get_path(repo), 0,
3505 got_worktree_get_root_path(worktree));
3506 if (error)
3507 goto done;
3509 error = check_merge_in_progress(worktree, repo);
3510 if (error)
3511 goto done;
3513 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3514 if (error)
3515 goto done;
3517 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3518 got_worktree_get_head_ref_name(worktree), 0);
3519 if (error != NULL)
3520 goto done;
3521 if (commit_id_str == NULL) {
3522 error = got_ref_resolve(&commit_id, repo, head_ref);
3523 if (error != NULL)
3524 goto done;
3525 error = got_object_id_str(&commit_id_str, commit_id);
3526 if (error != NULL)
3527 goto done;
3528 } else {
3529 struct got_reflist_head refs;
3530 TAILQ_INIT(&refs);
3531 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3532 NULL);
3533 if (error)
3534 goto done;
3535 error = got_repo_match_object_id(&commit_id, NULL,
3536 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3537 got_ref_list_free(&refs);
3538 free(commit_id_str);
3539 commit_id_str = NULL;
3540 if (error)
3541 goto done;
3542 error = got_object_id_str(&commit_id_str, commit_id);
3543 if (error)
3544 goto done;
3547 if (branch_name) {
3548 struct got_object_id *head_commit_id;
3549 TAILQ_FOREACH(pe, &paths, entry) {
3550 if (pe->path_len == 0)
3551 continue;
3552 error = got_error_msg(GOT_ERR_BAD_PATH,
3553 "switching between branches requires that "
3554 "the entire work tree gets updated");
3555 goto done;
3557 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3558 if (error)
3559 goto done;
3560 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3561 repo);
3562 free(head_commit_id);
3563 if (error != NULL)
3564 goto done;
3565 error = check_same_branch(commit_id, head_ref, NULL, repo);
3566 if (error)
3567 goto done;
3568 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3569 if (error)
3570 goto done;
3571 } else {
3572 error = check_linear_ancestry(commit_id,
3573 got_worktree_get_base_commit_id(worktree), 0, repo);
3574 if (error != NULL) {
3575 if (error->code == GOT_ERR_ANCESTRY)
3576 error = got_error(GOT_ERR_BRANCH_MOVED);
3577 goto done;
3579 error = check_same_branch(commit_id, head_ref, NULL, repo);
3580 if (error)
3581 goto done;
3584 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3585 commit_id) != 0) {
3586 error = got_worktree_set_base_commit_id(worktree, repo,
3587 commit_id);
3588 if (error)
3589 goto done;
3592 memset(&upa, 0, sizeof(upa));
3593 upa.verbosity = verbosity;
3594 error = got_worktree_checkout_files(worktree, &paths, repo,
3595 update_progress, &upa, check_cancelled, NULL);
3596 if (error != NULL)
3597 goto done;
3599 if (upa.did_something) {
3600 printf("Updated to %s: %s\n",
3601 got_worktree_get_head_ref_name(worktree), commit_id_str);
3602 } else
3603 printf("Already up-to-date\n");
3605 print_update_progress_stats(&upa);
3606 done:
3607 if (pack_fds) {
3608 const struct got_error *pack_err =
3609 got_repo_pack_fds_close(pack_fds);
3610 if (error == NULL)
3611 error = pack_err;
3613 free(worktree_path);
3614 TAILQ_FOREACH(pe, &paths, entry)
3615 free((char *)pe->path);
3616 got_pathlist_free(&paths);
3617 free(commit_id);
3618 free(commit_id_str);
3619 return error;
3622 static const struct got_error *
3623 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3624 const char *path, int diff_context, int ignore_whitespace,
3625 int force_text_diff, struct got_repository *repo, FILE *outfile)
3627 const struct got_error *err = NULL;
3628 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3629 FILE *f1 = NULL, *f2 = NULL;
3630 int fd1 = -1, fd2 = -1;
3632 fd1 = got_opentempfd();
3633 if (fd1 == -1)
3634 return got_error_from_errno("got_opentempfd");
3635 fd2 = got_opentempfd();
3636 if (fd2 == -1) {
3637 err = got_error_from_errno("got_opentempfd");
3638 goto done;
3641 if (blob_id1) {
3642 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3643 fd1);
3644 if (err)
3645 goto done;
3648 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3649 if (err)
3650 goto done;
3652 f1 = got_opentemp();
3653 if (f1 == NULL) {
3654 err = got_error_from_errno("got_opentemp");
3655 goto done;
3657 f2 = got_opentemp();
3658 if (f2 == NULL) {
3659 err = got_error_from_errno("got_opentemp");
3660 goto done;
3663 while (path[0] == '/')
3664 path++;
3665 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3666 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3667 force_text_diff, outfile);
3668 done:
3669 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3670 err = got_error_from_errno("close");
3671 if (blob1)
3672 got_object_blob_close(blob1);
3673 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3674 err = got_error_from_errno("close");
3675 got_object_blob_close(blob2);
3676 if (f1 && fclose(f1) == EOF && err == NULL)
3677 err = got_error_from_errno("fclose");
3678 if (f2 && fclose(f2) == EOF && err == NULL)
3679 err = got_error_from_errno("fclose");
3680 return err;
3683 static const struct got_error *
3684 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3685 const char *path, int diff_context, int ignore_whitespace,
3686 int force_text_diff, struct got_repository *repo, FILE *outfile)
3688 const struct got_error *err = NULL;
3689 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3690 struct got_diff_blob_output_unidiff_arg arg;
3691 FILE *f1 = NULL, *f2 = NULL;
3692 int fd1 = -1, fd2 = -1;
3694 if (tree_id1) {
3695 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3696 if (err)
3697 goto done;
3698 fd1 = got_opentempfd();
3699 if (fd1 == -1) {
3700 err = got_error_from_errno("got_opentempfd");
3701 goto done;
3705 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3706 if (err)
3707 goto done;
3709 f1 = got_opentemp();
3710 if (f1 == NULL) {
3711 err = got_error_from_errno("got_opentemp");
3712 goto done;
3715 f2 = got_opentemp();
3716 if (f2 == NULL) {
3717 err = got_error_from_errno("got_opentemp");
3718 goto done;
3720 fd2 = got_opentempfd();
3721 if (fd2 == -1) {
3722 err = got_error_from_errno("got_opentempfd");
3723 goto done;
3725 arg.diff_context = diff_context;
3726 arg.ignore_whitespace = ignore_whitespace;
3727 arg.force_text_diff = force_text_diff;
3728 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3729 arg.outfile = outfile;
3730 arg.lines = NULL;
3731 arg.nlines = 0;
3732 while (path[0] == '/')
3733 path++;
3734 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3735 got_diff_blob_output_unidiff, &arg, 1);
3736 done:
3737 if (tree1)
3738 got_object_tree_close(tree1);
3739 if (tree2)
3740 got_object_tree_close(tree2);
3741 if (f1 && fclose(f1) == EOF && err == NULL)
3742 err = got_error_from_errno("fclose");
3743 if (f2 && fclose(f2) == EOF && err == NULL)
3744 err = got_error_from_errno("fclose");
3745 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3746 err = got_error_from_errno("close");
3747 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3748 err = got_error_from_errno("close");
3749 return err;
3752 static const struct got_error *
3753 get_changed_paths(struct got_pathlist_head *paths,
3754 struct got_commit_object *commit, struct got_repository *repo)
3756 const struct got_error *err = NULL;
3757 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3758 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3759 struct got_object_qid *qid;
3761 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3762 if (qid != NULL) {
3763 struct got_commit_object *pcommit;
3764 err = got_object_open_as_commit(&pcommit, repo,
3765 &qid->id);
3766 if (err)
3767 return err;
3769 tree_id1 = got_object_id_dup(
3770 got_object_commit_get_tree_id(pcommit));
3771 if (tree_id1 == NULL) {
3772 got_object_commit_close(pcommit);
3773 return got_error_from_errno("got_object_id_dup");
3775 got_object_commit_close(pcommit);
3779 if (tree_id1) {
3780 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3781 if (err)
3782 goto done;
3785 tree_id2 = got_object_commit_get_tree_id(commit);
3786 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3787 if (err)
3788 goto done;
3790 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3791 got_diff_tree_collect_changed_paths, paths, 0);
3792 done:
3793 if (tree1)
3794 got_object_tree_close(tree1);
3795 if (tree2)
3796 got_object_tree_close(tree2);
3797 free(tree_id1);
3798 return err;
3801 static const struct got_error *
3802 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3803 const char *path, int diff_context, struct got_repository *repo,
3804 FILE *outfile)
3806 const struct got_error *err = NULL;
3807 struct got_commit_object *pcommit = NULL;
3808 char *id_str1 = NULL, *id_str2 = NULL;
3809 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3810 struct got_object_qid *qid;
3812 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3813 if (qid != NULL) {
3814 err = got_object_open_as_commit(&pcommit, repo,
3815 &qid->id);
3816 if (err)
3817 return err;
3818 err = got_object_id_str(&id_str1, &qid->id);
3819 if (err)
3820 goto done;
3823 err = got_object_id_str(&id_str2, id);
3824 if (err)
3825 goto done;
3827 if (path && path[0] != '\0') {
3828 int obj_type;
3829 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3830 if (err)
3831 goto done;
3832 if (pcommit) {
3833 err = got_object_id_by_path(&obj_id1, repo,
3834 pcommit, path);
3835 if (err) {
3836 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3837 free(obj_id2);
3838 goto done;
3842 err = got_object_get_type(&obj_type, repo, obj_id2);
3843 if (err) {
3844 free(obj_id2);
3845 goto done;
3847 fprintf(outfile,
3848 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3849 fprintf(outfile, "commit - %s\n",
3850 id_str1 ? id_str1 : "/dev/null");
3851 fprintf(outfile, "commit + %s\n", id_str2);
3852 switch (obj_type) {
3853 case GOT_OBJ_TYPE_BLOB:
3854 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3855 0, 0, repo, outfile);
3856 break;
3857 case GOT_OBJ_TYPE_TREE:
3858 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3859 0, 0, repo, outfile);
3860 break;
3861 default:
3862 err = got_error(GOT_ERR_OBJ_TYPE);
3863 break;
3865 free(obj_id1);
3866 free(obj_id2);
3867 } else {
3868 obj_id2 = got_object_commit_get_tree_id(commit);
3869 if (pcommit)
3870 obj_id1 = got_object_commit_get_tree_id(pcommit);
3871 fprintf(outfile,
3872 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3873 fprintf(outfile, "commit - %s\n",
3874 id_str1 ? id_str1 : "/dev/null");
3875 fprintf(outfile, "commit + %s\n", id_str2);
3876 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3877 repo, outfile);
3879 done:
3880 free(id_str1);
3881 free(id_str2);
3882 if (pcommit)
3883 got_object_commit_close(pcommit);
3884 return err;
3887 static char *
3888 get_datestr(time_t *time, char *datebuf)
3890 struct tm mytm, *tm;
3891 char *p, *s;
3893 tm = gmtime_r(time, &mytm);
3894 if (tm == NULL)
3895 return NULL;
3896 s = asctime_r(tm, datebuf);
3897 if (s == NULL)
3898 return NULL;
3899 p = strchr(s, '\n');
3900 if (p)
3901 *p = '\0';
3902 return s;
3905 static const struct got_error *
3906 match_commit(int *have_match, struct got_object_id *id,
3907 struct got_commit_object *commit, regex_t *regex)
3909 const struct got_error *err = NULL;
3910 regmatch_t regmatch;
3911 char *id_str = NULL, *logmsg = NULL;
3913 *have_match = 0;
3915 err = got_object_id_str(&id_str, id);
3916 if (err)
3917 return err;
3919 err = got_object_commit_get_logmsg(&logmsg, commit);
3920 if (err)
3921 goto done;
3923 if (regexec(regex, got_object_commit_get_author(commit), 1,
3924 &regmatch, 0) == 0 ||
3925 regexec(regex, got_object_commit_get_committer(commit), 1,
3926 &regmatch, 0) == 0 ||
3927 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3928 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3929 *have_match = 1;
3930 done:
3931 free(id_str);
3932 free(logmsg);
3933 return err;
3936 static void
3937 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3938 regex_t *regex)
3940 regmatch_t regmatch;
3941 struct got_pathlist_entry *pe;
3943 *have_match = 0;
3945 TAILQ_FOREACH(pe, changed_paths, entry) {
3946 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3947 *have_match = 1;
3948 break;
3953 static const struct got_error *
3954 match_patch(int *have_match, struct got_commit_object *commit,
3955 struct got_object_id *id, const char *path, int diff_context,
3956 struct got_repository *repo, regex_t *regex, FILE *f)
3958 const struct got_error *err = NULL;
3959 char *line = NULL;
3960 size_t linesize = 0;
3961 regmatch_t regmatch;
3963 *have_match = 0;
3965 err = got_opentemp_truncate(f);
3966 if (err)
3967 return err;
3969 err = print_patch(commit, id, path, diff_context, repo, f);
3970 if (err)
3971 goto done;
3973 if (fseeko(f, 0L, SEEK_SET) == -1) {
3974 err = got_error_from_errno("fseeko");
3975 goto done;
3978 while (getline(&line, &linesize, f) != -1) {
3979 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3980 *have_match = 1;
3981 break;
3984 done:
3985 free(line);
3986 return err;
3989 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3991 static const struct got_error*
3992 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3993 struct got_object_id *id, struct got_repository *repo,
3994 int local_only)
3996 static const struct got_error *err = NULL;
3997 struct got_reflist_entry *re;
3998 char *s;
3999 const char *name;
4001 *refs_str = NULL;
4003 TAILQ_FOREACH(re, refs, entry) {
4004 struct got_tag_object *tag = NULL;
4005 struct got_object_id *ref_id;
4006 int cmp;
4008 name = got_ref_get_name(re->ref);
4009 if (strcmp(name, GOT_REF_HEAD) == 0)
4010 continue;
4011 if (strncmp(name, "refs/", 5) == 0)
4012 name += 5;
4013 if (strncmp(name, "got/", 4) == 0)
4014 continue;
4015 if (strncmp(name, "heads/", 6) == 0)
4016 name += 6;
4017 if (strncmp(name, "remotes/", 8) == 0) {
4018 if (local_only)
4019 continue;
4020 name += 8;
4021 s = strstr(name, "/" GOT_REF_HEAD);
4022 if (s != NULL && s[strlen(s)] == '\0')
4023 continue;
4025 err = got_ref_resolve(&ref_id, repo, re->ref);
4026 if (err)
4027 break;
4028 if (strncmp(name, "tags/", 5) == 0) {
4029 err = got_object_open_as_tag(&tag, repo, ref_id);
4030 if (err) {
4031 if (err->code != GOT_ERR_OBJ_TYPE) {
4032 free(ref_id);
4033 break;
4035 /* Ref points at something other than a tag. */
4036 err = NULL;
4037 tag = NULL;
4040 cmp = got_object_id_cmp(tag ?
4041 got_object_tag_get_object_id(tag) : ref_id, id);
4042 free(ref_id);
4043 if (tag)
4044 got_object_tag_close(tag);
4045 if (cmp != 0)
4046 continue;
4047 s = *refs_str;
4048 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4049 s ? ", " : "", name) == -1) {
4050 err = got_error_from_errno("asprintf");
4051 free(s);
4052 *refs_str = NULL;
4053 break;
4055 free(s);
4058 return err;
4061 static const struct got_error *
4062 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4063 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4065 const struct got_error *err = NULL;
4066 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4067 char *comma, *s, *nl;
4068 struct got_reflist_head *refs;
4069 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4070 struct tm tm;
4071 time_t committer_time;
4073 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4074 if (refs) {
4075 err = build_refs_str(&ref_str, refs, id, repo, 1);
4076 if (err)
4077 return err;
4079 /* Display the first matching ref only. */
4080 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4081 *comma = '\0';
4084 if (ref_str == NULL) {
4085 err = got_object_id_str(&id_str, id);
4086 if (err)
4087 return err;
4090 committer_time = got_object_commit_get_committer_time(commit);
4091 if (gmtime_r(&committer_time, &tm) == NULL) {
4092 err = got_error_from_errno("gmtime_r");
4093 goto done;
4095 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4096 err = got_error(GOT_ERR_NO_SPACE);
4097 goto done;
4100 err = got_object_commit_get_logmsg(&logmsg0, commit);
4101 if (err)
4102 goto done;
4104 s = logmsg0;
4105 while (isspace((unsigned char)s[0]))
4106 s++;
4108 nl = strchr(s, '\n');
4109 if (nl) {
4110 *nl = '\0';
4113 if (ref_str)
4114 printf("%s%-7s %s\n", datebuf, ref_str, s);
4115 else
4116 printf("%s%.7s %s\n", datebuf, id_str, s);
4118 if (fflush(stdout) != 0 && err == NULL)
4119 err = got_error_from_errno("fflush");
4120 done:
4121 free(id_str);
4122 free(ref_str);
4123 free(logmsg0);
4124 return err;
4127 static const struct got_error *
4128 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4129 struct got_repository *repo, const char *path,
4130 struct got_pathlist_head *changed_paths, int show_patch,
4131 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4132 const char *custom_refs_str)
4134 const struct got_error *err = NULL;
4135 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4136 char datebuf[26];
4137 time_t committer_time;
4138 const char *author, *committer;
4139 char *refs_str = NULL;
4141 err = got_object_id_str(&id_str, id);
4142 if (err)
4143 return err;
4145 if (custom_refs_str == NULL) {
4146 struct got_reflist_head *refs;
4147 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4148 if (refs) {
4149 err = build_refs_str(&refs_str, refs, id, repo, 0);
4150 if (err)
4151 goto done;
4155 printf(GOT_COMMIT_SEP_STR);
4156 if (custom_refs_str)
4157 printf("commit %s (%s)\n", id_str, custom_refs_str);
4158 else
4159 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4160 refs_str ? refs_str : "", refs_str ? ")" : "");
4161 free(id_str);
4162 id_str = NULL;
4163 free(refs_str);
4164 refs_str = NULL;
4165 printf("from: %s\n", got_object_commit_get_author(commit));
4166 committer_time = got_object_commit_get_committer_time(commit);
4167 datestr = get_datestr(&committer_time, datebuf);
4168 if (datestr)
4169 printf("date: %s UTC\n", datestr);
4170 author = got_object_commit_get_author(commit);
4171 committer = got_object_commit_get_committer(commit);
4172 if (strcmp(author, committer) != 0)
4173 printf("via: %s\n", committer);
4174 if (got_object_commit_get_nparents(commit) > 1) {
4175 const struct got_object_id_queue *parent_ids;
4176 struct got_object_qid *qid;
4177 int n = 1;
4178 parent_ids = got_object_commit_get_parent_ids(commit);
4179 STAILQ_FOREACH(qid, parent_ids, entry) {
4180 err = got_object_id_str(&id_str, &qid->id);
4181 if (err)
4182 goto done;
4183 printf("parent %d: %s\n", n++, id_str);
4184 free(id_str);
4185 id_str = NULL;
4189 err = got_object_commit_get_logmsg(&logmsg0, commit);
4190 if (err)
4191 goto done;
4193 logmsg = logmsg0;
4194 do {
4195 line = strsep(&logmsg, "\n");
4196 if (line)
4197 printf(" %s\n", line);
4198 } while (line);
4199 free(logmsg0);
4201 if (changed_paths) {
4202 struct got_pathlist_entry *pe;
4203 TAILQ_FOREACH(pe, changed_paths, entry) {
4204 struct got_diff_changed_path *cp = pe->data;
4205 printf(" %c %s\n", cp->status, pe->path);
4207 printf("\n");
4209 if (show_patch) {
4210 err = print_patch(commit, id, path, diff_context, repo, stdout);
4211 if (err == 0)
4212 printf("\n");
4215 if (fflush(stdout) != 0 && err == NULL)
4216 err = got_error_from_errno("fflush");
4217 done:
4218 free(id_str);
4219 free(refs_str);
4220 return err;
4223 static const struct got_error *
4224 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4225 struct got_repository *repo, const char *path, int show_changed_paths,
4226 int show_patch, const char *search_pattern, int diff_context, int limit,
4227 int log_branches, int reverse_display_order,
4228 struct got_reflist_object_id_map *refs_idmap, int one_line,
4229 FILE *tmpfile)
4231 const struct got_error *err;
4232 struct got_commit_graph *graph;
4233 regex_t regex;
4234 int have_match;
4235 struct got_object_id_queue reversed_commits;
4236 struct got_object_qid *qid;
4237 struct got_commit_object *commit;
4238 struct got_pathlist_head changed_paths;
4239 struct got_pathlist_entry *pe;
4241 STAILQ_INIT(&reversed_commits);
4242 TAILQ_INIT(&changed_paths);
4244 if (search_pattern && regcomp(&regex, search_pattern,
4245 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4246 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4248 err = got_commit_graph_open(&graph, path, !log_branches);
4249 if (err)
4250 return err;
4251 err = got_commit_graph_iter_start(graph, root_id, repo,
4252 check_cancelled, NULL);
4253 if (err)
4254 goto done;
4255 for (;;) {
4256 struct got_object_id id;
4258 if (sigint_received || sigpipe_received)
4259 break;
4261 err = got_commit_graph_iter_next(&id, graph, repo,
4262 check_cancelled, NULL);
4263 if (err) {
4264 if (err->code == GOT_ERR_ITER_COMPLETED)
4265 err = NULL;
4266 break;
4269 err = got_object_open_as_commit(&commit, repo, &id);
4270 if (err)
4271 break;
4273 if (show_changed_paths && !reverse_display_order) {
4274 err = get_changed_paths(&changed_paths, commit, repo);
4275 if (err)
4276 break;
4279 if (search_pattern) {
4280 err = match_commit(&have_match, &id, commit, &regex);
4281 if (err) {
4282 got_object_commit_close(commit);
4283 break;
4285 if (have_match == 0 && show_changed_paths)
4286 match_changed_paths(&have_match,
4287 &changed_paths, &regex);
4288 if (have_match == 0 && show_patch) {
4289 err = match_patch(&have_match, commit, &id,
4290 path, diff_context, repo, &regex,
4291 tmpfile);
4292 if (err)
4293 break;
4295 if (have_match == 0) {
4296 got_object_commit_close(commit);
4297 TAILQ_FOREACH(pe, &changed_paths, entry) {
4298 free((char *)pe->path);
4299 free(pe->data);
4301 got_pathlist_free(&changed_paths);
4302 continue;
4306 if (reverse_display_order) {
4307 err = got_object_qid_alloc(&qid, &id);
4308 if (err)
4309 break;
4310 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4311 got_object_commit_close(commit);
4312 } else {
4313 if (one_line)
4314 err = print_commit_oneline(commit, &id,
4315 repo, refs_idmap);
4316 else
4317 err = print_commit(commit, &id, repo, path,
4318 show_changed_paths ? &changed_paths : NULL,
4319 show_patch, diff_context, refs_idmap, NULL);
4320 got_object_commit_close(commit);
4321 if (err)
4322 break;
4324 if ((limit && --limit == 0) ||
4325 (end_id && got_object_id_cmp(&id, end_id) == 0))
4326 break;
4328 TAILQ_FOREACH(pe, &changed_paths, entry) {
4329 free((char *)pe->path);
4330 free(pe->data);
4332 got_pathlist_free(&changed_paths);
4334 if (reverse_display_order) {
4335 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4336 err = got_object_open_as_commit(&commit, repo,
4337 &qid->id);
4338 if (err)
4339 break;
4340 if (show_changed_paths) {
4341 err = get_changed_paths(&changed_paths,
4342 commit, repo);
4343 if (err)
4344 break;
4346 if (one_line)
4347 err = print_commit_oneline(commit, &qid->id,
4348 repo, refs_idmap);
4349 else
4350 err = print_commit(commit, &qid->id, repo, path,
4351 show_changed_paths ? &changed_paths : NULL,
4352 show_patch, diff_context, refs_idmap, NULL);
4353 got_object_commit_close(commit);
4354 if (err)
4355 break;
4356 TAILQ_FOREACH(pe, &changed_paths, entry) {
4357 free((char *)pe->path);
4358 free(pe->data);
4360 got_pathlist_free(&changed_paths);
4363 done:
4364 while (!STAILQ_EMPTY(&reversed_commits)) {
4365 qid = STAILQ_FIRST(&reversed_commits);
4366 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4367 got_object_qid_free(qid);
4369 TAILQ_FOREACH(pe, &changed_paths, entry) {
4370 free((char *)pe->path);
4371 free(pe->data);
4373 got_pathlist_free(&changed_paths);
4374 if (search_pattern)
4375 regfree(&regex);
4376 got_commit_graph_close(graph);
4377 return err;
4380 __dead static void
4381 usage_log(void)
4383 fprintf(stderr, "usage: %s log [-bPpRs] [-C number] [-c commit] [-l N] "
4384 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4385 getprogname());
4386 exit(1);
4389 static int
4390 get_default_log_limit(void)
4392 const char *got_default_log_limit;
4393 long long n;
4394 const char *errstr;
4396 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4397 if (got_default_log_limit == NULL)
4398 return 0;
4399 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4400 if (errstr != NULL)
4401 return 0;
4402 return n;
4405 static const struct got_error *
4406 cmd_log(int argc, char *argv[])
4408 const struct got_error *error;
4409 struct got_repository *repo = NULL;
4410 struct got_worktree *worktree = NULL;
4411 struct got_object_id *start_id = NULL, *end_id = NULL;
4412 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4413 const char *start_commit = NULL, *end_commit = NULL;
4414 const char *search_pattern = NULL;
4415 int diff_context = -1, ch;
4416 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4417 int reverse_display_order = 0, one_line = 0;
4418 const char *errstr;
4419 struct got_reflist_head refs;
4420 struct got_reflist_object_id_map *refs_idmap = NULL;
4421 FILE *tmpfile = NULL;
4422 int *pack_fds = NULL;
4424 TAILQ_INIT(&refs);
4426 #ifndef PROFILE
4427 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4428 NULL)
4429 == -1)
4430 err(1, "pledge");
4431 #endif
4433 limit = get_default_log_limit();
4435 while ((ch = getopt(argc, argv, "bC:c:l:PpRr:S:sx:")) != -1) {
4436 switch (ch) {
4437 case 'b':
4438 log_branches = 1;
4439 break;
4440 case 'C':
4441 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4442 &errstr);
4443 if (errstr != NULL)
4444 errx(1, "number of context lines is %s: %s",
4445 errstr, optarg);
4446 break;
4447 case 'c':
4448 start_commit = optarg;
4449 break;
4450 case 'l':
4451 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4452 if (errstr != NULL)
4453 errx(1, "number of commits is %s: %s",
4454 errstr, optarg);
4455 break;
4456 case 'P':
4457 show_changed_paths = 1;
4458 break;
4459 case 'p':
4460 show_patch = 1;
4461 break;
4462 case 'R':
4463 reverse_display_order = 1;
4464 break;
4465 case 'r':
4466 repo_path = realpath(optarg, NULL);
4467 if (repo_path == NULL)
4468 return got_error_from_errno2("realpath",
4469 optarg);
4470 got_path_strip_trailing_slashes(repo_path);
4471 break;
4472 case 'S':
4473 search_pattern = optarg;
4474 break;
4475 case 's':
4476 one_line = 1;
4477 break;
4478 case 'x':
4479 end_commit = optarg;
4480 break;
4481 default:
4482 usage_log();
4483 /* NOTREACHED */
4487 argc -= optind;
4488 argv += optind;
4490 if (diff_context == -1)
4491 diff_context = 3;
4492 else if (!show_patch)
4493 errx(1, "-C requires -p");
4495 if (one_line && (show_patch || show_changed_paths))
4496 errx(1, "cannot use -s with -p or -P");
4498 cwd = getcwd(NULL, 0);
4499 if (cwd == NULL) {
4500 error = got_error_from_errno("getcwd");
4501 goto done;
4504 error = got_repo_pack_fds_open(&pack_fds);
4505 if (error != NULL)
4506 goto done;
4508 if (repo_path == NULL) {
4509 error = got_worktree_open(&worktree, cwd);
4510 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4511 goto done;
4512 error = NULL;
4515 if (argc == 1) {
4516 if (worktree) {
4517 error = got_worktree_resolve_path(&path, worktree,
4518 argv[0]);
4519 if (error)
4520 goto done;
4521 } else {
4522 path = strdup(argv[0]);
4523 if (path == NULL) {
4524 error = got_error_from_errno("strdup");
4525 goto done;
4528 } else if (argc != 0)
4529 usage_log();
4531 if (repo_path == NULL) {
4532 repo_path = worktree ?
4533 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4535 if (repo_path == NULL) {
4536 error = got_error_from_errno("strdup");
4537 goto done;
4540 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4541 if (error != NULL)
4542 goto done;
4544 error = apply_unveil(got_repo_get_path(repo), 1,
4545 worktree ? got_worktree_get_root_path(worktree) : NULL);
4546 if (error)
4547 goto done;
4549 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4550 if (error)
4551 goto done;
4553 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4554 if (error)
4555 goto done;
4557 if (start_commit == NULL) {
4558 struct got_reference *head_ref;
4559 struct got_commit_object *commit = NULL;
4560 error = got_ref_open(&head_ref, repo,
4561 worktree ? got_worktree_get_head_ref_name(worktree)
4562 : GOT_REF_HEAD, 0);
4563 if (error != NULL)
4564 goto done;
4565 error = got_ref_resolve(&start_id, repo, head_ref);
4566 got_ref_close(head_ref);
4567 if (error != NULL)
4568 goto done;
4569 error = got_object_open_as_commit(&commit, repo,
4570 start_id);
4571 if (error != NULL)
4572 goto done;
4573 got_object_commit_close(commit);
4574 } else {
4575 error = got_repo_match_object_id(&start_id, NULL,
4576 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4577 if (error != NULL)
4578 goto done;
4580 if (end_commit != NULL) {
4581 error = got_repo_match_object_id(&end_id, NULL,
4582 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4583 if (error != NULL)
4584 goto done;
4587 if (worktree) {
4589 * If a path was specified on the command line it was resolved
4590 * to a path in the work tree above. Prepend the work tree's
4591 * path prefix to obtain the corresponding in-repository path.
4593 if (path) {
4594 const char *prefix;
4595 prefix = got_worktree_get_path_prefix(worktree);
4596 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4597 (path[0] != '\0') ? "/" : "", path) == -1) {
4598 error = got_error_from_errno("asprintf");
4599 goto done;
4602 } else
4603 error = got_repo_map_path(&in_repo_path, repo,
4604 path ? path : "");
4605 if (error != NULL)
4606 goto done;
4607 if (in_repo_path) {
4608 free(path);
4609 path = in_repo_path;
4612 if (worktree) {
4613 /* Release work tree lock. */
4614 got_worktree_close(worktree);
4615 worktree = NULL;
4618 if (search_pattern && show_patch) {
4619 tmpfile = got_opentemp();
4620 if (tmpfile == NULL) {
4621 error = got_error_from_errno("got_opentemp");
4622 goto done;
4626 error = print_commits(start_id, end_id, repo, path ? path : "",
4627 show_changed_paths, show_patch, search_pattern, diff_context,
4628 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4629 tmpfile);
4630 done:
4631 free(path);
4632 free(repo_path);
4633 free(cwd);
4634 if (worktree)
4635 got_worktree_close(worktree);
4636 if (repo) {
4637 const struct got_error *close_err = got_repo_close(repo);
4638 if (error == NULL)
4639 error = close_err;
4641 if (pack_fds) {
4642 const struct got_error *pack_err =
4643 got_repo_pack_fds_close(pack_fds);
4644 if (error == NULL)
4645 error = pack_err;
4647 if (refs_idmap)
4648 got_reflist_object_id_map_free(refs_idmap);
4649 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4650 error = got_error_from_errno("fclose");
4651 got_ref_list_free(&refs);
4652 return error;
4655 __dead static void
4656 usage_diff(void)
4658 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4659 "[-r repository-path] [object1 object2 | path ...]\n",
4660 getprogname());
4661 exit(1);
4664 struct print_diff_arg {
4665 struct got_repository *repo;
4666 struct got_worktree *worktree;
4667 int diff_context;
4668 const char *id_str;
4669 int header_shown;
4670 int diff_staged;
4671 enum got_diff_algorithm diff_algo;
4672 int ignore_whitespace;
4673 int force_text_diff;
4674 FILE *f1;
4675 FILE *f2;
4679 * Create a file which contains the target path of a symlink so we can feed
4680 * it as content to the diff engine.
4682 static const struct got_error *
4683 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4684 const char *abspath)
4686 const struct got_error *err = NULL;
4687 char target_path[PATH_MAX];
4688 ssize_t target_len, outlen;
4690 *fd = -1;
4692 if (dirfd != -1) {
4693 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4694 if (target_len == -1)
4695 return got_error_from_errno2("readlinkat", abspath);
4696 } else {
4697 target_len = readlink(abspath, target_path, PATH_MAX);
4698 if (target_len == -1)
4699 return got_error_from_errno2("readlink", abspath);
4702 *fd = got_opentempfd();
4703 if (*fd == -1)
4704 return got_error_from_errno("got_opentempfd");
4706 outlen = write(*fd, target_path, target_len);
4707 if (outlen == -1) {
4708 err = got_error_from_errno("got_opentempfd");
4709 goto done;
4712 if (lseek(*fd, 0, SEEK_SET) == -1) {
4713 err = got_error_from_errno2("lseek", abspath);
4714 goto done;
4716 done:
4717 if (err) {
4718 close(*fd);
4719 *fd = -1;
4721 return err;
4724 static const struct got_error *
4725 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4726 const char *path, struct got_object_id *blob_id,
4727 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4728 int dirfd, const char *de_name)
4730 struct print_diff_arg *a = arg;
4731 const struct got_error *err = NULL;
4732 struct got_blob_object *blob1 = NULL;
4733 int fd = -1, fd1 = -1, fd2 = -1;
4734 FILE *f2 = NULL;
4735 char *abspath = NULL, *label1 = NULL;
4736 struct stat sb;
4737 off_t size1 = 0;
4738 int f2_exists = 0;
4740 memset(&sb, 0, sizeof(sb));
4742 if (a->diff_staged) {
4743 if (staged_status != GOT_STATUS_MODIFY &&
4744 staged_status != GOT_STATUS_ADD &&
4745 staged_status != GOT_STATUS_DELETE)
4746 return NULL;
4747 } else {
4748 if (staged_status == GOT_STATUS_DELETE)
4749 return NULL;
4750 if (status == GOT_STATUS_NONEXISTENT)
4751 return got_error_set_errno(ENOENT, path);
4752 if (status != GOT_STATUS_MODIFY &&
4753 status != GOT_STATUS_ADD &&
4754 status != GOT_STATUS_DELETE &&
4755 status != GOT_STATUS_CONFLICT)
4756 return NULL;
4759 err = got_opentemp_truncate(a->f1);
4760 if (err)
4761 return got_error_from_errno("got_opentemp_truncate");
4762 err = got_opentemp_truncate(a->f2);
4763 if (err)
4764 return got_error_from_errno("got_opentemp_truncate");
4766 if (!a->header_shown) {
4767 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4768 got_worktree_get_root_path(a->worktree));
4769 printf("commit - %s\n", a->id_str);
4770 printf("path + %s%s\n",
4771 got_worktree_get_root_path(a->worktree),
4772 a->diff_staged ? " (staged changes)" : "");
4773 a->header_shown = 1;
4776 if (a->diff_staged) {
4777 const char *label1 = NULL, *label2 = NULL;
4778 switch (staged_status) {
4779 case GOT_STATUS_MODIFY:
4780 label1 = path;
4781 label2 = path;
4782 break;
4783 case GOT_STATUS_ADD:
4784 label2 = path;
4785 break;
4786 case GOT_STATUS_DELETE:
4787 label1 = path;
4788 break;
4789 default:
4790 return got_error(GOT_ERR_FILE_STATUS);
4792 fd1 = got_opentempfd();
4793 if (fd1 == -1) {
4794 err = got_error_from_errno("got_opentempfd");
4795 goto done;
4797 fd2 = got_opentempfd();
4798 if (fd2 == -1) {
4799 err = got_error_from_errno("got_opentempfd");
4800 goto done;
4802 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4803 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4804 a->diff_algo, a->diff_context, a->ignore_whitespace,
4805 a->force_text_diff, a->repo, stdout);
4806 goto done;
4809 fd1 = got_opentempfd();
4810 if (fd1 == -1) {
4811 err = got_error_from_errno("got_opentempfd");
4812 goto done;
4815 if (staged_status == GOT_STATUS_ADD ||
4816 staged_status == GOT_STATUS_MODIFY) {
4817 char *id_str;
4818 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4819 8192, fd1);
4820 if (err)
4821 goto done;
4822 err = got_object_id_str(&id_str, staged_blob_id);
4823 if (err)
4824 goto done;
4825 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4826 err = got_error_from_errno("asprintf");
4827 free(id_str);
4828 goto done;
4830 free(id_str);
4831 } else if (status != GOT_STATUS_ADD) {
4832 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4833 fd1);
4834 if (err)
4835 goto done;
4838 if (status != GOT_STATUS_DELETE) {
4839 if (asprintf(&abspath, "%s/%s",
4840 got_worktree_get_root_path(a->worktree), path) == -1) {
4841 err = got_error_from_errno("asprintf");
4842 goto done;
4845 if (dirfd != -1) {
4846 fd = openat(dirfd, de_name,
4847 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4848 if (fd == -1) {
4849 if (!got_err_open_nofollow_on_symlink()) {
4850 err = got_error_from_errno2("openat",
4851 abspath);
4852 goto done;
4854 err = get_symlink_target_file(&fd, dirfd,
4855 de_name, abspath);
4856 if (err)
4857 goto done;
4859 } else {
4860 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4861 if (fd == -1) {
4862 if (!got_err_open_nofollow_on_symlink()) {
4863 err = got_error_from_errno2("open",
4864 abspath);
4865 goto done;
4867 err = get_symlink_target_file(&fd, dirfd,
4868 de_name, abspath);
4869 if (err)
4870 goto done;
4873 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4874 err = got_error_from_errno2("fstatat", abspath);
4875 goto done;
4877 f2 = fdopen(fd, "r");
4878 if (f2 == NULL) {
4879 err = got_error_from_errno2("fdopen", abspath);
4880 goto done;
4882 fd = -1;
4883 f2_exists = 1;
4886 if (blob1) {
4887 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4888 a->f1, blob1);
4889 if (err)
4890 goto done;
4893 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4894 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4895 a->ignore_whitespace, a->force_text_diff, stdout);
4896 done:
4897 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4898 err = got_error_from_errno("close");
4899 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4900 err = got_error_from_errno("close");
4901 if (blob1)
4902 got_object_blob_close(blob1);
4903 if (fd != -1 && close(fd) == -1 && err == NULL)
4904 err = got_error_from_errno("close");
4905 if (f2 && fclose(f2) == EOF && err == NULL)
4906 err = got_error_from_errno("fclose");
4907 free(abspath);
4908 return err;
4911 static const struct got_error *
4912 cmd_diff(int argc, char *argv[])
4914 const struct got_error *error;
4915 struct got_repository *repo = NULL;
4916 struct got_worktree *worktree = NULL;
4917 char *cwd = NULL, *repo_path = NULL;
4918 const char *commit_args[2] = { NULL, NULL };
4919 int ncommit_args = 0;
4920 struct got_object_id *ids[2] = { NULL, NULL };
4921 char *labels[2] = { NULL, NULL };
4922 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4923 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4924 int force_text_diff = 0, force_path = 0, rflag = 0;
4925 const char *errstr;
4926 struct got_reflist_head refs;
4927 struct got_pathlist_head paths;
4928 struct got_pathlist_entry *pe;
4929 FILE *f1 = NULL, *f2 = NULL;
4930 int fd1 = -1, fd2 = -1;
4931 int *pack_fds = NULL;
4933 TAILQ_INIT(&refs);
4934 TAILQ_INIT(&paths);
4936 #ifndef PROFILE
4937 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4938 NULL) == -1)
4939 err(1, "pledge");
4940 #endif
4942 while ((ch = getopt(argc, argv, "aC:c:Pr:sw")) != -1) {
4943 switch (ch) {
4944 case 'a':
4945 force_text_diff = 1;
4946 break;
4947 case 'C':
4948 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4949 &errstr);
4950 if (errstr != NULL)
4951 errx(1, "number of context lines is %s: %s",
4952 errstr, optarg);
4953 break;
4954 case 'c':
4955 if (ncommit_args >= 2)
4956 errx(1, "too many -c options used");
4957 commit_args[ncommit_args++] = optarg;
4958 break;
4959 case 'P':
4960 force_path = 1;
4961 break;
4962 case 'r':
4963 repo_path = realpath(optarg, NULL);
4964 if (repo_path == NULL)
4965 return got_error_from_errno2("realpath",
4966 optarg);
4967 got_path_strip_trailing_slashes(repo_path);
4968 rflag = 1;
4969 break;
4970 case 's':
4971 diff_staged = 1;
4972 break;
4973 case 'w':
4974 ignore_whitespace = 1;
4975 break;
4976 default:
4977 usage_diff();
4978 /* NOTREACHED */
4982 argc -= optind;
4983 argv += optind;
4985 cwd = getcwd(NULL, 0);
4986 if (cwd == NULL) {
4987 error = got_error_from_errno("getcwd");
4988 goto done;
4991 error = got_repo_pack_fds_open(&pack_fds);
4992 if (error != NULL)
4993 goto done;
4995 if (repo_path == NULL) {
4996 error = got_worktree_open(&worktree, cwd);
4997 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4998 goto done;
4999 else
5000 error = NULL;
5001 if (worktree) {
5002 repo_path =
5003 strdup(got_worktree_get_repo_path(worktree));
5004 if (repo_path == NULL) {
5005 error = got_error_from_errno("strdup");
5006 goto done;
5008 } else {
5009 repo_path = strdup(cwd);
5010 if (repo_path == NULL) {
5011 error = got_error_from_errno("strdup");
5012 goto done;
5017 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5018 free(repo_path);
5019 if (error != NULL)
5020 goto done;
5022 if (rflag || worktree == NULL || ncommit_args > 0) {
5023 if (force_path) {
5024 error = got_error_msg(GOT_ERR_NOT_IMPL,
5025 "-P option can only be used when diffing "
5026 "a work tree");
5027 goto done;
5029 if (diff_staged) {
5030 error = got_error_msg(GOT_ERR_NOT_IMPL,
5031 "-s option can only be used when diffing "
5032 "a work tree");
5033 goto done;
5037 error = apply_unveil(got_repo_get_path(repo), 1,
5038 worktree ? got_worktree_get_root_path(worktree) : NULL);
5039 if (error)
5040 goto done;
5042 if ((!force_path && argc == 2) || ncommit_args > 0) {
5043 int obj_type = (ncommit_args > 0 ?
5044 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5045 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5046 NULL);
5047 if (error)
5048 goto done;
5049 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5050 const char *arg;
5051 if (ncommit_args > 0)
5052 arg = commit_args[i];
5053 else
5054 arg = argv[i];
5055 error = got_repo_match_object_id(&ids[i], &labels[i],
5056 arg, obj_type, &refs, repo);
5057 if (error) {
5058 if (error->code != GOT_ERR_NOT_REF &&
5059 error->code != GOT_ERR_NO_OBJ)
5060 goto done;
5061 if (ncommit_args > 0)
5062 goto done;
5063 error = NULL;
5064 break;
5069 f1 = got_opentemp();
5070 if (f1 == NULL) {
5071 error = got_error_from_errno("got_opentemp");
5072 goto done;
5075 f2 = got_opentemp();
5076 if (f2 == NULL) {
5077 error = got_error_from_errno("got_opentemp");
5078 goto done;
5081 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5082 struct print_diff_arg arg;
5083 char *id_str;
5085 if (worktree == NULL) {
5086 if (argc == 2 && ids[0] == NULL) {
5087 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5088 goto done;
5089 } else if (argc == 2 && ids[1] == NULL) {
5090 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5091 goto done;
5092 } else if (argc > 0) {
5093 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5094 "%s", "specified paths cannot be resolved");
5095 goto done;
5096 } else {
5097 error = got_error(GOT_ERR_NOT_WORKTREE);
5098 goto done;
5102 error = get_worktree_paths_from_argv(&paths, argc, argv,
5103 worktree);
5104 if (error)
5105 goto done;
5107 error = got_object_id_str(&id_str,
5108 got_worktree_get_base_commit_id(worktree));
5109 if (error)
5110 goto done;
5111 arg.repo = repo;
5112 arg.worktree = worktree;
5113 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5114 arg.diff_context = diff_context;
5115 arg.id_str = id_str;
5116 arg.header_shown = 0;
5117 arg.diff_staged = diff_staged;
5118 arg.ignore_whitespace = ignore_whitespace;
5119 arg.force_text_diff = force_text_diff;
5120 arg.f1 = f1;
5121 arg.f2 = f2;
5123 error = got_worktree_status(worktree, &paths, repo, 0,
5124 print_diff, &arg, check_cancelled, NULL);
5125 free(id_str);
5126 goto done;
5129 if (ncommit_args == 1) {
5130 struct got_commit_object *commit;
5131 error = got_object_open_as_commit(&commit, repo, ids[0]);
5132 if (error)
5133 goto done;
5135 labels[1] = labels[0];
5136 ids[1] = ids[0];
5137 if (got_object_commit_get_nparents(commit) > 0) {
5138 const struct got_object_id_queue *pids;
5139 struct got_object_qid *pid;
5140 pids = got_object_commit_get_parent_ids(commit);
5141 pid = STAILQ_FIRST(pids);
5142 ids[0] = got_object_id_dup(&pid->id);
5143 if (ids[0] == NULL) {
5144 error = got_error_from_errno(
5145 "got_object_id_dup");
5146 got_object_commit_close(commit);
5147 goto done;
5149 error = got_object_id_str(&labels[0], ids[0]);
5150 if (error) {
5151 got_object_commit_close(commit);
5152 goto done;
5154 } else {
5155 ids[0] = NULL;
5156 labels[0] = strdup("/dev/null");
5157 if (labels[0] == NULL) {
5158 error = got_error_from_errno("strdup");
5159 got_object_commit_close(commit);
5160 goto done;
5164 got_object_commit_close(commit);
5167 if (ncommit_args == 0 && argc > 2) {
5168 error = got_error_msg(GOT_ERR_BAD_PATH,
5169 "path arguments cannot be used when diffing two objects");
5170 goto done;
5173 if (ids[0]) {
5174 error = got_object_get_type(&type1, repo, ids[0]);
5175 if (error)
5176 goto done;
5179 error = got_object_get_type(&type2, repo, ids[1]);
5180 if (error)
5181 goto done;
5182 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5183 error = got_error(GOT_ERR_OBJ_TYPE);
5184 goto done;
5186 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5187 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5188 "path arguments cannot be used when diffing blobs");
5189 goto done;
5192 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5193 char *in_repo_path;
5194 struct got_pathlist_entry *new;
5195 if (worktree) {
5196 const char *prefix;
5197 char *p;
5198 error = got_worktree_resolve_path(&p, worktree,
5199 argv[i]);
5200 if (error)
5201 goto done;
5202 prefix = got_worktree_get_path_prefix(worktree);
5203 while (prefix[0] == '/')
5204 prefix++;
5205 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5206 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5207 p) == -1) {
5208 error = got_error_from_errno("asprintf");
5209 free(p);
5210 goto done;
5212 free(p);
5213 } else {
5214 char *mapped_path, *s;
5215 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5216 if (error)
5217 goto done;
5218 s = mapped_path;
5219 while (s[0] == '/')
5220 s++;
5221 in_repo_path = strdup(s);
5222 if (in_repo_path == NULL) {
5223 error = got_error_from_errno("asprintf");
5224 free(mapped_path);
5225 goto done;
5227 free(mapped_path);
5230 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5231 if (error || new == NULL /* duplicate */)
5232 free(in_repo_path);
5233 if (error)
5234 goto done;
5237 if (worktree) {
5238 /* Release work tree lock. */
5239 got_worktree_close(worktree);
5240 worktree = NULL;
5243 fd1 = got_opentempfd();
5244 if (fd1 == -1) {
5245 error = got_error_from_errno("got_opentempfd");
5246 goto done;
5249 fd2 = got_opentempfd();
5250 if (fd2 == -1) {
5251 error = got_error_from_errno("got_opentempfd");
5252 goto done;
5255 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5256 case GOT_OBJ_TYPE_BLOB:
5257 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5258 fd1, fd2, ids[0], ids[1], NULL, NULL,
5259 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5260 ignore_whitespace, force_text_diff, repo, stdout);
5261 break;
5262 case GOT_OBJ_TYPE_TREE:
5263 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5264 ids[0], ids[1], &paths, "", "",
5265 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5266 ignore_whitespace, force_text_diff, repo, stdout);
5267 break;
5268 case GOT_OBJ_TYPE_COMMIT:
5269 printf("diff %s %s\n", labels[0], labels[1]);
5270 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5271 fd1, fd2, ids[0], ids[1], &paths,
5272 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5273 ignore_whitespace, force_text_diff, repo, stdout);
5274 break;
5275 default:
5276 error = got_error(GOT_ERR_OBJ_TYPE);
5278 done:
5279 free(labels[0]);
5280 free(labels[1]);
5281 free(ids[0]);
5282 free(ids[1]);
5283 if (worktree)
5284 got_worktree_close(worktree);
5285 if (repo) {
5286 const struct got_error *close_err = got_repo_close(repo);
5287 if (error == NULL)
5288 error = close_err;
5290 if (pack_fds) {
5291 const struct got_error *pack_err =
5292 got_repo_pack_fds_close(pack_fds);
5293 if (error == NULL)
5294 error = pack_err;
5296 TAILQ_FOREACH(pe, &paths, entry)
5297 free((char *)pe->path);
5298 got_pathlist_free(&paths);
5299 got_ref_list_free(&refs);
5300 if (f1 && fclose(f1) == EOF && error == NULL)
5301 error = got_error_from_errno("fclose");
5302 if (f2 && fclose(f2) == EOF && error == NULL)
5303 error = got_error_from_errno("fclose");
5304 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5305 error = got_error_from_errno("close");
5306 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5307 error = got_error_from_errno("close");
5308 return error;
5311 __dead static void
5312 usage_blame(void)
5314 fprintf(stderr,
5315 "usage: %s blame [-c commit] [-r repository-path] path\n",
5316 getprogname());
5317 exit(1);
5320 struct blame_line {
5321 int annotated;
5322 char *id_str;
5323 char *committer;
5324 char datebuf[11]; /* YYYY-MM-DD + NUL */
5327 struct blame_cb_args {
5328 struct blame_line *lines;
5329 int nlines;
5330 int nlines_prec;
5331 int lineno_cur;
5332 off_t *line_offsets;
5333 FILE *f;
5334 struct got_repository *repo;
5337 static const struct got_error *
5338 blame_cb(void *arg, int nlines, int lineno,
5339 struct got_commit_object *commit, struct got_object_id *id)
5341 const struct got_error *err = NULL;
5342 struct blame_cb_args *a = arg;
5343 struct blame_line *bline;
5344 char *line = NULL;
5345 size_t linesize = 0;
5346 off_t offset;
5347 struct tm tm;
5348 time_t committer_time;
5350 if (nlines != a->nlines ||
5351 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5352 return got_error(GOT_ERR_RANGE);
5354 if (sigint_received)
5355 return got_error(GOT_ERR_ITER_COMPLETED);
5357 if (lineno == -1)
5358 return NULL; /* no change in this commit */
5360 /* Annotate this line. */
5361 bline = &a->lines[lineno - 1];
5362 if (bline->annotated)
5363 return NULL;
5364 err = got_object_id_str(&bline->id_str, id);
5365 if (err)
5366 return err;
5368 bline->committer = strdup(got_object_commit_get_committer(commit));
5369 if (bline->committer == NULL) {
5370 err = got_error_from_errno("strdup");
5371 goto done;
5374 committer_time = got_object_commit_get_committer_time(commit);
5375 if (gmtime_r(&committer_time, &tm) == NULL)
5376 return got_error_from_errno("gmtime_r");
5377 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5378 &tm) == 0) {
5379 err = got_error(GOT_ERR_NO_SPACE);
5380 goto done;
5382 bline->annotated = 1;
5384 /* Print lines annotated so far. */
5385 bline = &a->lines[a->lineno_cur - 1];
5386 if (!bline->annotated)
5387 goto done;
5389 offset = a->line_offsets[a->lineno_cur - 1];
5390 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5391 err = got_error_from_errno("fseeko");
5392 goto done;
5395 while (a->lineno_cur <= a->nlines && bline->annotated) {
5396 char *smallerthan, *at, *nl, *committer;
5397 size_t len;
5399 if (getline(&line, &linesize, a->f) == -1) {
5400 if (ferror(a->f))
5401 err = got_error_from_errno("getline");
5402 break;
5405 committer = bline->committer;
5406 smallerthan = strchr(committer, '<');
5407 if (smallerthan && smallerthan[1] != '\0')
5408 committer = smallerthan + 1;
5409 at = strchr(committer, '@');
5410 if (at)
5411 *at = '\0';
5412 len = strlen(committer);
5413 if (len >= 9)
5414 committer[8] = '\0';
5416 nl = strchr(line, '\n');
5417 if (nl)
5418 *nl = '\0';
5419 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5420 bline->id_str, bline->datebuf, committer, line);
5422 a->lineno_cur++;
5423 bline = &a->lines[a->lineno_cur - 1];
5425 done:
5426 free(line);
5427 return err;
5430 static const struct got_error *
5431 cmd_blame(int argc, char *argv[])
5433 const struct got_error *error;
5434 struct got_repository *repo = NULL;
5435 struct got_worktree *worktree = NULL;
5436 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5437 char *link_target = NULL;
5438 struct got_object_id *obj_id = NULL;
5439 struct got_object_id *commit_id = NULL;
5440 struct got_commit_object *commit = NULL;
5441 struct got_blob_object *blob = NULL;
5442 char *commit_id_str = NULL;
5443 struct blame_cb_args bca;
5444 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5445 off_t filesize;
5446 int *pack_fds = NULL;
5447 FILE *f1 = NULL, *f2 = NULL;
5449 fd1 = got_opentempfd();
5450 if (fd1 == -1)
5451 return got_error_from_errno("got_opentempfd");
5453 memset(&bca, 0, sizeof(bca));
5455 #ifndef PROFILE
5456 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5457 NULL) == -1)
5458 err(1, "pledge");
5459 #endif
5461 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5462 switch (ch) {
5463 case 'c':
5464 commit_id_str = optarg;
5465 break;
5466 case 'r':
5467 repo_path = realpath(optarg, NULL);
5468 if (repo_path == NULL)
5469 return got_error_from_errno2("realpath",
5470 optarg);
5471 got_path_strip_trailing_slashes(repo_path);
5472 break;
5473 default:
5474 usage_blame();
5475 /* NOTREACHED */
5479 argc -= optind;
5480 argv += optind;
5482 if (argc == 1)
5483 path = argv[0];
5484 else
5485 usage_blame();
5487 cwd = getcwd(NULL, 0);
5488 if (cwd == NULL) {
5489 error = got_error_from_errno("getcwd");
5490 goto done;
5493 error = got_repo_pack_fds_open(&pack_fds);
5494 if (error != NULL)
5495 goto done;
5497 if (repo_path == NULL) {
5498 error = got_worktree_open(&worktree, cwd);
5499 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5500 goto done;
5501 else
5502 error = NULL;
5503 if (worktree) {
5504 repo_path =
5505 strdup(got_worktree_get_repo_path(worktree));
5506 if (repo_path == NULL) {
5507 error = got_error_from_errno("strdup");
5508 if (error)
5509 goto done;
5511 } else {
5512 repo_path = strdup(cwd);
5513 if (repo_path == NULL) {
5514 error = got_error_from_errno("strdup");
5515 goto done;
5520 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5521 if (error != NULL)
5522 goto done;
5524 if (worktree) {
5525 const char *prefix = got_worktree_get_path_prefix(worktree);
5526 char *p;
5528 error = got_worktree_resolve_path(&p, worktree, path);
5529 if (error)
5530 goto done;
5531 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5532 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5533 p) == -1) {
5534 error = got_error_from_errno("asprintf");
5535 free(p);
5536 goto done;
5538 free(p);
5539 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5540 } else {
5541 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5542 if (error)
5543 goto done;
5544 error = got_repo_map_path(&in_repo_path, repo, path);
5546 if (error)
5547 goto done;
5549 if (commit_id_str == NULL) {
5550 struct got_reference *head_ref;
5551 error = got_ref_open(&head_ref, repo, worktree ?
5552 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5553 if (error != NULL)
5554 goto done;
5555 error = got_ref_resolve(&commit_id, repo, head_ref);
5556 got_ref_close(head_ref);
5557 if (error != NULL)
5558 goto done;
5559 } else {
5560 struct got_reflist_head refs;
5561 TAILQ_INIT(&refs);
5562 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5563 NULL);
5564 if (error)
5565 goto done;
5566 error = got_repo_match_object_id(&commit_id, NULL,
5567 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5568 got_ref_list_free(&refs);
5569 if (error)
5570 goto done;
5573 if (worktree) {
5574 /* Release work tree lock. */
5575 got_worktree_close(worktree);
5576 worktree = NULL;
5579 error = got_object_open_as_commit(&commit, repo, commit_id);
5580 if (error)
5581 goto done;
5583 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5584 commit, repo);
5585 if (error)
5586 goto done;
5588 error = got_object_id_by_path(&obj_id, repo, commit,
5589 link_target ? link_target : in_repo_path);
5590 if (error)
5591 goto done;
5593 error = got_object_get_type(&obj_type, repo, obj_id);
5594 if (error)
5595 goto done;
5597 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5598 error = got_error_path(link_target ? link_target : in_repo_path,
5599 GOT_ERR_OBJ_TYPE);
5600 goto done;
5603 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5604 if (error)
5605 goto done;
5606 bca.f = got_opentemp();
5607 if (bca.f == NULL) {
5608 error = got_error_from_errno("got_opentemp");
5609 goto done;
5611 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5612 &bca.line_offsets, bca.f, blob);
5613 if (error || bca.nlines == 0)
5614 goto done;
5616 /* Don't include \n at EOF in the blame line count. */
5617 if (bca.line_offsets[bca.nlines - 1] == filesize)
5618 bca.nlines--;
5620 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5621 if (bca.lines == NULL) {
5622 error = got_error_from_errno("calloc");
5623 goto done;
5625 bca.lineno_cur = 1;
5626 bca.nlines_prec = 0;
5627 i = bca.nlines;
5628 while (i > 0) {
5629 i /= 10;
5630 bca.nlines_prec++;
5632 bca.repo = repo;
5634 fd2 = got_opentempfd();
5635 if (fd2 == -1) {
5636 error = got_error_from_errno("got_opentempfd");
5637 goto done;
5639 fd3 = got_opentempfd();
5640 if (fd3 == -1) {
5641 error = got_error_from_errno("got_opentempfd");
5642 goto done;
5644 f1 = got_opentemp();
5645 if (f1 == NULL) {
5646 error = got_error_from_errno("got_opentemp");
5647 goto done;
5649 f2 = got_opentemp();
5650 if (f2 == NULL) {
5651 error = got_error_from_errno("got_opentemp");
5652 goto done;
5654 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5655 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5656 check_cancelled, NULL, fd2, fd3, f1, f2);
5657 done:
5658 free(in_repo_path);
5659 free(link_target);
5660 free(repo_path);
5661 free(cwd);
5662 free(commit_id);
5663 free(obj_id);
5664 if (commit)
5665 got_object_commit_close(commit);
5667 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5668 error = got_error_from_errno("close");
5669 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5670 error = got_error_from_errno("close");
5671 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5672 error = got_error_from_errno("close");
5673 if (f1 && fclose(f1) == EOF && error == NULL)
5674 error = got_error_from_errno("fclose");
5675 if (f2 && fclose(f2) == EOF && error == NULL)
5676 error = got_error_from_errno("fclose");
5678 if (blob)
5679 got_object_blob_close(blob);
5680 if (worktree)
5681 got_worktree_close(worktree);
5682 if (repo) {
5683 const struct got_error *close_err = got_repo_close(repo);
5684 if (error == NULL)
5685 error = close_err;
5687 if (pack_fds) {
5688 const struct got_error *pack_err =
5689 got_repo_pack_fds_close(pack_fds);
5690 if (error == NULL)
5691 error = pack_err;
5693 if (bca.lines) {
5694 for (i = 0; i < bca.nlines; i++) {
5695 struct blame_line *bline = &bca.lines[i];
5696 free(bline->id_str);
5697 free(bline->committer);
5699 free(bca.lines);
5701 free(bca.line_offsets);
5702 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5703 error = got_error_from_errno("fclose");
5704 return error;
5707 __dead static void
5708 usage_tree(void)
5710 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5711 "[path]\n", getprogname());
5712 exit(1);
5715 static const struct got_error *
5716 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5717 const char *root_path, struct got_repository *repo)
5719 const struct got_error *err = NULL;
5720 int is_root_path = (strcmp(path, root_path) == 0);
5721 const char *modestr = "";
5722 mode_t mode = got_tree_entry_get_mode(te);
5723 char *link_target = NULL;
5725 path += strlen(root_path);
5726 while (path[0] == '/')
5727 path++;
5729 if (got_object_tree_entry_is_submodule(te))
5730 modestr = "$";
5731 else if (S_ISLNK(mode)) {
5732 int i;
5734 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5735 if (err)
5736 return err;
5737 for (i = 0; i < strlen(link_target); i++) {
5738 if (!isprint((unsigned char)link_target[i]))
5739 link_target[i] = '?';
5742 modestr = "@";
5744 else if (S_ISDIR(mode))
5745 modestr = "/";
5746 else if (mode & S_IXUSR)
5747 modestr = "*";
5749 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5750 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5751 link_target ? " -> ": "", link_target ? link_target : "");
5753 free(link_target);
5754 return NULL;
5757 static const struct got_error *
5758 print_tree(const char *path, struct got_commit_object *commit,
5759 int show_ids, int recurse, const char *root_path,
5760 struct got_repository *repo)
5762 const struct got_error *err = NULL;
5763 struct got_object_id *tree_id = NULL;
5764 struct got_tree_object *tree = NULL;
5765 int nentries, i;
5767 err = got_object_id_by_path(&tree_id, repo, commit, path);
5768 if (err)
5769 goto done;
5771 err = got_object_open_as_tree(&tree, repo, tree_id);
5772 if (err)
5773 goto done;
5774 nentries = got_object_tree_get_nentries(tree);
5775 for (i = 0; i < nentries; i++) {
5776 struct got_tree_entry *te;
5777 char *id = NULL;
5779 if (sigint_received || sigpipe_received)
5780 break;
5782 te = got_object_tree_get_entry(tree, i);
5783 if (show_ids) {
5784 char *id_str;
5785 err = got_object_id_str(&id_str,
5786 got_tree_entry_get_id(te));
5787 if (err)
5788 goto done;
5789 if (asprintf(&id, "%s ", id_str) == -1) {
5790 err = got_error_from_errno("asprintf");
5791 free(id_str);
5792 goto done;
5794 free(id_str);
5796 err = print_entry(te, id, path, root_path, repo);
5797 free(id);
5798 if (err)
5799 goto done;
5801 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5802 char *child_path;
5803 if (asprintf(&child_path, "%s%s%s", path,
5804 path[0] == '/' && path[1] == '\0' ? "" : "/",
5805 got_tree_entry_get_name(te)) == -1) {
5806 err = got_error_from_errno("asprintf");
5807 goto done;
5809 err = print_tree(child_path, commit, show_ids, 1,
5810 root_path, repo);
5811 free(child_path);
5812 if (err)
5813 goto done;
5816 done:
5817 if (tree)
5818 got_object_tree_close(tree);
5819 free(tree_id);
5820 return err;
5823 static const struct got_error *
5824 cmd_tree(int argc, char *argv[])
5826 const struct got_error *error;
5827 struct got_repository *repo = NULL;
5828 struct got_worktree *worktree = NULL;
5829 const char *path, *refname = NULL;
5830 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5831 struct got_object_id *commit_id = NULL;
5832 struct got_commit_object *commit = NULL;
5833 char *commit_id_str = NULL;
5834 int show_ids = 0, recurse = 0;
5835 int ch;
5836 int *pack_fds = NULL;
5838 #ifndef PROFILE
5839 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5840 NULL) == -1)
5841 err(1, "pledge");
5842 #endif
5844 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5845 switch (ch) {
5846 case 'c':
5847 commit_id_str = optarg;
5848 break;
5849 case 'i':
5850 show_ids = 1;
5851 break;
5852 case 'R':
5853 recurse = 1;
5854 break;
5855 case 'r':
5856 repo_path = realpath(optarg, NULL);
5857 if (repo_path == NULL)
5858 return got_error_from_errno2("realpath",
5859 optarg);
5860 got_path_strip_trailing_slashes(repo_path);
5861 break;
5862 default:
5863 usage_tree();
5864 /* NOTREACHED */
5868 argc -= optind;
5869 argv += optind;
5871 if (argc == 1)
5872 path = argv[0];
5873 else if (argc > 1)
5874 usage_tree();
5875 else
5876 path = NULL;
5878 cwd = getcwd(NULL, 0);
5879 if (cwd == NULL) {
5880 error = got_error_from_errno("getcwd");
5881 goto done;
5884 error = got_repo_pack_fds_open(&pack_fds);
5885 if (error != NULL)
5886 goto done;
5888 if (repo_path == NULL) {
5889 error = got_worktree_open(&worktree, cwd);
5890 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5891 goto done;
5892 else
5893 error = NULL;
5894 if (worktree) {
5895 repo_path =
5896 strdup(got_worktree_get_repo_path(worktree));
5897 if (repo_path == NULL)
5898 error = got_error_from_errno("strdup");
5899 if (error)
5900 goto done;
5901 } else {
5902 repo_path = strdup(cwd);
5903 if (repo_path == NULL) {
5904 error = got_error_from_errno("strdup");
5905 goto done;
5910 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5911 if (error != NULL)
5912 goto done;
5914 if (worktree) {
5915 const char *prefix = got_worktree_get_path_prefix(worktree);
5916 char *p;
5918 if (path == NULL)
5919 path = "";
5920 error = got_worktree_resolve_path(&p, worktree, path);
5921 if (error)
5922 goto done;
5923 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5924 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5925 p) == -1) {
5926 error = got_error_from_errno("asprintf");
5927 free(p);
5928 goto done;
5930 free(p);
5931 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5932 if (error)
5933 goto done;
5934 } else {
5935 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5936 if (error)
5937 goto done;
5938 if (path == NULL)
5939 path = "/";
5940 error = got_repo_map_path(&in_repo_path, repo, path);
5941 if (error != NULL)
5942 goto done;
5945 if (commit_id_str == NULL) {
5946 struct got_reference *head_ref;
5947 if (worktree)
5948 refname = got_worktree_get_head_ref_name(worktree);
5949 else
5950 refname = GOT_REF_HEAD;
5951 error = got_ref_open(&head_ref, repo, refname, 0);
5952 if (error != NULL)
5953 goto done;
5954 error = got_ref_resolve(&commit_id, repo, head_ref);
5955 got_ref_close(head_ref);
5956 if (error != NULL)
5957 goto done;
5958 } else {
5959 struct got_reflist_head refs;
5960 TAILQ_INIT(&refs);
5961 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5962 NULL);
5963 if (error)
5964 goto done;
5965 error = got_repo_match_object_id(&commit_id, NULL,
5966 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5967 got_ref_list_free(&refs);
5968 if (error)
5969 goto done;
5972 if (worktree) {
5973 /* Release work tree lock. */
5974 got_worktree_close(worktree);
5975 worktree = NULL;
5978 error = got_object_open_as_commit(&commit, repo, commit_id);
5979 if (error)
5980 goto done;
5982 error = print_tree(in_repo_path, commit, show_ids, recurse,
5983 in_repo_path, repo);
5984 done:
5985 free(in_repo_path);
5986 free(repo_path);
5987 free(cwd);
5988 free(commit_id);
5989 if (commit)
5990 got_object_commit_close(commit);
5991 if (worktree)
5992 got_worktree_close(worktree);
5993 if (repo) {
5994 const struct got_error *close_err = got_repo_close(repo);
5995 if (error == NULL)
5996 error = close_err;
5998 if (pack_fds) {
5999 const struct got_error *pack_err =
6000 got_repo_pack_fds_close(pack_fds);
6001 if (error == NULL)
6002 error = pack_err;
6004 return error;
6007 __dead static void
6008 usage_status(void)
6010 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6011 "[-s status-codes] [path ...]\n", getprogname());
6012 exit(1);
6015 struct got_status_arg {
6016 char *status_codes;
6017 int suppress;
6020 static const struct got_error *
6021 print_status(void *arg, unsigned char status, unsigned char staged_status,
6022 const char *path, struct got_object_id *blob_id,
6023 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6024 int dirfd, const char *de_name)
6026 struct got_status_arg *st = arg;
6028 if (status == staged_status && (status == GOT_STATUS_DELETE))
6029 status = GOT_STATUS_NO_CHANGE;
6030 if (st != NULL && st->status_codes) {
6031 size_t ncodes = strlen(st->status_codes);
6032 int i, j = 0;
6034 for (i = 0; i < ncodes ; i++) {
6035 if (st->suppress) {
6036 if (status == st->status_codes[i] ||
6037 staged_status == st->status_codes[i]) {
6038 j++;
6039 continue;
6041 } else {
6042 if (status == st->status_codes[i] ||
6043 staged_status == st->status_codes[i])
6044 break;
6048 if (st->suppress && j == 0)
6049 goto print;
6051 if (i == ncodes)
6052 return NULL;
6054 print:
6055 printf("%c%c %s\n", status, staged_status, path);
6056 return NULL;
6059 static const struct got_error *
6060 cmd_status(int argc, char *argv[])
6062 const struct got_error *error = NULL;
6063 struct got_repository *repo = NULL;
6064 struct got_worktree *worktree = NULL;
6065 struct got_status_arg st;
6066 char *cwd = NULL;
6067 struct got_pathlist_head paths;
6068 struct got_pathlist_entry *pe;
6069 int ch, i, no_ignores = 0;
6070 int *pack_fds = NULL;
6072 TAILQ_INIT(&paths);
6074 memset(&st, 0, sizeof(st));
6075 st.status_codes = NULL;
6076 st.suppress = 0;
6078 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6079 switch (ch) {
6080 case 'I':
6081 no_ignores = 1;
6082 break;
6083 case 'S':
6084 if (st.status_codes != NULL && st.suppress == 0)
6085 option_conflict('S', 's');
6086 st.suppress = 1;
6087 /* fallthrough */
6088 case 's':
6089 for (i = 0; i < strlen(optarg); i++) {
6090 switch (optarg[i]) {
6091 case GOT_STATUS_MODIFY:
6092 case GOT_STATUS_ADD:
6093 case GOT_STATUS_DELETE:
6094 case GOT_STATUS_CONFLICT:
6095 case GOT_STATUS_MISSING:
6096 case GOT_STATUS_OBSTRUCTED:
6097 case GOT_STATUS_UNVERSIONED:
6098 case GOT_STATUS_MODE_CHANGE:
6099 case GOT_STATUS_NONEXISTENT:
6100 break;
6101 default:
6102 errx(1, "invalid status code '%c'",
6103 optarg[i]);
6106 if (ch == 's' && st.suppress)
6107 option_conflict('s', 'S');
6108 st.status_codes = optarg;
6109 break;
6110 default:
6111 usage_status();
6112 /* NOTREACHED */
6116 argc -= optind;
6117 argv += optind;
6119 #ifndef PROFILE
6120 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6121 NULL) == -1)
6122 err(1, "pledge");
6123 #endif
6124 cwd = getcwd(NULL, 0);
6125 if (cwd == NULL) {
6126 error = got_error_from_errno("getcwd");
6127 goto done;
6130 error = got_repo_pack_fds_open(&pack_fds);
6131 if (error != NULL)
6132 goto done;
6134 error = got_worktree_open(&worktree, cwd);
6135 if (error) {
6136 if (error->code == GOT_ERR_NOT_WORKTREE)
6137 error = wrap_not_worktree_error(error, "status", cwd);
6138 goto done;
6141 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6142 NULL, pack_fds);
6143 if (error != NULL)
6144 goto done;
6146 error = apply_unveil(got_repo_get_path(repo), 1,
6147 got_worktree_get_root_path(worktree));
6148 if (error)
6149 goto done;
6151 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6152 if (error)
6153 goto done;
6155 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6156 print_status, &st, check_cancelled, NULL);
6157 done:
6158 if (pack_fds) {
6159 const struct got_error *pack_err =
6160 got_repo_pack_fds_close(pack_fds);
6161 if (error == NULL)
6162 error = pack_err;
6165 TAILQ_FOREACH(pe, &paths, entry)
6166 free((char *)pe->path);
6167 got_pathlist_free(&paths);
6168 free(cwd);
6169 return error;
6172 __dead static void
6173 usage_ref(void)
6175 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6176 "[-s reference] [name]\n", getprogname());
6177 exit(1);
6180 static const struct got_error *
6181 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6183 static const struct got_error *err = NULL;
6184 struct got_reflist_head refs;
6185 struct got_reflist_entry *re;
6187 TAILQ_INIT(&refs);
6188 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6189 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6190 repo);
6191 if (err)
6192 return err;
6194 TAILQ_FOREACH(re, &refs, entry) {
6195 char *refstr;
6196 refstr = got_ref_to_str(re->ref);
6197 if (refstr == NULL) {
6198 err = got_error_from_errno("got_ref_to_str");
6199 break;
6201 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6202 free(refstr);
6205 got_ref_list_free(&refs);
6206 return err;
6209 static const struct got_error *
6210 delete_ref_by_name(struct got_repository *repo, const char *refname)
6212 const struct got_error *err;
6213 struct got_reference *ref;
6215 err = got_ref_open(&ref, repo, refname, 0);
6216 if (err)
6217 return err;
6219 err = delete_ref(repo, ref);
6220 got_ref_close(ref);
6221 return err;
6224 static const struct got_error *
6225 add_ref(struct got_repository *repo, const char *refname, const char *target)
6227 const struct got_error *err = NULL;
6228 struct got_object_id *id = NULL;
6229 struct got_reference *ref = NULL;
6230 struct got_reflist_head refs;
6233 * Don't let the user create a reference name with a leading '-'.
6234 * While technically a valid reference name, this case is usually
6235 * an unintended typo.
6237 if (refname[0] == '-')
6238 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6240 TAILQ_INIT(&refs);
6241 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6242 if (err)
6243 goto done;
6244 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6245 &refs, repo);
6246 got_ref_list_free(&refs);
6247 if (err)
6248 goto done;
6250 err = got_ref_alloc(&ref, refname, id);
6251 if (err)
6252 goto done;
6254 err = got_ref_write(ref, repo);
6255 done:
6256 if (ref)
6257 got_ref_close(ref);
6258 free(id);
6259 return err;
6262 static const struct got_error *
6263 add_symref(struct got_repository *repo, const char *refname, const char *target)
6265 const struct got_error *err = NULL;
6266 struct got_reference *ref = NULL;
6267 struct got_reference *target_ref = NULL;
6270 * Don't let the user create a reference name with a leading '-'.
6271 * While technically a valid reference name, this case is usually
6272 * an unintended typo.
6274 if (refname[0] == '-')
6275 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6277 err = got_ref_open(&target_ref, repo, target, 0);
6278 if (err)
6279 return err;
6281 err = got_ref_alloc_symref(&ref, refname, target_ref);
6282 if (err)
6283 goto done;
6285 err = got_ref_write(ref, repo);
6286 done:
6287 if (target_ref)
6288 got_ref_close(target_ref);
6289 if (ref)
6290 got_ref_close(ref);
6291 return err;
6294 static const struct got_error *
6295 cmd_ref(int argc, char *argv[])
6297 const struct got_error *error = NULL;
6298 struct got_repository *repo = NULL;
6299 struct got_worktree *worktree = NULL;
6300 char *cwd = NULL, *repo_path = NULL;
6301 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6302 const char *obj_arg = NULL, *symref_target= NULL;
6303 char *refname = NULL;
6304 int *pack_fds = NULL;
6306 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6307 switch (ch) {
6308 case 'c':
6309 obj_arg = optarg;
6310 break;
6311 case 'd':
6312 do_delete = 1;
6313 break;
6314 case 'l':
6315 do_list = 1;
6316 break;
6317 case 'r':
6318 repo_path = realpath(optarg, NULL);
6319 if (repo_path == NULL)
6320 return got_error_from_errno2("realpath",
6321 optarg);
6322 got_path_strip_trailing_slashes(repo_path);
6323 break;
6324 case 's':
6325 symref_target = optarg;
6326 break;
6327 case 't':
6328 sort_by_time = 1;
6329 break;
6330 default:
6331 usage_ref();
6332 /* NOTREACHED */
6336 if (obj_arg && do_list)
6337 option_conflict('c', 'l');
6338 if (obj_arg && do_delete)
6339 option_conflict('c', 'd');
6340 if (obj_arg && symref_target)
6341 option_conflict('c', 's');
6342 if (symref_target && do_delete)
6343 option_conflict('s', 'd');
6344 if (symref_target && do_list)
6345 option_conflict('s', 'l');
6346 if (do_delete && do_list)
6347 option_conflict('d', 'l');
6348 if (sort_by_time && !do_list)
6349 errx(1, "-t option requires -l option");
6351 argc -= optind;
6352 argv += optind;
6354 if (do_list) {
6355 if (argc != 0 && argc != 1)
6356 usage_ref();
6357 if (argc == 1) {
6358 refname = strdup(argv[0]);
6359 if (refname == NULL) {
6360 error = got_error_from_errno("strdup");
6361 goto done;
6364 } else {
6365 if (argc != 1)
6366 usage_ref();
6367 refname = strdup(argv[0]);
6368 if (refname == NULL) {
6369 error = got_error_from_errno("strdup");
6370 goto done;
6374 if (refname)
6375 got_path_strip_trailing_slashes(refname);
6377 #ifndef PROFILE
6378 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6379 "sendfd unveil", NULL) == -1)
6380 err(1, "pledge");
6381 #endif
6382 cwd = getcwd(NULL, 0);
6383 if (cwd == NULL) {
6384 error = got_error_from_errno("getcwd");
6385 goto done;
6388 error = got_repo_pack_fds_open(&pack_fds);
6389 if (error != NULL)
6390 goto done;
6392 if (repo_path == NULL) {
6393 error = got_worktree_open(&worktree, cwd);
6394 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6395 goto done;
6396 else
6397 error = NULL;
6398 if (worktree) {
6399 repo_path =
6400 strdup(got_worktree_get_repo_path(worktree));
6401 if (repo_path == NULL)
6402 error = got_error_from_errno("strdup");
6403 if (error)
6404 goto done;
6405 } else {
6406 repo_path = strdup(cwd);
6407 if (repo_path == NULL) {
6408 error = got_error_from_errno("strdup");
6409 goto done;
6414 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6415 if (error != NULL)
6416 goto done;
6418 #ifndef PROFILE
6419 if (do_list) {
6420 /* Remove "cpath" promise. */
6421 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6422 NULL) == -1)
6423 err(1, "pledge");
6425 #endif
6427 error = apply_unveil(got_repo_get_path(repo), do_list,
6428 worktree ? got_worktree_get_root_path(worktree) : NULL);
6429 if (error)
6430 goto done;
6432 if (do_list)
6433 error = list_refs(repo, refname, sort_by_time);
6434 else if (do_delete)
6435 error = delete_ref_by_name(repo, refname);
6436 else if (symref_target)
6437 error = add_symref(repo, refname, symref_target);
6438 else {
6439 if (obj_arg == NULL)
6440 usage_ref();
6441 error = add_ref(repo, refname, obj_arg);
6443 done:
6444 free(refname);
6445 if (repo) {
6446 const struct got_error *close_err = got_repo_close(repo);
6447 if (error == NULL)
6448 error = close_err;
6450 if (worktree)
6451 got_worktree_close(worktree);
6452 if (pack_fds) {
6453 const struct got_error *pack_err =
6454 got_repo_pack_fds_close(pack_fds);
6455 if (error == NULL)
6456 error = pack_err;
6458 free(cwd);
6459 free(repo_path);
6460 return error;
6463 __dead static void
6464 usage_branch(void)
6466 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6467 "[-r repository-path] [name]\n", getprogname());
6468 exit(1);
6471 static const struct got_error *
6472 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6473 struct got_reference *ref)
6475 const struct got_error *err = NULL;
6476 const char *refname, *marker = " ";
6477 char *refstr;
6479 refname = got_ref_get_name(ref);
6480 if (worktree && strcmp(refname,
6481 got_worktree_get_head_ref_name(worktree)) == 0) {
6482 struct got_object_id *id = NULL;
6484 err = got_ref_resolve(&id, repo, ref);
6485 if (err)
6486 return err;
6487 if (got_object_id_cmp(id,
6488 got_worktree_get_base_commit_id(worktree)) == 0)
6489 marker = "* ";
6490 else
6491 marker = "~ ";
6492 free(id);
6495 if (strncmp(refname, "refs/heads/", 11) == 0)
6496 refname += 11;
6497 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6498 refname += 18;
6499 if (strncmp(refname, "refs/remotes/", 13) == 0)
6500 refname += 13;
6502 refstr = got_ref_to_str(ref);
6503 if (refstr == NULL)
6504 return got_error_from_errno("got_ref_to_str");
6506 printf("%s%s: %s\n", marker, refname, refstr);
6507 free(refstr);
6508 return NULL;
6511 static const struct got_error *
6512 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6514 const char *refname;
6516 if (worktree == NULL)
6517 return got_error(GOT_ERR_NOT_WORKTREE);
6519 refname = got_worktree_get_head_ref_name(worktree);
6521 if (strncmp(refname, "refs/heads/", 11) == 0)
6522 refname += 11;
6523 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6524 refname += 18;
6526 printf("%s\n", refname);
6528 return NULL;
6531 static const struct got_error *
6532 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6533 int sort_by_time)
6535 static const struct got_error *err = NULL;
6536 struct got_reflist_head refs;
6537 struct got_reflist_entry *re;
6538 struct got_reference *temp_ref = NULL;
6539 int rebase_in_progress, histedit_in_progress;
6541 TAILQ_INIT(&refs);
6543 if (worktree) {
6544 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6545 worktree);
6546 if (err)
6547 return err;
6549 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6550 worktree);
6551 if (err)
6552 return err;
6554 if (rebase_in_progress || histedit_in_progress) {
6555 err = got_ref_open(&temp_ref, repo,
6556 got_worktree_get_head_ref_name(worktree), 0);
6557 if (err)
6558 return err;
6559 list_branch(repo, worktree, temp_ref);
6560 got_ref_close(temp_ref);
6564 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6565 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6566 repo);
6567 if (err)
6568 return err;
6570 TAILQ_FOREACH(re, &refs, entry)
6571 list_branch(repo, worktree, re->ref);
6573 got_ref_list_free(&refs);
6575 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6576 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6577 repo);
6578 if (err)
6579 return err;
6581 TAILQ_FOREACH(re, &refs, entry)
6582 list_branch(repo, worktree, re->ref);
6584 got_ref_list_free(&refs);
6586 return NULL;
6589 static const struct got_error *
6590 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6591 const char *branch_name)
6593 const struct got_error *err = NULL;
6594 struct got_reference *ref = NULL;
6595 char *refname, *remote_refname = NULL;
6597 if (strncmp(branch_name, "refs/", 5) == 0)
6598 branch_name += 5;
6599 if (strncmp(branch_name, "heads/", 6) == 0)
6600 branch_name += 6;
6601 else if (strncmp(branch_name, "remotes/", 8) == 0)
6602 branch_name += 8;
6604 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6605 return got_error_from_errno("asprintf");
6607 if (asprintf(&remote_refname, "refs/remotes/%s",
6608 branch_name) == -1) {
6609 err = got_error_from_errno("asprintf");
6610 goto done;
6613 err = got_ref_open(&ref, repo, refname, 0);
6614 if (err) {
6615 const struct got_error *err2;
6616 if (err->code != GOT_ERR_NOT_REF)
6617 goto done;
6619 * Keep 'err' intact such that if neither branch exists
6620 * we report "refs/heads" rather than "refs/remotes" in
6621 * our error message.
6623 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6624 if (err2)
6625 goto done;
6626 err = NULL;
6629 if (worktree &&
6630 strcmp(got_worktree_get_head_ref_name(worktree),
6631 got_ref_get_name(ref)) == 0) {
6632 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6633 "will not delete this work tree's current branch");
6634 goto done;
6637 err = delete_ref(repo, ref);
6638 done:
6639 if (ref)
6640 got_ref_close(ref);
6641 free(refname);
6642 free(remote_refname);
6643 return err;
6646 static const struct got_error *
6647 add_branch(struct got_repository *repo, const char *branch_name,
6648 struct got_object_id *base_commit_id)
6650 const struct got_error *err = NULL;
6651 struct got_reference *ref = NULL;
6652 char *base_refname = NULL, *refname = NULL;
6655 * Don't let the user create a branch name with a leading '-'.
6656 * While technically a valid reference name, this case is usually
6657 * an unintended typo.
6659 if (branch_name[0] == '-')
6660 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6662 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6663 branch_name += 11;
6665 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6666 err = got_error_from_errno("asprintf");
6667 goto done;
6670 err = got_ref_open(&ref, repo, refname, 0);
6671 if (err == NULL) {
6672 err = got_error(GOT_ERR_BRANCH_EXISTS);
6673 goto done;
6674 } else if (err->code != GOT_ERR_NOT_REF)
6675 goto done;
6677 err = got_ref_alloc(&ref, refname, base_commit_id);
6678 if (err)
6679 goto done;
6681 err = got_ref_write(ref, repo);
6682 done:
6683 if (ref)
6684 got_ref_close(ref);
6685 free(base_refname);
6686 free(refname);
6687 return err;
6690 static const struct got_error *
6691 cmd_branch(int argc, char *argv[])
6693 const struct got_error *error = NULL;
6694 struct got_repository *repo = NULL;
6695 struct got_worktree *worktree = NULL;
6696 char *cwd = NULL, *repo_path = NULL;
6697 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6698 const char *delref = NULL, *commit_id_arg = NULL;
6699 struct got_reference *ref = NULL;
6700 struct got_pathlist_head paths;
6701 struct got_pathlist_entry *pe;
6702 struct got_object_id *commit_id = NULL;
6703 char *commit_id_str = NULL;
6704 int *pack_fds = NULL;
6706 TAILQ_INIT(&paths);
6708 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6709 switch (ch) {
6710 case 'c':
6711 commit_id_arg = optarg;
6712 break;
6713 case 'd':
6714 delref = optarg;
6715 break;
6716 case 'l':
6717 do_list = 1;
6718 break;
6719 case 'n':
6720 do_update = 0;
6721 break;
6722 case 'r':
6723 repo_path = realpath(optarg, NULL);
6724 if (repo_path == NULL)
6725 return got_error_from_errno2("realpath",
6726 optarg);
6727 got_path_strip_trailing_slashes(repo_path);
6728 break;
6729 case 't':
6730 sort_by_time = 1;
6731 break;
6732 default:
6733 usage_branch();
6734 /* NOTREACHED */
6738 if (do_list && delref)
6739 option_conflict('l', 'd');
6740 if (sort_by_time && !do_list)
6741 errx(1, "-t option requires -l option");
6743 argc -= optind;
6744 argv += optind;
6746 if (!do_list && !delref && argc == 0)
6747 do_show = 1;
6749 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6750 errx(1, "-c option can only be used when creating a branch");
6752 if (do_list || delref) {
6753 if (argc > 0)
6754 usage_branch();
6755 } else if (!do_show && argc != 1)
6756 usage_branch();
6758 #ifndef PROFILE
6759 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6760 "sendfd unveil", NULL) == -1)
6761 err(1, "pledge");
6762 #endif
6763 cwd = getcwd(NULL, 0);
6764 if (cwd == NULL) {
6765 error = got_error_from_errno("getcwd");
6766 goto done;
6769 error = got_repo_pack_fds_open(&pack_fds);
6770 if (error != NULL)
6771 goto done;
6773 if (repo_path == NULL) {
6774 error = got_worktree_open(&worktree, cwd);
6775 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6776 goto done;
6777 else
6778 error = NULL;
6779 if (worktree) {
6780 repo_path =
6781 strdup(got_worktree_get_repo_path(worktree));
6782 if (repo_path == NULL)
6783 error = got_error_from_errno("strdup");
6784 if (error)
6785 goto done;
6786 } else {
6787 repo_path = strdup(cwd);
6788 if (repo_path == NULL) {
6789 error = got_error_from_errno("strdup");
6790 goto done;
6795 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6796 if (error != NULL)
6797 goto done;
6799 #ifndef PROFILE
6800 if (do_list || do_show) {
6801 /* Remove "cpath" promise. */
6802 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6803 NULL) == -1)
6804 err(1, "pledge");
6806 #endif
6808 error = apply_unveil(got_repo_get_path(repo), do_list,
6809 worktree ? got_worktree_get_root_path(worktree) : NULL);
6810 if (error)
6811 goto done;
6813 if (do_show)
6814 error = show_current_branch(repo, worktree);
6815 else if (do_list)
6816 error = list_branches(repo, worktree, sort_by_time);
6817 else if (delref)
6818 error = delete_branch(repo, worktree, delref);
6819 else {
6820 struct got_reflist_head refs;
6821 TAILQ_INIT(&refs);
6822 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6823 NULL);
6824 if (error)
6825 goto done;
6826 if (commit_id_arg == NULL)
6827 commit_id_arg = worktree ?
6828 got_worktree_get_head_ref_name(worktree) :
6829 GOT_REF_HEAD;
6830 error = got_repo_match_object_id(&commit_id, NULL,
6831 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6832 got_ref_list_free(&refs);
6833 if (error)
6834 goto done;
6835 error = add_branch(repo, argv[0], commit_id);
6836 if (error)
6837 goto done;
6838 if (worktree && do_update) {
6839 struct got_update_progress_arg upa;
6840 char *branch_refname = NULL;
6842 error = got_object_id_str(&commit_id_str, commit_id);
6843 if (error)
6844 goto done;
6845 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6846 worktree);
6847 if (error)
6848 goto done;
6849 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6850 == -1) {
6851 error = got_error_from_errno("asprintf");
6852 goto done;
6854 error = got_ref_open(&ref, repo, branch_refname, 0);
6855 free(branch_refname);
6856 if (error)
6857 goto done;
6858 error = switch_head_ref(ref, commit_id, worktree,
6859 repo);
6860 if (error)
6861 goto done;
6862 error = got_worktree_set_base_commit_id(worktree, repo,
6863 commit_id);
6864 if (error)
6865 goto done;
6866 memset(&upa, 0, sizeof(upa));
6867 error = got_worktree_checkout_files(worktree, &paths,
6868 repo, update_progress, &upa, check_cancelled,
6869 NULL);
6870 if (error)
6871 goto done;
6872 if (upa.did_something) {
6873 printf("Updated to %s: %s\n",
6874 got_worktree_get_head_ref_name(worktree),
6875 commit_id_str);
6877 print_update_progress_stats(&upa);
6880 done:
6881 if (ref)
6882 got_ref_close(ref);
6883 if (repo) {
6884 const struct got_error *close_err = got_repo_close(repo);
6885 if (error == NULL)
6886 error = close_err;
6888 if (worktree)
6889 got_worktree_close(worktree);
6890 if (pack_fds) {
6891 const struct got_error *pack_err =
6892 got_repo_pack_fds_close(pack_fds);
6893 if (error == NULL)
6894 error = pack_err;
6896 free(cwd);
6897 free(repo_path);
6898 free(commit_id);
6899 free(commit_id_str);
6900 TAILQ_FOREACH(pe, &paths, entry)
6901 free((char *)pe->path);
6902 got_pathlist_free(&paths);
6903 return error;
6907 __dead static void
6908 usage_tag(void)
6910 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6911 "[-r repository-path] [-s signer-id] name\n", getprogname());
6912 exit(1);
6915 #if 0
6916 static const struct got_error *
6917 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6919 const struct got_error *err = NULL;
6920 struct got_reflist_entry *re, *se, *new;
6921 struct got_object_id *re_id, *se_id;
6922 struct got_tag_object *re_tag, *se_tag;
6923 time_t re_time, se_time;
6925 STAILQ_FOREACH(re, tags, entry) {
6926 se = STAILQ_FIRST(sorted);
6927 if (se == NULL) {
6928 err = got_reflist_entry_dup(&new, re);
6929 if (err)
6930 return err;
6931 STAILQ_INSERT_HEAD(sorted, new, entry);
6932 continue;
6933 } else {
6934 err = got_ref_resolve(&re_id, repo, re->ref);
6935 if (err)
6936 break;
6937 err = got_object_open_as_tag(&re_tag, repo, re_id);
6938 free(re_id);
6939 if (err)
6940 break;
6941 re_time = got_object_tag_get_tagger_time(re_tag);
6942 got_object_tag_close(re_tag);
6945 while (se) {
6946 err = got_ref_resolve(&se_id, repo, re->ref);
6947 if (err)
6948 break;
6949 err = got_object_open_as_tag(&se_tag, repo, se_id);
6950 free(se_id);
6951 if (err)
6952 break;
6953 se_time = got_object_tag_get_tagger_time(se_tag);
6954 got_object_tag_close(se_tag);
6956 if (se_time > re_time) {
6957 err = got_reflist_entry_dup(&new, re);
6958 if (err)
6959 return err;
6960 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6961 break;
6963 se = STAILQ_NEXT(se, entry);
6964 continue;
6967 done:
6968 return err;
6970 #endif
6972 static const struct got_error *
6973 get_tag_refname(char **refname, const char *tag_name)
6975 const struct got_error *err;
6977 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6978 *refname = strdup(tag_name);
6979 if (*refname == NULL)
6980 return got_error_from_errno("strdup");
6981 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6982 err = got_error_from_errno("asprintf");
6983 *refname = NULL;
6984 return err;
6987 return NULL;
6990 static const struct got_error *
6991 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6992 const char *allowed_signers, const char *revoked_signers, int verbosity)
6994 static const struct got_error *err = NULL;
6995 struct got_reflist_head refs;
6996 struct got_reflist_entry *re;
6997 char *wanted_refname = NULL;
6998 int bad_sigs = 0;
7000 TAILQ_INIT(&refs);
7002 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7003 if (err)
7004 return err;
7006 if (tag_name) {
7007 struct got_reference *ref;
7008 err = get_tag_refname(&wanted_refname, tag_name);
7009 if (err)
7010 goto done;
7011 /* Wanted tag reference should exist. */
7012 err = got_ref_open(&ref, repo, wanted_refname, 0);
7013 if (err)
7014 goto done;
7015 got_ref_close(ref);
7018 TAILQ_FOREACH(re, &refs, entry) {
7019 const char *refname;
7020 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7021 char datebuf[26];
7022 const char *tagger, *ssh_sig = NULL;
7023 char *sig_msg = NULL;
7024 time_t tagger_time;
7025 struct got_object_id *id;
7026 struct got_tag_object *tag;
7027 struct got_commit_object *commit = NULL;
7029 refname = got_ref_get_name(re->ref);
7030 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7031 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7032 continue;
7033 refname += 10;
7034 refstr = got_ref_to_str(re->ref);
7035 if (refstr == NULL) {
7036 err = got_error_from_errno("got_ref_to_str");
7037 break;
7040 err = got_ref_resolve(&id, repo, re->ref);
7041 if (err)
7042 break;
7043 err = got_object_open_as_tag(&tag, repo, id);
7044 if (err) {
7045 if (err->code != GOT_ERR_OBJ_TYPE) {
7046 free(id);
7047 break;
7049 /* "lightweight" tag */
7050 err = got_object_open_as_commit(&commit, repo, id);
7051 if (err) {
7052 free(id);
7053 break;
7055 tagger = got_object_commit_get_committer(commit);
7056 tagger_time =
7057 got_object_commit_get_committer_time(commit);
7058 err = got_object_id_str(&id_str, id);
7059 free(id);
7060 if (err)
7061 break;
7062 } else {
7063 free(id);
7064 tagger = got_object_tag_get_tagger(tag);
7065 tagger_time = got_object_tag_get_tagger_time(tag);
7066 err = got_object_id_str(&id_str,
7067 got_object_tag_get_object_id(tag));
7068 if (err)
7069 break;
7072 if (tag && verify_tags) {
7073 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7074 got_object_tag_get_message(tag));
7075 if (ssh_sig && allowed_signers == NULL) {
7076 err = got_error_msg(
7077 GOT_ERR_VERIFY_TAG_SIGNATURE,
7078 "SSH signature verification requires "
7079 "setting allowed_signers in "
7080 "got.conf(5)");
7081 break;
7085 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7086 free(refstr);
7087 printf("from: %s\n", tagger);
7088 datestr = get_datestr(&tagger_time, datebuf);
7089 if (datestr)
7090 printf("date: %s UTC\n", datestr);
7091 if (commit)
7092 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7093 else {
7094 switch (got_object_tag_get_object_type(tag)) {
7095 case GOT_OBJ_TYPE_BLOB:
7096 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7097 id_str);
7098 break;
7099 case GOT_OBJ_TYPE_TREE:
7100 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7101 id_str);
7102 break;
7103 case GOT_OBJ_TYPE_COMMIT:
7104 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7105 id_str);
7106 break;
7107 case GOT_OBJ_TYPE_TAG:
7108 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7109 id_str);
7110 break;
7111 default:
7112 break;
7115 free(id_str);
7117 if (ssh_sig) {
7118 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7119 allowed_signers, revoked_signers, verbosity);
7120 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7121 bad_sigs = 1;
7122 else if (err)
7123 break;
7124 printf("signature: %s", sig_msg);
7125 free(sig_msg);
7126 sig_msg = NULL;
7129 if (commit) {
7130 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7131 if (err)
7132 break;
7133 got_object_commit_close(commit);
7134 } else {
7135 tagmsg0 = strdup(got_object_tag_get_message(tag));
7136 got_object_tag_close(tag);
7137 if (tagmsg0 == NULL) {
7138 err = got_error_from_errno("strdup");
7139 break;
7143 tagmsg = tagmsg0;
7144 do {
7145 line = strsep(&tagmsg, "\n");
7146 if (line)
7147 printf(" %s\n", line);
7148 } while (line);
7149 free(tagmsg0);
7151 done:
7152 got_ref_list_free(&refs);
7153 free(wanted_refname);
7155 if (err == NULL && bad_sigs)
7156 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7157 return err;
7160 static const struct got_error *
7161 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7162 const char *tag_name, const char *repo_path)
7164 const struct got_error *err = NULL;
7165 char *template = NULL, *initial_content = NULL;
7166 char *editor = NULL;
7167 int initial_content_len;
7168 int fd = -1;
7170 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7171 err = got_error_from_errno("asprintf");
7172 goto done;
7175 initial_content_len = asprintf(&initial_content,
7176 "\n# tagging commit %s as %s\n",
7177 commit_id_str, tag_name);
7178 if (initial_content_len == -1) {
7179 err = got_error_from_errno("asprintf");
7180 goto done;
7183 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7184 if (err)
7185 goto done;
7187 if (write(fd, initial_content, initial_content_len) == -1) {
7188 err = got_error_from_errno2("write", *tagmsg_path);
7189 goto done;
7192 err = get_editor(&editor);
7193 if (err)
7194 goto done;
7195 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7196 initial_content_len, 1);
7197 done:
7198 free(initial_content);
7199 free(template);
7200 free(editor);
7202 if (fd != -1 && close(fd) == -1 && err == NULL)
7203 err = got_error_from_errno2("close", *tagmsg_path);
7205 if (err) {
7206 free(*tagmsg);
7207 *tagmsg = NULL;
7209 return err;
7212 static const struct got_error *
7213 add_tag(struct got_repository *repo, const char *tagger,
7214 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7215 const char *signer_id, int verbosity)
7217 const struct got_error *err = NULL;
7218 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7219 char *label = NULL, *commit_id_str = NULL;
7220 struct got_reference *ref = NULL;
7221 char *refname = NULL, *tagmsg = NULL;
7222 char *tagmsg_path = NULL, *tag_id_str = NULL;
7223 int preserve_tagmsg = 0;
7224 struct got_reflist_head refs;
7226 TAILQ_INIT(&refs);
7229 * Don't let the user create a tag name with a leading '-'.
7230 * While technically a valid reference name, this case is usually
7231 * an unintended typo.
7233 if (tag_name[0] == '-')
7234 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7236 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7237 if (err)
7238 goto done;
7240 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7241 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7242 if (err)
7243 goto done;
7245 err = got_object_id_str(&commit_id_str, commit_id);
7246 if (err)
7247 goto done;
7249 err = get_tag_refname(&refname, tag_name);
7250 if (err)
7251 goto done;
7252 if (strncmp("refs/tags/", tag_name, 10) == 0)
7253 tag_name += 10;
7255 err = got_ref_open(&ref, repo, refname, 0);
7256 if (err == NULL) {
7257 err = got_error(GOT_ERR_TAG_EXISTS);
7258 goto done;
7259 } else if (err->code != GOT_ERR_NOT_REF)
7260 goto done;
7262 if (tagmsg_arg == NULL) {
7263 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7264 tag_name, got_repo_get_path(repo));
7265 if (err) {
7266 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7267 tagmsg_path != NULL)
7268 preserve_tagmsg = 1;
7269 goto done;
7271 /* Editor is done; we can now apply unveil(2) */
7272 err = got_sigs_apply_unveil();
7273 if (err)
7274 goto done;
7275 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7276 if (err)
7277 goto done;
7280 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7281 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7282 verbosity);
7283 if (err) {
7284 if (tagmsg_path)
7285 preserve_tagmsg = 1;
7286 goto done;
7289 err = got_ref_alloc(&ref, refname, tag_id);
7290 if (err) {
7291 if (tagmsg_path)
7292 preserve_tagmsg = 1;
7293 goto done;
7296 err = got_ref_write(ref, repo);
7297 if (err) {
7298 if (tagmsg_path)
7299 preserve_tagmsg = 1;
7300 goto done;
7303 err = got_object_id_str(&tag_id_str, tag_id);
7304 if (err) {
7305 if (tagmsg_path)
7306 preserve_tagmsg = 1;
7307 goto done;
7309 printf("Created tag %s\n", tag_id_str);
7310 done:
7311 if (preserve_tagmsg) {
7312 fprintf(stderr, "%s: tag message preserved in %s\n",
7313 getprogname(), tagmsg_path);
7314 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7315 err = got_error_from_errno2("unlink", tagmsg_path);
7316 free(tag_id_str);
7317 if (ref)
7318 got_ref_close(ref);
7319 free(commit_id);
7320 free(commit_id_str);
7321 free(refname);
7322 free(tagmsg);
7323 free(tagmsg_path);
7324 got_ref_list_free(&refs);
7325 return err;
7328 static const struct got_error *
7329 cmd_tag(int argc, char *argv[])
7331 const struct got_error *error = NULL;
7332 struct got_repository *repo = NULL;
7333 struct got_worktree *worktree = NULL;
7334 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7335 char *gitconfig_path = NULL, *tagger = NULL;
7336 char *allowed_signers = NULL, *revoked_signers = NULL;
7337 char *signer_id = NULL;
7338 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7339 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7340 int *pack_fds = NULL;
7342 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7343 switch (ch) {
7344 case 'c':
7345 commit_id_arg = optarg;
7346 break;
7347 case 'l':
7348 do_list = 1;
7349 break;
7350 case 'm':
7351 tagmsg = optarg;
7352 break;
7353 case 'r':
7354 repo_path = realpath(optarg, NULL);
7355 if (repo_path == NULL) {
7356 error = got_error_from_errno2("realpath",
7357 optarg);
7358 goto done;
7360 got_path_strip_trailing_slashes(repo_path);
7361 break;
7362 case 's':
7363 signer_id = strdup(optarg);
7364 if (signer_id == NULL) {
7365 error = got_error_from_errno("strdup");
7366 goto done;
7368 break;
7369 case 'V':
7370 verify_tags = 1;
7371 break;
7372 case 'v':
7373 if (verbosity < 0)
7374 verbosity = 0;
7375 else if (verbosity < 3)
7376 verbosity++;
7377 break;
7378 default:
7379 usage_tag();
7380 /* NOTREACHED */
7384 argc -= optind;
7385 argv += optind;
7387 if (do_list || verify_tags) {
7388 if (commit_id_arg != NULL)
7389 errx(1,
7390 "-c option can only be used when creating a tag");
7391 if (tagmsg) {
7392 if (do_list)
7393 option_conflict('l', 'm');
7394 else
7395 option_conflict('V', 'm');
7397 if (signer_id) {
7398 if (do_list)
7399 option_conflict('l', 's');
7400 else
7401 option_conflict('V', 's');
7403 if (argc > 1)
7404 usage_tag();
7405 } else if (argc != 1)
7406 usage_tag();
7408 if (argc == 1)
7409 tag_name = argv[0];
7411 #ifndef PROFILE
7412 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7413 "sendfd unveil", NULL) == -1)
7414 err(1, "pledge");
7415 #endif
7416 cwd = getcwd(NULL, 0);
7417 if (cwd == NULL) {
7418 error = got_error_from_errno("getcwd");
7419 goto done;
7422 error = got_repo_pack_fds_open(&pack_fds);
7423 if (error != NULL)
7424 goto done;
7426 if (repo_path == NULL) {
7427 error = got_worktree_open(&worktree, cwd);
7428 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7429 goto done;
7430 else
7431 error = NULL;
7432 if (worktree) {
7433 repo_path =
7434 strdup(got_worktree_get_repo_path(worktree));
7435 if (repo_path == NULL)
7436 error = got_error_from_errno("strdup");
7437 if (error)
7438 goto done;
7439 } else {
7440 repo_path = strdup(cwd);
7441 if (repo_path == NULL) {
7442 error = got_error_from_errno("strdup");
7443 goto done;
7448 if (do_list || verify_tags) {
7449 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7450 if (error != NULL)
7451 goto done;
7452 error = get_allowed_signers(&allowed_signers, repo, worktree);
7453 if (error)
7454 goto done;
7455 error = get_revoked_signers(&revoked_signers, repo, worktree);
7456 if (error)
7457 goto done;
7458 if (worktree) {
7459 /* Release work tree lock. */
7460 got_worktree_close(worktree);
7461 worktree = NULL;
7465 * Remove "cpath" promise unless needed for signature tmpfile
7466 * creation.
7468 if (verify_tags)
7469 got_sigs_apply_unveil();
7470 else {
7471 #ifndef PROFILE
7472 if (pledge("stdio rpath wpath flock proc exec sendfd "
7473 "unveil", NULL) == -1)
7474 err(1, "pledge");
7475 #endif
7477 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7478 if (error)
7479 goto done;
7480 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7481 revoked_signers, verbosity);
7482 } else {
7483 error = get_gitconfig_path(&gitconfig_path);
7484 if (error)
7485 goto done;
7486 error = got_repo_open(&repo, repo_path, gitconfig_path,
7487 pack_fds);
7488 if (error != NULL)
7489 goto done;
7491 error = get_author(&tagger, repo, worktree);
7492 if (error)
7493 goto done;
7494 if (signer_id == NULL) {
7495 error = get_signer_id(&signer_id, repo, worktree);
7496 if (error)
7497 goto done;
7500 if (tagmsg) {
7501 if (signer_id) {
7502 error = got_sigs_apply_unveil();
7503 if (error)
7504 goto done;
7506 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7507 if (error)
7508 goto done;
7511 if (commit_id_arg == NULL) {
7512 struct got_reference *head_ref;
7513 struct got_object_id *commit_id;
7514 error = got_ref_open(&head_ref, repo,
7515 worktree ? got_worktree_get_head_ref_name(worktree)
7516 : GOT_REF_HEAD, 0);
7517 if (error)
7518 goto done;
7519 error = got_ref_resolve(&commit_id, repo, head_ref);
7520 got_ref_close(head_ref);
7521 if (error)
7522 goto done;
7523 error = got_object_id_str(&commit_id_str, commit_id);
7524 free(commit_id);
7525 if (error)
7526 goto done;
7529 if (worktree) {
7530 /* Release work tree lock. */
7531 got_worktree_close(worktree);
7532 worktree = NULL;
7535 error = add_tag(repo, tagger, tag_name,
7536 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7537 signer_id, verbosity);
7539 done:
7540 if (repo) {
7541 const struct got_error *close_err = got_repo_close(repo);
7542 if (error == NULL)
7543 error = close_err;
7545 if (worktree)
7546 got_worktree_close(worktree);
7547 if (pack_fds) {
7548 const struct got_error *pack_err =
7549 got_repo_pack_fds_close(pack_fds);
7550 if (error == NULL)
7551 error = pack_err;
7553 free(cwd);
7554 free(repo_path);
7555 free(gitconfig_path);
7556 free(commit_id_str);
7557 free(tagger);
7558 free(allowed_signers);
7559 free(revoked_signers);
7560 free(signer_id);
7561 return error;
7564 __dead static void
7565 usage_add(void)
7567 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7568 exit(1);
7571 static const struct got_error *
7572 add_progress(void *arg, unsigned char status, const char *path)
7574 while (path[0] == '/')
7575 path++;
7576 printf("%c %s\n", status, path);
7577 return NULL;
7580 static const struct got_error *
7581 cmd_add(int argc, char *argv[])
7583 const struct got_error *error = NULL;
7584 struct got_repository *repo = NULL;
7585 struct got_worktree *worktree = NULL;
7586 char *cwd = NULL;
7587 struct got_pathlist_head paths;
7588 struct got_pathlist_entry *pe;
7589 int ch, can_recurse = 0, no_ignores = 0;
7590 int *pack_fds = NULL;
7592 TAILQ_INIT(&paths);
7594 while ((ch = getopt(argc, argv, "IR")) != -1) {
7595 switch (ch) {
7596 case 'I':
7597 no_ignores = 1;
7598 break;
7599 case 'R':
7600 can_recurse = 1;
7601 break;
7602 default:
7603 usage_add();
7604 /* NOTREACHED */
7608 argc -= optind;
7609 argv += optind;
7611 #ifndef PROFILE
7612 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7613 NULL) == -1)
7614 err(1, "pledge");
7615 #endif
7616 if (argc < 1)
7617 usage_add();
7619 cwd = getcwd(NULL, 0);
7620 if (cwd == NULL) {
7621 error = got_error_from_errno("getcwd");
7622 goto done;
7625 error = got_repo_pack_fds_open(&pack_fds);
7626 if (error != NULL)
7627 goto done;
7629 error = got_worktree_open(&worktree, cwd);
7630 if (error) {
7631 if (error->code == GOT_ERR_NOT_WORKTREE)
7632 error = wrap_not_worktree_error(error, "add", cwd);
7633 goto done;
7636 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7637 NULL, pack_fds);
7638 if (error != NULL)
7639 goto done;
7641 error = apply_unveil(got_repo_get_path(repo), 1,
7642 got_worktree_get_root_path(worktree));
7643 if (error)
7644 goto done;
7646 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7647 if (error)
7648 goto done;
7650 if (!can_recurse) {
7651 char *ondisk_path;
7652 struct stat sb;
7653 TAILQ_FOREACH(pe, &paths, entry) {
7654 if (asprintf(&ondisk_path, "%s/%s",
7655 got_worktree_get_root_path(worktree),
7656 pe->path) == -1) {
7657 error = got_error_from_errno("asprintf");
7658 goto done;
7660 if (lstat(ondisk_path, &sb) == -1) {
7661 if (errno == ENOENT) {
7662 free(ondisk_path);
7663 continue;
7665 error = got_error_from_errno2("lstat",
7666 ondisk_path);
7667 free(ondisk_path);
7668 goto done;
7670 free(ondisk_path);
7671 if (S_ISDIR(sb.st_mode)) {
7672 error = got_error_msg(GOT_ERR_BAD_PATH,
7673 "adding directories requires -R option");
7674 goto done;
7679 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7680 NULL, repo, no_ignores);
7681 done:
7682 if (repo) {
7683 const struct got_error *close_err = got_repo_close(repo);
7684 if (error == NULL)
7685 error = close_err;
7687 if (worktree)
7688 got_worktree_close(worktree);
7689 if (pack_fds) {
7690 const struct got_error *pack_err =
7691 got_repo_pack_fds_close(pack_fds);
7692 if (error == NULL)
7693 error = pack_err;
7695 TAILQ_FOREACH(pe, &paths, entry)
7696 free((char *)pe->path);
7697 got_pathlist_free(&paths);
7698 free(cwd);
7699 return error;
7702 __dead static void
7703 usage_remove(void)
7705 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7706 getprogname());
7707 exit(1);
7710 static const struct got_error *
7711 print_remove_status(void *arg, unsigned char status,
7712 unsigned char staged_status, const char *path)
7714 while (path[0] == '/')
7715 path++;
7716 if (status == GOT_STATUS_NONEXISTENT)
7717 return NULL;
7718 if (status == staged_status && (status == GOT_STATUS_DELETE))
7719 status = GOT_STATUS_NO_CHANGE;
7720 printf("%c%c %s\n", status, staged_status, path);
7721 return NULL;
7724 static const struct got_error *
7725 cmd_remove(int argc, char *argv[])
7727 const struct got_error *error = NULL;
7728 struct got_worktree *worktree = NULL;
7729 struct got_repository *repo = NULL;
7730 const char *status_codes = NULL;
7731 char *cwd = NULL;
7732 struct got_pathlist_head paths;
7733 struct got_pathlist_entry *pe;
7734 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7735 int ignore_missing_paths = 0;
7736 int *pack_fds = NULL;
7738 TAILQ_INIT(&paths);
7740 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7741 switch (ch) {
7742 case 'f':
7743 delete_local_mods = 1;
7744 ignore_missing_paths = 1;
7745 break;
7746 case 'k':
7747 keep_on_disk = 1;
7748 break;
7749 case 'R':
7750 can_recurse = 1;
7751 break;
7752 case 's':
7753 for (i = 0; i < strlen(optarg); i++) {
7754 switch (optarg[i]) {
7755 case GOT_STATUS_MODIFY:
7756 delete_local_mods = 1;
7757 break;
7758 case GOT_STATUS_MISSING:
7759 ignore_missing_paths = 1;
7760 break;
7761 default:
7762 errx(1, "invalid status code '%c'",
7763 optarg[i]);
7766 status_codes = optarg;
7767 break;
7768 default:
7769 usage_remove();
7770 /* NOTREACHED */
7774 argc -= optind;
7775 argv += optind;
7777 #ifndef PROFILE
7778 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7779 NULL) == -1)
7780 err(1, "pledge");
7781 #endif
7782 if (argc < 1)
7783 usage_remove();
7785 cwd = getcwd(NULL, 0);
7786 if (cwd == NULL) {
7787 error = got_error_from_errno("getcwd");
7788 goto done;
7791 error = got_repo_pack_fds_open(&pack_fds);
7792 if (error != NULL)
7793 goto done;
7795 error = got_worktree_open(&worktree, cwd);
7796 if (error) {
7797 if (error->code == GOT_ERR_NOT_WORKTREE)
7798 error = wrap_not_worktree_error(error, "remove", cwd);
7799 goto done;
7802 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7803 NULL, pack_fds);
7804 if (error)
7805 goto done;
7807 error = apply_unveil(got_repo_get_path(repo), 1,
7808 got_worktree_get_root_path(worktree));
7809 if (error)
7810 goto done;
7812 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7813 if (error)
7814 goto done;
7816 if (!can_recurse) {
7817 char *ondisk_path;
7818 struct stat sb;
7819 TAILQ_FOREACH(pe, &paths, entry) {
7820 if (asprintf(&ondisk_path, "%s/%s",
7821 got_worktree_get_root_path(worktree),
7822 pe->path) == -1) {
7823 error = got_error_from_errno("asprintf");
7824 goto done;
7826 if (lstat(ondisk_path, &sb) == -1) {
7827 if (errno == ENOENT) {
7828 free(ondisk_path);
7829 continue;
7831 error = got_error_from_errno2("lstat",
7832 ondisk_path);
7833 free(ondisk_path);
7834 goto done;
7836 free(ondisk_path);
7837 if (S_ISDIR(sb.st_mode)) {
7838 error = got_error_msg(GOT_ERR_BAD_PATH,
7839 "removing directories requires -R option");
7840 goto done;
7845 error = got_worktree_schedule_delete(worktree, &paths,
7846 delete_local_mods, status_codes, print_remove_status, NULL,
7847 repo, keep_on_disk, ignore_missing_paths);
7848 done:
7849 if (repo) {
7850 const struct got_error *close_err = got_repo_close(repo);
7851 if (error == NULL)
7852 error = close_err;
7854 if (worktree)
7855 got_worktree_close(worktree);
7856 if (pack_fds) {
7857 const struct got_error *pack_err =
7858 got_repo_pack_fds_close(pack_fds);
7859 if (error == NULL)
7860 error = pack_err;
7862 TAILQ_FOREACH(pe, &paths, entry)
7863 free((char *)pe->path);
7864 got_pathlist_free(&paths);
7865 free(cwd);
7866 return error;
7869 __dead static void
7870 usage_patch(void)
7872 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7873 "[patchfile]\n", getprogname());
7874 exit(1);
7877 static const struct got_error *
7878 patch_from_stdin(int *patchfd)
7880 const struct got_error *err = NULL;
7881 ssize_t r;
7882 char buf[BUFSIZ];
7883 sig_t sighup, sigint, sigquit;
7885 *patchfd = got_opentempfd();
7886 if (*patchfd == -1)
7887 return got_error_from_errno("got_opentempfd");
7889 sighup = signal(SIGHUP, SIG_DFL);
7890 sigint = signal(SIGINT, SIG_DFL);
7891 sigquit = signal(SIGQUIT, SIG_DFL);
7893 for (;;) {
7894 r = read(0, buf, sizeof(buf));
7895 if (r == -1) {
7896 err = got_error_from_errno("read");
7897 break;
7899 if (r == 0)
7900 break;
7901 if (write(*patchfd, buf, r) == -1) {
7902 err = got_error_from_errno("write");
7903 break;
7907 signal(SIGHUP, sighup);
7908 signal(SIGINT, sigint);
7909 signal(SIGQUIT, sigquit);
7911 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7912 err = got_error_from_errno("lseek");
7914 if (err != NULL) {
7915 close(*patchfd);
7916 *patchfd = -1;
7919 return err;
7922 static const struct got_error *
7923 patch_progress(void *arg, const char *old, const char *new,
7924 unsigned char status, const struct got_error *error, int old_from,
7925 int old_lines, int new_from, int new_lines, int offset,
7926 int ws_mangled, const struct got_error *hunk_err)
7928 const char *path = new == NULL ? old : new;
7930 while (*path == '/')
7931 path++;
7933 if (status != 0)
7934 printf("%c %s\n", status, path);
7936 if (error != NULL)
7937 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7939 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7940 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7941 old_lines, new_from, new_lines);
7942 if (hunk_err != NULL)
7943 printf("%s\n", hunk_err->msg);
7944 else if (offset != 0)
7945 printf("applied with offset %d\n", offset);
7946 else
7947 printf("hunk contains mangled whitespace\n");
7950 return NULL;
7953 static const struct got_error *
7954 cmd_patch(int argc, char *argv[])
7956 const struct got_error *error = NULL, *close_error = NULL;
7957 struct got_worktree *worktree = NULL;
7958 struct got_repository *repo = NULL;
7959 struct got_reflist_head refs;
7960 struct got_object_id *commit_id = NULL;
7961 const char *commit_id_str = NULL;
7962 struct stat sb;
7963 const char *errstr;
7964 char *cwd = NULL;
7965 int ch, nop = 0, strip = -1, reverse = 0;
7966 int patchfd;
7967 int *pack_fds = NULL;
7969 TAILQ_INIT(&refs);
7971 #ifndef PROFILE
7972 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7973 "unveil", NULL) == -1)
7974 err(1, "pledge");
7975 #endif
7977 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7978 switch (ch) {
7979 case 'c':
7980 commit_id_str = optarg;
7981 break;
7982 case 'n':
7983 nop = 1;
7984 break;
7985 case 'p':
7986 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7987 if (errstr != NULL)
7988 errx(1, "pathname strip count is %s: %s",
7989 errstr, optarg);
7990 break;
7991 case 'R':
7992 reverse = 1;
7993 break;
7994 default:
7995 usage_patch();
7996 /* NOTREACHED */
8000 argc -= optind;
8001 argv += optind;
8003 if (argc == 0) {
8004 error = patch_from_stdin(&patchfd);
8005 if (error)
8006 return error;
8007 } else if (argc == 1) {
8008 patchfd = open(argv[0], O_RDONLY);
8009 if (patchfd == -1) {
8010 error = got_error_from_errno2("open", argv[0]);
8011 return error;
8013 if (fstat(patchfd, &sb) == -1) {
8014 error = got_error_from_errno2("fstat", argv[0]);
8015 goto done;
8017 if (!S_ISREG(sb.st_mode)) {
8018 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8019 goto done;
8021 } else
8022 usage_patch();
8024 if ((cwd = getcwd(NULL, 0)) == NULL) {
8025 error = got_error_from_errno("getcwd");
8026 goto done;
8029 error = got_repo_pack_fds_open(&pack_fds);
8030 if (error != NULL)
8031 goto done;
8033 error = got_worktree_open(&worktree, cwd);
8034 if (error != NULL)
8035 goto done;
8037 const char *repo_path = got_worktree_get_repo_path(worktree);
8038 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8039 if (error != NULL)
8040 goto done;
8042 error = apply_unveil(got_repo_get_path(repo), 0,
8043 got_worktree_get_root_path(worktree));
8044 if (error != NULL)
8045 goto done;
8047 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8048 if (error)
8049 goto done;
8051 if (commit_id_str != NULL) {
8052 error = got_repo_match_object_id(&commit_id, NULL,
8053 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8054 if (error)
8055 goto done;
8058 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8059 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8061 done:
8062 got_ref_list_free(&refs);
8063 free(commit_id);
8064 if (repo) {
8065 close_error = got_repo_close(repo);
8066 if (error == NULL)
8067 error = close_error;
8069 if (worktree != NULL) {
8070 close_error = got_worktree_close(worktree);
8071 if (error == NULL)
8072 error = close_error;
8074 if (pack_fds) {
8075 const struct got_error *pack_err =
8076 got_repo_pack_fds_close(pack_fds);
8077 if (error == NULL)
8078 error = pack_err;
8080 free(cwd);
8081 return error;
8084 __dead static void
8085 usage_revert(void)
8087 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8088 getprogname());
8089 exit(1);
8092 static const struct got_error *
8093 revert_progress(void *arg, unsigned char status, const char *path)
8095 if (status == GOT_STATUS_UNVERSIONED)
8096 return NULL;
8098 while (path[0] == '/')
8099 path++;
8100 printf("%c %s\n", status, path);
8101 return NULL;
8104 struct choose_patch_arg {
8105 FILE *patch_script_file;
8106 const char *action;
8109 static const struct got_error *
8110 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8111 int nchanges, const char *action)
8113 const struct got_error *err;
8114 char *line = NULL;
8115 size_t linesize = 0;
8116 ssize_t linelen;
8118 switch (status) {
8119 case GOT_STATUS_ADD:
8120 printf("A %s\n%s this addition? [y/n] ", path, action);
8121 break;
8122 case GOT_STATUS_DELETE:
8123 printf("D %s\n%s this deletion? [y/n] ", path, action);
8124 break;
8125 case GOT_STATUS_MODIFY:
8126 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8127 return got_error_from_errno("fseek");
8128 printf(GOT_COMMIT_SEP_STR);
8129 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8130 printf("%s", line);
8131 if (linelen == -1 && ferror(patch_file)) {
8132 err = got_error_from_errno("getline");
8133 free(line);
8134 return err;
8136 free(line);
8137 printf(GOT_COMMIT_SEP_STR);
8138 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8139 path, n, nchanges, action);
8140 break;
8141 default:
8142 return got_error_path(path, GOT_ERR_FILE_STATUS);
8145 fflush(stdout);
8146 return NULL;
8149 static const struct got_error *
8150 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8151 FILE *patch_file, int n, int nchanges)
8153 const struct got_error *err = NULL;
8154 char *line = NULL;
8155 size_t linesize = 0;
8156 ssize_t linelen;
8157 int resp = ' ';
8158 struct choose_patch_arg *a = arg;
8160 *choice = GOT_PATCH_CHOICE_NONE;
8162 if (a->patch_script_file) {
8163 char *nl;
8164 err = show_change(status, path, patch_file, n, nchanges,
8165 a->action);
8166 if (err)
8167 return err;
8168 linelen = getline(&line, &linesize, a->patch_script_file);
8169 if (linelen == -1) {
8170 if (ferror(a->patch_script_file))
8171 return got_error_from_errno("getline");
8172 return NULL;
8174 nl = strchr(line, '\n');
8175 if (nl)
8176 *nl = '\0';
8177 if (strcmp(line, "y") == 0) {
8178 *choice = GOT_PATCH_CHOICE_YES;
8179 printf("y\n");
8180 } else if (strcmp(line, "n") == 0) {
8181 *choice = GOT_PATCH_CHOICE_NO;
8182 printf("n\n");
8183 } else if (strcmp(line, "q") == 0 &&
8184 status == GOT_STATUS_MODIFY) {
8185 *choice = GOT_PATCH_CHOICE_QUIT;
8186 printf("q\n");
8187 } else
8188 printf("invalid response '%s'\n", line);
8189 free(line);
8190 return NULL;
8193 while (resp != 'y' && resp != 'n' && resp != 'q') {
8194 err = show_change(status, path, patch_file, n, nchanges,
8195 a->action);
8196 if (err)
8197 return err;
8198 resp = getchar();
8199 if (resp == '\n')
8200 resp = getchar();
8201 if (status == GOT_STATUS_MODIFY) {
8202 if (resp != 'y' && resp != 'n' && resp != 'q') {
8203 printf("invalid response '%c'\n", resp);
8204 resp = ' ';
8206 } else if (resp != 'y' && resp != 'n') {
8207 printf("invalid response '%c'\n", resp);
8208 resp = ' ';
8212 if (resp == 'y')
8213 *choice = GOT_PATCH_CHOICE_YES;
8214 else if (resp == 'n')
8215 *choice = GOT_PATCH_CHOICE_NO;
8216 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8217 *choice = GOT_PATCH_CHOICE_QUIT;
8219 return NULL;
8222 static const struct got_error *
8223 cmd_revert(int argc, char *argv[])
8225 const struct got_error *error = NULL;
8226 struct got_worktree *worktree = NULL;
8227 struct got_repository *repo = NULL;
8228 char *cwd = NULL, *path = NULL;
8229 struct got_pathlist_head paths;
8230 struct got_pathlist_entry *pe;
8231 int ch, can_recurse = 0, pflag = 0;
8232 FILE *patch_script_file = NULL;
8233 const char *patch_script_path = NULL;
8234 struct choose_patch_arg cpa;
8235 int *pack_fds = NULL;
8237 TAILQ_INIT(&paths);
8239 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8240 switch (ch) {
8241 case 'F':
8242 patch_script_path = optarg;
8243 break;
8244 case 'p':
8245 pflag = 1;
8246 break;
8247 case 'R':
8248 can_recurse = 1;
8249 break;
8250 default:
8251 usage_revert();
8252 /* NOTREACHED */
8256 argc -= optind;
8257 argv += optind;
8259 #ifndef PROFILE
8260 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8261 "unveil", NULL) == -1)
8262 err(1, "pledge");
8263 #endif
8264 if (argc < 1)
8265 usage_revert();
8266 if (patch_script_path && !pflag)
8267 errx(1, "-F option can only be used together with -p option");
8269 cwd = getcwd(NULL, 0);
8270 if (cwd == NULL) {
8271 error = got_error_from_errno("getcwd");
8272 goto done;
8275 error = got_repo_pack_fds_open(&pack_fds);
8276 if (error != NULL)
8277 goto done;
8279 error = got_worktree_open(&worktree, cwd);
8280 if (error) {
8281 if (error->code == GOT_ERR_NOT_WORKTREE)
8282 error = wrap_not_worktree_error(error, "revert", cwd);
8283 goto done;
8286 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8287 NULL, pack_fds);
8288 if (error != NULL)
8289 goto done;
8291 if (patch_script_path) {
8292 patch_script_file = fopen(patch_script_path, "re");
8293 if (patch_script_file == NULL) {
8294 error = got_error_from_errno2("fopen",
8295 patch_script_path);
8296 goto done;
8299 error = apply_unveil(got_repo_get_path(repo), 1,
8300 got_worktree_get_root_path(worktree));
8301 if (error)
8302 goto done;
8304 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8305 if (error)
8306 goto done;
8308 if (!can_recurse) {
8309 char *ondisk_path;
8310 struct stat sb;
8311 TAILQ_FOREACH(pe, &paths, entry) {
8312 if (asprintf(&ondisk_path, "%s/%s",
8313 got_worktree_get_root_path(worktree),
8314 pe->path) == -1) {
8315 error = got_error_from_errno("asprintf");
8316 goto done;
8318 if (lstat(ondisk_path, &sb) == -1) {
8319 if (errno == ENOENT) {
8320 free(ondisk_path);
8321 continue;
8323 error = got_error_from_errno2("lstat",
8324 ondisk_path);
8325 free(ondisk_path);
8326 goto done;
8328 free(ondisk_path);
8329 if (S_ISDIR(sb.st_mode)) {
8330 error = got_error_msg(GOT_ERR_BAD_PATH,
8331 "reverting directories requires -R option");
8332 goto done;
8337 cpa.patch_script_file = patch_script_file;
8338 cpa.action = "revert";
8339 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8340 pflag ? choose_patch : NULL, &cpa, repo);
8341 done:
8342 if (patch_script_file && fclose(patch_script_file) == EOF &&
8343 error == NULL)
8344 error = got_error_from_errno2("fclose", patch_script_path);
8345 if (repo) {
8346 const struct got_error *close_err = got_repo_close(repo);
8347 if (error == NULL)
8348 error = close_err;
8350 if (worktree)
8351 got_worktree_close(worktree);
8352 if (pack_fds) {
8353 const struct got_error *pack_err =
8354 got_repo_pack_fds_close(pack_fds);
8355 if (error == NULL)
8356 error = pack_err;
8358 free(path);
8359 free(cwd);
8360 return error;
8363 __dead static void
8364 usage_commit(void)
8366 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8367 "[-m message] [path ...]\n", getprogname());
8368 exit(1);
8371 struct collect_commit_logmsg_arg {
8372 const char *cmdline_log;
8373 const char *prepared_log;
8374 int non_interactive;
8375 const char *editor;
8376 const char *worktree_path;
8377 const char *branch_name;
8378 const char *repo_path;
8379 char *logmsg_path;
8383 static const struct got_error *
8384 read_prepared_logmsg(char **logmsg, const char *path)
8386 const struct got_error *err = NULL;
8387 FILE *f = NULL;
8388 struct stat sb;
8389 size_t r;
8391 *logmsg = NULL;
8392 memset(&sb, 0, sizeof(sb));
8394 f = fopen(path, "re");
8395 if (f == NULL)
8396 return got_error_from_errno2("fopen", path);
8398 if (fstat(fileno(f), &sb) == -1) {
8399 err = got_error_from_errno2("fstat", path);
8400 goto done;
8402 if (sb.st_size == 0) {
8403 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8404 goto done;
8407 *logmsg = malloc(sb.st_size + 1);
8408 if (*logmsg == NULL) {
8409 err = got_error_from_errno("malloc");
8410 goto done;
8413 r = fread(*logmsg, 1, sb.st_size, f);
8414 if (r != sb.st_size) {
8415 if (ferror(f))
8416 err = got_error_from_errno2("fread", path);
8417 else
8418 err = got_error(GOT_ERR_IO);
8419 goto done;
8421 (*logmsg)[sb.st_size] = '\0';
8422 done:
8423 if (fclose(f) == EOF && err == NULL)
8424 err = got_error_from_errno2("fclose", path);
8425 if (err) {
8426 free(*logmsg);
8427 *logmsg = NULL;
8429 return err;
8432 static const struct got_error *
8433 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8434 const char *diff_path, char **logmsg, void *arg)
8436 char *initial_content = NULL;
8437 struct got_pathlist_entry *pe;
8438 const struct got_error *err = NULL;
8439 char *template = NULL;
8440 struct collect_commit_logmsg_arg *a = arg;
8441 int initial_content_len;
8442 int fd = -1;
8443 size_t len;
8445 /* if a message was specified on the command line, just use it */
8446 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8447 len = strlen(a->cmdline_log) + 1;
8448 *logmsg = malloc(len + 1);
8449 if (*logmsg == NULL)
8450 return got_error_from_errno("malloc");
8451 strlcpy(*logmsg, a->cmdline_log, len);
8452 return NULL;
8453 } else if (a->prepared_log != NULL && a->non_interactive)
8454 return read_prepared_logmsg(logmsg, a->prepared_log);
8456 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8457 return got_error_from_errno("asprintf");
8459 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8460 if (err)
8461 goto done;
8463 if (a->prepared_log) {
8464 char *msg;
8465 err = read_prepared_logmsg(&msg, a->prepared_log);
8466 if (err)
8467 goto done;
8468 if (write(fd, msg, strlen(msg)) == -1) {
8469 err = got_error_from_errno2("write", a->logmsg_path);
8470 free(msg);
8471 goto done;
8473 free(msg);
8476 initial_content_len = asprintf(&initial_content,
8477 "\n# changes to be committed on branch %s:\n",
8478 a->branch_name);
8479 if (initial_content_len == -1) {
8480 err = got_error_from_errno("asprintf");
8481 goto done;
8484 if (write(fd, initial_content, initial_content_len) == -1) {
8485 err = got_error_from_errno2("write", a->logmsg_path);
8486 goto done;
8489 TAILQ_FOREACH(pe, commitable_paths, entry) {
8490 struct got_commitable *ct = pe->data;
8491 dprintf(fd, "# %c %s\n",
8492 got_commitable_get_status(ct),
8493 got_commitable_get_path(ct));
8496 if (diff_path) {
8497 dprintf(fd, "# detailed changes can be viewed in %s\n",
8498 diff_path);
8501 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8502 initial_content_len, a->prepared_log ? 0 : 1);
8503 done:
8504 free(initial_content);
8505 free(template);
8507 if (fd != -1 && close(fd) == -1 && err == NULL)
8508 err = got_error_from_errno2("close", a->logmsg_path);
8510 /* Editor is done; we can now apply unveil(2) */
8511 if (err == NULL)
8512 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8513 if (err) {
8514 free(*logmsg);
8515 *logmsg = NULL;
8517 return err;
8520 static const struct got_error *
8521 cmd_commit(int argc, char *argv[])
8523 const struct got_error *error = NULL;
8524 struct got_worktree *worktree = NULL;
8525 struct got_repository *repo = NULL;
8526 char *cwd = NULL, *id_str = NULL;
8527 struct got_object_id *id = NULL;
8528 const char *logmsg = NULL;
8529 char *prepared_logmsg = NULL;
8530 struct collect_commit_logmsg_arg cl_arg;
8531 const char *author = NULL;
8532 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8533 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8534 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8535 int show_diff = 1;
8536 struct got_pathlist_head paths;
8537 int *pack_fds = NULL;
8539 TAILQ_INIT(&paths);
8540 cl_arg.logmsg_path = NULL;
8542 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8543 switch (ch) {
8544 case 'A':
8545 author = optarg;
8546 error = valid_author(author);
8547 if (error)
8548 return error;
8549 break;
8550 case 'F':
8551 if (logmsg != NULL)
8552 option_conflict('F', 'm');
8553 prepared_logmsg = realpath(optarg, NULL);
8554 if (prepared_logmsg == NULL)
8555 return got_error_from_errno2("realpath",
8556 optarg);
8557 break;
8558 case 'm':
8559 if (prepared_logmsg)
8560 option_conflict('m', 'F');
8561 logmsg = optarg;
8562 break;
8563 case 'N':
8564 non_interactive = 1;
8565 break;
8566 case 'n':
8567 show_diff = 0;
8568 break;
8569 case 'S':
8570 allow_bad_symlinks = 1;
8571 break;
8572 default:
8573 usage_commit();
8574 /* NOTREACHED */
8578 argc -= optind;
8579 argv += optind;
8581 #ifndef PROFILE
8582 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8583 "unveil", NULL) == -1)
8584 err(1, "pledge");
8585 #endif
8586 cwd = getcwd(NULL, 0);
8587 if (cwd == NULL) {
8588 error = got_error_from_errno("getcwd");
8589 goto done;
8592 error = got_repo_pack_fds_open(&pack_fds);
8593 if (error != NULL)
8594 goto done;
8596 error = got_worktree_open(&worktree, cwd);
8597 if (error) {
8598 if (error->code == GOT_ERR_NOT_WORKTREE)
8599 error = wrap_not_worktree_error(error, "commit", cwd);
8600 goto done;
8603 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8604 if (error)
8605 goto done;
8606 if (rebase_in_progress) {
8607 error = got_error(GOT_ERR_REBASING);
8608 goto done;
8611 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8612 worktree);
8613 if (error)
8614 goto done;
8616 error = get_gitconfig_path(&gitconfig_path);
8617 if (error)
8618 goto done;
8619 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8620 gitconfig_path, pack_fds);
8621 if (error != NULL)
8622 goto done;
8624 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8625 if (error)
8626 goto done;
8627 if (merge_in_progress) {
8628 error = got_error(GOT_ERR_MERGE_BUSY);
8629 goto done;
8632 error = get_author(&committer, repo, worktree);
8633 if (error)
8634 goto done;
8636 if (author != NULL && !strcmp(committer, author)) {
8637 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8638 goto done;
8641 if (author == NULL)
8642 author = committer;
8645 * unveil(2) traverses exec(2); if an editor is used we have
8646 * to apply unveil after the log message has been written.
8648 if (logmsg == NULL || strlen(logmsg) == 0)
8649 error = get_editor(&editor);
8650 else
8651 error = apply_unveil(got_repo_get_path(repo), 0,
8652 got_worktree_get_root_path(worktree));
8653 if (error)
8654 goto done;
8656 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8657 if (error)
8658 goto done;
8660 cl_arg.editor = editor;
8661 cl_arg.cmdline_log = logmsg;
8662 cl_arg.prepared_log = prepared_logmsg;
8663 cl_arg.non_interactive = non_interactive;
8664 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8665 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8666 if (!histedit_in_progress) {
8667 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8668 error = got_error(GOT_ERR_COMMIT_BRANCH);
8669 goto done;
8671 cl_arg.branch_name += 11;
8673 cl_arg.repo_path = got_repo_get_path(repo);
8674 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8675 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8676 print_status, NULL, repo);
8677 if (error) {
8678 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8679 cl_arg.logmsg_path != NULL)
8680 preserve_logmsg = 1;
8681 goto done;
8684 error = got_object_id_str(&id_str, id);
8685 if (error)
8686 goto done;
8687 printf("Created commit %s\n", id_str);
8688 done:
8689 if (preserve_logmsg) {
8690 fprintf(stderr, "%s: log message preserved in %s\n",
8691 getprogname(), cl_arg.logmsg_path);
8692 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8693 error == NULL)
8694 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8695 free(cl_arg.logmsg_path);
8696 if (repo) {
8697 const struct got_error *close_err = got_repo_close(repo);
8698 if (error == NULL)
8699 error = close_err;
8701 if (worktree)
8702 got_worktree_close(worktree);
8703 if (pack_fds) {
8704 const struct got_error *pack_err =
8705 got_repo_pack_fds_close(pack_fds);
8706 if (error == NULL)
8707 error = pack_err;
8709 free(cwd);
8710 free(id_str);
8711 free(gitconfig_path);
8712 free(editor);
8713 free(committer);
8714 free(prepared_logmsg);
8715 return error;
8718 __dead static void
8719 usage_send(void)
8721 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8722 "[-r repository-path] [-t tag] [remote-repository]\n",
8723 getprogname());
8724 exit(1);
8727 static void
8728 print_load_info(int print_colored, int print_found, int print_trees,
8729 int ncolored, int nfound, int ntrees)
8731 if (print_colored) {
8732 printf("%d commit%s colored", ncolored,
8733 ncolored == 1 ? "" : "s");
8735 if (print_found) {
8736 printf("%s%d object%s found",
8737 ncolored > 0 ? "; " : "",
8738 nfound, nfound == 1 ? "" : "s");
8740 if (print_trees) {
8741 printf("; %d tree%s scanned", ntrees,
8742 ntrees == 1 ? "" : "s");
8746 struct got_send_progress_arg {
8747 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8748 int verbosity;
8749 int last_ncolored;
8750 int last_nfound;
8751 int last_ntrees;
8752 int loading_done;
8753 int last_ncommits;
8754 int last_nobj_total;
8755 int last_p_deltify;
8756 int last_p_written;
8757 int last_p_sent;
8758 int printed_something;
8759 int sent_something;
8760 struct got_pathlist_head *delete_branches;
8763 static const struct got_error *
8764 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8765 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8766 int nobj_written, off_t bytes_sent, const char *refname,
8767 const char *errmsg, int success)
8769 struct got_send_progress_arg *a = arg;
8770 char scaled_packsize[FMT_SCALED_STRSIZE];
8771 char scaled_sent[FMT_SCALED_STRSIZE];
8772 int p_deltify = 0, p_written = 0, p_sent = 0;
8773 int print_colored = 0, print_found = 0, print_trees = 0;
8774 int print_searching = 0, print_total = 0;
8775 int print_deltify = 0, print_written = 0, print_sent = 0;
8777 if (a->verbosity < 0)
8778 return NULL;
8780 if (refname) {
8781 const char *status = success ? "accepted" : "rejected";
8783 if (success) {
8784 struct got_pathlist_entry *pe;
8785 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8786 const char *branchname = pe->path;
8787 if (got_path_cmp(branchname, refname,
8788 strlen(branchname), strlen(refname)) == 0) {
8789 status = "deleted";
8790 a->sent_something = 1;
8791 break;
8796 if (a->printed_something)
8797 putchar('\n');
8798 printf("Server has %s %s", status, refname);
8799 if (errmsg)
8800 printf(": %s", errmsg);
8801 a->printed_something = 1;
8802 return NULL;
8805 if (a->last_ncolored != ncolored) {
8806 print_colored = 1;
8807 a->last_ncolored = ncolored;
8810 if (a->last_nfound != nfound) {
8811 print_colored = 1;
8812 print_found = 1;
8813 a->last_nfound = nfound;
8816 if (a->last_ntrees != ntrees) {
8817 print_colored = 1;
8818 print_found = 1;
8819 print_trees = 1;
8820 a->last_ntrees = ntrees;
8823 if ((print_colored || print_found || print_trees) &&
8824 !a->loading_done) {
8825 printf("\r");
8826 print_load_info(print_colored, print_found, print_trees,
8827 ncolored, nfound, ntrees);
8828 a->printed_something = 1;
8829 fflush(stdout);
8830 return NULL;
8831 } else if (!a->loading_done) {
8832 printf("\r");
8833 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8834 printf("\n");
8835 a->loading_done = 1;
8838 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8839 return got_error_from_errno("fmt_scaled");
8840 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8841 return got_error_from_errno("fmt_scaled");
8843 if (a->last_ncommits != ncommits) {
8844 print_searching = 1;
8845 a->last_ncommits = ncommits;
8848 if (a->last_nobj_total != nobj_total) {
8849 print_searching = 1;
8850 print_total = 1;
8851 a->last_nobj_total = nobj_total;
8854 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8855 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8856 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8857 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8858 return got_error(GOT_ERR_NO_SPACE);
8861 if (nobj_deltify > 0 || nobj_written > 0) {
8862 if (nobj_deltify > 0) {
8863 p_deltify = (nobj_deltify * 100) / nobj_total;
8864 if (p_deltify != a->last_p_deltify) {
8865 a->last_p_deltify = p_deltify;
8866 print_searching = 1;
8867 print_total = 1;
8868 print_deltify = 1;
8871 if (nobj_written > 0) {
8872 p_written = (nobj_written * 100) / nobj_total;
8873 if (p_written != a->last_p_written) {
8874 a->last_p_written = p_written;
8875 print_searching = 1;
8876 print_total = 1;
8877 print_deltify = 1;
8878 print_written = 1;
8883 if (bytes_sent > 0) {
8884 p_sent = (bytes_sent * 100) / packfile_size;
8885 if (p_sent != a->last_p_sent) {
8886 a->last_p_sent = p_sent;
8887 print_searching = 1;
8888 print_total = 1;
8889 print_deltify = 1;
8890 print_written = 1;
8891 print_sent = 1;
8893 a->sent_something = 1;
8896 if (print_searching || print_total || print_deltify || print_written ||
8897 print_sent)
8898 printf("\r");
8899 if (print_searching)
8900 printf("packing %d reference%s", ncommits,
8901 ncommits == 1 ? "" : "s");
8902 if (print_total)
8903 printf("; %d object%s", nobj_total,
8904 nobj_total == 1 ? "" : "s");
8905 if (print_deltify)
8906 printf("; deltify: %d%%", p_deltify);
8907 if (print_sent)
8908 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8909 scaled_packsize, p_sent);
8910 else if (print_written)
8911 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8912 scaled_packsize, p_written);
8913 if (print_searching || print_total || print_deltify ||
8914 print_written || print_sent) {
8915 a->printed_something = 1;
8916 fflush(stdout);
8918 return NULL;
8921 static const struct got_error *
8922 cmd_send(int argc, char *argv[])
8924 const struct got_error *error = NULL;
8925 char *cwd = NULL, *repo_path = NULL;
8926 const char *remote_name;
8927 char *proto = NULL, *host = NULL, *port = NULL;
8928 char *repo_name = NULL, *server_path = NULL;
8929 const struct got_remote_repo *remotes, *remote = NULL;
8930 int nremotes, nbranches = 0, ndelete_branches = 0;
8931 struct got_repository *repo = NULL;
8932 struct got_worktree *worktree = NULL;
8933 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8934 struct got_pathlist_head branches;
8935 struct got_pathlist_head tags;
8936 struct got_reflist_head all_branches;
8937 struct got_reflist_head all_tags;
8938 struct got_pathlist_head delete_args;
8939 struct got_pathlist_head delete_branches;
8940 struct got_reflist_entry *re;
8941 struct got_pathlist_entry *pe;
8942 int i, ch, sendfd = -1, sendstatus;
8943 pid_t sendpid = -1;
8944 struct got_send_progress_arg spa;
8945 int verbosity = 0, overwrite_refs = 0;
8946 int send_all_branches = 0, send_all_tags = 0;
8947 struct got_reference *ref = NULL;
8948 int *pack_fds = NULL;
8950 TAILQ_INIT(&branches);
8951 TAILQ_INIT(&tags);
8952 TAILQ_INIT(&all_branches);
8953 TAILQ_INIT(&all_tags);
8954 TAILQ_INIT(&delete_args);
8955 TAILQ_INIT(&delete_branches);
8957 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
8958 switch (ch) {
8959 case 'a':
8960 send_all_branches = 1;
8961 break;
8962 case 'b':
8963 error = got_pathlist_append(&branches, optarg, NULL);
8964 if (error)
8965 return error;
8966 nbranches++;
8967 break;
8968 case 'd':
8969 error = got_pathlist_append(&delete_args, optarg, NULL);
8970 if (error)
8971 return error;
8972 break;
8973 case 'f':
8974 overwrite_refs = 1;
8975 break;
8976 case 'q':
8977 verbosity = -1;
8978 break;
8979 case 'r':
8980 repo_path = realpath(optarg, NULL);
8981 if (repo_path == NULL)
8982 return got_error_from_errno2("realpath",
8983 optarg);
8984 got_path_strip_trailing_slashes(repo_path);
8985 break;
8986 case 'T':
8987 send_all_tags = 1;
8988 break;
8989 case 't':
8990 error = got_pathlist_append(&tags, optarg, NULL);
8991 if (error)
8992 return error;
8993 break;
8994 case 'v':
8995 if (verbosity < 0)
8996 verbosity = 0;
8997 else if (verbosity < 3)
8998 verbosity++;
8999 break;
9000 default:
9001 usage_send();
9002 /* NOTREACHED */
9005 argc -= optind;
9006 argv += optind;
9008 if (send_all_branches && !TAILQ_EMPTY(&branches))
9009 option_conflict('a', 'b');
9010 if (send_all_tags && !TAILQ_EMPTY(&tags))
9011 option_conflict('T', 't');
9014 if (argc == 0)
9015 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9016 else if (argc == 1)
9017 remote_name = argv[0];
9018 else
9019 usage_send();
9021 cwd = getcwd(NULL, 0);
9022 if (cwd == NULL) {
9023 error = got_error_from_errno("getcwd");
9024 goto done;
9027 error = got_repo_pack_fds_open(&pack_fds);
9028 if (error != NULL)
9029 goto done;
9031 if (repo_path == NULL) {
9032 error = got_worktree_open(&worktree, cwd);
9033 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9034 goto done;
9035 else
9036 error = NULL;
9037 if (worktree) {
9038 repo_path =
9039 strdup(got_worktree_get_repo_path(worktree));
9040 if (repo_path == NULL)
9041 error = got_error_from_errno("strdup");
9042 if (error)
9043 goto done;
9044 } else {
9045 repo_path = strdup(cwd);
9046 if (repo_path == NULL) {
9047 error = got_error_from_errno("strdup");
9048 goto done;
9053 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9054 if (error)
9055 goto done;
9057 if (worktree) {
9058 worktree_conf = got_worktree_get_gotconfig(worktree);
9059 if (worktree_conf) {
9060 got_gotconfig_get_remotes(&nremotes, &remotes,
9061 worktree_conf);
9062 for (i = 0; i < nremotes; i++) {
9063 if (strcmp(remotes[i].name, remote_name) == 0) {
9064 remote = &remotes[i];
9065 break;
9070 if (remote == NULL) {
9071 repo_conf = got_repo_get_gotconfig(repo);
9072 if (repo_conf) {
9073 got_gotconfig_get_remotes(&nremotes, &remotes,
9074 repo_conf);
9075 for (i = 0; i < nremotes; i++) {
9076 if (strcmp(remotes[i].name, remote_name) == 0) {
9077 remote = &remotes[i];
9078 break;
9083 if (remote == NULL) {
9084 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9085 for (i = 0; i < nremotes; i++) {
9086 if (strcmp(remotes[i].name, remote_name) == 0) {
9087 remote = &remotes[i];
9088 break;
9092 if (remote == NULL) {
9093 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9094 goto done;
9097 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9098 &repo_name, remote->send_url);
9099 if (error)
9100 goto done;
9102 if (strcmp(proto, "git") == 0) {
9103 #ifndef PROFILE
9104 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9105 "sendfd dns inet unveil", NULL) == -1)
9106 err(1, "pledge");
9107 #endif
9108 } else if (strcmp(proto, "git+ssh") == 0 ||
9109 strcmp(proto, "ssh") == 0) {
9110 #ifndef PROFILE
9111 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9112 "sendfd unveil", NULL) == -1)
9113 err(1, "pledge");
9114 #endif
9115 } else if (strcmp(proto, "http") == 0 ||
9116 strcmp(proto, "git+http") == 0) {
9117 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9118 goto done;
9119 } else {
9120 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9121 goto done;
9124 error = got_dial_apply_unveil(proto);
9125 if (error)
9126 goto done;
9128 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9129 if (error)
9130 goto done;
9132 if (send_all_branches) {
9133 error = got_ref_list(&all_branches, repo, "refs/heads",
9134 got_ref_cmp_by_name, NULL);
9135 if (error)
9136 goto done;
9137 TAILQ_FOREACH(re, &all_branches, entry) {
9138 const char *branchname = got_ref_get_name(re->ref);
9139 error = got_pathlist_append(&branches,
9140 branchname, NULL);
9141 if (error)
9142 goto done;
9143 nbranches++;
9145 } else if (nbranches == 0) {
9146 for (i = 0; i < remote->nsend_branches; i++) {
9147 got_pathlist_append(&branches,
9148 remote->send_branches[i], NULL);
9152 if (send_all_tags) {
9153 error = got_ref_list(&all_tags, repo, "refs/tags",
9154 got_ref_cmp_by_name, NULL);
9155 if (error)
9156 goto done;
9157 TAILQ_FOREACH(re, &all_tags, entry) {
9158 const char *tagname = got_ref_get_name(re->ref);
9159 error = got_pathlist_append(&tags,
9160 tagname, NULL);
9161 if (error)
9162 goto done;
9167 * To prevent accidents only branches in refs/heads/ can be deleted
9168 * with 'got send -d'.
9169 * Deleting anything else requires local repository access or Git.
9171 TAILQ_FOREACH(pe, &delete_args, entry) {
9172 const char *branchname = pe->path;
9173 char *s;
9174 struct got_pathlist_entry *new;
9175 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9176 s = strdup(branchname);
9177 if (s == NULL) {
9178 error = got_error_from_errno("strdup");
9179 goto done;
9181 } else {
9182 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9183 error = got_error_from_errno("asprintf");
9184 goto done;
9187 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9188 if (error || new == NULL /* duplicate */)
9189 free(s);
9190 if (error)
9191 goto done;
9192 ndelete_branches++;
9195 if (nbranches == 0 && ndelete_branches == 0) {
9196 struct got_reference *head_ref;
9197 if (worktree)
9198 error = got_ref_open(&head_ref, repo,
9199 got_worktree_get_head_ref_name(worktree), 0);
9200 else
9201 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9202 if (error)
9203 goto done;
9204 if (got_ref_is_symbolic(head_ref)) {
9205 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9206 got_ref_close(head_ref);
9207 if (error)
9208 goto done;
9209 } else
9210 ref = head_ref;
9211 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9212 NULL);
9213 if (error)
9214 goto done;
9215 nbranches++;
9218 if (verbosity >= 0)
9219 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9220 port ? ":" : "", port ? port : "");
9222 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9223 server_path, verbosity);
9224 if (error)
9225 goto done;
9227 memset(&spa, 0, sizeof(spa));
9228 spa.last_scaled_packsize[0] = '\0';
9229 spa.last_p_deltify = -1;
9230 spa.last_p_written = -1;
9231 spa.verbosity = verbosity;
9232 spa.delete_branches = &delete_branches;
9233 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9234 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9235 check_cancelled, NULL);
9236 if (spa.printed_something)
9237 putchar('\n');
9238 if (error)
9239 goto done;
9240 if (!spa.sent_something && verbosity >= 0)
9241 printf("Already up-to-date\n");
9242 done:
9243 if (sendpid > 0) {
9244 if (kill(sendpid, SIGTERM) == -1)
9245 error = got_error_from_errno("kill");
9246 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9247 error = got_error_from_errno("waitpid");
9249 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9250 error = got_error_from_errno("close");
9251 if (repo) {
9252 const struct got_error *close_err = got_repo_close(repo);
9253 if (error == NULL)
9254 error = close_err;
9256 if (worktree)
9257 got_worktree_close(worktree);
9258 if (pack_fds) {
9259 const struct got_error *pack_err =
9260 got_repo_pack_fds_close(pack_fds);
9261 if (error == NULL)
9262 error = pack_err;
9264 if (ref)
9265 got_ref_close(ref);
9266 got_pathlist_free(&branches);
9267 got_pathlist_free(&tags);
9268 got_ref_list_free(&all_branches);
9269 got_ref_list_free(&all_tags);
9270 got_pathlist_free(&delete_args);
9271 TAILQ_FOREACH(pe, &delete_branches, entry)
9272 free((char *)pe->path);
9273 got_pathlist_free(&delete_branches);
9274 free(cwd);
9275 free(repo_path);
9276 free(proto);
9277 free(host);
9278 free(port);
9279 free(server_path);
9280 free(repo_name);
9281 return error;
9284 __dead static void
9285 usage_cherrypick(void)
9287 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9288 exit(1);
9291 static const struct got_error *
9292 cmd_cherrypick(int argc, char *argv[])
9294 const struct got_error *error = NULL;
9295 struct got_worktree *worktree = NULL;
9296 struct got_repository *repo = NULL;
9297 char *cwd = NULL, *commit_id_str = NULL;
9298 struct got_object_id *commit_id = NULL;
9299 struct got_commit_object *commit = NULL;
9300 struct got_object_qid *pid;
9301 int ch;
9302 struct got_update_progress_arg upa;
9303 int *pack_fds = NULL;
9305 while ((ch = getopt(argc, argv, "")) != -1) {
9306 switch (ch) {
9307 default:
9308 usage_cherrypick();
9309 /* NOTREACHED */
9313 argc -= optind;
9314 argv += optind;
9316 #ifndef PROFILE
9317 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9318 "unveil", NULL) == -1)
9319 err(1, "pledge");
9320 #endif
9321 if (argc != 1)
9322 usage_cherrypick();
9324 cwd = getcwd(NULL, 0);
9325 if (cwd == NULL) {
9326 error = got_error_from_errno("getcwd");
9327 goto done;
9330 error = got_repo_pack_fds_open(&pack_fds);
9331 if (error != NULL)
9332 goto done;
9334 error = got_worktree_open(&worktree, cwd);
9335 if (error) {
9336 if (error->code == GOT_ERR_NOT_WORKTREE)
9337 error = wrap_not_worktree_error(error, "cherrypick",
9338 cwd);
9339 goto done;
9342 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9343 NULL, pack_fds);
9344 if (error != NULL)
9345 goto done;
9347 error = apply_unveil(got_repo_get_path(repo), 0,
9348 got_worktree_get_root_path(worktree));
9349 if (error)
9350 goto done;
9352 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9353 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9354 if (error)
9355 goto done;
9356 error = got_object_id_str(&commit_id_str, commit_id);
9357 if (error)
9358 goto done;
9360 error = got_object_open_as_commit(&commit, repo, commit_id);
9361 if (error)
9362 goto done;
9363 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9364 memset(&upa, 0, sizeof(upa));
9365 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9366 commit_id, repo, update_progress, &upa, check_cancelled,
9367 NULL);
9368 if (error != NULL)
9369 goto done;
9371 if (upa.did_something)
9372 printf("Merged commit %s\n", commit_id_str);
9373 print_merge_progress_stats(&upa);
9374 done:
9375 if (commit)
9376 got_object_commit_close(commit);
9377 free(commit_id_str);
9378 if (worktree)
9379 got_worktree_close(worktree);
9380 if (repo) {
9381 const struct got_error *close_err = got_repo_close(repo);
9382 if (error == NULL)
9383 error = close_err;
9385 if (pack_fds) {
9386 const struct got_error *pack_err =
9387 got_repo_pack_fds_close(pack_fds);
9388 if (error == NULL)
9389 error = pack_err;
9392 return error;
9395 __dead static void
9396 usage_backout(void)
9398 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9399 exit(1);
9402 static const struct got_error *
9403 cmd_backout(int argc, char *argv[])
9405 const struct got_error *error = NULL;
9406 struct got_worktree *worktree = NULL;
9407 struct got_repository *repo = NULL;
9408 char *cwd = NULL, *commit_id_str = NULL;
9409 struct got_object_id *commit_id = NULL;
9410 struct got_commit_object *commit = NULL;
9411 struct got_object_qid *pid;
9412 int ch;
9413 struct got_update_progress_arg upa;
9414 int *pack_fds = NULL;
9416 while ((ch = getopt(argc, argv, "")) != -1) {
9417 switch (ch) {
9418 default:
9419 usage_backout();
9420 /* NOTREACHED */
9424 argc -= optind;
9425 argv += optind;
9427 #ifndef PROFILE
9428 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9429 "unveil", NULL) == -1)
9430 err(1, "pledge");
9431 #endif
9432 if (argc != 1)
9433 usage_backout();
9435 cwd = getcwd(NULL, 0);
9436 if (cwd == NULL) {
9437 error = got_error_from_errno("getcwd");
9438 goto done;
9441 error = got_repo_pack_fds_open(&pack_fds);
9442 if (error != NULL)
9443 goto done;
9445 error = got_worktree_open(&worktree, cwd);
9446 if (error) {
9447 if (error->code == GOT_ERR_NOT_WORKTREE)
9448 error = wrap_not_worktree_error(error, "backout", cwd);
9449 goto done;
9452 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9453 NULL, pack_fds);
9454 if (error != NULL)
9455 goto done;
9457 error = apply_unveil(got_repo_get_path(repo), 0,
9458 got_worktree_get_root_path(worktree));
9459 if (error)
9460 goto done;
9462 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9463 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9464 if (error)
9465 goto done;
9466 error = got_object_id_str(&commit_id_str, commit_id);
9467 if (error)
9468 goto done;
9470 error = got_object_open_as_commit(&commit, repo, commit_id);
9471 if (error)
9472 goto done;
9473 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9474 if (pid == NULL) {
9475 error = got_error(GOT_ERR_ROOT_COMMIT);
9476 goto done;
9479 memset(&upa, 0, sizeof(upa));
9480 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9481 repo, update_progress, &upa, check_cancelled, NULL);
9482 if (error != NULL)
9483 goto done;
9485 if (upa.did_something)
9486 printf("Backed out commit %s\n", commit_id_str);
9487 print_merge_progress_stats(&upa);
9488 done:
9489 if (commit)
9490 got_object_commit_close(commit);
9491 free(commit_id_str);
9492 if (worktree)
9493 got_worktree_close(worktree);
9494 if (repo) {
9495 const struct got_error *close_err = got_repo_close(repo);
9496 if (error == NULL)
9497 error = close_err;
9499 if (pack_fds) {
9500 const struct got_error *pack_err =
9501 got_repo_pack_fds_close(pack_fds);
9502 if (error == NULL)
9503 error = pack_err;
9505 return error;
9508 __dead static void
9509 usage_rebase(void)
9511 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9512 exit(1);
9515 static void
9516 trim_logmsg(char *logmsg, int limit)
9518 char *nl;
9519 size_t len;
9521 len = strlen(logmsg);
9522 if (len > limit)
9523 len = limit;
9524 logmsg[len] = '\0';
9525 nl = strchr(logmsg, '\n');
9526 if (nl)
9527 *nl = '\0';
9530 static const struct got_error *
9531 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9533 const struct got_error *err;
9534 char *logmsg0 = NULL;
9535 const char *s;
9537 err = got_object_commit_get_logmsg(&logmsg0, commit);
9538 if (err)
9539 return err;
9541 s = logmsg0;
9542 while (isspace((unsigned char)s[0]))
9543 s++;
9545 *logmsg = strdup(s);
9546 if (*logmsg == NULL) {
9547 err = got_error_from_errno("strdup");
9548 goto done;
9551 trim_logmsg(*logmsg, limit);
9552 done:
9553 free(logmsg0);
9554 return err;
9557 static const struct got_error *
9558 show_rebase_merge_conflict(struct got_object_id *id,
9559 struct got_repository *repo)
9561 const struct got_error *err;
9562 struct got_commit_object *commit = NULL;
9563 char *id_str = NULL, *logmsg = NULL;
9565 err = got_object_open_as_commit(&commit, repo, id);
9566 if (err)
9567 return err;
9569 err = got_object_id_str(&id_str, id);
9570 if (err)
9571 goto done;
9573 id_str[12] = '\0';
9575 err = get_short_logmsg(&logmsg, 42, commit);
9576 if (err)
9577 goto done;
9579 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9580 done:
9581 free(id_str);
9582 got_object_commit_close(commit);
9583 free(logmsg);
9584 return err;
9587 static const struct got_error *
9588 show_rebase_progress(struct got_commit_object *commit,
9589 struct got_object_id *old_id, struct got_object_id *new_id)
9591 const struct got_error *err;
9592 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9594 err = got_object_id_str(&old_id_str, old_id);
9595 if (err)
9596 goto done;
9598 if (new_id) {
9599 err = got_object_id_str(&new_id_str, new_id);
9600 if (err)
9601 goto done;
9604 old_id_str[12] = '\0';
9605 if (new_id_str)
9606 new_id_str[12] = '\0';
9608 err = get_short_logmsg(&logmsg, 42, commit);
9609 if (err)
9610 goto done;
9612 printf("%s -> %s: %s\n", old_id_str,
9613 new_id_str ? new_id_str : "no-op change", logmsg);
9614 done:
9615 free(old_id_str);
9616 free(new_id_str);
9617 free(logmsg);
9618 return err;
9621 static const struct got_error *
9622 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9623 struct got_reference *branch, struct got_reference *new_base_branch,
9624 struct got_reference *tmp_branch, struct got_repository *repo,
9625 int create_backup)
9627 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9628 return got_worktree_rebase_complete(worktree, fileindex,
9629 new_base_branch, tmp_branch, branch, repo, create_backup);
9632 static const struct got_error *
9633 rebase_commit(struct got_pathlist_head *merged_paths,
9634 struct got_worktree *worktree, struct got_fileindex *fileindex,
9635 struct got_reference *tmp_branch, const char *committer,
9636 struct got_object_id *commit_id, struct got_repository *repo)
9638 const struct got_error *error;
9639 struct got_commit_object *commit;
9640 struct got_object_id *new_commit_id;
9642 error = got_object_open_as_commit(&commit, repo, commit_id);
9643 if (error)
9644 return error;
9646 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9647 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9648 repo);
9649 if (error) {
9650 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9651 goto done;
9652 error = show_rebase_progress(commit, commit_id, NULL);
9653 } else {
9654 error = show_rebase_progress(commit, commit_id, new_commit_id);
9655 free(new_commit_id);
9657 done:
9658 got_object_commit_close(commit);
9659 return error;
9662 struct check_path_prefix_arg {
9663 const char *path_prefix;
9664 size_t len;
9665 int errcode;
9668 static const struct got_error *
9669 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9670 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9671 struct got_object_id *id1, struct got_object_id *id2,
9672 const char *path1, const char *path2,
9673 mode_t mode1, mode_t mode2, struct got_repository *repo)
9675 struct check_path_prefix_arg *a = arg;
9677 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9678 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9679 return got_error(a->errcode);
9681 return NULL;
9684 static const struct got_error *
9685 check_path_prefix(struct got_object_id *parent_id,
9686 struct got_object_id *commit_id, const char *path_prefix,
9687 int errcode, struct got_repository *repo)
9689 const struct got_error *err;
9690 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9691 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9692 struct check_path_prefix_arg cpp_arg;
9694 if (got_path_is_root_dir(path_prefix))
9695 return NULL;
9697 err = got_object_open_as_commit(&commit, repo, commit_id);
9698 if (err)
9699 goto done;
9701 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9702 if (err)
9703 goto done;
9705 err = got_object_open_as_tree(&tree1, repo,
9706 got_object_commit_get_tree_id(parent_commit));
9707 if (err)
9708 goto done;
9710 err = got_object_open_as_tree(&tree2, repo,
9711 got_object_commit_get_tree_id(commit));
9712 if (err)
9713 goto done;
9715 cpp_arg.path_prefix = path_prefix;
9716 while (cpp_arg.path_prefix[0] == '/')
9717 cpp_arg.path_prefix++;
9718 cpp_arg.len = strlen(cpp_arg.path_prefix);
9719 cpp_arg.errcode = errcode;
9720 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9721 check_path_prefix_in_diff, &cpp_arg, 0);
9722 done:
9723 if (tree1)
9724 got_object_tree_close(tree1);
9725 if (tree2)
9726 got_object_tree_close(tree2);
9727 if (commit)
9728 got_object_commit_close(commit);
9729 if (parent_commit)
9730 got_object_commit_close(parent_commit);
9731 return err;
9734 static const struct got_error *
9735 collect_commits(struct got_object_id_queue *commits,
9736 struct got_object_id *initial_commit_id,
9737 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9738 const char *path_prefix, int path_prefix_errcode,
9739 struct got_repository *repo)
9741 const struct got_error *err = NULL;
9742 struct got_commit_graph *graph = NULL;
9743 struct got_object_id parent_id, commit_id;
9744 struct got_object_qid *qid;
9746 err = got_commit_graph_open(&graph, "/", 1);
9747 if (err)
9748 return err;
9750 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9751 check_cancelled, NULL);
9752 if (err)
9753 goto done;
9755 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9756 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9757 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9758 check_cancelled, NULL);
9759 if (err) {
9760 if (err->code == GOT_ERR_ITER_COMPLETED) {
9761 err = got_error_msg(GOT_ERR_ANCESTRY,
9762 "ran out of commits to rebase before "
9763 "youngest common ancestor commit has "
9764 "been reached?!?");
9766 goto done;
9767 } else {
9768 err = check_path_prefix(&parent_id, &commit_id,
9769 path_prefix, path_prefix_errcode, repo);
9770 if (err)
9771 goto done;
9773 err = got_object_qid_alloc(&qid, &commit_id);
9774 if (err)
9775 goto done;
9776 STAILQ_INSERT_HEAD(commits, qid, entry);
9778 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9781 done:
9782 got_commit_graph_close(graph);
9783 return err;
9786 static const struct got_error *
9787 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9789 const struct got_error *err = NULL;
9790 time_t committer_time;
9791 struct tm tm;
9792 char datebuf[11]; /* YYYY-MM-DD + NUL */
9793 char *author0 = NULL, *author, *smallerthan;
9794 char *logmsg0 = NULL, *logmsg, *newline;
9796 committer_time = got_object_commit_get_committer_time(commit);
9797 if (gmtime_r(&committer_time, &tm) == NULL)
9798 return got_error_from_errno("gmtime_r");
9799 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9800 return got_error(GOT_ERR_NO_SPACE);
9802 author0 = strdup(got_object_commit_get_author(commit));
9803 if (author0 == NULL)
9804 return got_error_from_errno("strdup");
9805 author = author0;
9806 smallerthan = strchr(author, '<');
9807 if (smallerthan && smallerthan[1] != '\0')
9808 author = smallerthan + 1;
9809 author[strcspn(author, "@>")] = '\0';
9811 err = got_object_commit_get_logmsg(&logmsg0, commit);
9812 if (err)
9813 goto done;
9814 logmsg = logmsg0;
9815 while (*logmsg == '\n')
9816 logmsg++;
9817 newline = strchr(logmsg, '\n');
9818 if (newline)
9819 *newline = '\0';
9821 if (asprintf(brief_str, "%s %s %s",
9822 datebuf, author, logmsg) == -1)
9823 err = got_error_from_errno("asprintf");
9824 done:
9825 free(author0);
9826 free(logmsg0);
9827 return err;
9830 static const struct got_error *
9831 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9832 struct got_repository *repo)
9834 const struct got_error *err;
9835 char *id_str;
9837 err = got_object_id_str(&id_str, id);
9838 if (err)
9839 return err;
9841 err = got_ref_delete(ref, repo);
9842 if (err)
9843 goto done;
9845 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9846 done:
9847 free(id_str);
9848 return err;
9851 static const struct got_error *
9852 print_backup_ref(const char *branch_name, const char *new_id_str,
9853 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9854 struct got_reflist_object_id_map *refs_idmap,
9855 struct got_repository *repo)
9857 const struct got_error *err = NULL;
9858 struct got_reflist_head *refs;
9859 char *refs_str = NULL;
9860 struct got_object_id *new_commit_id = NULL;
9861 struct got_commit_object *new_commit = NULL;
9862 char *new_commit_brief_str = NULL;
9863 struct got_object_id *yca_id = NULL;
9864 struct got_commit_object *yca_commit = NULL;
9865 char *yca_id_str = NULL, *yca_brief_str = NULL;
9866 char *custom_refs_str;
9868 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9869 return got_error_from_errno("asprintf");
9871 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9872 0, 0, refs_idmap, custom_refs_str);
9873 if (err)
9874 goto done;
9876 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9877 if (err)
9878 goto done;
9880 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9881 if (refs) {
9882 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9883 if (err)
9884 goto done;
9887 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9888 if (err)
9889 goto done;
9891 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9892 if (err)
9893 goto done;
9895 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9896 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9897 if (err)
9898 goto done;
9900 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9901 refs_str ? " (" : "", refs_str ? refs_str : "",
9902 refs_str ? ")" : "", new_commit_brief_str);
9903 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9904 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9905 free(refs_str);
9906 refs_str = NULL;
9908 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9909 if (err)
9910 goto done;
9912 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9913 if (err)
9914 goto done;
9916 err = got_object_id_str(&yca_id_str, yca_id);
9917 if (err)
9918 goto done;
9920 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9921 if (refs) {
9922 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9923 if (err)
9924 goto done;
9926 printf("history forked at %s%s%s%s\n %s\n",
9927 yca_id_str,
9928 refs_str ? " (" : "", refs_str ? refs_str : "",
9929 refs_str ? ")" : "", yca_brief_str);
9931 done:
9932 free(custom_refs_str);
9933 free(new_commit_id);
9934 free(refs_str);
9935 free(yca_id);
9936 free(yca_id_str);
9937 free(yca_brief_str);
9938 if (new_commit)
9939 got_object_commit_close(new_commit);
9940 if (yca_commit)
9941 got_object_commit_close(yca_commit);
9943 return NULL;
9946 static const struct got_error *
9947 process_backup_refs(const char *backup_ref_prefix,
9948 const char *wanted_branch_name,
9949 int delete, struct got_repository *repo)
9951 const struct got_error *err;
9952 struct got_reflist_head refs, backup_refs;
9953 struct got_reflist_entry *re;
9954 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9955 struct got_object_id *old_commit_id = NULL;
9956 char *branch_name = NULL;
9957 struct got_commit_object *old_commit = NULL;
9958 struct got_reflist_object_id_map *refs_idmap = NULL;
9959 int wanted_branch_found = 0;
9961 TAILQ_INIT(&refs);
9962 TAILQ_INIT(&backup_refs);
9964 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9965 if (err)
9966 return err;
9968 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9969 if (err)
9970 goto done;
9972 if (wanted_branch_name) {
9973 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9974 wanted_branch_name += 11;
9977 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9978 got_ref_cmp_by_commit_timestamp_descending, repo);
9979 if (err)
9980 goto done;
9982 TAILQ_FOREACH(re, &backup_refs, entry) {
9983 const char *refname = got_ref_get_name(re->ref);
9984 char *slash;
9986 err = check_cancelled(NULL);
9987 if (err)
9988 break;
9990 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9991 if (err)
9992 break;
9994 err = got_object_open_as_commit(&old_commit, repo,
9995 old_commit_id);
9996 if (err)
9997 break;
9999 if (strncmp(backup_ref_prefix, refname,
10000 backup_ref_prefix_len) == 0)
10001 refname += backup_ref_prefix_len;
10003 while (refname[0] == '/')
10004 refname++;
10006 branch_name = strdup(refname);
10007 if (branch_name == NULL) {
10008 err = got_error_from_errno("strdup");
10009 break;
10011 slash = strrchr(branch_name, '/');
10012 if (slash) {
10013 *slash = '\0';
10014 refname += strlen(branch_name) + 1;
10017 if (wanted_branch_name == NULL ||
10018 strcmp(wanted_branch_name, branch_name) == 0) {
10019 wanted_branch_found = 1;
10020 if (delete) {
10021 err = delete_backup_ref(re->ref,
10022 old_commit_id, repo);
10023 } else {
10024 err = print_backup_ref(branch_name, refname,
10025 old_commit_id, old_commit, refs_idmap,
10026 repo);
10028 if (err)
10029 break;
10032 free(old_commit_id);
10033 old_commit_id = NULL;
10034 free(branch_name);
10035 branch_name = NULL;
10036 got_object_commit_close(old_commit);
10037 old_commit = NULL;
10040 if (wanted_branch_name && !wanted_branch_found) {
10041 err = got_error_fmt(GOT_ERR_NOT_REF,
10042 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10044 done:
10045 if (refs_idmap)
10046 got_reflist_object_id_map_free(refs_idmap);
10047 got_ref_list_free(&refs);
10048 got_ref_list_free(&backup_refs);
10049 free(old_commit_id);
10050 free(branch_name);
10051 if (old_commit)
10052 got_object_commit_close(old_commit);
10053 return err;
10056 static const struct got_error *
10057 abort_progress(void *arg, unsigned char status, const char *path)
10060 * Unversioned files should not clutter progress output when
10061 * an operation is aborted.
10063 if (status == GOT_STATUS_UNVERSIONED)
10064 return NULL;
10066 return update_progress(arg, status, path);
10069 static const struct got_error *
10070 cmd_rebase(int argc, char *argv[])
10072 const struct got_error *error = NULL;
10073 struct got_worktree *worktree = NULL;
10074 struct got_repository *repo = NULL;
10075 struct got_fileindex *fileindex = NULL;
10076 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10077 struct got_reference *branch = NULL;
10078 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10079 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10080 struct got_object_id *resume_commit_id = NULL;
10081 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10082 struct got_commit_object *commit = NULL;
10083 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10084 int histedit_in_progress = 0, merge_in_progress = 0;
10085 int create_backup = 1, list_backups = 0, delete_backups = 0;
10086 struct got_object_id_queue commits;
10087 struct got_pathlist_head merged_paths;
10088 const struct got_object_id_queue *parent_ids;
10089 struct got_object_qid *qid, *pid;
10090 struct got_update_progress_arg upa;
10091 int *pack_fds = NULL;
10093 STAILQ_INIT(&commits);
10094 TAILQ_INIT(&merged_paths);
10095 memset(&upa, 0, sizeof(upa));
10097 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10098 switch (ch) {
10099 case 'a':
10100 abort_rebase = 1;
10101 break;
10102 case 'c':
10103 continue_rebase = 1;
10104 break;
10105 case 'l':
10106 list_backups = 1;
10107 break;
10108 case 'X':
10109 delete_backups = 1;
10110 break;
10111 default:
10112 usage_rebase();
10113 /* NOTREACHED */
10117 argc -= optind;
10118 argv += optind;
10120 #ifndef PROFILE
10121 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10122 "unveil", NULL) == -1)
10123 err(1, "pledge");
10124 #endif
10125 if (list_backups) {
10126 if (abort_rebase)
10127 option_conflict('l', 'a');
10128 if (continue_rebase)
10129 option_conflict('l', 'c');
10130 if (delete_backups)
10131 option_conflict('l', 'X');
10132 if (argc != 0 && argc != 1)
10133 usage_rebase();
10134 } else if (delete_backups) {
10135 if (abort_rebase)
10136 option_conflict('X', 'a');
10137 if (continue_rebase)
10138 option_conflict('X', 'c');
10139 if (list_backups)
10140 option_conflict('l', 'X');
10141 if (argc != 0 && argc != 1)
10142 usage_rebase();
10143 } else {
10144 if (abort_rebase && continue_rebase)
10145 usage_rebase();
10146 else if (abort_rebase || continue_rebase) {
10147 if (argc != 0)
10148 usage_rebase();
10149 } else if (argc != 1)
10150 usage_rebase();
10153 cwd = getcwd(NULL, 0);
10154 if (cwd == NULL) {
10155 error = got_error_from_errno("getcwd");
10156 goto done;
10159 error = got_repo_pack_fds_open(&pack_fds);
10160 if (error != NULL)
10161 goto done;
10163 error = got_worktree_open(&worktree, cwd);
10164 if (error) {
10165 if (list_backups || delete_backups) {
10166 if (error->code != GOT_ERR_NOT_WORKTREE)
10167 goto done;
10168 } else {
10169 if (error->code == GOT_ERR_NOT_WORKTREE)
10170 error = wrap_not_worktree_error(error,
10171 "rebase", cwd);
10172 goto done;
10176 error = get_gitconfig_path(&gitconfig_path);
10177 if (error)
10178 goto done;
10179 error = got_repo_open(&repo,
10180 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10181 gitconfig_path, pack_fds);
10182 if (error != NULL)
10183 goto done;
10185 error = get_author(&committer, repo, worktree);
10186 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10187 goto done;
10189 error = apply_unveil(got_repo_get_path(repo), 0,
10190 worktree ? got_worktree_get_root_path(worktree) : NULL);
10191 if (error)
10192 goto done;
10194 if (list_backups || delete_backups) {
10195 error = process_backup_refs(
10196 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10197 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10198 goto done; /* nothing else to do */
10201 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10202 worktree);
10203 if (error)
10204 goto done;
10205 if (histedit_in_progress) {
10206 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10207 goto done;
10210 error = got_worktree_merge_in_progress(&merge_in_progress,
10211 worktree, repo);
10212 if (error)
10213 goto done;
10214 if (merge_in_progress) {
10215 error = got_error(GOT_ERR_MERGE_BUSY);
10216 goto done;
10219 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10220 if (error)
10221 goto done;
10223 if (abort_rebase) {
10224 if (!rebase_in_progress) {
10225 error = got_error(GOT_ERR_NOT_REBASING);
10226 goto done;
10228 error = got_worktree_rebase_continue(&resume_commit_id,
10229 &new_base_branch, &tmp_branch, &branch, &fileindex,
10230 worktree, repo);
10231 if (error)
10232 goto done;
10233 printf("Switching work tree to %s\n",
10234 got_ref_get_symref_target(new_base_branch));
10235 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10236 new_base_branch, abort_progress, &upa);
10237 if (error)
10238 goto done;
10239 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10240 print_merge_progress_stats(&upa);
10241 goto done; /* nothing else to do */
10244 if (continue_rebase) {
10245 if (!rebase_in_progress) {
10246 error = got_error(GOT_ERR_NOT_REBASING);
10247 goto done;
10249 error = got_worktree_rebase_continue(&resume_commit_id,
10250 &new_base_branch, &tmp_branch, &branch, &fileindex,
10251 worktree, repo);
10252 if (error)
10253 goto done;
10255 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10256 committer, resume_commit_id, repo);
10257 if (error)
10258 goto done;
10260 yca_id = got_object_id_dup(resume_commit_id);
10261 if (yca_id == NULL) {
10262 error = got_error_from_errno("got_object_id_dup");
10263 goto done;
10265 } else {
10266 error = got_ref_open(&branch, repo, argv[0], 0);
10267 if (error != NULL)
10268 goto done;
10269 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10270 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10271 "will not rebase a branch which lives outside "
10272 "the \"refs/heads/\" reference namespace");
10273 goto done;
10277 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10278 if (error)
10279 goto done;
10281 if (!continue_rebase) {
10282 struct got_object_id *base_commit_id;
10284 base_commit_id = got_worktree_get_base_commit_id(worktree);
10285 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10286 base_commit_id, branch_head_commit_id, 1, repo,
10287 check_cancelled, NULL);
10288 if (error)
10289 goto done;
10290 if (yca_id == NULL) {
10291 error = got_error_msg(GOT_ERR_ANCESTRY,
10292 "specified branch shares no common ancestry "
10293 "with work tree's branch");
10294 goto done;
10297 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10298 if (error) {
10299 if (error->code != GOT_ERR_ANCESTRY)
10300 goto done;
10301 error = NULL;
10302 } else {
10303 struct got_pathlist_head paths;
10304 printf("%s is already based on %s\n",
10305 got_ref_get_name(branch),
10306 got_worktree_get_head_ref_name(worktree));
10307 error = switch_head_ref(branch, branch_head_commit_id,
10308 worktree, repo);
10309 if (error)
10310 goto done;
10311 error = got_worktree_set_base_commit_id(worktree, repo,
10312 branch_head_commit_id);
10313 if (error)
10314 goto done;
10315 TAILQ_INIT(&paths);
10316 error = got_pathlist_append(&paths, "", NULL);
10317 if (error)
10318 goto done;
10319 error = got_worktree_checkout_files(worktree,
10320 &paths, repo, update_progress, &upa,
10321 check_cancelled, NULL);
10322 got_pathlist_free(&paths);
10323 if (error)
10324 goto done;
10325 if (upa.did_something) {
10326 char *id_str;
10327 error = got_object_id_str(&id_str,
10328 branch_head_commit_id);
10329 if (error)
10330 goto done;
10331 printf("Updated to %s: %s\n",
10332 got_worktree_get_head_ref_name(worktree),
10333 id_str);
10334 free(id_str);
10335 } else
10336 printf("Already up-to-date\n");
10337 print_update_progress_stats(&upa);
10338 goto done;
10342 commit_id = branch_head_commit_id;
10343 error = got_object_open_as_commit(&commit, repo, commit_id);
10344 if (error)
10345 goto done;
10347 parent_ids = got_object_commit_get_parent_ids(commit);
10348 pid = STAILQ_FIRST(parent_ids);
10349 if (pid == NULL) {
10350 error = got_error(GOT_ERR_EMPTY_REBASE);
10351 goto done;
10353 error = collect_commits(&commits, commit_id, &pid->id,
10354 yca_id, got_worktree_get_path_prefix(worktree),
10355 GOT_ERR_REBASE_PATH, repo);
10356 got_object_commit_close(commit);
10357 commit = NULL;
10358 if (error)
10359 goto done;
10361 if (!continue_rebase) {
10362 error = got_worktree_rebase_prepare(&new_base_branch,
10363 &tmp_branch, &fileindex, worktree, branch, repo);
10364 if (error)
10365 goto done;
10368 if (STAILQ_EMPTY(&commits)) {
10369 if (continue_rebase) {
10370 error = rebase_complete(worktree, fileindex,
10371 branch, new_base_branch, tmp_branch, repo,
10372 create_backup);
10373 goto done;
10374 } else {
10375 /* Fast-forward the reference of the branch. */
10376 struct got_object_id *new_head_commit_id;
10377 char *id_str;
10378 error = got_ref_resolve(&new_head_commit_id, repo,
10379 new_base_branch);
10380 if (error)
10381 goto done;
10382 error = got_object_id_str(&id_str, new_head_commit_id);
10383 if (error)
10384 goto done;
10385 printf("Forwarding %s to commit %s\n",
10386 got_ref_get_name(branch), id_str);
10387 free(id_str);
10388 error = got_ref_change_ref(branch,
10389 new_head_commit_id);
10390 if (error)
10391 goto done;
10392 /* No backup needed since objects did not change. */
10393 create_backup = 0;
10397 pid = NULL;
10398 STAILQ_FOREACH(qid, &commits, entry) {
10400 commit_id = &qid->id;
10401 parent_id = pid ? &pid->id : yca_id;
10402 pid = qid;
10404 memset(&upa, 0, sizeof(upa));
10405 error = got_worktree_rebase_merge_files(&merged_paths,
10406 worktree, fileindex, parent_id, commit_id, repo,
10407 update_progress, &upa, check_cancelled, NULL);
10408 if (error)
10409 goto done;
10411 print_merge_progress_stats(&upa);
10412 if (upa.conflicts > 0 || upa.missing > 0 ||
10413 upa.not_deleted > 0 || upa.unversioned > 0) {
10414 if (upa.conflicts > 0) {
10415 error = show_rebase_merge_conflict(&qid->id,
10416 repo);
10417 if (error)
10418 goto done;
10420 got_worktree_rebase_pathlist_free(&merged_paths);
10421 break;
10424 error = rebase_commit(&merged_paths, worktree, fileindex,
10425 tmp_branch, committer, commit_id, repo);
10426 got_worktree_rebase_pathlist_free(&merged_paths);
10427 if (error)
10428 goto done;
10431 if (upa.conflicts > 0 || upa.missing > 0 ||
10432 upa.not_deleted > 0 || upa.unversioned > 0) {
10433 error = got_worktree_rebase_postpone(worktree, fileindex);
10434 if (error)
10435 goto done;
10436 if (upa.conflicts > 0 && upa.missing == 0 &&
10437 upa.not_deleted == 0 && upa.unversioned == 0) {
10438 error = got_error_msg(GOT_ERR_CONFLICTS,
10439 "conflicts must be resolved before rebasing "
10440 "can continue");
10441 } else if (upa.conflicts > 0) {
10442 error = got_error_msg(GOT_ERR_CONFLICTS,
10443 "conflicts must be resolved before rebasing "
10444 "can continue; changes destined for some "
10445 "files were not yet merged and should be "
10446 "merged manually if required before the "
10447 "rebase operation is continued");
10448 } else {
10449 error = got_error_msg(GOT_ERR_CONFLICTS,
10450 "changes destined for some files were not "
10451 "yet merged and should be merged manually "
10452 "if required before the rebase operation "
10453 "is continued");
10455 } else
10456 error = rebase_complete(worktree, fileindex, branch,
10457 new_base_branch, tmp_branch, repo, create_backup);
10458 done:
10459 free(cwd);
10460 free(committer);
10461 free(gitconfig_path);
10462 got_object_id_queue_free(&commits);
10463 free(branch_head_commit_id);
10464 free(resume_commit_id);
10465 free(yca_id);
10466 if (commit)
10467 got_object_commit_close(commit);
10468 if (branch)
10469 got_ref_close(branch);
10470 if (new_base_branch)
10471 got_ref_close(new_base_branch);
10472 if (tmp_branch)
10473 got_ref_close(tmp_branch);
10474 if (worktree)
10475 got_worktree_close(worktree);
10476 if (repo) {
10477 const struct got_error *close_err = got_repo_close(repo);
10478 if (error == NULL)
10479 error = close_err;
10481 if (pack_fds) {
10482 const struct got_error *pack_err =
10483 got_repo_pack_fds_close(pack_fds);
10484 if (error == NULL)
10485 error = pack_err;
10487 return error;
10490 __dead static void
10491 usage_histedit(void)
10493 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10494 "[branch]\n", getprogname());
10495 exit(1);
10498 #define GOT_HISTEDIT_PICK 'p'
10499 #define GOT_HISTEDIT_EDIT 'e'
10500 #define GOT_HISTEDIT_FOLD 'f'
10501 #define GOT_HISTEDIT_DROP 'd'
10502 #define GOT_HISTEDIT_MESG 'm'
10504 static const struct got_histedit_cmd {
10505 unsigned char code;
10506 const char *name;
10507 const char *desc;
10508 } got_histedit_cmds[] = {
10509 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10510 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10511 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10512 "be used" },
10513 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10514 { GOT_HISTEDIT_MESG, "mesg",
10515 "single-line log message for commit above (open editor if empty)" },
10518 struct got_histedit_list_entry {
10519 TAILQ_ENTRY(got_histedit_list_entry) entry;
10520 struct got_object_id *commit_id;
10521 const struct got_histedit_cmd *cmd;
10522 char *logmsg;
10524 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10526 static const struct got_error *
10527 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10528 FILE *f, struct got_repository *repo)
10530 const struct got_error *err = NULL;
10531 char *logmsg = NULL, *id_str = NULL;
10532 struct got_commit_object *commit = NULL;
10533 int n;
10535 err = got_object_open_as_commit(&commit, repo, commit_id);
10536 if (err)
10537 goto done;
10539 err = get_short_logmsg(&logmsg, 34, commit);
10540 if (err)
10541 goto done;
10543 err = got_object_id_str(&id_str, commit_id);
10544 if (err)
10545 goto done;
10547 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10548 if (n < 0)
10549 err = got_ferror(f, GOT_ERR_IO);
10550 done:
10551 if (commit)
10552 got_object_commit_close(commit);
10553 free(id_str);
10554 free(logmsg);
10555 return err;
10558 static const struct got_error *
10559 histedit_write_commit_list(struct got_object_id_queue *commits,
10560 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10561 struct got_repository *repo)
10563 const struct got_error *err = NULL;
10564 struct got_object_qid *qid;
10565 const char *histedit_cmd = NULL;
10567 if (STAILQ_EMPTY(commits))
10568 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10570 STAILQ_FOREACH(qid, commits, entry) {
10571 histedit_cmd = got_histedit_cmds[0].name;
10572 if (edit_only)
10573 histedit_cmd = "edit";
10574 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10575 histedit_cmd = "fold";
10576 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10577 if (err)
10578 break;
10579 if (edit_logmsg_only) {
10580 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10581 if (n < 0) {
10582 err = got_ferror(f, GOT_ERR_IO);
10583 break;
10588 return err;
10591 static const struct got_error *
10592 write_cmd_list(FILE *f, const char *branch_name,
10593 struct got_object_id_queue *commits)
10595 const struct got_error *err = NULL;
10596 size_t i;
10597 int n;
10598 char *id_str;
10599 struct got_object_qid *qid;
10601 qid = STAILQ_FIRST(commits);
10602 err = got_object_id_str(&id_str, &qid->id);
10603 if (err)
10604 return err;
10606 n = fprintf(f,
10607 "# Editing the history of branch '%s' starting at\n"
10608 "# commit %s\n"
10609 "# Commits will be processed in order from top to "
10610 "bottom of this file.\n", branch_name, id_str);
10611 if (n < 0) {
10612 err = got_ferror(f, GOT_ERR_IO);
10613 goto done;
10616 n = fprintf(f, "# Available histedit commands:\n");
10617 if (n < 0) {
10618 err = got_ferror(f, GOT_ERR_IO);
10619 goto done;
10622 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10623 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10624 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10625 cmd->desc);
10626 if (n < 0) {
10627 err = got_ferror(f, GOT_ERR_IO);
10628 break;
10631 done:
10632 free(id_str);
10633 return err;
10636 static const struct got_error *
10637 histedit_syntax_error(int lineno)
10639 static char msg[42];
10640 int ret;
10642 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10643 lineno);
10644 if (ret < 0 || (size_t)ret >= sizeof(msg))
10645 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10647 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10650 static const struct got_error *
10651 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10652 char *logmsg, struct got_repository *repo)
10654 const struct got_error *err;
10655 struct got_commit_object *folded_commit = NULL;
10656 char *id_str, *folded_logmsg = NULL;
10658 err = got_object_id_str(&id_str, hle->commit_id);
10659 if (err)
10660 return err;
10662 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10663 if (err)
10664 goto done;
10666 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10667 if (err)
10668 goto done;
10669 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10670 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10671 folded_logmsg) == -1) {
10672 err = got_error_from_errno("asprintf");
10674 done:
10675 if (folded_commit)
10676 got_object_commit_close(folded_commit);
10677 free(id_str);
10678 free(folded_logmsg);
10679 return err;
10682 static struct got_histedit_list_entry *
10683 get_folded_commits(struct got_histedit_list_entry *hle)
10685 struct got_histedit_list_entry *prev, *folded = NULL;
10687 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10688 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10689 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10690 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10691 folded = prev;
10692 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10695 return folded;
10698 static const struct got_error *
10699 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10700 struct got_repository *repo)
10702 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10703 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10704 const struct got_error *err = NULL;
10705 struct got_commit_object *commit = NULL;
10706 int logmsg_len;
10707 int fd;
10708 struct got_histedit_list_entry *folded = NULL;
10710 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10711 if (err)
10712 return err;
10714 folded = get_folded_commits(hle);
10715 if (folded) {
10716 while (folded != hle) {
10717 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10718 folded = TAILQ_NEXT(folded, entry);
10719 continue;
10721 err = append_folded_commit_msg(&new_msg, folded,
10722 logmsg, repo);
10723 if (err)
10724 goto done;
10725 free(logmsg);
10726 logmsg = new_msg;
10727 folded = TAILQ_NEXT(folded, entry);
10731 err = got_object_id_str(&id_str, hle->commit_id);
10732 if (err)
10733 goto done;
10734 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10735 if (err)
10736 goto done;
10737 logmsg_len = asprintf(&new_msg,
10738 "%s\n# original log message of commit %s: %s",
10739 logmsg ? logmsg : "", id_str, orig_logmsg);
10740 if (logmsg_len == -1) {
10741 err = got_error_from_errno("asprintf");
10742 goto done;
10744 free(logmsg);
10745 logmsg = new_msg;
10747 err = got_object_id_str(&id_str, hle->commit_id);
10748 if (err)
10749 goto done;
10751 err = got_opentemp_named_fd(&logmsg_path, &fd,
10752 GOT_TMPDIR_STR "/got-logmsg", "");
10753 if (err)
10754 goto done;
10756 write(fd, logmsg, logmsg_len);
10757 close(fd);
10759 err = get_editor(&editor);
10760 if (err)
10761 goto done;
10763 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10764 logmsg_len, 0);
10765 if (err) {
10766 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10767 goto done;
10768 err = NULL;
10769 hle->logmsg = strdup(new_msg);
10770 if (hle->logmsg == NULL)
10771 err = got_error_from_errno("strdup");
10773 done:
10774 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10775 err = got_error_from_errno2("unlink", logmsg_path);
10776 free(logmsg_path);
10777 free(logmsg);
10778 free(orig_logmsg);
10779 free(editor);
10780 if (commit)
10781 got_object_commit_close(commit);
10782 return err;
10785 static const struct got_error *
10786 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10787 FILE *f, struct got_repository *repo)
10789 const struct got_error *err = NULL;
10790 char *line = NULL, *p, *end;
10791 size_t i, size;
10792 ssize_t len;
10793 int lineno = 0, lastcmd = -1;
10794 const struct got_histedit_cmd *cmd;
10795 struct got_object_id *commit_id = NULL;
10796 struct got_histedit_list_entry *hle = NULL;
10798 for (;;) {
10799 len = getline(&line, &size, f);
10800 if (len == -1) {
10801 const struct got_error *getline_err;
10802 if (feof(f))
10803 break;
10804 getline_err = got_error_from_errno("getline");
10805 err = got_ferror(f, getline_err->code);
10806 break;
10808 lineno++;
10809 p = line;
10810 while (isspace((unsigned char)p[0]))
10811 p++;
10812 if (p[0] == '#' || p[0] == '\0') {
10813 free(line);
10814 line = NULL;
10815 continue;
10817 cmd = NULL;
10818 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10819 cmd = &got_histedit_cmds[i];
10820 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10821 isspace((unsigned char)p[strlen(cmd->name)])) {
10822 p += strlen(cmd->name);
10823 break;
10825 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10826 p++;
10827 break;
10830 if (i == nitems(got_histedit_cmds)) {
10831 err = histedit_syntax_error(lineno);
10832 break;
10834 while (isspace((unsigned char)p[0]))
10835 p++;
10836 if (cmd->code == GOT_HISTEDIT_MESG) {
10837 if (lastcmd != GOT_HISTEDIT_PICK &&
10838 lastcmd != GOT_HISTEDIT_EDIT) {
10839 err = got_error(GOT_ERR_HISTEDIT_CMD);
10840 break;
10842 if (p[0] == '\0') {
10843 err = histedit_edit_logmsg(hle, repo);
10844 if (err)
10845 break;
10846 } else {
10847 hle->logmsg = strdup(p);
10848 if (hle->logmsg == NULL) {
10849 err = got_error_from_errno("strdup");
10850 break;
10853 free(line);
10854 line = NULL;
10855 lastcmd = cmd->code;
10856 continue;
10857 } else {
10858 end = p;
10859 while (end[0] && !isspace((unsigned char)end[0]))
10860 end++;
10861 *end = '\0';
10863 err = got_object_resolve_id_str(&commit_id, repo, p);
10864 if (err) {
10865 /* override error code */
10866 err = histedit_syntax_error(lineno);
10867 break;
10870 hle = malloc(sizeof(*hle));
10871 if (hle == NULL) {
10872 err = got_error_from_errno("malloc");
10873 break;
10875 hle->cmd = cmd;
10876 hle->commit_id = commit_id;
10877 hle->logmsg = NULL;
10878 commit_id = NULL;
10879 free(line);
10880 line = NULL;
10881 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10882 lastcmd = cmd->code;
10885 free(line);
10886 free(commit_id);
10887 return err;
10890 static const struct got_error *
10891 histedit_check_script(struct got_histedit_list *histedit_cmds,
10892 struct got_object_id_queue *commits, struct got_repository *repo)
10894 const struct got_error *err = NULL;
10895 struct got_object_qid *qid;
10896 struct got_histedit_list_entry *hle;
10897 static char msg[92];
10898 char *id_str;
10900 if (TAILQ_EMPTY(histedit_cmds))
10901 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10902 "histedit script contains no commands");
10903 if (STAILQ_EMPTY(commits))
10904 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10906 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10907 struct got_histedit_list_entry *hle2;
10908 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10909 if (hle == hle2)
10910 continue;
10911 if (got_object_id_cmp(hle->commit_id,
10912 hle2->commit_id) != 0)
10913 continue;
10914 err = got_object_id_str(&id_str, hle->commit_id);
10915 if (err)
10916 return err;
10917 snprintf(msg, sizeof(msg), "commit %s is listed "
10918 "more than once in histedit script", id_str);
10919 free(id_str);
10920 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10924 STAILQ_FOREACH(qid, commits, entry) {
10925 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10926 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10927 break;
10929 if (hle == NULL) {
10930 err = got_object_id_str(&id_str, &qid->id);
10931 if (err)
10932 return err;
10933 snprintf(msg, sizeof(msg),
10934 "commit %s missing from histedit script", id_str);
10935 free(id_str);
10936 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10940 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10941 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10942 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10943 "last commit in histedit script cannot be folded");
10945 return NULL;
10948 static const struct got_error *
10949 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10950 const char *path, struct got_object_id_queue *commits,
10951 struct got_repository *repo)
10953 const struct got_error *err = NULL;
10954 char *editor;
10955 FILE *f = NULL;
10957 err = get_editor(&editor);
10958 if (err)
10959 return err;
10961 if (spawn_editor(editor, path) == -1) {
10962 err = got_error_from_errno("failed spawning editor");
10963 goto done;
10966 f = fopen(path, "re");
10967 if (f == NULL) {
10968 err = got_error_from_errno("fopen");
10969 goto done;
10971 err = histedit_parse_list(histedit_cmds, f, repo);
10972 if (err)
10973 goto done;
10975 err = histedit_check_script(histedit_cmds, commits, repo);
10976 done:
10977 if (f && fclose(f) == EOF && err == NULL)
10978 err = got_error_from_errno("fclose");
10979 free(editor);
10980 return err;
10983 static const struct got_error *
10984 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10985 struct got_object_id_queue *, const char *, const char *,
10986 struct got_repository *);
10988 static const struct got_error *
10989 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10990 struct got_object_id_queue *commits, const char *branch_name,
10991 int edit_logmsg_only, int fold_only, int edit_only,
10992 struct got_repository *repo)
10994 const struct got_error *err;
10995 FILE *f = NULL;
10996 char *path = NULL;
10998 err = got_opentemp_named(&path, &f, "got-histedit", "");
10999 if (err)
11000 return err;
11002 err = write_cmd_list(f, branch_name, commits);
11003 if (err)
11004 goto done;
11006 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11007 fold_only, edit_only, repo);
11008 if (err)
11009 goto done;
11011 if (edit_logmsg_only || fold_only || edit_only) {
11012 rewind(f);
11013 err = histedit_parse_list(histedit_cmds, f, repo);
11014 } else {
11015 if (fclose(f) == EOF) {
11016 err = got_error_from_errno("fclose");
11017 goto done;
11019 f = NULL;
11020 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11021 if (err) {
11022 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11023 err->code != GOT_ERR_HISTEDIT_CMD)
11024 goto done;
11025 err = histedit_edit_list_retry(histedit_cmds, err,
11026 commits, path, branch_name, repo);
11029 done:
11030 if (f && fclose(f) == EOF && err == NULL)
11031 err = got_error_from_errno("fclose");
11032 if (path && unlink(path) != 0 && err == NULL)
11033 err = got_error_from_errno2("unlink", path);
11034 free(path);
11035 return err;
11038 static const struct got_error *
11039 histedit_save_list(struct got_histedit_list *histedit_cmds,
11040 struct got_worktree *worktree, struct got_repository *repo)
11042 const struct got_error *err = NULL;
11043 char *path = NULL;
11044 FILE *f = NULL;
11045 struct got_histedit_list_entry *hle;
11046 struct got_commit_object *commit = NULL;
11048 err = got_worktree_get_histedit_script_path(&path, worktree);
11049 if (err)
11050 return err;
11052 f = fopen(path, "we");
11053 if (f == NULL) {
11054 err = got_error_from_errno2("fopen", path);
11055 goto done;
11057 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11058 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11059 repo);
11060 if (err)
11061 break;
11063 if (hle->logmsg) {
11064 int n = fprintf(f, "%c %s\n",
11065 GOT_HISTEDIT_MESG, hle->logmsg);
11066 if (n < 0) {
11067 err = got_ferror(f, GOT_ERR_IO);
11068 break;
11072 done:
11073 if (f && fclose(f) == EOF && err == NULL)
11074 err = got_error_from_errno("fclose");
11075 free(path);
11076 if (commit)
11077 got_object_commit_close(commit);
11078 return err;
11081 static void
11082 histedit_free_list(struct got_histedit_list *histedit_cmds)
11084 struct got_histedit_list_entry *hle;
11086 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11087 TAILQ_REMOVE(histedit_cmds, hle, entry);
11088 free(hle);
11092 static const struct got_error *
11093 histedit_load_list(struct got_histedit_list *histedit_cmds,
11094 const char *path, struct got_repository *repo)
11096 const struct got_error *err = NULL;
11097 FILE *f = NULL;
11099 f = fopen(path, "re");
11100 if (f == NULL) {
11101 err = got_error_from_errno2("fopen", path);
11102 goto done;
11105 err = histedit_parse_list(histedit_cmds, f, repo);
11106 done:
11107 if (f && fclose(f) == EOF && err == NULL)
11108 err = got_error_from_errno("fclose");
11109 return err;
11112 static const struct got_error *
11113 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11114 const struct got_error *edit_err, struct got_object_id_queue *commits,
11115 const char *path, const char *branch_name, struct got_repository *repo)
11117 const struct got_error *err = NULL, *prev_err = edit_err;
11118 int resp = ' ';
11120 while (resp != 'c' && resp != 'r' && resp != 'a') {
11121 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11122 "or (a)bort: ", getprogname(), prev_err->msg);
11123 resp = getchar();
11124 if (resp == '\n')
11125 resp = getchar();
11126 if (resp == 'c') {
11127 histedit_free_list(histedit_cmds);
11128 err = histedit_run_editor(histedit_cmds, path, commits,
11129 repo);
11130 if (err) {
11131 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11132 err->code != GOT_ERR_HISTEDIT_CMD)
11133 break;
11134 prev_err = err;
11135 resp = ' ';
11136 continue;
11138 break;
11139 } else if (resp == 'r') {
11140 histedit_free_list(histedit_cmds);
11141 err = histedit_edit_script(histedit_cmds,
11142 commits, branch_name, 0, 0, 0, repo);
11143 if (err) {
11144 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11145 err->code != GOT_ERR_HISTEDIT_CMD)
11146 break;
11147 prev_err = err;
11148 resp = ' ';
11149 continue;
11151 break;
11152 } else if (resp == 'a') {
11153 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11154 break;
11155 } else
11156 printf("invalid response '%c'\n", resp);
11159 return err;
11162 static const struct got_error *
11163 histedit_complete(struct got_worktree *worktree,
11164 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11165 struct got_reference *branch, struct got_repository *repo)
11167 printf("Switching work tree to %s\n",
11168 got_ref_get_symref_target(branch));
11169 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11170 branch, repo);
11173 static const struct got_error *
11174 show_histedit_progress(struct got_commit_object *commit,
11175 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11177 const struct got_error *err;
11178 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11180 err = got_object_id_str(&old_id_str, hle->commit_id);
11181 if (err)
11182 goto done;
11184 if (new_id) {
11185 err = got_object_id_str(&new_id_str, new_id);
11186 if (err)
11187 goto done;
11190 old_id_str[12] = '\0';
11191 if (new_id_str)
11192 new_id_str[12] = '\0';
11194 if (hle->logmsg) {
11195 logmsg = strdup(hle->logmsg);
11196 if (logmsg == NULL) {
11197 err = got_error_from_errno("strdup");
11198 goto done;
11200 trim_logmsg(logmsg, 42);
11201 } else {
11202 err = get_short_logmsg(&logmsg, 42, commit);
11203 if (err)
11204 goto done;
11207 switch (hle->cmd->code) {
11208 case GOT_HISTEDIT_PICK:
11209 case GOT_HISTEDIT_EDIT:
11210 printf("%s -> %s: %s\n", old_id_str,
11211 new_id_str ? new_id_str : "no-op change", logmsg);
11212 break;
11213 case GOT_HISTEDIT_DROP:
11214 case GOT_HISTEDIT_FOLD:
11215 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11216 logmsg);
11217 break;
11218 default:
11219 break;
11221 done:
11222 free(old_id_str);
11223 free(new_id_str);
11224 return err;
11227 static const struct got_error *
11228 histedit_commit(struct got_pathlist_head *merged_paths,
11229 struct got_worktree *worktree, struct got_fileindex *fileindex,
11230 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11231 const char *committer, struct got_repository *repo)
11233 const struct got_error *err;
11234 struct got_commit_object *commit;
11235 struct got_object_id *new_commit_id;
11237 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11238 && hle->logmsg == NULL) {
11239 err = histedit_edit_logmsg(hle, repo);
11240 if (err)
11241 return err;
11244 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11245 if (err)
11246 return err;
11248 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11249 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11250 hle->logmsg, repo);
11251 if (err) {
11252 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11253 goto done;
11254 err = show_histedit_progress(commit, hle, NULL);
11255 } else {
11256 err = show_histedit_progress(commit, hle, new_commit_id);
11257 free(new_commit_id);
11259 done:
11260 got_object_commit_close(commit);
11261 return err;
11264 static const struct got_error *
11265 histedit_skip_commit(struct got_histedit_list_entry *hle,
11266 struct got_worktree *worktree, struct got_repository *repo)
11268 const struct got_error *error;
11269 struct got_commit_object *commit;
11271 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11272 repo);
11273 if (error)
11274 return error;
11276 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11277 if (error)
11278 return error;
11280 error = show_histedit_progress(commit, hle, NULL);
11281 got_object_commit_close(commit);
11282 return error;
11285 static const struct got_error *
11286 check_local_changes(void *arg, unsigned char status,
11287 unsigned char staged_status, const char *path,
11288 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11289 struct got_object_id *commit_id, int dirfd, const char *de_name)
11291 int *have_local_changes = arg;
11293 switch (status) {
11294 case GOT_STATUS_ADD:
11295 case GOT_STATUS_DELETE:
11296 case GOT_STATUS_MODIFY:
11297 case GOT_STATUS_CONFLICT:
11298 *have_local_changes = 1;
11299 return got_error(GOT_ERR_CANCELLED);
11300 default:
11301 break;
11304 switch (staged_status) {
11305 case GOT_STATUS_ADD:
11306 case GOT_STATUS_DELETE:
11307 case GOT_STATUS_MODIFY:
11308 *have_local_changes = 1;
11309 return got_error(GOT_ERR_CANCELLED);
11310 default:
11311 break;
11314 return NULL;
11317 static const struct got_error *
11318 cmd_histedit(int argc, char *argv[])
11320 const struct got_error *error = NULL;
11321 struct got_worktree *worktree = NULL;
11322 struct got_fileindex *fileindex = NULL;
11323 struct got_repository *repo = NULL;
11324 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11325 struct got_reference *branch = NULL;
11326 struct got_reference *tmp_branch = NULL;
11327 struct got_object_id *resume_commit_id = NULL;
11328 struct got_object_id *base_commit_id = NULL;
11329 struct got_object_id *head_commit_id = NULL;
11330 struct got_commit_object *commit = NULL;
11331 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11332 struct got_update_progress_arg upa;
11333 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11334 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11335 int list_backups = 0, delete_backups = 0;
11336 const char *edit_script_path = NULL;
11337 struct got_object_id_queue commits;
11338 struct got_pathlist_head merged_paths;
11339 const struct got_object_id_queue *parent_ids;
11340 struct got_object_qid *pid;
11341 struct got_histedit_list histedit_cmds;
11342 struct got_histedit_list_entry *hle;
11343 int *pack_fds = NULL;
11345 STAILQ_INIT(&commits);
11346 TAILQ_INIT(&histedit_cmds);
11347 TAILQ_INIT(&merged_paths);
11348 memset(&upa, 0, sizeof(upa));
11350 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11351 switch (ch) {
11352 case 'a':
11353 abort_edit = 1;
11354 break;
11355 case 'c':
11356 continue_edit = 1;
11357 break;
11358 case 'e':
11359 edit_only = 1;
11360 break;
11361 case 'F':
11362 edit_script_path = optarg;
11363 break;
11364 case 'f':
11365 fold_only = 1;
11366 break;
11367 case 'l':
11368 list_backups = 1;
11369 break;
11370 case 'm':
11371 edit_logmsg_only = 1;
11372 break;
11373 case 'X':
11374 delete_backups = 1;
11375 break;
11376 default:
11377 usage_histedit();
11378 /* NOTREACHED */
11382 argc -= optind;
11383 argv += optind;
11385 #ifndef PROFILE
11386 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11387 "unveil", NULL) == -1)
11388 err(1, "pledge");
11389 #endif
11390 if (abort_edit && continue_edit)
11391 option_conflict('a', 'c');
11392 if (edit_script_path && edit_logmsg_only)
11393 option_conflict('F', 'm');
11394 if (abort_edit && edit_logmsg_only)
11395 option_conflict('a', 'm');
11396 if (continue_edit && edit_logmsg_only)
11397 option_conflict('c', 'm');
11398 if (abort_edit && fold_only)
11399 option_conflict('a', 'f');
11400 if (continue_edit && fold_only)
11401 option_conflict('c', 'f');
11402 if (fold_only && edit_logmsg_only)
11403 option_conflict('f', 'm');
11404 if (edit_script_path && fold_only)
11405 option_conflict('F', 'f');
11406 if (abort_edit && edit_only)
11407 option_conflict('a', 'e');
11408 if (continue_edit && edit_only)
11409 option_conflict('c', 'e');
11410 if (edit_only && edit_logmsg_only)
11411 option_conflict('e', 'm');
11412 if (edit_script_path && edit_only)
11413 option_conflict('F', 'e');
11414 if (list_backups) {
11415 if (abort_edit)
11416 option_conflict('l', 'a');
11417 if (continue_edit)
11418 option_conflict('l', 'c');
11419 if (edit_script_path)
11420 option_conflict('l', 'F');
11421 if (edit_logmsg_only)
11422 option_conflict('l', 'm');
11423 if (fold_only)
11424 option_conflict('l', 'f');
11425 if (edit_only)
11426 option_conflict('l', 'e');
11427 if (delete_backups)
11428 option_conflict('l', 'X');
11429 if (argc != 0 && argc != 1)
11430 usage_histedit();
11431 } else if (delete_backups) {
11432 if (abort_edit)
11433 option_conflict('X', 'a');
11434 if (continue_edit)
11435 option_conflict('X', 'c');
11436 if (edit_script_path)
11437 option_conflict('X', 'F');
11438 if (edit_logmsg_only)
11439 option_conflict('X', 'm');
11440 if (fold_only)
11441 option_conflict('X', 'f');
11442 if (edit_only)
11443 option_conflict('X', 'e');
11444 if (list_backups)
11445 option_conflict('X', 'l');
11446 if (argc != 0 && argc != 1)
11447 usage_histedit();
11448 } else if (argc != 0)
11449 usage_histedit();
11452 * This command cannot apply unveil(2) in all cases because the
11453 * user may choose to run an editor to edit the histedit script
11454 * and to edit individual commit log messages.
11455 * unveil(2) traverses exec(2); if an editor is used we have to
11456 * apply unveil after edit script and log messages have been written.
11457 * XXX TODO: Make use of unveil(2) where possible.
11460 cwd = getcwd(NULL, 0);
11461 if (cwd == NULL) {
11462 error = got_error_from_errno("getcwd");
11463 goto done;
11466 error = got_repo_pack_fds_open(&pack_fds);
11467 if (error != NULL)
11468 goto done;
11470 error = got_worktree_open(&worktree, cwd);
11471 if (error) {
11472 if (list_backups || delete_backups) {
11473 if (error->code != GOT_ERR_NOT_WORKTREE)
11474 goto done;
11475 } else {
11476 if (error->code == GOT_ERR_NOT_WORKTREE)
11477 error = wrap_not_worktree_error(error,
11478 "histedit", cwd);
11479 goto done;
11483 if (list_backups || delete_backups) {
11484 error = got_repo_open(&repo,
11485 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11486 NULL, pack_fds);
11487 if (error != NULL)
11488 goto done;
11489 error = apply_unveil(got_repo_get_path(repo), 0,
11490 worktree ? got_worktree_get_root_path(worktree) : NULL);
11491 if (error)
11492 goto done;
11493 error = process_backup_refs(
11494 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11495 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11496 goto done; /* nothing else to do */
11499 error = get_gitconfig_path(&gitconfig_path);
11500 if (error)
11501 goto done;
11502 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11503 gitconfig_path, pack_fds);
11504 if (error != NULL)
11505 goto done;
11507 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11508 if (error)
11509 goto done;
11510 if (rebase_in_progress) {
11511 error = got_error(GOT_ERR_REBASING);
11512 goto done;
11515 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11516 repo);
11517 if (error)
11518 goto done;
11519 if (merge_in_progress) {
11520 error = got_error(GOT_ERR_MERGE_BUSY);
11521 goto done;
11524 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11525 if (error)
11526 goto done;
11528 if (edit_in_progress && edit_logmsg_only) {
11529 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11530 "histedit operation is in progress in this "
11531 "work tree and must be continued or aborted "
11532 "before the -m option can be used");
11533 goto done;
11535 if (edit_in_progress && fold_only) {
11536 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11537 "histedit operation is in progress in this "
11538 "work tree and must be continued or aborted "
11539 "before the -f option can be used");
11540 goto done;
11542 if (edit_in_progress && edit_only) {
11543 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11544 "histedit operation is in progress in this "
11545 "work tree and must be continued or aborted "
11546 "before the -e option can be used");
11547 goto done;
11550 if (edit_in_progress && abort_edit) {
11551 error = got_worktree_histedit_continue(&resume_commit_id,
11552 &tmp_branch, &branch, &base_commit_id, &fileindex,
11553 worktree, repo);
11554 if (error)
11555 goto done;
11556 printf("Switching work tree to %s\n",
11557 got_ref_get_symref_target(branch));
11558 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11559 branch, base_commit_id, abort_progress, &upa);
11560 if (error)
11561 goto done;
11562 printf("Histedit of %s aborted\n",
11563 got_ref_get_symref_target(branch));
11564 print_merge_progress_stats(&upa);
11565 goto done; /* nothing else to do */
11566 } else if (abort_edit) {
11567 error = got_error(GOT_ERR_NOT_HISTEDIT);
11568 goto done;
11571 error = get_author(&committer, repo, worktree);
11572 if (error)
11573 goto done;
11575 if (continue_edit) {
11576 char *path;
11578 if (!edit_in_progress) {
11579 error = got_error(GOT_ERR_NOT_HISTEDIT);
11580 goto done;
11583 error = got_worktree_get_histedit_script_path(&path, worktree);
11584 if (error)
11585 goto done;
11587 error = histedit_load_list(&histedit_cmds, path, repo);
11588 free(path);
11589 if (error)
11590 goto done;
11592 error = got_worktree_histedit_continue(&resume_commit_id,
11593 &tmp_branch, &branch, &base_commit_id, &fileindex,
11594 worktree, repo);
11595 if (error)
11596 goto done;
11598 error = got_ref_resolve(&head_commit_id, repo, branch);
11599 if (error)
11600 goto done;
11602 error = got_object_open_as_commit(&commit, repo,
11603 head_commit_id);
11604 if (error)
11605 goto done;
11606 parent_ids = got_object_commit_get_parent_ids(commit);
11607 pid = STAILQ_FIRST(parent_ids);
11608 if (pid == NULL) {
11609 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11610 goto done;
11612 error = collect_commits(&commits, head_commit_id, &pid->id,
11613 base_commit_id, got_worktree_get_path_prefix(worktree),
11614 GOT_ERR_HISTEDIT_PATH, repo);
11615 got_object_commit_close(commit);
11616 commit = NULL;
11617 if (error)
11618 goto done;
11619 } else {
11620 if (edit_in_progress) {
11621 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11622 goto done;
11625 error = got_ref_open(&branch, repo,
11626 got_worktree_get_head_ref_name(worktree), 0);
11627 if (error != NULL)
11628 goto done;
11630 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11631 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11632 "will not edit commit history of a branch outside "
11633 "the \"refs/heads/\" reference namespace");
11634 goto done;
11637 error = got_ref_resolve(&head_commit_id, repo, branch);
11638 got_ref_close(branch);
11639 branch = NULL;
11640 if (error)
11641 goto done;
11643 error = got_object_open_as_commit(&commit, repo,
11644 head_commit_id);
11645 if (error)
11646 goto done;
11647 parent_ids = got_object_commit_get_parent_ids(commit);
11648 pid = STAILQ_FIRST(parent_ids);
11649 if (pid == NULL) {
11650 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11651 goto done;
11653 error = collect_commits(&commits, head_commit_id, &pid->id,
11654 got_worktree_get_base_commit_id(worktree),
11655 got_worktree_get_path_prefix(worktree),
11656 GOT_ERR_HISTEDIT_PATH, repo);
11657 got_object_commit_close(commit);
11658 commit = NULL;
11659 if (error)
11660 goto done;
11662 if (STAILQ_EMPTY(&commits)) {
11663 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11664 goto done;
11667 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11668 &base_commit_id, &fileindex, worktree, repo);
11669 if (error)
11670 goto done;
11672 if (edit_script_path) {
11673 error = histedit_load_list(&histedit_cmds,
11674 edit_script_path, repo);
11675 if (error) {
11676 got_worktree_histedit_abort(worktree, fileindex,
11677 repo, branch, base_commit_id,
11678 abort_progress, &upa);
11679 print_merge_progress_stats(&upa);
11680 goto done;
11682 } else {
11683 const char *branch_name;
11684 branch_name = got_ref_get_symref_target(branch);
11685 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11686 branch_name += 11;
11687 error = histedit_edit_script(&histedit_cmds, &commits,
11688 branch_name, edit_logmsg_only, fold_only,
11689 edit_only, repo);
11690 if (error) {
11691 got_worktree_histedit_abort(worktree, fileindex,
11692 repo, branch, base_commit_id,
11693 abort_progress, &upa);
11694 print_merge_progress_stats(&upa);
11695 goto done;
11700 error = histedit_save_list(&histedit_cmds, worktree,
11701 repo);
11702 if (error) {
11703 got_worktree_histedit_abort(worktree, fileindex,
11704 repo, branch, base_commit_id,
11705 abort_progress, &upa);
11706 print_merge_progress_stats(&upa);
11707 goto done;
11712 error = histedit_check_script(&histedit_cmds, &commits, repo);
11713 if (error)
11714 goto done;
11716 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11717 if (resume_commit_id) {
11718 if (got_object_id_cmp(hle->commit_id,
11719 resume_commit_id) != 0)
11720 continue;
11722 resume_commit_id = NULL;
11723 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11724 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11725 error = histedit_skip_commit(hle, worktree,
11726 repo);
11727 if (error)
11728 goto done;
11729 } else {
11730 struct got_pathlist_head paths;
11731 int have_changes = 0;
11733 TAILQ_INIT(&paths);
11734 error = got_pathlist_append(&paths, "", NULL);
11735 if (error)
11736 goto done;
11737 error = got_worktree_status(worktree, &paths,
11738 repo, 0, check_local_changes, &have_changes,
11739 check_cancelled, NULL);
11740 got_pathlist_free(&paths);
11741 if (error) {
11742 if (error->code != GOT_ERR_CANCELLED)
11743 goto done;
11744 if (sigint_received || sigpipe_received)
11745 goto done;
11747 if (have_changes) {
11748 error = histedit_commit(NULL, worktree,
11749 fileindex, tmp_branch, hle,
11750 committer, repo);
11751 if (error)
11752 goto done;
11753 } else {
11754 error = got_object_open_as_commit(
11755 &commit, repo, hle->commit_id);
11756 if (error)
11757 goto done;
11758 error = show_histedit_progress(commit,
11759 hle, NULL);
11760 got_object_commit_close(commit);
11761 commit = NULL;
11762 if (error)
11763 goto done;
11766 continue;
11769 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11770 error = histedit_skip_commit(hle, worktree, repo);
11771 if (error)
11772 goto done;
11773 continue;
11776 error = got_object_open_as_commit(&commit, repo,
11777 hle->commit_id);
11778 if (error)
11779 goto done;
11780 parent_ids = got_object_commit_get_parent_ids(commit);
11781 pid = STAILQ_FIRST(parent_ids);
11783 error = got_worktree_histedit_merge_files(&merged_paths,
11784 worktree, fileindex, &pid->id, hle->commit_id, repo,
11785 update_progress, &upa, check_cancelled, NULL);
11786 if (error)
11787 goto done;
11788 got_object_commit_close(commit);
11789 commit = NULL;
11791 print_merge_progress_stats(&upa);
11792 if (upa.conflicts > 0 || upa.missing > 0 ||
11793 upa.not_deleted > 0 || upa.unversioned > 0) {
11794 if (upa.conflicts > 0) {
11795 error = show_rebase_merge_conflict(
11796 hle->commit_id, repo);
11797 if (error)
11798 goto done;
11800 got_worktree_rebase_pathlist_free(&merged_paths);
11801 break;
11804 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11805 char *id_str;
11806 error = got_object_id_str(&id_str, hle->commit_id);
11807 if (error)
11808 goto done;
11809 printf("Stopping histedit for amending commit %s\n",
11810 id_str);
11811 free(id_str);
11812 got_worktree_rebase_pathlist_free(&merged_paths);
11813 error = got_worktree_histedit_postpone(worktree,
11814 fileindex);
11815 goto done;
11818 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11819 error = histedit_skip_commit(hle, worktree, repo);
11820 if (error)
11821 goto done;
11822 continue;
11825 error = histedit_commit(&merged_paths, worktree, fileindex,
11826 tmp_branch, hle, committer, repo);
11827 got_worktree_rebase_pathlist_free(&merged_paths);
11828 if (error)
11829 goto done;
11832 if (upa.conflicts > 0 || upa.missing > 0 ||
11833 upa.not_deleted > 0 || upa.unversioned > 0) {
11834 error = got_worktree_histedit_postpone(worktree, fileindex);
11835 if (error)
11836 goto done;
11837 if (upa.conflicts > 0 && upa.missing == 0 &&
11838 upa.not_deleted == 0 && upa.unversioned == 0) {
11839 error = got_error_msg(GOT_ERR_CONFLICTS,
11840 "conflicts must be resolved before histedit "
11841 "can continue");
11842 } else if (upa.conflicts > 0) {
11843 error = got_error_msg(GOT_ERR_CONFLICTS,
11844 "conflicts must be resolved before histedit "
11845 "can continue; changes destined for some "
11846 "files were not yet merged and should be "
11847 "merged manually if required before the "
11848 "histedit operation is continued");
11849 } else {
11850 error = got_error_msg(GOT_ERR_CONFLICTS,
11851 "changes destined for some files were not "
11852 "yet merged and should be merged manually "
11853 "if required before the histedit operation "
11854 "is continued");
11856 } else
11857 error = histedit_complete(worktree, fileindex, tmp_branch,
11858 branch, repo);
11859 done:
11860 free(cwd);
11861 free(committer);
11862 free(gitconfig_path);
11863 got_object_id_queue_free(&commits);
11864 histedit_free_list(&histedit_cmds);
11865 free(head_commit_id);
11866 free(base_commit_id);
11867 free(resume_commit_id);
11868 if (commit)
11869 got_object_commit_close(commit);
11870 if (branch)
11871 got_ref_close(branch);
11872 if (tmp_branch)
11873 got_ref_close(tmp_branch);
11874 if (worktree)
11875 got_worktree_close(worktree);
11876 if (repo) {
11877 const struct got_error *close_err = got_repo_close(repo);
11878 if (error == NULL)
11879 error = close_err;
11881 if (pack_fds) {
11882 const struct got_error *pack_err =
11883 got_repo_pack_fds_close(pack_fds);
11884 if (error == NULL)
11885 error = pack_err;
11887 return error;
11890 __dead static void
11891 usage_integrate(void)
11893 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11894 exit(1);
11897 static const struct got_error *
11898 cmd_integrate(int argc, char *argv[])
11900 const struct got_error *error = NULL;
11901 struct got_repository *repo = NULL;
11902 struct got_worktree *worktree = NULL;
11903 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11904 const char *branch_arg = NULL;
11905 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11906 struct got_fileindex *fileindex = NULL;
11907 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11908 int ch;
11909 struct got_update_progress_arg upa;
11910 int *pack_fds = NULL;
11912 while ((ch = getopt(argc, argv, "")) != -1) {
11913 switch (ch) {
11914 default:
11915 usage_integrate();
11916 /* NOTREACHED */
11920 argc -= optind;
11921 argv += optind;
11923 if (argc != 1)
11924 usage_integrate();
11925 branch_arg = argv[0];
11926 #ifndef PROFILE
11927 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11928 "unveil", NULL) == -1)
11929 err(1, "pledge");
11930 #endif
11931 cwd = getcwd(NULL, 0);
11932 if (cwd == NULL) {
11933 error = got_error_from_errno("getcwd");
11934 goto done;
11937 error = got_repo_pack_fds_open(&pack_fds);
11938 if (error != NULL)
11939 goto done;
11941 error = got_worktree_open(&worktree, cwd);
11942 if (error) {
11943 if (error->code == GOT_ERR_NOT_WORKTREE)
11944 error = wrap_not_worktree_error(error, "integrate",
11945 cwd);
11946 goto done;
11949 error = check_rebase_or_histedit_in_progress(worktree);
11950 if (error)
11951 goto done;
11953 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11954 NULL, pack_fds);
11955 if (error != NULL)
11956 goto done;
11958 error = apply_unveil(got_repo_get_path(repo), 0,
11959 got_worktree_get_root_path(worktree));
11960 if (error)
11961 goto done;
11963 error = check_merge_in_progress(worktree, repo);
11964 if (error)
11965 goto done;
11967 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11968 error = got_error_from_errno("asprintf");
11969 goto done;
11972 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11973 &base_branch_ref, worktree, refname, repo);
11974 if (error)
11975 goto done;
11977 refname = strdup(got_ref_get_name(branch_ref));
11978 if (refname == NULL) {
11979 error = got_error_from_errno("strdup");
11980 got_worktree_integrate_abort(worktree, fileindex, repo,
11981 branch_ref, base_branch_ref);
11982 goto done;
11984 base_refname = strdup(got_ref_get_name(base_branch_ref));
11985 if (base_refname == NULL) {
11986 error = got_error_from_errno("strdup");
11987 got_worktree_integrate_abort(worktree, fileindex, repo,
11988 branch_ref, base_branch_ref);
11989 goto done;
11991 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
11992 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
11993 got_worktree_integrate_abort(worktree, fileindex, repo,
11994 branch_ref, base_branch_ref);
11995 goto done;
11998 error = got_ref_resolve(&commit_id, repo, branch_ref);
11999 if (error)
12000 goto done;
12002 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12003 if (error)
12004 goto done;
12006 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12007 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12008 "specified branch has already been integrated");
12009 got_worktree_integrate_abort(worktree, fileindex, repo,
12010 branch_ref, base_branch_ref);
12011 goto done;
12014 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12015 if (error) {
12016 if (error->code == GOT_ERR_ANCESTRY)
12017 error = got_error(GOT_ERR_REBASE_REQUIRED);
12018 got_worktree_integrate_abort(worktree, fileindex, repo,
12019 branch_ref, base_branch_ref);
12020 goto done;
12023 memset(&upa, 0, sizeof(upa));
12024 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12025 branch_ref, base_branch_ref, update_progress, &upa,
12026 check_cancelled, NULL);
12027 if (error)
12028 goto done;
12030 printf("Integrated %s into %s\n", refname, base_refname);
12031 print_update_progress_stats(&upa);
12032 done:
12033 if (repo) {
12034 const struct got_error *close_err = got_repo_close(repo);
12035 if (error == NULL)
12036 error = close_err;
12038 if (worktree)
12039 got_worktree_close(worktree);
12040 if (pack_fds) {
12041 const struct got_error *pack_err =
12042 got_repo_pack_fds_close(pack_fds);
12043 if (error == NULL)
12044 error = pack_err;
12046 free(cwd);
12047 free(base_commit_id);
12048 free(commit_id);
12049 free(refname);
12050 free(base_refname);
12051 return error;
12054 __dead static void
12055 usage_merge(void)
12057 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12058 exit(1);
12061 static const struct got_error *
12062 cmd_merge(int argc, char *argv[])
12064 const struct got_error *error = NULL;
12065 struct got_worktree *worktree = NULL;
12066 struct got_repository *repo = NULL;
12067 struct got_fileindex *fileindex = NULL;
12068 char *cwd = NULL, *id_str = NULL, *author = NULL;
12069 struct got_reference *branch = NULL, *wt_branch = NULL;
12070 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12071 struct got_object_id *wt_branch_tip = NULL;
12072 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12073 int interrupt_merge = 0;
12074 struct got_update_progress_arg upa;
12075 struct got_object_id *merge_commit_id = NULL;
12076 char *branch_name = NULL;
12077 int *pack_fds = NULL;
12079 memset(&upa, 0, sizeof(upa));
12081 while ((ch = getopt(argc, argv, "acn")) != -1) {
12082 switch (ch) {
12083 case 'a':
12084 abort_merge = 1;
12085 break;
12086 case 'c':
12087 continue_merge = 1;
12088 break;
12089 case 'n':
12090 interrupt_merge = 1;
12091 break;
12092 default:
12093 usage_rebase();
12094 /* NOTREACHED */
12098 argc -= optind;
12099 argv += optind;
12101 #ifndef PROFILE
12102 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12103 "unveil", NULL) == -1)
12104 err(1, "pledge");
12105 #endif
12107 if (abort_merge && continue_merge)
12108 option_conflict('a', 'c');
12109 if (abort_merge || continue_merge) {
12110 if (argc != 0)
12111 usage_merge();
12112 } else if (argc != 1)
12113 usage_merge();
12115 cwd = getcwd(NULL, 0);
12116 if (cwd == NULL) {
12117 error = got_error_from_errno("getcwd");
12118 goto done;
12121 error = got_repo_pack_fds_open(&pack_fds);
12122 if (error != NULL)
12123 goto done;
12125 error = got_worktree_open(&worktree, cwd);
12126 if (error) {
12127 if (error->code == GOT_ERR_NOT_WORKTREE)
12128 error = wrap_not_worktree_error(error,
12129 "merge", cwd);
12130 goto done;
12133 error = got_repo_open(&repo,
12134 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12135 pack_fds);
12136 if (error != NULL)
12137 goto done;
12139 error = apply_unveil(got_repo_get_path(repo), 0,
12140 worktree ? got_worktree_get_root_path(worktree) : NULL);
12141 if (error)
12142 goto done;
12144 error = check_rebase_or_histedit_in_progress(worktree);
12145 if (error)
12146 goto done;
12148 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12149 repo);
12150 if (error)
12151 goto done;
12153 if (abort_merge) {
12154 if (!merge_in_progress) {
12155 error = got_error(GOT_ERR_NOT_MERGING);
12156 goto done;
12158 error = got_worktree_merge_continue(&branch_name,
12159 &branch_tip, &fileindex, worktree, repo);
12160 if (error)
12161 goto done;
12162 error = got_worktree_merge_abort(worktree, fileindex, repo,
12163 abort_progress, &upa);
12164 if (error)
12165 goto done;
12166 printf("Merge of %s aborted\n", branch_name);
12167 goto done; /* nothing else to do */
12170 error = get_author(&author, repo, worktree);
12171 if (error)
12172 goto done;
12174 if (continue_merge) {
12175 if (!merge_in_progress) {
12176 error = got_error(GOT_ERR_NOT_MERGING);
12177 goto done;
12179 error = got_worktree_merge_continue(&branch_name,
12180 &branch_tip, &fileindex, worktree, repo);
12181 if (error)
12182 goto done;
12183 } else {
12184 error = got_ref_open(&branch, repo, argv[0], 0);
12185 if (error != NULL)
12186 goto done;
12187 branch_name = strdup(got_ref_get_name(branch));
12188 if (branch_name == NULL) {
12189 error = got_error_from_errno("strdup");
12190 goto done;
12192 error = got_ref_resolve(&branch_tip, repo, branch);
12193 if (error)
12194 goto done;
12197 error = got_ref_open(&wt_branch, repo,
12198 got_worktree_get_head_ref_name(worktree), 0);
12199 if (error)
12200 goto done;
12201 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12202 if (error)
12203 goto done;
12204 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12205 wt_branch_tip, branch_tip, 0, repo,
12206 check_cancelled, NULL);
12207 if (error && error->code != GOT_ERR_ANCESTRY)
12208 goto done;
12210 if (!continue_merge) {
12211 error = check_path_prefix(wt_branch_tip, branch_tip,
12212 got_worktree_get_path_prefix(worktree),
12213 GOT_ERR_MERGE_PATH, repo);
12214 if (error)
12215 goto done;
12216 if (yca_id) {
12217 error = check_same_branch(wt_branch_tip, branch,
12218 yca_id, repo);
12219 if (error) {
12220 if (error->code != GOT_ERR_ANCESTRY)
12221 goto done;
12222 error = NULL;
12223 } else {
12224 static char msg[512];
12225 snprintf(msg, sizeof(msg),
12226 "cannot create a merge commit because "
12227 "%s is based on %s; %s can be integrated "
12228 "with 'got integrate' instead", branch_name,
12229 got_worktree_get_head_ref_name(worktree),
12230 branch_name);
12231 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12232 goto done;
12235 error = got_worktree_merge_prepare(&fileindex, worktree,
12236 branch, repo);
12237 if (error)
12238 goto done;
12240 error = got_worktree_merge_branch(worktree, fileindex,
12241 yca_id, branch_tip, repo, update_progress, &upa,
12242 check_cancelled, NULL);
12243 if (error)
12244 goto done;
12245 print_merge_progress_stats(&upa);
12246 if (!upa.did_something) {
12247 error = got_worktree_merge_abort(worktree, fileindex,
12248 repo, abort_progress, &upa);
12249 if (error)
12250 goto done;
12251 printf("Already up-to-date\n");
12252 goto done;
12256 if (interrupt_merge) {
12257 error = got_worktree_merge_postpone(worktree, fileindex);
12258 if (error)
12259 goto done;
12260 printf("Merge of %s interrupted on request\n", branch_name);
12261 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12262 upa.not_deleted > 0 || upa.unversioned > 0) {
12263 error = got_worktree_merge_postpone(worktree, fileindex);
12264 if (error)
12265 goto done;
12266 if (upa.conflicts > 0 && upa.missing == 0 &&
12267 upa.not_deleted == 0 && upa.unversioned == 0) {
12268 error = got_error_msg(GOT_ERR_CONFLICTS,
12269 "conflicts must be resolved before merging "
12270 "can continue");
12271 } else if (upa.conflicts > 0) {
12272 error = got_error_msg(GOT_ERR_CONFLICTS,
12273 "conflicts must be resolved before merging "
12274 "can continue; changes destined for some "
12275 "files were not yet merged and "
12276 "should be merged manually if required before the "
12277 "merge operation is continued");
12278 } else {
12279 error = got_error_msg(GOT_ERR_CONFLICTS,
12280 "changes destined for some "
12281 "files were not yet merged and should be "
12282 "merged manually if required before the "
12283 "merge operation is continued");
12285 goto done;
12286 } else {
12287 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12288 fileindex, author, NULL, 1, branch_tip, branch_name,
12289 repo, continue_merge ? print_status : NULL, NULL);
12290 if (error)
12291 goto done;
12292 error = got_worktree_merge_complete(worktree, fileindex, repo);
12293 if (error)
12294 goto done;
12295 error = got_object_id_str(&id_str, merge_commit_id);
12296 if (error)
12297 goto done;
12298 printf("Merged %s into %s: %s\n", branch_name,
12299 got_worktree_get_head_ref_name(worktree),
12300 id_str);
12303 done:
12304 free(id_str);
12305 free(merge_commit_id);
12306 free(author);
12307 free(branch_tip);
12308 free(branch_name);
12309 free(yca_id);
12310 if (branch)
12311 got_ref_close(branch);
12312 if (wt_branch)
12313 got_ref_close(wt_branch);
12314 if (worktree)
12315 got_worktree_close(worktree);
12316 if (repo) {
12317 const struct got_error *close_err = got_repo_close(repo);
12318 if (error == NULL)
12319 error = close_err;
12321 if (pack_fds) {
12322 const struct got_error *pack_err =
12323 got_repo_pack_fds_close(pack_fds);
12324 if (error == NULL)
12325 error = pack_err;
12327 return error;
12330 __dead static void
12331 usage_stage(void)
12333 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12334 "[path ...]\n", getprogname());
12335 exit(1);
12338 static const struct got_error *
12339 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12340 const char *path, struct got_object_id *blob_id,
12341 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12342 int dirfd, const char *de_name)
12344 const struct got_error *err = NULL;
12345 char *id_str = NULL;
12347 if (staged_status != GOT_STATUS_ADD &&
12348 staged_status != GOT_STATUS_MODIFY &&
12349 staged_status != GOT_STATUS_DELETE)
12350 return NULL;
12352 if (staged_status == GOT_STATUS_ADD ||
12353 staged_status == GOT_STATUS_MODIFY)
12354 err = got_object_id_str(&id_str, staged_blob_id);
12355 else
12356 err = got_object_id_str(&id_str, blob_id);
12357 if (err)
12358 return err;
12360 printf("%s %c %s\n", id_str, staged_status, path);
12361 free(id_str);
12362 return NULL;
12365 static const struct got_error *
12366 cmd_stage(int argc, char *argv[])
12368 const struct got_error *error = NULL;
12369 struct got_repository *repo = NULL;
12370 struct got_worktree *worktree = NULL;
12371 char *cwd = NULL;
12372 struct got_pathlist_head paths;
12373 struct got_pathlist_entry *pe;
12374 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12375 FILE *patch_script_file = NULL;
12376 const char *patch_script_path = NULL;
12377 struct choose_patch_arg cpa;
12378 int *pack_fds = NULL;
12380 TAILQ_INIT(&paths);
12382 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12383 switch (ch) {
12384 case 'F':
12385 patch_script_path = optarg;
12386 break;
12387 case 'l':
12388 list_stage = 1;
12389 break;
12390 case 'p':
12391 pflag = 1;
12392 break;
12393 case 'S':
12394 allow_bad_symlinks = 1;
12395 break;
12396 default:
12397 usage_stage();
12398 /* NOTREACHED */
12402 argc -= optind;
12403 argv += optind;
12405 #ifndef PROFILE
12406 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12407 "unveil", NULL) == -1)
12408 err(1, "pledge");
12409 #endif
12410 if (list_stage && (pflag || patch_script_path))
12411 errx(1, "-l option cannot be used with other options");
12412 if (patch_script_path && !pflag)
12413 errx(1, "-F option can only be used together with -p option");
12415 cwd = getcwd(NULL, 0);
12416 if (cwd == NULL) {
12417 error = got_error_from_errno("getcwd");
12418 goto done;
12421 error = got_repo_pack_fds_open(&pack_fds);
12422 if (error != NULL)
12423 goto done;
12425 error = got_worktree_open(&worktree, cwd);
12426 if (error) {
12427 if (error->code == GOT_ERR_NOT_WORKTREE)
12428 error = wrap_not_worktree_error(error, "stage", cwd);
12429 goto done;
12432 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12433 NULL, pack_fds);
12434 if (error != NULL)
12435 goto done;
12437 if (patch_script_path) {
12438 patch_script_file = fopen(patch_script_path, "re");
12439 if (patch_script_file == NULL) {
12440 error = got_error_from_errno2("fopen",
12441 patch_script_path);
12442 goto done;
12445 error = apply_unveil(got_repo_get_path(repo), 0,
12446 got_worktree_get_root_path(worktree));
12447 if (error)
12448 goto done;
12450 error = check_merge_in_progress(worktree, repo);
12451 if (error)
12452 goto done;
12454 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12455 if (error)
12456 goto done;
12458 if (list_stage)
12459 error = got_worktree_status(worktree, &paths, repo, 0,
12460 print_stage, NULL, check_cancelled, NULL);
12461 else {
12462 cpa.patch_script_file = patch_script_file;
12463 cpa.action = "stage";
12464 error = got_worktree_stage(worktree, &paths,
12465 pflag ? NULL : print_status, NULL,
12466 pflag ? choose_patch : NULL, &cpa,
12467 allow_bad_symlinks, repo);
12469 done:
12470 if (patch_script_file && fclose(patch_script_file) == EOF &&
12471 error == NULL)
12472 error = got_error_from_errno2("fclose", patch_script_path);
12473 if (repo) {
12474 const struct got_error *close_err = got_repo_close(repo);
12475 if (error == NULL)
12476 error = close_err;
12478 if (worktree)
12479 got_worktree_close(worktree);
12480 if (pack_fds) {
12481 const struct got_error *pack_err =
12482 got_repo_pack_fds_close(pack_fds);
12483 if (error == NULL)
12484 error = pack_err;
12486 TAILQ_FOREACH(pe, &paths, entry)
12487 free((char *)pe->path);
12488 got_pathlist_free(&paths);
12489 free(cwd);
12490 return error;
12493 __dead static void
12494 usage_unstage(void)
12496 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12497 "[path ...]\n", getprogname());
12498 exit(1);
12502 static const struct got_error *
12503 cmd_unstage(int argc, char *argv[])
12505 const struct got_error *error = NULL;
12506 struct got_repository *repo = NULL;
12507 struct got_worktree *worktree = NULL;
12508 char *cwd = NULL;
12509 struct got_pathlist_head paths;
12510 struct got_pathlist_entry *pe;
12511 int ch, pflag = 0;
12512 struct got_update_progress_arg upa;
12513 FILE *patch_script_file = NULL;
12514 const char *patch_script_path = NULL;
12515 struct choose_patch_arg cpa;
12516 int *pack_fds = NULL;
12518 TAILQ_INIT(&paths);
12520 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12521 switch (ch) {
12522 case 'F':
12523 patch_script_path = optarg;
12524 break;
12525 case 'p':
12526 pflag = 1;
12527 break;
12528 default:
12529 usage_unstage();
12530 /* NOTREACHED */
12534 argc -= optind;
12535 argv += optind;
12537 #ifndef PROFILE
12538 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12539 "unveil", NULL) == -1)
12540 err(1, "pledge");
12541 #endif
12542 if (patch_script_path && !pflag)
12543 errx(1, "-F option can only be used together with -p option");
12545 cwd = getcwd(NULL, 0);
12546 if (cwd == NULL) {
12547 error = got_error_from_errno("getcwd");
12548 goto done;
12551 error = got_repo_pack_fds_open(&pack_fds);
12552 if (error != NULL)
12553 goto done;
12555 error = got_worktree_open(&worktree, cwd);
12556 if (error) {
12557 if (error->code == GOT_ERR_NOT_WORKTREE)
12558 error = wrap_not_worktree_error(error, "unstage", cwd);
12559 goto done;
12562 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12563 NULL, pack_fds);
12564 if (error != NULL)
12565 goto done;
12567 if (patch_script_path) {
12568 patch_script_file = fopen(patch_script_path, "re");
12569 if (patch_script_file == NULL) {
12570 error = got_error_from_errno2("fopen",
12571 patch_script_path);
12572 goto done;
12576 error = apply_unveil(got_repo_get_path(repo), 0,
12577 got_worktree_get_root_path(worktree));
12578 if (error)
12579 goto done;
12581 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12582 if (error)
12583 goto done;
12585 cpa.patch_script_file = patch_script_file;
12586 cpa.action = "unstage";
12587 memset(&upa, 0, sizeof(upa));
12588 error = got_worktree_unstage(worktree, &paths, update_progress,
12589 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12590 if (!error)
12591 print_merge_progress_stats(&upa);
12592 done:
12593 if (patch_script_file && fclose(patch_script_file) == EOF &&
12594 error == NULL)
12595 error = got_error_from_errno2("fclose", patch_script_path);
12596 if (repo) {
12597 const struct got_error *close_err = got_repo_close(repo);
12598 if (error == NULL)
12599 error = close_err;
12601 if (worktree)
12602 got_worktree_close(worktree);
12603 if (pack_fds) {
12604 const struct got_error *pack_err =
12605 got_repo_pack_fds_close(pack_fds);
12606 if (error == NULL)
12607 error = pack_err;
12609 TAILQ_FOREACH(pe, &paths, entry)
12610 free((char *)pe->path);
12611 got_pathlist_free(&paths);
12612 free(cwd);
12613 return error;
12616 __dead static void
12617 usage_cat(void)
12619 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12620 "arg ...\n", getprogname());
12621 exit(1);
12624 static const struct got_error *
12625 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12627 const struct got_error *err;
12628 struct got_blob_object *blob;
12629 int fd = -1;
12631 fd = got_opentempfd();
12632 if (fd == -1)
12633 return got_error_from_errno("got_opentempfd");
12635 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12636 if (err)
12637 goto done;
12639 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12640 done:
12641 if (fd != -1 && close(fd) == -1 && err == NULL)
12642 err = got_error_from_errno("close");
12643 if (blob)
12644 got_object_blob_close(blob);
12645 return err;
12648 static const struct got_error *
12649 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12651 const struct got_error *err;
12652 struct got_tree_object *tree;
12653 int nentries, i;
12655 err = got_object_open_as_tree(&tree, repo, id);
12656 if (err)
12657 return err;
12659 nentries = got_object_tree_get_nentries(tree);
12660 for (i = 0; i < nentries; i++) {
12661 struct got_tree_entry *te;
12662 char *id_str;
12663 if (sigint_received || sigpipe_received)
12664 break;
12665 te = got_object_tree_get_entry(tree, i);
12666 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12667 if (err)
12668 break;
12669 fprintf(outfile, "%s %.7o %s\n", id_str,
12670 got_tree_entry_get_mode(te),
12671 got_tree_entry_get_name(te));
12672 free(id_str);
12675 got_object_tree_close(tree);
12676 return err;
12679 static const struct got_error *
12680 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12682 const struct got_error *err;
12683 struct got_commit_object *commit;
12684 const struct got_object_id_queue *parent_ids;
12685 struct got_object_qid *pid;
12686 char *id_str = NULL;
12687 const char *logmsg = NULL;
12688 char gmtoff[6];
12690 err = got_object_open_as_commit(&commit, repo, id);
12691 if (err)
12692 return err;
12694 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12695 if (err)
12696 goto done;
12698 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12699 parent_ids = got_object_commit_get_parent_ids(commit);
12700 fprintf(outfile, "numparents %d\n",
12701 got_object_commit_get_nparents(commit));
12702 STAILQ_FOREACH(pid, parent_ids, entry) {
12703 char *pid_str;
12704 err = got_object_id_str(&pid_str, &pid->id);
12705 if (err)
12706 goto done;
12707 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12708 free(pid_str);
12710 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12711 got_object_commit_get_author_gmtoff(commit));
12712 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12713 got_object_commit_get_author(commit),
12714 (long long)got_object_commit_get_author_time(commit),
12715 gmtoff);
12717 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12718 got_object_commit_get_committer_gmtoff(commit));
12719 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12720 got_object_commit_get_committer(commit),
12721 (long long)got_object_commit_get_committer_time(commit),
12722 gmtoff);
12724 logmsg = got_object_commit_get_logmsg_raw(commit);
12725 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12726 fprintf(outfile, "%s", logmsg);
12727 done:
12728 free(id_str);
12729 got_object_commit_close(commit);
12730 return err;
12733 static const struct got_error *
12734 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12736 const struct got_error *err;
12737 struct got_tag_object *tag;
12738 char *id_str = NULL;
12739 const char *tagmsg = NULL;
12740 char gmtoff[6];
12742 err = got_object_open_as_tag(&tag, repo, id);
12743 if (err)
12744 return err;
12746 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12747 if (err)
12748 goto done;
12750 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12752 switch (got_object_tag_get_object_type(tag)) {
12753 case GOT_OBJ_TYPE_BLOB:
12754 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12755 GOT_OBJ_LABEL_BLOB);
12756 break;
12757 case GOT_OBJ_TYPE_TREE:
12758 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12759 GOT_OBJ_LABEL_TREE);
12760 break;
12761 case GOT_OBJ_TYPE_COMMIT:
12762 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12763 GOT_OBJ_LABEL_COMMIT);
12764 break;
12765 case GOT_OBJ_TYPE_TAG:
12766 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12767 GOT_OBJ_LABEL_TAG);
12768 break;
12769 default:
12770 break;
12773 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12774 got_object_tag_get_name(tag));
12776 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12777 got_object_tag_get_tagger_gmtoff(tag));
12778 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12779 got_object_tag_get_tagger(tag),
12780 (long long)got_object_tag_get_tagger_time(tag),
12781 gmtoff);
12783 tagmsg = got_object_tag_get_message(tag);
12784 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12785 fprintf(outfile, "%s", tagmsg);
12786 done:
12787 free(id_str);
12788 got_object_tag_close(tag);
12789 return err;
12792 static const struct got_error *
12793 cmd_cat(int argc, char *argv[])
12795 const struct got_error *error;
12796 struct got_repository *repo = NULL;
12797 struct got_worktree *worktree = NULL;
12798 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12799 const char *commit_id_str = NULL;
12800 struct got_object_id *id = NULL, *commit_id = NULL;
12801 struct got_commit_object *commit = NULL;
12802 int ch, obj_type, i, force_path = 0;
12803 struct got_reflist_head refs;
12804 int *pack_fds = NULL;
12806 TAILQ_INIT(&refs);
12808 #ifndef PROFILE
12809 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12810 NULL) == -1)
12811 err(1, "pledge");
12812 #endif
12814 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12815 switch (ch) {
12816 case 'c':
12817 commit_id_str = optarg;
12818 break;
12819 case 'P':
12820 force_path = 1;
12821 break;
12822 case 'r':
12823 repo_path = realpath(optarg, NULL);
12824 if (repo_path == NULL)
12825 return got_error_from_errno2("realpath",
12826 optarg);
12827 got_path_strip_trailing_slashes(repo_path);
12828 break;
12829 default:
12830 usage_cat();
12831 /* NOTREACHED */
12835 argc -= optind;
12836 argv += optind;
12838 cwd = getcwd(NULL, 0);
12839 if (cwd == NULL) {
12840 error = got_error_from_errno("getcwd");
12841 goto done;
12844 error = got_repo_pack_fds_open(&pack_fds);
12845 if (error != NULL)
12846 goto done;
12848 if (repo_path == NULL) {
12849 error = got_worktree_open(&worktree, cwd);
12850 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12851 goto done;
12852 if (worktree) {
12853 repo_path = strdup(
12854 got_worktree_get_repo_path(worktree));
12855 if (repo_path == NULL) {
12856 error = got_error_from_errno("strdup");
12857 goto done;
12860 /* Release work tree lock. */
12861 got_worktree_close(worktree);
12862 worktree = NULL;
12866 if (repo_path == NULL) {
12867 repo_path = strdup(cwd);
12868 if (repo_path == NULL)
12869 return got_error_from_errno("strdup");
12872 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12873 free(repo_path);
12874 if (error != NULL)
12875 goto done;
12877 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12878 if (error)
12879 goto done;
12881 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12882 if (error)
12883 goto done;
12885 if (commit_id_str == NULL)
12886 commit_id_str = GOT_REF_HEAD;
12887 error = got_repo_match_object_id(&commit_id, NULL,
12888 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12889 if (error)
12890 goto done;
12892 error = got_object_open_as_commit(&commit, repo, commit_id);
12893 if (error)
12894 goto done;
12896 for (i = 0; i < argc; i++) {
12897 if (force_path) {
12898 error = got_object_id_by_path(&id, repo, commit,
12899 argv[i]);
12900 if (error)
12901 break;
12902 } else {
12903 error = got_repo_match_object_id(&id, &label, argv[i],
12904 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12905 repo);
12906 if (error) {
12907 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12908 error->code != GOT_ERR_NOT_REF)
12909 break;
12910 error = got_object_id_by_path(&id, repo,
12911 commit, argv[i]);
12912 if (error)
12913 break;
12917 error = got_object_get_type(&obj_type, repo, id);
12918 if (error)
12919 break;
12921 switch (obj_type) {
12922 case GOT_OBJ_TYPE_BLOB:
12923 error = cat_blob(id, repo, stdout);
12924 break;
12925 case GOT_OBJ_TYPE_TREE:
12926 error = cat_tree(id, repo, stdout);
12927 break;
12928 case GOT_OBJ_TYPE_COMMIT:
12929 error = cat_commit(id, repo, stdout);
12930 break;
12931 case GOT_OBJ_TYPE_TAG:
12932 error = cat_tag(id, repo, stdout);
12933 break;
12934 default:
12935 error = got_error(GOT_ERR_OBJ_TYPE);
12936 break;
12938 if (error)
12939 break;
12940 free(label);
12941 label = NULL;
12942 free(id);
12943 id = NULL;
12945 done:
12946 free(label);
12947 free(id);
12948 free(commit_id);
12949 if (commit)
12950 got_object_commit_close(commit);
12951 if (worktree)
12952 got_worktree_close(worktree);
12953 if (repo) {
12954 const struct got_error *close_err = got_repo_close(repo);
12955 if (error == NULL)
12956 error = close_err;
12958 if (pack_fds) {
12959 const struct got_error *pack_err =
12960 got_repo_pack_fds_close(pack_fds);
12961 if (error == NULL)
12962 error = pack_err;
12965 got_ref_list_free(&refs);
12966 return error;
12969 __dead static void
12970 usage_info(void)
12972 fprintf(stderr, "usage: %s info [path ...]\n",
12973 getprogname());
12974 exit(1);
12977 static const struct got_error *
12978 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12979 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12980 struct got_object_id *commit_id)
12982 const struct got_error *err = NULL;
12983 char *id_str = NULL;
12984 char datebuf[128];
12985 struct tm mytm, *tm;
12986 struct got_pathlist_head *paths = arg;
12987 struct got_pathlist_entry *pe;
12990 * Clear error indication from any of the path arguments which
12991 * would cause this file index entry to be displayed.
12993 TAILQ_FOREACH(pe, paths, entry) {
12994 if (got_path_cmp(path, pe->path, strlen(path),
12995 pe->path_len) == 0 ||
12996 got_path_is_child(path, pe->path, pe->path_len))
12997 pe->data = NULL; /* no error */
13000 printf(GOT_COMMIT_SEP_STR);
13001 if (S_ISLNK(mode))
13002 printf("symlink: %s\n", path);
13003 else if (S_ISREG(mode)) {
13004 printf("file: %s\n", path);
13005 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13006 } else if (S_ISDIR(mode))
13007 printf("directory: %s\n", path);
13008 else
13009 printf("something: %s\n", path);
13011 tm = localtime_r(&mtime, &mytm);
13012 if (tm == NULL)
13013 return NULL;
13014 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13015 return got_error(GOT_ERR_NO_SPACE);
13016 printf("timestamp: %s\n", datebuf);
13018 if (blob_id) {
13019 err = got_object_id_str(&id_str, blob_id);
13020 if (err)
13021 return err;
13022 printf("based on blob: %s\n", id_str);
13023 free(id_str);
13026 if (staged_blob_id) {
13027 err = got_object_id_str(&id_str, staged_blob_id);
13028 if (err)
13029 return err;
13030 printf("based on staged blob: %s\n", id_str);
13031 free(id_str);
13034 if (commit_id) {
13035 err = got_object_id_str(&id_str, commit_id);
13036 if (err)
13037 return err;
13038 printf("based on commit: %s\n", id_str);
13039 free(id_str);
13042 return NULL;
13045 static const struct got_error *
13046 cmd_info(int argc, char *argv[])
13048 const struct got_error *error = NULL;
13049 struct got_worktree *worktree = NULL;
13050 char *cwd = NULL, *id_str = NULL;
13051 struct got_pathlist_head paths;
13052 struct got_pathlist_entry *pe;
13053 char *uuidstr = NULL;
13054 int ch, show_files = 0;
13056 TAILQ_INIT(&paths);
13058 while ((ch = getopt(argc, argv, "")) != -1) {
13059 switch (ch) {
13060 default:
13061 usage_info();
13062 /* NOTREACHED */
13066 argc -= optind;
13067 argv += optind;
13069 #ifndef PROFILE
13070 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13071 NULL) == -1)
13072 err(1, "pledge");
13073 #endif
13074 cwd = getcwd(NULL, 0);
13075 if (cwd == NULL) {
13076 error = got_error_from_errno("getcwd");
13077 goto done;
13080 error = got_worktree_open(&worktree, cwd);
13081 if (error) {
13082 if (error->code == GOT_ERR_NOT_WORKTREE)
13083 error = wrap_not_worktree_error(error, "info", cwd);
13084 goto done;
13087 #ifndef PROFILE
13088 /* Remove "wpath cpath proc exec sendfd" promises. */
13089 if (pledge("stdio rpath flock unveil", NULL) == -1)
13090 err(1, "pledge");
13091 #endif
13092 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13093 if (error)
13094 goto done;
13096 if (argc >= 1) {
13097 error = get_worktree_paths_from_argv(&paths, argc, argv,
13098 worktree);
13099 if (error)
13100 goto done;
13101 show_files = 1;
13104 error = got_object_id_str(&id_str,
13105 got_worktree_get_base_commit_id(worktree));
13106 if (error)
13107 goto done;
13109 error = got_worktree_get_uuid(&uuidstr, worktree);
13110 if (error)
13111 goto done;
13113 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13114 printf("work tree base commit: %s\n", id_str);
13115 printf("work tree path prefix: %s\n",
13116 got_worktree_get_path_prefix(worktree));
13117 printf("work tree branch reference: %s\n",
13118 got_worktree_get_head_ref_name(worktree));
13119 printf("work tree UUID: %s\n", uuidstr);
13120 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13122 if (show_files) {
13123 struct got_pathlist_entry *pe;
13124 TAILQ_FOREACH(pe, &paths, entry) {
13125 if (pe->path_len == 0)
13126 continue;
13128 * Assume this path will fail. This will be corrected
13129 * in print_path_info() in case the path does suceeed.
13131 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13133 error = got_worktree_path_info(worktree, &paths,
13134 print_path_info, &paths, check_cancelled, NULL);
13135 if (error)
13136 goto done;
13137 TAILQ_FOREACH(pe, &paths, entry) {
13138 if (pe->data != NULL) {
13139 const struct got_error *perr;
13141 perr = pe->data;
13142 error = got_error_fmt(perr->code, "%s",
13143 pe->path);
13144 break;
13148 done:
13149 if (worktree)
13150 got_worktree_close(worktree);
13151 TAILQ_FOREACH(pe, &paths, entry)
13152 free((char *)pe->path);
13153 got_pathlist_free(&paths);
13154 free(cwd);
13155 free(id_str);
13156 free(uuidstr);
13157 return error;