Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] 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++ != '<')
566 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
567 while (*author && *author != '\n' && *author != '<' && *author != '>')
568 author++;
569 if (strcmp(author, ">") != 0)
570 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
571 return NULL;
574 static const struct got_error *
575 get_author(char **author, struct got_repository *repo,
576 struct got_worktree *worktree)
578 const struct got_error *err = NULL;
579 const char *got_author = NULL, *name, *email;
580 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
582 *author = NULL;
584 if (worktree)
585 worktree_conf = got_worktree_get_gotconfig(worktree);
586 repo_conf = got_repo_get_gotconfig(repo);
588 /*
589 * Priority of potential author information sources, from most
590 * significant to least significant:
591 * 1) work tree's .got/got.conf file
592 * 2) repository's got.conf file
593 * 3) repository's git config file
594 * 4) environment variables
595 * 5) global git config files (in user's home directory or /etc)
596 */
598 if (worktree_conf)
599 got_author = got_gotconfig_get_author(worktree_conf);
600 if (got_author == NULL)
601 got_author = got_gotconfig_get_author(repo_conf);
602 if (got_author == NULL) {
603 name = got_repo_get_gitconfig_author_name(repo);
604 email = got_repo_get_gitconfig_author_email(repo);
605 if (name && email) {
606 if (asprintf(author, "%s <%s>", name, email) == -1)
607 return got_error_from_errno("asprintf");
608 return NULL;
611 got_author = getenv("GOT_AUTHOR");
612 if (got_author == NULL) {
613 name = got_repo_get_global_gitconfig_author_name(repo);
614 email = got_repo_get_global_gitconfig_author_email(
615 repo);
616 if (name && email) {
617 if (asprintf(author, "%s <%s>", name, email)
618 == -1)
619 return got_error_from_errno("asprintf");
620 return NULL;
622 /* TODO: Look up user in password database? */
623 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
627 *author = strdup(got_author);
628 if (*author == NULL)
629 return got_error_from_errno("strdup");
631 err = valid_author(*author);
632 if (err) {
633 free(*author);
634 *author = NULL;
636 return err;
639 static const struct got_error *
640 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
641 struct got_worktree *worktree)
643 const char *got_allowed_signers = NULL;
644 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
646 *allowed_signers = NULL;
648 if (worktree)
649 worktree_conf = got_worktree_get_gotconfig(worktree);
650 repo_conf = got_repo_get_gotconfig(repo);
652 /*
653 * Priority of potential author information sources, from most
654 * significant to least significant:
655 * 1) work tree's .got/got.conf file
656 * 2) repository's got.conf file
657 */
659 if (worktree_conf)
660 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
661 worktree_conf);
662 if (got_allowed_signers == NULL)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 repo_conf);
666 if (got_allowed_signers) {
667 *allowed_signers = strdup(got_allowed_signers);
668 if (*allowed_signers == NULL)
669 return got_error_from_errno("strdup");
671 return NULL;
674 static const struct got_error *
675 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
676 struct got_worktree *worktree)
678 const char *got_revoked_signers = NULL;
679 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
681 *revoked_signers = NULL;
683 if (worktree)
684 worktree_conf = got_worktree_get_gotconfig(worktree);
685 repo_conf = got_repo_get_gotconfig(repo);
687 /*
688 * Priority of potential author information sources, from most
689 * significant to least significant:
690 * 1) work tree's .got/got.conf file
691 * 2) repository's got.conf file
692 */
694 if (worktree_conf)
695 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
696 worktree_conf);
697 if (got_revoked_signers == NULL)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 repo_conf);
701 if (got_revoked_signers) {
702 *revoked_signers = strdup(got_revoked_signers);
703 if (*revoked_signers == NULL)
704 return got_error_from_errno("strdup");
706 return NULL;
709 static const struct got_error *
710 get_signer_id(char **signer_id, struct got_repository *repo,
711 struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 *signer_id = NULL;
718 if (worktree)
719 worktree_conf = got_worktree_get_gotconfig(worktree);
720 repo_conf = got_repo_get_gotconfig(repo);
722 /*
723 * Priority of potential author information sources, from most
724 * significant to least significant:
725 * 1) work tree's .got/got.conf file
726 * 2) repository's got.conf file
727 */
729 if (worktree_conf)
730 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
731 if (got_signer_id == NULL)
732 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
734 if (got_signer_id) {
735 *signer_id = strdup(got_signer_id);
736 if (*signer_id == NULL)
737 return got_error_from_errno("strdup");
739 return NULL;
742 static const struct got_error *
743 get_gitconfig_path(char **gitconfig_path)
745 const char *homedir = getenv("HOME");
747 *gitconfig_path = NULL;
748 if (homedir) {
749 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
750 return got_error_from_errno("asprintf");
753 return NULL;
756 static const struct got_error *
757 cmd_import(int argc, char *argv[])
759 const struct got_error *error = NULL;
760 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
761 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
762 const char *branch_name = "main";
763 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
764 struct got_repository *repo = NULL;
765 struct got_reference *branch_ref = NULL, *head_ref = NULL;
766 struct got_object_id *new_commit_id = NULL;
767 int ch;
768 struct got_pathlist_head ignores;
769 struct got_pathlist_entry *pe;
770 int preserve_logmsg = 0;
771 int *pack_fds = NULL;
773 TAILQ_INIT(&ignores);
775 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
776 switch (ch) {
777 case 'b':
778 branch_name = optarg;
779 break;
780 case 'm':
781 logmsg = strdup(optarg);
782 if (logmsg == NULL) {
783 error = got_error_from_errno("strdup");
784 goto done;
786 break;
787 case 'r':
788 repo_path = realpath(optarg, NULL);
789 if (repo_path == NULL) {
790 error = got_error_from_errno2("realpath",
791 optarg);
792 goto done;
794 break;
795 case 'I':
796 if (optarg[0] == '\0')
797 break;
798 error = got_pathlist_insert(&pe, &ignores, optarg,
799 NULL);
800 if (error)
801 goto done;
802 break;
803 default:
804 usage_import();
805 /* NOTREACHED */
809 argc -= optind;
810 argv += optind;
812 #ifndef PROFILE
813 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
814 "unveil",
815 NULL) == -1)
816 err(1, "pledge");
817 #endif
818 if (argc != 1)
819 usage_import();
821 if (repo_path == NULL) {
822 repo_path = getcwd(NULL, 0);
823 if (repo_path == NULL)
824 return got_error_from_errno("getcwd");
826 got_path_strip_trailing_slashes(repo_path);
827 error = get_gitconfig_path(&gitconfig_path);
828 if (error)
829 goto done;
830 error = got_repo_pack_fds_open(&pack_fds);
831 if (error != NULL)
832 goto done;
833 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
834 if (error)
835 goto done;
837 error = get_author(&author, repo, NULL);
838 if (error)
839 return error;
841 /*
842 * Don't let the user create a branch name with a leading '-'.
843 * While technically a valid reference name, this case is usually
844 * an unintended typo.
845 */
846 if (branch_name[0] == '-')
847 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
849 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
850 error = got_error_from_errno("asprintf");
851 goto done;
854 error = got_ref_open(&branch_ref, repo, refname, 0);
855 if (error) {
856 if (error->code != GOT_ERR_NOT_REF)
857 goto done;
858 } else {
859 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
860 "import target branch already exists");
861 goto done;
864 path_dir = realpath(argv[0], NULL);
865 if (path_dir == NULL) {
866 error = got_error_from_errno2("realpath", argv[0]);
867 goto done;
869 got_path_strip_trailing_slashes(path_dir);
871 /*
872 * unveil(2) traverses exec(2); if an editor is used we have
873 * to apply unveil after the log message has been written.
874 */
875 if (logmsg == NULL || strlen(logmsg) == 0) {
876 error = get_editor(&editor);
877 if (error)
878 goto done;
879 free(logmsg);
880 error = collect_import_msg(&logmsg, &logmsg_path, editor,
881 path_dir, refname);
882 if (error) {
883 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
884 logmsg_path != NULL)
885 preserve_logmsg = 1;
886 goto done;
890 if (unveil(path_dir, "r") != 0) {
891 error = got_error_from_errno2("unveil", path_dir);
892 if (logmsg_path)
893 preserve_logmsg = 1;
894 goto done;
897 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
898 if (error) {
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = got_repo_import(&new_commit_id, path_dir, logmsg,
905 author, &ignores, repo, import_progress, NULL);
906 if (error) {
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_write(branch_ref, repo);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_object_id_str(&id_str, new_commit_id);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
934 if (error) {
935 if (error->code != GOT_ERR_NOT_REF) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
942 branch_ref);
943 if (error) {
944 if (logmsg_path)
945 preserve_logmsg = 1;
946 goto done;
949 error = got_ref_write(head_ref, repo);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
957 printf("Created branch %s with commit %s\n",
958 got_ref_get_name(branch_ref), id_str);
959 done:
960 if (pack_fds) {
961 const struct got_error *pack_err =
962 got_repo_pack_fds_close(pack_fds);
963 if (error == NULL)
964 error = pack_err;
966 if (preserve_logmsg) {
967 fprintf(stderr, "%s: log message preserved in %s\n",
968 getprogname(), logmsg_path);
969 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
970 error = got_error_from_errno2("unlink", logmsg_path);
971 free(logmsg);
972 free(logmsg_path);
973 free(repo_path);
974 free(editor);
975 free(refname);
976 free(new_commit_id);
977 free(id_str);
978 free(author);
979 free(gitconfig_path);
980 if (branch_ref)
981 got_ref_close(branch_ref);
982 if (head_ref)
983 got_ref_close(head_ref);
984 return error;
987 __dead static void
988 usage_clone(void)
990 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
991 "repository-URL [directory]\n", getprogname());
992 exit(1);
995 struct got_fetch_progress_arg {
996 char last_scaled_size[FMT_SCALED_STRSIZE];
997 int last_p_indexed;
998 int last_p_resolved;
999 int verbosity;
1001 struct got_repository *repo;
1003 int create_configs;
1004 int configs_created;
1005 struct {
1006 struct got_pathlist_head *symrefs;
1007 struct got_pathlist_head *wanted_branches;
1008 struct got_pathlist_head *wanted_refs;
1009 const char *proto;
1010 const char *host;
1011 const char *port;
1012 const char *remote_repo_path;
1013 const char *git_url;
1014 int fetch_all_branches;
1015 int mirror_references;
1016 } config_info;
1019 /* XXX forward declaration */
1020 static const struct got_error *
1021 create_config_files(const char *proto, const char *host, const char *port,
1022 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1023 int mirror_references, struct got_pathlist_head *symrefs,
1024 struct got_pathlist_head *wanted_branches,
1025 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1027 static const struct got_error *
1028 fetch_progress(void *arg, const char *message, off_t packfile_size,
1029 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1031 const struct got_error *err = NULL;
1032 struct got_fetch_progress_arg *a = arg;
1033 char scaled_size[FMT_SCALED_STRSIZE];
1034 int p_indexed, p_resolved;
1035 int print_size = 0, print_indexed = 0, print_resolved = 0;
1038 * In order to allow a failed clone to be resumed with 'got fetch'
1039 * we try to create configuration files as soon as possible.
1040 * Once the server has sent information about its default branch
1041 * we have all required information.
1043 if (a->create_configs && !a->configs_created &&
1044 !TAILQ_EMPTY(a->config_info.symrefs)) {
1045 err = create_config_files(a->config_info.proto,
1046 a->config_info.host, a->config_info.port,
1047 a->config_info.remote_repo_path,
1048 a->config_info.git_url,
1049 a->config_info.fetch_all_branches,
1050 a->config_info.mirror_references,
1051 a->config_info.symrefs,
1052 a->config_info.wanted_branches,
1053 a->config_info.wanted_refs, a->repo);
1054 if (err)
1055 return err;
1056 a->configs_created = 1;
1059 if (a->verbosity < 0)
1060 return NULL;
1062 if (message && message[0] != '\0') {
1063 printf("\rserver: %s", message);
1064 fflush(stdout);
1065 return NULL;
1068 if (packfile_size > 0 || nobj_indexed > 0) {
1069 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1070 (a->last_scaled_size[0] == '\0' ||
1071 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1072 print_size = 1;
1073 if (strlcpy(a->last_scaled_size, scaled_size,
1074 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1075 return got_error(GOT_ERR_NO_SPACE);
1077 if (nobj_indexed > 0) {
1078 p_indexed = (nobj_indexed * 100) / nobj_total;
1079 if (p_indexed != a->last_p_indexed) {
1080 a->last_p_indexed = p_indexed;
1081 print_indexed = 1;
1082 print_size = 1;
1085 if (nobj_resolved > 0) {
1086 p_resolved = (nobj_resolved * 100) /
1087 (nobj_total - nobj_loose);
1088 if (p_resolved != a->last_p_resolved) {
1089 a->last_p_resolved = p_resolved;
1090 print_resolved = 1;
1091 print_indexed = 1;
1092 print_size = 1;
1097 if (print_size || print_indexed || print_resolved)
1098 printf("\r");
1099 if (print_size)
1100 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1101 if (print_indexed)
1102 printf("; indexing %d%%", p_indexed);
1103 if (print_resolved)
1104 printf("; resolving deltas %d%%", p_resolved);
1105 if (print_size || print_indexed || print_resolved)
1106 fflush(stdout);
1108 return NULL;
1111 static const struct got_error *
1112 create_symref(const char *refname, struct got_reference *target_ref,
1113 int verbosity, struct got_repository *repo)
1115 const struct got_error *err;
1116 struct got_reference *head_symref;
1118 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1119 if (err)
1120 return err;
1122 err = got_ref_write(head_symref, repo);
1123 if (err == NULL && verbosity > 0) {
1124 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1125 got_ref_get_name(target_ref));
1127 got_ref_close(head_symref);
1128 return err;
1131 static const struct got_error *
1132 list_remote_refs(struct got_pathlist_head *symrefs,
1133 struct got_pathlist_head *refs)
1135 const struct got_error *err;
1136 struct got_pathlist_entry *pe;
1138 TAILQ_FOREACH(pe, symrefs, entry) {
1139 const char *refname = pe->path;
1140 const char *targetref = pe->data;
1142 printf("%s: %s\n", refname, targetref);
1145 TAILQ_FOREACH(pe, refs, entry) {
1146 const char *refname = pe->path;
1147 struct got_object_id *id = pe->data;
1148 char *id_str;
1150 err = got_object_id_str(&id_str, id);
1151 if (err)
1152 return err;
1153 printf("%s: %s\n", refname, id_str);
1154 free(id_str);
1157 return NULL;
1160 static const struct got_error *
1161 create_ref(const char *refname, struct got_object_id *id,
1162 int verbosity, struct got_repository *repo)
1164 const struct got_error *err = NULL;
1165 struct got_reference *ref;
1166 char *id_str;
1168 err = got_object_id_str(&id_str, id);
1169 if (err)
1170 return err;
1172 err = got_ref_alloc(&ref, refname, id);
1173 if (err)
1174 goto done;
1176 err = got_ref_write(ref, repo);
1177 got_ref_close(ref);
1179 if (err == NULL && verbosity >= 0)
1180 printf("Created reference %s: %s\n", refname, id_str);
1181 done:
1182 free(id_str);
1183 return err;
1186 static int
1187 match_wanted_ref(const char *refname, const char *wanted_ref)
1189 if (strncmp(refname, "refs/", 5) != 0)
1190 return 0;
1191 refname += 5;
1194 * Prevent fetching of references that won't make any
1195 * sense outside of the remote repository's context.
1197 if (strncmp(refname, "got/", 4) == 0)
1198 return 0;
1199 if (strncmp(refname, "remotes/", 8) == 0)
1200 return 0;
1202 if (strncmp(wanted_ref, "refs/", 5) == 0)
1203 wanted_ref += 5;
1205 /* Allow prefix match. */
1206 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1207 return 1;
1209 /* Allow exact match. */
1210 return (strcmp(refname, wanted_ref) == 0);
1213 static int
1214 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1216 struct got_pathlist_entry *pe;
1218 TAILQ_FOREACH(pe, wanted_refs, entry) {
1219 if (match_wanted_ref(refname, pe->path))
1220 return 1;
1223 return 0;
1226 static const struct got_error *
1227 create_wanted_ref(const char *refname, struct got_object_id *id,
1228 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1230 const struct got_error *err;
1231 char *remote_refname;
1233 if (strncmp("refs/", refname, 5) == 0)
1234 refname += 5;
1236 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1237 remote_repo_name, refname) == -1)
1238 return got_error_from_errno("asprintf");
1240 err = create_ref(remote_refname, id, verbosity, repo);
1241 free(remote_refname);
1242 return err;
1245 static const struct got_error *
1246 create_gotconfig(const char *proto, const char *host, const char *port,
1247 const char *remote_repo_path, const char *default_branch,
1248 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1249 struct got_pathlist_head *wanted_refs, int mirror_references,
1250 struct got_repository *repo)
1252 const struct got_error *err = NULL;
1253 char *gotconfig_path = NULL;
1254 char *gotconfig = NULL;
1255 FILE *gotconfig_file = NULL;
1256 const char *branchname = NULL;
1257 char *branches = NULL, *refs = NULL;
1258 ssize_t n;
1260 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1261 struct got_pathlist_entry *pe;
1262 TAILQ_FOREACH(pe, wanted_branches, entry) {
1263 char *s;
1264 branchname = pe->path;
1265 if (strncmp(branchname, "refs/heads/", 11) == 0)
1266 branchname += 11;
1267 if (asprintf(&s, "%s\"%s\" ",
1268 branches ? branches : "", branchname) == -1) {
1269 err = got_error_from_errno("asprintf");
1270 goto done;
1272 free(branches);
1273 branches = s;
1275 } else if (!fetch_all_branches && default_branch) {
1276 branchname = default_branch;
1277 if (strncmp(branchname, "refs/heads/", 11) == 0)
1278 branchname += 11;
1279 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1280 err = got_error_from_errno("asprintf");
1281 goto done;
1284 if (!TAILQ_EMPTY(wanted_refs)) {
1285 struct got_pathlist_entry *pe;
1286 TAILQ_FOREACH(pe, wanted_refs, entry) {
1287 char *s;
1288 const char *refname = pe->path;
1289 if (strncmp(refname, "refs/", 5) == 0)
1290 branchname += 5;
1291 if (asprintf(&s, "%s\"%s\" ",
1292 refs ? refs : "", refname) == -1) {
1293 err = got_error_from_errno("asprintf");
1294 goto done;
1296 free(refs);
1297 refs = s;
1301 /* Create got.conf(5). */
1302 gotconfig_path = got_repo_get_path_gotconfig(repo);
1303 if (gotconfig_path == NULL) {
1304 err = got_error_from_errno("got_repo_get_path_gotconfig");
1305 goto done;
1307 gotconfig_file = fopen(gotconfig_path, "ae");
1308 if (gotconfig_file == NULL) {
1309 err = got_error_from_errno2("fopen", gotconfig_path);
1310 goto done;
1312 if (asprintf(&gotconfig,
1313 "remote \"%s\" {\n"
1314 "\tserver %s\n"
1315 "\tprotocol %s\n"
1316 "%s%s%s"
1317 "\trepository \"%s\"\n"
1318 "%s%s%s"
1319 "%s%s%s"
1320 "%s"
1321 "%s"
1322 "}\n",
1323 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1324 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1325 remote_repo_path, branches ? "\tbranch { " : "",
1326 branches ? branches : "", branches ? "}\n" : "",
1327 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1328 mirror_references ? "\tmirror_references yes\n" : "",
1329 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1330 err = got_error_from_errno("asprintf");
1331 goto done;
1333 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1334 if (n != strlen(gotconfig)) {
1335 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1336 goto done;
1339 done:
1340 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1341 err = got_error_from_errno2("fclose", gotconfig_path);
1342 free(gotconfig_path);
1343 free(branches);
1344 return err;
1347 static const struct got_error *
1348 create_gitconfig(const char *git_url, const char *default_branch,
1349 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1350 struct got_pathlist_head *wanted_refs, int mirror_references,
1351 struct got_repository *repo)
1353 const struct got_error *err = NULL;
1354 char *gitconfig_path = NULL;
1355 char *gitconfig = NULL;
1356 FILE *gitconfig_file = NULL;
1357 char *branches = NULL, *refs = NULL;
1358 const char *branchname;
1359 ssize_t n;
1361 /* Create a config file Git can understand. */
1362 gitconfig_path = got_repo_get_path_gitconfig(repo);
1363 if (gitconfig_path == NULL) {
1364 err = got_error_from_errno("got_repo_get_path_gitconfig");
1365 goto done;
1367 gitconfig_file = fopen(gitconfig_path, "ae");
1368 if (gitconfig_file == NULL) {
1369 err = got_error_from_errno2("fopen", gitconfig_path);
1370 goto done;
1372 if (fetch_all_branches) {
1373 if (mirror_references) {
1374 if (asprintf(&branches,
1375 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1376 err = got_error_from_errno("asprintf");
1377 goto done;
1379 } else if (asprintf(&branches,
1380 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1381 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1382 err = got_error_from_errno("asprintf");
1383 goto done;
1385 } else if (!TAILQ_EMPTY(wanted_branches)) {
1386 struct got_pathlist_entry *pe;
1387 TAILQ_FOREACH(pe, wanted_branches, entry) {
1388 char *s;
1389 branchname = pe->path;
1390 if (strncmp(branchname, "refs/heads/", 11) == 0)
1391 branchname += 11;
1392 if (mirror_references) {
1393 if (asprintf(&s,
1394 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1395 branches ? branches : "",
1396 branchname, branchname) == -1) {
1397 err = got_error_from_errno("asprintf");
1398 goto done;
1400 } else if (asprintf(&s,
1401 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1402 branches ? branches : "",
1403 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1404 branchname) == -1) {
1405 err = got_error_from_errno("asprintf");
1406 goto done;
1408 free(branches);
1409 branches = s;
1411 } else {
1413 * If the server specified a default branch, use just that one.
1414 * Otherwise fall back to fetching all branches on next fetch.
1416 if (default_branch) {
1417 branchname = default_branch;
1418 if (strncmp(branchname, "refs/heads/", 11) == 0)
1419 branchname += 11;
1420 } else
1421 branchname = "*"; /* fall back to all branches */
1422 if (mirror_references) {
1423 if (asprintf(&branches,
1424 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1425 branchname, branchname) == -1) {
1426 err = got_error_from_errno("asprintf");
1427 goto done;
1429 } else if (asprintf(&branches,
1430 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1431 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1432 branchname) == -1) {
1433 err = got_error_from_errno("asprintf");
1434 goto done;
1437 if (!TAILQ_EMPTY(wanted_refs)) {
1438 struct got_pathlist_entry *pe;
1439 TAILQ_FOREACH(pe, wanted_refs, entry) {
1440 char *s;
1441 const char *refname = pe->path;
1442 if (strncmp(refname, "refs/", 5) == 0)
1443 refname += 5;
1444 if (mirror_references) {
1445 if (asprintf(&s,
1446 "%s\tfetch = refs/%s:refs/%s\n",
1447 refs ? refs : "", refname, refname) == -1) {
1448 err = got_error_from_errno("asprintf");
1449 goto done;
1451 } else if (asprintf(&s,
1452 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1453 refs ? refs : "",
1454 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1455 refname) == -1) {
1456 err = got_error_from_errno("asprintf");
1457 goto done;
1459 free(refs);
1460 refs = s;
1464 if (asprintf(&gitconfig,
1465 "[remote \"%s\"]\n"
1466 "\turl = %s\n"
1467 "%s"
1468 "%s"
1469 "\tfetch = refs/tags/*:refs/tags/*\n",
1470 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1471 refs ? refs : "") == -1) {
1472 err = got_error_from_errno("asprintf");
1473 goto done;
1475 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1476 if (n != strlen(gitconfig)) {
1477 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1478 goto done;
1480 done:
1481 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1482 err = got_error_from_errno2("fclose", gitconfig_path);
1483 free(gitconfig_path);
1484 free(branches);
1485 return err;
1488 static const struct got_error *
1489 create_config_files(const char *proto, const char *host, const char *port,
1490 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1491 int mirror_references, struct got_pathlist_head *symrefs,
1492 struct got_pathlist_head *wanted_branches,
1493 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1495 const struct got_error *err = NULL;
1496 const char *default_branch = NULL;
1497 struct got_pathlist_entry *pe;
1500 * If we asked for a set of wanted branches then use the first
1501 * one of those.
1503 if (!TAILQ_EMPTY(wanted_branches)) {
1504 pe = TAILQ_FIRST(wanted_branches);
1505 default_branch = pe->path;
1506 } else {
1507 /* First HEAD ref listed by server is the default branch. */
1508 TAILQ_FOREACH(pe, symrefs, entry) {
1509 const char *refname = pe->path;
1510 const char *target = pe->data;
1512 if (strcmp(refname, GOT_REF_HEAD) != 0)
1513 continue;
1515 default_branch = target;
1516 break;
1520 /* Create got.conf(5). */
1521 err = create_gotconfig(proto, host, port, remote_repo_path,
1522 default_branch, fetch_all_branches, wanted_branches,
1523 wanted_refs, mirror_references, repo);
1524 if (err)
1525 return err;
1527 /* Create a config file Git can understand. */
1528 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1529 wanted_branches, wanted_refs, mirror_references, repo);
1532 static const struct got_error *
1533 cmd_clone(int argc, char *argv[])
1535 const struct got_error *error = NULL;
1536 const char *uri, *dirname;
1537 char *proto, *host, *port, *repo_name, *server_path;
1538 char *default_destdir = NULL, *id_str = NULL;
1539 const char *repo_path;
1540 struct got_repository *repo = NULL;
1541 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1542 struct got_pathlist_entry *pe;
1543 struct got_object_id *pack_hash = NULL;
1544 int ch, fetchfd = -1, fetchstatus;
1545 pid_t fetchpid = -1;
1546 struct got_fetch_progress_arg fpa;
1547 char *git_url = NULL;
1548 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1549 int list_refs_only = 0;
1550 int *pack_fds = NULL;
1552 TAILQ_INIT(&refs);
1553 TAILQ_INIT(&symrefs);
1554 TAILQ_INIT(&wanted_branches);
1555 TAILQ_INIT(&wanted_refs);
1557 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1558 switch (ch) {
1559 case 'a':
1560 fetch_all_branches = 1;
1561 break;
1562 case 'b':
1563 error = got_pathlist_append(&wanted_branches,
1564 optarg, NULL);
1565 if (error)
1566 return error;
1567 break;
1568 case 'l':
1569 list_refs_only = 1;
1570 break;
1571 case 'm':
1572 mirror_references = 1;
1573 break;
1574 case 'v':
1575 if (verbosity < 0)
1576 verbosity = 0;
1577 else if (verbosity < 3)
1578 verbosity++;
1579 break;
1580 case 'q':
1581 verbosity = -1;
1582 break;
1583 case 'R':
1584 error = got_pathlist_append(&wanted_refs,
1585 optarg, NULL);
1586 if (error)
1587 return error;
1588 break;
1589 default:
1590 usage_clone();
1591 break;
1594 argc -= optind;
1595 argv += optind;
1597 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1598 option_conflict('a', 'b');
1599 if (list_refs_only) {
1600 if (!TAILQ_EMPTY(&wanted_branches))
1601 option_conflict('l', 'b');
1602 if (fetch_all_branches)
1603 option_conflict('l', 'a');
1604 if (mirror_references)
1605 option_conflict('l', 'm');
1606 if (!TAILQ_EMPTY(&wanted_refs))
1607 option_conflict('l', 'R');
1610 uri = argv[0];
1612 if (argc == 1)
1613 dirname = NULL;
1614 else if (argc == 2)
1615 dirname = argv[1];
1616 else
1617 usage_clone();
1619 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1620 &repo_name, uri);
1621 if (error)
1622 goto done;
1624 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1625 host, port ? ":" : "", port ? port : "",
1626 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1627 error = got_error_from_errno("asprintf");
1628 goto done;
1631 if (strcmp(proto, "git") == 0) {
1632 #ifndef PROFILE
1633 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1634 "sendfd dns inet unveil", NULL) == -1)
1635 err(1, "pledge");
1636 #endif
1637 } else if (strcmp(proto, "git+ssh") == 0 ||
1638 strcmp(proto, "ssh") == 0) {
1639 #ifndef PROFILE
1640 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1641 "sendfd unveil", NULL) == -1)
1642 err(1, "pledge");
1643 #endif
1644 } else if (strcmp(proto, "http") == 0 ||
1645 strcmp(proto, "git+http") == 0) {
1646 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1647 goto done;
1648 } else {
1649 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1650 goto done;
1652 if (dirname == NULL) {
1653 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1654 error = got_error_from_errno("asprintf");
1655 goto done;
1657 repo_path = default_destdir;
1658 } else
1659 repo_path = dirname;
1661 if (!list_refs_only) {
1662 error = got_path_mkdir(repo_path);
1663 if (error &&
1664 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1665 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1666 goto done;
1667 if (!got_path_dir_is_empty(repo_path)) {
1668 error = got_error_path(repo_path,
1669 GOT_ERR_DIR_NOT_EMPTY);
1670 goto done;
1674 error = got_dial_apply_unveil(proto);
1675 if (error)
1676 goto done;
1678 error = apply_unveil(repo_path, 0, NULL);
1679 if (error)
1680 goto done;
1682 if (verbosity >= 0)
1683 printf("Connecting to %s%s%s\n", host,
1684 port ? ":" : "", port ? port : "");
1686 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1687 server_path, verbosity);
1688 if (error)
1689 goto done;
1691 if (!list_refs_only) {
1692 error = got_repo_init(repo_path);
1693 if (error)
1694 goto done;
1695 error = got_repo_pack_fds_open(&pack_fds);
1696 if (error != NULL)
1697 goto done;
1698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1699 if (error)
1700 goto done;
1703 fpa.last_scaled_size[0] = '\0';
1704 fpa.last_p_indexed = -1;
1705 fpa.last_p_resolved = -1;
1706 fpa.verbosity = verbosity;
1707 fpa.create_configs = 1;
1708 fpa.configs_created = 0;
1709 fpa.repo = repo;
1710 fpa.config_info.symrefs = &symrefs;
1711 fpa.config_info.wanted_branches = &wanted_branches;
1712 fpa.config_info.wanted_refs = &wanted_refs;
1713 fpa.config_info.proto = proto;
1714 fpa.config_info.host = host;
1715 fpa.config_info.port = port;
1716 fpa.config_info.remote_repo_path = server_path;
1717 fpa.config_info.git_url = git_url;
1718 fpa.config_info.fetch_all_branches = fetch_all_branches;
1719 fpa.config_info.mirror_references = mirror_references;
1720 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1721 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1722 fetch_all_branches, &wanted_branches, &wanted_refs,
1723 list_refs_only, verbosity, fetchfd, repo,
1724 fetch_progress, &fpa);
1725 if (error)
1726 goto done;
1728 if (list_refs_only) {
1729 error = list_remote_refs(&symrefs, &refs);
1730 goto done;
1733 if (pack_hash == NULL) {
1734 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1735 "server sent an empty pack file");
1736 goto done;
1738 error = got_object_id_str(&id_str, pack_hash);
1739 if (error)
1740 goto done;
1741 if (verbosity >= 0)
1742 printf("\nFetched %s.pack\n", id_str);
1743 free(id_str);
1745 /* Set up references provided with the pack file. */
1746 TAILQ_FOREACH(pe, &refs, entry) {
1747 const char *refname = pe->path;
1748 struct got_object_id *id = pe->data;
1749 char *remote_refname;
1751 if (is_wanted_ref(&wanted_refs, refname) &&
1752 !mirror_references) {
1753 error = create_wanted_ref(refname, id,
1754 GOT_FETCH_DEFAULT_REMOTE_NAME,
1755 verbosity - 1, repo);
1756 if (error)
1757 goto done;
1758 continue;
1761 error = create_ref(refname, id, verbosity - 1, repo);
1762 if (error)
1763 goto done;
1765 if (mirror_references)
1766 continue;
1768 if (strncmp("refs/heads/", refname, 11) != 0)
1769 continue;
1771 if (asprintf(&remote_refname,
1772 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1773 refname + 11) == -1) {
1774 error = got_error_from_errno("asprintf");
1775 goto done;
1777 error = create_ref(remote_refname, id, verbosity - 1, repo);
1778 free(remote_refname);
1779 if (error)
1780 goto done;
1783 /* Set the HEAD reference if the server provided one. */
1784 TAILQ_FOREACH(pe, &symrefs, entry) {
1785 struct got_reference *target_ref;
1786 const char *refname = pe->path;
1787 const char *target = pe->data;
1788 char *remote_refname = NULL, *remote_target = NULL;
1790 if (strcmp(refname, GOT_REF_HEAD) != 0)
1791 continue;
1793 error = got_ref_open(&target_ref, repo, target, 0);
1794 if (error) {
1795 if (error->code == GOT_ERR_NOT_REF) {
1796 error = NULL;
1797 continue;
1799 goto done;
1802 error = create_symref(refname, target_ref, verbosity, repo);
1803 got_ref_close(target_ref);
1804 if (error)
1805 goto done;
1807 if (mirror_references)
1808 continue;
1810 if (strncmp("refs/heads/", target, 11) != 0)
1811 continue;
1813 if (asprintf(&remote_refname,
1814 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1815 refname) == -1) {
1816 error = got_error_from_errno("asprintf");
1817 goto done;
1819 if (asprintf(&remote_target,
1820 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1821 target + 11) == -1) {
1822 error = got_error_from_errno("asprintf");
1823 free(remote_refname);
1824 goto done;
1826 error = got_ref_open(&target_ref, repo, remote_target, 0);
1827 if (error) {
1828 free(remote_refname);
1829 free(remote_target);
1830 if (error->code == GOT_ERR_NOT_REF) {
1831 error = NULL;
1832 continue;
1834 goto done;
1836 error = create_symref(remote_refname, target_ref,
1837 verbosity - 1, repo);
1838 free(remote_refname);
1839 free(remote_target);
1840 got_ref_close(target_ref);
1841 if (error)
1842 goto done;
1844 if (pe == NULL) {
1846 * We failed to set the HEAD reference. If we asked for
1847 * a set of wanted branches use the first of one of those
1848 * which could be fetched instead.
1850 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1851 const char *target = pe->path;
1852 struct got_reference *target_ref;
1854 error = got_ref_open(&target_ref, repo, target, 0);
1855 if (error) {
1856 if (error->code == GOT_ERR_NOT_REF) {
1857 error = NULL;
1858 continue;
1860 goto done;
1863 error = create_symref(GOT_REF_HEAD, target_ref,
1864 verbosity, repo);
1865 got_ref_close(target_ref);
1866 if (error)
1867 goto done;
1868 break;
1872 if (verbosity >= 0)
1873 printf("Created %s repository '%s'\n",
1874 mirror_references ? "mirrored" : "cloned", repo_path);
1875 done:
1876 if (pack_fds) {
1877 const struct got_error *pack_err =
1878 got_repo_pack_fds_close(pack_fds);
1879 if (error == NULL)
1880 error = pack_err;
1882 if (fetchpid > 0) {
1883 if (kill(fetchpid, SIGTERM) == -1)
1884 error = got_error_from_errno("kill");
1885 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1886 error = got_error_from_errno("waitpid");
1888 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1889 error = got_error_from_errno("close");
1890 if (repo) {
1891 const struct got_error *close_err = got_repo_close(repo);
1892 if (error == NULL)
1893 error = close_err;
1895 TAILQ_FOREACH(pe, &refs, entry) {
1896 free((void *)pe->path);
1897 free(pe->data);
1899 got_pathlist_free(&refs);
1900 TAILQ_FOREACH(pe, &symrefs, entry) {
1901 free((void *)pe->path);
1902 free(pe->data);
1904 got_pathlist_free(&symrefs);
1905 got_pathlist_free(&wanted_branches);
1906 got_pathlist_free(&wanted_refs);
1907 free(pack_hash);
1908 free(proto);
1909 free(host);
1910 free(port);
1911 free(server_path);
1912 free(repo_name);
1913 free(default_destdir);
1914 free(git_url);
1915 return error;
1918 static const struct got_error *
1919 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1920 int replace_tags, int verbosity, struct got_repository *repo)
1922 const struct got_error *err = NULL;
1923 char *new_id_str = NULL;
1924 struct got_object_id *old_id = NULL;
1926 err = got_object_id_str(&new_id_str, new_id);
1927 if (err)
1928 goto done;
1930 if (!replace_tags &&
1931 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1932 err = got_ref_resolve(&old_id, repo, ref);
1933 if (err)
1934 goto done;
1935 if (got_object_id_cmp(old_id, new_id) == 0)
1936 goto done;
1937 if (verbosity >= 0) {
1938 printf("Rejecting update of existing tag %s: %s\n",
1939 got_ref_get_name(ref), new_id_str);
1941 goto done;
1944 if (got_ref_is_symbolic(ref)) {
1945 if (verbosity >= 0) {
1946 printf("Replacing reference %s: %s\n",
1947 got_ref_get_name(ref),
1948 got_ref_get_symref_target(ref));
1950 err = got_ref_change_symref_to_ref(ref, new_id);
1951 if (err)
1952 goto done;
1953 err = got_ref_write(ref, repo);
1954 if (err)
1955 goto done;
1956 } else {
1957 err = got_ref_resolve(&old_id, repo, ref);
1958 if (err)
1959 goto done;
1960 if (got_object_id_cmp(old_id, new_id) == 0)
1961 goto done;
1963 err = got_ref_change_ref(ref, new_id);
1964 if (err)
1965 goto done;
1966 err = got_ref_write(ref, repo);
1967 if (err)
1968 goto done;
1971 if (verbosity >= 0)
1972 printf("Updated %s: %s\n", got_ref_get_name(ref),
1973 new_id_str);
1974 done:
1975 free(old_id);
1976 free(new_id_str);
1977 return err;
1980 static const struct got_error *
1981 update_symref(const char *refname, struct got_reference *target_ref,
1982 int verbosity, struct got_repository *repo)
1984 const struct got_error *err = NULL, *unlock_err;
1985 struct got_reference *symref;
1986 int symref_is_locked = 0;
1988 err = got_ref_open(&symref, repo, refname, 1);
1989 if (err) {
1990 if (err->code != GOT_ERR_NOT_REF)
1991 return err;
1992 err = got_ref_alloc_symref(&symref, refname, target_ref);
1993 if (err)
1994 goto done;
1996 err = got_ref_write(symref, repo);
1997 if (err)
1998 goto done;
2000 if (verbosity >= 0)
2001 printf("Created reference %s: %s\n",
2002 got_ref_get_name(symref),
2003 got_ref_get_symref_target(symref));
2004 } else {
2005 symref_is_locked = 1;
2007 if (strcmp(got_ref_get_symref_target(symref),
2008 got_ref_get_name(target_ref)) == 0)
2009 goto done;
2011 err = got_ref_change_symref(symref,
2012 got_ref_get_name(target_ref));
2013 if (err)
2014 goto done;
2016 err = got_ref_write(symref, repo);
2017 if (err)
2018 goto done;
2020 if (verbosity >= 0)
2021 printf("Updated %s: %s\n", got_ref_get_name(symref),
2022 got_ref_get_symref_target(symref));
2025 done:
2026 if (symref_is_locked) {
2027 unlock_err = got_ref_unlock(symref);
2028 if (unlock_err && err == NULL)
2029 err = unlock_err;
2031 got_ref_close(symref);
2032 return err;
2035 __dead static void
2036 usage_fetch(void)
2038 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2039 "[-R reference] [-r repository-path] [remote-repository]\n",
2040 getprogname());
2041 exit(1);
2044 static const struct got_error *
2045 delete_missing_ref(struct got_reference *ref,
2046 int verbosity, struct got_repository *repo)
2048 const struct got_error *err = NULL;
2049 struct got_object_id *id = NULL;
2050 char *id_str = NULL;
2052 if (got_ref_is_symbolic(ref)) {
2053 err = got_ref_delete(ref, repo);
2054 if (err)
2055 return err;
2056 if (verbosity >= 0) {
2057 printf("Deleted %s: %s\n",
2058 got_ref_get_name(ref),
2059 got_ref_get_symref_target(ref));
2061 } else {
2062 err = got_ref_resolve(&id, repo, ref);
2063 if (err)
2064 return err;
2065 err = got_object_id_str(&id_str, id);
2066 if (err)
2067 goto done;
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 goto done;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref), id_str);
2077 done:
2078 free(id);
2079 free(id_str);
2080 return NULL;
2083 static const struct got_error *
2084 delete_missing_refs(struct got_pathlist_head *their_refs,
2085 struct got_pathlist_head *their_symrefs,
2086 const struct got_remote_repo *remote,
2087 int verbosity, struct got_repository *repo)
2089 const struct got_error *err = NULL, *unlock_err;
2090 struct got_reflist_head my_refs;
2091 struct got_reflist_entry *re;
2092 struct got_pathlist_entry *pe;
2093 char *remote_namespace = NULL;
2094 char *local_refname = NULL;
2096 TAILQ_INIT(&my_refs);
2098 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2099 == -1)
2100 return got_error_from_errno("asprintf");
2102 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2103 if (err)
2104 goto done;
2106 TAILQ_FOREACH(re, &my_refs, entry) {
2107 const char *refname = got_ref_get_name(re->ref);
2108 const char *their_refname;
2110 if (remote->mirror_references) {
2111 their_refname = refname;
2112 } else {
2113 if (strncmp(refname, remote_namespace,
2114 strlen(remote_namespace)) == 0) {
2115 if (strcmp(refname + strlen(remote_namespace),
2116 GOT_REF_HEAD) == 0)
2117 continue;
2118 if (asprintf(&local_refname, "refs/heads/%s",
2119 refname + strlen(remote_namespace)) == -1) {
2120 err = got_error_from_errno("asprintf");
2121 goto done;
2123 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2124 continue;
2126 their_refname = local_refname;
2129 TAILQ_FOREACH(pe, their_refs, entry) {
2130 if (strcmp(their_refname, pe->path) == 0)
2131 break;
2133 if (pe != NULL)
2134 continue;
2136 TAILQ_FOREACH(pe, their_symrefs, entry) {
2137 if (strcmp(their_refname, pe->path) == 0)
2138 break;
2140 if (pe != NULL)
2141 continue;
2143 err = delete_missing_ref(re->ref, verbosity, repo);
2144 if (err)
2145 break;
2147 if (local_refname) {
2148 struct got_reference *ref;
2149 err = got_ref_open(&ref, repo, local_refname, 1);
2150 if (err) {
2151 if (err->code != GOT_ERR_NOT_REF)
2152 break;
2153 free(local_refname);
2154 local_refname = NULL;
2155 continue;
2157 err = delete_missing_ref(ref, verbosity, repo);
2158 if (err)
2159 break;
2160 unlock_err = got_ref_unlock(ref);
2161 got_ref_close(ref);
2162 if (unlock_err && err == NULL) {
2163 err = unlock_err;
2164 break;
2167 free(local_refname);
2168 local_refname = NULL;
2171 done:
2172 free(remote_namespace);
2173 free(local_refname);
2174 return err;
2177 static const struct got_error *
2178 update_wanted_ref(const char *refname, struct got_object_id *id,
2179 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2181 const struct got_error *err, *unlock_err;
2182 char *remote_refname;
2183 struct got_reference *ref;
2185 if (strncmp("refs/", refname, 5) == 0)
2186 refname += 5;
2188 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2189 remote_repo_name, refname) == -1)
2190 return got_error_from_errno("asprintf");
2192 err = got_ref_open(&ref, repo, remote_refname, 1);
2193 if (err) {
2194 if (err->code != GOT_ERR_NOT_REF)
2195 goto done;
2196 err = create_ref(remote_refname, id, verbosity, repo);
2197 } else {
2198 err = update_ref(ref, id, 0, verbosity, repo);
2199 unlock_err = got_ref_unlock(ref);
2200 if (unlock_err && err == NULL)
2201 err = unlock_err;
2202 got_ref_close(ref);
2204 done:
2205 free(remote_refname);
2206 return err;
2209 static const struct got_error *
2210 delete_ref(struct got_repository *repo, struct got_reference *ref)
2212 const struct got_error *err = NULL;
2213 struct got_object_id *id = NULL;
2214 char *id_str = NULL;
2215 const char *target;
2217 if (got_ref_is_symbolic(ref)) {
2218 target = got_ref_get_symref_target(ref);
2219 } else {
2220 err = got_ref_resolve(&id, repo, ref);
2221 if (err)
2222 goto done;
2223 err = got_object_id_str(&id_str, id);
2224 if (err)
2225 goto done;
2226 target = id_str;
2229 err = got_ref_delete(ref, repo);
2230 if (err)
2231 goto done;
2233 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2234 done:
2235 free(id);
2236 free(id_str);
2237 return err;
2240 static const struct got_error *
2241 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2243 const struct got_error *err = NULL;
2244 struct got_reflist_head refs;
2245 struct got_reflist_entry *re;
2246 char *prefix;
2248 TAILQ_INIT(&refs);
2250 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2251 err = got_error_from_errno("asprintf");
2252 goto done;
2254 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2255 if (err)
2256 goto done;
2258 TAILQ_FOREACH(re, &refs, entry)
2259 delete_ref(repo, re->ref);
2260 done:
2261 got_ref_list_free(&refs);
2262 return err;
2265 static const struct got_error *
2266 cmd_fetch(int argc, char *argv[])
2268 const struct got_error *error = NULL, *unlock_err;
2269 char *cwd = NULL, *repo_path = NULL;
2270 const char *remote_name;
2271 char *proto = NULL, *host = NULL, *port = NULL;
2272 char *repo_name = NULL, *server_path = NULL;
2273 const struct got_remote_repo *remotes, *remote = NULL;
2274 int nremotes;
2275 char *id_str = NULL;
2276 struct got_repository *repo = NULL;
2277 struct got_worktree *worktree = NULL;
2278 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2279 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2280 struct got_pathlist_entry *pe;
2281 struct got_object_id *pack_hash = NULL;
2282 int i, ch, fetchfd = -1, fetchstatus;
2283 pid_t fetchpid = -1;
2284 struct got_fetch_progress_arg fpa;
2285 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2286 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2287 int *pack_fds = NULL;
2289 TAILQ_INIT(&refs);
2290 TAILQ_INIT(&symrefs);
2291 TAILQ_INIT(&wanted_branches);
2292 TAILQ_INIT(&wanted_refs);
2294 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2295 switch (ch) {
2296 case 'a':
2297 fetch_all_branches = 1;
2298 break;
2299 case 'b':
2300 error = got_pathlist_append(&wanted_branches,
2301 optarg, NULL);
2302 if (error)
2303 return error;
2304 break;
2305 case 'd':
2306 delete_refs = 1;
2307 break;
2308 case 'l':
2309 list_refs_only = 1;
2310 break;
2311 case 'r':
2312 repo_path = realpath(optarg, NULL);
2313 if (repo_path == NULL)
2314 return got_error_from_errno2("realpath",
2315 optarg);
2316 got_path_strip_trailing_slashes(repo_path);
2317 break;
2318 case 't':
2319 replace_tags = 1;
2320 break;
2321 case 'v':
2322 if (verbosity < 0)
2323 verbosity = 0;
2324 else if (verbosity < 3)
2325 verbosity++;
2326 break;
2327 case 'q':
2328 verbosity = -1;
2329 break;
2330 case 'R':
2331 error = got_pathlist_append(&wanted_refs,
2332 optarg, NULL);
2333 if (error)
2334 return error;
2335 break;
2336 case 'X':
2337 delete_remote = 1;
2338 break;
2339 default:
2340 usage_fetch();
2341 break;
2344 argc -= optind;
2345 argv += optind;
2347 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2348 option_conflict('a', 'b');
2349 if (list_refs_only) {
2350 if (!TAILQ_EMPTY(&wanted_branches))
2351 option_conflict('l', 'b');
2352 if (fetch_all_branches)
2353 option_conflict('l', 'a');
2354 if (delete_refs)
2355 option_conflict('l', 'd');
2356 if (delete_remote)
2357 option_conflict('l', 'X');
2359 if (delete_remote) {
2360 if (fetch_all_branches)
2361 option_conflict('X', 'a');
2362 if (!TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('X', 'b');
2364 if (delete_refs)
2365 option_conflict('X', 'd');
2366 if (replace_tags)
2367 option_conflict('X', 't');
2368 if (!TAILQ_EMPTY(&wanted_refs))
2369 option_conflict('X', 'R');
2372 if (argc == 0) {
2373 if (delete_remote)
2374 errx(1, "-X option requires a remote name");
2375 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2376 } else if (argc == 1)
2377 remote_name = argv[0];
2378 else
2379 usage_fetch();
2381 cwd = getcwd(NULL, 0);
2382 if (cwd == NULL) {
2383 error = got_error_from_errno("getcwd");
2384 goto done;
2387 error = got_repo_pack_fds_open(&pack_fds);
2388 if (error != NULL)
2389 goto done;
2391 if (repo_path == NULL) {
2392 error = got_worktree_open(&worktree, cwd);
2393 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2394 goto done;
2395 else
2396 error = NULL;
2397 if (worktree) {
2398 repo_path =
2399 strdup(got_worktree_get_repo_path(worktree));
2400 if (repo_path == NULL)
2401 error = got_error_from_errno("strdup");
2402 if (error)
2403 goto done;
2404 } else {
2405 repo_path = strdup(cwd);
2406 if (repo_path == NULL) {
2407 error = got_error_from_errno("strdup");
2408 goto done;
2413 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2414 if (error)
2415 goto done;
2417 if (delete_remote) {
2418 error = delete_refs_for_remote(repo, remote_name);
2419 goto done; /* nothing else to do */
2422 if (worktree) {
2423 worktree_conf = got_worktree_get_gotconfig(worktree);
2424 if (worktree_conf) {
2425 got_gotconfig_get_remotes(&nremotes, &remotes,
2426 worktree_conf);
2427 for (i = 0; i < nremotes; i++) {
2428 if (strcmp(remotes[i].name, remote_name) == 0) {
2429 remote = &remotes[i];
2430 break;
2435 if (remote == NULL) {
2436 repo_conf = got_repo_get_gotconfig(repo);
2437 if (repo_conf) {
2438 got_gotconfig_get_remotes(&nremotes, &remotes,
2439 repo_conf);
2440 for (i = 0; i < nremotes; i++) {
2441 if (strcmp(remotes[i].name, remote_name) == 0) {
2442 remote = &remotes[i];
2443 break;
2448 if (remote == NULL) {
2449 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 remote = &remotes[i];
2453 break;
2457 if (remote == NULL) {
2458 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2459 goto done;
2462 if (TAILQ_EMPTY(&wanted_branches)) {
2463 if (!fetch_all_branches)
2464 fetch_all_branches = remote->fetch_all_branches;
2465 for (i = 0; i < remote->nfetch_branches; i++) {
2466 got_pathlist_append(&wanted_branches,
2467 remote->fetch_branches[i], NULL);
2470 if (TAILQ_EMPTY(&wanted_refs)) {
2471 for (i = 0; i < remote->nfetch_refs; i++) {
2472 got_pathlist_append(&wanted_refs,
2473 remote->fetch_refs[i], NULL);
2477 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2478 &repo_name, remote->fetch_url);
2479 if (error)
2480 goto done;
2482 if (strcmp(proto, "git") == 0) {
2483 #ifndef PROFILE
2484 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2485 "sendfd dns inet unveil", NULL) == -1)
2486 err(1, "pledge");
2487 #endif
2488 } else if (strcmp(proto, "git+ssh") == 0 ||
2489 strcmp(proto, "ssh") == 0) {
2490 #ifndef PROFILE
2491 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2492 "sendfd unveil", NULL) == -1)
2493 err(1, "pledge");
2494 #endif
2495 } else if (strcmp(proto, "http") == 0 ||
2496 strcmp(proto, "git+http") == 0) {
2497 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2498 goto done;
2499 } else {
2500 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2501 goto done;
2504 error = got_dial_apply_unveil(proto);
2505 if (error)
2506 goto done;
2508 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2509 if (error)
2510 goto done;
2512 if (verbosity >= 0)
2513 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2514 port ? ":" : "", port ? port : "");
2516 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2517 server_path, verbosity);
2518 if (error)
2519 goto done;
2521 fpa.last_scaled_size[0] = '\0';
2522 fpa.last_p_indexed = -1;
2523 fpa.last_p_resolved = -1;
2524 fpa.verbosity = verbosity;
2525 fpa.repo = repo;
2526 fpa.create_configs = 0;
2527 fpa.configs_created = 0;
2528 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2529 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2530 remote->mirror_references, fetch_all_branches, &wanted_branches,
2531 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2532 fetch_progress, &fpa);
2533 if (error)
2534 goto done;
2536 if (list_refs_only) {
2537 error = list_remote_refs(&symrefs, &refs);
2538 goto done;
2541 if (pack_hash == NULL) {
2542 if (verbosity >= 0)
2543 printf("Already up-to-date\n");
2544 } else if (verbosity >= 0) {
2545 error = got_object_id_str(&id_str, pack_hash);
2546 if (error)
2547 goto done;
2548 printf("\nFetched %s.pack\n", id_str);
2549 free(id_str);
2550 id_str = NULL;
2553 /* Update references provided with the pack file. */
2554 TAILQ_FOREACH(pe, &refs, entry) {
2555 const char *refname = pe->path;
2556 struct got_object_id *id = pe->data;
2557 struct got_reference *ref;
2558 char *remote_refname;
2560 if (is_wanted_ref(&wanted_refs, refname) &&
2561 !remote->mirror_references) {
2562 error = update_wanted_ref(refname, id,
2563 remote->name, verbosity, repo);
2564 if (error)
2565 goto done;
2566 continue;
2569 if (remote->mirror_references ||
2570 strncmp("refs/tags/", refname, 10) == 0) {
2571 error = got_ref_open(&ref, repo, refname, 1);
2572 if (error) {
2573 if (error->code != GOT_ERR_NOT_REF)
2574 goto done;
2575 error = create_ref(refname, id, verbosity,
2576 repo);
2577 if (error)
2578 goto done;
2579 } else {
2580 error = update_ref(ref, id, replace_tags,
2581 verbosity, repo);
2582 unlock_err = got_ref_unlock(ref);
2583 if (unlock_err && error == NULL)
2584 error = unlock_err;
2585 got_ref_close(ref);
2586 if (error)
2587 goto done;
2589 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2590 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2591 remote_name, refname + 11) == -1) {
2592 error = got_error_from_errno("asprintf");
2593 goto done;
2596 error = got_ref_open(&ref, repo, remote_refname, 1);
2597 if (error) {
2598 if (error->code != GOT_ERR_NOT_REF)
2599 goto done;
2600 error = create_ref(remote_refname, id,
2601 verbosity, repo);
2602 if (error)
2603 goto done;
2604 } else {
2605 error = update_ref(ref, id, replace_tags,
2606 verbosity, repo);
2607 unlock_err = got_ref_unlock(ref);
2608 if (unlock_err && error == NULL)
2609 error = unlock_err;
2610 got_ref_close(ref);
2611 if (error)
2612 goto done;
2615 /* Also create a local branch if none exists yet. */
2616 error = got_ref_open(&ref, repo, refname, 1);
2617 if (error) {
2618 if (error->code != GOT_ERR_NOT_REF)
2619 goto done;
2620 error = create_ref(refname, id, verbosity,
2621 repo);
2622 if (error)
2623 goto done;
2624 } else {
2625 unlock_err = got_ref_unlock(ref);
2626 if (unlock_err && error == NULL)
2627 error = unlock_err;
2628 got_ref_close(ref);
2632 if (delete_refs) {
2633 error = delete_missing_refs(&refs, &symrefs, remote,
2634 verbosity, repo);
2635 if (error)
2636 goto done;
2639 if (!remote->mirror_references) {
2640 /* Update remote HEAD reference if the server provided one. */
2641 TAILQ_FOREACH(pe, &symrefs, entry) {
2642 struct got_reference *target_ref;
2643 const char *refname = pe->path;
2644 const char *target = pe->data;
2645 char *remote_refname = NULL, *remote_target = NULL;
2647 if (strcmp(refname, GOT_REF_HEAD) != 0)
2648 continue;
2650 if (strncmp("refs/heads/", target, 11) != 0)
2651 continue;
2653 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2654 remote->name, refname) == -1) {
2655 error = got_error_from_errno("asprintf");
2656 goto done;
2658 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2659 remote->name, target + 11) == -1) {
2660 error = got_error_from_errno("asprintf");
2661 free(remote_refname);
2662 goto done;
2665 error = got_ref_open(&target_ref, repo, remote_target,
2666 0);
2667 if (error) {
2668 free(remote_refname);
2669 free(remote_target);
2670 if (error->code == GOT_ERR_NOT_REF) {
2671 error = NULL;
2672 continue;
2674 goto done;
2676 error = update_symref(remote_refname, target_ref,
2677 verbosity, repo);
2678 free(remote_refname);
2679 free(remote_target);
2680 got_ref_close(target_ref);
2681 if (error)
2682 goto done;
2685 done:
2686 if (fetchpid > 0) {
2687 if (kill(fetchpid, SIGTERM) == -1)
2688 error = got_error_from_errno("kill");
2689 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2690 error = got_error_from_errno("waitpid");
2692 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2693 error = got_error_from_errno("close");
2694 if (repo) {
2695 const struct got_error *close_err = got_repo_close(repo);
2696 if (error == NULL)
2697 error = close_err;
2699 if (worktree)
2700 got_worktree_close(worktree);
2701 if (pack_fds) {
2702 const struct got_error *pack_err =
2703 got_repo_pack_fds_close(pack_fds);
2704 if (error == NULL)
2705 error = pack_err;
2707 TAILQ_FOREACH(pe, &refs, entry) {
2708 free((void *)pe->path);
2709 free(pe->data);
2711 got_pathlist_free(&refs);
2712 TAILQ_FOREACH(pe, &symrefs, entry) {
2713 free((void *)pe->path);
2714 free(pe->data);
2716 got_pathlist_free(&symrefs);
2717 got_pathlist_free(&wanted_branches);
2718 got_pathlist_free(&wanted_refs);
2719 free(id_str);
2720 free(cwd);
2721 free(repo_path);
2722 free(pack_hash);
2723 free(proto);
2724 free(host);
2725 free(port);
2726 free(server_path);
2727 free(repo_name);
2728 return error;
2732 __dead static void
2733 usage_checkout(void)
2735 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2736 "[-p path-prefix] repository-path [work-tree-path]\n",
2737 getprogname());
2738 exit(1);
2741 static void
2742 show_worktree_base_ref_warning(void)
2744 fprintf(stderr, "%s: warning: could not create a reference "
2745 "to the work tree's base commit; the commit could be "
2746 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2747 "repository writable and running 'got update' will prevent this\n",
2748 getprogname());
2751 struct got_checkout_progress_arg {
2752 const char *worktree_path;
2753 int had_base_commit_ref_error;
2754 int verbosity;
2757 static const struct got_error *
2758 checkout_progress(void *arg, unsigned char status, const char *path)
2760 struct got_checkout_progress_arg *a = arg;
2762 /* Base commit bump happens silently. */
2763 if (status == GOT_STATUS_BUMP_BASE)
2764 return NULL;
2766 if (status == GOT_STATUS_BASE_REF_ERR) {
2767 a->had_base_commit_ref_error = 1;
2768 return NULL;
2771 while (path[0] == '/')
2772 path++;
2774 if (a->verbosity >= 0)
2775 printf("%c %s/%s\n", status, a->worktree_path, path);
2777 return NULL;
2780 static const struct got_error *
2781 check_cancelled(void *arg)
2783 if (sigint_received || sigpipe_received)
2784 return got_error(GOT_ERR_CANCELLED);
2785 return NULL;
2788 static const struct got_error *
2789 check_linear_ancestry(struct got_object_id *commit_id,
2790 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2791 struct got_repository *repo)
2793 const struct got_error *err = NULL;
2794 struct got_object_id *yca_id;
2796 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2797 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2798 if (err)
2799 return err;
2801 if (yca_id == NULL)
2802 return got_error(GOT_ERR_ANCESTRY);
2805 * Require a straight line of history between the target commit
2806 * and the work tree's base commit.
2808 * Non-linear situations such as this require a rebase:
2810 * (commit) D F (base_commit)
2811 * \ /
2812 * C E
2813 * \ /
2814 * B (yca)
2815 * |
2816 * A
2818 * 'got update' only handles linear cases:
2819 * Update forwards in time: A (base/yca) - B - C - D (commit)
2820 * Update backwards in time: D (base) - C - B - A (commit/yca)
2822 if (allow_forwards_in_time_only) {
2823 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2824 return got_error(GOT_ERR_ANCESTRY);
2825 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2826 got_object_id_cmp(base_commit_id, yca_id) != 0)
2827 return got_error(GOT_ERR_ANCESTRY);
2829 free(yca_id);
2830 return NULL;
2833 static const struct got_error *
2834 check_same_branch(struct got_object_id *commit_id,
2835 struct got_reference *head_ref, struct got_object_id *yca_id,
2836 struct got_repository *repo)
2838 const struct got_error *err = NULL;
2839 struct got_commit_graph *graph = NULL;
2840 struct got_object_id *head_commit_id = NULL;
2841 int is_same_branch = 0;
2843 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2844 if (err)
2845 goto done;
2847 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2848 is_same_branch = 1;
2849 goto done;
2851 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2852 is_same_branch = 1;
2853 goto done;
2856 err = got_commit_graph_open(&graph, "/", 1);
2857 if (err)
2858 goto done;
2860 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2861 check_cancelled, NULL);
2862 if (err)
2863 goto done;
2865 for (;;) {
2866 struct got_object_id *id;
2867 err = got_commit_graph_iter_next(&id, graph, repo,
2868 check_cancelled, NULL);
2869 if (err) {
2870 if (err->code == GOT_ERR_ITER_COMPLETED)
2871 err = NULL;
2872 break;
2875 if (id) {
2876 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2877 break;
2878 if (got_object_id_cmp(id, commit_id) == 0) {
2879 is_same_branch = 1;
2880 break;
2884 done:
2885 if (graph)
2886 got_commit_graph_close(graph);
2887 free(head_commit_id);
2888 if (!err && !is_same_branch)
2889 err = got_error(GOT_ERR_ANCESTRY);
2890 return err;
2893 static const struct got_error *
2894 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2896 static char msg[512];
2897 const char *branch_name;
2899 if (got_ref_is_symbolic(ref))
2900 branch_name = got_ref_get_symref_target(ref);
2901 else
2902 branch_name = got_ref_get_name(ref);
2904 if (strncmp("refs/heads/", branch_name, 11) == 0)
2905 branch_name += 11;
2907 snprintf(msg, sizeof(msg),
2908 "target commit is not contained in branch '%s'; "
2909 "the branch to use must be specified with -b; "
2910 "if necessary a new branch can be created for "
2911 "this commit with 'got branch -c %s BRANCH_NAME'",
2912 branch_name, commit_id_str);
2914 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2917 static const struct got_error *
2918 cmd_checkout(int argc, char *argv[])
2920 const struct got_error *error = NULL;
2921 struct got_repository *repo = NULL;
2922 struct got_reference *head_ref = NULL, *ref = NULL;
2923 struct got_worktree *worktree = NULL;
2924 char *repo_path = NULL;
2925 char *worktree_path = NULL;
2926 const char *path_prefix = "";
2927 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2928 char *commit_id_str = NULL;
2929 struct got_object_id *commit_id = NULL;
2930 char *cwd = NULL;
2931 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2932 struct got_pathlist_head paths;
2933 struct got_checkout_progress_arg cpa;
2934 int *pack_fds = NULL;
2936 TAILQ_INIT(&paths);
2938 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2939 switch (ch) {
2940 case 'b':
2941 branch_name = optarg;
2942 break;
2943 case 'c':
2944 commit_id_str = strdup(optarg);
2945 if (commit_id_str == NULL)
2946 return got_error_from_errno("strdup");
2947 break;
2948 case 'E':
2949 allow_nonempty = 1;
2950 break;
2951 case 'p':
2952 path_prefix = optarg;
2953 break;
2954 case 'q':
2955 verbosity = -1;
2956 break;
2957 default:
2958 usage_checkout();
2959 /* NOTREACHED */
2963 argc -= optind;
2964 argv += optind;
2966 #ifndef PROFILE
2967 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2968 "unveil", NULL) == -1)
2969 err(1, "pledge");
2970 #endif
2971 if (argc == 1) {
2972 char *base, *dotgit;
2973 const char *path;
2974 repo_path = realpath(argv[0], NULL);
2975 if (repo_path == NULL)
2976 return got_error_from_errno2("realpath", argv[0]);
2977 cwd = getcwd(NULL, 0);
2978 if (cwd == NULL) {
2979 error = got_error_from_errno("getcwd");
2980 goto done;
2982 if (path_prefix[0])
2983 path = path_prefix;
2984 else
2985 path = repo_path;
2986 error = got_path_basename(&base, path);
2987 if (error)
2988 goto done;
2989 dotgit = strstr(base, ".git");
2990 if (dotgit)
2991 *dotgit = '\0';
2992 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2993 error = got_error_from_errno("asprintf");
2994 free(base);
2995 goto done;
2997 free(base);
2998 } else if (argc == 2) {
2999 repo_path = realpath(argv[0], NULL);
3000 if (repo_path == NULL) {
3001 error = got_error_from_errno2("realpath", argv[0]);
3002 goto done;
3004 worktree_path = realpath(argv[1], NULL);
3005 if (worktree_path == NULL) {
3006 if (errno != ENOENT) {
3007 error = got_error_from_errno2("realpath",
3008 argv[1]);
3009 goto done;
3011 worktree_path = strdup(argv[1]);
3012 if (worktree_path == NULL) {
3013 error = got_error_from_errno("strdup");
3014 goto done;
3017 } else
3018 usage_checkout();
3020 got_path_strip_trailing_slashes(repo_path);
3021 got_path_strip_trailing_slashes(worktree_path);
3023 error = got_repo_pack_fds_open(&pack_fds);
3024 if (error != NULL)
3025 goto done;
3027 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3028 if (error != NULL)
3029 goto done;
3031 /* Pre-create work tree path for unveil(2) */
3032 error = got_path_mkdir(worktree_path);
3033 if (error) {
3034 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3035 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3036 goto done;
3037 if (!allow_nonempty &&
3038 !got_path_dir_is_empty(worktree_path)) {
3039 error = got_error_path(worktree_path,
3040 GOT_ERR_DIR_NOT_EMPTY);
3041 goto done;
3045 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3046 if (error)
3047 goto done;
3049 error = got_ref_open(&head_ref, repo, branch_name, 0);
3050 if (error != NULL)
3051 goto done;
3053 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3054 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3055 goto done;
3057 error = got_worktree_open(&worktree, worktree_path);
3058 if (error != NULL)
3059 goto done;
3061 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3062 path_prefix);
3063 if (error != NULL)
3064 goto done;
3065 if (!same_path_prefix) {
3066 error = got_error(GOT_ERR_PATH_PREFIX);
3067 goto done;
3070 if (commit_id_str) {
3071 struct got_reflist_head refs;
3072 TAILQ_INIT(&refs);
3073 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3074 NULL);
3075 if (error)
3076 goto done;
3077 error = got_repo_match_object_id(&commit_id, NULL,
3078 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3079 got_ref_list_free(&refs);
3080 if (error)
3081 goto done;
3082 error = check_linear_ancestry(commit_id,
3083 got_worktree_get_base_commit_id(worktree), 0, repo);
3084 if (error != NULL) {
3085 if (error->code == GOT_ERR_ANCESTRY) {
3086 error = checkout_ancestry_error(
3087 head_ref, commit_id_str);
3089 goto done;
3091 error = check_same_branch(commit_id, head_ref, NULL, repo);
3092 if (error) {
3093 if (error->code == GOT_ERR_ANCESTRY) {
3094 error = checkout_ancestry_error(
3095 head_ref, commit_id_str);
3097 goto done;
3099 error = got_worktree_set_base_commit_id(worktree, repo,
3100 commit_id);
3101 if (error)
3102 goto done;
3103 /* Expand potentially abbreviated commit ID string. */
3104 free(commit_id_str);
3105 error = got_object_id_str(&commit_id_str, commit_id);
3106 if (error)
3107 goto done;
3108 } else {
3109 commit_id = got_object_id_dup(
3110 got_worktree_get_base_commit_id(worktree));
3111 if (commit_id == NULL) {
3112 error = got_error_from_errno("got_object_id_dup");
3113 goto done;
3115 error = got_object_id_str(&commit_id_str, commit_id);
3116 if (error)
3117 goto done;
3120 error = got_pathlist_append(&paths, "", NULL);
3121 if (error)
3122 goto done;
3123 cpa.worktree_path = worktree_path;
3124 cpa.had_base_commit_ref_error = 0;
3125 cpa.verbosity = verbosity;
3126 error = got_worktree_checkout_files(worktree, &paths, repo,
3127 checkout_progress, &cpa, check_cancelled, NULL);
3128 if (error != NULL)
3129 goto done;
3131 if (got_ref_is_symbolic(head_ref)) {
3132 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3133 if (error)
3134 goto done;
3135 refname = got_ref_get_name(ref);
3136 } else
3137 refname = got_ref_get_name(head_ref);
3138 printf("Checked out %s: %s\n", refname, commit_id_str);
3139 printf("Now shut up and hack\n");
3140 if (cpa.had_base_commit_ref_error)
3141 show_worktree_base_ref_warning();
3142 done:
3143 if (pack_fds) {
3144 const struct got_error *pack_err =
3145 got_repo_pack_fds_close(pack_fds);
3146 if (error == NULL)
3147 error = pack_err;
3149 if (head_ref)
3150 got_ref_close(head_ref);
3151 if (ref)
3152 got_ref_close(ref);
3153 got_pathlist_free(&paths);
3154 free(commit_id_str);
3155 free(commit_id);
3156 free(repo_path);
3157 free(worktree_path);
3158 free(cwd);
3159 return error;
3162 struct got_update_progress_arg {
3163 int did_something;
3164 int conflicts;
3165 int obstructed;
3166 int not_updated;
3167 int missing;
3168 int not_deleted;
3169 int unversioned;
3170 int verbosity;
3173 static void
3174 print_update_progress_stats(struct got_update_progress_arg *upa)
3176 if (!upa->did_something)
3177 return;
3179 if (upa->conflicts > 0)
3180 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3181 if (upa->obstructed > 0)
3182 printf("File paths obstructed by a non-regular file: %d\n",
3183 upa->obstructed);
3184 if (upa->not_updated > 0)
3185 printf("Files not updated because of existing merge "
3186 "conflicts: %d\n", upa->not_updated);
3190 * The meaning of some status codes differs between merge-style operations and
3191 * update operations. For example, the ! status code means "file was missing"
3192 * if changes were merged into the work tree, and "missing file was restored"
3193 * if the work tree was updated. This function should be used by any operation
3194 * which merges changes into the work tree without updating the work tree.
3196 static void
3197 print_merge_progress_stats(struct got_update_progress_arg *upa)
3199 if (!upa->did_something)
3200 return;
3202 if (upa->conflicts > 0)
3203 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3204 if (upa->obstructed > 0)
3205 printf("File paths obstructed by a non-regular file: %d\n",
3206 upa->obstructed);
3207 if (upa->missing > 0)
3208 printf("Files which had incoming changes but could not be "
3209 "found in the work tree: %d\n", upa->missing);
3210 if (upa->not_deleted > 0)
3211 printf("Files not deleted due to differences in deleted "
3212 "content: %d\n", upa->not_deleted);
3213 if (upa->unversioned > 0)
3214 printf("Files not merged because an unversioned file was "
3215 "found in the work tree: %d\n", upa->unversioned);
3218 __dead static void
3219 usage_update(void)
3221 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3222 "[path ...]\n", getprogname());
3223 exit(1);
3226 static const struct got_error *
3227 update_progress(void *arg, unsigned char status, const char *path)
3229 struct got_update_progress_arg *upa = arg;
3231 if (status == GOT_STATUS_EXISTS ||
3232 status == GOT_STATUS_BASE_REF_ERR)
3233 return NULL;
3235 upa->did_something = 1;
3237 /* Base commit bump happens silently. */
3238 if (status == GOT_STATUS_BUMP_BASE)
3239 return NULL;
3241 if (status == GOT_STATUS_CONFLICT)
3242 upa->conflicts++;
3243 if (status == GOT_STATUS_OBSTRUCTED)
3244 upa->obstructed++;
3245 if (status == GOT_STATUS_CANNOT_UPDATE)
3246 upa->not_updated++;
3247 if (status == GOT_STATUS_MISSING)
3248 upa->missing++;
3249 if (status == GOT_STATUS_CANNOT_DELETE)
3250 upa->not_deleted++;
3251 if (status == GOT_STATUS_UNVERSIONED)
3252 upa->unversioned++;
3254 while (path[0] == '/')
3255 path++;
3256 if (upa->verbosity >= 0)
3257 printf("%c %s\n", status, path);
3259 return NULL;
3262 static const struct got_error *
3263 switch_head_ref(struct got_reference *head_ref,
3264 struct got_object_id *commit_id, struct got_worktree *worktree,
3265 struct got_repository *repo)
3267 const struct got_error *err = NULL;
3268 char *base_id_str;
3269 int ref_has_moved = 0;
3271 /* Trivial case: switching between two different references. */
3272 if (strcmp(got_ref_get_name(head_ref),
3273 got_worktree_get_head_ref_name(worktree)) != 0) {
3274 printf("Switching work tree from %s to %s\n",
3275 got_worktree_get_head_ref_name(worktree),
3276 got_ref_get_name(head_ref));
3277 return got_worktree_set_head_ref(worktree, head_ref);
3280 err = check_linear_ancestry(commit_id,
3281 got_worktree_get_base_commit_id(worktree), 0, repo);
3282 if (err) {
3283 if (err->code != GOT_ERR_ANCESTRY)
3284 return err;
3285 ref_has_moved = 1;
3287 if (!ref_has_moved)
3288 return NULL;
3290 /* Switching to a rebased branch with the same reference name. */
3291 err = got_object_id_str(&base_id_str,
3292 got_worktree_get_base_commit_id(worktree));
3293 if (err)
3294 return err;
3295 printf("Reference %s now points at a different branch\n",
3296 got_worktree_get_head_ref_name(worktree));
3297 printf("Switching work tree from %s to %s\n", base_id_str,
3298 got_worktree_get_head_ref_name(worktree));
3299 return NULL;
3302 static const struct got_error *
3303 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3305 const struct got_error *err;
3306 int in_progress;
3308 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3309 if (err)
3310 return err;
3311 if (in_progress)
3312 return got_error(GOT_ERR_REBASING);
3314 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3315 if (err)
3316 return err;
3317 if (in_progress)
3318 return got_error(GOT_ERR_HISTEDIT_BUSY);
3320 return NULL;
3323 static const struct got_error *
3324 check_merge_in_progress(struct got_worktree *worktree,
3325 struct got_repository *repo)
3327 const struct got_error *err;
3328 int in_progress;
3330 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3331 if (err)
3332 return err;
3333 if (in_progress)
3334 return got_error(GOT_ERR_MERGE_BUSY);
3336 return NULL;
3339 static const struct got_error *
3340 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3341 char *argv[], struct got_worktree *worktree)
3343 const struct got_error *err = NULL;
3344 char *path;
3345 struct got_pathlist_entry *new;
3346 int i;
3348 if (argc == 0) {
3349 path = strdup("");
3350 if (path == NULL)
3351 return got_error_from_errno("strdup");
3352 return got_pathlist_append(paths, path, NULL);
3355 for (i = 0; i < argc; i++) {
3356 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3357 if (err)
3358 break;
3359 err = got_pathlist_insert(&new, paths, path, NULL);
3360 if (err || new == NULL /* duplicate */) {
3361 free(path);
3362 if (err)
3363 break;
3367 return err;
3370 static const struct got_error *
3371 wrap_not_worktree_error(const struct got_error *orig_err,
3372 const char *cmdname, const char *path)
3374 const struct got_error *err;
3375 struct got_repository *repo;
3376 static char msg[512];
3377 int *pack_fds = NULL;
3379 err = got_repo_pack_fds_open(&pack_fds);
3380 if (err)
3381 return err;
3383 err = got_repo_open(&repo, path, NULL, pack_fds);
3384 if (err)
3385 return orig_err;
3387 snprintf(msg, sizeof(msg),
3388 "'got %s' needs a work tree in addition to a git repository\n"
3389 "Work trees can be checked out from this Git repository with "
3390 "'got checkout'.\n"
3391 "The got(1) manual page contains more information.", cmdname);
3392 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3393 got_repo_close(repo);
3394 if (pack_fds) {
3395 const struct got_error *pack_err =
3396 got_repo_pack_fds_close(pack_fds);
3397 if (err == NULL)
3398 err = pack_err;
3400 return err;
3403 static const struct got_error *
3404 cmd_update(int argc, char *argv[])
3406 const struct got_error *error = NULL;
3407 struct got_repository *repo = NULL;
3408 struct got_worktree *worktree = NULL;
3409 char *worktree_path = NULL;
3410 struct got_object_id *commit_id = NULL;
3411 char *commit_id_str = NULL;
3412 const char *branch_name = NULL;
3413 struct got_reference *head_ref = NULL;
3414 struct got_pathlist_head paths;
3415 struct got_pathlist_entry *pe;
3416 int ch, verbosity = 0;
3417 struct got_update_progress_arg upa;
3418 int *pack_fds = NULL;
3420 TAILQ_INIT(&paths);
3422 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3423 switch (ch) {
3424 case 'b':
3425 branch_name = optarg;
3426 break;
3427 case 'c':
3428 commit_id_str = strdup(optarg);
3429 if (commit_id_str == NULL)
3430 return got_error_from_errno("strdup");
3431 break;
3432 case 'q':
3433 verbosity = -1;
3434 break;
3435 default:
3436 usage_update();
3437 /* NOTREACHED */
3441 argc -= optind;
3442 argv += optind;
3444 #ifndef PROFILE
3445 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3446 "unveil", NULL) == -1)
3447 err(1, "pledge");
3448 #endif
3449 worktree_path = getcwd(NULL, 0);
3450 if (worktree_path == NULL) {
3451 error = got_error_from_errno("getcwd");
3452 goto done;
3455 error = got_repo_pack_fds_open(&pack_fds);
3456 if (error != NULL)
3457 goto done;
3459 error = got_worktree_open(&worktree, worktree_path);
3460 if (error) {
3461 if (error->code == GOT_ERR_NOT_WORKTREE)
3462 error = wrap_not_worktree_error(error, "update",
3463 worktree_path);
3464 goto done;
3467 error = check_rebase_or_histedit_in_progress(worktree);
3468 if (error)
3469 goto done;
3471 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3472 NULL, pack_fds);
3473 if (error != NULL)
3474 goto done;
3476 error = apply_unveil(got_repo_get_path(repo), 0,
3477 got_worktree_get_root_path(worktree));
3478 if (error)
3479 goto done;
3481 error = check_merge_in_progress(worktree, repo);
3482 if (error)
3483 goto done;
3485 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3486 if (error)
3487 goto done;
3489 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3490 got_worktree_get_head_ref_name(worktree), 0);
3491 if (error != NULL)
3492 goto done;
3493 if (commit_id_str == NULL) {
3494 error = got_ref_resolve(&commit_id, repo, head_ref);
3495 if (error != NULL)
3496 goto done;
3497 error = got_object_id_str(&commit_id_str, commit_id);
3498 if (error != NULL)
3499 goto done;
3500 } else {
3501 struct got_reflist_head refs;
3502 TAILQ_INIT(&refs);
3503 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3504 NULL);
3505 if (error)
3506 goto done;
3507 error = got_repo_match_object_id(&commit_id, NULL,
3508 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3509 got_ref_list_free(&refs);
3510 free(commit_id_str);
3511 commit_id_str = NULL;
3512 if (error)
3513 goto done;
3514 error = got_object_id_str(&commit_id_str, commit_id);
3515 if (error)
3516 goto done;
3519 if (branch_name) {
3520 struct got_object_id *head_commit_id;
3521 TAILQ_FOREACH(pe, &paths, entry) {
3522 if (pe->path_len == 0)
3523 continue;
3524 error = got_error_msg(GOT_ERR_BAD_PATH,
3525 "switching between branches requires that "
3526 "the entire work tree gets updated");
3527 goto done;
3529 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3530 if (error)
3531 goto done;
3532 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3533 repo);
3534 free(head_commit_id);
3535 if (error != NULL)
3536 goto done;
3537 error = check_same_branch(commit_id, head_ref, NULL, repo);
3538 if (error)
3539 goto done;
3540 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3541 if (error)
3542 goto done;
3543 } else {
3544 error = check_linear_ancestry(commit_id,
3545 got_worktree_get_base_commit_id(worktree), 0, repo);
3546 if (error != NULL) {
3547 if (error->code == GOT_ERR_ANCESTRY)
3548 error = got_error(GOT_ERR_BRANCH_MOVED);
3549 goto done;
3551 error = check_same_branch(commit_id, head_ref, NULL, repo);
3552 if (error)
3553 goto done;
3556 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3557 commit_id) != 0) {
3558 error = got_worktree_set_base_commit_id(worktree, repo,
3559 commit_id);
3560 if (error)
3561 goto done;
3564 memset(&upa, 0, sizeof(upa));
3565 upa.verbosity = verbosity;
3566 error = got_worktree_checkout_files(worktree, &paths, repo,
3567 update_progress, &upa, check_cancelled, NULL);
3568 if (error != NULL)
3569 goto done;
3571 if (upa.did_something) {
3572 printf("Updated to %s: %s\n",
3573 got_worktree_get_head_ref_name(worktree), commit_id_str);
3574 } else
3575 printf("Already up-to-date\n");
3577 print_update_progress_stats(&upa);
3578 done:
3579 if (pack_fds) {
3580 const struct got_error *pack_err =
3581 got_repo_pack_fds_close(pack_fds);
3582 if (error == NULL)
3583 error = pack_err;
3585 free(worktree_path);
3586 TAILQ_FOREACH(pe, &paths, entry)
3587 free((char *)pe->path);
3588 got_pathlist_free(&paths);
3589 free(commit_id);
3590 free(commit_id_str);
3591 return error;
3594 static const struct got_error *
3595 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3596 const char *path, int diff_context, int ignore_whitespace,
3597 int force_text_diff, struct got_repository *repo, FILE *outfile)
3599 const struct got_error *err = NULL;
3600 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3601 FILE *f1 = NULL, *f2 = NULL;
3602 int fd1 = -1, fd2 = -1;
3604 fd1 = got_opentempfd();
3605 if (fd1 == -1)
3606 return got_error_from_errno("got_opentempfd");
3607 fd2 = got_opentempfd();
3608 if (fd2 == -1) {
3609 err = got_error_from_errno("got_opentempfd");
3610 goto done;
3613 if (blob_id1) {
3614 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3615 fd1);
3616 if (err)
3617 goto done;
3620 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3621 if (err)
3622 goto done;
3624 f1 = got_opentemp();
3625 if (f1 == NULL) {
3626 err = got_error_from_errno("got_opentemp");
3627 goto done;
3629 f2 = got_opentemp();
3630 if (f2 == NULL) {
3631 err = got_error_from_errno("got_opentemp");
3632 goto done;
3635 while (path[0] == '/')
3636 path++;
3637 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3638 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3639 force_text_diff, outfile);
3640 done:
3641 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3642 err = got_error_from_errno("close");
3643 if (blob1)
3644 got_object_blob_close(blob1);
3645 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3646 err = got_error_from_errno("close");
3647 got_object_blob_close(blob2);
3648 if (f1 && fclose(f1) == EOF && err == NULL)
3649 err = got_error_from_errno("fclose");
3650 if (f2 && fclose(f2) == EOF && err == NULL)
3651 err = got_error_from_errno("fclose");
3652 return err;
3655 static const struct got_error *
3656 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3657 const char *path, int diff_context, int ignore_whitespace,
3658 int force_text_diff, struct got_repository *repo, FILE *outfile)
3660 const struct got_error *err = NULL;
3661 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3662 struct got_diff_blob_output_unidiff_arg arg;
3663 FILE *f1 = NULL, *f2 = NULL;
3664 int fd1 = -1, fd2 = -1;
3666 if (tree_id1) {
3667 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3668 if (err)
3669 goto done;
3670 fd1 = got_opentempfd();
3671 if (fd1 == -1) {
3672 err = got_error_from_errno("got_opentempfd");
3673 goto done;
3677 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3678 if (err)
3679 goto done;
3681 f1 = got_opentemp();
3682 if (f1 == NULL) {
3683 err = got_error_from_errno("got_opentemp");
3684 goto done;
3687 f2 = got_opentemp();
3688 if (f2 == NULL) {
3689 err = got_error_from_errno("got_opentemp");
3690 goto done;
3692 fd2 = got_opentempfd();
3693 if (fd2 == -1) {
3694 err = got_error_from_errno("got_opentempfd");
3695 goto done;
3697 arg.diff_context = diff_context;
3698 arg.ignore_whitespace = ignore_whitespace;
3699 arg.force_text_diff = force_text_diff;
3700 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3701 arg.outfile = outfile;
3702 arg.lines = NULL;
3703 arg.nlines = 0;
3704 while (path[0] == '/')
3705 path++;
3706 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3707 got_diff_blob_output_unidiff, &arg, 1);
3708 done:
3709 if (tree1)
3710 got_object_tree_close(tree1);
3711 if (tree2)
3712 got_object_tree_close(tree2);
3713 if (f1 && fclose(f1) == EOF && err == NULL)
3714 err = got_error_from_errno("fclose");
3715 if (f2 && fclose(f2) == EOF && err == NULL)
3716 err = got_error_from_errno("fclose");
3717 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3718 err = got_error_from_errno("close");
3719 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3720 err = got_error_from_errno("close");
3721 return err;
3724 static const struct got_error *
3725 get_changed_paths(struct got_pathlist_head *paths,
3726 struct got_commit_object *commit, struct got_repository *repo)
3728 const struct got_error *err = NULL;
3729 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3730 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3731 struct got_object_qid *qid;
3733 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3734 if (qid != NULL) {
3735 struct got_commit_object *pcommit;
3736 err = got_object_open_as_commit(&pcommit, repo,
3737 &qid->id);
3738 if (err)
3739 return err;
3741 tree_id1 = got_object_id_dup(
3742 got_object_commit_get_tree_id(pcommit));
3743 if (tree_id1 == NULL) {
3744 got_object_commit_close(pcommit);
3745 return got_error_from_errno("got_object_id_dup");
3747 got_object_commit_close(pcommit);
3751 if (tree_id1) {
3752 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3753 if (err)
3754 goto done;
3757 tree_id2 = got_object_commit_get_tree_id(commit);
3758 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3759 if (err)
3760 goto done;
3762 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3763 got_diff_tree_collect_changed_paths, paths, 0);
3764 done:
3765 if (tree1)
3766 got_object_tree_close(tree1);
3767 if (tree2)
3768 got_object_tree_close(tree2);
3769 free(tree_id1);
3770 return err;
3773 static const struct got_error *
3774 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3775 const char *path, int diff_context, struct got_repository *repo,
3776 FILE *outfile)
3778 const struct got_error *err = NULL;
3779 struct got_commit_object *pcommit = NULL;
3780 char *id_str1 = NULL, *id_str2 = NULL;
3781 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3782 struct got_object_qid *qid;
3784 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3785 if (qid != NULL) {
3786 err = got_object_open_as_commit(&pcommit, repo,
3787 &qid->id);
3788 if (err)
3789 return err;
3790 err = got_object_id_str(&id_str1, &qid->id);
3791 if (err)
3792 goto done;
3795 err = got_object_id_str(&id_str2, id);
3796 if (err)
3797 goto done;
3799 if (path && path[0] != '\0') {
3800 int obj_type;
3801 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3802 if (err)
3803 goto done;
3804 if (pcommit) {
3805 err = got_object_id_by_path(&obj_id1, repo,
3806 pcommit, path);
3807 if (err) {
3808 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3809 free(obj_id2);
3810 goto done;
3814 err = got_object_get_type(&obj_type, repo, obj_id2);
3815 if (err) {
3816 free(obj_id2);
3817 goto done;
3819 fprintf(outfile,
3820 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3821 fprintf(outfile, "commit - %s\n",
3822 id_str1 ? id_str1 : "/dev/null");
3823 fprintf(outfile, "commit + %s\n", id_str2);
3824 switch (obj_type) {
3825 case GOT_OBJ_TYPE_BLOB:
3826 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3827 0, 0, repo, outfile);
3828 break;
3829 case GOT_OBJ_TYPE_TREE:
3830 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3831 0, 0, repo, outfile);
3832 break;
3833 default:
3834 err = got_error(GOT_ERR_OBJ_TYPE);
3835 break;
3837 free(obj_id1);
3838 free(obj_id2);
3839 } else {
3840 obj_id2 = got_object_commit_get_tree_id(commit);
3841 if (pcommit)
3842 obj_id1 = got_object_commit_get_tree_id(pcommit);
3843 fprintf(outfile,
3844 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3845 fprintf(outfile, "commit - %s\n",
3846 id_str1 ? id_str1 : "/dev/null");
3847 fprintf(outfile, "commit + %s\n", id_str2);
3848 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3849 repo, outfile);
3851 done:
3852 free(id_str1);
3853 free(id_str2);
3854 if (pcommit)
3855 got_object_commit_close(pcommit);
3856 return err;
3859 static char *
3860 get_datestr(time_t *time, char *datebuf)
3862 struct tm mytm, *tm;
3863 char *p, *s;
3865 tm = gmtime_r(time, &mytm);
3866 if (tm == NULL)
3867 return NULL;
3868 s = asctime_r(tm, datebuf);
3869 if (s == NULL)
3870 return NULL;
3871 p = strchr(s, '\n');
3872 if (p)
3873 *p = '\0';
3874 return s;
3877 static const struct got_error *
3878 match_commit(int *have_match, struct got_object_id *id,
3879 struct got_commit_object *commit, regex_t *regex)
3881 const struct got_error *err = NULL;
3882 regmatch_t regmatch;
3883 char *id_str = NULL, *logmsg = NULL;
3885 *have_match = 0;
3887 err = got_object_id_str(&id_str, id);
3888 if (err)
3889 return err;
3891 err = got_object_commit_get_logmsg(&logmsg, commit);
3892 if (err)
3893 goto done;
3895 if (regexec(regex, got_object_commit_get_author(commit), 1,
3896 &regmatch, 0) == 0 ||
3897 regexec(regex, got_object_commit_get_committer(commit), 1,
3898 &regmatch, 0) == 0 ||
3899 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3900 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3901 *have_match = 1;
3902 done:
3903 free(id_str);
3904 free(logmsg);
3905 return err;
3908 static void
3909 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3910 regex_t *regex)
3912 regmatch_t regmatch;
3913 struct got_pathlist_entry *pe;
3915 *have_match = 0;
3917 TAILQ_FOREACH(pe, changed_paths, entry) {
3918 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3919 *have_match = 1;
3920 break;
3925 static const struct got_error *
3926 match_patch(int *have_match, struct got_commit_object *commit,
3927 struct got_object_id *id, const char *path, int diff_context,
3928 struct got_repository *repo, regex_t *regex, FILE *f)
3930 const struct got_error *err = NULL;
3931 char *line = NULL;
3932 size_t linesize = 0;
3933 regmatch_t regmatch;
3935 *have_match = 0;
3937 err = got_opentemp_truncate(f);
3938 if (err)
3939 return err;
3941 err = print_patch(commit, id, path, diff_context, repo, f);
3942 if (err)
3943 goto done;
3945 if (fseeko(f, 0L, SEEK_SET) == -1) {
3946 err = got_error_from_errno("fseeko");
3947 goto done;
3950 while (getline(&line, &linesize, f) != -1) {
3951 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3952 *have_match = 1;
3953 break;
3956 done:
3957 free(line);
3958 return err;
3961 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3963 static const struct got_error*
3964 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3965 struct got_object_id *id, struct got_repository *repo,
3966 int local_only)
3968 static const struct got_error *err = NULL;
3969 struct got_reflist_entry *re;
3970 char *s;
3971 const char *name;
3973 *refs_str = NULL;
3975 TAILQ_FOREACH(re, refs, entry) {
3976 struct got_tag_object *tag = NULL;
3977 struct got_object_id *ref_id;
3978 int cmp;
3980 name = got_ref_get_name(re->ref);
3981 if (strcmp(name, GOT_REF_HEAD) == 0)
3982 continue;
3983 if (strncmp(name, "refs/", 5) == 0)
3984 name += 5;
3985 if (strncmp(name, "got/", 4) == 0)
3986 continue;
3987 if (strncmp(name, "heads/", 6) == 0)
3988 name += 6;
3989 if (strncmp(name, "remotes/", 8) == 0) {
3990 if (local_only)
3991 continue;
3992 name += 8;
3993 s = strstr(name, "/" GOT_REF_HEAD);
3994 if (s != NULL && s[strlen(s)] == '\0')
3995 continue;
3997 err = got_ref_resolve(&ref_id, repo, re->ref);
3998 if (err)
3999 break;
4000 if (strncmp(name, "tags/", 5) == 0) {
4001 err = got_object_open_as_tag(&tag, repo, ref_id);
4002 if (err) {
4003 if (err->code != GOT_ERR_OBJ_TYPE) {
4004 free(ref_id);
4005 break;
4007 /* Ref points at something other than a tag. */
4008 err = NULL;
4009 tag = NULL;
4012 cmp = got_object_id_cmp(tag ?
4013 got_object_tag_get_object_id(tag) : ref_id, id);
4014 free(ref_id);
4015 if (tag)
4016 got_object_tag_close(tag);
4017 if (cmp != 0)
4018 continue;
4019 s = *refs_str;
4020 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4021 s ? ", " : "", name) == -1) {
4022 err = got_error_from_errno("asprintf");
4023 free(s);
4024 *refs_str = NULL;
4025 break;
4027 free(s);
4030 return err;
4033 static const struct got_error *
4034 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4035 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4037 const struct got_error *err = NULL;
4038 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4039 char *comma, *s, *nl;
4040 struct got_reflist_head *refs;
4041 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4042 struct tm tm;
4043 time_t committer_time;
4045 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4046 if (refs) {
4047 err = build_refs_str(&ref_str, refs, id, repo, 1);
4048 if (err)
4049 return err;
4051 /* Display the first matching ref only. */
4052 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4053 *comma = '\0';
4056 if (ref_str == NULL) {
4057 err = got_object_id_str(&id_str, id);
4058 if (err)
4059 return err;
4062 committer_time = got_object_commit_get_committer_time(commit);
4063 if (gmtime_r(&committer_time, &tm) == NULL) {
4064 err = got_error_from_errno("gmtime_r");
4065 goto done;
4067 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4068 err = got_error(GOT_ERR_NO_SPACE);
4069 goto done;
4072 err = got_object_commit_get_logmsg(&logmsg0, commit);
4073 if (err)
4074 goto done;
4076 s = logmsg0;
4077 while (isspace((unsigned char)s[0]))
4078 s++;
4080 nl = strchr(s, '\n');
4081 if (nl) {
4082 *nl = '\0';
4085 if (ref_str)
4086 printf("%s%-7s %s\n", datebuf, ref_str, s);
4087 else
4088 printf("%s%.7s %s\n", datebuf, id_str, s);
4090 if (fflush(stdout) != 0 && err == NULL)
4091 err = got_error_from_errno("fflush");
4092 done:
4093 free(id_str);
4094 free(ref_str);
4095 free(logmsg0);
4096 return err;
4099 static const struct got_error *
4100 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4101 struct got_repository *repo, const char *path,
4102 struct got_pathlist_head *changed_paths, int show_patch,
4103 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4104 const char *custom_refs_str)
4106 const struct got_error *err = NULL;
4107 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4108 char datebuf[26];
4109 time_t committer_time;
4110 const char *author, *committer;
4111 char *refs_str = NULL;
4113 err = got_object_id_str(&id_str, id);
4114 if (err)
4115 return err;
4117 if (custom_refs_str == NULL) {
4118 struct got_reflist_head *refs;
4119 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4120 if (refs) {
4121 err = build_refs_str(&refs_str, refs, id, repo, 0);
4122 if (err)
4123 goto done;
4127 printf(GOT_COMMIT_SEP_STR);
4128 if (custom_refs_str)
4129 printf("commit %s (%s)\n", id_str, custom_refs_str);
4130 else
4131 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4132 refs_str ? refs_str : "", refs_str ? ")" : "");
4133 free(id_str);
4134 id_str = NULL;
4135 free(refs_str);
4136 refs_str = NULL;
4137 printf("from: %s\n", got_object_commit_get_author(commit));
4138 committer_time = got_object_commit_get_committer_time(commit);
4139 datestr = get_datestr(&committer_time, datebuf);
4140 if (datestr)
4141 printf("date: %s UTC\n", datestr);
4142 author = got_object_commit_get_author(commit);
4143 committer = got_object_commit_get_committer(commit);
4144 if (strcmp(author, committer) != 0)
4145 printf("via: %s\n", committer);
4146 if (got_object_commit_get_nparents(commit) > 1) {
4147 const struct got_object_id_queue *parent_ids;
4148 struct got_object_qid *qid;
4149 int n = 1;
4150 parent_ids = got_object_commit_get_parent_ids(commit);
4151 STAILQ_FOREACH(qid, parent_ids, entry) {
4152 err = got_object_id_str(&id_str, &qid->id);
4153 if (err)
4154 goto done;
4155 printf("parent %d: %s\n", n++, id_str);
4156 free(id_str);
4157 id_str = NULL;
4161 err = got_object_commit_get_logmsg(&logmsg0, commit);
4162 if (err)
4163 goto done;
4165 logmsg = logmsg0;
4166 do {
4167 line = strsep(&logmsg, "\n");
4168 if (line)
4169 printf(" %s\n", line);
4170 } while (line);
4171 free(logmsg0);
4173 if (changed_paths) {
4174 struct got_pathlist_entry *pe;
4175 TAILQ_FOREACH(pe, changed_paths, entry) {
4176 struct got_diff_changed_path *cp = pe->data;
4177 printf(" %c %s\n", cp->status, pe->path);
4179 printf("\n");
4181 if (show_patch) {
4182 err = print_patch(commit, id, path, diff_context, repo, stdout);
4183 if (err == 0)
4184 printf("\n");
4187 if (fflush(stdout) != 0 && err == NULL)
4188 err = got_error_from_errno("fflush");
4189 done:
4190 free(id_str);
4191 free(refs_str);
4192 return err;
4195 static const struct got_error *
4196 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4197 struct got_repository *repo, const char *path, int show_changed_paths,
4198 int show_patch, const char *search_pattern, int diff_context, int limit,
4199 int log_branches, int reverse_display_order,
4200 struct got_reflist_object_id_map *refs_idmap, int one_line,
4201 FILE *tmpfile)
4203 const struct got_error *err;
4204 struct got_commit_graph *graph;
4205 regex_t regex;
4206 int have_match;
4207 struct got_object_id_queue reversed_commits;
4208 struct got_object_qid *qid;
4209 struct got_commit_object *commit;
4210 struct got_pathlist_head changed_paths;
4211 struct got_pathlist_entry *pe;
4213 STAILQ_INIT(&reversed_commits);
4214 TAILQ_INIT(&changed_paths);
4216 if (search_pattern && regcomp(&regex, search_pattern,
4217 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4218 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4220 err = got_commit_graph_open(&graph, path, !log_branches);
4221 if (err)
4222 return err;
4223 err = got_commit_graph_iter_start(graph, root_id, repo,
4224 check_cancelled, NULL);
4225 if (err)
4226 goto done;
4227 for (;;) {
4228 struct got_object_id *id;
4230 if (sigint_received || sigpipe_received)
4231 break;
4233 err = got_commit_graph_iter_next(&id, graph, repo,
4234 check_cancelled, NULL);
4235 if (err) {
4236 if (err->code == GOT_ERR_ITER_COMPLETED)
4237 err = NULL;
4238 break;
4240 if (id == NULL)
4241 break;
4243 err = got_object_open_as_commit(&commit, repo, id);
4244 if (err)
4245 break;
4247 if (show_changed_paths && !reverse_display_order) {
4248 err = get_changed_paths(&changed_paths, commit, repo);
4249 if (err)
4250 break;
4253 if (search_pattern) {
4254 err = match_commit(&have_match, id, commit, &regex);
4255 if (err) {
4256 got_object_commit_close(commit);
4257 break;
4259 if (have_match == 0 && show_changed_paths)
4260 match_changed_paths(&have_match,
4261 &changed_paths, &regex);
4262 if (have_match == 0 && show_patch) {
4263 err = match_patch(&have_match, commit, id,
4264 path, diff_context, repo, &regex,
4265 tmpfile);
4266 if (err)
4267 break;
4269 if (have_match == 0) {
4270 got_object_commit_close(commit);
4271 TAILQ_FOREACH(pe, &changed_paths, entry) {
4272 free((char *)pe->path);
4273 free(pe->data);
4275 got_pathlist_free(&changed_paths);
4276 continue;
4280 if (reverse_display_order) {
4281 err = got_object_qid_alloc(&qid, id);
4282 if (err)
4283 break;
4284 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4285 got_object_commit_close(commit);
4286 } else {
4287 if (one_line)
4288 err = print_commit_oneline(commit, id,
4289 repo, refs_idmap);
4290 else
4291 err = print_commit(commit, id, repo, path,
4292 show_changed_paths ? &changed_paths : NULL,
4293 show_patch, diff_context, refs_idmap, NULL);
4294 got_object_commit_close(commit);
4295 if (err)
4296 break;
4298 if ((limit && --limit == 0) ||
4299 (end_id && got_object_id_cmp(id, end_id) == 0))
4300 break;
4302 TAILQ_FOREACH(pe, &changed_paths, entry) {
4303 free((char *)pe->path);
4304 free(pe->data);
4306 got_pathlist_free(&changed_paths);
4308 if (reverse_display_order) {
4309 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4310 err = got_object_open_as_commit(&commit, repo,
4311 &qid->id);
4312 if (err)
4313 break;
4314 if (show_changed_paths) {
4315 err = get_changed_paths(&changed_paths,
4316 commit, repo);
4317 if (err)
4318 break;
4320 if (one_line)
4321 err = print_commit_oneline(commit, &qid->id,
4322 repo, refs_idmap);
4323 else
4324 err = print_commit(commit, &qid->id, repo, path,
4325 show_changed_paths ? &changed_paths : NULL,
4326 show_patch, diff_context, refs_idmap, NULL);
4327 got_object_commit_close(commit);
4328 if (err)
4329 break;
4330 TAILQ_FOREACH(pe, &changed_paths, entry) {
4331 free((char *)pe->path);
4332 free(pe->data);
4334 got_pathlist_free(&changed_paths);
4337 done:
4338 while (!STAILQ_EMPTY(&reversed_commits)) {
4339 qid = STAILQ_FIRST(&reversed_commits);
4340 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4341 got_object_qid_free(qid);
4343 TAILQ_FOREACH(pe, &changed_paths, entry) {
4344 free((char *)pe->path);
4345 free(pe->data);
4347 got_pathlist_free(&changed_paths);
4348 if (search_pattern)
4349 regfree(&regex);
4350 got_commit_graph_close(graph);
4351 return err;
4354 __dead static void
4355 usage_log(void)
4357 fprintf(stderr, "usage: %s log [-bPpRs] [-C number] [-c commit] [-l N] "
4358 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4359 getprogname());
4360 exit(1);
4363 static int
4364 get_default_log_limit(void)
4366 const char *got_default_log_limit;
4367 long long n;
4368 const char *errstr;
4370 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4371 if (got_default_log_limit == NULL)
4372 return 0;
4373 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4374 if (errstr != NULL)
4375 return 0;
4376 return n;
4379 static const struct got_error *
4380 cmd_log(int argc, char *argv[])
4382 const struct got_error *error;
4383 struct got_repository *repo = NULL;
4384 struct got_worktree *worktree = NULL;
4385 struct got_object_id *start_id = NULL, *end_id = NULL;
4386 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4387 const char *start_commit = NULL, *end_commit = NULL;
4388 const char *search_pattern = NULL;
4389 int diff_context = -1, ch;
4390 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4391 int reverse_display_order = 0, one_line = 0;
4392 const char *errstr;
4393 struct got_reflist_head refs;
4394 struct got_reflist_object_id_map *refs_idmap = NULL;
4395 FILE *tmpfile = NULL;
4396 int *pack_fds = NULL;
4398 TAILQ_INIT(&refs);
4400 #ifndef PROFILE
4401 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4402 NULL)
4403 == -1)
4404 err(1, "pledge");
4405 #endif
4407 limit = get_default_log_limit();
4409 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4410 switch (ch) {
4411 case 'p':
4412 show_patch = 1;
4413 break;
4414 case 'P':
4415 show_changed_paths = 1;
4416 break;
4417 case 'c':
4418 start_commit = optarg;
4419 break;
4420 case 'C':
4421 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4422 &errstr);
4423 if (errstr != NULL)
4424 errx(1, "number of context lines is %s: %s",
4425 errstr, optarg);
4426 break;
4427 case 'l':
4428 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4429 if (errstr != NULL)
4430 errx(1, "number of commits is %s: %s",
4431 errstr, optarg);
4432 break;
4433 case 'b':
4434 log_branches = 1;
4435 break;
4436 case 'r':
4437 repo_path = realpath(optarg, NULL);
4438 if (repo_path == NULL)
4439 return got_error_from_errno2("realpath",
4440 optarg);
4441 got_path_strip_trailing_slashes(repo_path);
4442 break;
4443 case 'R':
4444 reverse_display_order = 1;
4445 break;
4446 case 's':
4447 one_line = 1;
4448 break;
4449 case 'S':
4450 search_pattern = optarg;
4451 break;
4452 case 'x':
4453 end_commit = optarg;
4454 break;
4455 default:
4456 usage_log();
4457 /* NOTREACHED */
4461 argc -= optind;
4462 argv += optind;
4464 if (diff_context == -1)
4465 diff_context = 3;
4466 else if (!show_patch)
4467 errx(1, "-C requires -p");
4469 if (one_line && (show_patch || show_changed_paths))
4470 errx(1, "cannot use -s with -p or -P");
4472 cwd = getcwd(NULL, 0);
4473 if (cwd == NULL) {
4474 error = got_error_from_errno("getcwd");
4475 goto done;
4478 error = got_repo_pack_fds_open(&pack_fds);
4479 if (error != NULL)
4480 goto done;
4482 if (repo_path == NULL) {
4483 error = got_worktree_open(&worktree, cwd);
4484 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4485 goto done;
4486 error = NULL;
4489 if (argc == 1) {
4490 if (worktree) {
4491 error = got_worktree_resolve_path(&path, worktree,
4492 argv[0]);
4493 if (error)
4494 goto done;
4495 } else {
4496 path = strdup(argv[0]);
4497 if (path == NULL) {
4498 error = got_error_from_errno("strdup");
4499 goto done;
4502 } else if (argc != 0)
4503 usage_log();
4505 if (repo_path == NULL) {
4506 repo_path = worktree ?
4507 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4509 if (repo_path == NULL) {
4510 error = got_error_from_errno("strdup");
4511 goto done;
4514 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4515 if (error != NULL)
4516 goto done;
4518 error = apply_unveil(got_repo_get_path(repo), 1,
4519 worktree ? got_worktree_get_root_path(worktree) : NULL);
4520 if (error)
4521 goto done;
4523 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4524 if (error)
4525 goto done;
4527 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4528 if (error)
4529 goto done;
4531 if (start_commit == NULL) {
4532 struct got_reference *head_ref;
4533 struct got_commit_object *commit = NULL;
4534 error = got_ref_open(&head_ref, repo,
4535 worktree ? got_worktree_get_head_ref_name(worktree)
4536 : GOT_REF_HEAD, 0);
4537 if (error != NULL)
4538 goto done;
4539 error = got_ref_resolve(&start_id, repo, head_ref);
4540 got_ref_close(head_ref);
4541 if (error != NULL)
4542 goto done;
4543 error = got_object_open_as_commit(&commit, repo,
4544 start_id);
4545 if (error != NULL)
4546 goto done;
4547 got_object_commit_close(commit);
4548 } else {
4549 error = got_repo_match_object_id(&start_id, NULL,
4550 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4551 if (error != NULL)
4552 goto done;
4554 if (end_commit != NULL) {
4555 error = got_repo_match_object_id(&end_id, NULL,
4556 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4557 if (error != NULL)
4558 goto done;
4561 if (worktree) {
4563 * If a path was specified on the command line it was resolved
4564 * to a path in the work tree above. Prepend the work tree's
4565 * path prefix to obtain the corresponding in-repository path.
4567 if (path) {
4568 const char *prefix;
4569 prefix = got_worktree_get_path_prefix(worktree);
4570 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4571 (path[0] != '\0') ? "/" : "", path) == -1) {
4572 error = got_error_from_errno("asprintf");
4573 goto done;
4576 } else
4577 error = got_repo_map_path(&in_repo_path, repo,
4578 path ? path : "");
4579 if (error != NULL)
4580 goto done;
4581 if (in_repo_path) {
4582 free(path);
4583 path = in_repo_path;
4586 if (worktree) {
4587 /* Release work tree lock. */
4588 got_worktree_close(worktree);
4589 worktree = NULL;
4592 if (search_pattern && show_patch) {
4593 tmpfile = got_opentemp();
4594 if (tmpfile == NULL) {
4595 error = got_error_from_errno("got_opentemp");
4596 goto done;
4600 error = print_commits(start_id, end_id, repo, path ? path : "",
4601 show_changed_paths, show_patch, search_pattern, diff_context,
4602 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4603 tmpfile);
4604 done:
4605 free(path);
4606 free(repo_path);
4607 free(cwd);
4608 if (worktree)
4609 got_worktree_close(worktree);
4610 if (repo) {
4611 const struct got_error *close_err = got_repo_close(repo);
4612 if (error == NULL)
4613 error = close_err;
4615 if (pack_fds) {
4616 const struct got_error *pack_err =
4617 got_repo_pack_fds_close(pack_fds);
4618 if (error == NULL)
4619 error = pack_err;
4621 if (refs_idmap)
4622 got_reflist_object_id_map_free(refs_idmap);
4623 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4624 error = got_error_from_errno("fclose");
4625 got_ref_list_free(&refs);
4626 return error;
4629 __dead static void
4630 usage_diff(void)
4632 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4633 "[-r repository-path] [object1 object2 | path ...]\n",
4634 getprogname());
4635 exit(1);
4638 struct print_diff_arg {
4639 struct got_repository *repo;
4640 struct got_worktree *worktree;
4641 int diff_context;
4642 const char *id_str;
4643 int header_shown;
4644 int diff_staged;
4645 enum got_diff_algorithm diff_algo;
4646 int ignore_whitespace;
4647 int force_text_diff;
4648 FILE *f1;
4649 FILE *f2;
4653 * Create a file which contains the target path of a symlink so we can feed
4654 * it as content to the diff engine.
4656 static const struct got_error *
4657 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4658 const char *abspath)
4660 const struct got_error *err = NULL;
4661 char target_path[PATH_MAX];
4662 ssize_t target_len, outlen;
4664 *fd = -1;
4666 if (dirfd != -1) {
4667 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4668 if (target_len == -1)
4669 return got_error_from_errno2("readlinkat", abspath);
4670 } else {
4671 target_len = readlink(abspath, target_path, PATH_MAX);
4672 if (target_len == -1)
4673 return got_error_from_errno2("readlink", abspath);
4676 *fd = got_opentempfd();
4677 if (*fd == -1)
4678 return got_error_from_errno("got_opentempfd");
4680 outlen = write(*fd, target_path, target_len);
4681 if (outlen == -1) {
4682 err = got_error_from_errno("got_opentempfd");
4683 goto done;
4686 if (lseek(*fd, 0, SEEK_SET) == -1) {
4687 err = got_error_from_errno2("lseek", abspath);
4688 goto done;
4690 done:
4691 if (err) {
4692 close(*fd);
4693 *fd = -1;
4695 return err;
4698 static const struct got_error *
4699 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4700 const char *path, struct got_object_id *blob_id,
4701 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4702 int dirfd, const char *de_name)
4704 struct print_diff_arg *a = arg;
4705 const struct got_error *err = NULL;
4706 struct got_blob_object *blob1 = NULL;
4707 int fd = -1, fd1 = -1, fd2 = -1;
4708 FILE *f2 = NULL;
4709 char *abspath = NULL, *label1 = NULL;
4710 struct stat sb;
4711 off_t size1 = 0;
4712 int f2_exists = 1;
4714 if (a->diff_staged) {
4715 if (staged_status != GOT_STATUS_MODIFY &&
4716 staged_status != GOT_STATUS_ADD &&
4717 staged_status != GOT_STATUS_DELETE)
4718 return NULL;
4719 } else {
4720 if (staged_status == GOT_STATUS_DELETE)
4721 return NULL;
4722 if (status == GOT_STATUS_NONEXISTENT)
4723 return got_error_set_errno(ENOENT, path);
4724 if (status != GOT_STATUS_MODIFY &&
4725 status != GOT_STATUS_ADD &&
4726 status != GOT_STATUS_DELETE &&
4727 status != GOT_STATUS_CONFLICT)
4728 return NULL;
4731 err = got_opentemp_truncate(a->f1);
4732 if (err)
4733 return got_error_from_errno("got_opentemp_truncate");
4734 err = got_opentemp_truncate(a->f2);
4735 if (err)
4736 return got_error_from_errno("got_opentemp_truncate");
4738 if (!a->header_shown) {
4739 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4740 got_worktree_get_root_path(a->worktree));
4741 printf("commit - %s\n", a->id_str);
4742 printf("path + %s%s\n",
4743 got_worktree_get_root_path(a->worktree),
4744 a->diff_staged ? " (staged changes)" : "");
4745 a->header_shown = 1;
4748 if (a->diff_staged) {
4749 const char *label1 = NULL, *label2 = NULL;
4750 switch (staged_status) {
4751 case GOT_STATUS_MODIFY:
4752 label1 = path;
4753 label2 = path;
4754 break;
4755 case GOT_STATUS_ADD:
4756 label2 = path;
4757 break;
4758 case GOT_STATUS_DELETE:
4759 label1 = path;
4760 break;
4761 default:
4762 return got_error(GOT_ERR_FILE_STATUS);
4764 fd1 = got_opentempfd();
4765 if (fd1 == -1) {
4766 err = got_error_from_errno("got_opentempfd");
4767 goto done;
4769 fd2 = got_opentempfd();
4770 if (fd2 == -1) {
4771 err = got_error_from_errno("got_opentempfd");
4772 goto done;
4774 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4775 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4776 a->diff_algo, a->diff_context, a->ignore_whitespace,
4777 a->force_text_diff, a->repo, stdout);
4778 goto done;
4781 fd1 = got_opentempfd();
4782 if (fd1 == -1) {
4783 err = got_error_from_errno("got_opentempfd");
4784 goto done;
4787 if (staged_status == GOT_STATUS_ADD ||
4788 staged_status == GOT_STATUS_MODIFY) {
4789 char *id_str;
4790 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4791 8192, fd1);
4792 if (err)
4793 goto done;
4794 err = got_object_id_str(&id_str, staged_blob_id);
4795 if (err)
4796 goto done;
4797 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4798 err = got_error_from_errno("asprintf");
4799 free(id_str);
4800 goto done;
4802 free(id_str);
4803 } else if (status != GOT_STATUS_ADD) {
4804 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4805 fd1);
4806 if (err)
4807 goto done;
4810 if (status != GOT_STATUS_DELETE) {
4811 if (asprintf(&abspath, "%s/%s",
4812 got_worktree_get_root_path(a->worktree), path) == -1) {
4813 err = got_error_from_errno("asprintf");
4814 goto done;
4817 if (dirfd != -1) {
4818 fd = openat(dirfd, de_name,
4819 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4820 if (fd == -1) {
4821 if (!got_err_open_nofollow_on_symlink()) {
4822 err = got_error_from_errno2("openat",
4823 abspath);
4824 goto done;
4826 err = get_symlink_target_file(&fd, dirfd,
4827 de_name, abspath);
4828 if (err)
4829 goto done;
4831 } else {
4832 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4833 if (fd == -1) {
4834 if (!got_err_open_nofollow_on_symlink()) {
4835 err = got_error_from_errno2("open",
4836 abspath);
4837 goto done;
4839 err = get_symlink_target_file(&fd, dirfd,
4840 de_name, abspath);
4841 if (err)
4842 goto done;
4845 if (fstat(fd, &sb) == -1) {
4846 err = got_error_from_errno2("fstat", abspath);
4847 goto done;
4849 f2 = fdopen(fd, "r");
4850 if (f2 == NULL) {
4851 err = got_error_from_errno2("fdopen", abspath);
4852 goto done;
4854 fd = -1;
4855 } else {
4856 sb.st_size = 0;
4857 f2_exists = 0;
4860 if (blob1) {
4861 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4862 a->f1, blob1);
4863 if (err)
4864 goto done;
4867 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4868 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4869 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4870 done:
4871 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4872 err = got_error_from_errno("close");
4873 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4874 err = got_error_from_errno("close");
4875 if (blob1)
4876 got_object_blob_close(blob1);
4877 if (fd != -1 && close(fd) == -1 && err == NULL)
4878 err = got_error_from_errno("close");
4879 if (f2 && fclose(f2) == EOF && err == NULL)
4880 err = got_error_from_errno("fclose");
4881 free(abspath);
4882 return err;
4885 static const struct got_error *
4886 cmd_diff(int argc, char *argv[])
4888 const struct got_error *error;
4889 struct got_repository *repo = NULL;
4890 struct got_worktree *worktree = NULL;
4891 char *cwd = NULL, *repo_path = NULL;
4892 const char *commit_args[2] = { NULL, NULL };
4893 int ncommit_args = 0;
4894 struct got_object_id *ids[2] = { NULL, NULL };
4895 char *labels[2] = { NULL, NULL };
4896 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4897 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4898 int force_text_diff = 0, force_path = 0, rflag = 0;
4899 const char *errstr;
4900 struct got_reflist_head refs;
4901 struct got_pathlist_head paths;
4902 struct got_pathlist_entry *pe;
4903 FILE *f1 = NULL, *f2 = NULL;
4904 int fd1 = -1, fd2 = -1;
4905 int *pack_fds = NULL;
4907 TAILQ_INIT(&refs);
4908 TAILQ_INIT(&paths);
4910 #ifndef PROFILE
4911 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4912 NULL) == -1)
4913 err(1, "pledge");
4914 #endif
4916 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4917 switch (ch) {
4918 case 'a':
4919 force_text_diff = 1;
4920 break;
4921 case 'c':
4922 if (ncommit_args >= 2)
4923 errx(1, "too many -c options used");
4924 commit_args[ncommit_args++] = optarg;
4925 break;
4926 case 'C':
4927 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4928 &errstr);
4929 if (errstr != NULL)
4930 errx(1, "number of context lines is %s: %s",
4931 errstr, optarg);
4932 break;
4933 case 'r':
4934 repo_path = realpath(optarg, NULL);
4935 if (repo_path == NULL)
4936 return got_error_from_errno2("realpath",
4937 optarg);
4938 got_path_strip_trailing_slashes(repo_path);
4939 rflag = 1;
4940 break;
4941 case 's':
4942 diff_staged = 1;
4943 break;
4944 case 'w':
4945 ignore_whitespace = 1;
4946 break;
4947 case 'P':
4948 force_path = 1;
4949 break;
4950 default:
4951 usage_diff();
4952 /* NOTREACHED */
4956 argc -= optind;
4957 argv += optind;
4959 cwd = getcwd(NULL, 0);
4960 if (cwd == NULL) {
4961 error = got_error_from_errno("getcwd");
4962 goto done;
4965 error = got_repo_pack_fds_open(&pack_fds);
4966 if (error != NULL)
4967 goto done;
4969 if (repo_path == NULL) {
4970 error = got_worktree_open(&worktree, cwd);
4971 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4972 goto done;
4973 else
4974 error = NULL;
4975 if (worktree) {
4976 repo_path =
4977 strdup(got_worktree_get_repo_path(worktree));
4978 if (repo_path == NULL) {
4979 error = got_error_from_errno("strdup");
4980 goto done;
4982 } else {
4983 repo_path = strdup(cwd);
4984 if (repo_path == NULL) {
4985 error = got_error_from_errno("strdup");
4986 goto done;
4991 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4992 free(repo_path);
4993 if (error != NULL)
4994 goto done;
4996 if (rflag || worktree == NULL || ncommit_args > 0) {
4997 if (force_path) {
4998 error = got_error_msg(GOT_ERR_NOT_IMPL,
4999 "-P option can only be used when diffing "
5000 "a work tree");
5001 goto done;
5003 if (diff_staged) {
5004 error = got_error_msg(GOT_ERR_NOT_IMPL,
5005 "-s option can only be used when diffing "
5006 "a work tree");
5007 goto done;
5011 error = apply_unveil(got_repo_get_path(repo), 1,
5012 worktree ? got_worktree_get_root_path(worktree) : NULL);
5013 if (error)
5014 goto done;
5016 if ((!force_path && argc == 2) || ncommit_args > 0) {
5017 int obj_type = (ncommit_args > 0 ?
5018 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5019 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5020 NULL);
5021 if (error)
5022 goto done;
5023 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5024 const char *arg;
5025 if (ncommit_args > 0)
5026 arg = commit_args[i];
5027 else
5028 arg = argv[i];
5029 error = got_repo_match_object_id(&ids[i], &labels[i],
5030 arg, obj_type, &refs, repo);
5031 if (error) {
5032 if (error->code != GOT_ERR_NOT_REF &&
5033 error->code != GOT_ERR_NO_OBJ)
5034 goto done;
5035 if (ncommit_args > 0)
5036 goto done;
5037 error = NULL;
5038 break;
5043 f1 = got_opentemp();
5044 if (f1 == NULL) {
5045 error = got_error_from_errno("got_opentemp");
5046 goto done;
5049 f2 = got_opentemp();
5050 if (f2 == NULL) {
5051 error = got_error_from_errno("got_opentemp");
5052 goto done;
5055 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5056 struct print_diff_arg arg;
5057 char *id_str;
5059 if (worktree == NULL) {
5060 if (argc == 2 && ids[0] == NULL) {
5061 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5062 goto done;
5063 } else if (argc == 2 && ids[1] == NULL) {
5064 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5065 goto done;
5066 } else if (argc > 0) {
5067 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5068 "%s", "specified paths cannot be resolved");
5069 goto done;
5070 } else {
5071 error = got_error(GOT_ERR_NOT_WORKTREE);
5072 goto done;
5076 error = get_worktree_paths_from_argv(&paths, argc, argv,
5077 worktree);
5078 if (error)
5079 goto done;
5081 error = got_object_id_str(&id_str,
5082 got_worktree_get_base_commit_id(worktree));
5083 if (error)
5084 goto done;
5085 arg.repo = repo;
5086 arg.worktree = worktree;
5087 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5088 arg.diff_context = diff_context;
5089 arg.id_str = id_str;
5090 arg.header_shown = 0;
5091 arg.diff_staged = diff_staged;
5092 arg.ignore_whitespace = ignore_whitespace;
5093 arg.force_text_diff = force_text_diff;
5094 arg.f1 = f1;
5095 arg.f2 = f2;
5097 error = got_worktree_status(worktree, &paths, repo, 0,
5098 print_diff, &arg, check_cancelled, NULL);
5099 free(id_str);
5100 goto done;
5103 if (ncommit_args == 1) {
5104 struct got_commit_object *commit;
5105 error = got_object_open_as_commit(&commit, repo, ids[0]);
5106 if (error)
5107 goto done;
5109 labels[1] = labels[0];
5110 ids[1] = ids[0];
5111 if (got_object_commit_get_nparents(commit) > 0) {
5112 const struct got_object_id_queue *pids;
5113 struct got_object_qid *pid;
5114 pids = got_object_commit_get_parent_ids(commit);
5115 pid = STAILQ_FIRST(pids);
5116 ids[0] = got_object_id_dup(&pid->id);
5117 if (ids[0] == NULL) {
5118 error = got_error_from_errno(
5119 "got_object_id_dup");
5120 got_object_commit_close(commit);
5121 goto done;
5123 error = got_object_id_str(&labels[0], ids[0]);
5124 if (error) {
5125 got_object_commit_close(commit);
5126 goto done;
5128 } else {
5129 ids[0] = NULL;
5130 labels[0] = strdup("/dev/null");
5131 if (labels[0] == NULL) {
5132 error = got_error_from_errno("strdup");
5133 got_object_commit_close(commit);
5134 goto done;
5138 got_object_commit_close(commit);
5141 if (ncommit_args == 0 && argc > 2) {
5142 error = got_error_msg(GOT_ERR_BAD_PATH,
5143 "path arguments cannot be used when diffing two objects");
5144 goto done;
5147 if (ids[0]) {
5148 error = got_object_get_type(&type1, repo, ids[0]);
5149 if (error)
5150 goto done;
5153 error = got_object_get_type(&type2, repo, ids[1]);
5154 if (error)
5155 goto done;
5156 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5157 error = got_error(GOT_ERR_OBJ_TYPE);
5158 goto done;
5160 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5161 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5162 "path arguments cannot be used when diffing blobs");
5163 goto done;
5166 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5167 char *in_repo_path;
5168 struct got_pathlist_entry *new;
5169 if (worktree) {
5170 const char *prefix;
5171 char *p;
5172 error = got_worktree_resolve_path(&p, worktree,
5173 argv[i]);
5174 if (error)
5175 goto done;
5176 prefix = got_worktree_get_path_prefix(worktree);
5177 while (prefix[0] == '/')
5178 prefix++;
5179 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5180 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5181 p) == -1) {
5182 error = got_error_from_errno("asprintf");
5183 free(p);
5184 goto done;
5186 free(p);
5187 } else {
5188 char *mapped_path, *s;
5189 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5190 if (error)
5191 goto done;
5192 s = mapped_path;
5193 while (s[0] == '/')
5194 s++;
5195 in_repo_path = strdup(s);
5196 if (in_repo_path == NULL) {
5197 error = got_error_from_errno("asprintf");
5198 free(mapped_path);
5199 goto done;
5201 free(mapped_path);
5204 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5205 if (error || new == NULL /* duplicate */)
5206 free(in_repo_path);
5207 if (error)
5208 goto done;
5211 if (worktree) {
5212 /* Release work tree lock. */
5213 got_worktree_close(worktree);
5214 worktree = NULL;
5217 fd1 = got_opentempfd();
5218 if (fd1 == -1) {
5219 error = got_error_from_errno("got_opentempfd");
5220 goto done;
5223 fd2 = got_opentempfd();
5224 if (fd2 == -1) {
5225 error = got_error_from_errno("got_opentempfd");
5226 goto done;
5229 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5230 case GOT_OBJ_TYPE_BLOB:
5231 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5232 fd1, fd2, ids[0], ids[1], NULL, NULL,
5233 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5234 ignore_whitespace, force_text_diff, repo, stdout);
5235 break;
5236 case GOT_OBJ_TYPE_TREE:
5237 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5238 ids[0], ids[1], &paths, "", "",
5239 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5240 ignore_whitespace, force_text_diff, repo, stdout);
5241 break;
5242 case GOT_OBJ_TYPE_COMMIT:
5243 printf("diff %s %s\n", labels[0], labels[1]);
5244 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5245 fd1, fd2, ids[0], ids[1], &paths,
5246 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5247 ignore_whitespace, force_text_diff, repo, stdout);
5248 break;
5249 default:
5250 error = got_error(GOT_ERR_OBJ_TYPE);
5252 done:
5253 free(labels[0]);
5254 free(labels[1]);
5255 free(ids[0]);
5256 free(ids[1]);
5257 if (worktree)
5258 got_worktree_close(worktree);
5259 if (repo) {
5260 const struct got_error *close_err = got_repo_close(repo);
5261 if (error == NULL)
5262 error = close_err;
5264 if (pack_fds) {
5265 const struct got_error *pack_err =
5266 got_repo_pack_fds_close(pack_fds);
5267 if (error == NULL)
5268 error = pack_err;
5270 TAILQ_FOREACH(pe, &paths, entry)
5271 free((char *)pe->path);
5272 got_pathlist_free(&paths);
5273 got_ref_list_free(&refs);
5274 if (f1 && fclose(f1) == EOF && error == NULL)
5275 error = got_error_from_errno("fclose");
5276 if (f2 && fclose(f2) == EOF && error == NULL)
5277 error = got_error_from_errno("fclose");
5278 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5279 error = got_error_from_errno("close");
5280 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5281 error = got_error_from_errno("close");
5282 return error;
5285 __dead static void
5286 usage_blame(void)
5288 fprintf(stderr,
5289 "usage: %s blame [-c commit] [-r repository-path] path\n",
5290 getprogname());
5291 exit(1);
5294 struct blame_line {
5295 int annotated;
5296 char *id_str;
5297 char *committer;
5298 char datebuf[11]; /* YYYY-MM-DD + NUL */
5301 struct blame_cb_args {
5302 struct blame_line *lines;
5303 int nlines;
5304 int nlines_prec;
5305 int lineno_cur;
5306 off_t *line_offsets;
5307 FILE *f;
5308 struct got_repository *repo;
5311 static const struct got_error *
5312 blame_cb(void *arg, int nlines, int lineno,
5313 struct got_commit_object *commit, struct got_object_id *id)
5315 const struct got_error *err = NULL;
5316 struct blame_cb_args *a = arg;
5317 struct blame_line *bline;
5318 char *line = NULL;
5319 size_t linesize = 0;
5320 off_t offset;
5321 struct tm tm;
5322 time_t committer_time;
5324 if (nlines != a->nlines ||
5325 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5326 return got_error(GOT_ERR_RANGE);
5328 if (sigint_received)
5329 return got_error(GOT_ERR_ITER_COMPLETED);
5331 if (lineno == -1)
5332 return NULL; /* no change in this commit */
5334 /* Annotate this line. */
5335 bline = &a->lines[lineno - 1];
5336 if (bline->annotated)
5337 return NULL;
5338 err = got_object_id_str(&bline->id_str, id);
5339 if (err)
5340 return err;
5342 bline->committer = strdup(got_object_commit_get_committer(commit));
5343 if (bline->committer == NULL) {
5344 err = got_error_from_errno("strdup");
5345 goto done;
5348 committer_time = got_object_commit_get_committer_time(commit);
5349 if (gmtime_r(&committer_time, &tm) == NULL)
5350 return got_error_from_errno("gmtime_r");
5351 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5352 &tm) == 0) {
5353 err = got_error(GOT_ERR_NO_SPACE);
5354 goto done;
5356 bline->annotated = 1;
5358 /* Print lines annotated so far. */
5359 bline = &a->lines[a->lineno_cur - 1];
5360 if (!bline->annotated)
5361 goto done;
5363 offset = a->line_offsets[a->lineno_cur - 1];
5364 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5365 err = got_error_from_errno("fseeko");
5366 goto done;
5369 while (a->lineno_cur <= a->nlines && bline->annotated) {
5370 char *smallerthan, *at, *nl, *committer;
5371 size_t len;
5373 if (getline(&line, &linesize, a->f) == -1) {
5374 if (ferror(a->f))
5375 err = got_error_from_errno("getline");
5376 break;
5379 committer = bline->committer;
5380 smallerthan = strchr(committer, '<');
5381 if (smallerthan && smallerthan[1] != '\0')
5382 committer = smallerthan + 1;
5383 at = strchr(committer, '@');
5384 if (at)
5385 *at = '\0';
5386 len = strlen(committer);
5387 if (len >= 9)
5388 committer[8] = '\0';
5390 nl = strchr(line, '\n');
5391 if (nl)
5392 *nl = '\0';
5393 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5394 bline->id_str, bline->datebuf, committer, line);
5396 a->lineno_cur++;
5397 bline = &a->lines[a->lineno_cur - 1];
5399 done:
5400 free(line);
5401 return err;
5404 static const struct got_error *
5405 cmd_blame(int argc, char *argv[])
5407 const struct got_error *error;
5408 struct got_repository *repo = NULL;
5409 struct got_worktree *worktree = NULL;
5410 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5411 char *link_target = NULL;
5412 struct got_object_id *obj_id = NULL;
5413 struct got_object_id *commit_id = NULL;
5414 struct got_commit_object *commit = NULL;
5415 struct got_blob_object *blob = NULL;
5416 char *commit_id_str = NULL;
5417 struct blame_cb_args bca;
5418 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5419 off_t filesize;
5420 int *pack_fds = NULL;
5421 FILE *f1 = NULL, *f2 = NULL;
5423 fd1 = got_opentempfd();
5424 if (fd1 == -1)
5425 return got_error_from_errno("got_opentempfd");
5427 memset(&bca, 0, sizeof(bca));
5429 #ifndef PROFILE
5430 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5431 NULL) == -1)
5432 err(1, "pledge");
5433 #endif
5435 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5436 switch (ch) {
5437 case 'c':
5438 commit_id_str = optarg;
5439 break;
5440 case 'r':
5441 repo_path = realpath(optarg, NULL);
5442 if (repo_path == NULL)
5443 return got_error_from_errno2("realpath",
5444 optarg);
5445 got_path_strip_trailing_slashes(repo_path);
5446 break;
5447 default:
5448 usage_blame();
5449 /* NOTREACHED */
5453 argc -= optind;
5454 argv += optind;
5456 if (argc == 1)
5457 path = argv[0];
5458 else
5459 usage_blame();
5461 cwd = getcwd(NULL, 0);
5462 if (cwd == NULL) {
5463 error = got_error_from_errno("getcwd");
5464 goto done;
5467 error = got_repo_pack_fds_open(&pack_fds);
5468 if (error != NULL)
5469 goto done;
5471 if (repo_path == NULL) {
5472 error = got_worktree_open(&worktree, cwd);
5473 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5474 goto done;
5475 else
5476 error = NULL;
5477 if (worktree) {
5478 repo_path =
5479 strdup(got_worktree_get_repo_path(worktree));
5480 if (repo_path == NULL) {
5481 error = got_error_from_errno("strdup");
5482 if (error)
5483 goto done;
5485 } else {
5486 repo_path = strdup(cwd);
5487 if (repo_path == NULL) {
5488 error = got_error_from_errno("strdup");
5489 goto done;
5494 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5495 if (error != NULL)
5496 goto done;
5498 if (worktree) {
5499 const char *prefix = got_worktree_get_path_prefix(worktree);
5500 char *p;
5502 error = got_worktree_resolve_path(&p, worktree, path);
5503 if (error)
5504 goto done;
5505 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5506 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5507 p) == -1) {
5508 error = got_error_from_errno("asprintf");
5509 free(p);
5510 goto done;
5512 free(p);
5513 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5514 } else {
5515 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5516 if (error)
5517 goto done;
5518 error = got_repo_map_path(&in_repo_path, repo, path);
5520 if (error)
5521 goto done;
5523 if (commit_id_str == NULL) {
5524 struct got_reference *head_ref;
5525 error = got_ref_open(&head_ref, repo, worktree ?
5526 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5527 if (error != NULL)
5528 goto done;
5529 error = got_ref_resolve(&commit_id, repo, head_ref);
5530 got_ref_close(head_ref);
5531 if (error != NULL)
5532 goto done;
5533 } else {
5534 struct got_reflist_head refs;
5535 TAILQ_INIT(&refs);
5536 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5537 NULL);
5538 if (error)
5539 goto done;
5540 error = got_repo_match_object_id(&commit_id, NULL,
5541 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5542 got_ref_list_free(&refs);
5543 if (error)
5544 goto done;
5547 if (worktree) {
5548 /* Release work tree lock. */
5549 got_worktree_close(worktree);
5550 worktree = NULL;
5553 error = got_object_open_as_commit(&commit, repo, commit_id);
5554 if (error)
5555 goto done;
5557 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5558 commit, repo);
5559 if (error)
5560 goto done;
5562 error = got_object_id_by_path(&obj_id, repo, commit,
5563 link_target ? link_target : in_repo_path);
5564 if (error)
5565 goto done;
5567 error = got_object_get_type(&obj_type, repo, obj_id);
5568 if (error)
5569 goto done;
5571 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5572 error = got_error_path(link_target ? link_target : in_repo_path,
5573 GOT_ERR_OBJ_TYPE);
5574 goto done;
5577 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5578 if (error)
5579 goto done;
5580 bca.f = got_opentemp();
5581 if (bca.f == NULL) {
5582 error = got_error_from_errno("got_opentemp");
5583 goto done;
5585 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5586 &bca.line_offsets, bca.f, blob);
5587 if (error || bca.nlines == 0)
5588 goto done;
5590 /* Don't include \n at EOF in the blame line count. */
5591 if (bca.line_offsets[bca.nlines - 1] == filesize)
5592 bca.nlines--;
5594 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5595 if (bca.lines == NULL) {
5596 error = got_error_from_errno("calloc");
5597 goto done;
5599 bca.lineno_cur = 1;
5600 bca.nlines_prec = 0;
5601 i = bca.nlines;
5602 while (i > 0) {
5603 i /= 10;
5604 bca.nlines_prec++;
5606 bca.repo = repo;
5608 fd2 = got_opentempfd();
5609 if (fd2 == -1) {
5610 error = got_error_from_errno("got_opentempfd");
5611 goto done;
5613 fd3 = got_opentempfd();
5614 if (fd3 == -1) {
5615 error = got_error_from_errno("got_opentempfd");
5616 goto done;
5618 f1 = got_opentemp();
5619 if (f1 == NULL) {
5620 error = got_error_from_errno("got_opentemp");
5621 goto done;
5623 f2 = got_opentemp();
5624 if (f2 == NULL) {
5625 error = got_error_from_errno("got_opentemp");
5626 goto done;
5628 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5629 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5630 check_cancelled, NULL, fd2, fd3, f1, f2);
5631 done:
5632 free(in_repo_path);
5633 free(link_target);
5634 free(repo_path);
5635 free(cwd);
5636 free(commit_id);
5637 free(obj_id);
5638 if (commit)
5639 got_object_commit_close(commit);
5641 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5642 error = got_error_from_errno("close");
5643 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5644 error = got_error_from_errno("close");
5645 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5646 error = got_error_from_errno("close");
5647 if (f1 && fclose(f1) == EOF && error == NULL)
5648 error = got_error_from_errno("fclose");
5649 if (f2 && fclose(f2) == EOF && error == NULL)
5650 error = got_error_from_errno("fclose");
5652 if (blob)
5653 got_object_blob_close(blob);
5654 if (worktree)
5655 got_worktree_close(worktree);
5656 if (repo) {
5657 const struct got_error *close_err = got_repo_close(repo);
5658 if (error == NULL)
5659 error = close_err;
5661 if (pack_fds) {
5662 const struct got_error *pack_err =
5663 got_repo_pack_fds_close(pack_fds);
5664 if (error == NULL)
5665 error = pack_err;
5667 if (bca.lines) {
5668 for (i = 0; i < bca.nlines; i++) {
5669 struct blame_line *bline = &bca.lines[i];
5670 free(bline->id_str);
5671 free(bline->committer);
5673 free(bca.lines);
5675 free(bca.line_offsets);
5676 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5677 error = got_error_from_errno("fclose");
5678 return error;
5681 __dead static void
5682 usage_tree(void)
5684 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5685 "[path]\n", getprogname());
5686 exit(1);
5689 static const struct got_error *
5690 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5691 const char *root_path, struct got_repository *repo)
5693 const struct got_error *err = NULL;
5694 int is_root_path = (strcmp(path, root_path) == 0);
5695 const char *modestr = "";
5696 mode_t mode = got_tree_entry_get_mode(te);
5697 char *link_target = NULL;
5699 path += strlen(root_path);
5700 while (path[0] == '/')
5701 path++;
5703 if (got_object_tree_entry_is_submodule(te))
5704 modestr = "$";
5705 else if (S_ISLNK(mode)) {
5706 int i;
5708 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5709 if (err)
5710 return err;
5711 for (i = 0; i < strlen(link_target); i++) {
5712 if (!isprint((unsigned char)link_target[i]))
5713 link_target[i] = '?';
5716 modestr = "@";
5718 else if (S_ISDIR(mode))
5719 modestr = "/";
5720 else if (mode & S_IXUSR)
5721 modestr = "*";
5723 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5724 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5725 link_target ? " -> ": "", link_target ? link_target : "");
5727 free(link_target);
5728 return NULL;
5731 static const struct got_error *
5732 print_tree(const char *path, struct got_commit_object *commit,
5733 int show_ids, int recurse, const char *root_path,
5734 struct got_repository *repo)
5736 const struct got_error *err = NULL;
5737 struct got_object_id *tree_id = NULL;
5738 struct got_tree_object *tree = NULL;
5739 int nentries, i;
5741 err = got_object_id_by_path(&tree_id, repo, commit, path);
5742 if (err)
5743 goto done;
5745 err = got_object_open_as_tree(&tree, repo, tree_id);
5746 if (err)
5747 goto done;
5748 nentries = got_object_tree_get_nentries(tree);
5749 for (i = 0; i < nentries; i++) {
5750 struct got_tree_entry *te;
5751 char *id = NULL;
5753 if (sigint_received || sigpipe_received)
5754 break;
5756 te = got_object_tree_get_entry(tree, i);
5757 if (show_ids) {
5758 char *id_str;
5759 err = got_object_id_str(&id_str,
5760 got_tree_entry_get_id(te));
5761 if (err)
5762 goto done;
5763 if (asprintf(&id, "%s ", id_str) == -1) {
5764 err = got_error_from_errno("asprintf");
5765 free(id_str);
5766 goto done;
5768 free(id_str);
5770 err = print_entry(te, id, path, root_path, repo);
5771 free(id);
5772 if (err)
5773 goto done;
5775 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5776 char *child_path;
5777 if (asprintf(&child_path, "%s%s%s", path,
5778 path[0] == '/' && path[1] == '\0' ? "" : "/",
5779 got_tree_entry_get_name(te)) == -1) {
5780 err = got_error_from_errno("asprintf");
5781 goto done;
5783 err = print_tree(child_path, commit, show_ids, 1,
5784 root_path, repo);
5785 free(child_path);
5786 if (err)
5787 goto done;
5790 done:
5791 if (tree)
5792 got_object_tree_close(tree);
5793 free(tree_id);
5794 return err;
5797 static const struct got_error *
5798 cmd_tree(int argc, char *argv[])
5800 const struct got_error *error;
5801 struct got_repository *repo = NULL;
5802 struct got_worktree *worktree = NULL;
5803 const char *path, *refname = NULL;
5804 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5805 struct got_object_id *commit_id = NULL;
5806 struct got_commit_object *commit = NULL;
5807 char *commit_id_str = NULL;
5808 int show_ids = 0, recurse = 0;
5809 int ch;
5810 int *pack_fds = NULL;
5812 #ifndef PROFILE
5813 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5814 NULL) == -1)
5815 err(1, "pledge");
5816 #endif
5818 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5819 switch (ch) {
5820 case 'c':
5821 commit_id_str = optarg;
5822 break;
5823 case 'r':
5824 repo_path = realpath(optarg, NULL);
5825 if (repo_path == NULL)
5826 return got_error_from_errno2("realpath",
5827 optarg);
5828 got_path_strip_trailing_slashes(repo_path);
5829 break;
5830 case 'i':
5831 show_ids = 1;
5832 break;
5833 case 'R':
5834 recurse = 1;
5835 break;
5836 default:
5837 usage_tree();
5838 /* NOTREACHED */
5842 argc -= optind;
5843 argv += optind;
5845 if (argc == 1)
5846 path = argv[0];
5847 else if (argc > 1)
5848 usage_tree();
5849 else
5850 path = NULL;
5852 cwd = getcwd(NULL, 0);
5853 if (cwd == NULL) {
5854 error = got_error_from_errno("getcwd");
5855 goto done;
5858 error = got_repo_pack_fds_open(&pack_fds);
5859 if (error != NULL)
5860 goto done;
5862 if (repo_path == NULL) {
5863 error = got_worktree_open(&worktree, cwd);
5864 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5865 goto done;
5866 else
5867 error = NULL;
5868 if (worktree) {
5869 repo_path =
5870 strdup(got_worktree_get_repo_path(worktree));
5871 if (repo_path == NULL)
5872 error = got_error_from_errno("strdup");
5873 if (error)
5874 goto done;
5875 } else {
5876 repo_path = strdup(cwd);
5877 if (repo_path == NULL) {
5878 error = got_error_from_errno("strdup");
5879 goto done;
5884 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5885 if (error != NULL)
5886 goto done;
5888 if (worktree) {
5889 const char *prefix = got_worktree_get_path_prefix(worktree);
5890 char *p;
5892 if (path == NULL)
5893 path = "";
5894 error = got_worktree_resolve_path(&p, worktree, path);
5895 if (error)
5896 goto done;
5897 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5898 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5899 p) == -1) {
5900 error = got_error_from_errno("asprintf");
5901 free(p);
5902 goto done;
5904 free(p);
5905 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5906 if (error)
5907 goto done;
5908 } else {
5909 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5910 if (error)
5911 goto done;
5912 if (path == NULL)
5913 path = "/";
5914 error = got_repo_map_path(&in_repo_path, repo, path);
5915 if (error != NULL)
5916 goto done;
5919 if (commit_id_str == NULL) {
5920 struct got_reference *head_ref;
5921 if (worktree)
5922 refname = got_worktree_get_head_ref_name(worktree);
5923 else
5924 refname = GOT_REF_HEAD;
5925 error = got_ref_open(&head_ref, repo, refname, 0);
5926 if (error != NULL)
5927 goto done;
5928 error = got_ref_resolve(&commit_id, repo, head_ref);
5929 got_ref_close(head_ref);
5930 if (error != NULL)
5931 goto done;
5932 } else {
5933 struct got_reflist_head refs;
5934 TAILQ_INIT(&refs);
5935 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5936 NULL);
5937 if (error)
5938 goto done;
5939 error = got_repo_match_object_id(&commit_id, NULL,
5940 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5941 got_ref_list_free(&refs);
5942 if (error)
5943 goto done;
5946 if (worktree) {
5947 /* Release work tree lock. */
5948 got_worktree_close(worktree);
5949 worktree = NULL;
5952 error = got_object_open_as_commit(&commit, repo, commit_id);
5953 if (error)
5954 goto done;
5956 error = print_tree(in_repo_path, commit, show_ids, recurse,
5957 in_repo_path, repo);
5958 done:
5959 free(in_repo_path);
5960 free(repo_path);
5961 free(cwd);
5962 free(commit_id);
5963 if (commit)
5964 got_object_commit_close(commit);
5965 if (worktree)
5966 got_worktree_close(worktree);
5967 if (repo) {
5968 const struct got_error *close_err = got_repo_close(repo);
5969 if (error == NULL)
5970 error = close_err;
5972 if (pack_fds) {
5973 const struct got_error *pack_err =
5974 got_repo_pack_fds_close(pack_fds);
5975 if (error == NULL)
5976 error = pack_err;
5978 return error;
5981 __dead static void
5982 usage_status(void)
5984 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5985 "[-s status-codes] [path ...]\n", getprogname());
5986 exit(1);
5989 struct got_status_arg {
5990 char *status_codes;
5991 int suppress;
5994 static const struct got_error *
5995 print_status(void *arg, unsigned char status, unsigned char staged_status,
5996 const char *path, struct got_object_id *blob_id,
5997 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5998 int dirfd, const char *de_name)
6000 struct got_status_arg *st = arg;
6002 if (status == staged_status && (status == GOT_STATUS_DELETE))
6003 status = GOT_STATUS_NO_CHANGE;
6004 if (st != NULL && st->status_codes) {
6005 size_t ncodes = strlen(st->status_codes);
6006 int i, j = 0;
6008 for (i = 0; i < ncodes ; i++) {
6009 if (st->suppress) {
6010 if (status == st->status_codes[i] ||
6011 staged_status == st->status_codes[i]) {
6012 j++;
6013 continue;
6015 } else {
6016 if (status == st->status_codes[i] ||
6017 staged_status == st->status_codes[i])
6018 break;
6022 if (st->suppress && j == 0)
6023 goto print;
6025 if (i == ncodes)
6026 return NULL;
6028 print:
6029 printf("%c%c %s\n", status, staged_status, path);
6030 return NULL;
6033 static const struct got_error *
6034 cmd_status(int argc, char *argv[])
6036 const struct got_error *error = NULL;
6037 struct got_repository *repo = NULL;
6038 struct got_worktree *worktree = NULL;
6039 struct got_status_arg st;
6040 char *cwd = NULL;
6041 struct got_pathlist_head paths;
6042 struct got_pathlist_entry *pe;
6043 int ch, i, no_ignores = 0;
6044 int *pack_fds = NULL;
6046 TAILQ_INIT(&paths);
6048 memset(&st, 0, sizeof(st));
6049 st.status_codes = NULL;
6050 st.suppress = 0;
6052 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6053 switch (ch) {
6054 case 'I':
6055 no_ignores = 1;
6056 break;
6057 case 'S':
6058 if (st.status_codes != NULL && st.suppress == 0)
6059 option_conflict('S', 's');
6060 st.suppress = 1;
6061 /* fallthrough */
6062 case 's':
6063 for (i = 0; i < strlen(optarg); i++) {
6064 switch (optarg[i]) {
6065 case GOT_STATUS_MODIFY:
6066 case GOT_STATUS_ADD:
6067 case GOT_STATUS_DELETE:
6068 case GOT_STATUS_CONFLICT:
6069 case GOT_STATUS_MISSING:
6070 case GOT_STATUS_OBSTRUCTED:
6071 case GOT_STATUS_UNVERSIONED:
6072 case GOT_STATUS_MODE_CHANGE:
6073 case GOT_STATUS_NONEXISTENT:
6074 break;
6075 default:
6076 errx(1, "invalid status code '%c'",
6077 optarg[i]);
6080 if (ch == 's' && st.suppress)
6081 option_conflict('s', 'S');
6082 st.status_codes = optarg;
6083 break;
6084 default:
6085 usage_status();
6086 /* NOTREACHED */
6090 argc -= optind;
6091 argv += optind;
6093 #ifndef PROFILE
6094 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6095 NULL) == -1)
6096 err(1, "pledge");
6097 #endif
6098 cwd = getcwd(NULL, 0);
6099 if (cwd == NULL) {
6100 error = got_error_from_errno("getcwd");
6101 goto done;
6104 error = got_repo_pack_fds_open(&pack_fds);
6105 if (error != NULL)
6106 goto done;
6108 error = got_worktree_open(&worktree, cwd);
6109 if (error) {
6110 if (error->code == GOT_ERR_NOT_WORKTREE)
6111 error = wrap_not_worktree_error(error, "status", cwd);
6112 goto done;
6115 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6116 NULL, pack_fds);
6117 if (error != NULL)
6118 goto done;
6120 error = apply_unveil(got_repo_get_path(repo), 1,
6121 got_worktree_get_root_path(worktree));
6122 if (error)
6123 goto done;
6125 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6126 if (error)
6127 goto done;
6129 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6130 print_status, &st, check_cancelled, NULL);
6131 done:
6132 if (pack_fds) {
6133 const struct got_error *pack_err =
6134 got_repo_pack_fds_close(pack_fds);
6135 if (error == NULL)
6136 error = pack_err;
6139 TAILQ_FOREACH(pe, &paths, entry)
6140 free((char *)pe->path);
6141 got_pathlist_free(&paths);
6142 free(cwd);
6143 return error;
6146 __dead static void
6147 usage_ref(void)
6149 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6150 "[-s reference] [name]\n", getprogname());
6151 exit(1);
6154 static const struct got_error *
6155 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6157 static const struct got_error *err = NULL;
6158 struct got_reflist_head refs;
6159 struct got_reflist_entry *re;
6161 TAILQ_INIT(&refs);
6162 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6163 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6164 repo);
6165 if (err)
6166 return err;
6168 TAILQ_FOREACH(re, &refs, entry) {
6169 char *refstr;
6170 refstr = got_ref_to_str(re->ref);
6171 if (refstr == NULL) {
6172 err = got_error_from_errno("got_ref_to_str");
6173 break;
6175 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6176 free(refstr);
6179 got_ref_list_free(&refs);
6180 return err;
6183 static const struct got_error *
6184 delete_ref_by_name(struct got_repository *repo, const char *refname)
6186 const struct got_error *err;
6187 struct got_reference *ref;
6189 err = got_ref_open(&ref, repo, refname, 0);
6190 if (err)
6191 return err;
6193 err = delete_ref(repo, ref);
6194 got_ref_close(ref);
6195 return err;
6198 static const struct got_error *
6199 add_ref(struct got_repository *repo, const char *refname, const char *target)
6201 const struct got_error *err = NULL;
6202 struct got_object_id *id = NULL;
6203 struct got_reference *ref = NULL;
6204 struct got_reflist_head refs;
6207 * Don't let the user create a reference name with a leading '-'.
6208 * While technically a valid reference name, this case is usually
6209 * an unintended typo.
6211 if (refname[0] == '-')
6212 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6214 TAILQ_INIT(&refs);
6215 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6216 if (err)
6217 goto done;
6218 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6219 &refs, repo);
6220 got_ref_list_free(&refs);
6221 if (err)
6222 goto done;
6224 err = got_ref_alloc(&ref, refname, id);
6225 if (err)
6226 goto done;
6228 err = got_ref_write(ref, repo);
6229 done:
6230 if (ref)
6231 got_ref_close(ref);
6232 free(id);
6233 return err;
6236 static const struct got_error *
6237 add_symref(struct got_repository *repo, const char *refname, const char *target)
6239 const struct got_error *err = NULL;
6240 struct got_reference *ref = NULL;
6241 struct got_reference *target_ref = NULL;
6244 * Don't let the user create a reference name with a leading '-'.
6245 * While technically a valid reference name, this case is usually
6246 * an unintended typo.
6248 if (refname[0] == '-')
6249 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6251 err = got_ref_open(&target_ref, repo, target, 0);
6252 if (err)
6253 return err;
6255 err = got_ref_alloc_symref(&ref, refname, target_ref);
6256 if (err)
6257 goto done;
6259 err = got_ref_write(ref, repo);
6260 done:
6261 if (target_ref)
6262 got_ref_close(target_ref);
6263 if (ref)
6264 got_ref_close(ref);
6265 return err;
6268 static const struct got_error *
6269 cmd_ref(int argc, char *argv[])
6271 const struct got_error *error = NULL;
6272 struct got_repository *repo = NULL;
6273 struct got_worktree *worktree = NULL;
6274 char *cwd = NULL, *repo_path = NULL;
6275 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6276 const char *obj_arg = NULL, *symref_target= NULL;
6277 char *refname = NULL;
6278 int *pack_fds = NULL;
6280 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6281 switch (ch) {
6282 case 'c':
6283 obj_arg = optarg;
6284 break;
6285 case 'd':
6286 do_delete = 1;
6287 break;
6288 case 'r':
6289 repo_path = realpath(optarg, NULL);
6290 if (repo_path == NULL)
6291 return got_error_from_errno2("realpath",
6292 optarg);
6293 got_path_strip_trailing_slashes(repo_path);
6294 break;
6295 case 'l':
6296 do_list = 1;
6297 break;
6298 case 's':
6299 symref_target = optarg;
6300 break;
6301 case 't':
6302 sort_by_time = 1;
6303 break;
6304 default:
6305 usage_ref();
6306 /* NOTREACHED */
6310 if (obj_arg && do_list)
6311 option_conflict('c', 'l');
6312 if (obj_arg && do_delete)
6313 option_conflict('c', 'd');
6314 if (obj_arg && symref_target)
6315 option_conflict('c', 's');
6316 if (symref_target && do_delete)
6317 option_conflict('s', 'd');
6318 if (symref_target && do_list)
6319 option_conflict('s', 'l');
6320 if (do_delete && do_list)
6321 option_conflict('d', 'l');
6322 if (sort_by_time && !do_list)
6323 errx(1, "-t option requires -l option");
6325 argc -= optind;
6326 argv += optind;
6328 if (do_list) {
6329 if (argc != 0 && argc != 1)
6330 usage_ref();
6331 if (argc == 1) {
6332 refname = strdup(argv[0]);
6333 if (refname == NULL) {
6334 error = got_error_from_errno("strdup");
6335 goto done;
6338 } else {
6339 if (argc != 1)
6340 usage_ref();
6341 refname = strdup(argv[0]);
6342 if (refname == NULL) {
6343 error = got_error_from_errno("strdup");
6344 goto done;
6348 if (refname)
6349 got_path_strip_trailing_slashes(refname);
6351 #ifndef PROFILE
6352 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6353 "sendfd unveil", NULL) == -1)
6354 err(1, "pledge");
6355 #endif
6356 cwd = getcwd(NULL, 0);
6357 if (cwd == NULL) {
6358 error = got_error_from_errno("getcwd");
6359 goto done;
6362 error = got_repo_pack_fds_open(&pack_fds);
6363 if (error != NULL)
6364 goto done;
6366 if (repo_path == NULL) {
6367 error = got_worktree_open(&worktree, cwd);
6368 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6369 goto done;
6370 else
6371 error = NULL;
6372 if (worktree) {
6373 repo_path =
6374 strdup(got_worktree_get_repo_path(worktree));
6375 if (repo_path == NULL)
6376 error = got_error_from_errno("strdup");
6377 if (error)
6378 goto done;
6379 } else {
6380 repo_path = strdup(cwd);
6381 if (repo_path == NULL) {
6382 error = got_error_from_errno("strdup");
6383 goto done;
6388 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6389 if (error != NULL)
6390 goto done;
6392 #ifndef PROFILE
6393 if (do_list) {
6394 /* Remove "cpath" promise. */
6395 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6396 NULL) == -1)
6397 err(1, "pledge");
6399 #endif
6401 error = apply_unveil(got_repo_get_path(repo), do_list,
6402 worktree ? got_worktree_get_root_path(worktree) : NULL);
6403 if (error)
6404 goto done;
6406 if (do_list)
6407 error = list_refs(repo, refname, sort_by_time);
6408 else if (do_delete)
6409 error = delete_ref_by_name(repo, refname);
6410 else if (symref_target)
6411 error = add_symref(repo, refname, symref_target);
6412 else {
6413 if (obj_arg == NULL)
6414 usage_ref();
6415 error = add_ref(repo, refname, obj_arg);
6417 done:
6418 free(refname);
6419 if (repo) {
6420 const struct got_error *close_err = got_repo_close(repo);
6421 if (error == NULL)
6422 error = close_err;
6424 if (worktree)
6425 got_worktree_close(worktree);
6426 if (pack_fds) {
6427 const struct got_error *pack_err =
6428 got_repo_pack_fds_close(pack_fds);
6429 if (error == NULL)
6430 error = pack_err;
6432 free(cwd);
6433 free(repo_path);
6434 return error;
6437 __dead static void
6438 usage_branch(void)
6440 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6441 "[-r repository-path] [name]\n", getprogname());
6442 exit(1);
6445 static const struct got_error *
6446 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6447 struct got_reference *ref)
6449 const struct got_error *err = NULL;
6450 const char *refname, *marker = " ";
6451 char *refstr;
6453 refname = got_ref_get_name(ref);
6454 if (worktree && strcmp(refname,
6455 got_worktree_get_head_ref_name(worktree)) == 0) {
6456 struct got_object_id *id = NULL;
6458 err = got_ref_resolve(&id, repo, ref);
6459 if (err)
6460 return err;
6461 if (got_object_id_cmp(id,
6462 got_worktree_get_base_commit_id(worktree)) == 0)
6463 marker = "* ";
6464 else
6465 marker = "~ ";
6466 free(id);
6469 if (strncmp(refname, "refs/heads/", 11) == 0)
6470 refname += 11;
6471 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6472 refname += 18;
6473 if (strncmp(refname, "refs/remotes/", 13) == 0)
6474 refname += 13;
6476 refstr = got_ref_to_str(ref);
6477 if (refstr == NULL)
6478 return got_error_from_errno("got_ref_to_str");
6480 printf("%s%s: %s\n", marker, refname, refstr);
6481 free(refstr);
6482 return NULL;
6485 static const struct got_error *
6486 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6488 const char *refname;
6490 if (worktree == NULL)
6491 return got_error(GOT_ERR_NOT_WORKTREE);
6493 refname = got_worktree_get_head_ref_name(worktree);
6495 if (strncmp(refname, "refs/heads/", 11) == 0)
6496 refname += 11;
6497 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6498 refname += 18;
6500 printf("%s\n", refname);
6502 return NULL;
6505 static const struct got_error *
6506 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6507 int sort_by_time)
6509 static const struct got_error *err = NULL;
6510 struct got_reflist_head refs;
6511 struct got_reflist_entry *re;
6512 struct got_reference *temp_ref = NULL;
6513 int rebase_in_progress, histedit_in_progress;
6515 TAILQ_INIT(&refs);
6517 if (worktree) {
6518 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6519 worktree);
6520 if (err)
6521 return err;
6523 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6524 worktree);
6525 if (err)
6526 return err;
6528 if (rebase_in_progress || histedit_in_progress) {
6529 err = got_ref_open(&temp_ref, repo,
6530 got_worktree_get_head_ref_name(worktree), 0);
6531 if (err)
6532 return err;
6533 list_branch(repo, worktree, temp_ref);
6534 got_ref_close(temp_ref);
6538 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6539 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6540 repo);
6541 if (err)
6542 return err;
6544 TAILQ_FOREACH(re, &refs, entry)
6545 list_branch(repo, worktree, re->ref);
6547 got_ref_list_free(&refs);
6549 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6550 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6551 repo);
6552 if (err)
6553 return err;
6555 TAILQ_FOREACH(re, &refs, entry)
6556 list_branch(repo, worktree, re->ref);
6558 got_ref_list_free(&refs);
6560 return NULL;
6563 static const struct got_error *
6564 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6565 const char *branch_name)
6567 const struct got_error *err = NULL;
6568 struct got_reference *ref = NULL;
6569 char *refname, *remote_refname = NULL;
6571 if (strncmp(branch_name, "refs/", 5) == 0)
6572 branch_name += 5;
6573 if (strncmp(branch_name, "heads/", 6) == 0)
6574 branch_name += 6;
6575 else if (strncmp(branch_name, "remotes/", 8) == 0)
6576 branch_name += 8;
6578 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6579 return got_error_from_errno("asprintf");
6581 if (asprintf(&remote_refname, "refs/remotes/%s",
6582 branch_name) == -1) {
6583 err = got_error_from_errno("asprintf");
6584 goto done;
6587 err = got_ref_open(&ref, repo, refname, 0);
6588 if (err) {
6589 const struct got_error *err2;
6590 if (err->code != GOT_ERR_NOT_REF)
6591 goto done;
6593 * Keep 'err' intact such that if neither branch exists
6594 * we report "refs/heads" rather than "refs/remotes" in
6595 * our error message.
6597 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6598 if (err2)
6599 goto done;
6600 err = NULL;
6603 if (worktree &&
6604 strcmp(got_worktree_get_head_ref_name(worktree),
6605 got_ref_get_name(ref)) == 0) {
6606 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6607 "will not delete this work tree's current branch");
6608 goto done;
6611 err = delete_ref(repo, ref);
6612 done:
6613 if (ref)
6614 got_ref_close(ref);
6615 free(refname);
6616 free(remote_refname);
6617 return err;
6620 static const struct got_error *
6621 add_branch(struct got_repository *repo, const char *branch_name,
6622 struct got_object_id *base_commit_id)
6624 const struct got_error *err = NULL;
6625 struct got_reference *ref = NULL;
6626 char *base_refname = NULL, *refname = NULL;
6629 * Don't let the user create a branch name with a leading '-'.
6630 * While technically a valid reference name, this case is usually
6631 * an unintended typo.
6633 if (branch_name[0] == '-')
6634 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6636 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6637 branch_name += 11;
6639 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6640 err = got_error_from_errno("asprintf");
6641 goto done;
6644 err = got_ref_open(&ref, repo, refname, 0);
6645 if (err == NULL) {
6646 err = got_error(GOT_ERR_BRANCH_EXISTS);
6647 goto done;
6648 } else if (err->code != GOT_ERR_NOT_REF)
6649 goto done;
6651 err = got_ref_alloc(&ref, refname, base_commit_id);
6652 if (err)
6653 goto done;
6655 err = got_ref_write(ref, repo);
6656 done:
6657 if (ref)
6658 got_ref_close(ref);
6659 free(base_refname);
6660 free(refname);
6661 return err;
6664 static const struct got_error *
6665 cmd_branch(int argc, char *argv[])
6667 const struct got_error *error = NULL;
6668 struct got_repository *repo = NULL;
6669 struct got_worktree *worktree = NULL;
6670 char *cwd = NULL, *repo_path = NULL;
6671 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6672 const char *delref = NULL, *commit_id_arg = NULL;
6673 struct got_reference *ref = NULL;
6674 struct got_pathlist_head paths;
6675 struct got_pathlist_entry *pe;
6676 struct got_object_id *commit_id = NULL;
6677 char *commit_id_str = NULL;
6678 int *pack_fds = NULL;
6680 TAILQ_INIT(&paths);
6682 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6683 switch (ch) {
6684 case 'c':
6685 commit_id_arg = optarg;
6686 break;
6687 case 'd':
6688 delref = optarg;
6689 break;
6690 case 'r':
6691 repo_path = realpath(optarg, NULL);
6692 if (repo_path == NULL)
6693 return got_error_from_errno2("realpath",
6694 optarg);
6695 got_path_strip_trailing_slashes(repo_path);
6696 break;
6697 case 'l':
6698 do_list = 1;
6699 break;
6700 case 'n':
6701 do_update = 0;
6702 break;
6703 case 't':
6704 sort_by_time = 1;
6705 break;
6706 default:
6707 usage_branch();
6708 /* NOTREACHED */
6712 if (do_list && delref)
6713 option_conflict('l', 'd');
6714 if (sort_by_time && !do_list)
6715 errx(1, "-t option requires -l option");
6717 argc -= optind;
6718 argv += optind;
6720 if (!do_list && !delref && argc == 0)
6721 do_show = 1;
6723 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6724 errx(1, "-c option can only be used when creating a branch");
6726 if (do_list || delref) {
6727 if (argc > 0)
6728 usage_branch();
6729 } else if (!do_show && argc != 1)
6730 usage_branch();
6732 #ifndef PROFILE
6733 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6734 "sendfd unveil", NULL) == -1)
6735 err(1, "pledge");
6736 #endif
6737 cwd = getcwd(NULL, 0);
6738 if (cwd == NULL) {
6739 error = got_error_from_errno("getcwd");
6740 goto done;
6743 error = got_repo_pack_fds_open(&pack_fds);
6744 if (error != NULL)
6745 goto done;
6747 if (repo_path == NULL) {
6748 error = got_worktree_open(&worktree, cwd);
6749 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6750 goto done;
6751 else
6752 error = NULL;
6753 if (worktree) {
6754 repo_path =
6755 strdup(got_worktree_get_repo_path(worktree));
6756 if (repo_path == NULL)
6757 error = got_error_from_errno("strdup");
6758 if (error)
6759 goto done;
6760 } else {
6761 repo_path = strdup(cwd);
6762 if (repo_path == NULL) {
6763 error = got_error_from_errno("strdup");
6764 goto done;
6769 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6770 if (error != NULL)
6771 goto done;
6773 #ifndef PROFILE
6774 if (do_list || do_show) {
6775 /* Remove "cpath" promise. */
6776 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6777 NULL) == -1)
6778 err(1, "pledge");
6780 #endif
6782 error = apply_unveil(got_repo_get_path(repo), do_list,
6783 worktree ? got_worktree_get_root_path(worktree) : NULL);
6784 if (error)
6785 goto done;
6787 if (do_show)
6788 error = show_current_branch(repo, worktree);
6789 else if (do_list)
6790 error = list_branches(repo, worktree, sort_by_time);
6791 else if (delref)
6792 error = delete_branch(repo, worktree, delref);
6793 else {
6794 struct got_reflist_head refs;
6795 TAILQ_INIT(&refs);
6796 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6797 NULL);
6798 if (error)
6799 goto done;
6800 if (commit_id_arg == NULL)
6801 commit_id_arg = worktree ?
6802 got_worktree_get_head_ref_name(worktree) :
6803 GOT_REF_HEAD;
6804 error = got_repo_match_object_id(&commit_id, NULL,
6805 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6806 got_ref_list_free(&refs);
6807 if (error)
6808 goto done;
6809 error = add_branch(repo, argv[0], commit_id);
6810 if (error)
6811 goto done;
6812 if (worktree && do_update) {
6813 struct got_update_progress_arg upa;
6814 char *branch_refname = NULL;
6816 error = got_object_id_str(&commit_id_str, commit_id);
6817 if (error)
6818 goto done;
6819 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6820 worktree);
6821 if (error)
6822 goto done;
6823 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6824 == -1) {
6825 error = got_error_from_errno("asprintf");
6826 goto done;
6828 error = got_ref_open(&ref, repo, branch_refname, 0);
6829 free(branch_refname);
6830 if (error)
6831 goto done;
6832 error = switch_head_ref(ref, commit_id, worktree,
6833 repo);
6834 if (error)
6835 goto done;
6836 error = got_worktree_set_base_commit_id(worktree, repo,
6837 commit_id);
6838 if (error)
6839 goto done;
6840 memset(&upa, 0, sizeof(upa));
6841 error = got_worktree_checkout_files(worktree, &paths,
6842 repo, update_progress, &upa, check_cancelled,
6843 NULL);
6844 if (error)
6845 goto done;
6846 if (upa.did_something) {
6847 printf("Updated to %s: %s\n",
6848 got_worktree_get_head_ref_name(worktree),
6849 commit_id_str);
6851 print_update_progress_stats(&upa);
6854 done:
6855 if (ref)
6856 got_ref_close(ref);
6857 if (repo) {
6858 const struct got_error *close_err = got_repo_close(repo);
6859 if (error == NULL)
6860 error = close_err;
6862 if (worktree)
6863 got_worktree_close(worktree);
6864 if (pack_fds) {
6865 const struct got_error *pack_err =
6866 got_repo_pack_fds_close(pack_fds);
6867 if (error == NULL)
6868 error = pack_err;
6870 free(cwd);
6871 free(repo_path);
6872 free(commit_id);
6873 free(commit_id_str);
6874 TAILQ_FOREACH(pe, &paths, entry)
6875 free((char *)pe->path);
6876 got_pathlist_free(&paths);
6877 return error;
6881 __dead static void
6882 usage_tag(void)
6884 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6885 "[-r repository-path] [-s signer-id] name\n", getprogname());
6886 exit(1);
6889 #if 0
6890 static const struct got_error *
6891 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6893 const struct got_error *err = NULL;
6894 struct got_reflist_entry *re, *se, *new;
6895 struct got_object_id *re_id, *se_id;
6896 struct got_tag_object *re_tag, *se_tag;
6897 time_t re_time, se_time;
6899 STAILQ_FOREACH(re, tags, entry) {
6900 se = STAILQ_FIRST(sorted);
6901 if (se == NULL) {
6902 err = got_reflist_entry_dup(&new, re);
6903 if (err)
6904 return err;
6905 STAILQ_INSERT_HEAD(sorted, new, entry);
6906 continue;
6907 } else {
6908 err = got_ref_resolve(&re_id, repo, re->ref);
6909 if (err)
6910 break;
6911 err = got_object_open_as_tag(&re_tag, repo, re_id);
6912 free(re_id);
6913 if (err)
6914 break;
6915 re_time = got_object_tag_get_tagger_time(re_tag);
6916 got_object_tag_close(re_tag);
6919 while (se) {
6920 err = got_ref_resolve(&se_id, repo, re->ref);
6921 if (err)
6922 break;
6923 err = got_object_open_as_tag(&se_tag, repo, se_id);
6924 free(se_id);
6925 if (err)
6926 break;
6927 se_time = got_object_tag_get_tagger_time(se_tag);
6928 got_object_tag_close(se_tag);
6930 if (se_time > re_time) {
6931 err = got_reflist_entry_dup(&new, re);
6932 if (err)
6933 return err;
6934 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6935 break;
6937 se = STAILQ_NEXT(se, entry);
6938 continue;
6941 done:
6942 return err;
6944 #endif
6946 static const struct got_error *
6947 get_tag_refname(char **refname, const char *tag_name)
6949 const struct got_error *err;
6951 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6952 *refname = strdup(tag_name);
6953 if (*refname == NULL)
6954 return got_error_from_errno("strdup");
6955 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6956 err = got_error_from_errno("asprintf");
6957 *refname = NULL;
6958 return err;
6961 return NULL;
6964 static const struct got_error *
6965 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6966 const char *allowed_signers, const char *revoked_signers, int verbosity)
6968 static const struct got_error *err = NULL;
6969 struct got_reflist_head refs;
6970 struct got_reflist_entry *re;
6971 char *wanted_refname = NULL;
6972 int bad_sigs = 0;
6974 TAILQ_INIT(&refs);
6976 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6977 if (err)
6978 return err;
6980 if (tag_name) {
6981 struct got_reference *ref;
6982 err = get_tag_refname(&wanted_refname, tag_name);
6983 if (err)
6984 goto done;
6985 /* Wanted tag reference should exist. */
6986 err = got_ref_open(&ref, repo, wanted_refname, 0);
6987 if (err)
6988 goto done;
6989 got_ref_close(ref);
6992 TAILQ_FOREACH(re, &refs, entry) {
6993 const char *refname;
6994 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6995 char datebuf[26];
6996 const char *tagger, *ssh_sig = NULL;
6997 char *sig_msg = NULL;
6998 time_t tagger_time;
6999 struct got_object_id *id;
7000 struct got_tag_object *tag;
7001 struct got_commit_object *commit = NULL;
7003 refname = got_ref_get_name(re->ref);
7004 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7005 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7006 continue;
7007 refname += 10;
7008 refstr = got_ref_to_str(re->ref);
7009 if (refstr == NULL) {
7010 err = got_error_from_errno("got_ref_to_str");
7011 break;
7014 err = got_ref_resolve(&id, repo, re->ref);
7015 if (err)
7016 break;
7017 err = got_object_open_as_tag(&tag, repo, id);
7018 if (err) {
7019 if (err->code != GOT_ERR_OBJ_TYPE) {
7020 free(id);
7021 break;
7023 /* "lightweight" tag */
7024 err = got_object_open_as_commit(&commit, repo, id);
7025 if (err) {
7026 free(id);
7027 break;
7029 tagger = got_object_commit_get_committer(commit);
7030 tagger_time =
7031 got_object_commit_get_committer_time(commit);
7032 err = got_object_id_str(&id_str, id);
7033 free(id);
7034 if (err)
7035 break;
7036 } else {
7037 free(id);
7038 tagger = got_object_tag_get_tagger(tag);
7039 tagger_time = got_object_tag_get_tagger_time(tag);
7040 err = got_object_id_str(&id_str,
7041 got_object_tag_get_object_id(tag));
7042 if (err)
7043 break;
7046 if (verify_tags) {
7047 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7048 got_object_tag_get_message(tag));
7049 if (ssh_sig && allowed_signers == NULL) {
7050 err = got_error_msg(
7051 GOT_ERR_VERIFY_TAG_SIGNATURE,
7052 "SSH signature verification requires "
7053 "setting allowed_signers in "
7054 "got.conf(5)");
7055 break;
7059 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7060 free(refstr);
7061 printf("from: %s\n", tagger);
7062 datestr = get_datestr(&tagger_time, datebuf);
7063 if (datestr)
7064 printf("date: %s UTC\n", datestr);
7065 if (commit)
7066 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7067 else {
7068 switch (got_object_tag_get_object_type(tag)) {
7069 case GOT_OBJ_TYPE_BLOB:
7070 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7071 id_str);
7072 break;
7073 case GOT_OBJ_TYPE_TREE:
7074 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7075 id_str);
7076 break;
7077 case GOT_OBJ_TYPE_COMMIT:
7078 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7079 id_str);
7080 break;
7081 case GOT_OBJ_TYPE_TAG:
7082 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7083 id_str);
7084 break;
7085 default:
7086 break;
7089 free(id_str);
7091 if (ssh_sig) {
7092 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7093 allowed_signers, revoked_signers, verbosity);
7094 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7095 bad_sigs = 1;
7096 else if (err)
7097 break;
7098 printf("signature: %s", sig_msg);
7099 free(sig_msg);
7100 sig_msg = NULL;
7103 if (commit) {
7104 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7105 if (err)
7106 break;
7107 got_object_commit_close(commit);
7108 } else {
7109 tagmsg0 = strdup(got_object_tag_get_message(tag));
7110 got_object_tag_close(tag);
7111 if (tagmsg0 == NULL) {
7112 err = got_error_from_errno("strdup");
7113 break;
7117 tagmsg = tagmsg0;
7118 do {
7119 line = strsep(&tagmsg, "\n");
7120 if (line)
7121 printf(" %s\n", line);
7122 } while (line);
7123 free(tagmsg0);
7125 done:
7126 got_ref_list_free(&refs);
7127 free(wanted_refname);
7129 if (err == NULL && bad_sigs)
7130 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7131 return err;
7134 static const struct got_error *
7135 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7136 const char *tag_name, const char *repo_path)
7138 const struct got_error *err = NULL;
7139 char *template = NULL, *initial_content = NULL;
7140 char *editor = NULL;
7141 int initial_content_len;
7142 int fd = -1;
7144 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7145 err = got_error_from_errno("asprintf");
7146 goto done;
7149 initial_content_len = asprintf(&initial_content,
7150 "\n# tagging commit %s as %s\n",
7151 commit_id_str, tag_name);
7152 if (initial_content_len == -1) {
7153 err = got_error_from_errno("asprintf");
7154 goto done;
7157 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7158 if (err)
7159 goto done;
7161 if (write(fd, initial_content, initial_content_len) == -1) {
7162 err = got_error_from_errno2("write", *tagmsg_path);
7163 goto done;
7166 err = get_editor(&editor);
7167 if (err)
7168 goto done;
7169 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7170 initial_content_len, 1);
7171 done:
7172 free(initial_content);
7173 free(template);
7174 free(editor);
7176 if (fd != -1 && close(fd) == -1 && err == NULL)
7177 err = got_error_from_errno2("close", *tagmsg_path);
7179 if (err) {
7180 free(*tagmsg);
7181 *tagmsg = NULL;
7183 return err;
7186 static const struct got_error *
7187 add_tag(struct got_repository *repo, const char *tagger,
7188 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7189 const char *signer_id, int verbosity)
7191 const struct got_error *err = NULL;
7192 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7193 char *label = NULL, *commit_id_str = NULL;
7194 struct got_reference *ref = NULL;
7195 char *refname = NULL, *tagmsg = NULL;
7196 char *tagmsg_path = NULL, *tag_id_str = NULL;
7197 int preserve_tagmsg = 0;
7198 struct got_reflist_head refs;
7200 TAILQ_INIT(&refs);
7203 * Don't let the user create a tag name with a leading '-'.
7204 * While technically a valid reference name, this case is usually
7205 * an unintended typo.
7207 if (tag_name[0] == '-')
7208 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7210 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7211 if (err)
7212 goto done;
7214 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7215 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7216 if (err)
7217 goto done;
7219 err = got_object_id_str(&commit_id_str, commit_id);
7220 if (err)
7221 goto done;
7223 err = get_tag_refname(&refname, tag_name);
7224 if (err)
7225 goto done;
7226 if (strncmp("refs/tags/", tag_name, 10) == 0)
7227 tag_name += 10;
7229 err = got_ref_open(&ref, repo, refname, 0);
7230 if (err == NULL) {
7231 err = got_error(GOT_ERR_TAG_EXISTS);
7232 goto done;
7233 } else if (err->code != GOT_ERR_NOT_REF)
7234 goto done;
7236 if (tagmsg_arg == NULL) {
7237 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7238 tag_name, got_repo_get_path(repo));
7239 if (err) {
7240 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7241 tagmsg_path != NULL)
7242 preserve_tagmsg = 1;
7243 goto done;
7245 /* Editor is done; we can now apply unveil(2) */
7246 err = got_sigs_apply_unveil();
7247 if (err)
7248 goto done;
7249 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7250 if (err)
7251 goto done;
7254 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7255 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7256 verbosity);
7257 if (err) {
7258 if (tagmsg_path)
7259 preserve_tagmsg = 1;
7260 goto done;
7263 err = got_ref_alloc(&ref, refname, tag_id);
7264 if (err) {
7265 if (tagmsg_path)
7266 preserve_tagmsg = 1;
7267 goto done;
7270 err = got_ref_write(ref, repo);
7271 if (err) {
7272 if (tagmsg_path)
7273 preserve_tagmsg = 1;
7274 goto done;
7277 err = got_object_id_str(&tag_id_str, tag_id);
7278 if (err) {
7279 if (tagmsg_path)
7280 preserve_tagmsg = 1;
7281 goto done;
7283 printf("Created tag %s\n", tag_id_str);
7284 done:
7285 if (preserve_tagmsg) {
7286 fprintf(stderr, "%s: tag message preserved in %s\n",
7287 getprogname(), tagmsg_path);
7288 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7289 err = got_error_from_errno2("unlink", tagmsg_path);
7290 free(tag_id_str);
7291 if (ref)
7292 got_ref_close(ref);
7293 free(commit_id);
7294 free(commit_id_str);
7295 free(refname);
7296 free(tagmsg);
7297 free(tagmsg_path);
7298 got_ref_list_free(&refs);
7299 return err;
7302 static const struct got_error *
7303 cmd_tag(int argc, char *argv[])
7305 const struct got_error *error = NULL;
7306 struct got_repository *repo = NULL;
7307 struct got_worktree *worktree = NULL;
7308 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7309 char *gitconfig_path = NULL, *tagger = NULL;
7310 char *allowed_signers = NULL, *revoked_signers = NULL;
7311 char *signer_id = NULL;
7312 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7313 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7314 int *pack_fds = NULL;
7316 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7317 switch (ch) {
7318 case 'c':
7319 commit_id_arg = optarg;
7320 break;
7321 case 'm':
7322 tagmsg = optarg;
7323 break;
7324 case 'r':
7325 repo_path = realpath(optarg, NULL);
7326 if (repo_path == NULL) {
7327 error = got_error_from_errno2("realpath",
7328 optarg);
7329 goto done;
7331 got_path_strip_trailing_slashes(repo_path);
7332 break;
7333 case 'l':
7334 do_list = 1;
7335 break;
7336 case 's':
7337 signer_id = strdup(optarg);
7338 if (signer_id == NULL) {
7339 error = got_error_from_errno("strdup");
7340 goto done;
7342 break;
7343 case 'V':
7344 verify_tags = 1;
7345 break;
7346 case 'v':
7347 if (verbosity < 0)
7348 verbosity = 0;
7349 else if (verbosity < 3)
7350 verbosity++;
7351 break;
7352 default:
7353 usage_tag();
7354 /* NOTREACHED */
7358 argc -= optind;
7359 argv += optind;
7361 if (do_list || verify_tags) {
7362 if (commit_id_arg != NULL)
7363 errx(1,
7364 "-c option can only be used when creating a tag");
7365 if (tagmsg) {
7366 if (do_list)
7367 option_conflict('l', 'm');
7368 else
7369 option_conflict('V', 'm');
7371 if (signer_id) {
7372 if (do_list)
7373 option_conflict('l', 's');
7374 else
7375 option_conflict('V', 's');
7377 if (argc > 1)
7378 usage_tag();
7379 } else if (argc != 1)
7380 usage_tag();
7382 if (argc == 1)
7383 tag_name = argv[0];
7385 #ifndef PROFILE
7386 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7387 "sendfd unveil", NULL) == -1)
7388 err(1, "pledge");
7389 #endif
7390 cwd = getcwd(NULL, 0);
7391 if (cwd == NULL) {
7392 error = got_error_from_errno("getcwd");
7393 goto done;
7396 error = got_repo_pack_fds_open(&pack_fds);
7397 if (error != NULL)
7398 goto done;
7400 if (repo_path == NULL) {
7401 error = got_worktree_open(&worktree, cwd);
7402 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7403 goto done;
7404 else
7405 error = NULL;
7406 if (worktree) {
7407 repo_path =
7408 strdup(got_worktree_get_repo_path(worktree));
7409 if (repo_path == NULL)
7410 error = got_error_from_errno("strdup");
7411 if (error)
7412 goto done;
7413 } else {
7414 repo_path = strdup(cwd);
7415 if (repo_path == NULL) {
7416 error = got_error_from_errno("strdup");
7417 goto done;
7422 if (do_list || verify_tags) {
7423 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7424 if (error != NULL)
7425 goto done;
7426 error = get_allowed_signers(&allowed_signers, repo, worktree);
7427 if (error)
7428 goto done;
7429 error = get_revoked_signers(&revoked_signers, repo, worktree);
7430 if (error)
7431 goto done;
7432 if (worktree) {
7433 /* Release work tree lock. */
7434 got_worktree_close(worktree);
7435 worktree = NULL;
7439 * Remove "cpath" promise unless needed for signature tmpfile
7440 * creation.
7442 if (verify_tags)
7443 got_sigs_apply_unveil();
7444 else {
7445 #ifndef PROFILE
7446 if (pledge("stdio rpath wpath flock proc exec sendfd "
7447 "unveil", NULL) == -1)
7448 err(1, "pledge");
7449 #endif
7451 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7452 if (error)
7453 goto done;
7454 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7455 revoked_signers, verbosity);
7456 } else {
7457 error = get_gitconfig_path(&gitconfig_path);
7458 if (error)
7459 goto done;
7460 error = got_repo_open(&repo, repo_path, gitconfig_path,
7461 pack_fds);
7462 if (error != NULL)
7463 goto done;
7465 error = get_author(&tagger, repo, worktree);
7466 if (error)
7467 goto done;
7468 if (signer_id == NULL) {
7469 error = get_signer_id(&signer_id, repo, worktree);
7470 if (error)
7471 goto done;
7474 if (tagmsg) {
7475 if (signer_id) {
7476 error = got_sigs_apply_unveil();
7477 if (error)
7478 goto done;
7480 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7481 if (error)
7482 goto done;
7485 if (commit_id_arg == NULL) {
7486 struct got_reference *head_ref;
7487 struct got_object_id *commit_id;
7488 error = got_ref_open(&head_ref, repo,
7489 worktree ? got_worktree_get_head_ref_name(worktree)
7490 : GOT_REF_HEAD, 0);
7491 if (error)
7492 goto done;
7493 error = got_ref_resolve(&commit_id, repo, head_ref);
7494 got_ref_close(head_ref);
7495 if (error)
7496 goto done;
7497 error = got_object_id_str(&commit_id_str, commit_id);
7498 free(commit_id);
7499 if (error)
7500 goto done;
7503 if (worktree) {
7504 /* Release work tree lock. */
7505 got_worktree_close(worktree);
7506 worktree = NULL;
7509 error = add_tag(repo, tagger, tag_name,
7510 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7511 signer_id, verbosity);
7513 done:
7514 if (repo) {
7515 const struct got_error *close_err = got_repo_close(repo);
7516 if (error == NULL)
7517 error = close_err;
7519 if (worktree)
7520 got_worktree_close(worktree);
7521 if (pack_fds) {
7522 const struct got_error *pack_err =
7523 got_repo_pack_fds_close(pack_fds);
7524 if (error == NULL)
7525 error = pack_err;
7527 free(cwd);
7528 free(repo_path);
7529 free(gitconfig_path);
7530 free(commit_id_str);
7531 free(tagger);
7532 free(allowed_signers);
7533 free(revoked_signers);
7534 free(signer_id);
7535 return error;
7538 __dead static void
7539 usage_add(void)
7541 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7542 exit(1);
7545 static const struct got_error *
7546 add_progress(void *arg, unsigned char status, const char *path)
7548 while (path[0] == '/')
7549 path++;
7550 printf("%c %s\n", status, path);
7551 return NULL;
7554 static const struct got_error *
7555 cmd_add(int argc, char *argv[])
7557 const struct got_error *error = NULL;
7558 struct got_repository *repo = NULL;
7559 struct got_worktree *worktree = NULL;
7560 char *cwd = NULL;
7561 struct got_pathlist_head paths;
7562 struct got_pathlist_entry *pe;
7563 int ch, can_recurse = 0, no_ignores = 0;
7564 int *pack_fds = NULL;
7566 TAILQ_INIT(&paths);
7568 while ((ch = getopt(argc, argv, "IR")) != -1) {
7569 switch (ch) {
7570 case 'I':
7571 no_ignores = 1;
7572 break;
7573 case 'R':
7574 can_recurse = 1;
7575 break;
7576 default:
7577 usage_add();
7578 /* NOTREACHED */
7582 argc -= optind;
7583 argv += optind;
7585 #ifndef PROFILE
7586 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7587 NULL) == -1)
7588 err(1, "pledge");
7589 #endif
7590 if (argc < 1)
7591 usage_add();
7593 cwd = getcwd(NULL, 0);
7594 if (cwd == NULL) {
7595 error = got_error_from_errno("getcwd");
7596 goto done;
7599 error = got_repo_pack_fds_open(&pack_fds);
7600 if (error != NULL)
7601 goto done;
7603 error = got_worktree_open(&worktree, cwd);
7604 if (error) {
7605 if (error->code == GOT_ERR_NOT_WORKTREE)
7606 error = wrap_not_worktree_error(error, "add", cwd);
7607 goto done;
7610 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7611 NULL, pack_fds);
7612 if (error != NULL)
7613 goto done;
7615 error = apply_unveil(got_repo_get_path(repo), 1,
7616 got_worktree_get_root_path(worktree));
7617 if (error)
7618 goto done;
7620 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7621 if (error)
7622 goto done;
7624 if (!can_recurse) {
7625 char *ondisk_path;
7626 struct stat sb;
7627 TAILQ_FOREACH(pe, &paths, entry) {
7628 if (asprintf(&ondisk_path, "%s/%s",
7629 got_worktree_get_root_path(worktree),
7630 pe->path) == -1) {
7631 error = got_error_from_errno("asprintf");
7632 goto done;
7634 if (lstat(ondisk_path, &sb) == -1) {
7635 if (errno == ENOENT) {
7636 free(ondisk_path);
7637 continue;
7639 error = got_error_from_errno2("lstat",
7640 ondisk_path);
7641 free(ondisk_path);
7642 goto done;
7644 free(ondisk_path);
7645 if (S_ISDIR(sb.st_mode)) {
7646 error = got_error_msg(GOT_ERR_BAD_PATH,
7647 "adding directories requires -R option");
7648 goto done;
7653 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7654 NULL, repo, no_ignores);
7655 done:
7656 if (repo) {
7657 const struct got_error *close_err = got_repo_close(repo);
7658 if (error == NULL)
7659 error = close_err;
7661 if (worktree)
7662 got_worktree_close(worktree);
7663 if (pack_fds) {
7664 const struct got_error *pack_err =
7665 got_repo_pack_fds_close(pack_fds);
7666 if (error == NULL)
7667 error = pack_err;
7669 TAILQ_FOREACH(pe, &paths, entry)
7670 free((char *)pe->path);
7671 got_pathlist_free(&paths);
7672 free(cwd);
7673 return error;
7676 __dead static void
7677 usage_remove(void)
7679 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7680 getprogname());
7681 exit(1);
7684 static const struct got_error *
7685 print_remove_status(void *arg, unsigned char status,
7686 unsigned char staged_status, const char *path)
7688 while (path[0] == '/')
7689 path++;
7690 if (status == GOT_STATUS_NONEXISTENT)
7691 return NULL;
7692 if (status == staged_status && (status == GOT_STATUS_DELETE))
7693 status = GOT_STATUS_NO_CHANGE;
7694 printf("%c%c %s\n", status, staged_status, path);
7695 return NULL;
7698 static const struct got_error *
7699 cmd_remove(int argc, char *argv[])
7701 const struct got_error *error = NULL;
7702 struct got_worktree *worktree = NULL;
7703 struct got_repository *repo = NULL;
7704 const char *status_codes = NULL;
7705 char *cwd = NULL;
7706 struct got_pathlist_head paths;
7707 struct got_pathlist_entry *pe;
7708 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7709 int ignore_missing_paths = 0;
7710 int *pack_fds = NULL;
7712 TAILQ_INIT(&paths);
7714 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7715 switch (ch) {
7716 case 'f':
7717 delete_local_mods = 1;
7718 ignore_missing_paths = 1;
7719 break;
7720 case 'k':
7721 keep_on_disk = 1;
7722 break;
7723 case 'R':
7724 can_recurse = 1;
7725 break;
7726 case 's':
7727 for (i = 0; i < strlen(optarg); i++) {
7728 switch (optarg[i]) {
7729 case GOT_STATUS_MODIFY:
7730 delete_local_mods = 1;
7731 break;
7732 case GOT_STATUS_MISSING:
7733 ignore_missing_paths = 1;
7734 break;
7735 default:
7736 errx(1, "invalid status code '%c'",
7737 optarg[i]);
7740 status_codes = optarg;
7741 break;
7742 default:
7743 usage_remove();
7744 /* NOTREACHED */
7748 argc -= optind;
7749 argv += optind;
7751 #ifndef PROFILE
7752 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7753 NULL) == -1)
7754 err(1, "pledge");
7755 #endif
7756 if (argc < 1)
7757 usage_remove();
7759 cwd = getcwd(NULL, 0);
7760 if (cwd == NULL) {
7761 error = got_error_from_errno("getcwd");
7762 goto done;
7765 error = got_repo_pack_fds_open(&pack_fds);
7766 if (error != NULL)
7767 goto done;
7769 error = got_worktree_open(&worktree, cwd);
7770 if (error) {
7771 if (error->code == GOT_ERR_NOT_WORKTREE)
7772 error = wrap_not_worktree_error(error, "remove", cwd);
7773 goto done;
7776 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7777 NULL, pack_fds);
7778 if (error)
7779 goto done;
7781 error = apply_unveil(got_repo_get_path(repo), 1,
7782 got_worktree_get_root_path(worktree));
7783 if (error)
7784 goto done;
7786 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7787 if (error)
7788 goto done;
7790 if (!can_recurse) {
7791 char *ondisk_path;
7792 struct stat sb;
7793 TAILQ_FOREACH(pe, &paths, entry) {
7794 if (asprintf(&ondisk_path, "%s/%s",
7795 got_worktree_get_root_path(worktree),
7796 pe->path) == -1) {
7797 error = got_error_from_errno("asprintf");
7798 goto done;
7800 if (lstat(ondisk_path, &sb) == -1) {
7801 if (errno == ENOENT) {
7802 free(ondisk_path);
7803 continue;
7805 error = got_error_from_errno2("lstat",
7806 ondisk_path);
7807 free(ondisk_path);
7808 goto done;
7810 free(ondisk_path);
7811 if (S_ISDIR(sb.st_mode)) {
7812 error = got_error_msg(GOT_ERR_BAD_PATH,
7813 "removing directories requires -R option");
7814 goto done;
7819 error = got_worktree_schedule_delete(worktree, &paths,
7820 delete_local_mods, status_codes, print_remove_status, NULL,
7821 repo, keep_on_disk, ignore_missing_paths);
7822 done:
7823 if (repo) {
7824 const struct got_error *close_err = got_repo_close(repo);
7825 if (error == NULL)
7826 error = close_err;
7828 if (worktree)
7829 got_worktree_close(worktree);
7830 if (pack_fds) {
7831 const struct got_error *pack_err =
7832 got_repo_pack_fds_close(pack_fds);
7833 if (error == NULL)
7834 error = pack_err;
7836 TAILQ_FOREACH(pe, &paths, entry)
7837 free((char *)pe->path);
7838 got_pathlist_free(&paths);
7839 free(cwd);
7840 return error;
7843 __dead static void
7844 usage_patch(void)
7846 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7847 "[patchfile]\n", getprogname());
7848 exit(1);
7851 static const struct got_error *
7852 patch_from_stdin(int *patchfd)
7854 const struct got_error *err = NULL;
7855 ssize_t r;
7856 char *path, buf[BUFSIZ];
7857 sig_t sighup, sigint, sigquit;
7859 err = got_opentemp_named_fd(&path, patchfd,
7860 GOT_TMPDIR_STR "/got-patch");
7861 if (err)
7862 return err;
7863 unlink(path);
7864 free(path);
7866 sighup = signal(SIGHUP, SIG_DFL);
7867 sigint = signal(SIGINT, SIG_DFL);
7868 sigquit = signal(SIGQUIT, SIG_DFL);
7870 for (;;) {
7871 r = read(0, buf, sizeof(buf));
7872 if (r == -1) {
7873 err = got_error_from_errno("read");
7874 break;
7876 if (r == 0)
7877 break;
7878 if (write(*patchfd, buf, r) == -1) {
7879 err = got_error_from_errno("write");
7880 break;
7884 signal(SIGHUP, sighup);
7885 signal(SIGINT, sigint);
7886 signal(SIGQUIT, sigquit);
7888 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7889 err = got_error_from_errno("lseek");
7891 if (err != NULL) {
7892 close(*patchfd);
7893 *patchfd = -1;
7896 return err;
7899 static const struct got_error *
7900 patch_progress(void *arg, const char *old, const char *new,
7901 unsigned char status, const struct got_error *error, int old_from,
7902 int old_lines, int new_from, int new_lines, int offset,
7903 int ws_mangled, const struct got_error *hunk_err)
7905 const char *path = new == NULL ? old : new;
7907 while (*path == '/')
7908 path++;
7910 if (status != 0)
7911 printf("%c %s\n", status, path);
7913 if (error != NULL)
7914 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7916 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7917 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7918 old_lines, new_from, new_lines);
7919 if (hunk_err != NULL)
7920 printf("%s\n", hunk_err->msg);
7921 else if (offset != 0)
7922 printf("applied with offset %d\n", offset);
7923 else
7924 printf("hunk contains mangled whitespace\n");
7927 return NULL;
7930 static const struct got_error *
7931 cmd_patch(int argc, char *argv[])
7933 const struct got_error *error = NULL, *close_error = NULL;
7934 struct got_worktree *worktree = NULL;
7935 struct got_repository *repo = NULL;
7936 struct got_reflist_head refs;
7937 struct got_object_id *commit_id = NULL;
7938 const char *commit_id_str = NULL;
7939 struct stat sb;
7940 const char *errstr;
7941 char *cwd = NULL;
7942 int ch, nop = 0, strip = -1, reverse = 0;
7943 int patchfd;
7944 int *pack_fds = NULL;
7946 TAILQ_INIT(&refs);
7948 #ifndef PROFILE
7949 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7950 "unveil", NULL) == -1)
7951 err(1, "pledge");
7952 #endif
7954 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7955 switch (ch) {
7956 case 'c':
7957 commit_id_str = optarg;
7958 break;
7959 case 'n':
7960 nop = 1;
7961 break;
7962 case 'p':
7963 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7964 if (errstr != NULL)
7965 errx(1, "pathname strip count is %s: %s",
7966 errstr, optarg);
7967 break;
7968 case 'R':
7969 reverse = 1;
7970 break;
7971 default:
7972 usage_patch();
7973 /* NOTREACHED */
7977 argc -= optind;
7978 argv += optind;
7980 if (argc == 0) {
7981 error = patch_from_stdin(&patchfd);
7982 if (error)
7983 return error;
7984 } else if (argc == 1) {
7985 patchfd = open(argv[0], O_RDONLY);
7986 if (patchfd == -1) {
7987 error = got_error_from_errno2("open", argv[0]);
7988 return error;
7990 if (fstat(patchfd, &sb) == -1) {
7991 error = got_error_from_errno2("fstat", argv[0]);
7992 goto done;
7994 if (!S_ISREG(sb.st_mode)) {
7995 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
7996 goto done;
7998 } else
7999 usage_patch();
8001 if ((cwd = getcwd(NULL, 0)) == NULL) {
8002 error = got_error_from_errno("getcwd");
8003 goto done;
8006 error = got_repo_pack_fds_open(&pack_fds);
8007 if (error != NULL)
8008 goto done;
8010 error = got_worktree_open(&worktree, cwd);
8011 if (error != NULL)
8012 goto done;
8014 const char *repo_path = got_worktree_get_repo_path(worktree);
8015 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8016 if (error != NULL)
8017 goto done;
8019 error = apply_unveil(got_repo_get_path(repo), 0,
8020 got_worktree_get_root_path(worktree));
8021 if (error != NULL)
8022 goto done;
8024 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8025 if (error)
8026 goto done;
8028 if (commit_id_str != NULL) {
8029 error = got_repo_match_object_id(&commit_id, NULL,
8030 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8031 if (error)
8032 goto done;
8035 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8036 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8038 done:
8039 got_ref_list_free(&refs);
8040 free(commit_id);
8041 if (repo) {
8042 close_error = got_repo_close(repo);
8043 if (error == NULL)
8044 error = close_error;
8046 if (worktree != NULL) {
8047 close_error = got_worktree_close(worktree);
8048 if (error == NULL)
8049 error = close_error;
8051 if (pack_fds) {
8052 const struct got_error *pack_err =
8053 got_repo_pack_fds_close(pack_fds);
8054 if (error == NULL)
8055 error = pack_err;
8057 free(cwd);
8058 return error;
8061 __dead static void
8062 usage_revert(void)
8064 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8065 getprogname());
8066 exit(1);
8069 static const struct got_error *
8070 revert_progress(void *arg, unsigned char status, const char *path)
8072 if (status == GOT_STATUS_UNVERSIONED)
8073 return NULL;
8075 while (path[0] == '/')
8076 path++;
8077 printf("%c %s\n", status, path);
8078 return NULL;
8081 struct choose_patch_arg {
8082 FILE *patch_script_file;
8083 const char *action;
8086 static const struct got_error *
8087 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8088 int nchanges, const char *action)
8090 const struct got_error *err;
8091 char *line = NULL;
8092 size_t linesize = 0;
8093 ssize_t linelen;
8095 switch (status) {
8096 case GOT_STATUS_ADD:
8097 printf("A %s\n%s this addition? [y/n] ", path, action);
8098 break;
8099 case GOT_STATUS_DELETE:
8100 printf("D %s\n%s this deletion? [y/n] ", path, action);
8101 break;
8102 case GOT_STATUS_MODIFY:
8103 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8104 return got_error_from_errno("fseek");
8105 printf(GOT_COMMIT_SEP_STR);
8106 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8107 printf("%s", line);
8108 if (linelen == -1 && ferror(patch_file)) {
8109 err = got_error_from_errno("getline");
8110 free(line);
8111 return err;
8113 free(line);
8114 printf(GOT_COMMIT_SEP_STR);
8115 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8116 path, n, nchanges, action);
8117 break;
8118 default:
8119 return got_error_path(path, GOT_ERR_FILE_STATUS);
8122 return NULL;
8125 static const struct got_error *
8126 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8127 FILE *patch_file, int n, int nchanges)
8129 const struct got_error *err = NULL;
8130 char *line = NULL;
8131 size_t linesize = 0;
8132 ssize_t linelen;
8133 int resp = ' ';
8134 struct choose_patch_arg *a = arg;
8136 *choice = GOT_PATCH_CHOICE_NONE;
8138 if (a->patch_script_file) {
8139 char *nl;
8140 err = show_change(status, path, patch_file, n, nchanges,
8141 a->action);
8142 if (err)
8143 return err;
8144 linelen = getline(&line, &linesize, a->patch_script_file);
8145 if (linelen == -1) {
8146 if (ferror(a->patch_script_file))
8147 return got_error_from_errno("getline");
8148 return NULL;
8150 nl = strchr(line, '\n');
8151 if (nl)
8152 *nl = '\0';
8153 if (strcmp(line, "y") == 0) {
8154 *choice = GOT_PATCH_CHOICE_YES;
8155 printf("y\n");
8156 } else if (strcmp(line, "n") == 0) {
8157 *choice = GOT_PATCH_CHOICE_NO;
8158 printf("n\n");
8159 } else if (strcmp(line, "q") == 0 &&
8160 status == GOT_STATUS_MODIFY) {
8161 *choice = GOT_PATCH_CHOICE_QUIT;
8162 printf("q\n");
8163 } else
8164 printf("invalid response '%s'\n", line);
8165 free(line);
8166 return NULL;
8169 while (resp != 'y' && resp != 'n' && resp != 'q') {
8170 err = show_change(status, path, patch_file, n, nchanges,
8171 a->action);
8172 if (err)
8173 return err;
8174 resp = getchar();
8175 if (resp == '\n')
8176 resp = getchar();
8177 if (status == GOT_STATUS_MODIFY) {
8178 if (resp != 'y' && resp != 'n' && resp != 'q') {
8179 printf("invalid response '%c'\n", resp);
8180 resp = ' ';
8182 } else if (resp != 'y' && resp != 'n') {
8183 printf("invalid response '%c'\n", resp);
8184 resp = ' ';
8188 if (resp == 'y')
8189 *choice = GOT_PATCH_CHOICE_YES;
8190 else if (resp == 'n')
8191 *choice = GOT_PATCH_CHOICE_NO;
8192 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8193 *choice = GOT_PATCH_CHOICE_QUIT;
8195 return NULL;
8198 static const struct got_error *
8199 cmd_revert(int argc, char *argv[])
8201 const struct got_error *error = NULL;
8202 struct got_worktree *worktree = NULL;
8203 struct got_repository *repo = NULL;
8204 char *cwd = NULL, *path = NULL;
8205 struct got_pathlist_head paths;
8206 struct got_pathlist_entry *pe;
8207 int ch, can_recurse = 0, pflag = 0;
8208 FILE *patch_script_file = NULL;
8209 const char *patch_script_path = NULL;
8210 struct choose_patch_arg cpa;
8211 int *pack_fds = NULL;
8213 TAILQ_INIT(&paths);
8215 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8216 switch (ch) {
8217 case 'p':
8218 pflag = 1;
8219 break;
8220 case 'F':
8221 patch_script_path = optarg;
8222 break;
8223 case 'R':
8224 can_recurse = 1;
8225 break;
8226 default:
8227 usage_revert();
8228 /* NOTREACHED */
8232 argc -= optind;
8233 argv += optind;
8235 #ifndef PROFILE
8236 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8237 "unveil", NULL) == -1)
8238 err(1, "pledge");
8239 #endif
8240 if (argc < 1)
8241 usage_revert();
8242 if (patch_script_path && !pflag)
8243 errx(1, "-F option can only be used together with -p option");
8245 cwd = getcwd(NULL, 0);
8246 if (cwd == NULL) {
8247 error = got_error_from_errno("getcwd");
8248 goto done;
8251 error = got_repo_pack_fds_open(&pack_fds);
8252 if (error != NULL)
8253 goto done;
8255 error = got_worktree_open(&worktree, cwd);
8256 if (error) {
8257 if (error->code == GOT_ERR_NOT_WORKTREE)
8258 error = wrap_not_worktree_error(error, "revert", cwd);
8259 goto done;
8262 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8263 NULL, pack_fds);
8264 if (error != NULL)
8265 goto done;
8267 if (patch_script_path) {
8268 patch_script_file = fopen(patch_script_path, "re");
8269 if (patch_script_file == NULL) {
8270 error = got_error_from_errno2("fopen",
8271 patch_script_path);
8272 goto done;
8275 error = apply_unveil(got_repo_get_path(repo), 1,
8276 got_worktree_get_root_path(worktree));
8277 if (error)
8278 goto done;
8280 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8281 if (error)
8282 goto done;
8284 if (!can_recurse) {
8285 char *ondisk_path;
8286 struct stat sb;
8287 TAILQ_FOREACH(pe, &paths, entry) {
8288 if (asprintf(&ondisk_path, "%s/%s",
8289 got_worktree_get_root_path(worktree),
8290 pe->path) == -1) {
8291 error = got_error_from_errno("asprintf");
8292 goto done;
8294 if (lstat(ondisk_path, &sb) == -1) {
8295 if (errno == ENOENT) {
8296 free(ondisk_path);
8297 continue;
8299 error = got_error_from_errno2("lstat",
8300 ondisk_path);
8301 free(ondisk_path);
8302 goto done;
8304 free(ondisk_path);
8305 if (S_ISDIR(sb.st_mode)) {
8306 error = got_error_msg(GOT_ERR_BAD_PATH,
8307 "reverting directories requires -R option");
8308 goto done;
8313 cpa.patch_script_file = patch_script_file;
8314 cpa.action = "revert";
8315 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8316 pflag ? choose_patch : NULL, &cpa, repo);
8317 done:
8318 if (patch_script_file && fclose(patch_script_file) == EOF &&
8319 error == NULL)
8320 error = got_error_from_errno2("fclose", patch_script_path);
8321 if (repo) {
8322 const struct got_error *close_err = got_repo_close(repo);
8323 if (error == NULL)
8324 error = close_err;
8326 if (worktree)
8327 got_worktree_close(worktree);
8328 if (pack_fds) {
8329 const struct got_error *pack_err =
8330 got_repo_pack_fds_close(pack_fds);
8331 if (error == NULL)
8332 error = pack_err;
8334 free(path);
8335 free(cwd);
8336 return error;
8339 __dead static void
8340 usage_commit(void)
8342 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8343 "[-m message] [path ...]\n", getprogname());
8344 exit(1);
8347 struct collect_commit_logmsg_arg {
8348 const char *cmdline_log;
8349 const char *prepared_log;
8350 int non_interactive;
8351 const char *editor;
8352 const char *worktree_path;
8353 const char *branch_name;
8354 const char *repo_path;
8355 char *logmsg_path;
8359 static const struct got_error *
8360 read_prepared_logmsg(char **logmsg, const char *path)
8362 const struct got_error *err = NULL;
8363 FILE *f = NULL;
8364 struct stat sb;
8365 size_t r;
8367 *logmsg = NULL;
8368 memset(&sb, 0, sizeof(sb));
8370 f = fopen(path, "re");
8371 if (f == NULL)
8372 return got_error_from_errno2("fopen", path);
8374 if (fstat(fileno(f), &sb) == -1) {
8375 err = got_error_from_errno2("fstat", path);
8376 goto done;
8378 if (sb.st_size == 0) {
8379 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8380 goto done;
8383 *logmsg = malloc(sb.st_size + 1);
8384 if (*logmsg == NULL) {
8385 err = got_error_from_errno("malloc");
8386 goto done;
8389 r = fread(*logmsg, 1, sb.st_size, f);
8390 if (r != sb.st_size) {
8391 if (ferror(f))
8392 err = got_error_from_errno2("fread", path);
8393 else
8394 err = got_error(GOT_ERR_IO);
8395 goto done;
8397 (*logmsg)[sb.st_size] = '\0';
8398 done:
8399 if (fclose(f) == EOF && err == NULL)
8400 err = got_error_from_errno2("fclose", path);
8401 if (err) {
8402 free(*logmsg);
8403 *logmsg = NULL;
8405 return err;
8409 static const struct got_error *
8410 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8411 void *arg)
8413 char *initial_content = NULL;
8414 struct got_pathlist_entry *pe;
8415 const struct got_error *err = NULL;
8416 char *template = NULL;
8417 struct collect_commit_logmsg_arg *a = arg;
8418 int initial_content_len;
8419 int fd = -1;
8420 size_t len;
8422 /* if a message was specified on the command line, just use it */
8423 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8424 len = strlen(a->cmdline_log) + 1;
8425 *logmsg = malloc(len + 1);
8426 if (*logmsg == NULL)
8427 return got_error_from_errno("malloc");
8428 strlcpy(*logmsg, a->cmdline_log, len);
8429 return NULL;
8430 } else if (a->prepared_log != NULL && a->non_interactive)
8431 return read_prepared_logmsg(logmsg, a->prepared_log);
8433 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8434 return got_error_from_errno("asprintf");
8436 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8437 if (err)
8438 goto done;
8440 if (a->prepared_log) {
8441 char *msg;
8442 err = read_prepared_logmsg(&msg, a->prepared_log);
8443 if (err)
8444 goto done;
8445 if (write(fd, msg, strlen(msg)) == -1) {
8446 err = got_error_from_errno2("write", a->logmsg_path);
8447 free(msg);
8448 goto done;
8450 free(msg);
8453 initial_content_len = asprintf(&initial_content,
8454 "\n# changes to be committed on branch %s:\n",
8455 a->branch_name);
8456 if (initial_content_len == -1) {
8457 err = got_error_from_errno("asprintf");
8458 goto done;
8461 if (write(fd, initial_content, initial_content_len) == -1) {
8462 err = got_error_from_errno2("write", a->logmsg_path);
8463 goto done;
8466 TAILQ_FOREACH(pe, commitable_paths, entry) {
8467 struct got_commitable *ct = pe->data;
8468 dprintf(fd, "# %c %s\n",
8469 got_commitable_get_status(ct),
8470 got_commitable_get_path(ct));
8473 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8474 initial_content_len, a->prepared_log ? 0 : 1);
8475 done:
8476 free(initial_content);
8477 free(template);
8479 if (fd != -1 && close(fd) == -1 && err == NULL)
8480 err = got_error_from_errno2("close", a->logmsg_path);
8482 /* Editor is done; we can now apply unveil(2) */
8483 if (err == NULL)
8484 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8485 if (err) {
8486 free(*logmsg);
8487 *logmsg = NULL;
8489 return err;
8492 static const struct got_error *
8493 cmd_commit(int argc, char *argv[])
8495 const struct got_error *error = NULL;
8496 struct got_worktree *worktree = NULL;
8497 struct got_repository *repo = NULL;
8498 char *cwd = NULL, *id_str = NULL;
8499 struct got_object_id *id = NULL;
8500 const char *logmsg = NULL;
8501 char *prepared_logmsg = NULL;
8502 struct collect_commit_logmsg_arg cl_arg;
8503 const char *author = NULL;
8504 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8505 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8506 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8507 struct got_pathlist_head paths;
8508 int *pack_fds = NULL;
8510 TAILQ_INIT(&paths);
8511 cl_arg.logmsg_path = NULL;
8513 while ((ch = getopt(argc, argv, "A:F:m:NS")) != -1) {
8514 switch (ch) {
8515 case 'A':
8516 author = optarg;
8517 error = valid_author(author);
8518 if (error)
8519 return error;
8520 break;
8521 case 'F':
8522 if (logmsg != NULL)
8523 option_conflict('F', 'm');
8524 prepared_logmsg = realpath(optarg, NULL);
8525 if (prepared_logmsg == NULL)
8526 return got_error_from_errno2("realpath",
8527 optarg);
8528 break;
8529 case 'm':
8530 if (prepared_logmsg)
8531 option_conflict('m', 'F');
8532 logmsg = optarg;
8533 break;
8534 case 'N':
8535 non_interactive = 1;
8536 break;
8537 case 'S':
8538 allow_bad_symlinks = 1;
8539 break;
8540 default:
8541 usage_commit();
8542 /* NOTREACHED */
8546 argc -= optind;
8547 argv += optind;
8549 #ifndef PROFILE
8550 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8551 "unveil", NULL) == -1)
8552 err(1, "pledge");
8553 #endif
8554 cwd = getcwd(NULL, 0);
8555 if (cwd == NULL) {
8556 error = got_error_from_errno("getcwd");
8557 goto done;
8560 error = got_repo_pack_fds_open(&pack_fds);
8561 if (error != NULL)
8562 goto done;
8564 error = got_worktree_open(&worktree, cwd);
8565 if (error) {
8566 if (error->code == GOT_ERR_NOT_WORKTREE)
8567 error = wrap_not_worktree_error(error, "commit", cwd);
8568 goto done;
8571 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8572 if (error)
8573 goto done;
8574 if (rebase_in_progress) {
8575 error = got_error(GOT_ERR_REBASING);
8576 goto done;
8579 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8580 worktree);
8581 if (error)
8582 goto done;
8584 error = get_gitconfig_path(&gitconfig_path);
8585 if (error)
8586 goto done;
8587 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8588 gitconfig_path, pack_fds);
8589 if (error != NULL)
8590 goto done;
8592 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8593 if (error)
8594 goto done;
8595 if (merge_in_progress) {
8596 error = got_error(GOT_ERR_MERGE_BUSY);
8597 goto done;
8600 error = get_author(&committer, repo, worktree);
8601 if (error)
8602 goto done;
8604 if (author != NULL && !strcmp(committer, author)) {
8605 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8606 goto done;
8609 if (author == NULL)
8610 author = committer;
8613 * unveil(2) traverses exec(2); if an editor is used we have
8614 * to apply unveil after the log message has been written.
8616 if (logmsg == NULL || strlen(logmsg) == 0)
8617 error = get_editor(&editor);
8618 else
8619 error = apply_unveil(got_repo_get_path(repo), 0,
8620 got_worktree_get_root_path(worktree));
8621 if (error)
8622 goto done;
8624 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8625 if (error)
8626 goto done;
8628 cl_arg.editor = editor;
8629 cl_arg.cmdline_log = logmsg;
8630 cl_arg.prepared_log = prepared_logmsg;
8631 cl_arg.non_interactive = non_interactive;
8632 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8633 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8634 if (!histedit_in_progress) {
8635 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8636 error = got_error(GOT_ERR_COMMIT_BRANCH);
8637 goto done;
8639 cl_arg.branch_name += 11;
8641 cl_arg.repo_path = got_repo_get_path(repo);
8642 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8643 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8644 print_status, NULL, repo);
8645 if (error) {
8646 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8647 cl_arg.logmsg_path != NULL)
8648 preserve_logmsg = 1;
8649 goto done;
8652 error = got_object_id_str(&id_str, id);
8653 if (error)
8654 goto done;
8655 printf("Created commit %s\n", id_str);
8656 done:
8657 if (preserve_logmsg) {
8658 fprintf(stderr, "%s: log message preserved in %s\n",
8659 getprogname(), cl_arg.logmsg_path);
8660 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8661 error == NULL)
8662 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8663 free(cl_arg.logmsg_path);
8664 if (repo) {
8665 const struct got_error *close_err = got_repo_close(repo);
8666 if (error == NULL)
8667 error = close_err;
8669 if (worktree)
8670 got_worktree_close(worktree);
8671 if (pack_fds) {
8672 const struct got_error *pack_err =
8673 got_repo_pack_fds_close(pack_fds);
8674 if (error == NULL)
8675 error = pack_err;
8677 free(cwd);
8678 free(id_str);
8679 free(gitconfig_path);
8680 free(editor);
8681 free(committer);
8682 free(prepared_logmsg);
8683 return error;
8686 __dead static void
8687 usage_send(void)
8689 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8690 "[-r repository-path] [-t tag] [remote-repository]\n",
8691 getprogname());
8692 exit(1);
8695 static void
8696 print_load_info(int print_colored, int print_found, int print_trees,
8697 int ncolored, int nfound, int ntrees)
8699 if (print_colored) {
8700 printf("%d commit%s colored", ncolored,
8701 ncolored == 1 ? "" : "s");
8703 if (print_found) {
8704 printf("%s%d object%s found",
8705 ncolored > 0 ? "; " : "",
8706 nfound, nfound == 1 ? "" : "s");
8708 if (print_trees) {
8709 printf("; %d tree%s scanned", ntrees,
8710 ntrees == 1 ? "" : "s");
8714 struct got_send_progress_arg {
8715 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8716 int verbosity;
8717 int last_ncolored;
8718 int last_nfound;
8719 int last_ntrees;
8720 int loading_done;
8721 int last_ncommits;
8722 int last_nobj_total;
8723 int last_p_deltify;
8724 int last_p_written;
8725 int last_p_sent;
8726 int printed_something;
8727 int sent_something;
8728 struct got_pathlist_head *delete_branches;
8731 static const struct got_error *
8732 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8733 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8734 int nobj_written, off_t bytes_sent, const char *refname, int success)
8736 struct got_send_progress_arg *a = arg;
8737 char scaled_packsize[FMT_SCALED_STRSIZE];
8738 char scaled_sent[FMT_SCALED_STRSIZE];
8739 int p_deltify = 0, p_written = 0, p_sent = 0;
8740 int print_colored = 0, print_found = 0, print_trees = 0;
8741 int print_searching = 0, print_total = 0;
8742 int print_deltify = 0, print_written = 0, print_sent = 0;
8744 if (a->verbosity < 0)
8745 return NULL;
8747 if (refname) {
8748 const char *status = success ? "accepted" : "rejected";
8750 if (success) {
8751 struct got_pathlist_entry *pe;
8752 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8753 const char *branchname = pe->path;
8754 if (got_path_cmp(branchname, refname,
8755 strlen(branchname), strlen(refname)) == 0) {
8756 status = "deleted";
8757 a->sent_something = 1;
8758 break;
8763 if (a->printed_something)
8764 putchar('\n');
8765 printf("Server has %s %s", status, refname);
8766 a->printed_something = 1;
8767 return NULL;
8770 if (a->last_ncolored != ncolored) {
8771 print_colored = 1;
8772 a->last_ncolored = ncolored;
8775 if (a->last_nfound != nfound) {
8776 print_colored = 1;
8777 print_found = 1;
8778 a->last_nfound = nfound;
8781 if (a->last_ntrees != ntrees) {
8782 print_colored = 1;
8783 print_found = 1;
8784 print_trees = 1;
8785 a->last_ntrees = ntrees;
8788 if ((print_colored || print_found || print_trees) &&
8789 !a->loading_done) {
8790 printf("\r");
8791 print_load_info(print_colored, print_found, print_trees,
8792 ncolored, nfound, ntrees);
8793 a->printed_something = 1;
8794 fflush(stdout);
8795 return NULL;
8796 } else if (!a->loading_done) {
8797 printf("\r");
8798 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8799 printf("\n");
8800 a->loading_done = 1;
8803 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8804 return got_error_from_errno("fmt_scaled");
8805 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8806 return got_error_from_errno("fmt_scaled");
8808 if (a->last_ncommits != ncommits) {
8809 print_searching = 1;
8810 a->last_ncommits = ncommits;
8813 if (a->last_nobj_total != nobj_total) {
8814 print_searching = 1;
8815 print_total = 1;
8816 a->last_nobj_total = nobj_total;
8819 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8820 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8821 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8822 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8823 return got_error(GOT_ERR_NO_SPACE);
8826 if (nobj_deltify > 0 || nobj_written > 0) {
8827 if (nobj_deltify > 0) {
8828 p_deltify = (nobj_deltify * 100) / nobj_total;
8829 if (p_deltify != a->last_p_deltify) {
8830 a->last_p_deltify = p_deltify;
8831 print_searching = 1;
8832 print_total = 1;
8833 print_deltify = 1;
8836 if (nobj_written > 0) {
8837 p_written = (nobj_written * 100) / nobj_total;
8838 if (p_written != a->last_p_written) {
8839 a->last_p_written = p_written;
8840 print_searching = 1;
8841 print_total = 1;
8842 print_deltify = 1;
8843 print_written = 1;
8848 if (bytes_sent > 0) {
8849 p_sent = (bytes_sent * 100) / packfile_size;
8850 if (p_sent != a->last_p_sent) {
8851 a->last_p_sent = p_sent;
8852 print_searching = 1;
8853 print_total = 1;
8854 print_deltify = 1;
8855 print_written = 1;
8856 print_sent = 1;
8858 a->sent_something = 1;
8861 if (print_searching || print_total || print_deltify || print_written ||
8862 print_sent)
8863 printf("\r");
8864 if (print_searching)
8865 printf("packing %d reference%s", ncommits,
8866 ncommits == 1 ? "" : "s");
8867 if (print_total)
8868 printf("; %d object%s", nobj_total,
8869 nobj_total == 1 ? "" : "s");
8870 if (print_deltify)
8871 printf("; deltify: %d%%", p_deltify);
8872 if (print_sent)
8873 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8874 scaled_packsize, p_sent);
8875 else if (print_written)
8876 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8877 scaled_packsize, p_written);
8878 if (print_searching || print_total || print_deltify ||
8879 print_written || print_sent) {
8880 a->printed_something = 1;
8881 fflush(stdout);
8883 return NULL;
8886 static const struct got_error *
8887 cmd_send(int argc, char *argv[])
8889 const struct got_error *error = NULL;
8890 char *cwd = NULL, *repo_path = NULL;
8891 const char *remote_name;
8892 char *proto = NULL, *host = NULL, *port = NULL;
8893 char *repo_name = NULL, *server_path = NULL;
8894 const struct got_remote_repo *remotes, *remote = NULL;
8895 int nremotes, nbranches = 0, ndelete_branches = 0;
8896 struct got_repository *repo = NULL;
8897 struct got_worktree *worktree = NULL;
8898 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8899 struct got_pathlist_head branches;
8900 struct got_pathlist_head tags;
8901 struct got_reflist_head all_branches;
8902 struct got_reflist_head all_tags;
8903 struct got_pathlist_head delete_args;
8904 struct got_pathlist_head delete_branches;
8905 struct got_reflist_entry *re;
8906 struct got_pathlist_entry *pe;
8907 int i, ch, sendfd = -1, sendstatus;
8908 pid_t sendpid = -1;
8909 struct got_send_progress_arg spa;
8910 int verbosity = 0, overwrite_refs = 0;
8911 int send_all_branches = 0, send_all_tags = 0;
8912 struct got_reference *ref = NULL;
8913 int *pack_fds = NULL;
8915 TAILQ_INIT(&branches);
8916 TAILQ_INIT(&tags);
8917 TAILQ_INIT(&all_branches);
8918 TAILQ_INIT(&all_tags);
8919 TAILQ_INIT(&delete_args);
8920 TAILQ_INIT(&delete_branches);
8922 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8923 switch (ch) {
8924 case 'a':
8925 send_all_branches = 1;
8926 break;
8927 case 'b':
8928 error = got_pathlist_append(&branches, optarg, NULL);
8929 if (error)
8930 return error;
8931 nbranches++;
8932 break;
8933 case 'd':
8934 error = got_pathlist_append(&delete_args, optarg, NULL);
8935 if (error)
8936 return error;
8937 break;
8938 case 'f':
8939 overwrite_refs = 1;
8940 break;
8941 case 'r':
8942 repo_path = realpath(optarg, NULL);
8943 if (repo_path == NULL)
8944 return got_error_from_errno2("realpath",
8945 optarg);
8946 got_path_strip_trailing_slashes(repo_path);
8947 break;
8948 case 't':
8949 error = got_pathlist_append(&tags, optarg, NULL);
8950 if (error)
8951 return error;
8952 break;
8953 case 'T':
8954 send_all_tags = 1;
8955 break;
8956 case 'v':
8957 if (verbosity < 0)
8958 verbosity = 0;
8959 else if (verbosity < 3)
8960 verbosity++;
8961 break;
8962 case 'q':
8963 verbosity = -1;
8964 break;
8965 default:
8966 usage_send();
8967 /* NOTREACHED */
8970 argc -= optind;
8971 argv += optind;
8973 if (send_all_branches && !TAILQ_EMPTY(&branches))
8974 option_conflict('a', 'b');
8975 if (send_all_tags && !TAILQ_EMPTY(&tags))
8976 option_conflict('T', 't');
8979 if (argc == 0)
8980 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8981 else if (argc == 1)
8982 remote_name = argv[0];
8983 else
8984 usage_send();
8986 cwd = getcwd(NULL, 0);
8987 if (cwd == NULL) {
8988 error = got_error_from_errno("getcwd");
8989 goto done;
8992 error = got_repo_pack_fds_open(&pack_fds);
8993 if (error != NULL)
8994 goto done;
8996 if (repo_path == NULL) {
8997 error = got_worktree_open(&worktree, cwd);
8998 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8999 goto done;
9000 else
9001 error = NULL;
9002 if (worktree) {
9003 repo_path =
9004 strdup(got_worktree_get_repo_path(worktree));
9005 if (repo_path == NULL)
9006 error = got_error_from_errno("strdup");
9007 if (error)
9008 goto done;
9009 } else {
9010 repo_path = strdup(cwd);
9011 if (repo_path == NULL) {
9012 error = got_error_from_errno("strdup");
9013 goto done;
9018 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9019 if (error)
9020 goto done;
9022 if (worktree) {
9023 worktree_conf = got_worktree_get_gotconfig(worktree);
9024 if (worktree_conf) {
9025 got_gotconfig_get_remotes(&nremotes, &remotes,
9026 worktree_conf);
9027 for (i = 0; i < nremotes; i++) {
9028 if (strcmp(remotes[i].name, remote_name) == 0) {
9029 remote = &remotes[i];
9030 break;
9035 if (remote == NULL) {
9036 repo_conf = got_repo_get_gotconfig(repo);
9037 if (repo_conf) {
9038 got_gotconfig_get_remotes(&nremotes, &remotes,
9039 repo_conf);
9040 for (i = 0; i < nremotes; i++) {
9041 if (strcmp(remotes[i].name, remote_name) == 0) {
9042 remote = &remotes[i];
9043 break;
9048 if (remote == NULL) {
9049 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9050 for (i = 0; i < nremotes; i++) {
9051 if (strcmp(remotes[i].name, remote_name) == 0) {
9052 remote = &remotes[i];
9053 break;
9057 if (remote == NULL) {
9058 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9059 goto done;
9062 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9063 &repo_name, remote->send_url);
9064 if (error)
9065 goto done;
9067 if (strcmp(proto, "git") == 0) {
9068 #ifndef PROFILE
9069 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9070 "sendfd dns inet unveil", NULL) == -1)
9071 err(1, "pledge");
9072 #endif
9073 } else if (strcmp(proto, "git+ssh") == 0 ||
9074 strcmp(proto, "ssh") == 0) {
9075 #ifndef PROFILE
9076 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9077 "sendfd unveil", NULL) == -1)
9078 err(1, "pledge");
9079 #endif
9080 } else if (strcmp(proto, "http") == 0 ||
9081 strcmp(proto, "git+http") == 0) {
9082 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9083 goto done;
9084 } else {
9085 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9086 goto done;
9089 error = got_dial_apply_unveil(proto);
9090 if (error)
9091 goto done;
9093 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9094 if (error)
9095 goto done;
9097 if (send_all_branches) {
9098 error = got_ref_list(&all_branches, repo, "refs/heads",
9099 got_ref_cmp_by_name, NULL);
9100 if (error)
9101 goto done;
9102 TAILQ_FOREACH(re, &all_branches, entry) {
9103 const char *branchname = got_ref_get_name(re->ref);
9104 error = got_pathlist_append(&branches,
9105 branchname, NULL);
9106 if (error)
9107 goto done;
9108 nbranches++;
9110 } else if (nbranches == 0) {
9111 for (i = 0; i < remote->nsend_branches; i++) {
9112 got_pathlist_append(&branches,
9113 remote->send_branches[i], NULL);
9117 if (send_all_tags) {
9118 error = got_ref_list(&all_tags, repo, "refs/tags",
9119 got_ref_cmp_by_name, NULL);
9120 if (error)
9121 goto done;
9122 TAILQ_FOREACH(re, &all_tags, entry) {
9123 const char *tagname = got_ref_get_name(re->ref);
9124 error = got_pathlist_append(&tags,
9125 tagname, NULL);
9126 if (error)
9127 goto done;
9132 * To prevent accidents only branches in refs/heads/ can be deleted
9133 * with 'got send -d'.
9134 * Deleting anything else requires local repository access or Git.
9136 TAILQ_FOREACH(pe, &delete_args, entry) {
9137 const char *branchname = pe->path;
9138 char *s;
9139 struct got_pathlist_entry *new;
9140 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9141 s = strdup(branchname);
9142 if (s == NULL) {
9143 error = got_error_from_errno("strdup");
9144 goto done;
9146 } else {
9147 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9148 error = got_error_from_errno("asprintf");
9149 goto done;
9152 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9153 if (error || new == NULL /* duplicate */)
9154 free(s);
9155 if (error)
9156 goto done;
9157 ndelete_branches++;
9160 if (nbranches == 0 && ndelete_branches == 0) {
9161 struct got_reference *head_ref;
9162 if (worktree)
9163 error = got_ref_open(&head_ref, repo,
9164 got_worktree_get_head_ref_name(worktree), 0);
9165 else
9166 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9167 if (error)
9168 goto done;
9169 if (got_ref_is_symbolic(head_ref)) {
9170 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9171 got_ref_close(head_ref);
9172 if (error)
9173 goto done;
9174 } else
9175 ref = head_ref;
9176 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9177 NULL);
9178 if (error)
9179 goto done;
9180 nbranches++;
9183 if (verbosity >= 0)
9184 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9185 port ? ":" : "", port ? port : "");
9187 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9188 server_path, verbosity);
9189 if (error)
9190 goto done;
9192 memset(&spa, 0, sizeof(spa));
9193 spa.last_scaled_packsize[0] = '\0';
9194 spa.last_p_deltify = -1;
9195 spa.last_p_written = -1;
9196 spa.verbosity = verbosity;
9197 spa.delete_branches = &delete_branches;
9198 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9199 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9200 check_cancelled, NULL);
9201 if (spa.printed_something)
9202 putchar('\n');
9203 if (error)
9204 goto done;
9205 if (!spa.sent_something && verbosity >= 0)
9206 printf("Already up-to-date\n");
9207 done:
9208 if (sendpid > 0) {
9209 if (kill(sendpid, SIGTERM) == -1)
9210 error = got_error_from_errno("kill");
9211 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9212 error = got_error_from_errno("waitpid");
9214 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9215 error = got_error_from_errno("close");
9216 if (repo) {
9217 const struct got_error *close_err = got_repo_close(repo);
9218 if (error == NULL)
9219 error = close_err;
9221 if (worktree)
9222 got_worktree_close(worktree);
9223 if (pack_fds) {
9224 const struct got_error *pack_err =
9225 got_repo_pack_fds_close(pack_fds);
9226 if (error == NULL)
9227 error = pack_err;
9229 if (ref)
9230 got_ref_close(ref);
9231 got_pathlist_free(&branches);
9232 got_pathlist_free(&tags);
9233 got_ref_list_free(&all_branches);
9234 got_ref_list_free(&all_tags);
9235 got_pathlist_free(&delete_args);
9236 TAILQ_FOREACH(pe, &delete_branches, entry)
9237 free((char *)pe->path);
9238 got_pathlist_free(&delete_branches);
9239 free(cwd);
9240 free(repo_path);
9241 free(proto);
9242 free(host);
9243 free(port);
9244 free(server_path);
9245 free(repo_name);
9246 return error;
9249 __dead static void
9250 usage_cherrypick(void)
9252 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9253 exit(1);
9256 static const struct got_error *
9257 cmd_cherrypick(int argc, char *argv[])
9259 const struct got_error *error = NULL;
9260 struct got_worktree *worktree = NULL;
9261 struct got_repository *repo = NULL;
9262 char *cwd = NULL, *commit_id_str = NULL;
9263 struct got_object_id *commit_id = NULL;
9264 struct got_commit_object *commit = NULL;
9265 struct got_object_qid *pid;
9266 int ch;
9267 struct got_update_progress_arg upa;
9268 int *pack_fds = NULL;
9270 while ((ch = getopt(argc, argv, "")) != -1) {
9271 switch (ch) {
9272 default:
9273 usage_cherrypick();
9274 /* NOTREACHED */
9278 argc -= optind;
9279 argv += optind;
9281 #ifndef PROFILE
9282 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9283 "unveil", NULL) == -1)
9284 err(1, "pledge");
9285 #endif
9286 if (argc != 1)
9287 usage_cherrypick();
9289 cwd = getcwd(NULL, 0);
9290 if (cwd == NULL) {
9291 error = got_error_from_errno("getcwd");
9292 goto done;
9295 error = got_repo_pack_fds_open(&pack_fds);
9296 if (error != NULL)
9297 goto done;
9299 error = got_worktree_open(&worktree, cwd);
9300 if (error) {
9301 if (error->code == GOT_ERR_NOT_WORKTREE)
9302 error = wrap_not_worktree_error(error, "cherrypick",
9303 cwd);
9304 goto done;
9307 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9308 NULL, pack_fds);
9309 if (error != NULL)
9310 goto done;
9312 error = apply_unveil(got_repo_get_path(repo), 0,
9313 got_worktree_get_root_path(worktree));
9314 if (error)
9315 goto done;
9317 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9318 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9319 if (error)
9320 goto done;
9321 error = got_object_id_str(&commit_id_str, commit_id);
9322 if (error)
9323 goto done;
9325 error = got_object_open_as_commit(&commit, repo, commit_id);
9326 if (error)
9327 goto done;
9328 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9329 memset(&upa, 0, sizeof(upa));
9330 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9331 commit_id, repo, update_progress, &upa, check_cancelled,
9332 NULL);
9333 if (error != NULL)
9334 goto done;
9336 if (upa.did_something)
9337 printf("Merged commit %s\n", commit_id_str);
9338 print_merge_progress_stats(&upa);
9339 done:
9340 if (commit)
9341 got_object_commit_close(commit);
9342 free(commit_id_str);
9343 if (worktree)
9344 got_worktree_close(worktree);
9345 if (repo) {
9346 const struct got_error *close_err = got_repo_close(repo);
9347 if (error == NULL)
9348 error = close_err;
9350 if (pack_fds) {
9351 const struct got_error *pack_err =
9352 got_repo_pack_fds_close(pack_fds);
9353 if (error == NULL)
9354 error = pack_err;
9357 return error;
9360 __dead static void
9361 usage_backout(void)
9363 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9364 exit(1);
9367 static const struct got_error *
9368 cmd_backout(int argc, char *argv[])
9370 const struct got_error *error = NULL;
9371 struct got_worktree *worktree = NULL;
9372 struct got_repository *repo = NULL;
9373 char *cwd = NULL, *commit_id_str = NULL;
9374 struct got_object_id *commit_id = NULL;
9375 struct got_commit_object *commit = NULL;
9376 struct got_object_qid *pid;
9377 int ch;
9378 struct got_update_progress_arg upa;
9379 int *pack_fds = NULL;
9381 while ((ch = getopt(argc, argv, "")) != -1) {
9382 switch (ch) {
9383 default:
9384 usage_backout();
9385 /* NOTREACHED */
9389 argc -= optind;
9390 argv += optind;
9392 #ifndef PROFILE
9393 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9394 "unveil", NULL) == -1)
9395 err(1, "pledge");
9396 #endif
9397 if (argc != 1)
9398 usage_backout();
9400 cwd = getcwd(NULL, 0);
9401 if (cwd == NULL) {
9402 error = got_error_from_errno("getcwd");
9403 goto done;
9406 error = got_repo_pack_fds_open(&pack_fds);
9407 if (error != NULL)
9408 goto done;
9410 error = got_worktree_open(&worktree, cwd);
9411 if (error) {
9412 if (error->code == GOT_ERR_NOT_WORKTREE)
9413 error = wrap_not_worktree_error(error, "backout", cwd);
9414 goto done;
9417 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9418 NULL, pack_fds);
9419 if (error != NULL)
9420 goto done;
9422 error = apply_unveil(got_repo_get_path(repo), 0,
9423 got_worktree_get_root_path(worktree));
9424 if (error)
9425 goto done;
9427 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9428 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9429 if (error)
9430 goto done;
9431 error = got_object_id_str(&commit_id_str, commit_id);
9432 if (error)
9433 goto done;
9435 error = got_object_open_as_commit(&commit, repo, commit_id);
9436 if (error)
9437 goto done;
9438 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9439 if (pid == NULL) {
9440 error = got_error(GOT_ERR_ROOT_COMMIT);
9441 goto done;
9444 memset(&upa, 0, sizeof(upa));
9445 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9446 repo, update_progress, &upa, check_cancelled, NULL);
9447 if (error != NULL)
9448 goto done;
9450 if (upa.did_something)
9451 printf("Backed out commit %s\n", commit_id_str);
9452 print_merge_progress_stats(&upa);
9453 done:
9454 if (commit)
9455 got_object_commit_close(commit);
9456 free(commit_id_str);
9457 if (worktree)
9458 got_worktree_close(worktree);
9459 if (repo) {
9460 const struct got_error *close_err = got_repo_close(repo);
9461 if (error == NULL)
9462 error = close_err;
9464 if (pack_fds) {
9465 const struct got_error *pack_err =
9466 got_repo_pack_fds_close(pack_fds);
9467 if (error == NULL)
9468 error = pack_err;
9470 return error;
9473 __dead static void
9474 usage_rebase(void)
9476 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9477 exit(1);
9480 static void
9481 trim_logmsg(char *logmsg, int limit)
9483 char *nl;
9484 size_t len;
9486 len = strlen(logmsg);
9487 if (len > limit)
9488 len = limit;
9489 logmsg[len] = '\0';
9490 nl = strchr(logmsg, '\n');
9491 if (nl)
9492 *nl = '\0';
9495 static const struct got_error *
9496 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9498 const struct got_error *err;
9499 char *logmsg0 = NULL;
9500 const char *s;
9502 err = got_object_commit_get_logmsg(&logmsg0, commit);
9503 if (err)
9504 return err;
9506 s = logmsg0;
9507 while (isspace((unsigned char)s[0]))
9508 s++;
9510 *logmsg = strdup(s);
9511 if (*logmsg == NULL) {
9512 err = got_error_from_errno("strdup");
9513 goto done;
9516 trim_logmsg(*logmsg, limit);
9517 done:
9518 free(logmsg0);
9519 return err;
9522 static const struct got_error *
9523 show_rebase_merge_conflict(struct got_object_id *id,
9524 struct got_repository *repo)
9526 const struct got_error *err;
9527 struct got_commit_object *commit = NULL;
9528 char *id_str = NULL, *logmsg = NULL;
9530 err = got_object_open_as_commit(&commit, repo, id);
9531 if (err)
9532 return err;
9534 err = got_object_id_str(&id_str, id);
9535 if (err)
9536 goto done;
9538 id_str[12] = '\0';
9540 err = get_short_logmsg(&logmsg, 42, commit);
9541 if (err)
9542 goto done;
9544 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9545 done:
9546 free(id_str);
9547 got_object_commit_close(commit);
9548 free(logmsg);
9549 return err;
9552 static const struct got_error *
9553 show_rebase_progress(struct got_commit_object *commit,
9554 struct got_object_id *old_id, struct got_object_id *new_id)
9556 const struct got_error *err;
9557 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9559 err = got_object_id_str(&old_id_str, old_id);
9560 if (err)
9561 goto done;
9563 if (new_id) {
9564 err = got_object_id_str(&new_id_str, new_id);
9565 if (err)
9566 goto done;
9569 old_id_str[12] = '\0';
9570 if (new_id_str)
9571 new_id_str[12] = '\0';
9573 err = get_short_logmsg(&logmsg, 42, commit);
9574 if (err)
9575 goto done;
9577 printf("%s -> %s: %s\n", old_id_str,
9578 new_id_str ? new_id_str : "no-op change", logmsg);
9579 done:
9580 free(old_id_str);
9581 free(new_id_str);
9582 free(logmsg);
9583 return err;
9586 static const struct got_error *
9587 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9588 struct got_reference *branch, struct got_reference *new_base_branch,
9589 struct got_reference *tmp_branch, struct got_repository *repo,
9590 int create_backup)
9592 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9593 return got_worktree_rebase_complete(worktree, fileindex,
9594 new_base_branch, tmp_branch, branch, repo, create_backup);
9597 static const struct got_error *
9598 rebase_commit(struct got_pathlist_head *merged_paths,
9599 struct got_worktree *worktree, struct got_fileindex *fileindex,
9600 struct got_reference *tmp_branch, const char *committer,
9601 struct got_object_id *commit_id, struct got_repository *repo)
9603 const struct got_error *error;
9604 struct got_commit_object *commit;
9605 struct got_object_id *new_commit_id;
9607 error = got_object_open_as_commit(&commit, repo, commit_id);
9608 if (error)
9609 return error;
9611 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9612 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9613 repo);
9614 if (error) {
9615 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9616 goto done;
9617 error = show_rebase_progress(commit, commit_id, NULL);
9618 } else {
9619 error = show_rebase_progress(commit, commit_id, new_commit_id);
9620 free(new_commit_id);
9622 done:
9623 got_object_commit_close(commit);
9624 return error;
9627 struct check_path_prefix_arg {
9628 const char *path_prefix;
9629 size_t len;
9630 int errcode;
9633 static const struct got_error *
9634 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9635 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9636 struct got_object_id *id1, struct got_object_id *id2,
9637 const char *path1, const char *path2,
9638 mode_t mode1, mode_t mode2, struct got_repository *repo)
9640 struct check_path_prefix_arg *a = arg;
9642 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9643 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9644 return got_error(a->errcode);
9646 return NULL;
9649 static const struct got_error *
9650 check_path_prefix(struct got_object_id *parent_id,
9651 struct got_object_id *commit_id, const char *path_prefix,
9652 int errcode, struct got_repository *repo)
9654 const struct got_error *err;
9655 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9656 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9657 struct check_path_prefix_arg cpp_arg;
9659 if (got_path_is_root_dir(path_prefix))
9660 return NULL;
9662 err = got_object_open_as_commit(&commit, repo, commit_id);
9663 if (err)
9664 goto done;
9666 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9667 if (err)
9668 goto done;
9670 err = got_object_open_as_tree(&tree1, repo,
9671 got_object_commit_get_tree_id(parent_commit));
9672 if (err)
9673 goto done;
9675 err = got_object_open_as_tree(&tree2, repo,
9676 got_object_commit_get_tree_id(commit));
9677 if (err)
9678 goto done;
9680 cpp_arg.path_prefix = path_prefix;
9681 while (cpp_arg.path_prefix[0] == '/')
9682 cpp_arg.path_prefix++;
9683 cpp_arg.len = strlen(cpp_arg.path_prefix);
9684 cpp_arg.errcode = errcode;
9685 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9686 check_path_prefix_in_diff, &cpp_arg, 0);
9687 done:
9688 if (tree1)
9689 got_object_tree_close(tree1);
9690 if (tree2)
9691 got_object_tree_close(tree2);
9692 if (commit)
9693 got_object_commit_close(commit);
9694 if (parent_commit)
9695 got_object_commit_close(parent_commit);
9696 return err;
9699 static const struct got_error *
9700 collect_commits(struct got_object_id_queue *commits,
9701 struct got_object_id *initial_commit_id,
9702 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9703 const char *path_prefix, int path_prefix_errcode,
9704 struct got_repository *repo)
9706 const struct got_error *err = NULL;
9707 struct got_commit_graph *graph = NULL;
9708 struct got_object_id *parent_id = NULL;
9709 struct got_object_qid *qid;
9710 struct got_object_id *commit_id = initial_commit_id;
9712 err = got_commit_graph_open(&graph, "/", 1);
9713 if (err)
9714 return err;
9716 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9717 check_cancelled, NULL);
9718 if (err)
9719 goto done;
9720 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9721 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9722 check_cancelled, NULL);
9723 if (err) {
9724 if (err->code == GOT_ERR_ITER_COMPLETED) {
9725 err = got_error_msg(GOT_ERR_ANCESTRY,
9726 "ran out of commits to rebase before "
9727 "youngest common ancestor commit has "
9728 "been reached?!?");
9730 goto done;
9731 } else {
9732 err = check_path_prefix(parent_id, commit_id,
9733 path_prefix, path_prefix_errcode, repo);
9734 if (err)
9735 goto done;
9737 err = got_object_qid_alloc(&qid, commit_id);
9738 if (err)
9739 goto done;
9740 STAILQ_INSERT_HEAD(commits, qid, entry);
9741 commit_id = parent_id;
9744 done:
9745 got_commit_graph_close(graph);
9746 return err;
9749 static const struct got_error *
9750 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9752 const struct got_error *err = NULL;
9753 time_t committer_time;
9754 struct tm tm;
9755 char datebuf[11]; /* YYYY-MM-DD + NUL */
9756 char *author0 = NULL, *author, *smallerthan;
9757 char *logmsg0 = NULL, *logmsg, *newline;
9759 committer_time = got_object_commit_get_committer_time(commit);
9760 if (gmtime_r(&committer_time, &tm) == NULL)
9761 return got_error_from_errno("gmtime_r");
9762 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9763 return got_error(GOT_ERR_NO_SPACE);
9765 author0 = strdup(got_object_commit_get_author(commit));
9766 if (author0 == NULL)
9767 return got_error_from_errno("strdup");
9768 author = author0;
9769 smallerthan = strchr(author, '<');
9770 if (smallerthan && smallerthan[1] != '\0')
9771 author = smallerthan + 1;
9772 author[strcspn(author, "@>")] = '\0';
9774 err = got_object_commit_get_logmsg(&logmsg0, commit);
9775 if (err)
9776 goto done;
9777 logmsg = logmsg0;
9778 while (*logmsg == '\n')
9779 logmsg++;
9780 newline = strchr(logmsg, '\n');
9781 if (newline)
9782 *newline = '\0';
9784 if (asprintf(brief_str, "%s %s %s",
9785 datebuf, author, logmsg) == -1)
9786 err = got_error_from_errno("asprintf");
9787 done:
9788 free(author0);
9789 free(logmsg0);
9790 return err;
9793 static const struct got_error *
9794 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9795 struct got_repository *repo)
9797 const struct got_error *err;
9798 char *id_str;
9800 err = got_object_id_str(&id_str, id);
9801 if (err)
9802 return err;
9804 err = got_ref_delete(ref, repo);
9805 if (err)
9806 goto done;
9808 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9809 done:
9810 free(id_str);
9811 return err;
9814 static const struct got_error *
9815 print_backup_ref(const char *branch_name, const char *new_id_str,
9816 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9817 struct got_reflist_object_id_map *refs_idmap,
9818 struct got_repository *repo)
9820 const struct got_error *err = NULL;
9821 struct got_reflist_head *refs;
9822 char *refs_str = NULL;
9823 struct got_object_id *new_commit_id = NULL;
9824 struct got_commit_object *new_commit = NULL;
9825 char *new_commit_brief_str = NULL;
9826 struct got_object_id *yca_id = NULL;
9827 struct got_commit_object *yca_commit = NULL;
9828 char *yca_id_str = NULL, *yca_brief_str = NULL;
9829 char *custom_refs_str;
9831 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9832 return got_error_from_errno("asprintf");
9834 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9835 0, 0, refs_idmap, custom_refs_str);
9836 if (err)
9837 goto done;
9839 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9840 if (err)
9841 goto done;
9843 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9844 if (refs) {
9845 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9846 if (err)
9847 goto done;
9850 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9851 if (err)
9852 goto done;
9854 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9855 if (err)
9856 goto done;
9858 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9859 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9860 if (err)
9861 goto done;
9863 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9864 refs_str ? " (" : "", refs_str ? refs_str : "",
9865 refs_str ? ")" : "", new_commit_brief_str);
9866 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9867 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9868 free(refs_str);
9869 refs_str = NULL;
9871 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9872 if (err)
9873 goto done;
9875 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9876 if (err)
9877 goto done;
9879 err = got_object_id_str(&yca_id_str, yca_id);
9880 if (err)
9881 goto done;
9883 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9884 if (refs) {
9885 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9886 if (err)
9887 goto done;
9889 printf("history forked at %s%s%s%s\n %s\n",
9890 yca_id_str,
9891 refs_str ? " (" : "", refs_str ? refs_str : "",
9892 refs_str ? ")" : "", yca_brief_str);
9894 done:
9895 free(custom_refs_str);
9896 free(new_commit_id);
9897 free(refs_str);
9898 free(yca_id);
9899 free(yca_id_str);
9900 free(yca_brief_str);
9901 if (new_commit)
9902 got_object_commit_close(new_commit);
9903 if (yca_commit)
9904 got_object_commit_close(yca_commit);
9906 return NULL;
9909 static const struct got_error *
9910 process_backup_refs(const char *backup_ref_prefix,
9911 const char *wanted_branch_name,
9912 int delete, struct got_repository *repo)
9914 const struct got_error *err;
9915 struct got_reflist_head refs, backup_refs;
9916 struct got_reflist_entry *re;
9917 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9918 struct got_object_id *old_commit_id = NULL;
9919 char *branch_name = NULL;
9920 struct got_commit_object *old_commit = NULL;
9921 struct got_reflist_object_id_map *refs_idmap = NULL;
9922 int wanted_branch_found = 0;
9924 TAILQ_INIT(&refs);
9925 TAILQ_INIT(&backup_refs);
9927 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9928 if (err)
9929 return err;
9931 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9932 if (err)
9933 goto done;
9935 if (wanted_branch_name) {
9936 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9937 wanted_branch_name += 11;
9940 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9941 got_ref_cmp_by_commit_timestamp_descending, repo);
9942 if (err)
9943 goto done;
9945 TAILQ_FOREACH(re, &backup_refs, entry) {
9946 const char *refname = got_ref_get_name(re->ref);
9947 char *slash;
9949 err = check_cancelled(NULL);
9950 if (err)
9951 break;
9953 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9954 if (err)
9955 break;
9957 err = got_object_open_as_commit(&old_commit, repo,
9958 old_commit_id);
9959 if (err)
9960 break;
9962 if (strncmp(backup_ref_prefix, refname,
9963 backup_ref_prefix_len) == 0)
9964 refname += backup_ref_prefix_len;
9966 while (refname[0] == '/')
9967 refname++;
9969 branch_name = strdup(refname);
9970 if (branch_name == NULL) {
9971 err = got_error_from_errno("strdup");
9972 break;
9974 slash = strrchr(branch_name, '/');
9975 if (slash) {
9976 *slash = '\0';
9977 refname += strlen(branch_name) + 1;
9980 if (wanted_branch_name == NULL ||
9981 strcmp(wanted_branch_name, branch_name) == 0) {
9982 wanted_branch_found = 1;
9983 if (delete) {
9984 err = delete_backup_ref(re->ref,
9985 old_commit_id, repo);
9986 } else {
9987 err = print_backup_ref(branch_name, refname,
9988 old_commit_id, old_commit, refs_idmap,
9989 repo);
9991 if (err)
9992 break;
9995 free(old_commit_id);
9996 old_commit_id = NULL;
9997 free(branch_name);
9998 branch_name = NULL;
9999 got_object_commit_close(old_commit);
10000 old_commit = NULL;
10003 if (wanted_branch_name && !wanted_branch_found) {
10004 err = got_error_fmt(GOT_ERR_NOT_REF,
10005 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10007 done:
10008 if (refs_idmap)
10009 got_reflist_object_id_map_free(refs_idmap);
10010 got_ref_list_free(&refs);
10011 got_ref_list_free(&backup_refs);
10012 free(old_commit_id);
10013 free(branch_name);
10014 if (old_commit)
10015 got_object_commit_close(old_commit);
10016 return err;
10019 static const struct got_error *
10020 abort_progress(void *arg, unsigned char status, const char *path)
10023 * Unversioned files should not clutter progress output when
10024 * an operation is aborted.
10026 if (status == GOT_STATUS_UNVERSIONED)
10027 return NULL;
10029 return update_progress(arg, status, path);
10032 static const struct got_error *
10033 cmd_rebase(int argc, char *argv[])
10035 const struct got_error *error = NULL;
10036 struct got_worktree *worktree = NULL;
10037 struct got_repository *repo = NULL;
10038 struct got_fileindex *fileindex = NULL;
10039 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10040 struct got_reference *branch = NULL;
10041 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10042 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10043 struct got_object_id *resume_commit_id = NULL;
10044 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10045 struct got_commit_object *commit = NULL;
10046 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10047 int histedit_in_progress = 0, merge_in_progress = 0;
10048 int create_backup = 1, list_backups = 0, delete_backups = 0;
10049 struct got_object_id_queue commits;
10050 struct got_pathlist_head merged_paths;
10051 const struct got_object_id_queue *parent_ids;
10052 struct got_object_qid *qid, *pid;
10053 struct got_update_progress_arg upa;
10054 int *pack_fds = NULL;
10056 STAILQ_INIT(&commits);
10057 TAILQ_INIT(&merged_paths);
10058 memset(&upa, 0, sizeof(upa));
10060 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10061 switch (ch) {
10062 case 'a':
10063 abort_rebase = 1;
10064 break;
10065 case 'c':
10066 continue_rebase = 1;
10067 break;
10068 case 'l':
10069 list_backups = 1;
10070 break;
10071 case 'X':
10072 delete_backups = 1;
10073 break;
10074 default:
10075 usage_rebase();
10076 /* NOTREACHED */
10080 argc -= optind;
10081 argv += optind;
10083 #ifndef PROFILE
10084 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10085 "unveil", NULL) == -1)
10086 err(1, "pledge");
10087 #endif
10088 if (list_backups) {
10089 if (abort_rebase)
10090 option_conflict('l', 'a');
10091 if (continue_rebase)
10092 option_conflict('l', 'c');
10093 if (delete_backups)
10094 option_conflict('l', 'X');
10095 if (argc != 0 && argc != 1)
10096 usage_rebase();
10097 } else if (delete_backups) {
10098 if (abort_rebase)
10099 option_conflict('X', 'a');
10100 if (continue_rebase)
10101 option_conflict('X', 'c');
10102 if (list_backups)
10103 option_conflict('l', 'X');
10104 if (argc != 0 && argc != 1)
10105 usage_rebase();
10106 } else {
10107 if (abort_rebase && continue_rebase)
10108 usage_rebase();
10109 else if (abort_rebase || continue_rebase) {
10110 if (argc != 0)
10111 usage_rebase();
10112 } else if (argc != 1)
10113 usage_rebase();
10116 cwd = getcwd(NULL, 0);
10117 if (cwd == NULL) {
10118 error = got_error_from_errno("getcwd");
10119 goto done;
10122 error = got_repo_pack_fds_open(&pack_fds);
10123 if (error != NULL)
10124 goto done;
10126 error = got_worktree_open(&worktree, cwd);
10127 if (error) {
10128 if (list_backups || delete_backups) {
10129 if (error->code != GOT_ERR_NOT_WORKTREE)
10130 goto done;
10131 } else {
10132 if (error->code == GOT_ERR_NOT_WORKTREE)
10133 error = wrap_not_worktree_error(error,
10134 "rebase", cwd);
10135 goto done;
10139 error = get_gitconfig_path(&gitconfig_path);
10140 if (error)
10141 goto done;
10142 error = got_repo_open(&repo,
10143 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10144 gitconfig_path, pack_fds);
10145 if (error != NULL)
10146 goto done;
10148 error = get_author(&committer, repo, worktree);
10149 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10150 goto done;
10152 error = apply_unveil(got_repo_get_path(repo), 0,
10153 worktree ? got_worktree_get_root_path(worktree) : NULL);
10154 if (error)
10155 goto done;
10157 if (list_backups || delete_backups) {
10158 error = process_backup_refs(
10159 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10160 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10161 goto done; /* nothing else to do */
10164 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10165 worktree);
10166 if (error)
10167 goto done;
10168 if (histedit_in_progress) {
10169 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10170 goto done;
10173 error = got_worktree_merge_in_progress(&merge_in_progress,
10174 worktree, repo);
10175 if (error)
10176 goto done;
10177 if (merge_in_progress) {
10178 error = got_error(GOT_ERR_MERGE_BUSY);
10179 goto done;
10182 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10183 if (error)
10184 goto done;
10186 if (abort_rebase) {
10187 if (!rebase_in_progress) {
10188 error = got_error(GOT_ERR_NOT_REBASING);
10189 goto done;
10191 error = got_worktree_rebase_continue(&resume_commit_id,
10192 &new_base_branch, &tmp_branch, &branch, &fileindex,
10193 worktree, repo);
10194 if (error)
10195 goto done;
10196 printf("Switching work tree to %s\n",
10197 got_ref_get_symref_target(new_base_branch));
10198 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10199 new_base_branch, abort_progress, &upa);
10200 if (error)
10201 goto done;
10202 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10203 print_merge_progress_stats(&upa);
10204 goto done; /* nothing else to do */
10207 if (continue_rebase) {
10208 if (!rebase_in_progress) {
10209 error = got_error(GOT_ERR_NOT_REBASING);
10210 goto done;
10212 error = got_worktree_rebase_continue(&resume_commit_id,
10213 &new_base_branch, &tmp_branch, &branch, &fileindex,
10214 worktree, repo);
10215 if (error)
10216 goto done;
10218 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10219 committer, resume_commit_id, repo);
10220 if (error)
10221 goto done;
10223 yca_id = got_object_id_dup(resume_commit_id);
10224 if (yca_id == NULL) {
10225 error = got_error_from_errno("got_object_id_dup");
10226 goto done;
10228 } else {
10229 error = got_ref_open(&branch, repo, argv[0], 0);
10230 if (error != NULL)
10231 goto done;
10234 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10235 if (error)
10236 goto done;
10238 if (!continue_rebase) {
10239 struct got_object_id *base_commit_id;
10241 base_commit_id = got_worktree_get_base_commit_id(worktree);
10242 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10243 base_commit_id, branch_head_commit_id, 1, repo,
10244 check_cancelled, NULL);
10245 if (error)
10246 goto done;
10247 if (yca_id == NULL) {
10248 error = got_error_msg(GOT_ERR_ANCESTRY,
10249 "specified branch shares no common ancestry "
10250 "with work tree's branch");
10251 goto done;
10254 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10255 if (error) {
10256 if (error->code != GOT_ERR_ANCESTRY)
10257 goto done;
10258 error = NULL;
10259 } else {
10260 struct got_pathlist_head paths;
10261 printf("%s is already based on %s\n",
10262 got_ref_get_name(branch),
10263 got_worktree_get_head_ref_name(worktree));
10264 error = switch_head_ref(branch, branch_head_commit_id,
10265 worktree, repo);
10266 if (error)
10267 goto done;
10268 error = got_worktree_set_base_commit_id(worktree, repo,
10269 branch_head_commit_id);
10270 if (error)
10271 goto done;
10272 TAILQ_INIT(&paths);
10273 error = got_pathlist_append(&paths, "", NULL);
10274 if (error)
10275 goto done;
10276 error = got_worktree_checkout_files(worktree,
10277 &paths, repo, update_progress, &upa,
10278 check_cancelled, NULL);
10279 got_pathlist_free(&paths);
10280 if (error)
10281 goto done;
10282 if (upa.did_something) {
10283 char *id_str;
10284 error = got_object_id_str(&id_str,
10285 branch_head_commit_id);
10286 if (error)
10287 goto done;
10288 printf("Updated to %s: %s\n",
10289 got_worktree_get_head_ref_name(worktree),
10290 id_str);
10291 free(id_str);
10292 } else
10293 printf("Already up-to-date\n");
10294 print_update_progress_stats(&upa);
10295 goto done;
10299 commit_id = branch_head_commit_id;
10300 error = got_object_open_as_commit(&commit, repo, commit_id);
10301 if (error)
10302 goto done;
10304 parent_ids = got_object_commit_get_parent_ids(commit);
10305 pid = STAILQ_FIRST(parent_ids);
10306 if (pid == NULL) {
10307 error = got_error(GOT_ERR_EMPTY_REBASE);
10308 goto done;
10310 error = collect_commits(&commits, commit_id, &pid->id,
10311 yca_id, got_worktree_get_path_prefix(worktree),
10312 GOT_ERR_REBASE_PATH, repo);
10313 got_object_commit_close(commit);
10314 commit = NULL;
10315 if (error)
10316 goto done;
10318 if (!continue_rebase) {
10319 error = got_worktree_rebase_prepare(&new_base_branch,
10320 &tmp_branch, &fileindex, worktree, branch, repo);
10321 if (error)
10322 goto done;
10325 if (STAILQ_EMPTY(&commits)) {
10326 if (continue_rebase) {
10327 error = rebase_complete(worktree, fileindex,
10328 branch, new_base_branch, tmp_branch, repo,
10329 create_backup);
10330 goto done;
10331 } else {
10332 /* Fast-forward the reference of the branch. */
10333 struct got_object_id *new_head_commit_id;
10334 char *id_str;
10335 error = got_ref_resolve(&new_head_commit_id, repo,
10336 new_base_branch);
10337 if (error)
10338 goto done;
10339 error = got_object_id_str(&id_str, new_head_commit_id);
10340 if (error)
10341 goto done;
10342 printf("Forwarding %s to commit %s\n",
10343 got_ref_get_name(branch), id_str);
10344 free(id_str);
10345 error = got_ref_change_ref(branch,
10346 new_head_commit_id);
10347 if (error)
10348 goto done;
10349 /* No backup needed since objects did not change. */
10350 create_backup = 0;
10354 pid = NULL;
10355 STAILQ_FOREACH(qid, &commits, entry) {
10357 commit_id = &qid->id;
10358 parent_id = pid ? &pid->id : yca_id;
10359 pid = qid;
10361 memset(&upa, 0, sizeof(upa));
10362 error = got_worktree_rebase_merge_files(&merged_paths,
10363 worktree, fileindex, parent_id, commit_id, repo,
10364 update_progress, &upa, check_cancelled, NULL);
10365 if (error)
10366 goto done;
10368 print_merge_progress_stats(&upa);
10369 if (upa.conflicts > 0 || upa.missing > 0 ||
10370 upa.not_deleted > 0 || upa.unversioned > 0) {
10371 if (upa.conflicts > 0) {
10372 error = show_rebase_merge_conflict(&qid->id,
10373 repo);
10374 if (error)
10375 goto done;
10377 got_worktree_rebase_pathlist_free(&merged_paths);
10378 break;
10381 error = rebase_commit(&merged_paths, worktree, fileindex,
10382 tmp_branch, committer, commit_id, repo);
10383 got_worktree_rebase_pathlist_free(&merged_paths);
10384 if (error)
10385 goto done;
10388 if (upa.conflicts > 0 || upa.missing > 0 ||
10389 upa.not_deleted > 0 || upa.unversioned > 0) {
10390 error = got_worktree_rebase_postpone(worktree, fileindex);
10391 if (error)
10392 goto done;
10393 if (upa.conflicts > 0 && upa.missing == 0 &&
10394 upa.not_deleted == 0 && upa.unversioned == 0) {
10395 error = got_error_msg(GOT_ERR_CONFLICTS,
10396 "conflicts must be resolved before rebasing "
10397 "can continue");
10398 } else if (upa.conflicts > 0) {
10399 error = got_error_msg(GOT_ERR_CONFLICTS,
10400 "conflicts must be resolved before rebasing "
10401 "can continue; changes destined for some "
10402 "files were not yet merged and should be "
10403 "merged manually if required before the "
10404 "rebase operation is continued");
10405 } else {
10406 error = got_error_msg(GOT_ERR_CONFLICTS,
10407 "changes destined for some files were not "
10408 "yet merged and should be merged manually "
10409 "if required before the rebase operation "
10410 "is continued");
10412 } else
10413 error = rebase_complete(worktree, fileindex, branch,
10414 new_base_branch, tmp_branch, repo, create_backup);
10415 done:
10416 free(cwd);
10417 free(committer);
10418 free(gitconfig_path);
10419 got_object_id_queue_free(&commits);
10420 free(branch_head_commit_id);
10421 free(resume_commit_id);
10422 free(yca_id);
10423 if (commit)
10424 got_object_commit_close(commit);
10425 if (branch)
10426 got_ref_close(branch);
10427 if (new_base_branch)
10428 got_ref_close(new_base_branch);
10429 if (tmp_branch)
10430 got_ref_close(tmp_branch);
10431 if (worktree)
10432 got_worktree_close(worktree);
10433 if (repo) {
10434 const struct got_error *close_err = got_repo_close(repo);
10435 if (error == NULL)
10436 error = close_err;
10438 if (pack_fds) {
10439 const struct got_error *pack_err =
10440 got_repo_pack_fds_close(pack_fds);
10441 if (error == NULL)
10442 error = pack_err;
10444 return error;
10447 __dead static void
10448 usage_histedit(void)
10450 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10451 "[branch]\n", getprogname());
10452 exit(1);
10455 #define GOT_HISTEDIT_PICK 'p'
10456 #define GOT_HISTEDIT_EDIT 'e'
10457 #define GOT_HISTEDIT_FOLD 'f'
10458 #define GOT_HISTEDIT_DROP 'd'
10459 #define GOT_HISTEDIT_MESG 'm'
10461 static const struct got_histedit_cmd {
10462 unsigned char code;
10463 const char *name;
10464 const char *desc;
10465 } got_histedit_cmds[] = {
10466 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10467 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10468 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10469 "be used" },
10470 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10471 { GOT_HISTEDIT_MESG, "mesg",
10472 "single-line log message for commit above (open editor if empty)" },
10475 struct got_histedit_list_entry {
10476 TAILQ_ENTRY(got_histedit_list_entry) entry;
10477 struct got_object_id *commit_id;
10478 const struct got_histedit_cmd *cmd;
10479 char *logmsg;
10481 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10483 static const struct got_error *
10484 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10485 FILE *f, struct got_repository *repo)
10487 const struct got_error *err = NULL;
10488 char *logmsg = NULL, *id_str = NULL;
10489 struct got_commit_object *commit = NULL;
10490 int n;
10492 err = got_object_open_as_commit(&commit, repo, commit_id);
10493 if (err)
10494 goto done;
10496 err = get_short_logmsg(&logmsg, 34, commit);
10497 if (err)
10498 goto done;
10500 err = got_object_id_str(&id_str, commit_id);
10501 if (err)
10502 goto done;
10504 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10505 if (n < 0)
10506 err = got_ferror(f, GOT_ERR_IO);
10507 done:
10508 if (commit)
10509 got_object_commit_close(commit);
10510 free(id_str);
10511 free(logmsg);
10512 return err;
10515 static const struct got_error *
10516 histedit_write_commit_list(struct got_object_id_queue *commits,
10517 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10518 struct got_repository *repo)
10520 const struct got_error *err = NULL;
10521 struct got_object_qid *qid;
10522 const char *histedit_cmd = NULL;
10524 if (STAILQ_EMPTY(commits))
10525 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10527 STAILQ_FOREACH(qid, commits, entry) {
10528 histedit_cmd = got_histedit_cmds[0].name;
10529 if (edit_only)
10530 histedit_cmd = "edit";
10531 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10532 histedit_cmd = "fold";
10533 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10534 if (err)
10535 break;
10536 if (edit_logmsg_only) {
10537 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10538 if (n < 0) {
10539 err = got_ferror(f, GOT_ERR_IO);
10540 break;
10545 return err;
10548 static const struct got_error *
10549 write_cmd_list(FILE *f, const char *branch_name,
10550 struct got_object_id_queue *commits)
10552 const struct got_error *err = NULL;
10553 size_t i;
10554 int n;
10555 char *id_str;
10556 struct got_object_qid *qid;
10558 qid = STAILQ_FIRST(commits);
10559 err = got_object_id_str(&id_str, &qid->id);
10560 if (err)
10561 return err;
10563 n = fprintf(f,
10564 "# Editing the history of branch '%s' starting at\n"
10565 "# commit %s\n"
10566 "# Commits will be processed in order from top to "
10567 "bottom of this file.\n", branch_name, id_str);
10568 if (n < 0) {
10569 err = got_ferror(f, GOT_ERR_IO);
10570 goto done;
10573 n = fprintf(f, "# Available histedit commands:\n");
10574 if (n < 0) {
10575 err = got_ferror(f, GOT_ERR_IO);
10576 goto done;
10579 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10580 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10581 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10582 cmd->desc);
10583 if (n < 0) {
10584 err = got_ferror(f, GOT_ERR_IO);
10585 break;
10588 done:
10589 free(id_str);
10590 return err;
10593 static const struct got_error *
10594 histedit_syntax_error(int lineno)
10596 static char msg[42];
10597 int ret;
10599 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10600 lineno);
10601 if (ret < 0 || (size_t)ret >= sizeof(msg))
10602 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10604 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10607 static const struct got_error *
10608 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10609 char *logmsg, struct got_repository *repo)
10611 const struct got_error *err;
10612 struct got_commit_object *folded_commit = NULL;
10613 char *id_str, *folded_logmsg = NULL;
10615 err = got_object_id_str(&id_str, hle->commit_id);
10616 if (err)
10617 return err;
10619 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10620 if (err)
10621 goto done;
10623 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10624 if (err)
10625 goto done;
10626 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10627 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10628 folded_logmsg) == -1) {
10629 err = got_error_from_errno("asprintf");
10631 done:
10632 if (folded_commit)
10633 got_object_commit_close(folded_commit);
10634 free(id_str);
10635 free(folded_logmsg);
10636 return err;
10639 static struct got_histedit_list_entry *
10640 get_folded_commits(struct got_histedit_list_entry *hle)
10642 struct got_histedit_list_entry *prev, *folded = NULL;
10644 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10645 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10646 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10647 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10648 folded = prev;
10649 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10652 return folded;
10655 static const struct got_error *
10656 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10657 struct got_repository *repo)
10659 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10660 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10661 const struct got_error *err = NULL;
10662 struct got_commit_object *commit = NULL;
10663 int logmsg_len;
10664 int fd;
10665 struct got_histedit_list_entry *folded = NULL;
10667 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10668 if (err)
10669 return err;
10671 folded = get_folded_commits(hle);
10672 if (folded) {
10673 while (folded != hle) {
10674 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10675 folded = TAILQ_NEXT(folded, entry);
10676 continue;
10678 err = append_folded_commit_msg(&new_msg, folded,
10679 logmsg, repo);
10680 if (err)
10681 goto done;
10682 free(logmsg);
10683 logmsg = new_msg;
10684 folded = TAILQ_NEXT(folded, entry);
10688 err = got_object_id_str(&id_str, hle->commit_id);
10689 if (err)
10690 goto done;
10691 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10692 if (err)
10693 goto done;
10694 logmsg_len = asprintf(&new_msg,
10695 "%s\n# original log message of commit %s: %s",
10696 logmsg ? logmsg : "", id_str, orig_logmsg);
10697 if (logmsg_len == -1) {
10698 err = got_error_from_errno("asprintf");
10699 goto done;
10701 free(logmsg);
10702 logmsg = new_msg;
10704 err = got_object_id_str(&id_str, hle->commit_id);
10705 if (err)
10706 goto done;
10708 err = got_opentemp_named_fd(&logmsg_path, &fd,
10709 GOT_TMPDIR_STR "/got-logmsg");
10710 if (err)
10711 goto done;
10713 write(fd, logmsg, logmsg_len);
10714 close(fd);
10716 err = get_editor(&editor);
10717 if (err)
10718 goto done;
10720 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10721 logmsg_len, 0);
10722 if (err) {
10723 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10724 goto done;
10725 err = NULL;
10726 hle->logmsg = strdup(new_msg);
10727 if (hle->logmsg == NULL)
10728 err = got_error_from_errno("strdup");
10730 done:
10731 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10732 err = got_error_from_errno2("unlink", logmsg_path);
10733 free(logmsg_path);
10734 free(logmsg);
10735 free(orig_logmsg);
10736 free(editor);
10737 if (commit)
10738 got_object_commit_close(commit);
10739 return err;
10742 static const struct got_error *
10743 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10744 FILE *f, struct got_repository *repo)
10746 const struct got_error *err = NULL;
10747 char *line = NULL, *p, *end;
10748 size_t i, size;
10749 ssize_t len;
10750 int lineno = 0, lastcmd = -1;
10751 const struct got_histedit_cmd *cmd;
10752 struct got_object_id *commit_id = NULL;
10753 struct got_histedit_list_entry *hle = NULL;
10755 for (;;) {
10756 len = getline(&line, &size, f);
10757 if (len == -1) {
10758 const struct got_error *getline_err;
10759 if (feof(f))
10760 break;
10761 getline_err = got_error_from_errno("getline");
10762 err = got_ferror(f, getline_err->code);
10763 break;
10765 lineno++;
10766 p = line;
10767 while (isspace((unsigned char)p[0]))
10768 p++;
10769 if (p[0] == '#' || p[0] == '\0') {
10770 free(line);
10771 line = NULL;
10772 continue;
10774 cmd = NULL;
10775 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10776 cmd = &got_histedit_cmds[i];
10777 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10778 isspace((unsigned char)p[strlen(cmd->name)])) {
10779 p += strlen(cmd->name);
10780 break;
10782 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10783 p++;
10784 break;
10787 if (i == nitems(got_histedit_cmds)) {
10788 err = histedit_syntax_error(lineno);
10789 break;
10791 while (isspace((unsigned char)p[0]))
10792 p++;
10793 if (cmd->code == GOT_HISTEDIT_MESG) {
10794 if (lastcmd != GOT_HISTEDIT_PICK &&
10795 lastcmd != GOT_HISTEDIT_EDIT) {
10796 err = got_error(GOT_ERR_HISTEDIT_CMD);
10797 break;
10799 if (p[0] == '\0') {
10800 err = histedit_edit_logmsg(hle, repo);
10801 if (err)
10802 break;
10803 } else {
10804 hle->logmsg = strdup(p);
10805 if (hle->logmsg == NULL) {
10806 err = got_error_from_errno("strdup");
10807 break;
10810 free(line);
10811 line = NULL;
10812 lastcmd = cmd->code;
10813 continue;
10814 } else {
10815 end = p;
10816 while (end[0] && !isspace((unsigned char)end[0]))
10817 end++;
10818 *end = '\0';
10820 err = got_object_resolve_id_str(&commit_id, repo, p);
10821 if (err) {
10822 /* override error code */
10823 err = histedit_syntax_error(lineno);
10824 break;
10827 hle = malloc(sizeof(*hle));
10828 if (hle == NULL) {
10829 err = got_error_from_errno("malloc");
10830 break;
10832 hle->cmd = cmd;
10833 hle->commit_id = commit_id;
10834 hle->logmsg = NULL;
10835 commit_id = NULL;
10836 free(line);
10837 line = NULL;
10838 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10839 lastcmd = cmd->code;
10842 free(line);
10843 free(commit_id);
10844 return err;
10847 static const struct got_error *
10848 histedit_check_script(struct got_histedit_list *histedit_cmds,
10849 struct got_object_id_queue *commits, struct got_repository *repo)
10851 const struct got_error *err = NULL;
10852 struct got_object_qid *qid;
10853 struct got_histedit_list_entry *hle;
10854 static char msg[92];
10855 char *id_str;
10857 if (TAILQ_EMPTY(histedit_cmds))
10858 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10859 "histedit script contains no commands");
10860 if (STAILQ_EMPTY(commits))
10861 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10863 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10864 struct got_histedit_list_entry *hle2;
10865 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10866 if (hle == hle2)
10867 continue;
10868 if (got_object_id_cmp(hle->commit_id,
10869 hle2->commit_id) != 0)
10870 continue;
10871 err = got_object_id_str(&id_str, hle->commit_id);
10872 if (err)
10873 return err;
10874 snprintf(msg, sizeof(msg), "commit %s is listed "
10875 "more than once in histedit script", id_str);
10876 free(id_str);
10877 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10881 STAILQ_FOREACH(qid, commits, entry) {
10882 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10883 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10884 break;
10886 if (hle == NULL) {
10887 err = got_object_id_str(&id_str, &qid->id);
10888 if (err)
10889 return err;
10890 snprintf(msg, sizeof(msg),
10891 "commit %s missing from histedit script", id_str);
10892 free(id_str);
10893 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10897 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10898 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10899 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10900 "last commit in histedit script cannot be folded");
10902 return NULL;
10905 static const struct got_error *
10906 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10907 const char *path, struct got_object_id_queue *commits,
10908 struct got_repository *repo)
10910 const struct got_error *err = NULL;
10911 char *editor;
10912 FILE *f = NULL;
10914 err = get_editor(&editor);
10915 if (err)
10916 return err;
10918 if (spawn_editor(editor, path) == -1) {
10919 err = got_error_from_errno("failed spawning editor");
10920 goto done;
10923 f = fopen(path, "re");
10924 if (f == NULL) {
10925 err = got_error_from_errno("fopen");
10926 goto done;
10928 err = histedit_parse_list(histedit_cmds, f, repo);
10929 if (err)
10930 goto done;
10932 err = histedit_check_script(histedit_cmds, commits, repo);
10933 done:
10934 if (f && fclose(f) == EOF && err == NULL)
10935 err = got_error_from_errno("fclose");
10936 free(editor);
10937 return err;
10940 static const struct got_error *
10941 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10942 struct got_object_id_queue *, const char *, const char *,
10943 struct got_repository *);
10945 static const struct got_error *
10946 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10947 struct got_object_id_queue *commits, const char *branch_name,
10948 int edit_logmsg_only, int fold_only, int edit_only,
10949 struct got_repository *repo)
10951 const struct got_error *err;
10952 FILE *f = NULL;
10953 char *path = NULL;
10955 err = got_opentemp_named(&path, &f, "got-histedit");
10956 if (err)
10957 return err;
10959 err = write_cmd_list(f, branch_name, commits);
10960 if (err)
10961 goto done;
10963 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10964 fold_only, edit_only, repo);
10965 if (err)
10966 goto done;
10968 if (edit_logmsg_only || fold_only || edit_only) {
10969 rewind(f);
10970 err = histedit_parse_list(histedit_cmds, f, repo);
10971 } else {
10972 if (fclose(f) == EOF) {
10973 err = got_error_from_errno("fclose");
10974 goto done;
10976 f = NULL;
10977 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10978 if (err) {
10979 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10980 err->code != GOT_ERR_HISTEDIT_CMD)
10981 goto done;
10982 err = histedit_edit_list_retry(histedit_cmds, err,
10983 commits, path, branch_name, repo);
10986 done:
10987 if (f && fclose(f) == EOF && err == NULL)
10988 err = got_error_from_errno("fclose");
10989 if (path && unlink(path) != 0 && err == NULL)
10990 err = got_error_from_errno2("unlink", path);
10991 free(path);
10992 return err;
10995 static const struct got_error *
10996 histedit_save_list(struct got_histedit_list *histedit_cmds,
10997 struct got_worktree *worktree, struct got_repository *repo)
10999 const struct got_error *err = NULL;
11000 char *path = NULL;
11001 FILE *f = NULL;
11002 struct got_histedit_list_entry *hle;
11003 struct got_commit_object *commit = NULL;
11005 err = got_worktree_get_histedit_script_path(&path, worktree);
11006 if (err)
11007 return err;
11009 f = fopen(path, "we");
11010 if (f == NULL) {
11011 err = got_error_from_errno2("fopen", path);
11012 goto done;
11014 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11015 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11016 repo);
11017 if (err)
11018 break;
11020 if (hle->logmsg) {
11021 int n = fprintf(f, "%c %s\n",
11022 GOT_HISTEDIT_MESG, hle->logmsg);
11023 if (n < 0) {
11024 err = got_ferror(f, GOT_ERR_IO);
11025 break;
11029 done:
11030 if (f && fclose(f) == EOF && err == NULL)
11031 err = got_error_from_errno("fclose");
11032 free(path);
11033 if (commit)
11034 got_object_commit_close(commit);
11035 return err;
11038 static void
11039 histedit_free_list(struct got_histedit_list *histedit_cmds)
11041 struct got_histedit_list_entry *hle;
11043 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11044 TAILQ_REMOVE(histedit_cmds, hle, entry);
11045 free(hle);
11049 static const struct got_error *
11050 histedit_load_list(struct got_histedit_list *histedit_cmds,
11051 const char *path, struct got_repository *repo)
11053 const struct got_error *err = NULL;
11054 FILE *f = NULL;
11056 f = fopen(path, "re");
11057 if (f == NULL) {
11058 err = got_error_from_errno2("fopen", path);
11059 goto done;
11062 err = histedit_parse_list(histedit_cmds, f, repo);
11063 done:
11064 if (f && fclose(f) == EOF && err == NULL)
11065 err = got_error_from_errno("fclose");
11066 return err;
11069 static const struct got_error *
11070 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11071 const struct got_error *edit_err, struct got_object_id_queue *commits,
11072 const char *path, const char *branch_name, struct got_repository *repo)
11074 const struct got_error *err = NULL, *prev_err = edit_err;
11075 int resp = ' ';
11077 while (resp != 'c' && resp != 'r' && resp != 'a') {
11078 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11079 "or (a)bort: ", getprogname(), prev_err->msg);
11080 resp = getchar();
11081 if (resp == '\n')
11082 resp = getchar();
11083 if (resp == 'c') {
11084 histedit_free_list(histedit_cmds);
11085 err = histedit_run_editor(histedit_cmds, path, commits,
11086 repo);
11087 if (err) {
11088 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11089 err->code != GOT_ERR_HISTEDIT_CMD)
11090 break;
11091 prev_err = err;
11092 resp = ' ';
11093 continue;
11095 break;
11096 } else if (resp == 'r') {
11097 histedit_free_list(histedit_cmds);
11098 err = histedit_edit_script(histedit_cmds,
11099 commits, branch_name, 0, 0, 0, repo);
11100 if (err) {
11101 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11102 err->code != GOT_ERR_HISTEDIT_CMD)
11103 break;
11104 prev_err = err;
11105 resp = ' ';
11106 continue;
11108 break;
11109 } else if (resp == 'a') {
11110 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11111 break;
11112 } else
11113 printf("invalid response '%c'\n", resp);
11116 return err;
11119 static const struct got_error *
11120 histedit_complete(struct got_worktree *worktree,
11121 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11122 struct got_reference *branch, struct got_repository *repo)
11124 printf("Switching work tree to %s\n",
11125 got_ref_get_symref_target(branch));
11126 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11127 branch, repo);
11130 static const struct got_error *
11131 show_histedit_progress(struct got_commit_object *commit,
11132 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11134 const struct got_error *err;
11135 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11137 err = got_object_id_str(&old_id_str, hle->commit_id);
11138 if (err)
11139 goto done;
11141 if (new_id) {
11142 err = got_object_id_str(&new_id_str, new_id);
11143 if (err)
11144 goto done;
11147 old_id_str[12] = '\0';
11148 if (new_id_str)
11149 new_id_str[12] = '\0';
11151 if (hle->logmsg) {
11152 logmsg = strdup(hle->logmsg);
11153 if (logmsg == NULL) {
11154 err = got_error_from_errno("strdup");
11155 goto done;
11157 trim_logmsg(logmsg, 42);
11158 } else {
11159 err = get_short_logmsg(&logmsg, 42, commit);
11160 if (err)
11161 goto done;
11164 switch (hle->cmd->code) {
11165 case GOT_HISTEDIT_PICK:
11166 case GOT_HISTEDIT_EDIT:
11167 printf("%s -> %s: %s\n", old_id_str,
11168 new_id_str ? new_id_str : "no-op change", logmsg);
11169 break;
11170 case GOT_HISTEDIT_DROP:
11171 case GOT_HISTEDIT_FOLD:
11172 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11173 logmsg);
11174 break;
11175 default:
11176 break;
11178 done:
11179 free(old_id_str);
11180 free(new_id_str);
11181 return err;
11184 static const struct got_error *
11185 histedit_commit(struct got_pathlist_head *merged_paths,
11186 struct got_worktree *worktree, struct got_fileindex *fileindex,
11187 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11188 const char *committer, struct got_repository *repo)
11190 const struct got_error *err;
11191 struct got_commit_object *commit;
11192 struct got_object_id *new_commit_id;
11194 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11195 && hle->logmsg == NULL) {
11196 err = histedit_edit_logmsg(hle, repo);
11197 if (err)
11198 return err;
11201 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11202 if (err)
11203 return err;
11205 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11206 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11207 hle->logmsg, repo);
11208 if (err) {
11209 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11210 goto done;
11211 err = show_histedit_progress(commit, hle, NULL);
11212 } else {
11213 err = show_histedit_progress(commit, hle, new_commit_id);
11214 free(new_commit_id);
11216 done:
11217 got_object_commit_close(commit);
11218 return err;
11221 static const struct got_error *
11222 histedit_skip_commit(struct got_histedit_list_entry *hle,
11223 struct got_worktree *worktree, struct got_repository *repo)
11225 const struct got_error *error;
11226 struct got_commit_object *commit;
11228 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11229 repo);
11230 if (error)
11231 return error;
11233 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11234 if (error)
11235 return error;
11237 error = show_histedit_progress(commit, hle, NULL);
11238 got_object_commit_close(commit);
11239 return error;
11242 static const struct got_error *
11243 check_local_changes(void *arg, unsigned char status,
11244 unsigned char staged_status, const char *path,
11245 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11246 struct got_object_id *commit_id, int dirfd, const char *de_name)
11248 int *have_local_changes = arg;
11250 switch (status) {
11251 case GOT_STATUS_ADD:
11252 case GOT_STATUS_DELETE:
11253 case GOT_STATUS_MODIFY:
11254 case GOT_STATUS_CONFLICT:
11255 *have_local_changes = 1;
11256 return got_error(GOT_ERR_CANCELLED);
11257 default:
11258 break;
11261 switch (staged_status) {
11262 case GOT_STATUS_ADD:
11263 case GOT_STATUS_DELETE:
11264 case GOT_STATUS_MODIFY:
11265 *have_local_changes = 1;
11266 return got_error(GOT_ERR_CANCELLED);
11267 default:
11268 break;
11271 return NULL;
11274 static const struct got_error *
11275 cmd_histedit(int argc, char *argv[])
11277 const struct got_error *error = NULL;
11278 struct got_worktree *worktree = NULL;
11279 struct got_fileindex *fileindex = NULL;
11280 struct got_repository *repo = NULL;
11281 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11282 struct got_reference *branch = NULL;
11283 struct got_reference *tmp_branch = NULL;
11284 struct got_object_id *resume_commit_id = NULL;
11285 struct got_object_id *base_commit_id = NULL;
11286 struct got_object_id *head_commit_id = NULL;
11287 struct got_commit_object *commit = NULL;
11288 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11289 struct got_update_progress_arg upa;
11290 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11291 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11292 int list_backups = 0, delete_backups = 0;
11293 const char *edit_script_path = NULL;
11294 struct got_object_id_queue commits;
11295 struct got_pathlist_head merged_paths;
11296 const struct got_object_id_queue *parent_ids;
11297 struct got_object_qid *pid;
11298 struct got_histedit_list histedit_cmds;
11299 struct got_histedit_list_entry *hle;
11300 int *pack_fds = NULL;
11302 STAILQ_INIT(&commits);
11303 TAILQ_INIT(&histedit_cmds);
11304 TAILQ_INIT(&merged_paths);
11305 memset(&upa, 0, sizeof(upa));
11307 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11308 switch (ch) {
11309 case 'a':
11310 abort_edit = 1;
11311 break;
11312 case 'c':
11313 continue_edit = 1;
11314 break;
11315 case 'e':
11316 edit_only = 1;
11317 break;
11318 case 'f':
11319 fold_only = 1;
11320 break;
11321 case 'F':
11322 edit_script_path = optarg;
11323 break;
11324 case 'm':
11325 edit_logmsg_only = 1;
11326 break;
11327 case 'l':
11328 list_backups = 1;
11329 break;
11330 case 'X':
11331 delete_backups = 1;
11332 break;
11333 default:
11334 usage_histedit();
11335 /* NOTREACHED */
11339 argc -= optind;
11340 argv += optind;
11342 #ifndef PROFILE
11343 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11344 "unveil", NULL) == -1)
11345 err(1, "pledge");
11346 #endif
11347 if (abort_edit && continue_edit)
11348 option_conflict('a', 'c');
11349 if (edit_script_path && edit_logmsg_only)
11350 option_conflict('F', 'm');
11351 if (abort_edit && edit_logmsg_only)
11352 option_conflict('a', 'm');
11353 if (continue_edit && edit_logmsg_only)
11354 option_conflict('c', 'm');
11355 if (abort_edit && fold_only)
11356 option_conflict('a', 'f');
11357 if (continue_edit && fold_only)
11358 option_conflict('c', 'f');
11359 if (fold_only && edit_logmsg_only)
11360 option_conflict('f', 'm');
11361 if (edit_script_path && fold_only)
11362 option_conflict('F', 'f');
11363 if (abort_edit && edit_only)
11364 option_conflict('a', 'e');
11365 if (continue_edit && edit_only)
11366 option_conflict('c', 'e');
11367 if (edit_only && edit_logmsg_only)
11368 option_conflict('e', 'm');
11369 if (edit_script_path && edit_only)
11370 option_conflict('F', 'e');
11371 if (list_backups) {
11372 if (abort_edit)
11373 option_conflict('l', 'a');
11374 if (continue_edit)
11375 option_conflict('l', 'c');
11376 if (edit_script_path)
11377 option_conflict('l', 'F');
11378 if (edit_logmsg_only)
11379 option_conflict('l', 'm');
11380 if (fold_only)
11381 option_conflict('l', 'f');
11382 if (edit_only)
11383 option_conflict('l', 'e');
11384 if (delete_backups)
11385 option_conflict('l', 'X');
11386 if (argc != 0 && argc != 1)
11387 usage_histedit();
11388 } else if (delete_backups) {
11389 if (abort_edit)
11390 option_conflict('X', 'a');
11391 if (continue_edit)
11392 option_conflict('X', 'c');
11393 if (edit_script_path)
11394 option_conflict('X', 'F');
11395 if (edit_logmsg_only)
11396 option_conflict('X', 'm');
11397 if (fold_only)
11398 option_conflict('X', 'f');
11399 if (edit_only)
11400 option_conflict('X', 'e');
11401 if (list_backups)
11402 option_conflict('X', 'l');
11403 if (argc != 0 && argc != 1)
11404 usage_histedit();
11405 } else if (argc != 0)
11406 usage_histedit();
11409 * This command cannot apply unveil(2) in all cases because the
11410 * user may choose to run an editor to edit the histedit script
11411 * and to edit individual commit log messages.
11412 * unveil(2) traverses exec(2); if an editor is used we have to
11413 * apply unveil after edit script and log messages have been written.
11414 * XXX TODO: Make use of unveil(2) where possible.
11417 cwd = getcwd(NULL, 0);
11418 if (cwd == NULL) {
11419 error = got_error_from_errno("getcwd");
11420 goto done;
11423 error = got_repo_pack_fds_open(&pack_fds);
11424 if (error != NULL)
11425 goto done;
11427 error = got_worktree_open(&worktree, cwd);
11428 if (error) {
11429 if (list_backups || delete_backups) {
11430 if (error->code != GOT_ERR_NOT_WORKTREE)
11431 goto done;
11432 } else {
11433 if (error->code == GOT_ERR_NOT_WORKTREE)
11434 error = wrap_not_worktree_error(error,
11435 "histedit", cwd);
11436 goto done;
11440 if (list_backups || delete_backups) {
11441 error = got_repo_open(&repo,
11442 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11443 NULL, pack_fds);
11444 if (error != NULL)
11445 goto done;
11446 error = apply_unveil(got_repo_get_path(repo), 0,
11447 worktree ? got_worktree_get_root_path(worktree) : NULL);
11448 if (error)
11449 goto done;
11450 error = process_backup_refs(
11451 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11452 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11453 goto done; /* nothing else to do */
11456 error = get_gitconfig_path(&gitconfig_path);
11457 if (error)
11458 goto done;
11459 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11460 gitconfig_path, pack_fds);
11461 if (error != NULL)
11462 goto done;
11464 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11465 if (error)
11466 goto done;
11467 if (rebase_in_progress) {
11468 error = got_error(GOT_ERR_REBASING);
11469 goto done;
11472 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11473 repo);
11474 if (error)
11475 goto done;
11476 if (merge_in_progress) {
11477 error = got_error(GOT_ERR_MERGE_BUSY);
11478 goto done;
11481 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11482 if (error)
11483 goto done;
11485 if (edit_in_progress && edit_logmsg_only) {
11486 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11487 "histedit operation is in progress in this "
11488 "work tree and must be continued or aborted "
11489 "before the -m option can be used");
11490 goto done;
11492 if (edit_in_progress && fold_only) {
11493 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11494 "histedit operation is in progress in this "
11495 "work tree and must be continued or aborted "
11496 "before the -f option can be used");
11497 goto done;
11499 if (edit_in_progress && edit_only) {
11500 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11501 "histedit operation is in progress in this "
11502 "work tree and must be continued or aborted "
11503 "before the -e option can be used");
11504 goto done;
11507 if (edit_in_progress && abort_edit) {
11508 error = got_worktree_histedit_continue(&resume_commit_id,
11509 &tmp_branch, &branch, &base_commit_id, &fileindex,
11510 worktree, repo);
11511 if (error)
11512 goto done;
11513 printf("Switching work tree to %s\n",
11514 got_ref_get_symref_target(branch));
11515 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11516 branch, base_commit_id, abort_progress, &upa);
11517 if (error)
11518 goto done;
11519 printf("Histedit of %s aborted\n",
11520 got_ref_get_symref_target(branch));
11521 print_merge_progress_stats(&upa);
11522 goto done; /* nothing else to do */
11523 } else if (abort_edit) {
11524 error = got_error(GOT_ERR_NOT_HISTEDIT);
11525 goto done;
11528 error = get_author(&committer, repo, worktree);
11529 if (error)
11530 goto done;
11532 if (continue_edit) {
11533 char *path;
11535 if (!edit_in_progress) {
11536 error = got_error(GOT_ERR_NOT_HISTEDIT);
11537 goto done;
11540 error = got_worktree_get_histedit_script_path(&path, worktree);
11541 if (error)
11542 goto done;
11544 error = histedit_load_list(&histedit_cmds, path, repo);
11545 free(path);
11546 if (error)
11547 goto done;
11549 error = got_worktree_histedit_continue(&resume_commit_id,
11550 &tmp_branch, &branch, &base_commit_id, &fileindex,
11551 worktree, repo);
11552 if (error)
11553 goto done;
11555 error = got_ref_resolve(&head_commit_id, repo, branch);
11556 if (error)
11557 goto done;
11559 error = got_object_open_as_commit(&commit, repo,
11560 head_commit_id);
11561 if (error)
11562 goto done;
11563 parent_ids = got_object_commit_get_parent_ids(commit);
11564 pid = STAILQ_FIRST(parent_ids);
11565 if (pid == NULL) {
11566 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11567 goto done;
11569 error = collect_commits(&commits, head_commit_id, &pid->id,
11570 base_commit_id, got_worktree_get_path_prefix(worktree),
11571 GOT_ERR_HISTEDIT_PATH, repo);
11572 got_object_commit_close(commit);
11573 commit = NULL;
11574 if (error)
11575 goto done;
11576 } else {
11577 if (edit_in_progress) {
11578 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11579 goto done;
11582 error = got_ref_open(&branch, repo,
11583 got_worktree_get_head_ref_name(worktree), 0);
11584 if (error != NULL)
11585 goto done;
11587 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11588 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11589 "will not edit commit history of a branch outside "
11590 "the \"refs/heads/\" reference namespace");
11591 goto done;
11594 error = got_ref_resolve(&head_commit_id, repo, branch);
11595 got_ref_close(branch);
11596 branch = NULL;
11597 if (error)
11598 goto done;
11600 error = got_object_open_as_commit(&commit, repo,
11601 head_commit_id);
11602 if (error)
11603 goto done;
11604 parent_ids = got_object_commit_get_parent_ids(commit);
11605 pid = STAILQ_FIRST(parent_ids);
11606 if (pid == NULL) {
11607 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11608 goto done;
11610 error = collect_commits(&commits, head_commit_id, &pid->id,
11611 got_worktree_get_base_commit_id(worktree),
11612 got_worktree_get_path_prefix(worktree),
11613 GOT_ERR_HISTEDIT_PATH, repo);
11614 got_object_commit_close(commit);
11615 commit = NULL;
11616 if (error)
11617 goto done;
11619 if (STAILQ_EMPTY(&commits)) {
11620 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11621 goto done;
11624 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11625 &base_commit_id, &fileindex, worktree, repo);
11626 if (error)
11627 goto done;
11629 if (edit_script_path) {
11630 error = histedit_load_list(&histedit_cmds,
11631 edit_script_path, repo);
11632 if (error) {
11633 got_worktree_histedit_abort(worktree, fileindex,
11634 repo, branch, base_commit_id,
11635 abort_progress, &upa);
11636 print_merge_progress_stats(&upa);
11637 goto done;
11639 } else {
11640 const char *branch_name;
11641 branch_name = got_ref_get_symref_target(branch);
11642 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11643 branch_name += 11;
11644 error = histedit_edit_script(&histedit_cmds, &commits,
11645 branch_name, edit_logmsg_only, fold_only,
11646 edit_only, repo);
11647 if (error) {
11648 got_worktree_histedit_abort(worktree, fileindex,
11649 repo, branch, base_commit_id,
11650 abort_progress, &upa);
11651 print_merge_progress_stats(&upa);
11652 goto done;
11657 error = histedit_save_list(&histedit_cmds, worktree,
11658 repo);
11659 if (error) {
11660 got_worktree_histedit_abort(worktree, fileindex,
11661 repo, branch, base_commit_id,
11662 abort_progress, &upa);
11663 print_merge_progress_stats(&upa);
11664 goto done;
11669 error = histedit_check_script(&histedit_cmds, &commits, repo);
11670 if (error)
11671 goto done;
11673 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11674 if (resume_commit_id) {
11675 if (got_object_id_cmp(hle->commit_id,
11676 resume_commit_id) != 0)
11677 continue;
11679 resume_commit_id = NULL;
11680 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11681 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11682 error = histedit_skip_commit(hle, worktree,
11683 repo);
11684 if (error)
11685 goto done;
11686 } else {
11687 struct got_pathlist_head paths;
11688 int have_changes = 0;
11690 TAILQ_INIT(&paths);
11691 error = got_pathlist_append(&paths, "", NULL);
11692 if (error)
11693 goto done;
11694 error = got_worktree_status(worktree, &paths,
11695 repo, 0, check_local_changes, &have_changes,
11696 check_cancelled, NULL);
11697 got_pathlist_free(&paths);
11698 if (error) {
11699 if (error->code != GOT_ERR_CANCELLED)
11700 goto done;
11701 if (sigint_received || sigpipe_received)
11702 goto done;
11704 if (have_changes) {
11705 error = histedit_commit(NULL, worktree,
11706 fileindex, tmp_branch, hle,
11707 committer, repo);
11708 if (error)
11709 goto done;
11710 } else {
11711 error = got_object_open_as_commit(
11712 &commit, repo, hle->commit_id);
11713 if (error)
11714 goto done;
11715 error = show_histedit_progress(commit,
11716 hle, NULL);
11717 got_object_commit_close(commit);
11718 commit = NULL;
11719 if (error)
11720 goto done;
11723 continue;
11726 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11727 error = histedit_skip_commit(hle, worktree, repo);
11728 if (error)
11729 goto done;
11730 continue;
11733 error = got_object_open_as_commit(&commit, repo,
11734 hle->commit_id);
11735 if (error)
11736 goto done;
11737 parent_ids = got_object_commit_get_parent_ids(commit);
11738 pid = STAILQ_FIRST(parent_ids);
11740 error = got_worktree_histedit_merge_files(&merged_paths,
11741 worktree, fileindex, &pid->id, hle->commit_id, repo,
11742 update_progress, &upa, check_cancelled, NULL);
11743 if (error)
11744 goto done;
11745 got_object_commit_close(commit);
11746 commit = NULL;
11748 print_merge_progress_stats(&upa);
11749 if (upa.conflicts > 0 || upa.missing > 0 ||
11750 upa.not_deleted > 0 || upa.unversioned > 0) {
11751 if (upa.conflicts > 0) {
11752 error = show_rebase_merge_conflict(
11753 hle->commit_id, repo);
11754 if (error)
11755 goto done;
11757 got_worktree_rebase_pathlist_free(&merged_paths);
11758 break;
11761 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11762 char *id_str;
11763 error = got_object_id_str(&id_str, hle->commit_id);
11764 if (error)
11765 goto done;
11766 printf("Stopping histedit for amending commit %s\n",
11767 id_str);
11768 free(id_str);
11769 got_worktree_rebase_pathlist_free(&merged_paths);
11770 error = got_worktree_histedit_postpone(worktree,
11771 fileindex);
11772 goto done;
11775 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11776 error = histedit_skip_commit(hle, worktree, repo);
11777 if (error)
11778 goto done;
11779 continue;
11782 error = histedit_commit(&merged_paths, worktree, fileindex,
11783 tmp_branch, hle, committer, repo);
11784 got_worktree_rebase_pathlist_free(&merged_paths);
11785 if (error)
11786 goto done;
11789 if (upa.conflicts > 0 || upa.missing > 0 ||
11790 upa.not_deleted > 0 || upa.unversioned > 0) {
11791 error = got_worktree_histedit_postpone(worktree, fileindex);
11792 if (error)
11793 goto done;
11794 if (upa.conflicts > 0 && upa.missing == 0 &&
11795 upa.not_deleted == 0 && upa.unversioned == 0) {
11796 error = got_error_msg(GOT_ERR_CONFLICTS,
11797 "conflicts must be resolved before histedit "
11798 "can continue");
11799 } else if (upa.conflicts > 0) {
11800 error = got_error_msg(GOT_ERR_CONFLICTS,
11801 "conflicts must be resolved before histedit "
11802 "can continue; changes destined for some "
11803 "files were not yet merged and should be "
11804 "merged manually if required before the "
11805 "histedit operation is continued");
11806 } else {
11807 error = got_error_msg(GOT_ERR_CONFLICTS,
11808 "changes destined for some files were not "
11809 "yet merged and should be merged manually "
11810 "if required before the histedit operation "
11811 "is continued");
11813 } else
11814 error = histedit_complete(worktree, fileindex, tmp_branch,
11815 branch, repo);
11816 done:
11817 free(cwd);
11818 free(committer);
11819 free(gitconfig_path);
11820 got_object_id_queue_free(&commits);
11821 histedit_free_list(&histedit_cmds);
11822 free(head_commit_id);
11823 free(base_commit_id);
11824 free(resume_commit_id);
11825 if (commit)
11826 got_object_commit_close(commit);
11827 if (branch)
11828 got_ref_close(branch);
11829 if (tmp_branch)
11830 got_ref_close(tmp_branch);
11831 if (worktree)
11832 got_worktree_close(worktree);
11833 if (repo) {
11834 const struct got_error *close_err = got_repo_close(repo);
11835 if (error == NULL)
11836 error = close_err;
11838 if (pack_fds) {
11839 const struct got_error *pack_err =
11840 got_repo_pack_fds_close(pack_fds);
11841 if (error == NULL)
11842 error = pack_err;
11844 return error;
11847 __dead static void
11848 usage_integrate(void)
11850 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11851 exit(1);
11854 static const struct got_error *
11855 cmd_integrate(int argc, char *argv[])
11857 const struct got_error *error = NULL;
11858 struct got_repository *repo = NULL;
11859 struct got_worktree *worktree = NULL;
11860 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11861 const char *branch_arg = NULL;
11862 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11863 struct got_fileindex *fileindex = NULL;
11864 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11865 int ch;
11866 struct got_update_progress_arg upa;
11867 int *pack_fds = NULL;
11869 while ((ch = getopt(argc, argv, "")) != -1) {
11870 switch (ch) {
11871 default:
11872 usage_integrate();
11873 /* NOTREACHED */
11877 argc -= optind;
11878 argv += optind;
11880 if (argc != 1)
11881 usage_integrate();
11882 branch_arg = argv[0];
11883 #ifndef PROFILE
11884 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11885 "unveil", NULL) == -1)
11886 err(1, "pledge");
11887 #endif
11888 cwd = getcwd(NULL, 0);
11889 if (cwd == NULL) {
11890 error = got_error_from_errno("getcwd");
11891 goto done;
11894 error = got_repo_pack_fds_open(&pack_fds);
11895 if (error != NULL)
11896 goto done;
11898 error = got_worktree_open(&worktree, cwd);
11899 if (error) {
11900 if (error->code == GOT_ERR_NOT_WORKTREE)
11901 error = wrap_not_worktree_error(error, "integrate",
11902 cwd);
11903 goto done;
11906 error = check_rebase_or_histedit_in_progress(worktree);
11907 if (error)
11908 goto done;
11910 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11911 NULL, pack_fds);
11912 if (error != NULL)
11913 goto done;
11915 error = apply_unveil(got_repo_get_path(repo), 0,
11916 got_worktree_get_root_path(worktree));
11917 if (error)
11918 goto done;
11920 error = check_merge_in_progress(worktree, repo);
11921 if (error)
11922 goto done;
11924 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11925 error = got_error_from_errno("asprintf");
11926 goto done;
11929 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11930 &base_branch_ref, worktree, refname, repo);
11931 if (error)
11932 goto done;
11934 refname = strdup(got_ref_get_name(branch_ref));
11935 if (refname == NULL) {
11936 error = got_error_from_errno("strdup");
11937 got_worktree_integrate_abort(worktree, fileindex, repo,
11938 branch_ref, base_branch_ref);
11939 goto done;
11941 base_refname = strdup(got_ref_get_name(base_branch_ref));
11942 if (base_refname == NULL) {
11943 error = got_error_from_errno("strdup");
11944 got_worktree_integrate_abort(worktree, fileindex, repo,
11945 branch_ref, base_branch_ref);
11946 goto done;
11949 error = got_ref_resolve(&commit_id, repo, branch_ref);
11950 if (error)
11951 goto done;
11953 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11954 if (error)
11955 goto done;
11957 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11958 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11959 "specified branch has already been integrated");
11960 got_worktree_integrate_abort(worktree, fileindex, repo,
11961 branch_ref, base_branch_ref);
11962 goto done;
11965 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11966 if (error) {
11967 if (error->code == GOT_ERR_ANCESTRY)
11968 error = got_error(GOT_ERR_REBASE_REQUIRED);
11969 got_worktree_integrate_abort(worktree, fileindex, repo,
11970 branch_ref, base_branch_ref);
11971 goto done;
11974 memset(&upa, 0, sizeof(upa));
11975 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11976 branch_ref, base_branch_ref, update_progress, &upa,
11977 check_cancelled, NULL);
11978 if (error)
11979 goto done;
11981 printf("Integrated %s into %s\n", refname, base_refname);
11982 print_update_progress_stats(&upa);
11983 done:
11984 if (repo) {
11985 const struct got_error *close_err = got_repo_close(repo);
11986 if (error == NULL)
11987 error = close_err;
11989 if (worktree)
11990 got_worktree_close(worktree);
11991 if (pack_fds) {
11992 const struct got_error *pack_err =
11993 got_repo_pack_fds_close(pack_fds);
11994 if (error == NULL)
11995 error = pack_err;
11997 free(cwd);
11998 free(base_commit_id);
11999 free(commit_id);
12000 free(refname);
12001 free(base_refname);
12002 return error;
12005 __dead static void
12006 usage_merge(void)
12008 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12009 exit(1);
12012 static const struct got_error *
12013 cmd_merge(int argc, char *argv[])
12015 const struct got_error *error = NULL;
12016 struct got_worktree *worktree = NULL;
12017 struct got_repository *repo = NULL;
12018 struct got_fileindex *fileindex = NULL;
12019 char *cwd = NULL, *id_str = NULL, *author = NULL;
12020 struct got_reference *branch = NULL, *wt_branch = NULL;
12021 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12022 struct got_object_id *wt_branch_tip = NULL;
12023 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12024 int interrupt_merge = 0;
12025 struct got_update_progress_arg upa;
12026 struct got_object_id *merge_commit_id = NULL;
12027 char *branch_name = NULL;
12028 int *pack_fds = NULL;
12030 memset(&upa, 0, sizeof(upa));
12032 while ((ch = getopt(argc, argv, "acn")) != -1) {
12033 switch (ch) {
12034 case 'a':
12035 abort_merge = 1;
12036 break;
12037 case 'c':
12038 continue_merge = 1;
12039 break;
12040 case 'n':
12041 interrupt_merge = 1;
12042 break;
12043 default:
12044 usage_rebase();
12045 /* NOTREACHED */
12049 argc -= optind;
12050 argv += optind;
12052 #ifndef PROFILE
12053 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12054 "unveil", NULL) == -1)
12055 err(1, "pledge");
12056 #endif
12058 if (abort_merge && continue_merge)
12059 option_conflict('a', 'c');
12060 if (abort_merge || continue_merge) {
12061 if (argc != 0)
12062 usage_merge();
12063 } else if (argc != 1)
12064 usage_merge();
12066 cwd = getcwd(NULL, 0);
12067 if (cwd == NULL) {
12068 error = got_error_from_errno("getcwd");
12069 goto done;
12072 error = got_repo_pack_fds_open(&pack_fds);
12073 if (error != NULL)
12074 goto done;
12076 error = got_worktree_open(&worktree, cwd);
12077 if (error) {
12078 if (error->code == GOT_ERR_NOT_WORKTREE)
12079 error = wrap_not_worktree_error(error,
12080 "merge", cwd);
12081 goto done;
12084 error = got_repo_open(&repo,
12085 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12086 pack_fds);
12087 if (error != NULL)
12088 goto done;
12090 error = apply_unveil(got_repo_get_path(repo), 0,
12091 worktree ? got_worktree_get_root_path(worktree) : NULL);
12092 if (error)
12093 goto done;
12095 error = check_rebase_or_histedit_in_progress(worktree);
12096 if (error)
12097 goto done;
12099 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12100 repo);
12101 if (error)
12102 goto done;
12104 if (abort_merge) {
12105 if (!merge_in_progress) {
12106 error = got_error(GOT_ERR_NOT_MERGING);
12107 goto done;
12109 error = got_worktree_merge_continue(&branch_name,
12110 &branch_tip, &fileindex, worktree, repo);
12111 if (error)
12112 goto done;
12113 error = got_worktree_merge_abort(worktree, fileindex, repo,
12114 abort_progress, &upa);
12115 if (error)
12116 goto done;
12117 printf("Merge of %s aborted\n", branch_name);
12118 goto done; /* nothing else to do */
12121 error = get_author(&author, repo, worktree);
12122 if (error)
12123 goto done;
12125 if (continue_merge) {
12126 if (!merge_in_progress) {
12127 error = got_error(GOT_ERR_NOT_MERGING);
12128 goto done;
12130 error = got_worktree_merge_continue(&branch_name,
12131 &branch_tip, &fileindex, worktree, repo);
12132 if (error)
12133 goto done;
12134 } else {
12135 error = got_ref_open(&branch, repo, argv[0], 0);
12136 if (error != NULL)
12137 goto done;
12138 branch_name = strdup(got_ref_get_name(branch));
12139 if (branch_name == NULL) {
12140 error = got_error_from_errno("strdup");
12141 goto done;
12143 error = got_ref_resolve(&branch_tip, repo, branch);
12144 if (error)
12145 goto done;
12148 error = got_ref_open(&wt_branch, repo,
12149 got_worktree_get_head_ref_name(worktree), 0);
12150 if (error)
12151 goto done;
12152 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12153 if (error)
12154 goto done;
12155 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12156 wt_branch_tip, branch_tip, 0, repo,
12157 check_cancelled, NULL);
12158 if (error && error->code != GOT_ERR_ANCESTRY)
12159 goto done;
12161 if (!continue_merge) {
12162 error = check_path_prefix(wt_branch_tip, branch_tip,
12163 got_worktree_get_path_prefix(worktree),
12164 GOT_ERR_MERGE_PATH, repo);
12165 if (error)
12166 goto done;
12167 if (yca_id) {
12168 error = check_same_branch(wt_branch_tip, branch,
12169 yca_id, repo);
12170 if (error) {
12171 if (error->code != GOT_ERR_ANCESTRY)
12172 goto done;
12173 error = NULL;
12174 } else {
12175 static char msg[512];
12176 snprintf(msg, sizeof(msg),
12177 "cannot create a merge commit because "
12178 "%s is based on %s; %s can be integrated "
12179 "with 'got integrate' instead", branch_name,
12180 got_worktree_get_head_ref_name(worktree),
12181 branch_name);
12182 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12183 goto done;
12186 error = got_worktree_merge_prepare(&fileindex, worktree,
12187 branch, repo);
12188 if (error)
12189 goto done;
12191 error = got_worktree_merge_branch(worktree, fileindex,
12192 yca_id, branch_tip, repo, update_progress, &upa,
12193 check_cancelled, NULL);
12194 if (error)
12195 goto done;
12196 print_merge_progress_stats(&upa);
12197 if (!upa.did_something) {
12198 error = got_worktree_merge_abort(worktree, fileindex,
12199 repo, abort_progress, &upa);
12200 if (error)
12201 goto done;
12202 printf("Already up-to-date\n");
12203 goto done;
12207 if (interrupt_merge) {
12208 error = got_worktree_merge_postpone(worktree, fileindex);
12209 if (error)
12210 goto done;
12211 printf("Merge of %s interrupted on request\n", branch_name);
12212 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12213 upa.not_deleted > 0 || upa.unversioned > 0) {
12214 error = got_worktree_merge_postpone(worktree, fileindex);
12215 if (error)
12216 goto done;
12217 if (upa.conflicts > 0 && upa.missing == 0 &&
12218 upa.not_deleted == 0 && upa.unversioned == 0) {
12219 error = got_error_msg(GOT_ERR_CONFLICTS,
12220 "conflicts must be resolved before merging "
12221 "can continue");
12222 } else if (upa.conflicts > 0) {
12223 error = got_error_msg(GOT_ERR_CONFLICTS,
12224 "conflicts must be resolved before merging "
12225 "can continue; changes destined for some "
12226 "files were not yet merged and "
12227 "should be merged manually if required before the "
12228 "merge operation is continued");
12229 } else {
12230 error = got_error_msg(GOT_ERR_CONFLICTS,
12231 "changes destined for some "
12232 "files were not yet merged and should be "
12233 "merged manually if required before the "
12234 "merge operation is continued");
12236 goto done;
12237 } else {
12238 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12239 fileindex, author, NULL, 1, branch_tip, branch_name,
12240 repo, continue_merge ? print_status : NULL, NULL);
12241 if (error)
12242 goto done;
12243 error = got_worktree_merge_complete(worktree, fileindex, repo);
12244 if (error)
12245 goto done;
12246 error = got_object_id_str(&id_str, merge_commit_id);
12247 if (error)
12248 goto done;
12249 printf("Merged %s into %s: %s\n", branch_name,
12250 got_worktree_get_head_ref_name(worktree),
12251 id_str);
12254 done:
12255 free(id_str);
12256 free(merge_commit_id);
12257 free(author);
12258 free(branch_tip);
12259 free(branch_name);
12260 free(yca_id);
12261 if (branch)
12262 got_ref_close(branch);
12263 if (wt_branch)
12264 got_ref_close(wt_branch);
12265 if (worktree)
12266 got_worktree_close(worktree);
12267 if (repo) {
12268 const struct got_error *close_err = got_repo_close(repo);
12269 if (error == NULL)
12270 error = close_err;
12272 if (pack_fds) {
12273 const struct got_error *pack_err =
12274 got_repo_pack_fds_close(pack_fds);
12275 if (error == NULL)
12276 error = pack_err;
12278 return error;
12281 __dead static void
12282 usage_stage(void)
12284 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12285 "[path ...]\n", getprogname());
12286 exit(1);
12289 static const struct got_error *
12290 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12291 const char *path, struct got_object_id *blob_id,
12292 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12293 int dirfd, const char *de_name)
12295 const struct got_error *err = NULL;
12296 char *id_str = NULL;
12298 if (staged_status != GOT_STATUS_ADD &&
12299 staged_status != GOT_STATUS_MODIFY &&
12300 staged_status != GOT_STATUS_DELETE)
12301 return NULL;
12303 if (staged_status == GOT_STATUS_ADD ||
12304 staged_status == GOT_STATUS_MODIFY)
12305 err = got_object_id_str(&id_str, staged_blob_id);
12306 else
12307 err = got_object_id_str(&id_str, blob_id);
12308 if (err)
12309 return err;
12311 printf("%s %c %s\n", id_str, staged_status, path);
12312 free(id_str);
12313 return NULL;
12316 static const struct got_error *
12317 cmd_stage(int argc, char *argv[])
12319 const struct got_error *error = NULL;
12320 struct got_repository *repo = NULL;
12321 struct got_worktree *worktree = NULL;
12322 char *cwd = NULL;
12323 struct got_pathlist_head paths;
12324 struct got_pathlist_entry *pe;
12325 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12326 FILE *patch_script_file = NULL;
12327 const char *patch_script_path = NULL;
12328 struct choose_patch_arg cpa;
12329 int *pack_fds = NULL;
12331 TAILQ_INIT(&paths);
12333 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12334 switch (ch) {
12335 case 'l':
12336 list_stage = 1;
12337 break;
12338 case 'p':
12339 pflag = 1;
12340 break;
12341 case 'F':
12342 patch_script_path = optarg;
12343 break;
12344 case 'S':
12345 allow_bad_symlinks = 1;
12346 break;
12347 default:
12348 usage_stage();
12349 /* NOTREACHED */
12353 argc -= optind;
12354 argv += optind;
12356 #ifndef PROFILE
12357 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12358 "unveil", NULL) == -1)
12359 err(1, "pledge");
12360 #endif
12361 if (list_stage && (pflag || patch_script_path))
12362 errx(1, "-l option cannot be used with other options");
12363 if (patch_script_path && !pflag)
12364 errx(1, "-F option can only be used together with -p option");
12366 cwd = getcwd(NULL, 0);
12367 if (cwd == NULL) {
12368 error = got_error_from_errno("getcwd");
12369 goto done;
12372 error = got_repo_pack_fds_open(&pack_fds);
12373 if (error != NULL)
12374 goto done;
12376 error = got_worktree_open(&worktree, cwd);
12377 if (error) {
12378 if (error->code == GOT_ERR_NOT_WORKTREE)
12379 error = wrap_not_worktree_error(error, "stage", cwd);
12380 goto done;
12383 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12384 NULL, pack_fds);
12385 if (error != NULL)
12386 goto done;
12388 if (patch_script_path) {
12389 patch_script_file = fopen(patch_script_path, "re");
12390 if (patch_script_file == NULL) {
12391 error = got_error_from_errno2("fopen",
12392 patch_script_path);
12393 goto done;
12396 error = apply_unveil(got_repo_get_path(repo), 0,
12397 got_worktree_get_root_path(worktree));
12398 if (error)
12399 goto done;
12401 error = check_merge_in_progress(worktree, repo);
12402 if (error)
12403 goto done;
12405 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12406 if (error)
12407 goto done;
12409 if (list_stage)
12410 error = got_worktree_status(worktree, &paths, repo, 0,
12411 print_stage, NULL, check_cancelled, NULL);
12412 else {
12413 cpa.patch_script_file = patch_script_file;
12414 cpa.action = "stage";
12415 error = got_worktree_stage(worktree, &paths,
12416 pflag ? NULL : print_status, NULL,
12417 pflag ? choose_patch : NULL, &cpa,
12418 allow_bad_symlinks, repo);
12420 done:
12421 if (patch_script_file && fclose(patch_script_file) == EOF &&
12422 error == NULL)
12423 error = got_error_from_errno2("fclose", patch_script_path);
12424 if (repo) {
12425 const struct got_error *close_err = got_repo_close(repo);
12426 if (error == NULL)
12427 error = close_err;
12429 if (worktree)
12430 got_worktree_close(worktree);
12431 if (pack_fds) {
12432 const struct got_error *pack_err =
12433 got_repo_pack_fds_close(pack_fds);
12434 if (error == NULL)
12435 error = pack_err;
12437 TAILQ_FOREACH(pe, &paths, entry)
12438 free((char *)pe->path);
12439 got_pathlist_free(&paths);
12440 free(cwd);
12441 return error;
12444 __dead static void
12445 usage_unstage(void)
12447 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12448 "[path ...]\n", getprogname());
12449 exit(1);
12453 static const struct got_error *
12454 cmd_unstage(int argc, char *argv[])
12456 const struct got_error *error = NULL;
12457 struct got_repository *repo = NULL;
12458 struct got_worktree *worktree = NULL;
12459 char *cwd = NULL;
12460 struct got_pathlist_head paths;
12461 struct got_pathlist_entry *pe;
12462 int ch, pflag = 0;
12463 struct got_update_progress_arg upa;
12464 FILE *patch_script_file = NULL;
12465 const char *patch_script_path = NULL;
12466 struct choose_patch_arg cpa;
12467 int *pack_fds = NULL;
12469 TAILQ_INIT(&paths);
12471 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12472 switch (ch) {
12473 case 'p':
12474 pflag = 1;
12475 break;
12476 case 'F':
12477 patch_script_path = optarg;
12478 break;
12479 default:
12480 usage_unstage();
12481 /* NOTREACHED */
12485 argc -= optind;
12486 argv += optind;
12488 #ifndef PROFILE
12489 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12490 "unveil", NULL) == -1)
12491 err(1, "pledge");
12492 #endif
12493 if (patch_script_path && !pflag)
12494 errx(1, "-F option can only be used together with -p option");
12496 cwd = getcwd(NULL, 0);
12497 if (cwd == NULL) {
12498 error = got_error_from_errno("getcwd");
12499 goto done;
12502 error = got_repo_pack_fds_open(&pack_fds);
12503 if (error != NULL)
12504 goto done;
12506 error = got_worktree_open(&worktree, cwd);
12507 if (error) {
12508 if (error->code == GOT_ERR_NOT_WORKTREE)
12509 error = wrap_not_worktree_error(error, "unstage", cwd);
12510 goto done;
12513 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12514 NULL, pack_fds);
12515 if (error != NULL)
12516 goto done;
12518 if (patch_script_path) {
12519 patch_script_file = fopen(patch_script_path, "re");
12520 if (patch_script_file == NULL) {
12521 error = got_error_from_errno2("fopen",
12522 patch_script_path);
12523 goto done;
12527 error = apply_unveil(got_repo_get_path(repo), 0,
12528 got_worktree_get_root_path(worktree));
12529 if (error)
12530 goto done;
12532 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12533 if (error)
12534 goto done;
12536 cpa.patch_script_file = patch_script_file;
12537 cpa.action = "unstage";
12538 memset(&upa, 0, sizeof(upa));
12539 error = got_worktree_unstage(worktree, &paths, update_progress,
12540 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12541 if (!error)
12542 print_merge_progress_stats(&upa);
12543 done:
12544 if (patch_script_file && fclose(patch_script_file) == EOF &&
12545 error == NULL)
12546 error = got_error_from_errno2("fclose", patch_script_path);
12547 if (repo) {
12548 const struct got_error *close_err = got_repo_close(repo);
12549 if (error == NULL)
12550 error = close_err;
12552 if (worktree)
12553 got_worktree_close(worktree);
12554 if (pack_fds) {
12555 const struct got_error *pack_err =
12556 got_repo_pack_fds_close(pack_fds);
12557 if (error == NULL)
12558 error = pack_err;
12560 TAILQ_FOREACH(pe, &paths, entry)
12561 free((char *)pe->path);
12562 got_pathlist_free(&paths);
12563 free(cwd);
12564 return error;
12567 __dead static void
12568 usage_cat(void)
12570 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12571 "arg ...\n", getprogname());
12572 exit(1);
12575 static const struct got_error *
12576 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12578 const struct got_error *err;
12579 struct got_blob_object *blob;
12580 int fd = -1;
12582 fd = got_opentempfd();
12583 if (fd == -1)
12584 return got_error_from_errno("got_opentempfd");
12586 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12587 if (err)
12588 goto done;
12590 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12591 done:
12592 if (fd != -1 && close(fd) == -1 && err == NULL)
12593 err = got_error_from_errno("close");
12594 if (blob)
12595 got_object_blob_close(blob);
12596 return err;
12599 static const struct got_error *
12600 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12602 const struct got_error *err;
12603 struct got_tree_object *tree;
12604 int nentries, i;
12606 err = got_object_open_as_tree(&tree, repo, id);
12607 if (err)
12608 return err;
12610 nentries = got_object_tree_get_nentries(tree);
12611 for (i = 0; i < nentries; i++) {
12612 struct got_tree_entry *te;
12613 char *id_str;
12614 if (sigint_received || sigpipe_received)
12615 break;
12616 te = got_object_tree_get_entry(tree, i);
12617 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12618 if (err)
12619 break;
12620 fprintf(outfile, "%s %.7o %s\n", id_str,
12621 got_tree_entry_get_mode(te),
12622 got_tree_entry_get_name(te));
12623 free(id_str);
12626 got_object_tree_close(tree);
12627 return err;
12630 static const struct got_error *
12631 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12633 const struct got_error *err;
12634 struct got_commit_object *commit;
12635 const struct got_object_id_queue *parent_ids;
12636 struct got_object_qid *pid;
12637 char *id_str = NULL;
12638 const char *logmsg = NULL;
12639 char gmtoff[6];
12641 err = got_object_open_as_commit(&commit, repo, id);
12642 if (err)
12643 return err;
12645 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12646 if (err)
12647 goto done;
12649 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12650 parent_ids = got_object_commit_get_parent_ids(commit);
12651 fprintf(outfile, "numparents %d\n",
12652 got_object_commit_get_nparents(commit));
12653 STAILQ_FOREACH(pid, parent_ids, entry) {
12654 char *pid_str;
12655 err = got_object_id_str(&pid_str, &pid->id);
12656 if (err)
12657 goto done;
12658 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12659 free(pid_str);
12661 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12662 got_object_commit_get_author_gmtoff(commit));
12663 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12664 got_object_commit_get_author(commit),
12665 (long long)got_object_commit_get_author_time(commit),
12666 gmtoff);
12668 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12669 got_object_commit_get_committer_gmtoff(commit));
12670 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12671 got_object_commit_get_committer(commit),
12672 (long long)got_object_commit_get_committer_time(commit),
12673 gmtoff);
12675 logmsg = got_object_commit_get_logmsg_raw(commit);
12676 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12677 fprintf(outfile, "%s", logmsg);
12678 done:
12679 free(id_str);
12680 got_object_commit_close(commit);
12681 return err;
12684 static const struct got_error *
12685 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12687 const struct got_error *err;
12688 struct got_tag_object *tag;
12689 char *id_str = NULL;
12690 const char *tagmsg = NULL;
12691 char gmtoff[6];
12693 err = got_object_open_as_tag(&tag, repo, id);
12694 if (err)
12695 return err;
12697 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12698 if (err)
12699 goto done;
12701 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12703 switch (got_object_tag_get_object_type(tag)) {
12704 case GOT_OBJ_TYPE_BLOB:
12705 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12706 GOT_OBJ_LABEL_BLOB);
12707 break;
12708 case GOT_OBJ_TYPE_TREE:
12709 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12710 GOT_OBJ_LABEL_TREE);
12711 break;
12712 case GOT_OBJ_TYPE_COMMIT:
12713 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12714 GOT_OBJ_LABEL_COMMIT);
12715 break;
12716 case GOT_OBJ_TYPE_TAG:
12717 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12718 GOT_OBJ_LABEL_TAG);
12719 break;
12720 default:
12721 break;
12724 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12725 got_object_tag_get_name(tag));
12727 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12728 got_object_tag_get_tagger_gmtoff(tag));
12729 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12730 got_object_tag_get_tagger(tag),
12731 (long long)got_object_tag_get_tagger_time(tag),
12732 gmtoff);
12734 tagmsg = got_object_tag_get_message(tag);
12735 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12736 fprintf(outfile, "%s", tagmsg);
12737 done:
12738 free(id_str);
12739 got_object_tag_close(tag);
12740 return err;
12743 static const struct got_error *
12744 cmd_cat(int argc, char *argv[])
12746 const struct got_error *error;
12747 struct got_repository *repo = NULL;
12748 struct got_worktree *worktree = NULL;
12749 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12750 const char *commit_id_str = NULL;
12751 struct got_object_id *id = NULL, *commit_id = NULL;
12752 struct got_commit_object *commit = NULL;
12753 int ch, obj_type, i, force_path = 0;
12754 struct got_reflist_head refs;
12755 int *pack_fds = NULL;
12757 TAILQ_INIT(&refs);
12759 #ifndef PROFILE
12760 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12761 NULL) == -1)
12762 err(1, "pledge");
12763 #endif
12765 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12766 switch (ch) {
12767 case 'c':
12768 commit_id_str = optarg;
12769 break;
12770 case 'r':
12771 repo_path = realpath(optarg, NULL);
12772 if (repo_path == NULL)
12773 return got_error_from_errno2("realpath",
12774 optarg);
12775 got_path_strip_trailing_slashes(repo_path);
12776 break;
12777 case 'P':
12778 force_path = 1;
12779 break;
12780 default:
12781 usage_cat();
12782 /* NOTREACHED */
12786 argc -= optind;
12787 argv += optind;
12789 cwd = getcwd(NULL, 0);
12790 if (cwd == NULL) {
12791 error = got_error_from_errno("getcwd");
12792 goto done;
12795 error = got_repo_pack_fds_open(&pack_fds);
12796 if (error != NULL)
12797 goto done;
12799 if (repo_path == NULL) {
12800 error = got_worktree_open(&worktree, cwd);
12801 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12802 goto done;
12803 if (worktree) {
12804 repo_path = strdup(
12805 got_worktree_get_repo_path(worktree));
12806 if (repo_path == NULL) {
12807 error = got_error_from_errno("strdup");
12808 goto done;
12811 /* Release work tree lock. */
12812 got_worktree_close(worktree);
12813 worktree = NULL;
12817 if (repo_path == NULL) {
12818 repo_path = strdup(cwd);
12819 if (repo_path == NULL)
12820 return got_error_from_errno("strdup");
12823 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12824 free(repo_path);
12825 if (error != NULL)
12826 goto done;
12828 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12829 if (error)
12830 goto done;
12832 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12833 if (error)
12834 goto done;
12836 if (commit_id_str == NULL)
12837 commit_id_str = GOT_REF_HEAD;
12838 error = got_repo_match_object_id(&commit_id, NULL,
12839 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12840 if (error)
12841 goto done;
12843 error = got_object_open_as_commit(&commit, repo, commit_id);
12844 if (error)
12845 goto done;
12847 for (i = 0; i < argc; i++) {
12848 if (force_path) {
12849 error = got_object_id_by_path(&id, repo, commit,
12850 argv[i]);
12851 if (error)
12852 break;
12853 } else {
12854 error = got_repo_match_object_id(&id, &label, argv[i],
12855 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12856 repo);
12857 if (error) {
12858 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12859 error->code != GOT_ERR_NOT_REF)
12860 break;
12861 error = got_object_id_by_path(&id, repo,
12862 commit, argv[i]);
12863 if (error)
12864 break;
12868 error = got_object_get_type(&obj_type, repo, id);
12869 if (error)
12870 break;
12872 switch (obj_type) {
12873 case GOT_OBJ_TYPE_BLOB:
12874 error = cat_blob(id, repo, stdout);
12875 break;
12876 case GOT_OBJ_TYPE_TREE:
12877 error = cat_tree(id, repo, stdout);
12878 break;
12879 case GOT_OBJ_TYPE_COMMIT:
12880 error = cat_commit(id, repo, stdout);
12881 break;
12882 case GOT_OBJ_TYPE_TAG:
12883 error = cat_tag(id, repo, stdout);
12884 break;
12885 default:
12886 error = got_error(GOT_ERR_OBJ_TYPE);
12887 break;
12889 if (error)
12890 break;
12891 free(label);
12892 label = NULL;
12893 free(id);
12894 id = NULL;
12896 done:
12897 free(label);
12898 free(id);
12899 free(commit_id);
12900 if (commit)
12901 got_object_commit_close(commit);
12902 if (worktree)
12903 got_worktree_close(worktree);
12904 if (repo) {
12905 const struct got_error *close_err = got_repo_close(repo);
12906 if (error == NULL)
12907 error = close_err;
12909 if (pack_fds) {
12910 const struct got_error *pack_err =
12911 got_repo_pack_fds_close(pack_fds);
12912 if (error == NULL)
12913 error = pack_err;
12916 got_ref_list_free(&refs);
12917 return error;
12920 __dead static void
12921 usage_info(void)
12923 fprintf(stderr, "usage: %s info [path ...]\n",
12924 getprogname());
12925 exit(1);
12928 static const struct got_error *
12929 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12930 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12931 struct got_object_id *commit_id)
12933 const struct got_error *err = NULL;
12934 char *id_str = NULL;
12935 char datebuf[128];
12936 struct tm mytm, *tm;
12937 struct got_pathlist_head *paths = arg;
12938 struct got_pathlist_entry *pe;
12941 * Clear error indication from any of the path arguments which
12942 * would cause this file index entry to be displayed.
12944 TAILQ_FOREACH(pe, paths, entry) {
12945 if (got_path_cmp(path, pe->path, strlen(path),
12946 pe->path_len) == 0 ||
12947 got_path_is_child(path, pe->path, pe->path_len))
12948 pe->data = NULL; /* no error */
12951 printf(GOT_COMMIT_SEP_STR);
12952 if (S_ISLNK(mode))
12953 printf("symlink: %s\n", path);
12954 else if (S_ISREG(mode)) {
12955 printf("file: %s\n", path);
12956 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12957 } else if (S_ISDIR(mode))
12958 printf("directory: %s\n", path);
12959 else
12960 printf("something: %s\n", path);
12962 tm = localtime_r(&mtime, &mytm);
12963 if (tm == NULL)
12964 return NULL;
12965 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12966 return got_error(GOT_ERR_NO_SPACE);
12967 printf("timestamp: %s\n", datebuf);
12969 if (blob_id) {
12970 err = got_object_id_str(&id_str, blob_id);
12971 if (err)
12972 return err;
12973 printf("based on blob: %s\n", id_str);
12974 free(id_str);
12977 if (staged_blob_id) {
12978 err = got_object_id_str(&id_str, staged_blob_id);
12979 if (err)
12980 return err;
12981 printf("based on staged blob: %s\n", id_str);
12982 free(id_str);
12985 if (commit_id) {
12986 err = got_object_id_str(&id_str, commit_id);
12987 if (err)
12988 return err;
12989 printf("based on commit: %s\n", id_str);
12990 free(id_str);
12993 return NULL;
12996 static const struct got_error *
12997 cmd_info(int argc, char *argv[])
12999 const struct got_error *error = NULL;
13000 struct got_worktree *worktree = NULL;
13001 char *cwd = NULL, *id_str = NULL;
13002 struct got_pathlist_head paths;
13003 struct got_pathlist_entry *pe;
13004 char *uuidstr = NULL;
13005 int ch, show_files = 0;
13007 TAILQ_INIT(&paths);
13009 while ((ch = getopt(argc, argv, "")) != -1) {
13010 switch (ch) {
13011 default:
13012 usage_info();
13013 /* NOTREACHED */
13017 argc -= optind;
13018 argv += optind;
13020 #ifndef PROFILE
13021 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13022 NULL) == -1)
13023 err(1, "pledge");
13024 #endif
13025 cwd = getcwd(NULL, 0);
13026 if (cwd == NULL) {
13027 error = got_error_from_errno("getcwd");
13028 goto done;
13031 error = got_worktree_open(&worktree, cwd);
13032 if (error) {
13033 if (error->code == GOT_ERR_NOT_WORKTREE)
13034 error = wrap_not_worktree_error(error, "info", cwd);
13035 goto done;
13038 #ifndef PROFILE
13039 /* Remove "wpath cpath proc exec sendfd" promises. */
13040 if (pledge("stdio rpath flock unveil", NULL) == -1)
13041 err(1, "pledge");
13042 #endif
13043 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13044 if (error)
13045 goto done;
13047 if (argc >= 1) {
13048 error = get_worktree_paths_from_argv(&paths, argc, argv,
13049 worktree);
13050 if (error)
13051 goto done;
13052 show_files = 1;
13055 error = got_object_id_str(&id_str,
13056 got_worktree_get_base_commit_id(worktree));
13057 if (error)
13058 goto done;
13060 error = got_worktree_get_uuid(&uuidstr, worktree);
13061 if (error)
13062 goto done;
13064 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13065 printf("work tree base commit: %s\n", id_str);
13066 printf("work tree path prefix: %s\n",
13067 got_worktree_get_path_prefix(worktree));
13068 printf("work tree branch reference: %s\n",
13069 got_worktree_get_head_ref_name(worktree));
13070 printf("work tree UUID: %s\n", uuidstr);
13071 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13073 if (show_files) {
13074 struct got_pathlist_entry *pe;
13075 TAILQ_FOREACH(pe, &paths, entry) {
13076 if (pe->path_len == 0)
13077 continue;
13079 * Assume this path will fail. This will be corrected
13080 * in print_path_info() in case the path does suceeed.
13082 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13084 error = got_worktree_path_info(worktree, &paths,
13085 print_path_info, &paths, check_cancelled, NULL);
13086 if (error)
13087 goto done;
13088 TAILQ_FOREACH(pe, &paths, entry) {
13089 if (pe->data != NULL) {
13090 const struct got_error *perr;
13092 perr = pe->data;
13093 error = got_error_fmt(perr->code, "%s",
13094 pe->path);
13095 break;
13099 done:
13100 if (worktree)
13101 got_worktree_close(worktree);
13102 TAILQ_FOREACH(pe, &paths, entry)
13103 free((char *)pe->path);
13104 got_pathlist_free(&paths);
13105 free(cwd);
13106 free(id_str);
13107 free(uuidstr);
13108 return error;