Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (*author++ != '<')
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 = NULL;
763 char *id_str = NULL, *logmsg_path = NULL;
764 char refname[PATH_MAX] = "refs/heads/";
765 struct got_repository *repo = NULL;
766 struct got_reference *branch_ref = NULL, *head_ref = NULL;
767 struct got_object_id *new_commit_id = NULL;
768 int ch, n = 0;
769 struct got_pathlist_head ignores;
770 struct got_pathlist_entry *pe;
771 int preserve_logmsg = 0;
772 int *pack_fds = NULL;
774 TAILQ_INIT(&ignores);
776 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'I':
782 if (optarg[0] == '\0')
783 break;
784 error = got_pathlist_insert(&pe, &ignores, optarg,
785 NULL);
786 if (error)
787 goto done;
788 break;
789 case 'm':
790 logmsg = strdup(optarg);
791 if (logmsg == NULL) {
792 error = got_error_from_errno("strdup");
793 goto done;
795 break;
796 case 'r':
797 repo_path = realpath(optarg, NULL);
798 if (repo_path == NULL) {
799 error = got_error_from_errno2("realpath",
800 optarg);
801 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 #ifndef PROFILE
814 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
815 "unveil",
816 NULL) == -1)
817 err(1, "pledge");
818 #endif
819 if (argc != 1)
820 usage_import();
822 if (repo_path == NULL) {
823 repo_path = getcwd(NULL, 0);
824 if (repo_path == NULL)
825 return got_error_from_errno("getcwd");
827 got_path_strip_trailing_slashes(repo_path);
828 error = get_gitconfig_path(&gitconfig_path);
829 if (error)
830 goto done;
831 error = got_repo_pack_fds_open(&pack_fds);
832 if (error != NULL)
833 goto done;
834 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
835 if (error)
836 goto done;
838 error = get_author(&author, repo, NULL);
839 if (error)
840 return error;
842 /*
843 * Don't let the user create a branch name with a leading '-'.
844 * While technically a valid reference name, this case is usually
845 * an unintended typo.
846 */
847 if (branch_name && branch_name[0] == '-')
848 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
850 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
851 if (error && error->code != GOT_ERR_NOT_REF)
852 goto done;
854 if (branch_name)
855 n = strlcat(refname, branch_name, sizeof(refname));
856 else if (head_ref && got_ref_is_symbolic(head_ref))
857 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
858 sizeof(refname));
859 else
860 n = strlcat(refname, "main", sizeof(refname));
861 if (n >= sizeof(refname)) {
862 error = got_error(GOT_ERR_NO_SPACE);
863 goto done;
866 error = got_ref_open(&branch_ref, repo, refname, 0);
867 if (error) {
868 if (error->code != GOT_ERR_NOT_REF)
869 goto done;
870 } else {
871 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
872 "import target branch already exists");
873 goto done;
876 path_dir = realpath(argv[0], NULL);
877 if (path_dir == NULL) {
878 error = got_error_from_errno2("realpath", argv[0]);
879 goto done;
881 got_path_strip_trailing_slashes(path_dir);
883 /*
884 * unveil(2) traverses exec(2); if an editor is used we have
885 * to apply unveil after the log message has been written.
886 */
887 if (logmsg == NULL || strlen(logmsg) == 0) {
888 error = get_editor(&editor);
889 if (error)
890 goto done;
891 free(logmsg);
892 error = collect_import_msg(&logmsg, &logmsg_path, editor,
893 path_dir, refname);
894 if (error) {
895 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
896 logmsg_path != NULL)
897 preserve_logmsg = 1;
898 goto done;
902 if (unveil(path_dir, "r") != 0) {
903 error = got_error_from_errno2("unveil", path_dir);
904 if (logmsg_path)
905 preserve_logmsg = 1;
906 goto done;
909 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
910 if (error) {
911 if (logmsg_path)
912 preserve_logmsg = 1;
913 goto done;
916 error = got_repo_import(&new_commit_id, path_dir, logmsg,
917 author, &ignores, repo, import_progress, NULL);
918 if (error) {
919 if (logmsg_path)
920 preserve_logmsg = 1;
921 goto done;
924 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
925 if (error) {
926 if (logmsg_path)
927 preserve_logmsg = 1;
928 goto done;
931 error = got_ref_write(branch_ref, repo);
932 if (error) {
933 if (logmsg_path)
934 preserve_logmsg = 1;
935 goto done;
938 error = got_object_id_str(&id_str, new_commit_id);
939 if (error) {
940 if (logmsg_path)
941 preserve_logmsg = 1;
942 goto done;
945 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
946 if (error) {
947 if (error->code != GOT_ERR_NOT_REF) {
948 if (logmsg_path)
949 preserve_logmsg = 1;
950 goto done;
953 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
954 branch_ref);
955 if (error) {
956 if (logmsg_path)
957 preserve_logmsg = 1;
958 goto done;
961 error = got_ref_write(head_ref, repo);
962 if (error) {
963 if (logmsg_path)
964 preserve_logmsg = 1;
965 goto done;
969 printf("Created branch %s with commit %s\n",
970 got_ref_get_name(branch_ref), id_str);
971 done:
972 if (pack_fds) {
973 const struct got_error *pack_err =
974 got_repo_pack_fds_close(pack_fds);
975 if (error == NULL)
976 error = pack_err;
978 if (preserve_logmsg) {
979 fprintf(stderr, "%s: log message preserved in %s\n",
980 getprogname(), logmsg_path);
981 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
982 error = got_error_from_errno2("unlink", logmsg_path);
983 free(logmsg);
984 free(logmsg_path);
985 free(repo_path);
986 free(editor);
987 free(new_commit_id);
988 free(id_str);
989 free(author);
990 free(gitconfig_path);
991 if (branch_ref)
992 got_ref_close(branch_ref);
993 if (head_ref)
994 got_ref_close(head_ref);
995 return error;
998 __dead static void
999 usage_clone(void)
1001 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1002 "repository-URL [directory]\n", getprogname());
1003 exit(1);
1006 struct got_fetch_progress_arg {
1007 char last_scaled_size[FMT_SCALED_STRSIZE];
1008 int last_p_indexed;
1009 int last_p_resolved;
1010 int verbosity;
1012 struct got_repository *repo;
1014 int create_configs;
1015 int configs_created;
1016 struct {
1017 struct got_pathlist_head *symrefs;
1018 struct got_pathlist_head *wanted_branches;
1019 struct got_pathlist_head *wanted_refs;
1020 const char *proto;
1021 const char *host;
1022 const char *port;
1023 const char *remote_repo_path;
1024 const char *git_url;
1025 int fetch_all_branches;
1026 int mirror_references;
1027 } config_info;
1030 /* XXX forward declaration */
1031 static const struct got_error *
1032 create_config_files(const char *proto, const char *host, const char *port,
1033 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1034 int mirror_references, struct got_pathlist_head *symrefs,
1035 struct got_pathlist_head *wanted_branches,
1036 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1038 static const struct got_error *
1039 fetch_progress(void *arg, const char *message, off_t packfile_size,
1040 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1042 const struct got_error *err = NULL;
1043 struct got_fetch_progress_arg *a = arg;
1044 char scaled_size[FMT_SCALED_STRSIZE];
1045 int p_indexed, p_resolved;
1046 int print_size = 0, print_indexed = 0, print_resolved = 0;
1049 * In order to allow a failed clone to be resumed with 'got fetch'
1050 * we try to create configuration files as soon as possible.
1051 * Once the server has sent information about its default branch
1052 * we have all required information.
1054 if (a->create_configs && !a->configs_created &&
1055 !TAILQ_EMPTY(a->config_info.symrefs)) {
1056 err = create_config_files(a->config_info.proto,
1057 a->config_info.host, a->config_info.port,
1058 a->config_info.remote_repo_path,
1059 a->config_info.git_url,
1060 a->config_info.fetch_all_branches,
1061 a->config_info.mirror_references,
1062 a->config_info.symrefs,
1063 a->config_info.wanted_branches,
1064 a->config_info.wanted_refs, a->repo);
1065 if (err)
1066 return err;
1067 a->configs_created = 1;
1070 if (a->verbosity < 0)
1071 return NULL;
1073 if (message && message[0] != '\0') {
1074 printf("\rserver: %s", message);
1075 fflush(stdout);
1076 return NULL;
1079 if (packfile_size > 0 || nobj_indexed > 0) {
1080 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1081 (a->last_scaled_size[0] == '\0' ||
1082 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1083 print_size = 1;
1084 if (strlcpy(a->last_scaled_size, scaled_size,
1085 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1086 return got_error(GOT_ERR_NO_SPACE);
1088 if (nobj_indexed > 0) {
1089 p_indexed = (nobj_indexed * 100) / nobj_total;
1090 if (p_indexed != a->last_p_indexed) {
1091 a->last_p_indexed = p_indexed;
1092 print_indexed = 1;
1093 print_size = 1;
1096 if (nobj_resolved > 0) {
1097 p_resolved = (nobj_resolved * 100) /
1098 (nobj_total - nobj_loose);
1099 if (p_resolved != a->last_p_resolved) {
1100 a->last_p_resolved = p_resolved;
1101 print_resolved = 1;
1102 print_indexed = 1;
1103 print_size = 1;
1108 if (print_size || print_indexed || print_resolved)
1109 printf("\r");
1110 if (print_size)
1111 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1112 if (print_indexed)
1113 printf("; indexing %d%%", p_indexed);
1114 if (print_resolved)
1115 printf("; resolving deltas %d%%", p_resolved);
1116 if (print_size || print_indexed || print_resolved)
1117 fflush(stdout);
1119 return NULL;
1122 static const struct got_error *
1123 create_symref(const char *refname, struct got_reference *target_ref,
1124 int verbosity, struct got_repository *repo)
1126 const struct got_error *err;
1127 struct got_reference *head_symref;
1129 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1130 if (err)
1131 return err;
1133 err = got_ref_write(head_symref, repo);
1134 if (err == NULL && verbosity > 0) {
1135 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1136 got_ref_get_name(target_ref));
1138 got_ref_close(head_symref);
1139 return err;
1142 static const struct got_error *
1143 list_remote_refs(struct got_pathlist_head *symrefs,
1144 struct got_pathlist_head *refs)
1146 const struct got_error *err;
1147 struct got_pathlist_entry *pe;
1149 TAILQ_FOREACH(pe, symrefs, entry) {
1150 const char *refname = pe->path;
1151 const char *targetref = pe->data;
1153 printf("%s: %s\n", refname, targetref);
1156 TAILQ_FOREACH(pe, refs, entry) {
1157 const char *refname = pe->path;
1158 struct got_object_id *id = pe->data;
1159 char *id_str;
1161 err = got_object_id_str(&id_str, id);
1162 if (err)
1163 return err;
1164 printf("%s: %s\n", refname, id_str);
1165 free(id_str);
1168 return NULL;
1171 static const struct got_error *
1172 create_ref(const char *refname, struct got_object_id *id,
1173 int verbosity, struct got_repository *repo)
1175 const struct got_error *err = NULL;
1176 struct got_reference *ref;
1177 char *id_str;
1179 err = got_object_id_str(&id_str, id);
1180 if (err)
1181 return err;
1183 err = got_ref_alloc(&ref, refname, id);
1184 if (err)
1185 goto done;
1187 err = got_ref_write(ref, repo);
1188 got_ref_close(ref);
1190 if (err == NULL && verbosity >= 0)
1191 printf("Created reference %s: %s\n", refname, id_str);
1192 done:
1193 free(id_str);
1194 return err;
1197 static int
1198 match_wanted_ref(const char *refname, const char *wanted_ref)
1200 if (strncmp(refname, "refs/", 5) != 0)
1201 return 0;
1202 refname += 5;
1205 * Prevent fetching of references that won't make any
1206 * sense outside of the remote repository's context.
1208 if (strncmp(refname, "got/", 4) == 0)
1209 return 0;
1210 if (strncmp(refname, "remotes/", 8) == 0)
1211 return 0;
1213 if (strncmp(wanted_ref, "refs/", 5) == 0)
1214 wanted_ref += 5;
1216 /* Allow prefix match. */
1217 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1218 return 1;
1220 /* Allow exact match. */
1221 return (strcmp(refname, wanted_ref) == 0);
1224 static int
1225 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1227 struct got_pathlist_entry *pe;
1229 TAILQ_FOREACH(pe, wanted_refs, entry) {
1230 if (match_wanted_ref(refname, pe->path))
1231 return 1;
1234 return 0;
1237 static const struct got_error *
1238 create_wanted_ref(const char *refname, struct got_object_id *id,
1239 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1241 const struct got_error *err;
1242 char *remote_refname;
1244 if (strncmp("refs/", refname, 5) == 0)
1245 refname += 5;
1247 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1248 remote_repo_name, refname) == -1)
1249 return got_error_from_errno("asprintf");
1251 err = create_ref(remote_refname, id, verbosity, repo);
1252 free(remote_refname);
1253 return err;
1256 static const struct got_error *
1257 create_gotconfig(const char *proto, const char *host, const char *port,
1258 const char *remote_repo_path, const char *default_branch,
1259 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1260 struct got_pathlist_head *wanted_refs, int mirror_references,
1261 struct got_repository *repo)
1263 const struct got_error *err = NULL;
1264 char *gotconfig_path = NULL;
1265 char *gotconfig = NULL;
1266 FILE *gotconfig_file = NULL;
1267 const char *branchname = NULL;
1268 char *branches = NULL, *refs = NULL;
1269 ssize_t n;
1271 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1272 struct got_pathlist_entry *pe;
1273 TAILQ_FOREACH(pe, wanted_branches, entry) {
1274 char *s;
1275 branchname = pe->path;
1276 if (strncmp(branchname, "refs/heads/", 11) == 0)
1277 branchname += 11;
1278 if (asprintf(&s, "%s\"%s\" ",
1279 branches ? branches : "", branchname) == -1) {
1280 err = got_error_from_errno("asprintf");
1281 goto done;
1283 free(branches);
1284 branches = s;
1286 } else if (!fetch_all_branches && default_branch) {
1287 branchname = default_branch;
1288 if (strncmp(branchname, "refs/heads/", 11) == 0)
1289 branchname += 11;
1290 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1291 err = got_error_from_errno("asprintf");
1292 goto done;
1295 if (!TAILQ_EMPTY(wanted_refs)) {
1296 struct got_pathlist_entry *pe;
1297 TAILQ_FOREACH(pe, wanted_refs, entry) {
1298 char *s;
1299 const char *refname = pe->path;
1300 if (strncmp(refname, "refs/", 5) == 0)
1301 branchname += 5;
1302 if (asprintf(&s, "%s\"%s\" ",
1303 refs ? refs : "", refname) == -1) {
1304 err = got_error_from_errno("asprintf");
1305 goto done;
1307 free(refs);
1308 refs = s;
1312 /* Create got.conf(5). */
1313 gotconfig_path = got_repo_get_path_gotconfig(repo);
1314 if (gotconfig_path == NULL) {
1315 err = got_error_from_errno("got_repo_get_path_gotconfig");
1316 goto done;
1318 gotconfig_file = fopen(gotconfig_path, "ae");
1319 if (gotconfig_file == NULL) {
1320 err = got_error_from_errno2("fopen", gotconfig_path);
1321 goto done;
1323 if (asprintf(&gotconfig,
1324 "remote \"%s\" {\n"
1325 "\tserver %s\n"
1326 "\tprotocol %s\n"
1327 "%s%s%s"
1328 "\trepository \"%s\"\n"
1329 "%s%s%s"
1330 "%s%s%s"
1331 "%s"
1332 "%s"
1333 "}\n",
1334 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1335 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1336 remote_repo_path, branches ? "\tbranch { " : "",
1337 branches ? branches : "", branches ? "}\n" : "",
1338 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1339 mirror_references ? "\tmirror_references yes\n" : "",
1340 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1345 if (n != strlen(gotconfig)) {
1346 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1347 goto done;
1350 done:
1351 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1352 err = got_error_from_errno2("fclose", gotconfig_path);
1353 free(gotconfig_path);
1354 free(branches);
1355 return err;
1358 static const struct got_error *
1359 create_gitconfig(const char *git_url, const char *default_branch,
1360 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1361 struct got_pathlist_head *wanted_refs, int mirror_references,
1362 struct got_repository *repo)
1364 const struct got_error *err = NULL;
1365 char *gitconfig_path = NULL;
1366 char *gitconfig = NULL;
1367 FILE *gitconfig_file = NULL;
1368 char *branches = NULL, *refs = NULL;
1369 const char *branchname;
1370 ssize_t n;
1372 /* Create a config file Git can understand. */
1373 gitconfig_path = got_repo_get_path_gitconfig(repo);
1374 if (gitconfig_path == NULL) {
1375 err = got_error_from_errno("got_repo_get_path_gitconfig");
1376 goto done;
1378 gitconfig_file = fopen(gitconfig_path, "ae");
1379 if (gitconfig_file == NULL) {
1380 err = got_error_from_errno2("fopen", gitconfig_path);
1381 goto done;
1383 if (fetch_all_branches) {
1384 if (mirror_references) {
1385 if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1387 err = got_error_from_errno("asprintf");
1388 goto done;
1390 } else if (asprintf(&branches,
1391 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1392 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 } else if (!TAILQ_EMPTY(wanted_branches)) {
1397 struct got_pathlist_entry *pe;
1398 TAILQ_FOREACH(pe, wanted_branches, entry) {
1399 char *s;
1400 branchname = pe->path;
1401 if (strncmp(branchname, "refs/heads/", 11) == 0)
1402 branchname += 11;
1403 if (mirror_references) {
1404 if (asprintf(&s,
1405 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1406 branches ? branches : "",
1407 branchname, branchname) == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 } else if (asprintf(&s,
1412 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1413 branches ? branches : "",
1414 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1415 branchname) == -1) {
1416 err = got_error_from_errno("asprintf");
1417 goto done;
1419 free(branches);
1420 branches = s;
1422 } else {
1424 * If the server specified a default branch, use just that one.
1425 * Otherwise fall back to fetching all branches on next fetch.
1427 if (default_branch) {
1428 branchname = default_branch;
1429 if (strncmp(branchname, "refs/heads/", 11) == 0)
1430 branchname += 11;
1431 } else
1432 branchname = "*"; /* fall back to all branches */
1433 if (mirror_references) {
1434 if (asprintf(&branches,
1435 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1436 branchname, branchname) == -1) {
1437 err = got_error_from_errno("asprintf");
1438 goto done;
1440 } else if (asprintf(&branches,
1441 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1442 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1443 branchname) == -1) {
1444 err = got_error_from_errno("asprintf");
1445 goto done;
1448 if (!TAILQ_EMPTY(wanted_refs)) {
1449 struct got_pathlist_entry *pe;
1450 TAILQ_FOREACH(pe, wanted_refs, entry) {
1451 char *s;
1452 const char *refname = pe->path;
1453 if (strncmp(refname, "refs/", 5) == 0)
1454 refname += 5;
1455 if (mirror_references) {
1456 if (asprintf(&s,
1457 "%s\tfetch = refs/%s:refs/%s\n",
1458 refs ? refs : "", refname, refname) == -1) {
1459 err = got_error_from_errno("asprintf");
1460 goto done;
1462 } else if (asprintf(&s,
1463 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1464 refs ? refs : "",
1465 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1466 refname) == -1) {
1467 err = got_error_from_errno("asprintf");
1468 goto done;
1470 free(refs);
1471 refs = s;
1475 if (asprintf(&gitconfig,
1476 "[remote \"%s\"]\n"
1477 "\turl = %s\n"
1478 "%s"
1479 "%s"
1480 "\tfetch = refs/tags/*:refs/tags/*\n",
1481 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1482 refs ? refs : "") == -1) {
1483 err = got_error_from_errno("asprintf");
1484 goto done;
1486 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1487 if (n != strlen(gitconfig)) {
1488 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1489 goto done;
1491 done:
1492 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1493 err = got_error_from_errno2("fclose", gitconfig_path);
1494 free(gitconfig_path);
1495 free(branches);
1496 return err;
1499 static const struct got_error *
1500 create_config_files(const char *proto, const char *host, const char *port,
1501 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1502 int mirror_references, struct got_pathlist_head *symrefs,
1503 struct got_pathlist_head *wanted_branches,
1504 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1506 const struct got_error *err = NULL;
1507 const char *default_branch = NULL;
1508 struct got_pathlist_entry *pe;
1511 * If we asked for a set of wanted branches then use the first
1512 * one of those.
1514 if (!TAILQ_EMPTY(wanted_branches)) {
1515 pe = TAILQ_FIRST(wanted_branches);
1516 default_branch = pe->path;
1517 } else {
1518 /* First HEAD ref listed by server is the default branch. */
1519 TAILQ_FOREACH(pe, symrefs, entry) {
1520 const char *refname = pe->path;
1521 const char *target = pe->data;
1523 if (strcmp(refname, GOT_REF_HEAD) != 0)
1524 continue;
1526 default_branch = target;
1527 break;
1531 /* Create got.conf(5). */
1532 err = create_gotconfig(proto, host, port, remote_repo_path,
1533 default_branch, fetch_all_branches, wanted_branches,
1534 wanted_refs, mirror_references, repo);
1535 if (err)
1536 return err;
1538 /* Create a config file Git can understand. */
1539 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1540 wanted_branches, wanted_refs, mirror_references, repo);
1543 static const struct got_error *
1544 cmd_clone(int argc, char *argv[])
1546 const struct got_error *error = NULL;
1547 const char *uri, *dirname;
1548 char *proto, *host, *port, *repo_name, *server_path;
1549 char *default_destdir = NULL, *id_str = NULL;
1550 const char *repo_path;
1551 struct got_repository *repo = NULL;
1552 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1553 struct got_pathlist_entry *pe;
1554 struct got_object_id *pack_hash = NULL;
1555 int ch, fetchfd = -1, fetchstatus;
1556 pid_t fetchpid = -1;
1557 struct got_fetch_progress_arg fpa;
1558 char *git_url = NULL;
1559 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1560 int list_refs_only = 0;
1561 int *pack_fds = NULL;
1563 TAILQ_INIT(&refs);
1564 TAILQ_INIT(&symrefs);
1565 TAILQ_INIT(&wanted_branches);
1566 TAILQ_INIT(&wanted_refs);
1568 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1569 switch (ch) {
1570 case 'a':
1571 fetch_all_branches = 1;
1572 break;
1573 case 'b':
1574 error = got_pathlist_append(&wanted_branches,
1575 optarg, NULL);
1576 if (error)
1577 return error;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s%s%s\n", host,
1695 port ? ":" : "", port ? port : "");
1697 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1698 server_path, verbosity);
1699 if (error)
1700 goto done;
1702 if (!list_refs_only) {
1703 error = got_repo_init(repo_path, NULL);
1704 if (error)
1705 goto done;
1706 error = got_repo_pack_fds_open(&pack_fds);
1707 if (error != NULL)
1708 goto done;
1709 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1710 if (error)
1711 goto done;
1714 fpa.last_scaled_size[0] = '\0';
1715 fpa.last_p_indexed = -1;
1716 fpa.last_p_resolved = -1;
1717 fpa.verbosity = verbosity;
1718 fpa.create_configs = 1;
1719 fpa.configs_created = 0;
1720 fpa.repo = repo;
1721 fpa.config_info.symrefs = &symrefs;
1722 fpa.config_info.wanted_branches = &wanted_branches;
1723 fpa.config_info.wanted_refs = &wanted_refs;
1724 fpa.config_info.proto = proto;
1725 fpa.config_info.host = host;
1726 fpa.config_info.port = port;
1727 fpa.config_info.remote_repo_path = server_path;
1728 fpa.config_info.git_url = git_url;
1729 fpa.config_info.fetch_all_branches = fetch_all_branches;
1730 fpa.config_info.mirror_references = mirror_references;
1731 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1732 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1733 fetch_all_branches, &wanted_branches, &wanted_refs,
1734 list_refs_only, verbosity, fetchfd, repo,
1735 fetch_progress, &fpa);
1736 if (error)
1737 goto done;
1739 if (list_refs_only) {
1740 error = list_remote_refs(&symrefs, &refs);
1741 goto done;
1744 if (pack_hash == NULL) {
1745 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1746 "server sent an empty pack file");
1747 goto done;
1749 error = got_object_id_str(&id_str, pack_hash);
1750 if (error)
1751 goto done;
1752 if (verbosity >= 0)
1753 printf("\nFetched %s.pack\n", id_str);
1754 free(id_str);
1756 /* Set up references provided with the pack file. */
1757 TAILQ_FOREACH(pe, &refs, entry) {
1758 const char *refname = pe->path;
1759 struct got_object_id *id = pe->data;
1760 char *remote_refname;
1762 if (is_wanted_ref(&wanted_refs, refname) &&
1763 !mirror_references) {
1764 error = create_wanted_ref(refname, id,
1765 GOT_FETCH_DEFAULT_REMOTE_NAME,
1766 verbosity - 1, repo);
1767 if (error)
1768 goto done;
1769 continue;
1772 error = create_ref(refname, id, verbosity - 1, repo);
1773 if (error)
1774 goto done;
1776 if (mirror_references)
1777 continue;
1779 if (strncmp("refs/heads/", refname, 11) != 0)
1780 continue;
1782 if (asprintf(&remote_refname,
1783 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1784 refname + 11) == -1) {
1785 error = got_error_from_errno("asprintf");
1786 goto done;
1788 error = create_ref(remote_refname, id, verbosity - 1, repo);
1789 free(remote_refname);
1790 if (error)
1791 goto done;
1794 /* Set the HEAD reference if the server provided one. */
1795 TAILQ_FOREACH(pe, &symrefs, entry) {
1796 struct got_reference *target_ref;
1797 const char *refname = pe->path;
1798 const char *target = pe->data;
1799 char *remote_refname = NULL, *remote_target = NULL;
1801 if (strcmp(refname, GOT_REF_HEAD) != 0)
1802 continue;
1804 error = got_ref_open(&target_ref, repo, target, 0);
1805 if (error) {
1806 if (error->code == GOT_ERR_NOT_REF) {
1807 error = NULL;
1808 continue;
1810 goto done;
1813 error = create_symref(refname, target_ref, verbosity, repo);
1814 got_ref_close(target_ref);
1815 if (error)
1816 goto done;
1818 if (mirror_references)
1819 continue;
1821 if (strncmp("refs/heads/", target, 11) != 0)
1822 continue;
1824 if (asprintf(&remote_refname,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 refname) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 goto done;
1830 if (asprintf(&remote_target,
1831 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1832 target + 11) == -1) {
1833 error = got_error_from_errno("asprintf");
1834 free(remote_refname);
1835 goto done;
1837 error = got_ref_open(&target_ref, repo, remote_target, 0);
1838 if (error) {
1839 free(remote_refname);
1840 free(remote_target);
1841 if (error->code == GOT_ERR_NOT_REF) {
1842 error = NULL;
1843 continue;
1845 goto done;
1847 error = create_symref(remote_refname, target_ref,
1848 verbosity - 1, repo);
1849 free(remote_refname);
1850 free(remote_target);
1851 got_ref_close(target_ref);
1852 if (error)
1853 goto done;
1855 if (pe == NULL) {
1857 * We failed to set the HEAD reference. If we asked for
1858 * a set of wanted branches use the first of one of those
1859 * which could be fetched instead.
1861 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1862 const char *target = pe->path;
1863 struct got_reference *target_ref;
1865 error = got_ref_open(&target_ref, repo, target, 0);
1866 if (error) {
1867 if (error->code == GOT_ERR_NOT_REF) {
1868 error = NULL;
1869 continue;
1871 goto done;
1874 error = create_symref(GOT_REF_HEAD, target_ref,
1875 verbosity, repo);
1876 got_ref_close(target_ref);
1877 if (error)
1878 goto done;
1879 break;
1883 if (verbosity >= 0)
1884 printf("Created %s repository '%s'\n",
1885 mirror_references ? "mirrored" : "cloned", repo_path);
1886 done:
1887 if (pack_fds) {
1888 const struct got_error *pack_err =
1889 got_repo_pack_fds_close(pack_fds);
1890 if (error == NULL)
1891 error = pack_err;
1893 if (fetchpid > 0) {
1894 if (kill(fetchpid, SIGTERM) == -1)
1895 error = got_error_from_errno("kill");
1896 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1897 error = got_error_from_errno("waitpid");
1899 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1900 error = got_error_from_errno("close");
1901 if (repo) {
1902 const struct got_error *close_err = got_repo_close(repo);
1903 if (error == NULL)
1904 error = close_err;
1906 TAILQ_FOREACH(pe, &refs, entry) {
1907 free((void *)pe->path);
1908 free(pe->data);
1910 got_pathlist_free(&refs);
1911 TAILQ_FOREACH(pe, &symrefs, entry) {
1912 free((void *)pe->path);
1913 free(pe->data);
1915 got_pathlist_free(&symrefs);
1916 got_pathlist_free(&wanted_branches);
1917 got_pathlist_free(&wanted_refs);
1918 free(pack_hash);
1919 free(proto);
1920 free(host);
1921 free(port);
1922 free(server_path);
1923 free(repo_name);
1924 free(default_destdir);
1925 free(git_url);
1926 return error;
1929 static const struct got_error *
1930 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1931 int replace_tags, int verbosity, struct got_repository *repo)
1933 const struct got_error *err = NULL;
1934 char *new_id_str = NULL;
1935 struct got_object_id *old_id = NULL;
1937 err = got_object_id_str(&new_id_str, new_id);
1938 if (err)
1939 goto done;
1941 if (!replace_tags &&
1942 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1943 err = got_ref_resolve(&old_id, repo, ref);
1944 if (err)
1945 goto done;
1946 if (got_object_id_cmp(old_id, new_id) == 0)
1947 goto done;
1948 if (verbosity >= 0) {
1949 printf("Rejecting update of existing tag %s: %s\n",
1950 got_ref_get_name(ref), new_id_str);
1952 goto done;
1955 if (got_ref_is_symbolic(ref)) {
1956 if (verbosity >= 0) {
1957 printf("Replacing reference %s: %s\n",
1958 got_ref_get_name(ref),
1959 got_ref_get_symref_target(ref));
1961 err = got_ref_change_symref_to_ref(ref, new_id);
1962 if (err)
1963 goto done;
1964 err = got_ref_write(ref, repo);
1965 if (err)
1966 goto done;
1967 } else {
1968 err = got_ref_resolve(&old_id, repo, ref);
1969 if (err)
1970 goto done;
1971 if (got_object_id_cmp(old_id, new_id) == 0)
1972 goto done;
1974 err = got_ref_change_ref(ref, new_id);
1975 if (err)
1976 goto done;
1977 err = got_ref_write(ref, repo);
1978 if (err)
1979 goto done;
1982 if (verbosity >= 0)
1983 printf("Updated %s: %s\n", got_ref_get_name(ref),
1984 new_id_str);
1985 done:
1986 free(old_id);
1987 free(new_id_str);
1988 return err;
1991 static const struct got_error *
1992 update_symref(const char *refname, struct got_reference *target_ref,
1993 int verbosity, struct got_repository *repo)
1995 const struct got_error *err = NULL, *unlock_err;
1996 struct got_reference *symref;
1997 int symref_is_locked = 0;
1999 err = got_ref_open(&symref, repo, refname, 1);
2000 if (err) {
2001 if (err->code != GOT_ERR_NOT_REF)
2002 return err;
2003 err = got_ref_alloc_symref(&symref, refname, target_ref);
2004 if (err)
2005 goto done;
2007 err = got_ref_write(symref, repo);
2008 if (err)
2009 goto done;
2011 if (verbosity >= 0)
2012 printf("Created reference %s: %s\n",
2013 got_ref_get_name(symref),
2014 got_ref_get_symref_target(symref));
2015 } else {
2016 symref_is_locked = 1;
2018 if (strcmp(got_ref_get_symref_target(symref),
2019 got_ref_get_name(target_ref)) == 0)
2020 goto done;
2022 err = got_ref_change_symref(symref,
2023 got_ref_get_name(target_ref));
2024 if (err)
2025 goto done;
2027 err = got_ref_write(symref, repo);
2028 if (err)
2029 goto done;
2031 if (verbosity >= 0)
2032 printf("Updated %s: %s\n", got_ref_get_name(symref),
2033 got_ref_get_symref_target(symref));
2036 done:
2037 if (symref_is_locked) {
2038 unlock_err = got_ref_unlock(symref);
2039 if (unlock_err && err == NULL)
2040 err = unlock_err;
2042 got_ref_close(symref);
2043 return err;
2046 __dead static void
2047 usage_fetch(void)
2049 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2050 "[-R reference] [-r repository-path] [remote-repository]\n",
2051 getprogname());
2052 exit(1);
2055 static const struct got_error *
2056 delete_missing_ref(struct got_reference *ref,
2057 int verbosity, struct got_repository *repo)
2059 const struct got_error *err = NULL;
2060 struct got_object_id *id = NULL;
2061 char *id_str = NULL;
2063 if (got_ref_is_symbolic(ref)) {
2064 err = got_ref_delete(ref, repo);
2065 if (err)
2066 return err;
2067 if (verbosity >= 0) {
2068 printf("Deleted %s: %s\n",
2069 got_ref_get_name(ref),
2070 got_ref_get_symref_target(ref));
2072 } else {
2073 err = got_ref_resolve(&id, repo, ref);
2074 if (err)
2075 return err;
2076 err = got_object_id_str(&id_str, id);
2077 if (err)
2078 goto done;
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 goto done;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref), id_str);
2088 done:
2089 free(id);
2090 free(id_str);
2091 return NULL;
2094 static const struct got_error *
2095 delete_missing_refs(struct got_pathlist_head *their_refs,
2096 struct got_pathlist_head *their_symrefs,
2097 const struct got_remote_repo *remote,
2098 int verbosity, struct got_repository *repo)
2100 const struct got_error *err = NULL, *unlock_err;
2101 struct got_reflist_head my_refs;
2102 struct got_reflist_entry *re;
2103 struct got_pathlist_entry *pe;
2104 char *remote_namespace = NULL;
2105 char *local_refname = NULL;
2107 TAILQ_INIT(&my_refs);
2109 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2110 == -1)
2111 return got_error_from_errno("asprintf");
2113 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2114 if (err)
2115 goto done;
2117 TAILQ_FOREACH(re, &my_refs, entry) {
2118 const char *refname = got_ref_get_name(re->ref);
2119 const char *their_refname;
2121 if (remote->mirror_references) {
2122 their_refname = refname;
2123 } else {
2124 if (strncmp(refname, remote_namespace,
2125 strlen(remote_namespace)) == 0) {
2126 if (strcmp(refname + strlen(remote_namespace),
2127 GOT_REF_HEAD) == 0)
2128 continue;
2129 if (asprintf(&local_refname, "refs/heads/%s",
2130 refname + strlen(remote_namespace)) == -1) {
2131 err = got_error_from_errno("asprintf");
2132 goto done;
2134 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2135 continue;
2137 their_refname = local_refname;
2140 TAILQ_FOREACH(pe, their_refs, entry) {
2141 if (strcmp(their_refname, pe->path) == 0)
2142 break;
2144 if (pe != NULL)
2145 continue;
2147 TAILQ_FOREACH(pe, their_symrefs, entry) {
2148 if (strcmp(their_refname, pe->path) == 0)
2149 break;
2151 if (pe != NULL)
2152 continue;
2154 err = delete_missing_ref(re->ref, verbosity, repo);
2155 if (err)
2156 break;
2158 if (local_refname) {
2159 struct got_reference *ref;
2160 err = got_ref_open(&ref, repo, local_refname, 1);
2161 if (err) {
2162 if (err->code != GOT_ERR_NOT_REF)
2163 break;
2164 free(local_refname);
2165 local_refname = NULL;
2166 continue;
2168 err = delete_missing_ref(ref, verbosity, repo);
2169 if (err)
2170 break;
2171 unlock_err = got_ref_unlock(ref);
2172 got_ref_close(ref);
2173 if (unlock_err && err == NULL) {
2174 err = unlock_err;
2175 break;
2178 free(local_refname);
2179 local_refname = NULL;
2182 done:
2183 got_ref_list_free(&my_refs);
2184 free(remote_namespace);
2185 free(local_refname);
2186 return err;
2189 static const struct got_error *
2190 update_wanted_ref(const char *refname, struct got_object_id *id,
2191 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2193 const struct got_error *err, *unlock_err;
2194 char *remote_refname;
2195 struct got_reference *ref;
2197 if (strncmp("refs/", refname, 5) == 0)
2198 refname += 5;
2200 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2201 remote_repo_name, refname) == -1)
2202 return got_error_from_errno("asprintf");
2204 err = got_ref_open(&ref, repo, remote_refname, 1);
2205 if (err) {
2206 if (err->code != GOT_ERR_NOT_REF)
2207 goto done;
2208 err = create_ref(remote_refname, id, verbosity, repo);
2209 } else {
2210 err = update_ref(ref, id, 0, verbosity, repo);
2211 unlock_err = got_ref_unlock(ref);
2212 if (unlock_err && err == NULL)
2213 err = unlock_err;
2214 got_ref_close(ref);
2216 done:
2217 free(remote_refname);
2218 return err;
2221 static const struct got_error *
2222 delete_ref(struct got_repository *repo, struct got_reference *ref)
2224 const struct got_error *err = NULL;
2225 struct got_object_id *id = NULL;
2226 char *id_str = NULL;
2227 const char *target;
2229 if (got_ref_is_symbolic(ref)) {
2230 target = got_ref_get_symref_target(ref);
2231 } else {
2232 err = got_ref_resolve(&id, repo, ref);
2233 if (err)
2234 goto done;
2235 err = got_object_id_str(&id_str, id);
2236 if (err)
2237 goto done;
2238 target = id_str;
2241 err = got_ref_delete(ref, repo);
2242 if (err)
2243 goto done;
2245 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2246 done:
2247 free(id);
2248 free(id_str);
2249 return err;
2252 static const struct got_error *
2253 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2255 const struct got_error *err = NULL;
2256 struct got_reflist_head refs;
2257 struct got_reflist_entry *re;
2258 char *prefix;
2260 TAILQ_INIT(&refs);
2262 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2263 err = got_error_from_errno("asprintf");
2264 goto done;
2266 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2267 if (err)
2268 goto done;
2270 TAILQ_FOREACH(re, &refs, entry)
2271 delete_ref(repo, re->ref);
2272 done:
2273 got_ref_list_free(&refs);
2274 return err;
2277 static const struct got_error *
2278 cmd_fetch(int argc, char *argv[])
2280 const struct got_error *error = NULL, *unlock_err;
2281 char *cwd = NULL, *repo_path = NULL;
2282 const char *remote_name;
2283 char *proto = NULL, *host = NULL, *port = NULL;
2284 char *repo_name = NULL, *server_path = NULL;
2285 const struct got_remote_repo *remotes, *remote = NULL;
2286 int nremotes;
2287 char *id_str = NULL;
2288 struct got_repository *repo = NULL;
2289 struct got_worktree *worktree = NULL;
2290 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2291 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2292 struct got_pathlist_entry *pe;
2293 struct got_object_id *pack_hash = NULL;
2294 int i, ch, fetchfd = -1, fetchstatus;
2295 pid_t fetchpid = -1;
2296 struct got_fetch_progress_arg fpa;
2297 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2298 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2299 int *pack_fds = NULL;
2301 TAILQ_INIT(&refs);
2302 TAILQ_INIT(&symrefs);
2303 TAILQ_INIT(&wanted_branches);
2304 TAILQ_INIT(&wanted_refs);
2306 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2307 switch (ch) {
2308 case 'a':
2309 fetch_all_branches = 1;
2310 break;
2311 case 'b':
2312 error = got_pathlist_append(&wanted_branches,
2313 optarg, NULL);
2314 if (error)
2315 return error;
2316 break;
2317 case 'd':
2318 delete_refs = 1;
2319 break;
2320 case 'l':
2321 list_refs_only = 1;
2322 break;
2323 case 'q':
2324 verbosity = -1;
2325 break;
2326 case 'R':
2327 error = got_pathlist_append(&wanted_refs,
2328 optarg, NULL);
2329 if (error)
2330 return error;
2331 break;
2332 case 'r':
2333 repo_path = realpath(optarg, NULL);
2334 if (repo_path == NULL)
2335 return got_error_from_errno2("realpath",
2336 optarg);
2337 got_path_strip_trailing_slashes(repo_path);
2338 break;
2339 case 't':
2340 replace_tags = 1;
2341 break;
2342 case 'v':
2343 if (verbosity < 0)
2344 verbosity = 0;
2345 else if (verbosity < 3)
2346 verbosity++;
2347 break;
2348 case 'X':
2349 delete_remote = 1;
2350 break;
2351 default:
2352 usage_fetch();
2353 break;
2356 argc -= optind;
2357 argv += optind;
2359 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2360 option_conflict('a', 'b');
2361 if (list_refs_only) {
2362 if (!TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('l', 'b');
2364 if (fetch_all_branches)
2365 option_conflict('l', 'a');
2366 if (delete_refs)
2367 option_conflict('l', 'd');
2368 if (delete_remote)
2369 option_conflict('l', 'X');
2371 if (delete_remote) {
2372 if (fetch_all_branches)
2373 option_conflict('X', 'a');
2374 if (!TAILQ_EMPTY(&wanted_branches))
2375 option_conflict('X', 'b');
2376 if (delete_refs)
2377 option_conflict('X', 'd');
2378 if (replace_tags)
2379 option_conflict('X', 't');
2380 if (!TAILQ_EMPTY(&wanted_refs))
2381 option_conflict('X', 'R');
2384 if (argc == 0) {
2385 if (delete_remote)
2386 errx(1, "-X option requires a remote name");
2387 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2388 } else if (argc == 1)
2389 remote_name = argv[0];
2390 else
2391 usage_fetch();
2393 cwd = getcwd(NULL, 0);
2394 if (cwd == NULL) {
2395 error = got_error_from_errno("getcwd");
2396 goto done;
2399 error = got_repo_pack_fds_open(&pack_fds);
2400 if (error != NULL)
2401 goto done;
2403 if (repo_path == NULL) {
2404 error = got_worktree_open(&worktree, cwd);
2405 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2406 goto done;
2407 else
2408 error = NULL;
2409 if (worktree) {
2410 repo_path =
2411 strdup(got_worktree_get_repo_path(worktree));
2412 if (repo_path == NULL)
2413 error = got_error_from_errno("strdup");
2414 if (error)
2415 goto done;
2416 } else {
2417 repo_path = strdup(cwd);
2418 if (repo_path == NULL) {
2419 error = got_error_from_errno("strdup");
2420 goto done;
2425 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2426 if (error)
2427 goto done;
2429 if (delete_remote) {
2430 error = delete_refs_for_remote(repo, remote_name);
2431 goto done; /* nothing else to do */
2434 if (worktree) {
2435 worktree_conf = got_worktree_get_gotconfig(worktree);
2436 if (worktree_conf) {
2437 got_gotconfig_get_remotes(&nremotes, &remotes,
2438 worktree_conf);
2439 for (i = 0; i < nremotes; i++) {
2440 if (strcmp(remotes[i].name, remote_name) == 0) {
2441 remote = &remotes[i];
2442 break;
2447 if (remote == NULL) {
2448 repo_conf = got_repo_get_gotconfig(repo);
2449 if (repo_conf) {
2450 got_gotconfig_get_remotes(&nremotes, &remotes,
2451 repo_conf);
2452 for (i = 0; i < nremotes; i++) {
2453 if (strcmp(remotes[i].name, remote_name) == 0) {
2454 remote = &remotes[i];
2455 break;
2460 if (remote == NULL) {
2461 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2469 if (remote == NULL) {
2470 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2471 goto done;
2474 if (TAILQ_EMPTY(&wanted_branches)) {
2475 if (!fetch_all_branches)
2476 fetch_all_branches = remote->fetch_all_branches;
2477 for (i = 0; i < remote->nfetch_branches; i++) {
2478 got_pathlist_append(&wanted_branches,
2479 remote->fetch_branches[i], NULL);
2482 if (TAILQ_EMPTY(&wanted_refs)) {
2483 for (i = 0; i < remote->nfetch_refs; i++) {
2484 got_pathlist_append(&wanted_refs,
2485 remote->fetch_refs[i], NULL);
2489 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2490 &repo_name, remote->fetch_url);
2491 if (error)
2492 goto done;
2494 if (strcmp(proto, "git") == 0) {
2495 #ifndef PROFILE
2496 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2497 "sendfd dns inet unveil", NULL) == -1)
2498 err(1, "pledge");
2499 #endif
2500 } else if (strcmp(proto, "git+ssh") == 0 ||
2501 strcmp(proto, "ssh") == 0) {
2502 #ifndef PROFILE
2503 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2504 "sendfd unveil", NULL) == -1)
2505 err(1, "pledge");
2506 #endif
2507 } else if (strcmp(proto, "http") == 0 ||
2508 strcmp(proto, "git+http") == 0) {
2509 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2510 goto done;
2511 } else {
2512 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2513 goto done;
2516 error = got_dial_apply_unveil(proto);
2517 if (error)
2518 goto done;
2520 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2521 if (error)
2522 goto done;
2524 if (verbosity >= 0)
2525 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2526 port ? ":" : "", port ? port : "");
2528 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2529 server_path, verbosity);
2530 if (error)
2531 goto done;
2533 fpa.last_scaled_size[0] = '\0';
2534 fpa.last_p_indexed = -1;
2535 fpa.last_p_resolved = -1;
2536 fpa.verbosity = verbosity;
2537 fpa.repo = repo;
2538 fpa.create_configs = 0;
2539 fpa.configs_created = 0;
2540 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2541 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2542 remote->mirror_references, fetch_all_branches, &wanted_branches,
2543 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2544 fetch_progress, &fpa);
2545 if (error)
2546 goto done;
2548 if (list_refs_only) {
2549 error = list_remote_refs(&symrefs, &refs);
2550 goto done;
2553 if (pack_hash == NULL) {
2554 if (verbosity >= 0)
2555 printf("Already up-to-date\n");
2556 } else if (verbosity >= 0) {
2557 error = got_object_id_str(&id_str, pack_hash);
2558 if (error)
2559 goto done;
2560 printf("\nFetched %s.pack\n", id_str);
2561 free(id_str);
2562 id_str = NULL;
2565 /* Update references provided with the pack file. */
2566 TAILQ_FOREACH(pe, &refs, entry) {
2567 const char *refname = pe->path;
2568 struct got_object_id *id = pe->data;
2569 struct got_reference *ref;
2570 char *remote_refname;
2572 if (is_wanted_ref(&wanted_refs, refname) &&
2573 !remote->mirror_references) {
2574 error = update_wanted_ref(refname, id,
2575 remote->name, verbosity, repo);
2576 if (error)
2577 goto done;
2578 continue;
2581 if (remote->mirror_references ||
2582 strncmp("refs/tags/", refname, 10) == 0) {
2583 error = got_ref_open(&ref, repo, refname, 1);
2584 if (error) {
2585 if (error->code != GOT_ERR_NOT_REF)
2586 goto done;
2587 error = create_ref(refname, id, verbosity,
2588 repo);
2589 if (error)
2590 goto done;
2591 } else {
2592 error = update_ref(ref, id, replace_tags,
2593 verbosity, repo);
2594 unlock_err = got_ref_unlock(ref);
2595 if (unlock_err && error == NULL)
2596 error = unlock_err;
2597 got_ref_close(ref);
2598 if (error)
2599 goto done;
2601 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2602 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2603 remote_name, refname + 11) == -1) {
2604 error = got_error_from_errno("asprintf");
2605 goto done;
2608 error = got_ref_open(&ref, repo, remote_refname, 1);
2609 if (error) {
2610 if (error->code != GOT_ERR_NOT_REF)
2611 goto done;
2612 error = create_ref(remote_refname, id,
2613 verbosity, repo);
2614 if (error)
2615 goto done;
2616 } else {
2617 error = update_ref(ref, id, replace_tags,
2618 verbosity, repo);
2619 unlock_err = got_ref_unlock(ref);
2620 if (unlock_err && error == NULL)
2621 error = unlock_err;
2622 got_ref_close(ref);
2623 if (error)
2624 goto done;
2627 /* Also create a local branch if none exists yet. */
2628 error = got_ref_open(&ref, repo, refname, 1);
2629 if (error) {
2630 if (error->code != GOT_ERR_NOT_REF)
2631 goto done;
2632 error = create_ref(refname, id, verbosity,
2633 repo);
2634 if (error)
2635 goto done;
2636 } else {
2637 unlock_err = got_ref_unlock(ref);
2638 if (unlock_err && error == NULL)
2639 error = unlock_err;
2640 got_ref_close(ref);
2644 if (delete_refs) {
2645 error = delete_missing_refs(&refs, &symrefs, remote,
2646 verbosity, repo);
2647 if (error)
2648 goto done;
2651 if (!remote->mirror_references) {
2652 /* Update remote HEAD reference if the server provided one. */
2653 TAILQ_FOREACH(pe, &symrefs, entry) {
2654 struct got_reference *target_ref;
2655 const char *refname = pe->path;
2656 const char *target = pe->data;
2657 char *remote_refname = NULL, *remote_target = NULL;
2659 if (strcmp(refname, GOT_REF_HEAD) != 0)
2660 continue;
2662 if (strncmp("refs/heads/", target, 11) != 0)
2663 continue;
2665 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2666 remote->name, refname) == -1) {
2667 error = got_error_from_errno("asprintf");
2668 goto done;
2670 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2671 remote->name, target + 11) == -1) {
2672 error = got_error_from_errno("asprintf");
2673 free(remote_refname);
2674 goto done;
2677 error = got_ref_open(&target_ref, repo, remote_target,
2678 0);
2679 if (error) {
2680 free(remote_refname);
2681 free(remote_target);
2682 if (error->code == GOT_ERR_NOT_REF) {
2683 error = NULL;
2684 continue;
2686 goto done;
2688 error = update_symref(remote_refname, target_ref,
2689 verbosity, repo);
2690 free(remote_refname);
2691 free(remote_target);
2692 got_ref_close(target_ref);
2693 if (error)
2694 goto done;
2697 done:
2698 if (fetchpid > 0) {
2699 if (kill(fetchpid, SIGTERM) == -1)
2700 error = got_error_from_errno("kill");
2701 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2702 error = got_error_from_errno("waitpid");
2704 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2705 error = got_error_from_errno("close");
2706 if (repo) {
2707 const struct got_error *close_err = got_repo_close(repo);
2708 if (error == NULL)
2709 error = close_err;
2711 if (worktree)
2712 got_worktree_close(worktree);
2713 if (pack_fds) {
2714 const struct got_error *pack_err =
2715 got_repo_pack_fds_close(pack_fds);
2716 if (error == NULL)
2717 error = pack_err;
2719 TAILQ_FOREACH(pe, &refs, entry) {
2720 free((void *)pe->path);
2721 free(pe->data);
2723 got_pathlist_free(&refs);
2724 TAILQ_FOREACH(pe, &symrefs, entry) {
2725 free((void *)pe->path);
2726 free(pe->data);
2728 got_pathlist_free(&symrefs);
2729 got_pathlist_free(&wanted_branches);
2730 got_pathlist_free(&wanted_refs);
2731 free(id_str);
2732 free(cwd);
2733 free(repo_path);
2734 free(pack_hash);
2735 free(proto);
2736 free(host);
2737 free(port);
2738 free(server_path);
2739 free(repo_name);
2740 return error;
2744 __dead static void
2745 usage_checkout(void)
2747 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2748 "[-p path-prefix] repository-path [work-tree-path]\n",
2749 getprogname());
2750 exit(1);
2753 static void
2754 show_worktree_base_ref_warning(void)
2756 fprintf(stderr, "%s: warning: could not create a reference "
2757 "to the work tree's base commit; the commit could be "
2758 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2759 "repository writable and running 'got update' will prevent this\n",
2760 getprogname());
2763 struct got_checkout_progress_arg {
2764 const char *worktree_path;
2765 int had_base_commit_ref_error;
2766 int verbosity;
2769 static const struct got_error *
2770 checkout_progress(void *arg, unsigned char status, const char *path)
2772 struct got_checkout_progress_arg *a = arg;
2774 /* Base commit bump happens silently. */
2775 if (status == GOT_STATUS_BUMP_BASE)
2776 return NULL;
2778 if (status == GOT_STATUS_BASE_REF_ERR) {
2779 a->had_base_commit_ref_error = 1;
2780 return NULL;
2783 while (path[0] == '/')
2784 path++;
2786 if (a->verbosity >= 0)
2787 printf("%c %s/%s\n", status, a->worktree_path, path);
2789 return NULL;
2792 static const struct got_error *
2793 check_cancelled(void *arg)
2795 if (sigint_received || sigpipe_received)
2796 return got_error(GOT_ERR_CANCELLED);
2797 return NULL;
2800 static const struct got_error *
2801 check_linear_ancestry(struct got_object_id *commit_id,
2802 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2803 struct got_repository *repo)
2805 const struct got_error *err = NULL;
2806 struct got_object_id *yca_id;
2808 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2809 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2810 if (err)
2811 return err;
2813 if (yca_id == NULL)
2814 return got_error(GOT_ERR_ANCESTRY);
2817 * Require a straight line of history between the target commit
2818 * and the work tree's base commit.
2820 * Non-linear situations such as this require a rebase:
2822 * (commit) D F (base_commit)
2823 * \ /
2824 * C E
2825 * \ /
2826 * B (yca)
2827 * |
2828 * A
2830 * 'got update' only handles linear cases:
2831 * Update forwards in time: A (base/yca) - B - C - D (commit)
2832 * Update backwards in time: D (base) - C - B - A (commit/yca)
2834 if (allow_forwards_in_time_only) {
2835 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2836 return got_error(GOT_ERR_ANCESTRY);
2837 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2838 got_object_id_cmp(base_commit_id, yca_id) != 0)
2839 return got_error(GOT_ERR_ANCESTRY);
2841 free(yca_id);
2842 return NULL;
2845 static const struct got_error *
2846 check_same_branch(struct got_object_id *commit_id,
2847 struct got_reference *head_ref, struct got_object_id *yca_id,
2848 struct got_repository *repo)
2850 const struct got_error *err = NULL;
2851 struct got_commit_graph *graph = NULL;
2852 struct got_object_id *head_commit_id = NULL;
2853 int is_same_branch = 0;
2855 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2856 if (err)
2857 goto done;
2859 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2860 is_same_branch = 1;
2861 goto done;
2863 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2864 is_same_branch = 1;
2865 goto done;
2868 err = got_commit_graph_open(&graph, "/", 1);
2869 if (err)
2870 goto done;
2872 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2873 check_cancelled, NULL);
2874 if (err)
2875 goto done;
2877 for (;;) {
2878 struct got_object_id id;
2880 err = got_commit_graph_iter_next(&id, graph, repo,
2881 check_cancelled, NULL);
2882 if (err) {
2883 if (err->code == GOT_ERR_ITER_COMPLETED)
2884 err = NULL;
2885 break;
2888 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2889 break;
2890 if (got_object_id_cmp(&id, commit_id) == 0) {
2891 is_same_branch = 1;
2892 break;
2895 done:
2896 if (graph)
2897 got_commit_graph_close(graph);
2898 free(head_commit_id);
2899 if (!err && !is_same_branch)
2900 err = got_error(GOT_ERR_ANCESTRY);
2901 return err;
2904 static const struct got_error *
2905 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2907 static char msg[512];
2908 const char *branch_name;
2910 if (got_ref_is_symbolic(ref))
2911 branch_name = got_ref_get_symref_target(ref);
2912 else
2913 branch_name = got_ref_get_name(ref);
2915 if (strncmp("refs/heads/", branch_name, 11) == 0)
2916 branch_name += 11;
2918 snprintf(msg, sizeof(msg),
2919 "target commit is not contained in branch '%s'; "
2920 "the branch to use must be specified with -b; "
2921 "if necessary a new branch can be created for "
2922 "this commit with 'got branch -c %s BRANCH_NAME'",
2923 branch_name, commit_id_str);
2925 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2928 static const struct got_error *
2929 cmd_checkout(int argc, char *argv[])
2931 const struct got_error *error = NULL;
2932 struct got_repository *repo = NULL;
2933 struct got_reference *head_ref = NULL, *ref = NULL;
2934 struct got_worktree *worktree = NULL;
2935 char *repo_path = NULL;
2936 char *worktree_path = NULL;
2937 const char *path_prefix = "";
2938 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2939 char *commit_id_str = NULL;
2940 struct got_object_id *commit_id = NULL;
2941 char *cwd = NULL;
2942 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2943 struct got_pathlist_head paths;
2944 struct got_checkout_progress_arg cpa;
2945 int *pack_fds = NULL;
2947 TAILQ_INIT(&paths);
2949 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2950 switch (ch) {
2951 case 'b':
2952 branch_name = optarg;
2953 break;
2954 case 'c':
2955 commit_id_str = strdup(optarg);
2956 if (commit_id_str == NULL)
2957 return got_error_from_errno("strdup");
2958 break;
2959 case 'E':
2960 allow_nonempty = 1;
2961 break;
2962 case 'p':
2963 path_prefix = optarg;
2964 break;
2965 case 'q':
2966 verbosity = -1;
2967 break;
2968 default:
2969 usage_checkout();
2970 /* NOTREACHED */
2974 argc -= optind;
2975 argv += optind;
2977 #ifndef PROFILE
2978 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2979 "unveil", NULL) == -1)
2980 err(1, "pledge");
2981 #endif
2982 if (argc == 1) {
2983 char *base, *dotgit;
2984 const char *path;
2985 repo_path = realpath(argv[0], NULL);
2986 if (repo_path == NULL)
2987 return got_error_from_errno2("realpath", argv[0]);
2988 cwd = getcwd(NULL, 0);
2989 if (cwd == NULL) {
2990 error = got_error_from_errno("getcwd");
2991 goto done;
2993 if (path_prefix[0])
2994 path = path_prefix;
2995 else
2996 path = repo_path;
2997 error = got_path_basename(&base, path);
2998 if (error)
2999 goto done;
3000 dotgit = strstr(base, ".git");
3001 if (dotgit)
3002 *dotgit = '\0';
3003 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3004 error = got_error_from_errno("asprintf");
3005 free(base);
3006 goto done;
3008 free(base);
3009 } else if (argc == 2) {
3010 repo_path = realpath(argv[0], NULL);
3011 if (repo_path == NULL) {
3012 error = got_error_from_errno2("realpath", argv[0]);
3013 goto done;
3015 worktree_path = realpath(argv[1], NULL);
3016 if (worktree_path == NULL) {
3017 if (errno != ENOENT) {
3018 error = got_error_from_errno2("realpath",
3019 argv[1]);
3020 goto done;
3022 worktree_path = strdup(argv[1]);
3023 if (worktree_path == NULL) {
3024 error = got_error_from_errno("strdup");
3025 goto done;
3028 } else
3029 usage_checkout();
3031 got_path_strip_trailing_slashes(repo_path);
3032 got_path_strip_trailing_slashes(worktree_path);
3034 error = got_repo_pack_fds_open(&pack_fds);
3035 if (error != NULL)
3036 goto done;
3038 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3039 if (error != NULL)
3040 goto done;
3042 /* Pre-create work tree path for unveil(2) */
3043 error = got_path_mkdir(worktree_path);
3044 if (error) {
3045 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3046 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3047 goto done;
3048 if (!allow_nonempty &&
3049 !got_path_dir_is_empty(worktree_path)) {
3050 error = got_error_path(worktree_path,
3051 GOT_ERR_DIR_NOT_EMPTY);
3052 goto done;
3056 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3057 if (error)
3058 goto done;
3060 error = got_ref_open(&head_ref, repo, branch_name, 0);
3061 if (error != NULL)
3062 goto done;
3064 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3065 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3066 goto done;
3068 error = got_worktree_open(&worktree, worktree_path);
3069 if (error != NULL)
3070 goto done;
3072 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3073 path_prefix);
3074 if (error != NULL)
3075 goto done;
3076 if (!same_path_prefix) {
3077 error = got_error(GOT_ERR_PATH_PREFIX);
3078 goto done;
3081 if (commit_id_str) {
3082 struct got_reflist_head refs;
3083 TAILQ_INIT(&refs);
3084 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3085 NULL);
3086 if (error)
3087 goto done;
3088 error = got_repo_match_object_id(&commit_id, NULL,
3089 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3090 got_ref_list_free(&refs);
3091 if (error)
3092 goto done;
3093 error = check_linear_ancestry(commit_id,
3094 got_worktree_get_base_commit_id(worktree), 0, repo);
3095 if (error != NULL) {
3096 if (error->code == GOT_ERR_ANCESTRY) {
3097 error = checkout_ancestry_error(
3098 head_ref, commit_id_str);
3100 goto done;
3102 error = check_same_branch(commit_id, head_ref, NULL, repo);
3103 if (error) {
3104 if (error->code == GOT_ERR_ANCESTRY) {
3105 error = checkout_ancestry_error(
3106 head_ref, commit_id_str);
3108 goto done;
3110 error = got_worktree_set_base_commit_id(worktree, repo,
3111 commit_id);
3112 if (error)
3113 goto done;
3114 /* Expand potentially abbreviated commit ID string. */
3115 free(commit_id_str);
3116 error = got_object_id_str(&commit_id_str, commit_id);
3117 if (error)
3118 goto done;
3119 } else {
3120 commit_id = got_object_id_dup(
3121 got_worktree_get_base_commit_id(worktree));
3122 if (commit_id == NULL) {
3123 error = got_error_from_errno("got_object_id_dup");
3124 goto done;
3126 error = got_object_id_str(&commit_id_str, commit_id);
3127 if (error)
3128 goto done;
3131 error = got_pathlist_append(&paths, "", NULL);
3132 if (error)
3133 goto done;
3134 cpa.worktree_path = worktree_path;
3135 cpa.had_base_commit_ref_error = 0;
3136 cpa.verbosity = verbosity;
3137 error = got_worktree_checkout_files(worktree, &paths, repo,
3138 checkout_progress, &cpa, check_cancelled, NULL);
3139 if (error != NULL)
3140 goto done;
3142 if (got_ref_is_symbolic(head_ref)) {
3143 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3144 if (error)
3145 goto done;
3146 refname = got_ref_get_name(ref);
3147 } else
3148 refname = got_ref_get_name(head_ref);
3149 printf("Checked out %s: %s\n", refname, commit_id_str);
3150 printf("Now shut up and hack\n");
3151 if (cpa.had_base_commit_ref_error)
3152 show_worktree_base_ref_warning();
3153 done:
3154 if (pack_fds) {
3155 const struct got_error *pack_err =
3156 got_repo_pack_fds_close(pack_fds);
3157 if (error == NULL)
3158 error = pack_err;
3160 if (head_ref)
3161 got_ref_close(head_ref);
3162 if (ref)
3163 got_ref_close(ref);
3164 got_pathlist_free(&paths);
3165 free(commit_id_str);
3166 free(commit_id);
3167 free(repo_path);
3168 free(worktree_path);
3169 free(cwd);
3170 return error;
3173 struct got_update_progress_arg {
3174 int did_something;
3175 int conflicts;
3176 int obstructed;
3177 int not_updated;
3178 int missing;
3179 int not_deleted;
3180 int unversioned;
3181 int verbosity;
3184 static void
3185 print_update_progress_stats(struct got_update_progress_arg *upa)
3187 if (!upa->did_something)
3188 return;
3190 if (upa->conflicts > 0)
3191 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3192 if (upa->obstructed > 0)
3193 printf("File paths obstructed by a non-regular file: %d\n",
3194 upa->obstructed);
3195 if (upa->not_updated > 0)
3196 printf("Files not updated because of existing merge "
3197 "conflicts: %d\n", upa->not_updated);
3201 * The meaning of some status codes differs between merge-style operations and
3202 * update operations. For example, the ! status code means "file was missing"
3203 * if changes were merged into the work tree, and "missing file was restored"
3204 * if the work tree was updated. This function should be used by any operation
3205 * which merges changes into the work tree without updating the work tree.
3207 static void
3208 print_merge_progress_stats(struct got_update_progress_arg *upa)
3210 if (!upa->did_something)
3211 return;
3213 if (upa->conflicts > 0)
3214 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3215 if (upa->obstructed > 0)
3216 printf("File paths obstructed by a non-regular file: %d\n",
3217 upa->obstructed);
3218 if (upa->missing > 0)
3219 printf("Files which had incoming changes but could not be "
3220 "found in the work tree: %d\n", upa->missing);
3221 if (upa->not_deleted > 0)
3222 printf("Files not deleted due to differences in deleted "
3223 "content: %d\n", upa->not_deleted);
3224 if (upa->unversioned > 0)
3225 printf("Files not merged because an unversioned file was "
3226 "found in the work tree: %d\n", upa->unversioned);
3229 __dead static void
3230 usage_update(void)
3232 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3233 "[path ...]\n", getprogname());
3234 exit(1);
3237 static const struct got_error *
3238 update_progress(void *arg, unsigned char status, const char *path)
3240 struct got_update_progress_arg *upa = arg;
3242 if (status == GOT_STATUS_EXISTS ||
3243 status == GOT_STATUS_BASE_REF_ERR)
3244 return NULL;
3246 upa->did_something = 1;
3248 /* Base commit bump happens silently. */
3249 if (status == GOT_STATUS_BUMP_BASE)
3250 return NULL;
3252 if (status == GOT_STATUS_CONFLICT)
3253 upa->conflicts++;
3254 if (status == GOT_STATUS_OBSTRUCTED)
3255 upa->obstructed++;
3256 if (status == GOT_STATUS_CANNOT_UPDATE)
3257 upa->not_updated++;
3258 if (status == GOT_STATUS_MISSING)
3259 upa->missing++;
3260 if (status == GOT_STATUS_CANNOT_DELETE)
3261 upa->not_deleted++;
3262 if (status == GOT_STATUS_UNVERSIONED)
3263 upa->unversioned++;
3265 while (path[0] == '/')
3266 path++;
3267 if (upa->verbosity >= 0)
3268 printf("%c %s\n", status, path);
3270 return NULL;
3273 static const struct got_error *
3274 switch_head_ref(struct got_reference *head_ref,
3275 struct got_object_id *commit_id, struct got_worktree *worktree,
3276 struct got_repository *repo)
3278 const struct got_error *err = NULL;
3279 char *base_id_str;
3280 int ref_has_moved = 0;
3282 /* Trivial case: switching between two different references. */
3283 if (strcmp(got_ref_get_name(head_ref),
3284 got_worktree_get_head_ref_name(worktree)) != 0) {
3285 printf("Switching work tree from %s to %s\n",
3286 got_worktree_get_head_ref_name(worktree),
3287 got_ref_get_name(head_ref));
3288 return got_worktree_set_head_ref(worktree, head_ref);
3291 err = check_linear_ancestry(commit_id,
3292 got_worktree_get_base_commit_id(worktree), 0, repo);
3293 if (err) {
3294 if (err->code != GOT_ERR_ANCESTRY)
3295 return err;
3296 ref_has_moved = 1;
3298 if (!ref_has_moved)
3299 return NULL;
3301 /* Switching to a rebased branch with the same reference name. */
3302 err = got_object_id_str(&base_id_str,
3303 got_worktree_get_base_commit_id(worktree));
3304 if (err)
3305 return err;
3306 printf("Reference %s now points at a different branch\n",
3307 got_worktree_get_head_ref_name(worktree));
3308 printf("Switching work tree from %s to %s\n", base_id_str,
3309 got_worktree_get_head_ref_name(worktree));
3310 return NULL;
3313 static const struct got_error *
3314 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3316 const struct got_error *err;
3317 int in_progress;
3319 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3320 if (err)
3321 return err;
3322 if (in_progress)
3323 return got_error(GOT_ERR_REBASING);
3325 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3326 if (err)
3327 return err;
3328 if (in_progress)
3329 return got_error(GOT_ERR_HISTEDIT_BUSY);
3331 return NULL;
3334 static const struct got_error *
3335 check_merge_in_progress(struct got_worktree *worktree,
3336 struct got_repository *repo)
3338 const struct got_error *err;
3339 int in_progress;
3341 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3342 if (err)
3343 return err;
3344 if (in_progress)
3345 return got_error(GOT_ERR_MERGE_BUSY);
3347 return NULL;
3350 static const struct got_error *
3351 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3352 char *argv[], struct got_worktree *worktree)
3354 const struct got_error *err = NULL;
3355 char *path;
3356 struct got_pathlist_entry *new;
3357 int i;
3359 if (argc == 0) {
3360 path = strdup("");
3361 if (path == NULL)
3362 return got_error_from_errno("strdup");
3363 return got_pathlist_append(paths, path, NULL);
3366 for (i = 0; i < argc; i++) {
3367 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3368 if (err)
3369 break;
3370 err = got_pathlist_insert(&new, paths, path, NULL);
3371 if (err || new == NULL /* duplicate */) {
3372 free(path);
3373 if (err)
3374 break;
3378 return err;
3381 static const struct got_error *
3382 wrap_not_worktree_error(const struct got_error *orig_err,
3383 const char *cmdname, const char *path)
3385 const struct got_error *err;
3386 struct got_repository *repo;
3387 static char msg[512];
3388 int *pack_fds = NULL;
3390 err = got_repo_pack_fds_open(&pack_fds);
3391 if (err)
3392 return err;
3394 err = got_repo_open(&repo, path, NULL, pack_fds);
3395 if (err)
3396 return orig_err;
3398 snprintf(msg, sizeof(msg),
3399 "'got %s' needs a work tree in addition to a git repository\n"
3400 "Work trees can be checked out from this Git repository with "
3401 "'got checkout'.\n"
3402 "The got(1) manual page contains more information.", cmdname);
3403 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3404 got_repo_close(repo);
3405 if (pack_fds) {
3406 const struct got_error *pack_err =
3407 got_repo_pack_fds_close(pack_fds);
3408 if (err == NULL)
3409 err = pack_err;
3411 return err;
3414 static const struct got_error *
3415 cmd_update(int argc, char *argv[])
3417 const struct got_error *error = NULL;
3418 struct got_repository *repo = NULL;
3419 struct got_worktree *worktree = NULL;
3420 char *worktree_path = NULL;
3421 struct got_object_id *commit_id = NULL;
3422 char *commit_id_str = NULL;
3423 const char *branch_name = NULL;
3424 struct got_reference *head_ref = NULL;
3425 struct got_pathlist_head paths;
3426 struct got_pathlist_entry *pe;
3427 int ch, verbosity = 0;
3428 struct got_update_progress_arg upa;
3429 int *pack_fds = NULL;
3431 TAILQ_INIT(&paths);
3433 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3434 switch (ch) {
3435 case 'b':
3436 branch_name = optarg;
3437 break;
3438 case 'c':
3439 commit_id_str = strdup(optarg);
3440 if (commit_id_str == NULL)
3441 return got_error_from_errno("strdup");
3442 break;
3443 case 'q':
3444 verbosity = -1;
3445 break;
3446 default:
3447 usage_update();
3448 /* NOTREACHED */
3452 argc -= optind;
3453 argv += optind;
3455 #ifndef PROFILE
3456 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3457 "unveil", NULL) == -1)
3458 err(1, "pledge");
3459 #endif
3460 worktree_path = getcwd(NULL, 0);
3461 if (worktree_path == NULL) {
3462 error = got_error_from_errno("getcwd");
3463 goto done;
3466 error = got_repo_pack_fds_open(&pack_fds);
3467 if (error != NULL)
3468 goto done;
3470 error = got_worktree_open(&worktree, worktree_path);
3471 if (error) {
3472 if (error->code == GOT_ERR_NOT_WORKTREE)
3473 error = wrap_not_worktree_error(error, "update",
3474 worktree_path);
3475 goto done;
3478 error = check_rebase_or_histedit_in_progress(worktree);
3479 if (error)
3480 goto done;
3482 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3483 NULL, pack_fds);
3484 if (error != NULL)
3485 goto done;
3487 error = apply_unveil(got_repo_get_path(repo), 0,
3488 got_worktree_get_root_path(worktree));
3489 if (error)
3490 goto done;
3492 error = check_merge_in_progress(worktree, repo);
3493 if (error)
3494 goto done;
3496 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3497 if (error)
3498 goto done;
3500 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3501 got_worktree_get_head_ref_name(worktree), 0);
3502 if (error != NULL)
3503 goto done;
3504 if (commit_id_str == NULL) {
3505 error = got_ref_resolve(&commit_id, repo, head_ref);
3506 if (error != NULL)
3507 goto done;
3508 error = got_object_id_str(&commit_id_str, commit_id);
3509 if (error != NULL)
3510 goto done;
3511 } else {
3512 struct got_reflist_head refs;
3513 TAILQ_INIT(&refs);
3514 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3515 NULL);
3516 if (error)
3517 goto done;
3518 error = got_repo_match_object_id(&commit_id, NULL,
3519 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3520 got_ref_list_free(&refs);
3521 free(commit_id_str);
3522 commit_id_str = NULL;
3523 if (error)
3524 goto done;
3525 error = got_object_id_str(&commit_id_str, commit_id);
3526 if (error)
3527 goto done;
3530 if (branch_name) {
3531 struct got_object_id *head_commit_id;
3532 TAILQ_FOREACH(pe, &paths, entry) {
3533 if (pe->path_len == 0)
3534 continue;
3535 error = got_error_msg(GOT_ERR_BAD_PATH,
3536 "switching between branches requires that "
3537 "the entire work tree gets updated");
3538 goto done;
3540 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3541 if (error)
3542 goto done;
3543 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3544 repo);
3545 free(head_commit_id);
3546 if (error != NULL)
3547 goto done;
3548 error = check_same_branch(commit_id, head_ref, NULL, repo);
3549 if (error)
3550 goto done;
3551 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3552 if (error)
3553 goto done;
3554 } else {
3555 error = check_linear_ancestry(commit_id,
3556 got_worktree_get_base_commit_id(worktree), 0, repo);
3557 if (error != NULL) {
3558 if (error->code == GOT_ERR_ANCESTRY)
3559 error = got_error(GOT_ERR_BRANCH_MOVED);
3560 goto done;
3562 error = check_same_branch(commit_id, head_ref, NULL, repo);
3563 if (error)
3564 goto done;
3567 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3568 commit_id) != 0) {
3569 error = got_worktree_set_base_commit_id(worktree, repo,
3570 commit_id);
3571 if (error)
3572 goto done;
3575 memset(&upa, 0, sizeof(upa));
3576 upa.verbosity = verbosity;
3577 error = got_worktree_checkout_files(worktree, &paths, repo,
3578 update_progress, &upa, check_cancelled, NULL);
3579 if (error != NULL)
3580 goto done;
3582 if (upa.did_something) {
3583 printf("Updated to %s: %s\n",
3584 got_worktree_get_head_ref_name(worktree), commit_id_str);
3585 } else
3586 printf("Already up-to-date\n");
3588 print_update_progress_stats(&upa);
3589 done:
3590 if (pack_fds) {
3591 const struct got_error *pack_err =
3592 got_repo_pack_fds_close(pack_fds);
3593 if (error == NULL)
3594 error = pack_err;
3596 free(worktree_path);
3597 TAILQ_FOREACH(pe, &paths, entry)
3598 free((char *)pe->path);
3599 got_pathlist_free(&paths);
3600 free(commit_id);
3601 free(commit_id_str);
3602 return error;
3605 static const struct got_error *
3606 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3607 const char *path, int diff_context, int ignore_whitespace,
3608 int force_text_diff, struct got_repository *repo, FILE *outfile)
3610 const struct got_error *err = NULL;
3611 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3612 FILE *f1 = NULL, *f2 = NULL;
3613 int fd1 = -1, fd2 = -1;
3615 fd1 = got_opentempfd();
3616 if (fd1 == -1)
3617 return got_error_from_errno("got_opentempfd");
3618 fd2 = got_opentempfd();
3619 if (fd2 == -1) {
3620 err = got_error_from_errno("got_opentempfd");
3621 goto done;
3624 if (blob_id1) {
3625 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3626 fd1);
3627 if (err)
3628 goto done;
3631 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3632 if (err)
3633 goto done;
3635 f1 = got_opentemp();
3636 if (f1 == NULL) {
3637 err = got_error_from_errno("got_opentemp");
3638 goto done;
3640 f2 = got_opentemp();
3641 if (f2 == NULL) {
3642 err = got_error_from_errno("got_opentemp");
3643 goto done;
3646 while (path[0] == '/')
3647 path++;
3648 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3649 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3650 force_text_diff, outfile);
3651 done:
3652 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3653 err = got_error_from_errno("close");
3654 if (blob1)
3655 got_object_blob_close(blob1);
3656 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3657 err = got_error_from_errno("close");
3658 got_object_blob_close(blob2);
3659 if (f1 && fclose(f1) == EOF && err == NULL)
3660 err = got_error_from_errno("fclose");
3661 if (f2 && fclose(f2) == EOF && err == NULL)
3662 err = got_error_from_errno("fclose");
3663 return err;
3666 static const struct got_error *
3667 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3668 const char *path, int diff_context, int ignore_whitespace,
3669 int force_text_diff, struct got_repository *repo, FILE *outfile)
3671 const struct got_error *err = NULL;
3672 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3673 struct got_diff_blob_output_unidiff_arg arg;
3674 FILE *f1 = NULL, *f2 = NULL;
3675 int fd1 = -1, fd2 = -1;
3677 if (tree_id1) {
3678 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3679 if (err)
3680 goto done;
3681 fd1 = got_opentempfd();
3682 if (fd1 == -1) {
3683 err = got_error_from_errno("got_opentempfd");
3684 goto done;
3688 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3689 if (err)
3690 goto done;
3692 f1 = got_opentemp();
3693 if (f1 == NULL) {
3694 err = got_error_from_errno("got_opentemp");
3695 goto done;
3698 f2 = got_opentemp();
3699 if (f2 == NULL) {
3700 err = got_error_from_errno("got_opentemp");
3701 goto done;
3703 fd2 = got_opentempfd();
3704 if (fd2 == -1) {
3705 err = got_error_from_errno("got_opentempfd");
3706 goto done;
3708 arg.diff_context = diff_context;
3709 arg.ignore_whitespace = ignore_whitespace;
3710 arg.force_text_diff = force_text_diff;
3711 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3712 arg.outfile = outfile;
3713 arg.lines = NULL;
3714 arg.nlines = 0;
3715 while (path[0] == '/')
3716 path++;
3717 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3718 got_diff_blob_output_unidiff, &arg, 1);
3719 done:
3720 if (tree1)
3721 got_object_tree_close(tree1);
3722 if (tree2)
3723 got_object_tree_close(tree2);
3724 if (f1 && fclose(f1) == EOF && err == NULL)
3725 err = got_error_from_errno("fclose");
3726 if (f2 && fclose(f2) == EOF && err == NULL)
3727 err = got_error_from_errno("fclose");
3728 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3729 err = got_error_from_errno("close");
3730 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3731 err = got_error_from_errno("close");
3732 return err;
3735 static const struct got_error *
3736 get_changed_paths(struct got_pathlist_head *paths,
3737 struct got_commit_object *commit, struct got_repository *repo)
3739 const struct got_error *err = NULL;
3740 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3741 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3742 struct got_object_qid *qid;
3744 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3745 if (qid != NULL) {
3746 struct got_commit_object *pcommit;
3747 err = got_object_open_as_commit(&pcommit, repo,
3748 &qid->id);
3749 if (err)
3750 return err;
3752 tree_id1 = got_object_id_dup(
3753 got_object_commit_get_tree_id(pcommit));
3754 if (tree_id1 == NULL) {
3755 got_object_commit_close(pcommit);
3756 return got_error_from_errno("got_object_id_dup");
3758 got_object_commit_close(pcommit);
3762 if (tree_id1) {
3763 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3764 if (err)
3765 goto done;
3768 tree_id2 = got_object_commit_get_tree_id(commit);
3769 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3770 if (err)
3771 goto done;
3773 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3774 got_diff_tree_collect_changed_paths, paths, 0);
3775 done:
3776 if (tree1)
3777 got_object_tree_close(tree1);
3778 if (tree2)
3779 got_object_tree_close(tree2);
3780 free(tree_id1);
3781 return err;
3784 static const struct got_error *
3785 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3786 const char *path, int diff_context, struct got_repository *repo,
3787 FILE *outfile)
3789 const struct got_error *err = NULL;
3790 struct got_commit_object *pcommit = NULL;
3791 char *id_str1 = NULL, *id_str2 = NULL;
3792 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3793 struct got_object_qid *qid;
3795 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3796 if (qid != NULL) {
3797 err = got_object_open_as_commit(&pcommit, repo,
3798 &qid->id);
3799 if (err)
3800 return err;
3801 err = got_object_id_str(&id_str1, &qid->id);
3802 if (err)
3803 goto done;
3806 err = got_object_id_str(&id_str2, id);
3807 if (err)
3808 goto done;
3810 if (path && path[0] != '\0') {
3811 int obj_type;
3812 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3813 if (err)
3814 goto done;
3815 if (pcommit) {
3816 err = got_object_id_by_path(&obj_id1, repo,
3817 pcommit, path);
3818 if (err) {
3819 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3820 free(obj_id2);
3821 goto done;
3825 err = got_object_get_type(&obj_type, repo, obj_id2);
3826 if (err) {
3827 free(obj_id2);
3828 goto done;
3830 fprintf(outfile,
3831 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3832 fprintf(outfile, "commit - %s\n",
3833 id_str1 ? id_str1 : "/dev/null");
3834 fprintf(outfile, "commit + %s\n", id_str2);
3835 switch (obj_type) {
3836 case GOT_OBJ_TYPE_BLOB:
3837 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3838 0, 0, repo, outfile);
3839 break;
3840 case GOT_OBJ_TYPE_TREE:
3841 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3842 0, 0, repo, outfile);
3843 break;
3844 default:
3845 err = got_error(GOT_ERR_OBJ_TYPE);
3846 break;
3848 free(obj_id1);
3849 free(obj_id2);
3850 } else {
3851 obj_id2 = got_object_commit_get_tree_id(commit);
3852 if (pcommit)
3853 obj_id1 = got_object_commit_get_tree_id(pcommit);
3854 fprintf(outfile,
3855 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3856 fprintf(outfile, "commit - %s\n",
3857 id_str1 ? id_str1 : "/dev/null");
3858 fprintf(outfile, "commit + %s\n", id_str2);
3859 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3860 repo, outfile);
3862 done:
3863 free(id_str1);
3864 free(id_str2);
3865 if (pcommit)
3866 got_object_commit_close(pcommit);
3867 return err;
3870 static char *
3871 get_datestr(time_t *time, char *datebuf)
3873 struct tm mytm, *tm;
3874 char *p, *s;
3876 tm = gmtime_r(time, &mytm);
3877 if (tm == NULL)
3878 return NULL;
3879 s = asctime_r(tm, datebuf);
3880 if (s == NULL)
3881 return NULL;
3882 p = strchr(s, '\n');
3883 if (p)
3884 *p = '\0';
3885 return s;
3888 static const struct got_error *
3889 match_commit(int *have_match, struct got_object_id *id,
3890 struct got_commit_object *commit, regex_t *regex)
3892 const struct got_error *err = NULL;
3893 regmatch_t regmatch;
3894 char *id_str = NULL, *logmsg = NULL;
3896 *have_match = 0;
3898 err = got_object_id_str(&id_str, id);
3899 if (err)
3900 return err;
3902 err = got_object_commit_get_logmsg(&logmsg, commit);
3903 if (err)
3904 goto done;
3906 if (regexec(regex, got_object_commit_get_author(commit), 1,
3907 &regmatch, 0) == 0 ||
3908 regexec(regex, got_object_commit_get_committer(commit), 1,
3909 &regmatch, 0) == 0 ||
3910 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3911 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3912 *have_match = 1;
3913 done:
3914 free(id_str);
3915 free(logmsg);
3916 return err;
3919 static void
3920 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3921 regex_t *regex)
3923 regmatch_t regmatch;
3924 struct got_pathlist_entry *pe;
3926 *have_match = 0;
3928 TAILQ_FOREACH(pe, changed_paths, entry) {
3929 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3930 *have_match = 1;
3931 break;
3936 static const struct got_error *
3937 match_patch(int *have_match, struct got_commit_object *commit,
3938 struct got_object_id *id, const char *path, int diff_context,
3939 struct got_repository *repo, regex_t *regex, FILE *f)
3941 const struct got_error *err = NULL;
3942 char *line = NULL;
3943 size_t linesize = 0;
3944 regmatch_t regmatch;
3946 *have_match = 0;
3948 err = got_opentemp_truncate(f);
3949 if (err)
3950 return err;
3952 err = print_patch(commit, id, path, diff_context, repo, f);
3953 if (err)
3954 goto done;
3956 if (fseeko(f, 0L, SEEK_SET) == -1) {
3957 err = got_error_from_errno("fseeko");
3958 goto done;
3961 while (getline(&line, &linesize, f) != -1) {
3962 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3963 *have_match = 1;
3964 break;
3967 done:
3968 free(line);
3969 return err;
3972 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3974 static const struct got_error*
3975 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3976 struct got_object_id *id, struct got_repository *repo,
3977 int local_only)
3979 static const struct got_error *err = NULL;
3980 struct got_reflist_entry *re;
3981 char *s;
3982 const char *name;
3984 *refs_str = NULL;
3986 TAILQ_FOREACH(re, refs, entry) {
3987 struct got_tag_object *tag = NULL;
3988 struct got_object_id *ref_id;
3989 int cmp;
3991 name = got_ref_get_name(re->ref);
3992 if (strcmp(name, GOT_REF_HEAD) == 0)
3993 continue;
3994 if (strncmp(name, "refs/", 5) == 0)
3995 name += 5;
3996 if (strncmp(name, "got/", 4) == 0)
3997 continue;
3998 if (strncmp(name, "heads/", 6) == 0)
3999 name += 6;
4000 if (strncmp(name, "remotes/", 8) == 0) {
4001 if (local_only)
4002 continue;
4003 name += 8;
4004 s = strstr(name, "/" GOT_REF_HEAD);
4005 if (s != NULL && s[strlen(s)] == '\0')
4006 continue;
4008 err = got_ref_resolve(&ref_id, repo, re->ref);
4009 if (err)
4010 break;
4011 if (strncmp(name, "tags/", 5) == 0) {
4012 err = got_object_open_as_tag(&tag, repo, ref_id);
4013 if (err) {
4014 if (err->code != GOT_ERR_OBJ_TYPE) {
4015 free(ref_id);
4016 break;
4018 /* Ref points at something other than a tag. */
4019 err = NULL;
4020 tag = NULL;
4023 cmp = got_object_id_cmp(tag ?
4024 got_object_tag_get_object_id(tag) : ref_id, id);
4025 free(ref_id);
4026 if (tag)
4027 got_object_tag_close(tag);
4028 if (cmp != 0)
4029 continue;
4030 s = *refs_str;
4031 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4032 s ? ", " : "", name) == -1) {
4033 err = got_error_from_errno("asprintf");
4034 free(s);
4035 *refs_str = NULL;
4036 break;
4038 free(s);
4041 return err;
4044 static const struct got_error *
4045 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4046 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4048 const struct got_error *err = NULL;
4049 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4050 char *comma, *s, *nl;
4051 struct got_reflist_head *refs;
4052 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4053 struct tm tm;
4054 time_t committer_time;
4056 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4057 if (refs) {
4058 err = build_refs_str(&ref_str, refs, id, repo, 1);
4059 if (err)
4060 return err;
4062 /* Display the first matching ref only. */
4063 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4064 *comma = '\0';
4067 if (ref_str == NULL) {
4068 err = got_object_id_str(&id_str, id);
4069 if (err)
4070 return err;
4073 committer_time = got_object_commit_get_committer_time(commit);
4074 if (gmtime_r(&committer_time, &tm) == NULL) {
4075 err = got_error_from_errno("gmtime_r");
4076 goto done;
4078 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4079 err = got_error(GOT_ERR_NO_SPACE);
4080 goto done;
4083 err = got_object_commit_get_logmsg(&logmsg0, commit);
4084 if (err)
4085 goto done;
4087 s = logmsg0;
4088 while (isspace((unsigned char)s[0]))
4089 s++;
4091 nl = strchr(s, '\n');
4092 if (nl) {
4093 *nl = '\0';
4096 if (ref_str)
4097 printf("%s%-7s %s\n", datebuf, ref_str, s);
4098 else
4099 printf("%s%.7s %s\n", datebuf, id_str, s);
4101 if (fflush(stdout) != 0 && err == NULL)
4102 err = got_error_from_errno("fflush");
4103 done:
4104 free(id_str);
4105 free(ref_str);
4106 free(logmsg0);
4107 return err;
4110 static const struct got_error *
4111 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4112 struct got_repository *repo, const char *path,
4113 struct got_pathlist_head *changed_paths, int show_patch,
4114 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4115 const char *custom_refs_str)
4117 const struct got_error *err = NULL;
4118 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4119 char datebuf[26];
4120 time_t committer_time;
4121 const char *author, *committer;
4122 char *refs_str = NULL;
4124 err = got_object_id_str(&id_str, id);
4125 if (err)
4126 return err;
4128 if (custom_refs_str == NULL) {
4129 struct got_reflist_head *refs;
4130 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4131 if (refs) {
4132 err = build_refs_str(&refs_str, refs, id, repo, 0);
4133 if (err)
4134 goto done;
4138 printf(GOT_COMMIT_SEP_STR);
4139 if (custom_refs_str)
4140 printf("commit %s (%s)\n", id_str, custom_refs_str);
4141 else
4142 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4143 refs_str ? refs_str : "", refs_str ? ")" : "");
4144 free(id_str);
4145 id_str = NULL;
4146 free(refs_str);
4147 refs_str = NULL;
4148 printf("from: %s\n", got_object_commit_get_author(commit));
4149 committer_time = got_object_commit_get_committer_time(commit);
4150 datestr = get_datestr(&committer_time, datebuf);
4151 if (datestr)
4152 printf("date: %s UTC\n", datestr);
4153 author = got_object_commit_get_author(commit);
4154 committer = got_object_commit_get_committer(commit);
4155 if (strcmp(author, committer) != 0)
4156 printf("via: %s\n", committer);
4157 if (got_object_commit_get_nparents(commit) > 1) {
4158 const struct got_object_id_queue *parent_ids;
4159 struct got_object_qid *qid;
4160 int n = 1;
4161 parent_ids = got_object_commit_get_parent_ids(commit);
4162 STAILQ_FOREACH(qid, parent_ids, entry) {
4163 err = got_object_id_str(&id_str, &qid->id);
4164 if (err)
4165 goto done;
4166 printf("parent %d: %s\n", n++, id_str);
4167 free(id_str);
4168 id_str = NULL;
4172 err = got_object_commit_get_logmsg(&logmsg0, commit);
4173 if (err)
4174 goto done;
4176 logmsg = logmsg0;
4177 do {
4178 line = strsep(&logmsg, "\n");
4179 if (line)
4180 printf(" %s\n", line);
4181 } while (line);
4182 free(logmsg0);
4184 if (changed_paths) {
4185 struct got_pathlist_entry *pe;
4186 TAILQ_FOREACH(pe, changed_paths, entry) {
4187 struct got_diff_changed_path *cp = pe->data;
4188 printf(" %c %s\n", cp->status, pe->path);
4190 printf("\n");
4192 if (show_patch) {
4193 err = print_patch(commit, id, path, diff_context, repo, stdout);
4194 if (err == 0)
4195 printf("\n");
4198 if (fflush(stdout) != 0 && err == NULL)
4199 err = got_error_from_errno("fflush");
4200 done:
4201 free(id_str);
4202 free(refs_str);
4203 return err;
4206 static const struct got_error *
4207 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4208 struct got_repository *repo, const char *path, int show_changed_paths,
4209 int show_patch, const char *search_pattern, int diff_context, int limit,
4210 int log_branches, int reverse_display_order,
4211 struct got_reflist_object_id_map *refs_idmap, int one_line,
4212 FILE *tmpfile)
4214 const struct got_error *err;
4215 struct got_commit_graph *graph;
4216 regex_t regex;
4217 int have_match;
4218 struct got_object_id_queue reversed_commits;
4219 struct got_object_qid *qid;
4220 struct got_commit_object *commit;
4221 struct got_pathlist_head changed_paths;
4222 struct got_pathlist_entry *pe;
4224 STAILQ_INIT(&reversed_commits);
4225 TAILQ_INIT(&changed_paths);
4227 if (search_pattern && regcomp(&regex, search_pattern,
4228 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4229 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4231 err = got_commit_graph_open(&graph, path, !log_branches);
4232 if (err)
4233 return err;
4234 err = got_commit_graph_iter_start(graph, root_id, repo,
4235 check_cancelled, NULL);
4236 if (err)
4237 goto done;
4238 for (;;) {
4239 struct got_object_id id;
4241 if (sigint_received || sigpipe_received)
4242 break;
4244 err = got_commit_graph_iter_next(&id, graph, repo,
4245 check_cancelled, NULL);
4246 if (err) {
4247 if (err->code == GOT_ERR_ITER_COMPLETED)
4248 err = NULL;
4249 break;
4252 err = got_object_open_as_commit(&commit, repo, &id);
4253 if (err)
4254 break;
4256 if (show_changed_paths && !reverse_display_order) {
4257 err = get_changed_paths(&changed_paths, commit, repo);
4258 if (err)
4259 break;
4262 if (search_pattern) {
4263 err = match_commit(&have_match, &id, commit, &regex);
4264 if (err) {
4265 got_object_commit_close(commit);
4266 break;
4268 if (have_match == 0 && show_changed_paths)
4269 match_changed_paths(&have_match,
4270 &changed_paths, &regex);
4271 if (have_match == 0 && show_patch) {
4272 err = match_patch(&have_match, commit, &id,
4273 path, diff_context, repo, &regex,
4274 tmpfile);
4275 if (err)
4276 break;
4278 if (have_match == 0) {
4279 got_object_commit_close(commit);
4280 TAILQ_FOREACH(pe, &changed_paths, entry) {
4281 free((char *)pe->path);
4282 free(pe->data);
4284 got_pathlist_free(&changed_paths);
4285 continue;
4289 if (reverse_display_order) {
4290 err = got_object_qid_alloc(&qid, &id);
4291 if (err)
4292 break;
4293 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4294 got_object_commit_close(commit);
4295 } else {
4296 if (one_line)
4297 err = print_commit_oneline(commit, &id,
4298 repo, refs_idmap);
4299 else
4300 err = print_commit(commit, &id, repo, path,
4301 show_changed_paths ? &changed_paths : NULL,
4302 show_patch, diff_context, refs_idmap, NULL);
4303 got_object_commit_close(commit);
4304 if (err)
4305 break;
4307 if ((limit && --limit == 0) ||
4308 (end_id && got_object_id_cmp(&id, end_id) == 0))
4309 break;
4311 TAILQ_FOREACH(pe, &changed_paths, entry) {
4312 free((char *)pe->path);
4313 free(pe->data);
4315 got_pathlist_free(&changed_paths);
4317 if (reverse_display_order) {
4318 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4319 err = got_object_open_as_commit(&commit, repo,
4320 &qid->id);
4321 if (err)
4322 break;
4323 if (show_changed_paths) {
4324 err = get_changed_paths(&changed_paths,
4325 commit, repo);
4326 if (err)
4327 break;
4329 if (one_line)
4330 err = print_commit_oneline(commit, &qid->id,
4331 repo, refs_idmap);
4332 else
4333 err = print_commit(commit, &qid->id, repo, path,
4334 show_changed_paths ? &changed_paths : NULL,
4335 show_patch, diff_context, refs_idmap, NULL);
4336 got_object_commit_close(commit);
4337 if (err)
4338 break;
4339 TAILQ_FOREACH(pe, &changed_paths, entry) {
4340 free((char *)pe->path);
4341 free(pe->data);
4343 got_pathlist_free(&changed_paths);
4346 done:
4347 while (!STAILQ_EMPTY(&reversed_commits)) {
4348 qid = STAILQ_FIRST(&reversed_commits);
4349 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4350 got_object_qid_free(qid);
4352 TAILQ_FOREACH(pe, &changed_paths, entry) {
4353 free((char *)pe->path);
4354 free(pe->data);
4356 got_pathlist_free(&changed_paths);
4357 if (search_pattern)
4358 regfree(&regex);
4359 got_commit_graph_close(graph);
4360 return err;
4363 __dead static void
4364 usage_log(void)
4366 fprintf(stderr, "usage: %s log [-bPpRs] [-C number] [-c commit] [-l N] "
4367 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4368 getprogname());
4369 exit(1);
4372 static int
4373 get_default_log_limit(void)
4375 const char *got_default_log_limit;
4376 long long n;
4377 const char *errstr;
4379 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4380 if (got_default_log_limit == NULL)
4381 return 0;
4382 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4383 if (errstr != NULL)
4384 return 0;
4385 return n;
4388 static const struct got_error *
4389 cmd_log(int argc, char *argv[])
4391 const struct got_error *error;
4392 struct got_repository *repo = NULL;
4393 struct got_worktree *worktree = NULL;
4394 struct got_object_id *start_id = NULL, *end_id = NULL;
4395 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4396 const char *start_commit = NULL, *end_commit = NULL;
4397 const char *search_pattern = NULL;
4398 int diff_context = -1, ch;
4399 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4400 int reverse_display_order = 0, one_line = 0;
4401 const char *errstr;
4402 struct got_reflist_head refs;
4403 struct got_reflist_object_id_map *refs_idmap = NULL;
4404 FILE *tmpfile = NULL;
4405 int *pack_fds = NULL;
4407 TAILQ_INIT(&refs);
4409 #ifndef PROFILE
4410 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4411 NULL)
4412 == -1)
4413 err(1, "pledge");
4414 #endif
4416 limit = get_default_log_limit();
4418 while ((ch = getopt(argc, argv, "bC:c:l:PpRr:S:sx:")) != -1) {
4419 switch (ch) {
4420 case 'b':
4421 log_branches = 1;
4422 break;
4423 case 'C':
4424 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4425 &errstr);
4426 if (errstr != NULL)
4427 errx(1, "number of context lines is %s: %s",
4428 errstr, optarg);
4429 break;
4430 case 'c':
4431 start_commit = optarg;
4432 break;
4433 case 'l':
4434 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4435 if (errstr != NULL)
4436 errx(1, "number of commits is %s: %s",
4437 errstr, optarg);
4438 break;
4439 case 'P':
4440 show_changed_paths = 1;
4441 break;
4442 case 'p':
4443 show_patch = 1;
4444 break;
4445 case 'R':
4446 reverse_display_order = 1;
4447 break;
4448 case 'r':
4449 repo_path = realpath(optarg, NULL);
4450 if (repo_path == NULL)
4451 return got_error_from_errno2("realpath",
4452 optarg);
4453 got_path_strip_trailing_slashes(repo_path);
4454 break;
4455 case 'S':
4456 search_pattern = optarg;
4457 break;
4458 case 's':
4459 one_line = 1;
4460 break;
4461 case 'x':
4462 end_commit = optarg;
4463 break;
4464 default:
4465 usage_log();
4466 /* NOTREACHED */
4470 argc -= optind;
4471 argv += optind;
4473 if (diff_context == -1)
4474 diff_context = 3;
4475 else if (!show_patch)
4476 errx(1, "-C requires -p");
4478 if (one_line && (show_patch || show_changed_paths))
4479 errx(1, "cannot use -s with -p or -P");
4481 cwd = getcwd(NULL, 0);
4482 if (cwd == NULL) {
4483 error = got_error_from_errno("getcwd");
4484 goto done;
4487 error = got_repo_pack_fds_open(&pack_fds);
4488 if (error != NULL)
4489 goto done;
4491 if (repo_path == NULL) {
4492 error = got_worktree_open(&worktree, cwd);
4493 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4494 goto done;
4495 error = NULL;
4498 if (argc == 1) {
4499 if (worktree) {
4500 error = got_worktree_resolve_path(&path, worktree,
4501 argv[0]);
4502 if (error)
4503 goto done;
4504 } else {
4505 path = strdup(argv[0]);
4506 if (path == NULL) {
4507 error = got_error_from_errno("strdup");
4508 goto done;
4511 } else if (argc != 0)
4512 usage_log();
4514 if (repo_path == NULL) {
4515 repo_path = worktree ?
4516 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4518 if (repo_path == NULL) {
4519 error = got_error_from_errno("strdup");
4520 goto done;
4523 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4524 if (error != NULL)
4525 goto done;
4527 error = apply_unveil(got_repo_get_path(repo), 1,
4528 worktree ? got_worktree_get_root_path(worktree) : NULL);
4529 if (error)
4530 goto done;
4532 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4533 if (error)
4534 goto done;
4536 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4537 if (error)
4538 goto done;
4540 if (start_commit == NULL) {
4541 struct got_reference *head_ref;
4542 struct got_commit_object *commit = NULL;
4543 error = got_ref_open(&head_ref, repo,
4544 worktree ? got_worktree_get_head_ref_name(worktree)
4545 : GOT_REF_HEAD, 0);
4546 if (error != NULL)
4547 goto done;
4548 error = got_ref_resolve(&start_id, repo, head_ref);
4549 got_ref_close(head_ref);
4550 if (error != NULL)
4551 goto done;
4552 error = got_object_open_as_commit(&commit, repo,
4553 start_id);
4554 if (error != NULL)
4555 goto done;
4556 got_object_commit_close(commit);
4557 } else {
4558 error = got_repo_match_object_id(&start_id, NULL,
4559 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4560 if (error != NULL)
4561 goto done;
4563 if (end_commit != NULL) {
4564 error = got_repo_match_object_id(&end_id, NULL,
4565 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4566 if (error != NULL)
4567 goto done;
4570 if (worktree) {
4572 * If a path was specified on the command line it was resolved
4573 * to a path in the work tree above. Prepend the work tree's
4574 * path prefix to obtain the corresponding in-repository path.
4576 if (path) {
4577 const char *prefix;
4578 prefix = got_worktree_get_path_prefix(worktree);
4579 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4580 (path[0] != '\0') ? "/" : "", path) == -1) {
4581 error = got_error_from_errno("asprintf");
4582 goto done;
4585 } else
4586 error = got_repo_map_path(&in_repo_path, repo,
4587 path ? path : "");
4588 if (error != NULL)
4589 goto done;
4590 if (in_repo_path) {
4591 free(path);
4592 path = in_repo_path;
4595 if (worktree) {
4596 /* Release work tree lock. */
4597 got_worktree_close(worktree);
4598 worktree = NULL;
4601 if (search_pattern && show_patch) {
4602 tmpfile = got_opentemp();
4603 if (tmpfile == NULL) {
4604 error = got_error_from_errno("got_opentemp");
4605 goto done;
4609 error = print_commits(start_id, end_id, repo, path ? path : "",
4610 show_changed_paths, show_patch, search_pattern, diff_context,
4611 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4612 tmpfile);
4613 done:
4614 free(path);
4615 free(repo_path);
4616 free(cwd);
4617 if (worktree)
4618 got_worktree_close(worktree);
4619 if (repo) {
4620 const struct got_error *close_err = got_repo_close(repo);
4621 if (error == NULL)
4622 error = close_err;
4624 if (pack_fds) {
4625 const struct got_error *pack_err =
4626 got_repo_pack_fds_close(pack_fds);
4627 if (error == NULL)
4628 error = pack_err;
4630 if (refs_idmap)
4631 got_reflist_object_id_map_free(refs_idmap);
4632 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4633 error = got_error_from_errno("fclose");
4634 got_ref_list_free(&refs);
4635 return error;
4638 __dead static void
4639 usage_diff(void)
4641 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4642 "[-r repository-path] [object1 object2 | path ...]\n",
4643 getprogname());
4644 exit(1);
4647 struct print_diff_arg {
4648 struct got_repository *repo;
4649 struct got_worktree *worktree;
4650 int diff_context;
4651 const char *id_str;
4652 int header_shown;
4653 int diff_staged;
4654 enum got_diff_algorithm diff_algo;
4655 int ignore_whitespace;
4656 int force_text_diff;
4657 FILE *f1;
4658 FILE *f2;
4662 * Create a file which contains the target path of a symlink so we can feed
4663 * it as content to the diff engine.
4665 static const struct got_error *
4666 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4667 const char *abspath)
4669 const struct got_error *err = NULL;
4670 char target_path[PATH_MAX];
4671 ssize_t target_len, outlen;
4673 *fd = -1;
4675 if (dirfd != -1) {
4676 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4677 if (target_len == -1)
4678 return got_error_from_errno2("readlinkat", abspath);
4679 } else {
4680 target_len = readlink(abspath, target_path, PATH_MAX);
4681 if (target_len == -1)
4682 return got_error_from_errno2("readlink", abspath);
4685 *fd = got_opentempfd();
4686 if (*fd == -1)
4687 return got_error_from_errno("got_opentempfd");
4689 outlen = write(*fd, target_path, target_len);
4690 if (outlen == -1) {
4691 err = got_error_from_errno("got_opentempfd");
4692 goto done;
4695 if (lseek(*fd, 0, SEEK_SET) == -1) {
4696 err = got_error_from_errno2("lseek", abspath);
4697 goto done;
4699 done:
4700 if (err) {
4701 close(*fd);
4702 *fd = -1;
4704 return err;
4707 static const struct got_error *
4708 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4709 const char *path, struct got_object_id *blob_id,
4710 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4711 int dirfd, const char *de_name)
4713 struct print_diff_arg *a = arg;
4714 const struct got_error *err = NULL;
4715 struct got_blob_object *blob1 = NULL;
4716 int fd = -1, fd1 = -1, fd2 = -1;
4717 FILE *f2 = NULL;
4718 char *abspath = NULL, *label1 = NULL;
4719 struct stat sb;
4720 off_t size1 = 0;
4721 int f2_exists = 0;
4723 memset(&sb, 0, sizeof(sb));
4725 if (a->diff_staged) {
4726 if (staged_status != GOT_STATUS_MODIFY &&
4727 staged_status != GOT_STATUS_ADD &&
4728 staged_status != GOT_STATUS_DELETE)
4729 return NULL;
4730 } else {
4731 if (staged_status == GOT_STATUS_DELETE)
4732 return NULL;
4733 if (status == GOT_STATUS_NONEXISTENT)
4734 return got_error_set_errno(ENOENT, path);
4735 if (status != GOT_STATUS_MODIFY &&
4736 status != GOT_STATUS_ADD &&
4737 status != GOT_STATUS_DELETE &&
4738 status != GOT_STATUS_CONFLICT)
4739 return NULL;
4742 err = got_opentemp_truncate(a->f1);
4743 if (err)
4744 return got_error_from_errno("got_opentemp_truncate");
4745 err = got_opentemp_truncate(a->f2);
4746 if (err)
4747 return got_error_from_errno("got_opentemp_truncate");
4749 if (!a->header_shown) {
4750 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4751 got_worktree_get_root_path(a->worktree));
4752 printf("commit - %s\n", a->id_str);
4753 printf("path + %s%s\n",
4754 got_worktree_get_root_path(a->worktree),
4755 a->diff_staged ? " (staged changes)" : "");
4756 a->header_shown = 1;
4759 if (a->diff_staged) {
4760 const char *label1 = NULL, *label2 = NULL;
4761 switch (staged_status) {
4762 case GOT_STATUS_MODIFY:
4763 label1 = path;
4764 label2 = path;
4765 break;
4766 case GOT_STATUS_ADD:
4767 label2 = path;
4768 break;
4769 case GOT_STATUS_DELETE:
4770 label1 = path;
4771 break;
4772 default:
4773 return got_error(GOT_ERR_FILE_STATUS);
4775 fd1 = got_opentempfd();
4776 if (fd1 == -1) {
4777 err = got_error_from_errno("got_opentempfd");
4778 goto done;
4780 fd2 = got_opentempfd();
4781 if (fd2 == -1) {
4782 err = got_error_from_errno("got_opentempfd");
4783 goto done;
4785 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4786 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4787 a->diff_algo, a->diff_context, a->ignore_whitespace,
4788 a->force_text_diff, a->repo, stdout);
4789 goto done;
4792 fd1 = got_opentempfd();
4793 if (fd1 == -1) {
4794 err = got_error_from_errno("got_opentempfd");
4795 goto done;
4798 if (staged_status == GOT_STATUS_ADD ||
4799 staged_status == GOT_STATUS_MODIFY) {
4800 char *id_str;
4801 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4802 8192, fd1);
4803 if (err)
4804 goto done;
4805 err = got_object_id_str(&id_str, staged_blob_id);
4806 if (err)
4807 goto done;
4808 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4809 err = got_error_from_errno("asprintf");
4810 free(id_str);
4811 goto done;
4813 free(id_str);
4814 } else if (status != GOT_STATUS_ADD) {
4815 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4816 fd1);
4817 if (err)
4818 goto done;
4821 if (status != GOT_STATUS_DELETE) {
4822 if (asprintf(&abspath, "%s/%s",
4823 got_worktree_get_root_path(a->worktree), path) == -1) {
4824 err = got_error_from_errno("asprintf");
4825 goto done;
4828 if (dirfd != -1) {
4829 fd = openat(dirfd, de_name,
4830 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4831 if (fd == -1) {
4832 if (!got_err_open_nofollow_on_symlink()) {
4833 err = got_error_from_errno2("openat",
4834 abspath);
4835 goto done;
4837 err = get_symlink_target_file(&fd, dirfd,
4838 de_name, abspath);
4839 if (err)
4840 goto done;
4842 } else {
4843 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4844 if (fd == -1) {
4845 if (!got_err_open_nofollow_on_symlink()) {
4846 err = got_error_from_errno2("open",
4847 abspath);
4848 goto done;
4850 err = get_symlink_target_file(&fd, dirfd,
4851 de_name, abspath);
4852 if (err)
4853 goto done;
4856 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4857 err = got_error_from_errno2("fstatat", abspath);
4858 goto done;
4860 f2 = fdopen(fd, "r");
4861 if (f2 == NULL) {
4862 err = got_error_from_errno2("fdopen", abspath);
4863 goto done;
4865 fd = -1;
4866 f2_exists = 1;
4869 if (blob1) {
4870 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4871 a->f1, blob1);
4872 if (err)
4873 goto done;
4876 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4877 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4878 a->ignore_whitespace, a->force_text_diff, stdout);
4879 done:
4880 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4881 err = got_error_from_errno("close");
4882 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4883 err = got_error_from_errno("close");
4884 if (blob1)
4885 got_object_blob_close(blob1);
4886 if (fd != -1 && close(fd) == -1 && err == NULL)
4887 err = got_error_from_errno("close");
4888 if (f2 && fclose(f2) == EOF && err == NULL)
4889 err = got_error_from_errno("fclose");
4890 free(abspath);
4891 return err;
4894 static const struct got_error *
4895 cmd_diff(int argc, char *argv[])
4897 const struct got_error *error;
4898 struct got_repository *repo = NULL;
4899 struct got_worktree *worktree = NULL;
4900 char *cwd = NULL, *repo_path = NULL;
4901 const char *commit_args[2] = { NULL, NULL };
4902 int ncommit_args = 0;
4903 struct got_object_id *ids[2] = { NULL, NULL };
4904 char *labels[2] = { NULL, NULL };
4905 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4906 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4907 int force_text_diff = 0, force_path = 0, rflag = 0;
4908 const char *errstr;
4909 struct got_reflist_head refs;
4910 struct got_pathlist_head paths;
4911 struct got_pathlist_entry *pe;
4912 FILE *f1 = NULL, *f2 = NULL;
4913 int fd1 = -1, fd2 = -1;
4914 int *pack_fds = NULL;
4916 TAILQ_INIT(&refs);
4917 TAILQ_INIT(&paths);
4919 #ifndef PROFILE
4920 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4921 NULL) == -1)
4922 err(1, "pledge");
4923 #endif
4925 while ((ch = getopt(argc, argv, "aC:c:Pr:sw")) != -1) {
4926 switch (ch) {
4927 case 'a':
4928 force_text_diff = 1;
4929 break;
4930 case 'C':
4931 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4932 &errstr);
4933 if (errstr != NULL)
4934 errx(1, "number of context lines is %s: %s",
4935 errstr, optarg);
4936 break;
4937 case 'c':
4938 if (ncommit_args >= 2)
4939 errx(1, "too many -c options used");
4940 commit_args[ncommit_args++] = optarg;
4941 break;
4942 case 'P':
4943 force_path = 1;
4944 break;
4945 case 'r':
4946 repo_path = realpath(optarg, NULL);
4947 if (repo_path == NULL)
4948 return got_error_from_errno2("realpath",
4949 optarg);
4950 got_path_strip_trailing_slashes(repo_path);
4951 rflag = 1;
4952 break;
4953 case 's':
4954 diff_staged = 1;
4955 break;
4956 case 'w':
4957 ignore_whitespace = 1;
4958 break;
4959 default:
4960 usage_diff();
4961 /* NOTREACHED */
4965 argc -= optind;
4966 argv += optind;
4968 cwd = getcwd(NULL, 0);
4969 if (cwd == NULL) {
4970 error = got_error_from_errno("getcwd");
4971 goto done;
4974 error = got_repo_pack_fds_open(&pack_fds);
4975 if (error != NULL)
4976 goto done;
4978 if (repo_path == NULL) {
4979 error = got_worktree_open(&worktree, cwd);
4980 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4981 goto done;
4982 else
4983 error = NULL;
4984 if (worktree) {
4985 repo_path =
4986 strdup(got_worktree_get_repo_path(worktree));
4987 if (repo_path == NULL) {
4988 error = got_error_from_errno("strdup");
4989 goto done;
4991 } else {
4992 repo_path = strdup(cwd);
4993 if (repo_path == NULL) {
4994 error = got_error_from_errno("strdup");
4995 goto done;
5000 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5001 free(repo_path);
5002 if (error != NULL)
5003 goto done;
5005 if (rflag || worktree == NULL || ncommit_args > 0) {
5006 if (force_path) {
5007 error = got_error_msg(GOT_ERR_NOT_IMPL,
5008 "-P option can only be used when diffing "
5009 "a work tree");
5010 goto done;
5012 if (diff_staged) {
5013 error = got_error_msg(GOT_ERR_NOT_IMPL,
5014 "-s option can only be used when diffing "
5015 "a work tree");
5016 goto done;
5020 error = apply_unveil(got_repo_get_path(repo), 1,
5021 worktree ? got_worktree_get_root_path(worktree) : NULL);
5022 if (error)
5023 goto done;
5025 if ((!force_path && argc == 2) || ncommit_args > 0) {
5026 int obj_type = (ncommit_args > 0 ?
5027 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5028 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5029 NULL);
5030 if (error)
5031 goto done;
5032 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5033 const char *arg;
5034 if (ncommit_args > 0)
5035 arg = commit_args[i];
5036 else
5037 arg = argv[i];
5038 error = got_repo_match_object_id(&ids[i], &labels[i],
5039 arg, obj_type, &refs, repo);
5040 if (error) {
5041 if (error->code != GOT_ERR_NOT_REF &&
5042 error->code != GOT_ERR_NO_OBJ)
5043 goto done;
5044 if (ncommit_args > 0)
5045 goto done;
5046 error = NULL;
5047 break;
5052 f1 = got_opentemp();
5053 if (f1 == NULL) {
5054 error = got_error_from_errno("got_opentemp");
5055 goto done;
5058 f2 = got_opentemp();
5059 if (f2 == NULL) {
5060 error = got_error_from_errno("got_opentemp");
5061 goto done;
5064 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5065 struct print_diff_arg arg;
5066 char *id_str;
5068 if (worktree == NULL) {
5069 if (argc == 2 && ids[0] == NULL) {
5070 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5071 goto done;
5072 } else if (argc == 2 && ids[1] == NULL) {
5073 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5074 goto done;
5075 } else if (argc > 0) {
5076 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5077 "%s", "specified paths cannot be resolved");
5078 goto done;
5079 } else {
5080 error = got_error(GOT_ERR_NOT_WORKTREE);
5081 goto done;
5085 error = get_worktree_paths_from_argv(&paths, argc, argv,
5086 worktree);
5087 if (error)
5088 goto done;
5090 error = got_object_id_str(&id_str,
5091 got_worktree_get_base_commit_id(worktree));
5092 if (error)
5093 goto done;
5094 arg.repo = repo;
5095 arg.worktree = worktree;
5096 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5097 arg.diff_context = diff_context;
5098 arg.id_str = id_str;
5099 arg.header_shown = 0;
5100 arg.diff_staged = diff_staged;
5101 arg.ignore_whitespace = ignore_whitespace;
5102 arg.force_text_diff = force_text_diff;
5103 arg.f1 = f1;
5104 arg.f2 = f2;
5106 error = got_worktree_status(worktree, &paths, repo, 0,
5107 print_diff, &arg, check_cancelled, NULL);
5108 free(id_str);
5109 goto done;
5112 if (ncommit_args == 1) {
5113 struct got_commit_object *commit;
5114 error = got_object_open_as_commit(&commit, repo, ids[0]);
5115 if (error)
5116 goto done;
5118 labels[1] = labels[0];
5119 ids[1] = ids[0];
5120 if (got_object_commit_get_nparents(commit) > 0) {
5121 const struct got_object_id_queue *pids;
5122 struct got_object_qid *pid;
5123 pids = got_object_commit_get_parent_ids(commit);
5124 pid = STAILQ_FIRST(pids);
5125 ids[0] = got_object_id_dup(&pid->id);
5126 if (ids[0] == NULL) {
5127 error = got_error_from_errno(
5128 "got_object_id_dup");
5129 got_object_commit_close(commit);
5130 goto done;
5132 error = got_object_id_str(&labels[0], ids[0]);
5133 if (error) {
5134 got_object_commit_close(commit);
5135 goto done;
5137 } else {
5138 ids[0] = NULL;
5139 labels[0] = strdup("/dev/null");
5140 if (labels[0] == NULL) {
5141 error = got_error_from_errno("strdup");
5142 got_object_commit_close(commit);
5143 goto done;
5147 got_object_commit_close(commit);
5150 if (ncommit_args == 0 && argc > 2) {
5151 error = got_error_msg(GOT_ERR_BAD_PATH,
5152 "path arguments cannot be used when diffing two objects");
5153 goto done;
5156 if (ids[0]) {
5157 error = got_object_get_type(&type1, repo, ids[0]);
5158 if (error)
5159 goto done;
5162 error = got_object_get_type(&type2, repo, ids[1]);
5163 if (error)
5164 goto done;
5165 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5166 error = got_error(GOT_ERR_OBJ_TYPE);
5167 goto done;
5169 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5170 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5171 "path arguments cannot be used when diffing blobs");
5172 goto done;
5175 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5176 char *in_repo_path;
5177 struct got_pathlist_entry *new;
5178 if (worktree) {
5179 const char *prefix;
5180 char *p;
5181 error = got_worktree_resolve_path(&p, worktree,
5182 argv[i]);
5183 if (error)
5184 goto done;
5185 prefix = got_worktree_get_path_prefix(worktree);
5186 while (prefix[0] == '/')
5187 prefix++;
5188 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5189 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5190 p) == -1) {
5191 error = got_error_from_errno("asprintf");
5192 free(p);
5193 goto done;
5195 free(p);
5196 } else {
5197 char *mapped_path, *s;
5198 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5199 if (error)
5200 goto done;
5201 s = mapped_path;
5202 while (s[0] == '/')
5203 s++;
5204 in_repo_path = strdup(s);
5205 if (in_repo_path == NULL) {
5206 error = got_error_from_errno("asprintf");
5207 free(mapped_path);
5208 goto done;
5210 free(mapped_path);
5213 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5214 if (error || new == NULL /* duplicate */)
5215 free(in_repo_path);
5216 if (error)
5217 goto done;
5220 if (worktree) {
5221 /* Release work tree lock. */
5222 got_worktree_close(worktree);
5223 worktree = NULL;
5226 fd1 = got_opentempfd();
5227 if (fd1 == -1) {
5228 error = got_error_from_errno("got_opentempfd");
5229 goto done;
5232 fd2 = got_opentempfd();
5233 if (fd2 == -1) {
5234 error = got_error_from_errno("got_opentempfd");
5235 goto done;
5238 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5239 case GOT_OBJ_TYPE_BLOB:
5240 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5241 fd1, fd2, ids[0], ids[1], NULL, NULL,
5242 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5243 ignore_whitespace, force_text_diff, repo, stdout);
5244 break;
5245 case GOT_OBJ_TYPE_TREE:
5246 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5247 ids[0], ids[1], &paths, "", "",
5248 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5249 ignore_whitespace, force_text_diff, repo, stdout);
5250 break;
5251 case GOT_OBJ_TYPE_COMMIT:
5252 printf("diff %s %s\n", labels[0], labels[1]);
5253 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5254 fd1, fd2, ids[0], ids[1], &paths,
5255 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5256 ignore_whitespace, force_text_diff, repo, stdout);
5257 break;
5258 default:
5259 error = got_error(GOT_ERR_OBJ_TYPE);
5261 done:
5262 free(labels[0]);
5263 free(labels[1]);
5264 free(ids[0]);
5265 free(ids[1]);
5266 if (worktree)
5267 got_worktree_close(worktree);
5268 if (repo) {
5269 const struct got_error *close_err = got_repo_close(repo);
5270 if (error == NULL)
5271 error = close_err;
5273 if (pack_fds) {
5274 const struct got_error *pack_err =
5275 got_repo_pack_fds_close(pack_fds);
5276 if (error == NULL)
5277 error = pack_err;
5279 TAILQ_FOREACH(pe, &paths, entry)
5280 free((char *)pe->path);
5281 got_pathlist_free(&paths);
5282 got_ref_list_free(&refs);
5283 if (f1 && fclose(f1) == EOF && error == NULL)
5284 error = got_error_from_errno("fclose");
5285 if (f2 && fclose(f2) == EOF && error == NULL)
5286 error = got_error_from_errno("fclose");
5287 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5288 error = got_error_from_errno("close");
5289 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5290 error = got_error_from_errno("close");
5291 return error;
5294 __dead static void
5295 usage_blame(void)
5297 fprintf(stderr,
5298 "usage: %s blame [-c commit] [-r repository-path] path\n",
5299 getprogname());
5300 exit(1);
5303 struct blame_line {
5304 int annotated;
5305 char *id_str;
5306 char *committer;
5307 char datebuf[11]; /* YYYY-MM-DD + NUL */
5310 struct blame_cb_args {
5311 struct blame_line *lines;
5312 int nlines;
5313 int nlines_prec;
5314 int lineno_cur;
5315 off_t *line_offsets;
5316 FILE *f;
5317 struct got_repository *repo;
5320 static const struct got_error *
5321 blame_cb(void *arg, int nlines, int lineno,
5322 struct got_commit_object *commit, struct got_object_id *id)
5324 const struct got_error *err = NULL;
5325 struct blame_cb_args *a = arg;
5326 struct blame_line *bline;
5327 char *line = NULL;
5328 size_t linesize = 0;
5329 off_t offset;
5330 struct tm tm;
5331 time_t committer_time;
5333 if (nlines != a->nlines ||
5334 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5335 return got_error(GOT_ERR_RANGE);
5337 if (sigint_received)
5338 return got_error(GOT_ERR_ITER_COMPLETED);
5340 if (lineno == -1)
5341 return NULL; /* no change in this commit */
5343 /* Annotate this line. */
5344 bline = &a->lines[lineno - 1];
5345 if (bline->annotated)
5346 return NULL;
5347 err = got_object_id_str(&bline->id_str, id);
5348 if (err)
5349 return err;
5351 bline->committer = strdup(got_object_commit_get_committer(commit));
5352 if (bline->committer == NULL) {
5353 err = got_error_from_errno("strdup");
5354 goto done;
5357 committer_time = got_object_commit_get_committer_time(commit);
5358 if (gmtime_r(&committer_time, &tm) == NULL)
5359 return got_error_from_errno("gmtime_r");
5360 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5361 &tm) == 0) {
5362 err = got_error(GOT_ERR_NO_SPACE);
5363 goto done;
5365 bline->annotated = 1;
5367 /* Print lines annotated so far. */
5368 bline = &a->lines[a->lineno_cur - 1];
5369 if (!bline->annotated)
5370 goto done;
5372 offset = a->line_offsets[a->lineno_cur - 1];
5373 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5374 err = got_error_from_errno("fseeko");
5375 goto done;
5378 while (a->lineno_cur <= a->nlines && bline->annotated) {
5379 char *smallerthan, *at, *nl, *committer;
5380 size_t len;
5382 if (getline(&line, &linesize, a->f) == -1) {
5383 if (ferror(a->f))
5384 err = got_error_from_errno("getline");
5385 break;
5388 committer = bline->committer;
5389 smallerthan = strchr(committer, '<');
5390 if (smallerthan && smallerthan[1] != '\0')
5391 committer = smallerthan + 1;
5392 at = strchr(committer, '@');
5393 if (at)
5394 *at = '\0';
5395 len = strlen(committer);
5396 if (len >= 9)
5397 committer[8] = '\0';
5399 nl = strchr(line, '\n');
5400 if (nl)
5401 *nl = '\0';
5402 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5403 bline->id_str, bline->datebuf, committer, line);
5405 a->lineno_cur++;
5406 bline = &a->lines[a->lineno_cur - 1];
5408 done:
5409 free(line);
5410 return err;
5413 static const struct got_error *
5414 cmd_blame(int argc, char *argv[])
5416 const struct got_error *error;
5417 struct got_repository *repo = NULL;
5418 struct got_worktree *worktree = NULL;
5419 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5420 char *link_target = NULL;
5421 struct got_object_id *obj_id = NULL;
5422 struct got_object_id *commit_id = NULL;
5423 struct got_commit_object *commit = NULL;
5424 struct got_blob_object *blob = NULL;
5425 char *commit_id_str = NULL;
5426 struct blame_cb_args bca;
5427 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5428 off_t filesize;
5429 int *pack_fds = NULL;
5430 FILE *f1 = NULL, *f2 = NULL;
5432 fd1 = got_opentempfd();
5433 if (fd1 == -1)
5434 return got_error_from_errno("got_opentempfd");
5436 memset(&bca, 0, sizeof(bca));
5438 #ifndef PROFILE
5439 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5440 NULL) == -1)
5441 err(1, "pledge");
5442 #endif
5444 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5445 switch (ch) {
5446 case 'c':
5447 commit_id_str = optarg;
5448 break;
5449 case 'r':
5450 repo_path = realpath(optarg, NULL);
5451 if (repo_path == NULL)
5452 return got_error_from_errno2("realpath",
5453 optarg);
5454 got_path_strip_trailing_slashes(repo_path);
5455 break;
5456 default:
5457 usage_blame();
5458 /* NOTREACHED */
5462 argc -= optind;
5463 argv += optind;
5465 if (argc == 1)
5466 path = argv[0];
5467 else
5468 usage_blame();
5470 cwd = getcwd(NULL, 0);
5471 if (cwd == NULL) {
5472 error = got_error_from_errno("getcwd");
5473 goto done;
5476 error = got_repo_pack_fds_open(&pack_fds);
5477 if (error != NULL)
5478 goto done;
5480 if (repo_path == NULL) {
5481 error = got_worktree_open(&worktree, cwd);
5482 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5483 goto done;
5484 else
5485 error = NULL;
5486 if (worktree) {
5487 repo_path =
5488 strdup(got_worktree_get_repo_path(worktree));
5489 if (repo_path == NULL) {
5490 error = got_error_from_errno("strdup");
5491 if (error)
5492 goto done;
5494 } else {
5495 repo_path = strdup(cwd);
5496 if (repo_path == NULL) {
5497 error = got_error_from_errno("strdup");
5498 goto done;
5503 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5504 if (error != NULL)
5505 goto done;
5507 if (worktree) {
5508 const char *prefix = got_worktree_get_path_prefix(worktree);
5509 char *p;
5511 error = got_worktree_resolve_path(&p, worktree, path);
5512 if (error)
5513 goto done;
5514 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5515 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5516 p) == -1) {
5517 error = got_error_from_errno("asprintf");
5518 free(p);
5519 goto done;
5521 free(p);
5522 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5523 } else {
5524 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5525 if (error)
5526 goto done;
5527 error = got_repo_map_path(&in_repo_path, repo, path);
5529 if (error)
5530 goto done;
5532 if (commit_id_str == NULL) {
5533 struct got_reference *head_ref;
5534 error = got_ref_open(&head_ref, repo, worktree ?
5535 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5536 if (error != NULL)
5537 goto done;
5538 error = got_ref_resolve(&commit_id, repo, head_ref);
5539 got_ref_close(head_ref);
5540 if (error != NULL)
5541 goto done;
5542 } else {
5543 struct got_reflist_head refs;
5544 TAILQ_INIT(&refs);
5545 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5546 NULL);
5547 if (error)
5548 goto done;
5549 error = got_repo_match_object_id(&commit_id, NULL,
5550 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5551 got_ref_list_free(&refs);
5552 if (error)
5553 goto done;
5556 if (worktree) {
5557 /* Release work tree lock. */
5558 got_worktree_close(worktree);
5559 worktree = NULL;
5562 error = got_object_open_as_commit(&commit, repo, commit_id);
5563 if (error)
5564 goto done;
5566 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5567 commit, repo);
5568 if (error)
5569 goto done;
5571 error = got_object_id_by_path(&obj_id, repo, commit,
5572 link_target ? link_target : in_repo_path);
5573 if (error)
5574 goto done;
5576 error = got_object_get_type(&obj_type, repo, obj_id);
5577 if (error)
5578 goto done;
5580 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5581 error = got_error_path(link_target ? link_target : in_repo_path,
5582 GOT_ERR_OBJ_TYPE);
5583 goto done;
5586 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5587 if (error)
5588 goto done;
5589 bca.f = got_opentemp();
5590 if (bca.f == NULL) {
5591 error = got_error_from_errno("got_opentemp");
5592 goto done;
5594 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5595 &bca.line_offsets, bca.f, blob);
5596 if (error || bca.nlines == 0)
5597 goto done;
5599 /* Don't include \n at EOF in the blame line count. */
5600 if (bca.line_offsets[bca.nlines - 1] == filesize)
5601 bca.nlines--;
5603 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5604 if (bca.lines == NULL) {
5605 error = got_error_from_errno("calloc");
5606 goto done;
5608 bca.lineno_cur = 1;
5609 bca.nlines_prec = 0;
5610 i = bca.nlines;
5611 while (i > 0) {
5612 i /= 10;
5613 bca.nlines_prec++;
5615 bca.repo = repo;
5617 fd2 = got_opentempfd();
5618 if (fd2 == -1) {
5619 error = got_error_from_errno("got_opentempfd");
5620 goto done;
5622 fd3 = got_opentempfd();
5623 if (fd3 == -1) {
5624 error = got_error_from_errno("got_opentempfd");
5625 goto done;
5627 f1 = got_opentemp();
5628 if (f1 == NULL) {
5629 error = got_error_from_errno("got_opentemp");
5630 goto done;
5632 f2 = got_opentemp();
5633 if (f2 == NULL) {
5634 error = got_error_from_errno("got_opentemp");
5635 goto done;
5637 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5638 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5639 check_cancelled, NULL, fd2, fd3, f1, f2);
5640 done:
5641 free(in_repo_path);
5642 free(link_target);
5643 free(repo_path);
5644 free(cwd);
5645 free(commit_id);
5646 free(obj_id);
5647 if (commit)
5648 got_object_commit_close(commit);
5650 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5651 error = got_error_from_errno("close");
5652 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5653 error = got_error_from_errno("close");
5654 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5655 error = got_error_from_errno("close");
5656 if (f1 && fclose(f1) == EOF && error == NULL)
5657 error = got_error_from_errno("fclose");
5658 if (f2 && fclose(f2) == EOF && error == NULL)
5659 error = got_error_from_errno("fclose");
5661 if (blob)
5662 got_object_blob_close(blob);
5663 if (worktree)
5664 got_worktree_close(worktree);
5665 if (repo) {
5666 const struct got_error *close_err = got_repo_close(repo);
5667 if (error == NULL)
5668 error = close_err;
5670 if (pack_fds) {
5671 const struct got_error *pack_err =
5672 got_repo_pack_fds_close(pack_fds);
5673 if (error == NULL)
5674 error = pack_err;
5676 if (bca.lines) {
5677 for (i = 0; i < bca.nlines; i++) {
5678 struct blame_line *bline = &bca.lines[i];
5679 free(bline->id_str);
5680 free(bline->committer);
5682 free(bca.lines);
5684 free(bca.line_offsets);
5685 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5686 error = got_error_from_errno("fclose");
5687 return error;
5690 __dead static void
5691 usage_tree(void)
5693 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5694 "[path]\n", getprogname());
5695 exit(1);
5698 static const struct got_error *
5699 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5700 const char *root_path, struct got_repository *repo)
5702 const struct got_error *err = NULL;
5703 int is_root_path = (strcmp(path, root_path) == 0);
5704 const char *modestr = "";
5705 mode_t mode = got_tree_entry_get_mode(te);
5706 char *link_target = NULL;
5708 path += strlen(root_path);
5709 while (path[0] == '/')
5710 path++;
5712 if (got_object_tree_entry_is_submodule(te))
5713 modestr = "$";
5714 else if (S_ISLNK(mode)) {
5715 int i;
5717 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5718 if (err)
5719 return err;
5720 for (i = 0; i < strlen(link_target); i++) {
5721 if (!isprint((unsigned char)link_target[i]))
5722 link_target[i] = '?';
5725 modestr = "@";
5727 else if (S_ISDIR(mode))
5728 modestr = "/";
5729 else if (mode & S_IXUSR)
5730 modestr = "*";
5732 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5733 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5734 link_target ? " -> ": "", link_target ? link_target : "");
5736 free(link_target);
5737 return NULL;
5740 static const struct got_error *
5741 print_tree(const char *path, struct got_commit_object *commit,
5742 int show_ids, int recurse, const char *root_path,
5743 struct got_repository *repo)
5745 const struct got_error *err = NULL;
5746 struct got_object_id *tree_id = NULL;
5747 struct got_tree_object *tree = NULL;
5748 int nentries, i;
5750 err = got_object_id_by_path(&tree_id, repo, commit, path);
5751 if (err)
5752 goto done;
5754 err = got_object_open_as_tree(&tree, repo, tree_id);
5755 if (err)
5756 goto done;
5757 nentries = got_object_tree_get_nentries(tree);
5758 for (i = 0; i < nentries; i++) {
5759 struct got_tree_entry *te;
5760 char *id = NULL;
5762 if (sigint_received || sigpipe_received)
5763 break;
5765 te = got_object_tree_get_entry(tree, i);
5766 if (show_ids) {
5767 char *id_str;
5768 err = got_object_id_str(&id_str,
5769 got_tree_entry_get_id(te));
5770 if (err)
5771 goto done;
5772 if (asprintf(&id, "%s ", id_str) == -1) {
5773 err = got_error_from_errno("asprintf");
5774 free(id_str);
5775 goto done;
5777 free(id_str);
5779 err = print_entry(te, id, path, root_path, repo);
5780 free(id);
5781 if (err)
5782 goto done;
5784 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5785 char *child_path;
5786 if (asprintf(&child_path, "%s%s%s", path,
5787 path[0] == '/' && path[1] == '\0' ? "" : "/",
5788 got_tree_entry_get_name(te)) == -1) {
5789 err = got_error_from_errno("asprintf");
5790 goto done;
5792 err = print_tree(child_path, commit, show_ids, 1,
5793 root_path, repo);
5794 free(child_path);
5795 if (err)
5796 goto done;
5799 done:
5800 if (tree)
5801 got_object_tree_close(tree);
5802 free(tree_id);
5803 return err;
5806 static const struct got_error *
5807 cmd_tree(int argc, char *argv[])
5809 const struct got_error *error;
5810 struct got_repository *repo = NULL;
5811 struct got_worktree *worktree = NULL;
5812 const char *path, *refname = NULL;
5813 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5814 struct got_object_id *commit_id = NULL;
5815 struct got_commit_object *commit = NULL;
5816 char *commit_id_str = NULL;
5817 int show_ids = 0, recurse = 0;
5818 int ch;
5819 int *pack_fds = NULL;
5821 #ifndef PROFILE
5822 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5823 NULL) == -1)
5824 err(1, "pledge");
5825 #endif
5827 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5828 switch (ch) {
5829 case 'c':
5830 commit_id_str = optarg;
5831 break;
5832 case 'i':
5833 show_ids = 1;
5834 break;
5835 case 'R':
5836 recurse = 1;
5837 break;
5838 case 'r':
5839 repo_path = realpath(optarg, NULL);
5840 if (repo_path == NULL)
5841 return got_error_from_errno2("realpath",
5842 optarg);
5843 got_path_strip_trailing_slashes(repo_path);
5844 break;
5845 default:
5846 usage_tree();
5847 /* NOTREACHED */
5851 argc -= optind;
5852 argv += optind;
5854 if (argc == 1)
5855 path = argv[0];
5856 else if (argc > 1)
5857 usage_tree();
5858 else
5859 path = NULL;
5861 cwd = getcwd(NULL, 0);
5862 if (cwd == NULL) {
5863 error = got_error_from_errno("getcwd");
5864 goto done;
5867 error = got_repo_pack_fds_open(&pack_fds);
5868 if (error != NULL)
5869 goto done;
5871 if (repo_path == NULL) {
5872 error = got_worktree_open(&worktree, cwd);
5873 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5874 goto done;
5875 else
5876 error = NULL;
5877 if (worktree) {
5878 repo_path =
5879 strdup(got_worktree_get_repo_path(worktree));
5880 if (repo_path == NULL)
5881 error = got_error_from_errno("strdup");
5882 if (error)
5883 goto done;
5884 } else {
5885 repo_path = strdup(cwd);
5886 if (repo_path == NULL) {
5887 error = got_error_from_errno("strdup");
5888 goto done;
5893 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5894 if (error != NULL)
5895 goto done;
5897 if (worktree) {
5898 const char *prefix = got_worktree_get_path_prefix(worktree);
5899 char *p;
5901 if (path == NULL)
5902 path = "";
5903 error = got_worktree_resolve_path(&p, worktree, path);
5904 if (error)
5905 goto done;
5906 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5907 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5908 p) == -1) {
5909 error = got_error_from_errno("asprintf");
5910 free(p);
5911 goto done;
5913 free(p);
5914 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5915 if (error)
5916 goto done;
5917 } else {
5918 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5919 if (error)
5920 goto done;
5921 if (path == NULL)
5922 path = "/";
5923 error = got_repo_map_path(&in_repo_path, repo, path);
5924 if (error != NULL)
5925 goto done;
5928 if (commit_id_str == NULL) {
5929 struct got_reference *head_ref;
5930 if (worktree)
5931 refname = got_worktree_get_head_ref_name(worktree);
5932 else
5933 refname = GOT_REF_HEAD;
5934 error = got_ref_open(&head_ref, repo, refname, 0);
5935 if (error != NULL)
5936 goto done;
5937 error = got_ref_resolve(&commit_id, repo, head_ref);
5938 got_ref_close(head_ref);
5939 if (error != NULL)
5940 goto done;
5941 } else {
5942 struct got_reflist_head refs;
5943 TAILQ_INIT(&refs);
5944 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5945 NULL);
5946 if (error)
5947 goto done;
5948 error = got_repo_match_object_id(&commit_id, NULL,
5949 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5950 got_ref_list_free(&refs);
5951 if (error)
5952 goto done;
5955 if (worktree) {
5956 /* Release work tree lock. */
5957 got_worktree_close(worktree);
5958 worktree = NULL;
5961 error = got_object_open_as_commit(&commit, repo, commit_id);
5962 if (error)
5963 goto done;
5965 error = print_tree(in_repo_path, commit, show_ids, recurse,
5966 in_repo_path, repo);
5967 done:
5968 free(in_repo_path);
5969 free(repo_path);
5970 free(cwd);
5971 free(commit_id);
5972 if (commit)
5973 got_object_commit_close(commit);
5974 if (worktree)
5975 got_worktree_close(worktree);
5976 if (repo) {
5977 const struct got_error *close_err = got_repo_close(repo);
5978 if (error == NULL)
5979 error = close_err;
5981 if (pack_fds) {
5982 const struct got_error *pack_err =
5983 got_repo_pack_fds_close(pack_fds);
5984 if (error == NULL)
5985 error = pack_err;
5987 return error;
5990 __dead static void
5991 usage_status(void)
5993 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5994 "[-s status-codes] [path ...]\n", getprogname());
5995 exit(1);
5998 struct got_status_arg {
5999 char *status_codes;
6000 int suppress;
6003 static const struct got_error *
6004 print_status(void *arg, unsigned char status, unsigned char staged_status,
6005 const char *path, struct got_object_id *blob_id,
6006 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6007 int dirfd, const char *de_name)
6009 struct got_status_arg *st = arg;
6011 if (status == staged_status && (status == GOT_STATUS_DELETE))
6012 status = GOT_STATUS_NO_CHANGE;
6013 if (st != NULL && st->status_codes) {
6014 size_t ncodes = strlen(st->status_codes);
6015 int i, j = 0;
6017 for (i = 0; i < ncodes ; i++) {
6018 if (st->suppress) {
6019 if (status == st->status_codes[i] ||
6020 staged_status == st->status_codes[i]) {
6021 j++;
6022 continue;
6024 } else {
6025 if (status == st->status_codes[i] ||
6026 staged_status == st->status_codes[i])
6027 break;
6031 if (st->suppress && j == 0)
6032 goto print;
6034 if (i == ncodes)
6035 return NULL;
6037 print:
6038 printf("%c%c %s\n", status, staged_status, path);
6039 return NULL;
6042 static const struct got_error *
6043 cmd_status(int argc, char *argv[])
6045 const struct got_error *error = NULL;
6046 struct got_repository *repo = NULL;
6047 struct got_worktree *worktree = NULL;
6048 struct got_status_arg st;
6049 char *cwd = NULL;
6050 struct got_pathlist_head paths;
6051 struct got_pathlist_entry *pe;
6052 int ch, i, no_ignores = 0;
6053 int *pack_fds = NULL;
6055 TAILQ_INIT(&paths);
6057 memset(&st, 0, sizeof(st));
6058 st.status_codes = NULL;
6059 st.suppress = 0;
6061 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6062 switch (ch) {
6063 case 'I':
6064 no_ignores = 1;
6065 break;
6066 case 'S':
6067 if (st.status_codes != NULL && st.suppress == 0)
6068 option_conflict('S', 's');
6069 st.suppress = 1;
6070 /* fallthrough */
6071 case 's':
6072 for (i = 0; i < strlen(optarg); i++) {
6073 switch (optarg[i]) {
6074 case GOT_STATUS_MODIFY:
6075 case GOT_STATUS_ADD:
6076 case GOT_STATUS_DELETE:
6077 case GOT_STATUS_CONFLICT:
6078 case GOT_STATUS_MISSING:
6079 case GOT_STATUS_OBSTRUCTED:
6080 case GOT_STATUS_UNVERSIONED:
6081 case GOT_STATUS_MODE_CHANGE:
6082 case GOT_STATUS_NONEXISTENT:
6083 break;
6084 default:
6085 errx(1, "invalid status code '%c'",
6086 optarg[i]);
6089 if (ch == 's' && st.suppress)
6090 option_conflict('s', 'S');
6091 st.status_codes = optarg;
6092 break;
6093 default:
6094 usage_status();
6095 /* NOTREACHED */
6099 argc -= optind;
6100 argv += optind;
6102 #ifndef PROFILE
6103 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6104 NULL) == -1)
6105 err(1, "pledge");
6106 #endif
6107 cwd = getcwd(NULL, 0);
6108 if (cwd == NULL) {
6109 error = got_error_from_errno("getcwd");
6110 goto done;
6113 error = got_repo_pack_fds_open(&pack_fds);
6114 if (error != NULL)
6115 goto done;
6117 error = got_worktree_open(&worktree, cwd);
6118 if (error) {
6119 if (error->code == GOT_ERR_NOT_WORKTREE)
6120 error = wrap_not_worktree_error(error, "status", cwd);
6121 goto done;
6124 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6125 NULL, pack_fds);
6126 if (error != NULL)
6127 goto done;
6129 error = apply_unveil(got_repo_get_path(repo), 1,
6130 got_worktree_get_root_path(worktree));
6131 if (error)
6132 goto done;
6134 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6135 if (error)
6136 goto done;
6138 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6139 print_status, &st, check_cancelled, NULL);
6140 done:
6141 if (pack_fds) {
6142 const struct got_error *pack_err =
6143 got_repo_pack_fds_close(pack_fds);
6144 if (error == NULL)
6145 error = pack_err;
6148 TAILQ_FOREACH(pe, &paths, entry)
6149 free((char *)pe->path);
6150 got_pathlist_free(&paths);
6151 free(cwd);
6152 return error;
6155 __dead static void
6156 usage_ref(void)
6158 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6159 "[-s reference] [name]\n", getprogname());
6160 exit(1);
6163 static const struct got_error *
6164 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6166 static const struct got_error *err = NULL;
6167 struct got_reflist_head refs;
6168 struct got_reflist_entry *re;
6170 TAILQ_INIT(&refs);
6171 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6172 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6173 repo);
6174 if (err)
6175 return err;
6177 TAILQ_FOREACH(re, &refs, entry) {
6178 char *refstr;
6179 refstr = got_ref_to_str(re->ref);
6180 if (refstr == NULL) {
6181 err = got_error_from_errno("got_ref_to_str");
6182 break;
6184 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6185 free(refstr);
6188 got_ref_list_free(&refs);
6189 return err;
6192 static const struct got_error *
6193 delete_ref_by_name(struct got_repository *repo, const char *refname)
6195 const struct got_error *err;
6196 struct got_reference *ref;
6198 err = got_ref_open(&ref, repo, refname, 0);
6199 if (err)
6200 return err;
6202 err = delete_ref(repo, ref);
6203 got_ref_close(ref);
6204 return err;
6207 static const struct got_error *
6208 add_ref(struct got_repository *repo, const char *refname, const char *target)
6210 const struct got_error *err = NULL;
6211 struct got_object_id *id = NULL;
6212 struct got_reference *ref = NULL;
6213 struct got_reflist_head refs;
6216 * Don't let the user create a reference name with a leading '-'.
6217 * While technically a valid reference name, this case is usually
6218 * an unintended typo.
6220 if (refname[0] == '-')
6221 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6223 TAILQ_INIT(&refs);
6224 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6225 if (err)
6226 goto done;
6227 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6228 &refs, repo);
6229 got_ref_list_free(&refs);
6230 if (err)
6231 goto done;
6233 err = got_ref_alloc(&ref, refname, id);
6234 if (err)
6235 goto done;
6237 err = got_ref_write(ref, repo);
6238 done:
6239 if (ref)
6240 got_ref_close(ref);
6241 free(id);
6242 return err;
6245 static const struct got_error *
6246 add_symref(struct got_repository *repo, const char *refname, const char *target)
6248 const struct got_error *err = NULL;
6249 struct got_reference *ref = NULL;
6250 struct got_reference *target_ref = NULL;
6253 * Don't let the user create a reference name with a leading '-'.
6254 * While technically a valid reference name, this case is usually
6255 * an unintended typo.
6257 if (refname[0] == '-')
6258 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6260 err = got_ref_open(&target_ref, repo, target, 0);
6261 if (err)
6262 return err;
6264 err = got_ref_alloc_symref(&ref, refname, target_ref);
6265 if (err)
6266 goto done;
6268 err = got_ref_write(ref, repo);
6269 done:
6270 if (target_ref)
6271 got_ref_close(target_ref);
6272 if (ref)
6273 got_ref_close(ref);
6274 return err;
6277 static const struct got_error *
6278 cmd_ref(int argc, char *argv[])
6280 const struct got_error *error = NULL;
6281 struct got_repository *repo = NULL;
6282 struct got_worktree *worktree = NULL;
6283 char *cwd = NULL, *repo_path = NULL;
6284 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6285 const char *obj_arg = NULL, *symref_target= NULL;
6286 char *refname = NULL;
6287 int *pack_fds = NULL;
6289 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6290 switch (ch) {
6291 case 'c':
6292 obj_arg = optarg;
6293 break;
6294 case 'd':
6295 do_delete = 1;
6296 break;
6297 case 'l':
6298 do_list = 1;
6299 break;
6300 case 'r':
6301 repo_path = realpath(optarg, NULL);
6302 if (repo_path == NULL)
6303 return got_error_from_errno2("realpath",
6304 optarg);
6305 got_path_strip_trailing_slashes(repo_path);
6306 break;
6307 case 's':
6308 symref_target = optarg;
6309 break;
6310 case 't':
6311 sort_by_time = 1;
6312 break;
6313 default:
6314 usage_ref();
6315 /* NOTREACHED */
6319 if (obj_arg && do_list)
6320 option_conflict('c', 'l');
6321 if (obj_arg && do_delete)
6322 option_conflict('c', 'd');
6323 if (obj_arg && symref_target)
6324 option_conflict('c', 's');
6325 if (symref_target && do_delete)
6326 option_conflict('s', 'd');
6327 if (symref_target && do_list)
6328 option_conflict('s', 'l');
6329 if (do_delete && do_list)
6330 option_conflict('d', 'l');
6331 if (sort_by_time && !do_list)
6332 errx(1, "-t option requires -l option");
6334 argc -= optind;
6335 argv += optind;
6337 if (do_list) {
6338 if (argc != 0 && argc != 1)
6339 usage_ref();
6340 if (argc == 1) {
6341 refname = strdup(argv[0]);
6342 if (refname == NULL) {
6343 error = got_error_from_errno("strdup");
6344 goto done;
6347 } else {
6348 if (argc != 1)
6349 usage_ref();
6350 refname = strdup(argv[0]);
6351 if (refname == NULL) {
6352 error = got_error_from_errno("strdup");
6353 goto done;
6357 if (refname)
6358 got_path_strip_trailing_slashes(refname);
6360 #ifndef PROFILE
6361 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6362 "sendfd unveil", NULL) == -1)
6363 err(1, "pledge");
6364 #endif
6365 cwd = getcwd(NULL, 0);
6366 if (cwd == NULL) {
6367 error = got_error_from_errno("getcwd");
6368 goto done;
6371 error = got_repo_pack_fds_open(&pack_fds);
6372 if (error != NULL)
6373 goto done;
6375 if (repo_path == NULL) {
6376 error = got_worktree_open(&worktree, cwd);
6377 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6378 goto done;
6379 else
6380 error = NULL;
6381 if (worktree) {
6382 repo_path =
6383 strdup(got_worktree_get_repo_path(worktree));
6384 if (repo_path == NULL)
6385 error = got_error_from_errno("strdup");
6386 if (error)
6387 goto done;
6388 } else {
6389 repo_path = strdup(cwd);
6390 if (repo_path == NULL) {
6391 error = got_error_from_errno("strdup");
6392 goto done;
6397 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6398 if (error != NULL)
6399 goto done;
6401 #ifndef PROFILE
6402 if (do_list) {
6403 /* Remove "cpath" promise. */
6404 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6405 NULL) == -1)
6406 err(1, "pledge");
6408 #endif
6410 error = apply_unveil(got_repo_get_path(repo), do_list,
6411 worktree ? got_worktree_get_root_path(worktree) : NULL);
6412 if (error)
6413 goto done;
6415 if (do_list)
6416 error = list_refs(repo, refname, sort_by_time);
6417 else if (do_delete)
6418 error = delete_ref_by_name(repo, refname);
6419 else if (symref_target)
6420 error = add_symref(repo, refname, symref_target);
6421 else {
6422 if (obj_arg == NULL)
6423 usage_ref();
6424 error = add_ref(repo, refname, obj_arg);
6426 done:
6427 free(refname);
6428 if (repo) {
6429 const struct got_error *close_err = got_repo_close(repo);
6430 if (error == NULL)
6431 error = close_err;
6433 if (worktree)
6434 got_worktree_close(worktree);
6435 if (pack_fds) {
6436 const struct got_error *pack_err =
6437 got_repo_pack_fds_close(pack_fds);
6438 if (error == NULL)
6439 error = pack_err;
6441 free(cwd);
6442 free(repo_path);
6443 return error;
6446 __dead static void
6447 usage_branch(void)
6449 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6450 "[-r repository-path] [name]\n", getprogname());
6451 exit(1);
6454 static const struct got_error *
6455 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6456 struct got_reference *ref)
6458 const struct got_error *err = NULL;
6459 const char *refname, *marker = " ";
6460 char *refstr;
6462 refname = got_ref_get_name(ref);
6463 if (worktree && strcmp(refname,
6464 got_worktree_get_head_ref_name(worktree)) == 0) {
6465 struct got_object_id *id = NULL;
6467 err = got_ref_resolve(&id, repo, ref);
6468 if (err)
6469 return err;
6470 if (got_object_id_cmp(id,
6471 got_worktree_get_base_commit_id(worktree)) == 0)
6472 marker = "* ";
6473 else
6474 marker = "~ ";
6475 free(id);
6478 if (strncmp(refname, "refs/heads/", 11) == 0)
6479 refname += 11;
6480 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6481 refname += 18;
6482 if (strncmp(refname, "refs/remotes/", 13) == 0)
6483 refname += 13;
6485 refstr = got_ref_to_str(ref);
6486 if (refstr == NULL)
6487 return got_error_from_errno("got_ref_to_str");
6489 printf("%s%s: %s\n", marker, refname, refstr);
6490 free(refstr);
6491 return NULL;
6494 static const struct got_error *
6495 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6497 const char *refname;
6499 if (worktree == NULL)
6500 return got_error(GOT_ERR_NOT_WORKTREE);
6502 refname = got_worktree_get_head_ref_name(worktree);
6504 if (strncmp(refname, "refs/heads/", 11) == 0)
6505 refname += 11;
6506 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6507 refname += 18;
6509 printf("%s\n", refname);
6511 return NULL;
6514 static const struct got_error *
6515 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6516 int sort_by_time)
6518 static const struct got_error *err = NULL;
6519 struct got_reflist_head refs;
6520 struct got_reflist_entry *re;
6521 struct got_reference *temp_ref = NULL;
6522 int rebase_in_progress, histedit_in_progress;
6524 TAILQ_INIT(&refs);
6526 if (worktree) {
6527 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6528 worktree);
6529 if (err)
6530 return err;
6532 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6533 worktree);
6534 if (err)
6535 return err;
6537 if (rebase_in_progress || histedit_in_progress) {
6538 err = got_ref_open(&temp_ref, repo,
6539 got_worktree_get_head_ref_name(worktree), 0);
6540 if (err)
6541 return err;
6542 list_branch(repo, worktree, temp_ref);
6543 got_ref_close(temp_ref);
6547 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6548 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6549 repo);
6550 if (err)
6551 return err;
6553 TAILQ_FOREACH(re, &refs, entry)
6554 list_branch(repo, worktree, re->ref);
6556 got_ref_list_free(&refs);
6558 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6559 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6560 repo);
6561 if (err)
6562 return err;
6564 TAILQ_FOREACH(re, &refs, entry)
6565 list_branch(repo, worktree, re->ref);
6567 got_ref_list_free(&refs);
6569 return NULL;
6572 static const struct got_error *
6573 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6574 const char *branch_name)
6576 const struct got_error *err = NULL;
6577 struct got_reference *ref = NULL;
6578 char *refname, *remote_refname = NULL;
6580 if (strncmp(branch_name, "refs/", 5) == 0)
6581 branch_name += 5;
6582 if (strncmp(branch_name, "heads/", 6) == 0)
6583 branch_name += 6;
6584 else if (strncmp(branch_name, "remotes/", 8) == 0)
6585 branch_name += 8;
6587 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6588 return got_error_from_errno("asprintf");
6590 if (asprintf(&remote_refname, "refs/remotes/%s",
6591 branch_name) == -1) {
6592 err = got_error_from_errno("asprintf");
6593 goto done;
6596 err = got_ref_open(&ref, repo, refname, 0);
6597 if (err) {
6598 const struct got_error *err2;
6599 if (err->code != GOT_ERR_NOT_REF)
6600 goto done;
6602 * Keep 'err' intact such that if neither branch exists
6603 * we report "refs/heads" rather than "refs/remotes" in
6604 * our error message.
6606 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6607 if (err2)
6608 goto done;
6609 err = NULL;
6612 if (worktree &&
6613 strcmp(got_worktree_get_head_ref_name(worktree),
6614 got_ref_get_name(ref)) == 0) {
6615 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6616 "will not delete this work tree's current branch");
6617 goto done;
6620 err = delete_ref(repo, ref);
6621 done:
6622 if (ref)
6623 got_ref_close(ref);
6624 free(refname);
6625 free(remote_refname);
6626 return err;
6629 static const struct got_error *
6630 add_branch(struct got_repository *repo, const char *branch_name,
6631 struct got_object_id *base_commit_id)
6633 const struct got_error *err = NULL;
6634 struct got_reference *ref = NULL;
6635 char *base_refname = NULL, *refname = NULL;
6638 * Don't let the user create a branch name with a leading '-'.
6639 * While technically a valid reference name, this case is usually
6640 * an unintended typo.
6642 if (branch_name[0] == '-')
6643 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6645 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6646 branch_name += 11;
6648 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6649 err = got_error_from_errno("asprintf");
6650 goto done;
6653 err = got_ref_open(&ref, repo, refname, 0);
6654 if (err == NULL) {
6655 err = got_error(GOT_ERR_BRANCH_EXISTS);
6656 goto done;
6657 } else if (err->code != GOT_ERR_NOT_REF)
6658 goto done;
6660 err = got_ref_alloc(&ref, refname, base_commit_id);
6661 if (err)
6662 goto done;
6664 err = got_ref_write(ref, repo);
6665 done:
6666 if (ref)
6667 got_ref_close(ref);
6668 free(base_refname);
6669 free(refname);
6670 return err;
6673 static const struct got_error *
6674 cmd_branch(int argc, char *argv[])
6676 const struct got_error *error = NULL;
6677 struct got_repository *repo = NULL;
6678 struct got_worktree *worktree = NULL;
6679 char *cwd = NULL, *repo_path = NULL;
6680 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6681 const char *delref = NULL, *commit_id_arg = NULL;
6682 struct got_reference *ref = NULL;
6683 struct got_pathlist_head paths;
6684 struct got_pathlist_entry *pe;
6685 struct got_object_id *commit_id = NULL;
6686 char *commit_id_str = NULL;
6687 int *pack_fds = NULL;
6689 TAILQ_INIT(&paths);
6691 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6692 switch (ch) {
6693 case 'c':
6694 commit_id_arg = optarg;
6695 break;
6696 case 'd':
6697 delref = optarg;
6698 break;
6699 case 'l':
6700 do_list = 1;
6701 break;
6702 case 'n':
6703 do_update = 0;
6704 break;
6705 case 'r':
6706 repo_path = realpath(optarg, NULL);
6707 if (repo_path == NULL)
6708 return got_error_from_errno2("realpath",
6709 optarg);
6710 got_path_strip_trailing_slashes(repo_path);
6711 break;
6712 case 't':
6713 sort_by_time = 1;
6714 break;
6715 default:
6716 usage_branch();
6717 /* NOTREACHED */
6721 if (do_list && delref)
6722 option_conflict('l', 'd');
6723 if (sort_by_time && !do_list)
6724 errx(1, "-t option requires -l option");
6726 argc -= optind;
6727 argv += optind;
6729 if (!do_list && !delref && argc == 0)
6730 do_show = 1;
6732 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6733 errx(1, "-c option can only be used when creating a branch");
6735 if (do_list || delref) {
6736 if (argc > 0)
6737 usage_branch();
6738 } else if (!do_show && argc != 1)
6739 usage_branch();
6741 #ifndef PROFILE
6742 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6743 "sendfd unveil", NULL) == -1)
6744 err(1, "pledge");
6745 #endif
6746 cwd = getcwd(NULL, 0);
6747 if (cwd == NULL) {
6748 error = got_error_from_errno("getcwd");
6749 goto done;
6752 error = got_repo_pack_fds_open(&pack_fds);
6753 if (error != NULL)
6754 goto done;
6756 if (repo_path == NULL) {
6757 error = got_worktree_open(&worktree, cwd);
6758 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6759 goto done;
6760 else
6761 error = NULL;
6762 if (worktree) {
6763 repo_path =
6764 strdup(got_worktree_get_repo_path(worktree));
6765 if (repo_path == NULL)
6766 error = got_error_from_errno("strdup");
6767 if (error)
6768 goto done;
6769 } else {
6770 repo_path = strdup(cwd);
6771 if (repo_path == NULL) {
6772 error = got_error_from_errno("strdup");
6773 goto done;
6778 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6779 if (error != NULL)
6780 goto done;
6782 #ifndef PROFILE
6783 if (do_list || do_show) {
6784 /* Remove "cpath" promise. */
6785 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6786 NULL) == -1)
6787 err(1, "pledge");
6789 #endif
6791 error = apply_unveil(got_repo_get_path(repo), do_list,
6792 worktree ? got_worktree_get_root_path(worktree) : NULL);
6793 if (error)
6794 goto done;
6796 if (do_show)
6797 error = show_current_branch(repo, worktree);
6798 else if (do_list)
6799 error = list_branches(repo, worktree, sort_by_time);
6800 else if (delref)
6801 error = delete_branch(repo, worktree, delref);
6802 else {
6803 struct got_reflist_head refs;
6804 TAILQ_INIT(&refs);
6805 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6806 NULL);
6807 if (error)
6808 goto done;
6809 if (commit_id_arg == NULL)
6810 commit_id_arg = worktree ?
6811 got_worktree_get_head_ref_name(worktree) :
6812 GOT_REF_HEAD;
6813 error = got_repo_match_object_id(&commit_id, NULL,
6814 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6815 got_ref_list_free(&refs);
6816 if (error)
6817 goto done;
6818 error = add_branch(repo, argv[0], commit_id);
6819 if (error)
6820 goto done;
6821 if (worktree && do_update) {
6822 struct got_update_progress_arg upa;
6823 char *branch_refname = NULL;
6825 error = got_object_id_str(&commit_id_str, commit_id);
6826 if (error)
6827 goto done;
6828 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6829 worktree);
6830 if (error)
6831 goto done;
6832 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6833 == -1) {
6834 error = got_error_from_errno("asprintf");
6835 goto done;
6837 error = got_ref_open(&ref, repo, branch_refname, 0);
6838 free(branch_refname);
6839 if (error)
6840 goto done;
6841 error = switch_head_ref(ref, commit_id, worktree,
6842 repo);
6843 if (error)
6844 goto done;
6845 error = got_worktree_set_base_commit_id(worktree, repo,
6846 commit_id);
6847 if (error)
6848 goto done;
6849 memset(&upa, 0, sizeof(upa));
6850 error = got_worktree_checkout_files(worktree, &paths,
6851 repo, update_progress, &upa, check_cancelled,
6852 NULL);
6853 if (error)
6854 goto done;
6855 if (upa.did_something) {
6856 printf("Updated to %s: %s\n",
6857 got_worktree_get_head_ref_name(worktree),
6858 commit_id_str);
6860 print_update_progress_stats(&upa);
6863 done:
6864 if (ref)
6865 got_ref_close(ref);
6866 if (repo) {
6867 const struct got_error *close_err = got_repo_close(repo);
6868 if (error == NULL)
6869 error = close_err;
6871 if (worktree)
6872 got_worktree_close(worktree);
6873 if (pack_fds) {
6874 const struct got_error *pack_err =
6875 got_repo_pack_fds_close(pack_fds);
6876 if (error == NULL)
6877 error = pack_err;
6879 free(cwd);
6880 free(repo_path);
6881 free(commit_id);
6882 free(commit_id_str);
6883 TAILQ_FOREACH(pe, &paths, entry)
6884 free((char *)pe->path);
6885 got_pathlist_free(&paths);
6886 return error;
6890 __dead static void
6891 usage_tag(void)
6893 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6894 "[-r repository-path] [-s signer-id] name\n", getprogname());
6895 exit(1);
6898 #if 0
6899 static const struct got_error *
6900 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6902 const struct got_error *err = NULL;
6903 struct got_reflist_entry *re, *se, *new;
6904 struct got_object_id *re_id, *se_id;
6905 struct got_tag_object *re_tag, *se_tag;
6906 time_t re_time, se_time;
6908 STAILQ_FOREACH(re, tags, entry) {
6909 se = STAILQ_FIRST(sorted);
6910 if (se == NULL) {
6911 err = got_reflist_entry_dup(&new, re);
6912 if (err)
6913 return err;
6914 STAILQ_INSERT_HEAD(sorted, new, entry);
6915 continue;
6916 } else {
6917 err = got_ref_resolve(&re_id, repo, re->ref);
6918 if (err)
6919 break;
6920 err = got_object_open_as_tag(&re_tag, repo, re_id);
6921 free(re_id);
6922 if (err)
6923 break;
6924 re_time = got_object_tag_get_tagger_time(re_tag);
6925 got_object_tag_close(re_tag);
6928 while (se) {
6929 err = got_ref_resolve(&se_id, repo, re->ref);
6930 if (err)
6931 break;
6932 err = got_object_open_as_tag(&se_tag, repo, se_id);
6933 free(se_id);
6934 if (err)
6935 break;
6936 se_time = got_object_tag_get_tagger_time(se_tag);
6937 got_object_tag_close(se_tag);
6939 if (se_time > re_time) {
6940 err = got_reflist_entry_dup(&new, re);
6941 if (err)
6942 return err;
6943 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6944 break;
6946 se = STAILQ_NEXT(se, entry);
6947 continue;
6950 done:
6951 return err;
6953 #endif
6955 static const struct got_error *
6956 get_tag_refname(char **refname, const char *tag_name)
6958 const struct got_error *err;
6960 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6961 *refname = strdup(tag_name);
6962 if (*refname == NULL)
6963 return got_error_from_errno("strdup");
6964 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6965 err = got_error_from_errno("asprintf");
6966 *refname = NULL;
6967 return err;
6970 return NULL;
6973 static const struct got_error *
6974 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6975 const char *allowed_signers, const char *revoked_signers, int verbosity)
6977 static const struct got_error *err = NULL;
6978 struct got_reflist_head refs;
6979 struct got_reflist_entry *re;
6980 char *wanted_refname = NULL;
6981 int bad_sigs = 0;
6983 TAILQ_INIT(&refs);
6985 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6986 if (err)
6987 return err;
6989 if (tag_name) {
6990 struct got_reference *ref;
6991 err = get_tag_refname(&wanted_refname, tag_name);
6992 if (err)
6993 goto done;
6994 /* Wanted tag reference should exist. */
6995 err = got_ref_open(&ref, repo, wanted_refname, 0);
6996 if (err)
6997 goto done;
6998 got_ref_close(ref);
7001 TAILQ_FOREACH(re, &refs, entry) {
7002 const char *refname;
7003 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7004 char datebuf[26];
7005 const char *tagger, *ssh_sig = NULL;
7006 char *sig_msg = NULL;
7007 time_t tagger_time;
7008 struct got_object_id *id;
7009 struct got_tag_object *tag;
7010 struct got_commit_object *commit = NULL;
7012 refname = got_ref_get_name(re->ref);
7013 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7014 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7015 continue;
7016 refname += 10;
7017 refstr = got_ref_to_str(re->ref);
7018 if (refstr == NULL) {
7019 err = got_error_from_errno("got_ref_to_str");
7020 break;
7023 err = got_ref_resolve(&id, repo, re->ref);
7024 if (err)
7025 break;
7026 err = got_object_open_as_tag(&tag, repo, id);
7027 if (err) {
7028 if (err->code != GOT_ERR_OBJ_TYPE) {
7029 free(id);
7030 break;
7032 /* "lightweight" tag */
7033 err = got_object_open_as_commit(&commit, repo, id);
7034 if (err) {
7035 free(id);
7036 break;
7038 tagger = got_object_commit_get_committer(commit);
7039 tagger_time =
7040 got_object_commit_get_committer_time(commit);
7041 err = got_object_id_str(&id_str, id);
7042 free(id);
7043 if (err)
7044 break;
7045 } else {
7046 free(id);
7047 tagger = got_object_tag_get_tagger(tag);
7048 tagger_time = got_object_tag_get_tagger_time(tag);
7049 err = got_object_id_str(&id_str,
7050 got_object_tag_get_object_id(tag));
7051 if (err)
7052 break;
7055 if (tag && verify_tags) {
7056 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7057 got_object_tag_get_message(tag));
7058 if (ssh_sig && allowed_signers == NULL) {
7059 err = got_error_msg(
7060 GOT_ERR_VERIFY_TAG_SIGNATURE,
7061 "SSH signature verification requires "
7062 "setting allowed_signers in "
7063 "got.conf(5)");
7064 break;
7068 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7069 free(refstr);
7070 printf("from: %s\n", tagger);
7071 datestr = get_datestr(&tagger_time, datebuf);
7072 if (datestr)
7073 printf("date: %s UTC\n", datestr);
7074 if (commit)
7075 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7076 else {
7077 switch (got_object_tag_get_object_type(tag)) {
7078 case GOT_OBJ_TYPE_BLOB:
7079 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7080 id_str);
7081 break;
7082 case GOT_OBJ_TYPE_TREE:
7083 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7084 id_str);
7085 break;
7086 case GOT_OBJ_TYPE_COMMIT:
7087 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7088 id_str);
7089 break;
7090 case GOT_OBJ_TYPE_TAG:
7091 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7092 id_str);
7093 break;
7094 default:
7095 break;
7098 free(id_str);
7100 if (ssh_sig) {
7101 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7102 allowed_signers, revoked_signers, verbosity);
7103 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7104 bad_sigs = 1;
7105 else if (err)
7106 break;
7107 printf("signature: %s", sig_msg);
7108 free(sig_msg);
7109 sig_msg = NULL;
7112 if (commit) {
7113 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7114 if (err)
7115 break;
7116 got_object_commit_close(commit);
7117 } else {
7118 tagmsg0 = strdup(got_object_tag_get_message(tag));
7119 got_object_tag_close(tag);
7120 if (tagmsg0 == NULL) {
7121 err = got_error_from_errno("strdup");
7122 break;
7126 tagmsg = tagmsg0;
7127 do {
7128 line = strsep(&tagmsg, "\n");
7129 if (line)
7130 printf(" %s\n", line);
7131 } while (line);
7132 free(tagmsg0);
7134 done:
7135 got_ref_list_free(&refs);
7136 free(wanted_refname);
7138 if (err == NULL && bad_sigs)
7139 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7140 return err;
7143 static const struct got_error *
7144 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7145 const char *tag_name, const char *repo_path)
7147 const struct got_error *err = NULL;
7148 char *template = NULL, *initial_content = NULL;
7149 char *editor = NULL;
7150 int initial_content_len;
7151 int fd = -1;
7153 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7154 err = got_error_from_errno("asprintf");
7155 goto done;
7158 initial_content_len = asprintf(&initial_content,
7159 "\n# tagging commit %s as %s\n",
7160 commit_id_str, tag_name);
7161 if (initial_content_len == -1) {
7162 err = got_error_from_errno("asprintf");
7163 goto done;
7166 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7167 if (err)
7168 goto done;
7170 if (write(fd, initial_content, initial_content_len) == -1) {
7171 err = got_error_from_errno2("write", *tagmsg_path);
7172 goto done;
7175 err = get_editor(&editor);
7176 if (err)
7177 goto done;
7178 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7179 initial_content_len, 1);
7180 done:
7181 free(initial_content);
7182 free(template);
7183 free(editor);
7185 if (fd != -1 && close(fd) == -1 && err == NULL)
7186 err = got_error_from_errno2("close", *tagmsg_path);
7188 if (err) {
7189 free(*tagmsg);
7190 *tagmsg = NULL;
7192 return err;
7195 static const struct got_error *
7196 add_tag(struct got_repository *repo, const char *tagger,
7197 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7198 const char *signer_id, int verbosity)
7200 const struct got_error *err = NULL;
7201 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7202 char *label = NULL, *commit_id_str = NULL;
7203 struct got_reference *ref = NULL;
7204 char *refname = NULL, *tagmsg = NULL;
7205 char *tagmsg_path = NULL, *tag_id_str = NULL;
7206 int preserve_tagmsg = 0;
7207 struct got_reflist_head refs;
7209 TAILQ_INIT(&refs);
7212 * Don't let the user create a tag name with a leading '-'.
7213 * While technically a valid reference name, this case is usually
7214 * an unintended typo.
7216 if (tag_name[0] == '-')
7217 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7219 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7220 if (err)
7221 goto done;
7223 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7224 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7225 if (err)
7226 goto done;
7228 err = got_object_id_str(&commit_id_str, commit_id);
7229 if (err)
7230 goto done;
7232 err = get_tag_refname(&refname, tag_name);
7233 if (err)
7234 goto done;
7235 if (strncmp("refs/tags/", tag_name, 10) == 0)
7236 tag_name += 10;
7238 err = got_ref_open(&ref, repo, refname, 0);
7239 if (err == NULL) {
7240 err = got_error(GOT_ERR_TAG_EXISTS);
7241 goto done;
7242 } else if (err->code != GOT_ERR_NOT_REF)
7243 goto done;
7245 if (tagmsg_arg == NULL) {
7246 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7247 tag_name, got_repo_get_path(repo));
7248 if (err) {
7249 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7250 tagmsg_path != NULL)
7251 preserve_tagmsg = 1;
7252 goto done;
7254 /* Editor is done; we can now apply unveil(2) */
7255 err = got_sigs_apply_unveil();
7256 if (err)
7257 goto done;
7258 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7259 if (err)
7260 goto done;
7263 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7264 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7265 verbosity);
7266 if (err) {
7267 if (tagmsg_path)
7268 preserve_tagmsg = 1;
7269 goto done;
7272 err = got_ref_alloc(&ref, refname, tag_id);
7273 if (err) {
7274 if (tagmsg_path)
7275 preserve_tagmsg = 1;
7276 goto done;
7279 err = got_ref_write(ref, repo);
7280 if (err) {
7281 if (tagmsg_path)
7282 preserve_tagmsg = 1;
7283 goto done;
7286 err = got_object_id_str(&tag_id_str, tag_id);
7287 if (err) {
7288 if (tagmsg_path)
7289 preserve_tagmsg = 1;
7290 goto done;
7292 printf("Created tag %s\n", tag_id_str);
7293 done:
7294 if (preserve_tagmsg) {
7295 fprintf(stderr, "%s: tag message preserved in %s\n",
7296 getprogname(), tagmsg_path);
7297 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7298 err = got_error_from_errno2("unlink", tagmsg_path);
7299 free(tag_id_str);
7300 if (ref)
7301 got_ref_close(ref);
7302 free(commit_id);
7303 free(commit_id_str);
7304 free(refname);
7305 free(tagmsg);
7306 free(tagmsg_path);
7307 got_ref_list_free(&refs);
7308 return err;
7311 static const struct got_error *
7312 cmd_tag(int argc, char *argv[])
7314 const struct got_error *error = NULL;
7315 struct got_repository *repo = NULL;
7316 struct got_worktree *worktree = NULL;
7317 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7318 char *gitconfig_path = NULL, *tagger = NULL;
7319 char *allowed_signers = NULL, *revoked_signers = NULL;
7320 char *signer_id = NULL;
7321 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7322 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7323 int *pack_fds = NULL;
7325 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7326 switch (ch) {
7327 case 'c':
7328 commit_id_arg = optarg;
7329 break;
7330 case 'l':
7331 do_list = 1;
7332 break;
7333 case 'm':
7334 tagmsg = optarg;
7335 break;
7336 case 'r':
7337 repo_path = realpath(optarg, NULL);
7338 if (repo_path == NULL) {
7339 error = got_error_from_errno2("realpath",
7340 optarg);
7341 goto done;
7343 got_path_strip_trailing_slashes(repo_path);
7344 break;
7345 case 's':
7346 signer_id = strdup(optarg);
7347 if (signer_id == NULL) {
7348 error = got_error_from_errno("strdup");
7349 goto done;
7351 break;
7352 case 'V':
7353 verify_tags = 1;
7354 break;
7355 case 'v':
7356 if (verbosity < 0)
7357 verbosity = 0;
7358 else if (verbosity < 3)
7359 verbosity++;
7360 break;
7361 default:
7362 usage_tag();
7363 /* NOTREACHED */
7367 argc -= optind;
7368 argv += optind;
7370 if (do_list || verify_tags) {
7371 if (commit_id_arg != NULL)
7372 errx(1,
7373 "-c option can only be used when creating a tag");
7374 if (tagmsg) {
7375 if (do_list)
7376 option_conflict('l', 'm');
7377 else
7378 option_conflict('V', 'm');
7380 if (signer_id) {
7381 if (do_list)
7382 option_conflict('l', 's');
7383 else
7384 option_conflict('V', 's');
7386 if (argc > 1)
7387 usage_tag();
7388 } else if (argc != 1)
7389 usage_tag();
7391 if (argc == 1)
7392 tag_name = argv[0];
7394 #ifndef PROFILE
7395 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7396 "sendfd unveil", NULL) == -1)
7397 err(1, "pledge");
7398 #endif
7399 cwd = getcwd(NULL, 0);
7400 if (cwd == NULL) {
7401 error = got_error_from_errno("getcwd");
7402 goto done;
7405 error = got_repo_pack_fds_open(&pack_fds);
7406 if (error != NULL)
7407 goto done;
7409 if (repo_path == NULL) {
7410 error = got_worktree_open(&worktree, cwd);
7411 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7412 goto done;
7413 else
7414 error = NULL;
7415 if (worktree) {
7416 repo_path =
7417 strdup(got_worktree_get_repo_path(worktree));
7418 if (repo_path == NULL)
7419 error = got_error_from_errno("strdup");
7420 if (error)
7421 goto done;
7422 } else {
7423 repo_path = strdup(cwd);
7424 if (repo_path == NULL) {
7425 error = got_error_from_errno("strdup");
7426 goto done;
7431 if (do_list || verify_tags) {
7432 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7433 if (error != NULL)
7434 goto done;
7435 error = get_allowed_signers(&allowed_signers, repo, worktree);
7436 if (error)
7437 goto done;
7438 error = get_revoked_signers(&revoked_signers, repo, worktree);
7439 if (error)
7440 goto done;
7441 if (worktree) {
7442 /* Release work tree lock. */
7443 got_worktree_close(worktree);
7444 worktree = NULL;
7448 * Remove "cpath" promise unless needed for signature tmpfile
7449 * creation.
7451 if (verify_tags)
7452 got_sigs_apply_unveil();
7453 else {
7454 #ifndef PROFILE
7455 if (pledge("stdio rpath wpath flock proc exec sendfd "
7456 "unveil", NULL) == -1)
7457 err(1, "pledge");
7458 #endif
7460 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7461 if (error)
7462 goto done;
7463 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7464 revoked_signers, verbosity);
7465 } else {
7466 error = get_gitconfig_path(&gitconfig_path);
7467 if (error)
7468 goto done;
7469 error = got_repo_open(&repo, repo_path, gitconfig_path,
7470 pack_fds);
7471 if (error != NULL)
7472 goto done;
7474 error = get_author(&tagger, repo, worktree);
7475 if (error)
7476 goto done;
7477 if (signer_id == NULL) {
7478 error = get_signer_id(&signer_id, repo, worktree);
7479 if (error)
7480 goto done;
7483 if (tagmsg) {
7484 if (signer_id) {
7485 error = got_sigs_apply_unveil();
7486 if (error)
7487 goto done;
7489 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7490 if (error)
7491 goto done;
7494 if (commit_id_arg == NULL) {
7495 struct got_reference *head_ref;
7496 struct got_object_id *commit_id;
7497 error = got_ref_open(&head_ref, repo,
7498 worktree ? got_worktree_get_head_ref_name(worktree)
7499 : GOT_REF_HEAD, 0);
7500 if (error)
7501 goto done;
7502 error = got_ref_resolve(&commit_id, repo, head_ref);
7503 got_ref_close(head_ref);
7504 if (error)
7505 goto done;
7506 error = got_object_id_str(&commit_id_str, commit_id);
7507 free(commit_id);
7508 if (error)
7509 goto done;
7512 if (worktree) {
7513 /* Release work tree lock. */
7514 got_worktree_close(worktree);
7515 worktree = NULL;
7518 error = add_tag(repo, tagger, tag_name,
7519 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7520 signer_id, verbosity);
7522 done:
7523 if (repo) {
7524 const struct got_error *close_err = got_repo_close(repo);
7525 if (error == NULL)
7526 error = close_err;
7528 if (worktree)
7529 got_worktree_close(worktree);
7530 if (pack_fds) {
7531 const struct got_error *pack_err =
7532 got_repo_pack_fds_close(pack_fds);
7533 if (error == NULL)
7534 error = pack_err;
7536 free(cwd);
7537 free(repo_path);
7538 free(gitconfig_path);
7539 free(commit_id_str);
7540 free(tagger);
7541 free(allowed_signers);
7542 free(revoked_signers);
7543 free(signer_id);
7544 return error;
7547 __dead static void
7548 usage_add(void)
7550 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7551 exit(1);
7554 static const struct got_error *
7555 add_progress(void *arg, unsigned char status, const char *path)
7557 while (path[0] == '/')
7558 path++;
7559 printf("%c %s\n", status, path);
7560 return NULL;
7563 static const struct got_error *
7564 cmd_add(int argc, char *argv[])
7566 const struct got_error *error = NULL;
7567 struct got_repository *repo = NULL;
7568 struct got_worktree *worktree = NULL;
7569 char *cwd = NULL;
7570 struct got_pathlist_head paths;
7571 struct got_pathlist_entry *pe;
7572 int ch, can_recurse = 0, no_ignores = 0;
7573 int *pack_fds = NULL;
7575 TAILQ_INIT(&paths);
7577 while ((ch = getopt(argc, argv, "IR")) != -1) {
7578 switch (ch) {
7579 case 'I':
7580 no_ignores = 1;
7581 break;
7582 case 'R':
7583 can_recurse = 1;
7584 break;
7585 default:
7586 usage_add();
7587 /* NOTREACHED */
7591 argc -= optind;
7592 argv += optind;
7594 #ifndef PROFILE
7595 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7596 NULL) == -1)
7597 err(1, "pledge");
7598 #endif
7599 if (argc < 1)
7600 usage_add();
7602 cwd = getcwd(NULL, 0);
7603 if (cwd == NULL) {
7604 error = got_error_from_errno("getcwd");
7605 goto done;
7608 error = got_repo_pack_fds_open(&pack_fds);
7609 if (error != NULL)
7610 goto done;
7612 error = got_worktree_open(&worktree, cwd);
7613 if (error) {
7614 if (error->code == GOT_ERR_NOT_WORKTREE)
7615 error = wrap_not_worktree_error(error, "add", cwd);
7616 goto done;
7619 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7620 NULL, pack_fds);
7621 if (error != NULL)
7622 goto done;
7624 error = apply_unveil(got_repo_get_path(repo), 1,
7625 got_worktree_get_root_path(worktree));
7626 if (error)
7627 goto done;
7629 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7630 if (error)
7631 goto done;
7633 if (!can_recurse) {
7634 char *ondisk_path;
7635 struct stat sb;
7636 TAILQ_FOREACH(pe, &paths, entry) {
7637 if (asprintf(&ondisk_path, "%s/%s",
7638 got_worktree_get_root_path(worktree),
7639 pe->path) == -1) {
7640 error = got_error_from_errno("asprintf");
7641 goto done;
7643 if (lstat(ondisk_path, &sb) == -1) {
7644 if (errno == ENOENT) {
7645 free(ondisk_path);
7646 continue;
7648 error = got_error_from_errno2("lstat",
7649 ondisk_path);
7650 free(ondisk_path);
7651 goto done;
7653 free(ondisk_path);
7654 if (S_ISDIR(sb.st_mode)) {
7655 error = got_error_msg(GOT_ERR_BAD_PATH,
7656 "adding directories requires -R option");
7657 goto done;
7662 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7663 NULL, repo, no_ignores);
7664 done:
7665 if (repo) {
7666 const struct got_error *close_err = got_repo_close(repo);
7667 if (error == NULL)
7668 error = close_err;
7670 if (worktree)
7671 got_worktree_close(worktree);
7672 if (pack_fds) {
7673 const struct got_error *pack_err =
7674 got_repo_pack_fds_close(pack_fds);
7675 if (error == NULL)
7676 error = pack_err;
7678 TAILQ_FOREACH(pe, &paths, entry)
7679 free((char *)pe->path);
7680 got_pathlist_free(&paths);
7681 free(cwd);
7682 return error;
7685 __dead static void
7686 usage_remove(void)
7688 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7689 getprogname());
7690 exit(1);
7693 static const struct got_error *
7694 print_remove_status(void *arg, unsigned char status,
7695 unsigned char staged_status, const char *path)
7697 while (path[0] == '/')
7698 path++;
7699 if (status == GOT_STATUS_NONEXISTENT)
7700 return NULL;
7701 if (status == staged_status && (status == GOT_STATUS_DELETE))
7702 status = GOT_STATUS_NO_CHANGE;
7703 printf("%c%c %s\n", status, staged_status, path);
7704 return NULL;
7707 static const struct got_error *
7708 cmd_remove(int argc, char *argv[])
7710 const struct got_error *error = NULL;
7711 struct got_worktree *worktree = NULL;
7712 struct got_repository *repo = NULL;
7713 const char *status_codes = NULL;
7714 char *cwd = NULL;
7715 struct got_pathlist_head paths;
7716 struct got_pathlist_entry *pe;
7717 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7718 int ignore_missing_paths = 0;
7719 int *pack_fds = NULL;
7721 TAILQ_INIT(&paths);
7723 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7724 switch (ch) {
7725 case 'f':
7726 delete_local_mods = 1;
7727 ignore_missing_paths = 1;
7728 break;
7729 case 'k':
7730 keep_on_disk = 1;
7731 break;
7732 case 'R':
7733 can_recurse = 1;
7734 break;
7735 case 's':
7736 for (i = 0; i < strlen(optarg); i++) {
7737 switch (optarg[i]) {
7738 case GOT_STATUS_MODIFY:
7739 delete_local_mods = 1;
7740 break;
7741 case GOT_STATUS_MISSING:
7742 ignore_missing_paths = 1;
7743 break;
7744 default:
7745 errx(1, "invalid status code '%c'",
7746 optarg[i]);
7749 status_codes = optarg;
7750 break;
7751 default:
7752 usage_remove();
7753 /* NOTREACHED */
7757 argc -= optind;
7758 argv += optind;
7760 #ifndef PROFILE
7761 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7762 NULL) == -1)
7763 err(1, "pledge");
7764 #endif
7765 if (argc < 1)
7766 usage_remove();
7768 cwd = getcwd(NULL, 0);
7769 if (cwd == NULL) {
7770 error = got_error_from_errno("getcwd");
7771 goto done;
7774 error = got_repo_pack_fds_open(&pack_fds);
7775 if (error != NULL)
7776 goto done;
7778 error = got_worktree_open(&worktree, cwd);
7779 if (error) {
7780 if (error->code == GOT_ERR_NOT_WORKTREE)
7781 error = wrap_not_worktree_error(error, "remove", cwd);
7782 goto done;
7785 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7786 NULL, pack_fds);
7787 if (error)
7788 goto done;
7790 error = apply_unveil(got_repo_get_path(repo), 1,
7791 got_worktree_get_root_path(worktree));
7792 if (error)
7793 goto done;
7795 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7796 if (error)
7797 goto done;
7799 if (!can_recurse) {
7800 char *ondisk_path;
7801 struct stat sb;
7802 TAILQ_FOREACH(pe, &paths, entry) {
7803 if (asprintf(&ondisk_path, "%s/%s",
7804 got_worktree_get_root_path(worktree),
7805 pe->path) == -1) {
7806 error = got_error_from_errno("asprintf");
7807 goto done;
7809 if (lstat(ondisk_path, &sb) == -1) {
7810 if (errno == ENOENT) {
7811 free(ondisk_path);
7812 continue;
7814 error = got_error_from_errno2("lstat",
7815 ondisk_path);
7816 free(ondisk_path);
7817 goto done;
7819 free(ondisk_path);
7820 if (S_ISDIR(sb.st_mode)) {
7821 error = got_error_msg(GOT_ERR_BAD_PATH,
7822 "removing directories requires -R option");
7823 goto done;
7828 error = got_worktree_schedule_delete(worktree, &paths,
7829 delete_local_mods, status_codes, print_remove_status, NULL,
7830 repo, keep_on_disk, ignore_missing_paths);
7831 done:
7832 if (repo) {
7833 const struct got_error *close_err = got_repo_close(repo);
7834 if (error == NULL)
7835 error = close_err;
7837 if (worktree)
7838 got_worktree_close(worktree);
7839 if (pack_fds) {
7840 const struct got_error *pack_err =
7841 got_repo_pack_fds_close(pack_fds);
7842 if (error == NULL)
7843 error = pack_err;
7845 TAILQ_FOREACH(pe, &paths, entry)
7846 free((char *)pe->path);
7847 got_pathlist_free(&paths);
7848 free(cwd);
7849 return error;
7852 __dead static void
7853 usage_patch(void)
7855 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7856 "[patchfile]\n", getprogname());
7857 exit(1);
7860 static const struct got_error *
7861 patch_from_stdin(int *patchfd)
7863 const struct got_error *err = NULL;
7864 ssize_t r;
7865 char buf[BUFSIZ];
7866 sig_t sighup, sigint, sigquit;
7868 *patchfd = got_opentempfd();
7869 if (*patchfd == -1)
7870 return got_error_from_errno("got_opentempfd");
7872 sighup = signal(SIGHUP, SIG_DFL);
7873 sigint = signal(SIGINT, SIG_DFL);
7874 sigquit = signal(SIGQUIT, SIG_DFL);
7876 for (;;) {
7877 r = read(0, buf, sizeof(buf));
7878 if (r == -1) {
7879 err = got_error_from_errno("read");
7880 break;
7882 if (r == 0)
7883 break;
7884 if (write(*patchfd, buf, r) == -1) {
7885 err = got_error_from_errno("write");
7886 break;
7890 signal(SIGHUP, sighup);
7891 signal(SIGINT, sigint);
7892 signal(SIGQUIT, sigquit);
7894 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7895 err = got_error_from_errno("lseek");
7897 if (err != NULL) {
7898 close(*patchfd);
7899 *patchfd = -1;
7902 return err;
7905 static const struct got_error *
7906 patch_progress(void *arg, const char *old, const char *new,
7907 unsigned char status, const struct got_error *error, int old_from,
7908 int old_lines, int new_from, int new_lines, int offset,
7909 int ws_mangled, const struct got_error *hunk_err)
7911 const char *path = new == NULL ? old : new;
7913 while (*path == '/')
7914 path++;
7916 if (status != 0)
7917 printf("%c %s\n", status, path);
7919 if (error != NULL)
7920 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7922 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7923 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7924 old_lines, new_from, new_lines);
7925 if (hunk_err != NULL)
7926 printf("%s\n", hunk_err->msg);
7927 else if (offset != 0)
7928 printf("applied with offset %d\n", offset);
7929 else
7930 printf("hunk contains mangled whitespace\n");
7933 return NULL;
7936 static const struct got_error *
7937 cmd_patch(int argc, char *argv[])
7939 const struct got_error *error = NULL, *close_error = NULL;
7940 struct got_worktree *worktree = NULL;
7941 struct got_repository *repo = NULL;
7942 struct got_reflist_head refs;
7943 struct got_object_id *commit_id = NULL;
7944 const char *commit_id_str = NULL;
7945 struct stat sb;
7946 const char *errstr;
7947 char *cwd = NULL;
7948 int ch, nop = 0, strip = -1, reverse = 0;
7949 int patchfd;
7950 int *pack_fds = NULL;
7952 TAILQ_INIT(&refs);
7954 #ifndef PROFILE
7955 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7956 "unveil", NULL) == -1)
7957 err(1, "pledge");
7958 #endif
7960 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7961 switch (ch) {
7962 case 'c':
7963 commit_id_str = optarg;
7964 break;
7965 case 'n':
7966 nop = 1;
7967 break;
7968 case 'p':
7969 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7970 if (errstr != NULL)
7971 errx(1, "pathname strip count is %s: %s",
7972 errstr, optarg);
7973 break;
7974 case 'R':
7975 reverse = 1;
7976 break;
7977 default:
7978 usage_patch();
7979 /* NOTREACHED */
7983 argc -= optind;
7984 argv += optind;
7986 if (argc == 0) {
7987 error = patch_from_stdin(&patchfd);
7988 if (error)
7989 return error;
7990 } else if (argc == 1) {
7991 patchfd = open(argv[0], O_RDONLY);
7992 if (patchfd == -1) {
7993 error = got_error_from_errno2("open", argv[0]);
7994 return error;
7996 if (fstat(patchfd, &sb) == -1) {
7997 error = got_error_from_errno2("fstat", argv[0]);
7998 goto done;
8000 if (!S_ISREG(sb.st_mode)) {
8001 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8002 goto done;
8004 } else
8005 usage_patch();
8007 if ((cwd = getcwd(NULL, 0)) == NULL) {
8008 error = got_error_from_errno("getcwd");
8009 goto done;
8012 error = got_repo_pack_fds_open(&pack_fds);
8013 if (error != NULL)
8014 goto done;
8016 error = got_worktree_open(&worktree, cwd);
8017 if (error != NULL)
8018 goto done;
8020 const char *repo_path = got_worktree_get_repo_path(worktree);
8021 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8022 if (error != NULL)
8023 goto done;
8025 error = apply_unveil(got_repo_get_path(repo), 0,
8026 got_worktree_get_root_path(worktree));
8027 if (error != NULL)
8028 goto done;
8030 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8031 if (error)
8032 goto done;
8034 if (commit_id_str != NULL) {
8035 error = got_repo_match_object_id(&commit_id, NULL,
8036 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8037 if (error)
8038 goto done;
8041 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8042 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8044 done:
8045 got_ref_list_free(&refs);
8046 free(commit_id);
8047 if (repo) {
8048 close_error = got_repo_close(repo);
8049 if (error == NULL)
8050 error = close_error;
8052 if (worktree != NULL) {
8053 close_error = got_worktree_close(worktree);
8054 if (error == NULL)
8055 error = close_error;
8057 if (pack_fds) {
8058 const struct got_error *pack_err =
8059 got_repo_pack_fds_close(pack_fds);
8060 if (error == NULL)
8061 error = pack_err;
8063 free(cwd);
8064 return error;
8067 __dead static void
8068 usage_revert(void)
8070 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8071 getprogname());
8072 exit(1);
8075 static const struct got_error *
8076 revert_progress(void *arg, unsigned char status, const char *path)
8078 if (status == GOT_STATUS_UNVERSIONED)
8079 return NULL;
8081 while (path[0] == '/')
8082 path++;
8083 printf("%c %s\n", status, path);
8084 return NULL;
8087 struct choose_patch_arg {
8088 FILE *patch_script_file;
8089 const char *action;
8092 static const struct got_error *
8093 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8094 int nchanges, const char *action)
8096 const struct got_error *err;
8097 char *line = NULL;
8098 size_t linesize = 0;
8099 ssize_t linelen;
8101 switch (status) {
8102 case GOT_STATUS_ADD:
8103 printf("A %s\n%s this addition? [y/n] ", path, action);
8104 break;
8105 case GOT_STATUS_DELETE:
8106 printf("D %s\n%s this deletion? [y/n] ", path, action);
8107 break;
8108 case GOT_STATUS_MODIFY:
8109 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8110 return got_error_from_errno("fseek");
8111 printf(GOT_COMMIT_SEP_STR);
8112 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8113 printf("%s", line);
8114 if (linelen == -1 && ferror(patch_file)) {
8115 err = got_error_from_errno("getline");
8116 free(line);
8117 return err;
8119 free(line);
8120 printf(GOT_COMMIT_SEP_STR);
8121 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8122 path, n, nchanges, action);
8123 break;
8124 default:
8125 return got_error_path(path, GOT_ERR_FILE_STATUS);
8128 fflush(stdout);
8129 return NULL;
8132 static const struct got_error *
8133 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8134 FILE *patch_file, int n, int nchanges)
8136 const struct got_error *err = NULL;
8137 char *line = NULL;
8138 size_t linesize = 0;
8139 ssize_t linelen;
8140 int resp = ' ';
8141 struct choose_patch_arg *a = arg;
8143 *choice = GOT_PATCH_CHOICE_NONE;
8145 if (a->patch_script_file) {
8146 char *nl;
8147 err = show_change(status, path, patch_file, n, nchanges,
8148 a->action);
8149 if (err)
8150 return err;
8151 linelen = getline(&line, &linesize, a->patch_script_file);
8152 if (linelen == -1) {
8153 if (ferror(a->patch_script_file))
8154 return got_error_from_errno("getline");
8155 return NULL;
8157 nl = strchr(line, '\n');
8158 if (nl)
8159 *nl = '\0';
8160 if (strcmp(line, "y") == 0) {
8161 *choice = GOT_PATCH_CHOICE_YES;
8162 printf("y\n");
8163 } else if (strcmp(line, "n") == 0) {
8164 *choice = GOT_PATCH_CHOICE_NO;
8165 printf("n\n");
8166 } else if (strcmp(line, "q") == 0 &&
8167 status == GOT_STATUS_MODIFY) {
8168 *choice = GOT_PATCH_CHOICE_QUIT;
8169 printf("q\n");
8170 } else
8171 printf("invalid response '%s'\n", line);
8172 free(line);
8173 return NULL;
8176 while (resp != 'y' && resp != 'n' && resp != 'q') {
8177 err = show_change(status, path, patch_file, n, nchanges,
8178 a->action);
8179 if (err)
8180 return err;
8181 resp = getchar();
8182 if (resp == '\n')
8183 resp = getchar();
8184 if (status == GOT_STATUS_MODIFY) {
8185 if (resp != 'y' && resp != 'n' && resp != 'q') {
8186 printf("invalid response '%c'\n", resp);
8187 resp = ' ';
8189 } else if (resp != 'y' && resp != 'n') {
8190 printf("invalid response '%c'\n", resp);
8191 resp = ' ';
8195 if (resp == 'y')
8196 *choice = GOT_PATCH_CHOICE_YES;
8197 else if (resp == 'n')
8198 *choice = GOT_PATCH_CHOICE_NO;
8199 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8200 *choice = GOT_PATCH_CHOICE_QUIT;
8202 return NULL;
8205 static const struct got_error *
8206 cmd_revert(int argc, char *argv[])
8208 const struct got_error *error = NULL;
8209 struct got_worktree *worktree = NULL;
8210 struct got_repository *repo = NULL;
8211 char *cwd = NULL, *path = NULL;
8212 struct got_pathlist_head paths;
8213 struct got_pathlist_entry *pe;
8214 int ch, can_recurse = 0, pflag = 0;
8215 FILE *patch_script_file = NULL;
8216 const char *patch_script_path = NULL;
8217 struct choose_patch_arg cpa;
8218 int *pack_fds = NULL;
8220 TAILQ_INIT(&paths);
8222 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8223 switch (ch) {
8224 case 'F':
8225 patch_script_path = optarg;
8226 break;
8227 case 'p':
8228 pflag = 1;
8229 break;
8230 case 'R':
8231 can_recurse = 1;
8232 break;
8233 default:
8234 usage_revert();
8235 /* NOTREACHED */
8239 argc -= optind;
8240 argv += optind;
8242 #ifndef PROFILE
8243 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8244 "unveil", NULL) == -1)
8245 err(1, "pledge");
8246 #endif
8247 if (argc < 1)
8248 usage_revert();
8249 if (patch_script_path && !pflag)
8250 errx(1, "-F option can only be used together with -p option");
8252 cwd = getcwd(NULL, 0);
8253 if (cwd == NULL) {
8254 error = got_error_from_errno("getcwd");
8255 goto done;
8258 error = got_repo_pack_fds_open(&pack_fds);
8259 if (error != NULL)
8260 goto done;
8262 error = got_worktree_open(&worktree, cwd);
8263 if (error) {
8264 if (error->code == GOT_ERR_NOT_WORKTREE)
8265 error = wrap_not_worktree_error(error, "revert", cwd);
8266 goto done;
8269 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8270 NULL, pack_fds);
8271 if (error != NULL)
8272 goto done;
8274 if (patch_script_path) {
8275 patch_script_file = fopen(patch_script_path, "re");
8276 if (patch_script_file == NULL) {
8277 error = got_error_from_errno2("fopen",
8278 patch_script_path);
8279 goto done;
8282 error = apply_unveil(got_repo_get_path(repo), 1,
8283 got_worktree_get_root_path(worktree));
8284 if (error)
8285 goto done;
8287 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8288 if (error)
8289 goto done;
8291 if (!can_recurse) {
8292 char *ondisk_path;
8293 struct stat sb;
8294 TAILQ_FOREACH(pe, &paths, entry) {
8295 if (asprintf(&ondisk_path, "%s/%s",
8296 got_worktree_get_root_path(worktree),
8297 pe->path) == -1) {
8298 error = got_error_from_errno("asprintf");
8299 goto done;
8301 if (lstat(ondisk_path, &sb) == -1) {
8302 if (errno == ENOENT) {
8303 free(ondisk_path);
8304 continue;
8306 error = got_error_from_errno2("lstat",
8307 ondisk_path);
8308 free(ondisk_path);
8309 goto done;
8311 free(ondisk_path);
8312 if (S_ISDIR(sb.st_mode)) {
8313 error = got_error_msg(GOT_ERR_BAD_PATH,
8314 "reverting directories requires -R option");
8315 goto done;
8320 cpa.patch_script_file = patch_script_file;
8321 cpa.action = "revert";
8322 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8323 pflag ? choose_patch : NULL, &cpa, repo);
8324 done:
8325 if (patch_script_file && fclose(patch_script_file) == EOF &&
8326 error == NULL)
8327 error = got_error_from_errno2("fclose", patch_script_path);
8328 if (repo) {
8329 const struct got_error *close_err = got_repo_close(repo);
8330 if (error == NULL)
8331 error = close_err;
8333 if (worktree)
8334 got_worktree_close(worktree);
8335 if (pack_fds) {
8336 const struct got_error *pack_err =
8337 got_repo_pack_fds_close(pack_fds);
8338 if (error == NULL)
8339 error = pack_err;
8341 free(path);
8342 free(cwd);
8343 return error;
8346 __dead static void
8347 usage_commit(void)
8349 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8350 "[-m message] [path ...]\n", getprogname());
8351 exit(1);
8354 struct collect_commit_logmsg_arg {
8355 const char *cmdline_log;
8356 const char *prepared_log;
8357 int non_interactive;
8358 const char *editor;
8359 const char *worktree_path;
8360 const char *branch_name;
8361 const char *repo_path;
8362 char *logmsg_path;
8366 static const struct got_error *
8367 read_prepared_logmsg(char **logmsg, const char *path)
8369 const struct got_error *err = NULL;
8370 FILE *f = NULL;
8371 struct stat sb;
8372 size_t r;
8374 *logmsg = NULL;
8375 memset(&sb, 0, sizeof(sb));
8377 f = fopen(path, "re");
8378 if (f == NULL)
8379 return got_error_from_errno2("fopen", path);
8381 if (fstat(fileno(f), &sb) == -1) {
8382 err = got_error_from_errno2("fstat", path);
8383 goto done;
8385 if (sb.st_size == 0) {
8386 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8387 goto done;
8390 *logmsg = malloc(sb.st_size + 1);
8391 if (*logmsg == NULL) {
8392 err = got_error_from_errno("malloc");
8393 goto done;
8396 r = fread(*logmsg, 1, sb.st_size, f);
8397 if (r != sb.st_size) {
8398 if (ferror(f))
8399 err = got_error_from_errno2("fread", path);
8400 else
8401 err = got_error(GOT_ERR_IO);
8402 goto done;
8404 (*logmsg)[sb.st_size] = '\0';
8405 done:
8406 if (fclose(f) == EOF && err == NULL)
8407 err = got_error_from_errno2("fclose", path);
8408 if (err) {
8409 free(*logmsg);
8410 *logmsg = NULL;
8412 return err;
8415 static const struct got_error *
8416 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8417 void *arg)
8419 char *initial_content = NULL;
8420 struct got_pathlist_entry *pe;
8421 const struct got_error *err = NULL;
8422 char *template = NULL;
8423 struct collect_commit_logmsg_arg *a = arg;
8424 int initial_content_len;
8425 int fd = -1;
8426 size_t len;
8428 /* if a message was specified on the command line, just use it */
8429 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8430 len = strlen(a->cmdline_log) + 1;
8431 *logmsg = malloc(len + 1);
8432 if (*logmsg == NULL)
8433 return got_error_from_errno("malloc");
8434 strlcpy(*logmsg, a->cmdline_log, len);
8435 return NULL;
8436 } else if (a->prepared_log != NULL && a->non_interactive)
8437 return read_prepared_logmsg(logmsg, a->prepared_log);
8439 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8440 return got_error_from_errno("asprintf");
8442 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8443 if (err)
8444 goto done;
8446 if (a->prepared_log) {
8447 char *msg;
8448 err = read_prepared_logmsg(&msg, a->prepared_log);
8449 if (err)
8450 goto done;
8451 if (write(fd, msg, strlen(msg)) == -1) {
8452 err = got_error_from_errno2("write", a->logmsg_path);
8453 free(msg);
8454 goto done;
8456 free(msg);
8459 initial_content_len = asprintf(&initial_content,
8460 "\n# changes to be committed on branch %s:\n",
8461 a->branch_name);
8462 if (initial_content_len == -1) {
8463 err = got_error_from_errno("asprintf");
8464 goto done;
8467 if (write(fd, initial_content, initial_content_len) == -1) {
8468 err = got_error_from_errno2("write", a->logmsg_path);
8469 goto done;
8472 TAILQ_FOREACH(pe, commitable_paths, entry) {
8473 struct got_commitable *ct = pe->data;
8474 dprintf(fd, "# %c %s\n",
8475 got_commitable_get_status(ct),
8476 got_commitable_get_path(ct));
8479 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8480 initial_content_len, a->prepared_log ? 0 : 1);
8481 done:
8482 free(initial_content);
8483 free(template);
8485 if (fd != -1 && close(fd) == -1 && err == NULL)
8486 err = got_error_from_errno2("close", a->logmsg_path);
8488 /* Editor is done; we can now apply unveil(2) */
8489 if (err == NULL)
8490 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8491 if (err) {
8492 free(*logmsg);
8493 *logmsg = NULL;
8495 return err;
8498 static const struct got_error *
8499 cmd_commit(int argc, char *argv[])
8501 const struct got_error *error = NULL;
8502 struct got_worktree *worktree = NULL;
8503 struct got_repository *repo = NULL;
8504 char *cwd = NULL, *id_str = NULL;
8505 struct got_object_id *id = NULL;
8506 const char *logmsg = NULL;
8507 char *prepared_logmsg = NULL;
8508 struct collect_commit_logmsg_arg cl_arg;
8509 const char *author = NULL;
8510 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8511 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8512 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8513 struct got_pathlist_head paths;
8514 int *pack_fds = NULL;
8516 TAILQ_INIT(&paths);
8517 cl_arg.logmsg_path = NULL;
8519 while ((ch = getopt(argc, argv, "A:F:m:NS")) != -1) {
8520 switch (ch) {
8521 case 'A':
8522 author = optarg;
8523 error = valid_author(author);
8524 if (error)
8525 return error;
8526 break;
8527 case 'F':
8528 if (logmsg != NULL)
8529 option_conflict('F', 'm');
8530 prepared_logmsg = realpath(optarg, NULL);
8531 if (prepared_logmsg == NULL)
8532 return got_error_from_errno2("realpath",
8533 optarg);
8534 break;
8535 case 'm':
8536 if (prepared_logmsg)
8537 option_conflict('m', 'F');
8538 logmsg = optarg;
8539 break;
8540 case 'N':
8541 non_interactive = 1;
8542 break;
8543 case 'S':
8544 allow_bad_symlinks = 1;
8545 break;
8546 default:
8547 usage_commit();
8548 /* NOTREACHED */
8552 argc -= optind;
8553 argv += optind;
8555 #ifndef PROFILE
8556 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8557 "unveil", NULL) == -1)
8558 err(1, "pledge");
8559 #endif
8560 cwd = getcwd(NULL, 0);
8561 if (cwd == NULL) {
8562 error = got_error_from_errno("getcwd");
8563 goto done;
8566 error = got_repo_pack_fds_open(&pack_fds);
8567 if (error != NULL)
8568 goto done;
8570 error = got_worktree_open(&worktree, cwd);
8571 if (error) {
8572 if (error->code == GOT_ERR_NOT_WORKTREE)
8573 error = wrap_not_worktree_error(error, "commit", cwd);
8574 goto done;
8577 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8578 if (error)
8579 goto done;
8580 if (rebase_in_progress) {
8581 error = got_error(GOT_ERR_REBASING);
8582 goto done;
8585 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8586 worktree);
8587 if (error)
8588 goto done;
8590 error = get_gitconfig_path(&gitconfig_path);
8591 if (error)
8592 goto done;
8593 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8594 gitconfig_path, pack_fds);
8595 if (error != NULL)
8596 goto done;
8598 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8599 if (error)
8600 goto done;
8601 if (merge_in_progress) {
8602 error = got_error(GOT_ERR_MERGE_BUSY);
8603 goto done;
8606 error = get_author(&committer, repo, worktree);
8607 if (error)
8608 goto done;
8610 if (author != NULL && !strcmp(committer, author)) {
8611 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8612 goto done;
8615 if (author == NULL)
8616 author = committer;
8619 * unveil(2) traverses exec(2); if an editor is used we have
8620 * to apply unveil after the log message has been written.
8622 if (logmsg == NULL || strlen(logmsg) == 0)
8623 error = get_editor(&editor);
8624 else
8625 error = apply_unveil(got_repo_get_path(repo), 0,
8626 got_worktree_get_root_path(worktree));
8627 if (error)
8628 goto done;
8630 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8631 if (error)
8632 goto done;
8634 cl_arg.editor = editor;
8635 cl_arg.cmdline_log = logmsg;
8636 cl_arg.prepared_log = prepared_logmsg;
8637 cl_arg.non_interactive = non_interactive;
8638 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8639 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8640 if (!histedit_in_progress) {
8641 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8642 error = got_error(GOT_ERR_COMMIT_BRANCH);
8643 goto done;
8645 cl_arg.branch_name += 11;
8647 cl_arg.repo_path = got_repo_get_path(repo);
8648 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8649 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8650 print_status, NULL, repo);
8651 if (error) {
8652 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8653 cl_arg.logmsg_path != NULL)
8654 preserve_logmsg = 1;
8655 goto done;
8658 error = got_object_id_str(&id_str, id);
8659 if (error)
8660 goto done;
8661 printf("Created commit %s\n", id_str);
8662 done:
8663 if (preserve_logmsg) {
8664 fprintf(stderr, "%s: log message preserved in %s\n",
8665 getprogname(), cl_arg.logmsg_path);
8666 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8667 error == NULL)
8668 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8669 free(cl_arg.logmsg_path);
8670 if (repo) {
8671 const struct got_error *close_err = got_repo_close(repo);
8672 if (error == NULL)
8673 error = close_err;
8675 if (worktree)
8676 got_worktree_close(worktree);
8677 if (pack_fds) {
8678 const struct got_error *pack_err =
8679 got_repo_pack_fds_close(pack_fds);
8680 if (error == NULL)
8681 error = pack_err;
8683 free(cwd);
8684 free(id_str);
8685 free(gitconfig_path);
8686 free(editor);
8687 free(committer);
8688 free(prepared_logmsg);
8689 return error;
8692 __dead static void
8693 usage_send(void)
8695 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8696 "[-r repository-path] [-t tag] [remote-repository]\n",
8697 getprogname());
8698 exit(1);
8701 static void
8702 print_load_info(int print_colored, int print_found, int print_trees,
8703 int ncolored, int nfound, int ntrees)
8705 if (print_colored) {
8706 printf("%d commit%s colored", ncolored,
8707 ncolored == 1 ? "" : "s");
8709 if (print_found) {
8710 printf("%s%d object%s found",
8711 ncolored > 0 ? "; " : "",
8712 nfound, nfound == 1 ? "" : "s");
8714 if (print_trees) {
8715 printf("; %d tree%s scanned", ntrees,
8716 ntrees == 1 ? "" : "s");
8720 struct got_send_progress_arg {
8721 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8722 int verbosity;
8723 int last_ncolored;
8724 int last_nfound;
8725 int last_ntrees;
8726 int loading_done;
8727 int last_ncommits;
8728 int last_nobj_total;
8729 int last_p_deltify;
8730 int last_p_written;
8731 int last_p_sent;
8732 int printed_something;
8733 int sent_something;
8734 struct got_pathlist_head *delete_branches;
8737 static const struct got_error *
8738 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8739 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8740 int nobj_written, off_t bytes_sent, const char *refname, int success)
8742 struct got_send_progress_arg *a = arg;
8743 char scaled_packsize[FMT_SCALED_STRSIZE];
8744 char scaled_sent[FMT_SCALED_STRSIZE];
8745 int p_deltify = 0, p_written = 0, p_sent = 0;
8746 int print_colored = 0, print_found = 0, print_trees = 0;
8747 int print_searching = 0, print_total = 0;
8748 int print_deltify = 0, print_written = 0, print_sent = 0;
8750 if (a->verbosity < 0)
8751 return NULL;
8753 if (refname) {
8754 const char *status = success ? "accepted" : "rejected";
8756 if (success) {
8757 struct got_pathlist_entry *pe;
8758 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8759 const char *branchname = pe->path;
8760 if (got_path_cmp(branchname, refname,
8761 strlen(branchname), strlen(refname)) == 0) {
8762 status = "deleted";
8763 a->sent_something = 1;
8764 break;
8769 if (a->printed_something)
8770 putchar('\n');
8771 printf("Server has %s %s", status, refname);
8772 a->printed_something = 1;
8773 return NULL;
8776 if (a->last_ncolored != ncolored) {
8777 print_colored = 1;
8778 a->last_ncolored = ncolored;
8781 if (a->last_nfound != nfound) {
8782 print_colored = 1;
8783 print_found = 1;
8784 a->last_nfound = nfound;
8787 if (a->last_ntrees != ntrees) {
8788 print_colored = 1;
8789 print_found = 1;
8790 print_trees = 1;
8791 a->last_ntrees = ntrees;
8794 if ((print_colored || print_found || print_trees) &&
8795 !a->loading_done) {
8796 printf("\r");
8797 print_load_info(print_colored, print_found, print_trees,
8798 ncolored, nfound, ntrees);
8799 a->printed_something = 1;
8800 fflush(stdout);
8801 return NULL;
8802 } else if (!a->loading_done) {
8803 printf("\r");
8804 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8805 printf("\n");
8806 a->loading_done = 1;
8809 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8810 return got_error_from_errno("fmt_scaled");
8811 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8812 return got_error_from_errno("fmt_scaled");
8814 if (a->last_ncommits != ncommits) {
8815 print_searching = 1;
8816 a->last_ncommits = ncommits;
8819 if (a->last_nobj_total != nobj_total) {
8820 print_searching = 1;
8821 print_total = 1;
8822 a->last_nobj_total = nobj_total;
8825 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8826 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8827 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8828 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8829 return got_error(GOT_ERR_NO_SPACE);
8832 if (nobj_deltify > 0 || nobj_written > 0) {
8833 if (nobj_deltify > 0) {
8834 p_deltify = (nobj_deltify * 100) / nobj_total;
8835 if (p_deltify != a->last_p_deltify) {
8836 a->last_p_deltify = p_deltify;
8837 print_searching = 1;
8838 print_total = 1;
8839 print_deltify = 1;
8842 if (nobj_written > 0) {
8843 p_written = (nobj_written * 100) / nobj_total;
8844 if (p_written != a->last_p_written) {
8845 a->last_p_written = p_written;
8846 print_searching = 1;
8847 print_total = 1;
8848 print_deltify = 1;
8849 print_written = 1;
8854 if (bytes_sent > 0) {
8855 p_sent = (bytes_sent * 100) / packfile_size;
8856 if (p_sent != a->last_p_sent) {
8857 a->last_p_sent = p_sent;
8858 print_searching = 1;
8859 print_total = 1;
8860 print_deltify = 1;
8861 print_written = 1;
8862 print_sent = 1;
8864 a->sent_something = 1;
8867 if (print_searching || print_total || print_deltify || print_written ||
8868 print_sent)
8869 printf("\r");
8870 if (print_searching)
8871 printf("packing %d reference%s", ncommits,
8872 ncommits == 1 ? "" : "s");
8873 if (print_total)
8874 printf("; %d object%s", nobj_total,
8875 nobj_total == 1 ? "" : "s");
8876 if (print_deltify)
8877 printf("; deltify: %d%%", p_deltify);
8878 if (print_sent)
8879 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8880 scaled_packsize, p_sent);
8881 else if (print_written)
8882 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8883 scaled_packsize, p_written);
8884 if (print_searching || print_total || print_deltify ||
8885 print_written || print_sent) {
8886 a->printed_something = 1;
8887 fflush(stdout);
8889 return NULL;
8892 static const struct got_error *
8893 cmd_send(int argc, char *argv[])
8895 const struct got_error *error = NULL;
8896 char *cwd = NULL, *repo_path = NULL;
8897 const char *remote_name;
8898 char *proto = NULL, *host = NULL, *port = NULL;
8899 char *repo_name = NULL, *server_path = NULL;
8900 const struct got_remote_repo *remotes, *remote = NULL;
8901 int nremotes, nbranches = 0, ndelete_branches = 0;
8902 struct got_repository *repo = NULL;
8903 struct got_worktree *worktree = NULL;
8904 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8905 struct got_pathlist_head branches;
8906 struct got_pathlist_head tags;
8907 struct got_reflist_head all_branches;
8908 struct got_reflist_head all_tags;
8909 struct got_pathlist_head delete_args;
8910 struct got_pathlist_head delete_branches;
8911 struct got_reflist_entry *re;
8912 struct got_pathlist_entry *pe;
8913 int i, ch, sendfd = -1, sendstatus;
8914 pid_t sendpid = -1;
8915 struct got_send_progress_arg spa;
8916 int verbosity = 0, overwrite_refs = 0;
8917 int send_all_branches = 0, send_all_tags = 0;
8918 struct got_reference *ref = NULL;
8919 int *pack_fds = NULL;
8921 TAILQ_INIT(&branches);
8922 TAILQ_INIT(&tags);
8923 TAILQ_INIT(&all_branches);
8924 TAILQ_INIT(&all_tags);
8925 TAILQ_INIT(&delete_args);
8926 TAILQ_INIT(&delete_branches);
8928 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
8929 switch (ch) {
8930 case 'a':
8931 send_all_branches = 1;
8932 break;
8933 case 'b':
8934 error = got_pathlist_append(&branches, optarg, NULL);
8935 if (error)
8936 return error;
8937 nbranches++;
8938 break;
8939 case 'd':
8940 error = got_pathlist_append(&delete_args, optarg, NULL);
8941 if (error)
8942 return error;
8943 break;
8944 case 'f':
8945 overwrite_refs = 1;
8946 break;
8947 case 'q':
8948 verbosity = -1;
8949 break;
8950 case 'r':
8951 repo_path = realpath(optarg, NULL);
8952 if (repo_path == NULL)
8953 return got_error_from_errno2("realpath",
8954 optarg);
8955 got_path_strip_trailing_slashes(repo_path);
8956 break;
8957 case 'T':
8958 send_all_tags = 1;
8959 break;
8960 case 't':
8961 error = got_pathlist_append(&tags, optarg, NULL);
8962 if (error)
8963 return error;
8964 break;
8965 case 'v':
8966 if (verbosity < 0)
8967 verbosity = 0;
8968 else if (verbosity < 3)
8969 verbosity++;
8970 break;
8971 default:
8972 usage_send();
8973 /* NOTREACHED */
8976 argc -= optind;
8977 argv += optind;
8979 if (send_all_branches && !TAILQ_EMPTY(&branches))
8980 option_conflict('a', 'b');
8981 if (send_all_tags && !TAILQ_EMPTY(&tags))
8982 option_conflict('T', 't');
8985 if (argc == 0)
8986 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8987 else if (argc == 1)
8988 remote_name = argv[0];
8989 else
8990 usage_send();
8992 cwd = getcwd(NULL, 0);
8993 if (cwd == NULL) {
8994 error = got_error_from_errno("getcwd");
8995 goto done;
8998 error = got_repo_pack_fds_open(&pack_fds);
8999 if (error != NULL)
9000 goto done;
9002 if (repo_path == NULL) {
9003 error = got_worktree_open(&worktree, cwd);
9004 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9005 goto done;
9006 else
9007 error = NULL;
9008 if (worktree) {
9009 repo_path =
9010 strdup(got_worktree_get_repo_path(worktree));
9011 if (repo_path == NULL)
9012 error = got_error_from_errno("strdup");
9013 if (error)
9014 goto done;
9015 } else {
9016 repo_path = strdup(cwd);
9017 if (repo_path == NULL) {
9018 error = got_error_from_errno("strdup");
9019 goto done;
9024 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9025 if (error)
9026 goto done;
9028 if (worktree) {
9029 worktree_conf = got_worktree_get_gotconfig(worktree);
9030 if (worktree_conf) {
9031 got_gotconfig_get_remotes(&nremotes, &remotes,
9032 worktree_conf);
9033 for (i = 0; i < nremotes; i++) {
9034 if (strcmp(remotes[i].name, remote_name) == 0) {
9035 remote = &remotes[i];
9036 break;
9041 if (remote == NULL) {
9042 repo_conf = got_repo_get_gotconfig(repo);
9043 if (repo_conf) {
9044 got_gotconfig_get_remotes(&nremotes, &remotes,
9045 repo_conf);
9046 for (i = 0; i < nremotes; i++) {
9047 if (strcmp(remotes[i].name, remote_name) == 0) {
9048 remote = &remotes[i];
9049 break;
9054 if (remote == NULL) {
9055 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9056 for (i = 0; i < nremotes; i++) {
9057 if (strcmp(remotes[i].name, remote_name) == 0) {
9058 remote = &remotes[i];
9059 break;
9063 if (remote == NULL) {
9064 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9065 goto done;
9068 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9069 &repo_name, remote->send_url);
9070 if (error)
9071 goto done;
9073 if (strcmp(proto, "git") == 0) {
9074 #ifndef PROFILE
9075 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9076 "sendfd dns inet unveil", NULL) == -1)
9077 err(1, "pledge");
9078 #endif
9079 } else if (strcmp(proto, "git+ssh") == 0 ||
9080 strcmp(proto, "ssh") == 0) {
9081 #ifndef PROFILE
9082 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9083 "sendfd unveil", NULL) == -1)
9084 err(1, "pledge");
9085 #endif
9086 } else if (strcmp(proto, "http") == 0 ||
9087 strcmp(proto, "git+http") == 0) {
9088 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9089 goto done;
9090 } else {
9091 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9092 goto done;
9095 error = got_dial_apply_unveil(proto);
9096 if (error)
9097 goto done;
9099 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9100 if (error)
9101 goto done;
9103 if (send_all_branches) {
9104 error = got_ref_list(&all_branches, repo, "refs/heads",
9105 got_ref_cmp_by_name, NULL);
9106 if (error)
9107 goto done;
9108 TAILQ_FOREACH(re, &all_branches, entry) {
9109 const char *branchname = got_ref_get_name(re->ref);
9110 error = got_pathlist_append(&branches,
9111 branchname, NULL);
9112 if (error)
9113 goto done;
9114 nbranches++;
9116 } else if (nbranches == 0) {
9117 for (i = 0; i < remote->nsend_branches; i++) {
9118 got_pathlist_append(&branches,
9119 remote->send_branches[i], NULL);
9123 if (send_all_tags) {
9124 error = got_ref_list(&all_tags, repo, "refs/tags",
9125 got_ref_cmp_by_name, NULL);
9126 if (error)
9127 goto done;
9128 TAILQ_FOREACH(re, &all_tags, entry) {
9129 const char *tagname = got_ref_get_name(re->ref);
9130 error = got_pathlist_append(&tags,
9131 tagname, NULL);
9132 if (error)
9133 goto done;
9138 * To prevent accidents only branches in refs/heads/ can be deleted
9139 * with 'got send -d'.
9140 * Deleting anything else requires local repository access or Git.
9142 TAILQ_FOREACH(pe, &delete_args, entry) {
9143 const char *branchname = pe->path;
9144 char *s;
9145 struct got_pathlist_entry *new;
9146 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9147 s = strdup(branchname);
9148 if (s == NULL) {
9149 error = got_error_from_errno("strdup");
9150 goto done;
9152 } else {
9153 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9154 error = got_error_from_errno("asprintf");
9155 goto done;
9158 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9159 if (error || new == NULL /* duplicate */)
9160 free(s);
9161 if (error)
9162 goto done;
9163 ndelete_branches++;
9166 if (nbranches == 0 && ndelete_branches == 0) {
9167 struct got_reference *head_ref;
9168 if (worktree)
9169 error = got_ref_open(&head_ref, repo,
9170 got_worktree_get_head_ref_name(worktree), 0);
9171 else
9172 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9173 if (error)
9174 goto done;
9175 if (got_ref_is_symbolic(head_ref)) {
9176 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9177 got_ref_close(head_ref);
9178 if (error)
9179 goto done;
9180 } else
9181 ref = head_ref;
9182 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9183 NULL);
9184 if (error)
9185 goto done;
9186 nbranches++;
9189 if (verbosity >= 0)
9190 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9191 port ? ":" : "", port ? port : "");
9193 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9194 server_path, verbosity);
9195 if (error)
9196 goto done;
9198 memset(&spa, 0, sizeof(spa));
9199 spa.last_scaled_packsize[0] = '\0';
9200 spa.last_p_deltify = -1;
9201 spa.last_p_written = -1;
9202 spa.verbosity = verbosity;
9203 spa.delete_branches = &delete_branches;
9204 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9205 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9206 check_cancelled, NULL);
9207 if (spa.printed_something)
9208 putchar('\n');
9209 if (error)
9210 goto done;
9211 if (!spa.sent_something && verbosity >= 0)
9212 printf("Already up-to-date\n");
9213 done:
9214 if (sendpid > 0) {
9215 if (kill(sendpid, SIGTERM) == -1)
9216 error = got_error_from_errno("kill");
9217 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9218 error = got_error_from_errno("waitpid");
9220 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9221 error = got_error_from_errno("close");
9222 if (repo) {
9223 const struct got_error *close_err = got_repo_close(repo);
9224 if (error == NULL)
9225 error = close_err;
9227 if (worktree)
9228 got_worktree_close(worktree);
9229 if (pack_fds) {
9230 const struct got_error *pack_err =
9231 got_repo_pack_fds_close(pack_fds);
9232 if (error == NULL)
9233 error = pack_err;
9235 if (ref)
9236 got_ref_close(ref);
9237 got_pathlist_free(&branches);
9238 got_pathlist_free(&tags);
9239 got_ref_list_free(&all_branches);
9240 got_ref_list_free(&all_tags);
9241 got_pathlist_free(&delete_args);
9242 TAILQ_FOREACH(pe, &delete_branches, entry)
9243 free((char *)pe->path);
9244 got_pathlist_free(&delete_branches);
9245 free(cwd);
9246 free(repo_path);
9247 free(proto);
9248 free(host);
9249 free(port);
9250 free(server_path);
9251 free(repo_name);
9252 return error;
9255 __dead static void
9256 usage_cherrypick(void)
9258 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9259 exit(1);
9262 static const struct got_error *
9263 cmd_cherrypick(int argc, char *argv[])
9265 const struct got_error *error = NULL;
9266 struct got_worktree *worktree = NULL;
9267 struct got_repository *repo = NULL;
9268 char *cwd = NULL, *commit_id_str = NULL;
9269 struct got_object_id *commit_id = NULL;
9270 struct got_commit_object *commit = NULL;
9271 struct got_object_qid *pid;
9272 int ch;
9273 struct got_update_progress_arg upa;
9274 int *pack_fds = NULL;
9276 while ((ch = getopt(argc, argv, "")) != -1) {
9277 switch (ch) {
9278 default:
9279 usage_cherrypick();
9280 /* NOTREACHED */
9284 argc -= optind;
9285 argv += optind;
9287 #ifndef PROFILE
9288 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9289 "unveil", NULL) == -1)
9290 err(1, "pledge");
9291 #endif
9292 if (argc != 1)
9293 usage_cherrypick();
9295 cwd = getcwd(NULL, 0);
9296 if (cwd == NULL) {
9297 error = got_error_from_errno("getcwd");
9298 goto done;
9301 error = got_repo_pack_fds_open(&pack_fds);
9302 if (error != NULL)
9303 goto done;
9305 error = got_worktree_open(&worktree, cwd);
9306 if (error) {
9307 if (error->code == GOT_ERR_NOT_WORKTREE)
9308 error = wrap_not_worktree_error(error, "cherrypick",
9309 cwd);
9310 goto done;
9313 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9314 NULL, pack_fds);
9315 if (error != NULL)
9316 goto done;
9318 error = apply_unveil(got_repo_get_path(repo), 0,
9319 got_worktree_get_root_path(worktree));
9320 if (error)
9321 goto done;
9323 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9324 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9325 if (error)
9326 goto done;
9327 error = got_object_id_str(&commit_id_str, commit_id);
9328 if (error)
9329 goto done;
9331 error = got_object_open_as_commit(&commit, repo, commit_id);
9332 if (error)
9333 goto done;
9334 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9335 memset(&upa, 0, sizeof(upa));
9336 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9337 commit_id, repo, update_progress, &upa, check_cancelled,
9338 NULL);
9339 if (error != NULL)
9340 goto done;
9342 if (upa.did_something)
9343 printf("Merged commit %s\n", commit_id_str);
9344 print_merge_progress_stats(&upa);
9345 done:
9346 if (commit)
9347 got_object_commit_close(commit);
9348 free(commit_id_str);
9349 if (worktree)
9350 got_worktree_close(worktree);
9351 if (repo) {
9352 const struct got_error *close_err = got_repo_close(repo);
9353 if (error == NULL)
9354 error = close_err;
9356 if (pack_fds) {
9357 const struct got_error *pack_err =
9358 got_repo_pack_fds_close(pack_fds);
9359 if (error == NULL)
9360 error = pack_err;
9363 return error;
9366 __dead static void
9367 usage_backout(void)
9369 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9370 exit(1);
9373 static const struct got_error *
9374 cmd_backout(int argc, char *argv[])
9376 const struct got_error *error = NULL;
9377 struct got_worktree *worktree = NULL;
9378 struct got_repository *repo = NULL;
9379 char *cwd = NULL, *commit_id_str = NULL;
9380 struct got_object_id *commit_id = NULL;
9381 struct got_commit_object *commit = NULL;
9382 struct got_object_qid *pid;
9383 int ch;
9384 struct got_update_progress_arg upa;
9385 int *pack_fds = NULL;
9387 while ((ch = getopt(argc, argv, "")) != -1) {
9388 switch (ch) {
9389 default:
9390 usage_backout();
9391 /* NOTREACHED */
9395 argc -= optind;
9396 argv += optind;
9398 #ifndef PROFILE
9399 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9400 "unveil", NULL) == -1)
9401 err(1, "pledge");
9402 #endif
9403 if (argc != 1)
9404 usage_backout();
9406 cwd = getcwd(NULL, 0);
9407 if (cwd == NULL) {
9408 error = got_error_from_errno("getcwd");
9409 goto done;
9412 error = got_repo_pack_fds_open(&pack_fds);
9413 if (error != NULL)
9414 goto done;
9416 error = got_worktree_open(&worktree, cwd);
9417 if (error) {
9418 if (error->code == GOT_ERR_NOT_WORKTREE)
9419 error = wrap_not_worktree_error(error, "backout", cwd);
9420 goto done;
9423 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9424 NULL, pack_fds);
9425 if (error != NULL)
9426 goto done;
9428 error = apply_unveil(got_repo_get_path(repo), 0,
9429 got_worktree_get_root_path(worktree));
9430 if (error)
9431 goto done;
9433 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9434 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9435 if (error)
9436 goto done;
9437 error = got_object_id_str(&commit_id_str, commit_id);
9438 if (error)
9439 goto done;
9441 error = got_object_open_as_commit(&commit, repo, commit_id);
9442 if (error)
9443 goto done;
9444 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9445 if (pid == NULL) {
9446 error = got_error(GOT_ERR_ROOT_COMMIT);
9447 goto done;
9450 memset(&upa, 0, sizeof(upa));
9451 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9452 repo, update_progress, &upa, check_cancelled, NULL);
9453 if (error != NULL)
9454 goto done;
9456 if (upa.did_something)
9457 printf("Backed out commit %s\n", commit_id_str);
9458 print_merge_progress_stats(&upa);
9459 done:
9460 if (commit)
9461 got_object_commit_close(commit);
9462 free(commit_id_str);
9463 if (worktree)
9464 got_worktree_close(worktree);
9465 if (repo) {
9466 const struct got_error *close_err = got_repo_close(repo);
9467 if (error == NULL)
9468 error = close_err;
9470 if (pack_fds) {
9471 const struct got_error *pack_err =
9472 got_repo_pack_fds_close(pack_fds);
9473 if (error == NULL)
9474 error = pack_err;
9476 return error;
9479 __dead static void
9480 usage_rebase(void)
9482 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9483 exit(1);
9486 static void
9487 trim_logmsg(char *logmsg, int limit)
9489 char *nl;
9490 size_t len;
9492 len = strlen(logmsg);
9493 if (len > limit)
9494 len = limit;
9495 logmsg[len] = '\0';
9496 nl = strchr(logmsg, '\n');
9497 if (nl)
9498 *nl = '\0';
9501 static const struct got_error *
9502 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9504 const struct got_error *err;
9505 char *logmsg0 = NULL;
9506 const char *s;
9508 err = got_object_commit_get_logmsg(&logmsg0, commit);
9509 if (err)
9510 return err;
9512 s = logmsg0;
9513 while (isspace((unsigned char)s[0]))
9514 s++;
9516 *logmsg = strdup(s);
9517 if (*logmsg == NULL) {
9518 err = got_error_from_errno("strdup");
9519 goto done;
9522 trim_logmsg(*logmsg, limit);
9523 done:
9524 free(logmsg0);
9525 return err;
9528 static const struct got_error *
9529 show_rebase_merge_conflict(struct got_object_id *id,
9530 struct got_repository *repo)
9532 const struct got_error *err;
9533 struct got_commit_object *commit = NULL;
9534 char *id_str = NULL, *logmsg = NULL;
9536 err = got_object_open_as_commit(&commit, repo, id);
9537 if (err)
9538 return err;
9540 err = got_object_id_str(&id_str, id);
9541 if (err)
9542 goto done;
9544 id_str[12] = '\0';
9546 err = get_short_logmsg(&logmsg, 42, commit);
9547 if (err)
9548 goto done;
9550 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9551 done:
9552 free(id_str);
9553 got_object_commit_close(commit);
9554 free(logmsg);
9555 return err;
9558 static const struct got_error *
9559 show_rebase_progress(struct got_commit_object *commit,
9560 struct got_object_id *old_id, struct got_object_id *new_id)
9562 const struct got_error *err;
9563 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9565 err = got_object_id_str(&old_id_str, old_id);
9566 if (err)
9567 goto done;
9569 if (new_id) {
9570 err = got_object_id_str(&new_id_str, new_id);
9571 if (err)
9572 goto done;
9575 old_id_str[12] = '\0';
9576 if (new_id_str)
9577 new_id_str[12] = '\0';
9579 err = get_short_logmsg(&logmsg, 42, commit);
9580 if (err)
9581 goto done;
9583 printf("%s -> %s: %s\n", old_id_str,
9584 new_id_str ? new_id_str : "no-op change", logmsg);
9585 done:
9586 free(old_id_str);
9587 free(new_id_str);
9588 free(logmsg);
9589 return err;
9592 static const struct got_error *
9593 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9594 struct got_reference *branch, struct got_reference *new_base_branch,
9595 struct got_reference *tmp_branch, struct got_repository *repo,
9596 int create_backup)
9598 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9599 return got_worktree_rebase_complete(worktree, fileindex,
9600 new_base_branch, tmp_branch, branch, repo, create_backup);
9603 static const struct got_error *
9604 rebase_commit(struct got_pathlist_head *merged_paths,
9605 struct got_worktree *worktree, struct got_fileindex *fileindex,
9606 struct got_reference *tmp_branch, const char *committer,
9607 struct got_object_id *commit_id, struct got_repository *repo)
9609 const struct got_error *error;
9610 struct got_commit_object *commit;
9611 struct got_object_id *new_commit_id;
9613 error = got_object_open_as_commit(&commit, repo, commit_id);
9614 if (error)
9615 return error;
9617 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9618 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9619 repo);
9620 if (error) {
9621 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9622 goto done;
9623 error = show_rebase_progress(commit, commit_id, NULL);
9624 } else {
9625 error = show_rebase_progress(commit, commit_id, new_commit_id);
9626 free(new_commit_id);
9628 done:
9629 got_object_commit_close(commit);
9630 return error;
9633 struct check_path_prefix_arg {
9634 const char *path_prefix;
9635 size_t len;
9636 int errcode;
9639 static const struct got_error *
9640 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9641 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9642 struct got_object_id *id1, struct got_object_id *id2,
9643 const char *path1, const char *path2,
9644 mode_t mode1, mode_t mode2, struct got_repository *repo)
9646 struct check_path_prefix_arg *a = arg;
9648 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9649 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9650 return got_error(a->errcode);
9652 return NULL;
9655 static const struct got_error *
9656 check_path_prefix(struct got_object_id *parent_id,
9657 struct got_object_id *commit_id, const char *path_prefix,
9658 int errcode, struct got_repository *repo)
9660 const struct got_error *err;
9661 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9662 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9663 struct check_path_prefix_arg cpp_arg;
9665 if (got_path_is_root_dir(path_prefix))
9666 return NULL;
9668 err = got_object_open_as_commit(&commit, repo, commit_id);
9669 if (err)
9670 goto done;
9672 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9673 if (err)
9674 goto done;
9676 err = got_object_open_as_tree(&tree1, repo,
9677 got_object_commit_get_tree_id(parent_commit));
9678 if (err)
9679 goto done;
9681 err = got_object_open_as_tree(&tree2, repo,
9682 got_object_commit_get_tree_id(commit));
9683 if (err)
9684 goto done;
9686 cpp_arg.path_prefix = path_prefix;
9687 while (cpp_arg.path_prefix[0] == '/')
9688 cpp_arg.path_prefix++;
9689 cpp_arg.len = strlen(cpp_arg.path_prefix);
9690 cpp_arg.errcode = errcode;
9691 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9692 check_path_prefix_in_diff, &cpp_arg, 0);
9693 done:
9694 if (tree1)
9695 got_object_tree_close(tree1);
9696 if (tree2)
9697 got_object_tree_close(tree2);
9698 if (commit)
9699 got_object_commit_close(commit);
9700 if (parent_commit)
9701 got_object_commit_close(parent_commit);
9702 return err;
9705 static const struct got_error *
9706 collect_commits(struct got_object_id_queue *commits,
9707 struct got_object_id *initial_commit_id,
9708 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9709 const char *path_prefix, int path_prefix_errcode,
9710 struct got_repository *repo)
9712 const struct got_error *err = NULL;
9713 struct got_commit_graph *graph = NULL;
9714 struct got_object_id parent_id, commit_id;
9715 struct got_object_qid *qid;
9717 err = got_commit_graph_open(&graph, "/", 1);
9718 if (err)
9719 return err;
9721 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9722 check_cancelled, NULL);
9723 if (err)
9724 goto done;
9726 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9727 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9728 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9729 check_cancelled, NULL);
9730 if (err) {
9731 if (err->code == GOT_ERR_ITER_COMPLETED) {
9732 err = got_error_msg(GOT_ERR_ANCESTRY,
9733 "ran out of commits to rebase before "
9734 "youngest common ancestor commit has "
9735 "been reached?!?");
9737 goto done;
9738 } else {
9739 err = check_path_prefix(&parent_id, &commit_id,
9740 path_prefix, path_prefix_errcode, repo);
9741 if (err)
9742 goto done;
9744 err = got_object_qid_alloc(&qid, &commit_id);
9745 if (err)
9746 goto done;
9747 STAILQ_INSERT_HEAD(commits, qid, entry);
9749 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9752 done:
9753 got_commit_graph_close(graph);
9754 return err;
9757 static const struct got_error *
9758 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9760 const struct got_error *err = NULL;
9761 time_t committer_time;
9762 struct tm tm;
9763 char datebuf[11]; /* YYYY-MM-DD + NUL */
9764 char *author0 = NULL, *author, *smallerthan;
9765 char *logmsg0 = NULL, *logmsg, *newline;
9767 committer_time = got_object_commit_get_committer_time(commit);
9768 if (gmtime_r(&committer_time, &tm) == NULL)
9769 return got_error_from_errno("gmtime_r");
9770 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9771 return got_error(GOT_ERR_NO_SPACE);
9773 author0 = strdup(got_object_commit_get_author(commit));
9774 if (author0 == NULL)
9775 return got_error_from_errno("strdup");
9776 author = author0;
9777 smallerthan = strchr(author, '<');
9778 if (smallerthan && smallerthan[1] != '\0')
9779 author = smallerthan + 1;
9780 author[strcspn(author, "@>")] = '\0';
9782 err = got_object_commit_get_logmsg(&logmsg0, commit);
9783 if (err)
9784 goto done;
9785 logmsg = logmsg0;
9786 while (*logmsg == '\n')
9787 logmsg++;
9788 newline = strchr(logmsg, '\n');
9789 if (newline)
9790 *newline = '\0';
9792 if (asprintf(brief_str, "%s %s %s",
9793 datebuf, author, logmsg) == -1)
9794 err = got_error_from_errno("asprintf");
9795 done:
9796 free(author0);
9797 free(logmsg0);
9798 return err;
9801 static const struct got_error *
9802 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9803 struct got_repository *repo)
9805 const struct got_error *err;
9806 char *id_str;
9808 err = got_object_id_str(&id_str, id);
9809 if (err)
9810 return err;
9812 err = got_ref_delete(ref, repo);
9813 if (err)
9814 goto done;
9816 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9817 done:
9818 free(id_str);
9819 return err;
9822 static const struct got_error *
9823 print_backup_ref(const char *branch_name, const char *new_id_str,
9824 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9825 struct got_reflist_object_id_map *refs_idmap,
9826 struct got_repository *repo)
9828 const struct got_error *err = NULL;
9829 struct got_reflist_head *refs;
9830 char *refs_str = NULL;
9831 struct got_object_id *new_commit_id = NULL;
9832 struct got_commit_object *new_commit = NULL;
9833 char *new_commit_brief_str = NULL;
9834 struct got_object_id *yca_id = NULL;
9835 struct got_commit_object *yca_commit = NULL;
9836 char *yca_id_str = NULL, *yca_brief_str = NULL;
9837 char *custom_refs_str;
9839 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9840 return got_error_from_errno("asprintf");
9842 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9843 0, 0, refs_idmap, custom_refs_str);
9844 if (err)
9845 goto done;
9847 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9848 if (err)
9849 goto done;
9851 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9852 if (refs) {
9853 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9854 if (err)
9855 goto done;
9858 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9859 if (err)
9860 goto done;
9862 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9863 if (err)
9864 goto done;
9866 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9867 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9868 if (err)
9869 goto done;
9871 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9872 refs_str ? " (" : "", refs_str ? refs_str : "",
9873 refs_str ? ")" : "", new_commit_brief_str);
9874 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9875 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9876 free(refs_str);
9877 refs_str = NULL;
9879 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9880 if (err)
9881 goto done;
9883 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9884 if (err)
9885 goto done;
9887 err = got_object_id_str(&yca_id_str, yca_id);
9888 if (err)
9889 goto done;
9891 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9892 if (refs) {
9893 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9894 if (err)
9895 goto done;
9897 printf("history forked at %s%s%s%s\n %s\n",
9898 yca_id_str,
9899 refs_str ? " (" : "", refs_str ? refs_str : "",
9900 refs_str ? ")" : "", yca_brief_str);
9902 done:
9903 free(custom_refs_str);
9904 free(new_commit_id);
9905 free(refs_str);
9906 free(yca_id);
9907 free(yca_id_str);
9908 free(yca_brief_str);
9909 if (new_commit)
9910 got_object_commit_close(new_commit);
9911 if (yca_commit)
9912 got_object_commit_close(yca_commit);
9914 return NULL;
9917 static const struct got_error *
9918 process_backup_refs(const char *backup_ref_prefix,
9919 const char *wanted_branch_name,
9920 int delete, struct got_repository *repo)
9922 const struct got_error *err;
9923 struct got_reflist_head refs, backup_refs;
9924 struct got_reflist_entry *re;
9925 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9926 struct got_object_id *old_commit_id = NULL;
9927 char *branch_name = NULL;
9928 struct got_commit_object *old_commit = NULL;
9929 struct got_reflist_object_id_map *refs_idmap = NULL;
9930 int wanted_branch_found = 0;
9932 TAILQ_INIT(&refs);
9933 TAILQ_INIT(&backup_refs);
9935 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9936 if (err)
9937 return err;
9939 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9940 if (err)
9941 goto done;
9943 if (wanted_branch_name) {
9944 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9945 wanted_branch_name += 11;
9948 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9949 got_ref_cmp_by_commit_timestamp_descending, repo);
9950 if (err)
9951 goto done;
9953 TAILQ_FOREACH(re, &backup_refs, entry) {
9954 const char *refname = got_ref_get_name(re->ref);
9955 char *slash;
9957 err = check_cancelled(NULL);
9958 if (err)
9959 break;
9961 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9962 if (err)
9963 break;
9965 err = got_object_open_as_commit(&old_commit, repo,
9966 old_commit_id);
9967 if (err)
9968 break;
9970 if (strncmp(backup_ref_prefix, refname,
9971 backup_ref_prefix_len) == 0)
9972 refname += backup_ref_prefix_len;
9974 while (refname[0] == '/')
9975 refname++;
9977 branch_name = strdup(refname);
9978 if (branch_name == NULL) {
9979 err = got_error_from_errno("strdup");
9980 break;
9982 slash = strrchr(branch_name, '/');
9983 if (slash) {
9984 *slash = '\0';
9985 refname += strlen(branch_name) + 1;
9988 if (wanted_branch_name == NULL ||
9989 strcmp(wanted_branch_name, branch_name) == 0) {
9990 wanted_branch_found = 1;
9991 if (delete) {
9992 err = delete_backup_ref(re->ref,
9993 old_commit_id, repo);
9994 } else {
9995 err = print_backup_ref(branch_name, refname,
9996 old_commit_id, old_commit, refs_idmap,
9997 repo);
9999 if (err)
10000 break;
10003 free(old_commit_id);
10004 old_commit_id = NULL;
10005 free(branch_name);
10006 branch_name = NULL;
10007 got_object_commit_close(old_commit);
10008 old_commit = NULL;
10011 if (wanted_branch_name && !wanted_branch_found) {
10012 err = got_error_fmt(GOT_ERR_NOT_REF,
10013 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10015 done:
10016 if (refs_idmap)
10017 got_reflist_object_id_map_free(refs_idmap);
10018 got_ref_list_free(&refs);
10019 got_ref_list_free(&backup_refs);
10020 free(old_commit_id);
10021 free(branch_name);
10022 if (old_commit)
10023 got_object_commit_close(old_commit);
10024 return err;
10027 static const struct got_error *
10028 abort_progress(void *arg, unsigned char status, const char *path)
10031 * Unversioned files should not clutter progress output when
10032 * an operation is aborted.
10034 if (status == GOT_STATUS_UNVERSIONED)
10035 return NULL;
10037 return update_progress(arg, status, path);
10040 static const struct got_error *
10041 cmd_rebase(int argc, char *argv[])
10043 const struct got_error *error = NULL;
10044 struct got_worktree *worktree = NULL;
10045 struct got_repository *repo = NULL;
10046 struct got_fileindex *fileindex = NULL;
10047 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10048 struct got_reference *branch = NULL;
10049 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10050 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10051 struct got_object_id *resume_commit_id = NULL;
10052 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10053 struct got_commit_object *commit = NULL;
10054 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10055 int histedit_in_progress = 0, merge_in_progress = 0;
10056 int create_backup = 1, list_backups = 0, delete_backups = 0;
10057 struct got_object_id_queue commits;
10058 struct got_pathlist_head merged_paths;
10059 const struct got_object_id_queue *parent_ids;
10060 struct got_object_qid *qid, *pid;
10061 struct got_update_progress_arg upa;
10062 int *pack_fds = NULL;
10064 STAILQ_INIT(&commits);
10065 TAILQ_INIT(&merged_paths);
10066 memset(&upa, 0, sizeof(upa));
10068 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10069 switch (ch) {
10070 case 'a':
10071 abort_rebase = 1;
10072 break;
10073 case 'c':
10074 continue_rebase = 1;
10075 break;
10076 case 'l':
10077 list_backups = 1;
10078 break;
10079 case 'X':
10080 delete_backups = 1;
10081 break;
10082 default:
10083 usage_rebase();
10084 /* NOTREACHED */
10088 argc -= optind;
10089 argv += optind;
10091 #ifndef PROFILE
10092 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10093 "unveil", NULL) == -1)
10094 err(1, "pledge");
10095 #endif
10096 if (list_backups) {
10097 if (abort_rebase)
10098 option_conflict('l', 'a');
10099 if (continue_rebase)
10100 option_conflict('l', 'c');
10101 if (delete_backups)
10102 option_conflict('l', 'X');
10103 if (argc != 0 && argc != 1)
10104 usage_rebase();
10105 } else if (delete_backups) {
10106 if (abort_rebase)
10107 option_conflict('X', 'a');
10108 if (continue_rebase)
10109 option_conflict('X', 'c');
10110 if (list_backups)
10111 option_conflict('l', 'X');
10112 if (argc != 0 && argc != 1)
10113 usage_rebase();
10114 } else {
10115 if (abort_rebase && continue_rebase)
10116 usage_rebase();
10117 else if (abort_rebase || continue_rebase) {
10118 if (argc != 0)
10119 usage_rebase();
10120 } else if (argc != 1)
10121 usage_rebase();
10124 cwd = getcwd(NULL, 0);
10125 if (cwd == NULL) {
10126 error = got_error_from_errno("getcwd");
10127 goto done;
10130 error = got_repo_pack_fds_open(&pack_fds);
10131 if (error != NULL)
10132 goto done;
10134 error = got_worktree_open(&worktree, cwd);
10135 if (error) {
10136 if (list_backups || delete_backups) {
10137 if (error->code != GOT_ERR_NOT_WORKTREE)
10138 goto done;
10139 } else {
10140 if (error->code == GOT_ERR_NOT_WORKTREE)
10141 error = wrap_not_worktree_error(error,
10142 "rebase", cwd);
10143 goto done;
10147 error = get_gitconfig_path(&gitconfig_path);
10148 if (error)
10149 goto done;
10150 error = got_repo_open(&repo,
10151 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10152 gitconfig_path, pack_fds);
10153 if (error != NULL)
10154 goto done;
10156 error = get_author(&committer, repo, worktree);
10157 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10158 goto done;
10160 error = apply_unveil(got_repo_get_path(repo), 0,
10161 worktree ? got_worktree_get_root_path(worktree) : NULL);
10162 if (error)
10163 goto done;
10165 if (list_backups || delete_backups) {
10166 error = process_backup_refs(
10167 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10168 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10169 goto done; /* nothing else to do */
10172 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10173 worktree);
10174 if (error)
10175 goto done;
10176 if (histedit_in_progress) {
10177 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10178 goto done;
10181 error = got_worktree_merge_in_progress(&merge_in_progress,
10182 worktree, repo);
10183 if (error)
10184 goto done;
10185 if (merge_in_progress) {
10186 error = got_error(GOT_ERR_MERGE_BUSY);
10187 goto done;
10190 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10191 if (error)
10192 goto done;
10194 if (abort_rebase) {
10195 if (!rebase_in_progress) {
10196 error = got_error(GOT_ERR_NOT_REBASING);
10197 goto done;
10199 error = got_worktree_rebase_continue(&resume_commit_id,
10200 &new_base_branch, &tmp_branch, &branch, &fileindex,
10201 worktree, repo);
10202 if (error)
10203 goto done;
10204 printf("Switching work tree to %s\n",
10205 got_ref_get_symref_target(new_base_branch));
10206 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10207 new_base_branch, abort_progress, &upa);
10208 if (error)
10209 goto done;
10210 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10211 print_merge_progress_stats(&upa);
10212 goto done; /* nothing else to do */
10215 if (continue_rebase) {
10216 if (!rebase_in_progress) {
10217 error = got_error(GOT_ERR_NOT_REBASING);
10218 goto done;
10220 error = got_worktree_rebase_continue(&resume_commit_id,
10221 &new_base_branch, &tmp_branch, &branch, &fileindex,
10222 worktree, repo);
10223 if (error)
10224 goto done;
10226 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10227 committer, resume_commit_id, repo);
10228 if (error)
10229 goto done;
10231 yca_id = got_object_id_dup(resume_commit_id);
10232 if (yca_id == NULL) {
10233 error = got_error_from_errno("got_object_id_dup");
10234 goto done;
10236 } else {
10237 error = got_ref_open(&branch, repo, argv[0], 0);
10238 if (error != NULL)
10239 goto done;
10240 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10241 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10242 "will not rebase a branch which lives outside "
10243 "the \"refs/heads/\" reference namespace");
10244 goto done;
10248 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10249 if (error)
10250 goto done;
10252 if (!continue_rebase) {
10253 struct got_object_id *base_commit_id;
10255 base_commit_id = got_worktree_get_base_commit_id(worktree);
10256 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10257 base_commit_id, branch_head_commit_id, 1, repo,
10258 check_cancelled, NULL);
10259 if (error)
10260 goto done;
10261 if (yca_id == NULL) {
10262 error = got_error_msg(GOT_ERR_ANCESTRY,
10263 "specified branch shares no common ancestry "
10264 "with work tree's branch");
10265 goto done;
10268 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10269 if (error) {
10270 if (error->code != GOT_ERR_ANCESTRY)
10271 goto done;
10272 error = NULL;
10273 } else {
10274 struct got_pathlist_head paths;
10275 printf("%s is already based on %s\n",
10276 got_ref_get_name(branch),
10277 got_worktree_get_head_ref_name(worktree));
10278 error = switch_head_ref(branch, branch_head_commit_id,
10279 worktree, repo);
10280 if (error)
10281 goto done;
10282 error = got_worktree_set_base_commit_id(worktree, repo,
10283 branch_head_commit_id);
10284 if (error)
10285 goto done;
10286 TAILQ_INIT(&paths);
10287 error = got_pathlist_append(&paths, "", NULL);
10288 if (error)
10289 goto done;
10290 error = got_worktree_checkout_files(worktree,
10291 &paths, repo, update_progress, &upa,
10292 check_cancelled, NULL);
10293 got_pathlist_free(&paths);
10294 if (error)
10295 goto done;
10296 if (upa.did_something) {
10297 char *id_str;
10298 error = got_object_id_str(&id_str,
10299 branch_head_commit_id);
10300 if (error)
10301 goto done;
10302 printf("Updated to %s: %s\n",
10303 got_worktree_get_head_ref_name(worktree),
10304 id_str);
10305 free(id_str);
10306 } else
10307 printf("Already up-to-date\n");
10308 print_update_progress_stats(&upa);
10309 goto done;
10313 commit_id = branch_head_commit_id;
10314 error = got_object_open_as_commit(&commit, repo, commit_id);
10315 if (error)
10316 goto done;
10318 parent_ids = got_object_commit_get_parent_ids(commit);
10319 pid = STAILQ_FIRST(parent_ids);
10320 if (pid == NULL) {
10321 error = got_error(GOT_ERR_EMPTY_REBASE);
10322 goto done;
10324 error = collect_commits(&commits, commit_id, &pid->id,
10325 yca_id, got_worktree_get_path_prefix(worktree),
10326 GOT_ERR_REBASE_PATH, repo);
10327 got_object_commit_close(commit);
10328 commit = NULL;
10329 if (error)
10330 goto done;
10332 if (!continue_rebase) {
10333 error = got_worktree_rebase_prepare(&new_base_branch,
10334 &tmp_branch, &fileindex, worktree, branch, repo);
10335 if (error)
10336 goto done;
10339 if (STAILQ_EMPTY(&commits)) {
10340 if (continue_rebase) {
10341 error = rebase_complete(worktree, fileindex,
10342 branch, new_base_branch, tmp_branch, repo,
10343 create_backup);
10344 goto done;
10345 } else {
10346 /* Fast-forward the reference of the branch. */
10347 struct got_object_id *new_head_commit_id;
10348 char *id_str;
10349 error = got_ref_resolve(&new_head_commit_id, repo,
10350 new_base_branch);
10351 if (error)
10352 goto done;
10353 error = got_object_id_str(&id_str, new_head_commit_id);
10354 if (error)
10355 goto done;
10356 printf("Forwarding %s to commit %s\n",
10357 got_ref_get_name(branch), id_str);
10358 free(id_str);
10359 error = got_ref_change_ref(branch,
10360 new_head_commit_id);
10361 if (error)
10362 goto done;
10363 /* No backup needed since objects did not change. */
10364 create_backup = 0;
10368 pid = NULL;
10369 STAILQ_FOREACH(qid, &commits, entry) {
10371 commit_id = &qid->id;
10372 parent_id = pid ? &pid->id : yca_id;
10373 pid = qid;
10375 memset(&upa, 0, sizeof(upa));
10376 error = got_worktree_rebase_merge_files(&merged_paths,
10377 worktree, fileindex, parent_id, commit_id, repo,
10378 update_progress, &upa, check_cancelled, NULL);
10379 if (error)
10380 goto done;
10382 print_merge_progress_stats(&upa);
10383 if (upa.conflicts > 0 || upa.missing > 0 ||
10384 upa.not_deleted > 0 || upa.unversioned > 0) {
10385 if (upa.conflicts > 0) {
10386 error = show_rebase_merge_conflict(&qid->id,
10387 repo);
10388 if (error)
10389 goto done;
10391 got_worktree_rebase_pathlist_free(&merged_paths);
10392 break;
10395 error = rebase_commit(&merged_paths, worktree, fileindex,
10396 tmp_branch, committer, commit_id, repo);
10397 got_worktree_rebase_pathlist_free(&merged_paths);
10398 if (error)
10399 goto done;
10402 if (upa.conflicts > 0 || upa.missing > 0 ||
10403 upa.not_deleted > 0 || upa.unversioned > 0) {
10404 error = got_worktree_rebase_postpone(worktree, fileindex);
10405 if (error)
10406 goto done;
10407 if (upa.conflicts > 0 && upa.missing == 0 &&
10408 upa.not_deleted == 0 && upa.unversioned == 0) {
10409 error = got_error_msg(GOT_ERR_CONFLICTS,
10410 "conflicts must be resolved before rebasing "
10411 "can continue");
10412 } else if (upa.conflicts > 0) {
10413 error = got_error_msg(GOT_ERR_CONFLICTS,
10414 "conflicts must be resolved before rebasing "
10415 "can continue; changes destined for some "
10416 "files were not yet merged and should be "
10417 "merged manually if required before the "
10418 "rebase operation is continued");
10419 } else {
10420 error = got_error_msg(GOT_ERR_CONFLICTS,
10421 "changes destined for some files were not "
10422 "yet merged and should be merged manually "
10423 "if required before the rebase operation "
10424 "is continued");
10426 } else
10427 error = rebase_complete(worktree, fileindex, branch,
10428 new_base_branch, tmp_branch, repo, create_backup);
10429 done:
10430 free(cwd);
10431 free(committer);
10432 free(gitconfig_path);
10433 got_object_id_queue_free(&commits);
10434 free(branch_head_commit_id);
10435 free(resume_commit_id);
10436 free(yca_id);
10437 if (commit)
10438 got_object_commit_close(commit);
10439 if (branch)
10440 got_ref_close(branch);
10441 if (new_base_branch)
10442 got_ref_close(new_base_branch);
10443 if (tmp_branch)
10444 got_ref_close(tmp_branch);
10445 if (worktree)
10446 got_worktree_close(worktree);
10447 if (repo) {
10448 const struct got_error *close_err = got_repo_close(repo);
10449 if (error == NULL)
10450 error = close_err;
10452 if (pack_fds) {
10453 const struct got_error *pack_err =
10454 got_repo_pack_fds_close(pack_fds);
10455 if (error == NULL)
10456 error = pack_err;
10458 return error;
10461 __dead static void
10462 usage_histedit(void)
10464 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10465 "[branch]\n", getprogname());
10466 exit(1);
10469 #define GOT_HISTEDIT_PICK 'p'
10470 #define GOT_HISTEDIT_EDIT 'e'
10471 #define GOT_HISTEDIT_FOLD 'f'
10472 #define GOT_HISTEDIT_DROP 'd'
10473 #define GOT_HISTEDIT_MESG 'm'
10475 static const struct got_histedit_cmd {
10476 unsigned char code;
10477 const char *name;
10478 const char *desc;
10479 } got_histedit_cmds[] = {
10480 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10481 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10482 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10483 "be used" },
10484 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10485 { GOT_HISTEDIT_MESG, "mesg",
10486 "single-line log message for commit above (open editor if empty)" },
10489 struct got_histedit_list_entry {
10490 TAILQ_ENTRY(got_histedit_list_entry) entry;
10491 struct got_object_id *commit_id;
10492 const struct got_histedit_cmd *cmd;
10493 char *logmsg;
10495 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10497 static const struct got_error *
10498 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10499 FILE *f, struct got_repository *repo)
10501 const struct got_error *err = NULL;
10502 char *logmsg = NULL, *id_str = NULL;
10503 struct got_commit_object *commit = NULL;
10504 int n;
10506 err = got_object_open_as_commit(&commit, repo, commit_id);
10507 if (err)
10508 goto done;
10510 err = get_short_logmsg(&logmsg, 34, commit);
10511 if (err)
10512 goto done;
10514 err = got_object_id_str(&id_str, commit_id);
10515 if (err)
10516 goto done;
10518 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10519 if (n < 0)
10520 err = got_ferror(f, GOT_ERR_IO);
10521 done:
10522 if (commit)
10523 got_object_commit_close(commit);
10524 free(id_str);
10525 free(logmsg);
10526 return err;
10529 static const struct got_error *
10530 histedit_write_commit_list(struct got_object_id_queue *commits,
10531 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10532 struct got_repository *repo)
10534 const struct got_error *err = NULL;
10535 struct got_object_qid *qid;
10536 const char *histedit_cmd = NULL;
10538 if (STAILQ_EMPTY(commits))
10539 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10541 STAILQ_FOREACH(qid, commits, entry) {
10542 histedit_cmd = got_histedit_cmds[0].name;
10543 if (edit_only)
10544 histedit_cmd = "edit";
10545 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10546 histedit_cmd = "fold";
10547 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10548 if (err)
10549 break;
10550 if (edit_logmsg_only) {
10551 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10552 if (n < 0) {
10553 err = got_ferror(f, GOT_ERR_IO);
10554 break;
10559 return err;
10562 static const struct got_error *
10563 write_cmd_list(FILE *f, const char *branch_name,
10564 struct got_object_id_queue *commits)
10566 const struct got_error *err = NULL;
10567 size_t i;
10568 int n;
10569 char *id_str;
10570 struct got_object_qid *qid;
10572 qid = STAILQ_FIRST(commits);
10573 err = got_object_id_str(&id_str, &qid->id);
10574 if (err)
10575 return err;
10577 n = fprintf(f,
10578 "# Editing the history of branch '%s' starting at\n"
10579 "# commit %s\n"
10580 "# Commits will be processed in order from top to "
10581 "bottom of this file.\n", branch_name, id_str);
10582 if (n < 0) {
10583 err = got_ferror(f, GOT_ERR_IO);
10584 goto done;
10587 n = fprintf(f, "# Available histedit commands:\n");
10588 if (n < 0) {
10589 err = got_ferror(f, GOT_ERR_IO);
10590 goto done;
10593 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10594 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10595 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10596 cmd->desc);
10597 if (n < 0) {
10598 err = got_ferror(f, GOT_ERR_IO);
10599 break;
10602 done:
10603 free(id_str);
10604 return err;
10607 static const struct got_error *
10608 histedit_syntax_error(int lineno)
10610 static char msg[42];
10611 int ret;
10613 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10614 lineno);
10615 if (ret < 0 || (size_t)ret >= sizeof(msg))
10616 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10618 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10621 static const struct got_error *
10622 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10623 char *logmsg, struct got_repository *repo)
10625 const struct got_error *err;
10626 struct got_commit_object *folded_commit = NULL;
10627 char *id_str, *folded_logmsg = NULL;
10629 err = got_object_id_str(&id_str, hle->commit_id);
10630 if (err)
10631 return err;
10633 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10634 if (err)
10635 goto done;
10637 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10638 if (err)
10639 goto done;
10640 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10641 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10642 folded_logmsg) == -1) {
10643 err = got_error_from_errno("asprintf");
10645 done:
10646 if (folded_commit)
10647 got_object_commit_close(folded_commit);
10648 free(id_str);
10649 free(folded_logmsg);
10650 return err;
10653 static struct got_histedit_list_entry *
10654 get_folded_commits(struct got_histedit_list_entry *hle)
10656 struct got_histedit_list_entry *prev, *folded = NULL;
10658 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10659 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10660 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10661 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10662 folded = prev;
10663 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10666 return folded;
10669 static const struct got_error *
10670 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10671 struct got_repository *repo)
10673 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10674 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10675 const struct got_error *err = NULL;
10676 struct got_commit_object *commit = NULL;
10677 int logmsg_len;
10678 int fd;
10679 struct got_histedit_list_entry *folded = NULL;
10681 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10682 if (err)
10683 return err;
10685 folded = get_folded_commits(hle);
10686 if (folded) {
10687 while (folded != hle) {
10688 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10689 folded = TAILQ_NEXT(folded, entry);
10690 continue;
10692 err = append_folded_commit_msg(&new_msg, folded,
10693 logmsg, repo);
10694 if (err)
10695 goto done;
10696 free(logmsg);
10697 logmsg = new_msg;
10698 folded = TAILQ_NEXT(folded, entry);
10702 err = got_object_id_str(&id_str, hle->commit_id);
10703 if (err)
10704 goto done;
10705 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10706 if (err)
10707 goto done;
10708 logmsg_len = asprintf(&new_msg,
10709 "%s\n# original log message of commit %s: %s",
10710 logmsg ? logmsg : "", id_str, orig_logmsg);
10711 if (logmsg_len == -1) {
10712 err = got_error_from_errno("asprintf");
10713 goto done;
10715 free(logmsg);
10716 logmsg = new_msg;
10718 err = got_object_id_str(&id_str, hle->commit_id);
10719 if (err)
10720 goto done;
10722 err = got_opentemp_named_fd(&logmsg_path, &fd,
10723 GOT_TMPDIR_STR "/got-logmsg");
10724 if (err)
10725 goto done;
10727 write(fd, logmsg, logmsg_len);
10728 close(fd);
10730 err = get_editor(&editor);
10731 if (err)
10732 goto done;
10734 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10735 logmsg_len, 0);
10736 if (err) {
10737 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10738 goto done;
10739 err = NULL;
10740 hle->logmsg = strdup(new_msg);
10741 if (hle->logmsg == NULL)
10742 err = got_error_from_errno("strdup");
10744 done:
10745 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10746 err = got_error_from_errno2("unlink", logmsg_path);
10747 free(logmsg_path);
10748 free(logmsg);
10749 free(orig_logmsg);
10750 free(editor);
10751 if (commit)
10752 got_object_commit_close(commit);
10753 return err;
10756 static const struct got_error *
10757 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10758 FILE *f, struct got_repository *repo)
10760 const struct got_error *err = NULL;
10761 char *line = NULL, *p, *end;
10762 size_t i, size;
10763 ssize_t len;
10764 int lineno = 0, lastcmd = -1;
10765 const struct got_histedit_cmd *cmd;
10766 struct got_object_id *commit_id = NULL;
10767 struct got_histedit_list_entry *hle = NULL;
10769 for (;;) {
10770 len = getline(&line, &size, f);
10771 if (len == -1) {
10772 const struct got_error *getline_err;
10773 if (feof(f))
10774 break;
10775 getline_err = got_error_from_errno("getline");
10776 err = got_ferror(f, getline_err->code);
10777 break;
10779 lineno++;
10780 p = line;
10781 while (isspace((unsigned char)p[0]))
10782 p++;
10783 if (p[0] == '#' || p[0] == '\0') {
10784 free(line);
10785 line = NULL;
10786 continue;
10788 cmd = NULL;
10789 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10790 cmd = &got_histedit_cmds[i];
10791 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10792 isspace((unsigned char)p[strlen(cmd->name)])) {
10793 p += strlen(cmd->name);
10794 break;
10796 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10797 p++;
10798 break;
10801 if (i == nitems(got_histedit_cmds)) {
10802 err = histedit_syntax_error(lineno);
10803 break;
10805 while (isspace((unsigned char)p[0]))
10806 p++;
10807 if (cmd->code == GOT_HISTEDIT_MESG) {
10808 if (lastcmd != GOT_HISTEDIT_PICK &&
10809 lastcmd != GOT_HISTEDIT_EDIT) {
10810 err = got_error(GOT_ERR_HISTEDIT_CMD);
10811 break;
10813 if (p[0] == '\0') {
10814 err = histedit_edit_logmsg(hle, repo);
10815 if (err)
10816 break;
10817 } else {
10818 hle->logmsg = strdup(p);
10819 if (hle->logmsg == NULL) {
10820 err = got_error_from_errno("strdup");
10821 break;
10824 free(line);
10825 line = NULL;
10826 lastcmd = cmd->code;
10827 continue;
10828 } else {
10829 end = p;
10830 while (end[0] && !isspace((unsigned char)end[0]))
10831 end++;
10832 *end = '\0';
10834 err = got_object_resolve_id_str(&commit_id, repo, p);
10835 if (err) {
10836 /* override error code */
10837 err = histedit_syntax_error(lineno);
10838 break;
10841 hle = malloc(sizeof(*hle));
10842 if (hle == NULL) {
10843 err = got_error_from_errno("malloc");
10844 break;
10846 hle->cmd = cmd;
10847 hle->commit_id = commit_id;
10848 hle->logmsg = NULL;
10849 commit_id = NULL;
10850 free(line);
10851 line = NULL;
10852 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10853 lastcmd = cmd->code;
10856 free(line);
10857 free(commit_id);
10858 return err;
10861 static const struct got_error *
10862 histedit_check_script(struct got_histedit_list *histedit_cmds,
10863 struct got_object_id_queue *commits, struct got_repository *repo)
10865 const struct got_error *err = NULL;
10866 struct got_object_qid *qid;
10867 struct got_histedit_list_entry *hle;
10868 static char msg[92];
10869 char *id_str;
10871 if (TAILQ_EMPTY(histedit_cmds))
10872 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10873 "histedit script contains no commands");
10874 if (STAILQ_EMPTY(commits))
10875 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10877 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10878 struct got_histedit_list_entry *hle2;
10879 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10880 if (hle == hle2)
10881 continue;
10882 if (got_object_id_cmp(hle->commit_id,
10883 hle2->commit_id) != 0)
10884 continue;
10885 err = got_object_id_str(&id_str, hle->commit_id);
10886 if (err)
10887 return err;
10888 snprintf(msg, sizeof(msg), "commit %s is listed "
10889 "more than once in histedit script", id_str);
10890 free(id_str);
10891 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10895 STAILQ_FOREACH(qid, commits, entry) {
10896 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10897 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10898 break;
10900 if (hle == NULL) {
10901 err = got_object_id_str(&id_str, &qid->id);
10902 if (err)
10903 return err;
10904 snprintf(msg, sizeof(msg),
10905 "commit %s missing from histedit script", id_str);
10906 free(id_str);
10907 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10911 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10912 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10913 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10914 "last commit in histedit script cannot be folded");
10916 return NULL;
10919 static const struct got_error *
10920 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10921 const char *path, struct got_object_id_queue *commits,
10922 struct got_repository *repo)
10924 const struct got_error *err = NULL;
10925 char *editor;
10926 FILE *f = NULL;
10928 err = get_editor(&editor);
10929 if (err)
10930 return err;
10932 if (spawn_editor(editor, path) == -1) {
10933 err = got_error_from_errno("failed spawning editor");
10934 goto done;
10937 f = fopen(path, "re");
10938 if (f == NULL) {
10939 err = got_error_from_errno("fopen");
10940 goto done;
10942 err = histedit_parse_list(histedit_cmds, f, repo);
10943 if (err)
10944 goto done;
10946 err = histedit_check_script(histedit_cmds, commits, repo);
10947 done:
10948 if (f && fclose(f) == EOF && err == NULL)
10949 err = got_error_from_errno("fclose");
10950 free(editor);
10951 return err;
10954 static const struct got_error *
10955 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10956 struct got_object_id_queue *, const char *, const char *,
10957 struct got_repository *);
10959 static const struct got_error *
10960 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10961 struct got_object_id_queue *commits, const char *branch_name,
10962 int edit_logmsg_only, int fold_only, int edit_only,
10963 struct got_repository *repo)
10965 const struct got_error *err;
10966 FILE *f = NULL;
10967 char *path = NULL;
10969 err = got_opentemp_named(&path, &f, "got-histedit");
10970 if (err)
10971 return err;
10973 err = write_cmd_list(f, branch_name, commits);
10974 if (err)
10975 goto done;
10977 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10978 fold_only, edit_only, repo);
10979 if (err)
10980 goto done;
10982 if (edit_logmsg_only || fold_only || edit_only) {
10983 rewind(f);
10984 err = histedit_parse_list(histedit_cmds, f, repo);
10985 } else {
10986 if (fclose(f) == EOF) {
10987 err = got_error_from_errno("fclose");
10988 goto done;
10990 f = NULL;
10991 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10992 if (err) {
10993 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10994 err->code != GOT_ERR_HISTEDIT_CMD)
10995 goto done;
10996 err = histedit_edit_list_retry(histedit_cmds, err,
10997 commits, path, branch_name, repo);
11000 done:
11001 if (f && fclose(f) == EOF && err == NULL)
11002 err = got_error_from_errno("fclose");
11003 if (path && unlink(path) != 0 && err == NULL)
11004 err = got_error_from_errno2("unlink", path);
11005 free(path);
11006 return err;
11009 static const struct got_error *
11010 histedit_save_list(struct got_histedit_list *histedit_cmds,
11011 struct got_worktree *worktree, struct got_repository *repo)
11013 const struct got_error *err = NULL;
11014 char *path = NULL;
11015 FILE *f = NULL;
11016 struct got_histedit_list_entry *hle;
11017 struct got_commit_object *commit = NULL;
11019 err = got_worktree_get_histedit_script_path(&path, worktree);
11020 if (err)
11021 return err;
11023 f = fopen(path, "we");
11024 if (f == NULL) {
11025 err = got_error_from_errno2("fopen", path);
11026 goto done;
11028 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11029 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11030 repo);
11031 if (err)
11032 break;
11034 if (hle->logmsg) {
11035 int n = fprintf(f, "%c %s\n",
11036 GOT_HISTEDIT_MESG, hle->logmsg);
11037 if (n < 0) {
11038 err = got_ferror(f, GOT_ERR_IO);
11039 break;
11043 done:
11044 if (f && fclose(f) == EOF && err == NULL)
11045 err = got_error_from_errno("fclose");
11046 free(path);
11047 if (commit)
11048 got_object_commit_close(commit);
11049 return err;
11052 static void
11053 histedit_free_list(struct got_histedit_list *histedit_cmds)
11055 struct got_histedit_list_entry *hle;
11057 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11058 TAILQ_REMOVE(histedit_cmds, hle, entry);
11059 free(hle);
11063 static const struct got_error *
11064 histedit_load_list(struct got_histedit_list *histedit_cmds,
11065 const char *path, struct got_repository *repo)
11067 const struct got_error *err = NULL;
11068 FILE *f = NULL;
11070 f = fopen(path, "re");
11071 if (f == NULL) {
11072 err = got_error_from_errno2("fopen", path);
11073 goto done;
11076 err = histedit_parse_list(histedit_cmds, f, repo);
11077 done:
11078 if (f && fclose(f) == EOF && err == NULL)
11079 err = got_error_from_errno("fclose");
11080 return err;
11083 static const struct got_error *
11084 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11085 const struct got_error *edit_err, struct got_object_id_queue *commits,
11086 const char *path, const char *branch_name, struct got_repository *repo)
11088 const struct got_error *err = NULL, *prev_err = edit_err;
11089 int resp = ' ';
11091 while (resp != 'c' && resp != 'r' && resp != 'a') {
11092 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11093 "or (a)bort: ", getprogname(), prev_err->msg);
11094 resp = getchar();
11095 if (resp == '\n')
11096 resp = getchar();
11097 if (resp == 'c') {
11098 histedit_free_list(histedit_cmds);
11099 err = histedit_run_editor(histedit_cmds, path, commits,
11100 repo);
11101 if (err) {
11102 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11103 err->code != GOT_ERR_HISTEDIT_CMD)
11104 break;
11105 prev_err = err;
11106 resp = ' ';
11107 continue;
11109 break;
11110 } else if (resp == 'r') {
11111 histedit_free_list(histedit_cmds);
11112 err = histedit_edit_script(histedit_cmds,
11113 commits, branch_name, 0, 0, 0, repo);
11114 if (err) {
11115 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11116 err->code != GOT_ERR_HISTEDIT_CMD)
11117 break;
11118 prev_err = err;
11119 resp = ' ';
11120 continue;
11122 break;
11123 } else if (resp == 'a') {
11124 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11125 break;
11126 } else
11127 printf("invalid response '%c'\n", resp);
11130 return err;
11133 static const struct got_error *
11134 histedit_complete(struct got_worktree *worktree,
11135 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11136 struct got_reference *branch, struct got_repository *repo)
11138 printf("Switching work tree to %s\n",
11139 got_ref_get_symref_target(branch));
11140 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11141 branch, repo);
11144 static const struct got_error *
11145 show_histedit_progress(struct got_commit_object *commit,
11146 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11148 const struct got_error *err;
11149 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11151 err = got_object_id_str(&old_id_str, hle->commit_id);
11152 if (err)
11153 goto done;
11155 if (new_id) {
11156 err = got_object_id_str(&new_id_str, new_id);
11157 if (err)
11158 goto done;
11161 old_id_str[12] = '\0';
11162 if (new_id_str)
11163 new_id_str[12] = '\0';
11165 if (hle->logmsg) {
11166 logmsg = strdup(hle->logmsg);
11167 if (logmsg == NULL) {
11168 err = got_error_from_errno("strdup");
11169 goto done;
11171 trim_logmsg(logmsg, 42);
11172 } else {
11173 err = get_short_logmsg(&logmsg, 42, commit);
11174 if (err)
11175 goto done;
11178 switch (hle->cmd->code) {
11179 case GOT_HISTEDIT_PICK:
11180 case GOT_HISTEDIT_EDIT:
11181 printf("%s -> %s: %s\n", old_id_str,
11182 new_id_str ? new_id_str : "no-op change", logmsg);
11183 break;
11184 case GOT_HISTEDIT_DROP:
11185 case GOT_HISTEDIT_FOLD:
11186 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11187 logmsg);
11188 break;
11189 default:
11190 break;
11192 done:
11193 free(old_id_str);
11194 free(new_id_str);
11195 return err;
11198 static const struct got_error *
11199 histedit_commit(struct got_pathlist_head *merged_paths,
11200 struct got_worktree *worktree, struct got_fileindex *fileindex,
11201 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11202 const char *committer, struct got_repository *repo)
11204 const struct got_error *err;
11205 struct got_commit_object *commit;
11206 struct got_object_id *new_commit_id;
11208 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11209 && hle->logmsg == NULL) {
11210 err = histedit_edit_logmsg(hle, repo);
11211 if (err)
11212 return err;
11215 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11216 if (err)
11217 return err;
11219 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11220 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11221 hle->logmsg, repo);
11222 if (err) {
11223 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11224 goto done;
11225 err = show_histedit_progress(commit, hle, NULL);
11226 } else {
11227 err = show_histedit_progress(commit, hle, new_commit_id);
11228 free(new_commit_id);
11230 done:
11231 got_object_commit_close(commit);
11232 return err;
11235 static const struct got_error *
11236 histedit_skip_commit(struct got_histedit_list_entry *hle,
11237 struct got_worktree *worktree, struct got_repository *repo)
11239 const struct got_error *error;
11240 struct got_commit_object *commit;
11242 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11243 repo);
11244 if (error)
11245 return error;
11247 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11248 if (error)
11249 return error;
11251 error = show_histedit_progress(commit, hle, NULL);
11252 got_object_commit_close(commit);
11253 return error;
11256 static const struct got_error *
11257 check_local_changes(void *arg, unsigned char status,
11258 unsigned char staged_status, const char *path,
11259 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11260 struct got_object_id *commit_id, int dirfd, const char *de_name)
11262 int *have_local_changes = arg;
11264 switch (status) {
11265 case GOT_STATUS_ADD:
11266 case GOT_STATUS_DELETE:
11267 case GOT_STATUS_MODIFY:
11268 case GOT_STATUS_CONFLICT:
11269 *have_local_changes = 1;
11270 return got_error(GOT_ERR_CANCELLED);
11271 default:
11272 break;
11275 switch (staged_status) {
11276 case GOT_STATUS_ADD:
11277 case GOT_STATUS_DELETE:
11278 case GOT_STATUS_MODIFY:
11279 *have_local_changes = 1;
11280 return got_error(GOT_ERR_CANCELLED);
11281 default:
11282 break;
11285 return NULL;
11288 static const struct got_error *
11289 cmd_histedit(int argc, char *argv[])
11291 const struct got_error *error = NULL;
11292 struct got_worktree *worktree = NULL;
11293 struct got_fileindex *fileindex = NULL;
11294 struct got_repository *repo = NULL;
11295 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11296 struct got_reference *branch = NULL;
11297 struct got_reference *tmp_branch = NULL;
11298 struct got_object_id *resume_commit_id = NULL;
11299 struct got_object_id *base_commit_id = NULL;
11300 struct got_object_id *head_commit_id = NULL;
11301 struct got_commit_object *commit = NULL;
11302 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11303 struct got_update_progress_arg upa;
11304 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11305 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11306 int list_backups = 0, delete_backups = 0;
11307 const char *edit_script_path = NULL;
11308 struct got_object_id_queue commits;
11309 struct got_pathlist_head merged_paths;
11310 const struct got_object_id_queue *parent_ids;
11311 struct got_object_qid *pid;
11312 struct got_histedit_list histedit_cmds;
11313 struct got_histedit_list_entry *hle;
11314 int *pack_fds = NULL;
11316 STAILQ_INIT(&commits);
11317 TAILQ_INIT(&histedit_cmds);
11318 TAILQ_INIT(&merged_paths);
11319 memset(&upa, 0, sizeof(upa));
11321 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11322 switch (ch) {
11323 case 'a':
11324 abort_edit = 1;
11325 break;
11326 case 'c':
11327 continue_edit = 1;
11328 break;
11329 case 'e':
11330 edit_only = 1;
11331 break;
11332 case 'F':
11333 edit_script_path = optarg;
11334 break;
11335 case 'f':
11336 fold_only = 1;
11337 break;
11338 case 'l':
11339 list_backups = 1;
11340 break;
11341 case 'm':
11342 edit_logmsg_only = 1;
11343 break;
11344 case 'X':
11345 delete_backups = 1;
11346 break;
11347 default:
11348 usage_histedit();
11349 /* NOTREACHED */
11353 argc -= optind;
11354 argv += optind;
11356 #ifndef PROFILE
11357 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11358 "unveil", NULL) == -1)
11359 err(1, "pledge");
11360 #endif
11361 if (abort_edit && continue_edit)
11362 option_conflict('a', 'c');
11363 if (edit_script_path && edit_logmsg_only)
11364 option_conflict('F', 'm');
11365 if (abort_edit && edit_logmsg_only)
11366 option_conflict('a', 'm');
11367 if (continue_edit && edit_logmsg_only)
11368 option_conflict('c', 'm');
11369 if (abort_edit && fold_only)
11370 option_conflict('a', 'f');
11371 if (continue_edit && fold_only)
11372 option_conflict('c', 'f');
11373 if (fold_only && edit_logmsg_only)
11374 option_conflict('f', 'm');
11375 if (edit_script_path && fold_only)
11376 option_conflict('F', 'f');
11377 if (abort_edit && edit_only)
11378 option_conflict('a', 'e');
11379 if (continue_edit && edit_only)
11380 option_conflict('c', 'e');
11381 if (edit_only && edit_logmsg_only)
11382 option_conflict('e', 'm');
11383 if (edit_script_path && edit_only)
11384 option_conflict('F', 'e');
11385 if (list_backups) {
11386 if (abort_edit)
11387 option_conflict('l', 'a');
11388 if (continue_edit)
11389 option_conflict('l', 'c');
11390 if (edit_script_path)
11391 option_conflict('l', 'F');
11392 if (edit_logmsg_only)
11393 option_conflict('l', 'm');
11394 if (fold_only)
11395 option_conflict('l', 'f');
11396 if (edit_only)
11397 option_conflict('l', 'e');
11398 if (delete_backups)
11399 option_conflict('l', 'X');
11400 if (argc != 0 && argc != 1)
11401 usage_histedit();
11402 } else if (delete_backups) {
11403 if (abort_edit)
11404 option_conflict('X', 'a');
11405 if (continue_edit)
11406 option_conflict('X', 'c');
11407 if (edit_script_path)
11408 option_conflict('X', 'F');
11409 if (edit_logmsg_only)
11410 option_conflict('X', 'm');
11411 if (fold_only)
11412 option_conflict('X', 'f');
11413 if (edit_only)
11414 option_conflict('X', 'e');
11415 if (list_backups)
11416 option_conflict('X', 'l');
11417 if (argc != 0 && argc != 1)
11418 usage_histedit();
11419 } else if (argc != 0)
11420 usage_histedit();
11423 * This command cannot apply unveil(2) in all cases because the
11424 * user may choose to run an editor to edit the histedit script
11425 * and to edit individual commit log messages.
11426 * unveil(2) traverses exec(2); if an editor is used we have to
11427 * apply unveil after edit script and log messages have been written.
11428 * XXX TODO: Make use of unveil(2) where possible.
11431 cwd = getcwd(NULL, 0);
11432 if (cwd == NULL) {
11433 error = got_error_from_errno("getcwd");
11434 goto done;
11437 error = got_repo_pack_fds_open(&pack_fds);
11438 if (error != NULL)
11439 goto done;
11441 error = got_worktree_open(&worktree, cwd);
11442 if (error) {
11443 if (list_backups || delete_backups) {
11444 if (error->code != GOT_ERR_NOT_WORKTREE)
11445 goto done;
11446 } else {
11447 if (error->code == GOT_ERR_NOT_WORKTREE)
11448 error = wrap_not_worktree_error(error,
11449 "histedit", cwd);
11450 goto done;
11454 if (list_backups || delete_backups) {
11455 error = got_repo_open(&repo,
11456 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11457 NULL, pack_fds);
11458 if (error != NULL)
11459 goto done;
11460 error = apply_unveil(got_repo_get_path(repo), 0,
11461 worktree ? got_worktree_get_root_path(worktree) : NULL);
11462 if (error)
11463 goto done;
11464 error = process_backup_refs(
11465 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11466 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11467 goto done; /* nothing else to do */
11470 error = get_gitconfig_path(&gitconfig_path);
11471 if (error)
11472 goto done;
11473 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11474 gitconfig_path, pack_fds);
11475 if (error != NULL)
11476 goto done;
11478 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11479 if (error)
11480 goto done;
11481 if (rebase_in_progress) {
11482 error = got_error(GOT_ERR_REBASING);
11483 goto done;
11486 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11487 repo);
11488 if (error)
11489 goto done;
11490 if (merge_in_progress) {
11491 error = got_error(GOT_ERR_MERGE_BUSY);
11492 goto done;
11495 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11496 if (error)
11497 goto done;
11499 if (edit_in_progress && edit_logmsg_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 -m option can be used");
11504 goto done;
11506 if (edit_in_progress && fold_only) {
11507 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11508 "histedit operation is in progress in this "
11509 "work tree and must be continued or aborted "
11510 "before the -f option can be used");
11511 goto done;
11513 if (edit_in_progress && edit_only) {
11514 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11515 "histedit operation is in progress in this "
11516 "work tree and must be continued or aborted "
11517 "before the -e option can be used");
11518 goto done;
11521 if (edit_in_progress && abort_edit) {
11522 error = got_worktree_histedit_continue(&resume_commit_id,
11523 &tmp_branch, &branch, &base_commit_id, &fileindex,
11524 worktree, repo);
11525 if (error)
11526 goto done;
11527 printf("Switching work tree to %s\n",
11528 got_ref_get_symref_target(branch));
11529 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11530 branch, base_commit_id, abort_progress, &upa);
11531 if (error)
11532 goto done;
11533 printf("Histedit of %s aborted\n",
11534 got_ref_get_symref_target(branch));
11535 print_merge_progress_stats(&upa);
11536 goto done; /* nothing else to do */
11537 } else if (abort_edit) {
11538 error = got_error(GOT_ERR_NOT_HISTEDIT);
11539 goto done;
11542 error = get_author(&committer, repo, worktree);
11543 if (error)
11544 goto done;
11546 if (continue_edit) {
11547 char *path;
11549 if (!edit_in_progress) {
11550 error = got_error(GOT_ERR_NOT_HISTEDIT);
11551 goto done;
11554 error = got_worktree_get_histedit_script_path(&path, worktree);
11555 if (error)
11556 goto done;
11558 error = histedit_load_list(&histedit_cmds, path, repo);
11559 free(path);
11560 if (error)
11561 goto done;
11563 error = got_worktree_histedit_continue(&resume_commit_id,
11564 &tmp_branch, &branch, &base_commit_id, &fileindex,
11565 worktree, repo);
11566 if (error)
11567 goto done;
11569 error = got_ref_resolve(&head_commit_id, repo, branch);
11570 if (error)
11571 goto done;
11573 error = got_object_open_as_commit(&commit, repo,
11574 head_commit_id);
11575 if (error)
11576 goto done;
11577 parent_ids = got_object_commit_get_parent_ids(commit);
11578 pid = STAILQ_FIRST(parent_ids);
11579 if (pid == NULL) {
11580 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11581 goto done;
11583 error = collect_commits(&commits, head_commit_id, &pid->id,
11584 base_commit_id, got_worktree_get_path_prefix(worktree),
11585 GOT_ERR_HISTEDIT_PATH, repo);
11586 got_object_commit_close(commit);
11587 commit = NULL;
11588 if (error)
11589 goto done;
11590 } else {
11591 if (edit_in_progress) {
11592 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11593 goto done;
11596 error = got_ref_open(&branch, repo,
11597 got_worktree_get_head_ref_name(worktree), 0);
11598 if (error != NULL)
11599 goto done;
11601 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11602 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11603 "will not edit commit history of a branch outside "
11604 "the \"refs/heads/\" reference namespace");
11605 goto done;
11608 error = got_ref_resolve(&head_commit_id, repo, branch);
11609 got_ref_close(branch);
11610 branch = NULL;
11611 if (error)
11612 goto done;
11614 error = got_object_open_as_commit(&commit, repo,
11615 head_commit_id);
11616 if (error)
11617 goto done;
11618 parent_ids = got_object_commit_get_parent_ids(commit);
11619 pid = STAILQ_FIRST(parent_ids);
11620 if (pid == NULL) {
11621 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11622 goto done;
11624 error = collect_commits(&commits, head_commit_id, &pid->id,
11625 got_worktree_get_base_commit_id(worktree),
11626 got_worktree_get_path_prefix(worktree),
11627 GOT_ERR_HISTEDIT_PATH, repo);
11628 got_object_commit_close(commit);
11629 commit = NULL;
11630 if (error)
11631 goto done;
11633 if (STAILQ_EMPTY(&commits)) {
11634 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11635 goto done;
11638 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11639 &base_commit_id, &fileindex, worktree, repo);
11640 if (error)
11641 goto done;
11643 if (edit_script_path) {
11644 error = histedit_load_list(&histedit_cmds,
11645 edit_script_path, repo);
11646 if (error) {
11647 got_worktree_histedit_abort(worktree, fileindex,
11648 repo, branch, base_commit_id,
11649 abort_progress, &upa);
11650 print_merge_progress_stats(&upa);
11651 goto done;
11653 } else {
11654 const char *branch_name;
11655 branch_name = got_ref_get_symref_target(branch);
11656 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11657 branch_name += 11;
11658 error = histedit_edit_script(&histedit_cmds, &commits,
11659 branch_name, edit_logmsg_only, fold_only,
11660 edit_only, repo);
11661 if (error) {
11662 got_worktree_histedit_abort(worktree, fileindex,
11663 repo, branch, base_commit_id,
11664 abort_progress, &upa);
11665 print_merge_progress_stats(&upa);
11666 goto done;
11671 error = histedit_save_list(&histedit_cmds, worktree,
11672 repo);
11673 if (error) {
11674 got_worktree_histedit_abort(worktree, fileindex,
11675 repo, branch, base_commit_id,
11676 abort_progress, &upa);
11677 print_merge_progress_stats(&upa);
11678 goto done;
11683 error = histedit_check_script(&histedit_cmds, &commits, repo);
11684 if (error)
11685 goto done;
11687 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11688 if (resume_commit_id) {
11689 if (got_object_id_cmp(hle->commit_id,
11690 resume_commit_id) != 0)
11691 continue;
11693 resume_commit_id = NULL;
11694 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11695 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11696 error = histedit_skip_commit(hle, worktree,
11697 repo);
11698 if (error)
11699 goto done;
11700 } else {
11701 struct got_pathlist_head paths;
11702 int have_changes = 0;
11704 TAILQ_INIT(&paths);
11705 error = got_pathlist_append(&paths, "", NULL);
11706 if (error)
11707 goto done;
11708 error = got_worktree_status(worktree, &paths,
11709 repo, 0, check_local_changes, &have_changes,
11710 check_cancelled, NULL);
11711 got_pathlist_free(&paths);
11712 if (error) {
11713 if (error->code != GOT_ERR_CANCELLED)
11714 goto done;
11715 if (sigint_received || sigpipe_received)
11716 goto done;
11718 if (have_changes) {
11719 error = histedit_commit(NULL, worktree,
11720 fileindex, tmp_branch, hle,
11721 committer, repo);
11722 if (error)
11723 goto done;
11724 } else {
11725 error = got_object_open_as_commit(
11726 &commit, repo, hle->commit_id);
11727 if (error)
11728 goto done;
11729 error = show_histedit_progress(commit,
11730 hle, NULL);
11731 got_object_commit_close(commit);
11732 commit = NULL;
11733 if (error)
11734 goto done;
11737 continue;
11740 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11741 error = histedit_skip_commit(hle, worktree, repo);
11742 if (error)
11743 goto done;
11744 continue;
11747 error = got_object_open_as_commit(&commit, repo,
11748 hle->commit_id);
11749 if (error)
11750 goto done;
11751 parent_ids = got_object_commit_get_parent_ids(commit);
11752 pid = STAILQ_FIRST(parent_ids);
11754 error = got_worktree_histedit_merge_files(&merged_paths,
11755 worktree, fileindex, &pid->id, hle->commit_id, repo,
11756 update_progress, &upa, check_cancelled, NULL);
11757 if (error)
11758 goto done;
11759 got_object_commit_close(commit);
11760 commit = NULL;
11762 print_merge_progress_stats(&upa);
11763 if (upa.conflicts > 0 || upa.missing > 0 ||
11764 upa.not_deleted > 0 || upa.unversioned > 0) {
11765 if (upa.conflicts > 0) {
11766 error = show_rebase_merge_conflict(
11767 hle->commit_id, repo);
11768 if (error)
11769 goto done;
11771 got_worktree_rebase_pathlist_free(&merged_paths);
11772 break;
11775 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11776 char *id_str;
11777 error = got_object_id_str(&id_str, hle->commit_id);
11778 if (error)
11779 goto done;
11780 printf("Stopping histedit for amending commit %s\n",
11781 id_str);
11782 free(id_str);
11783 got_worktree_rebase_pathlist_free(&merged_paths);
11784 error = got_worktree_histedit_postpone(worktree,
11785 fileindex);
11786 goto done;
11789 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11790 error = histedit_skip_commit(hle, worktree, repo);
11791 if (error)
11792 goto done;
11793 continue;
11796 error = histedit_commit(&merged_paths, worktree, fileindex,
11797 tmp_branch, hle, committer, repo);
11798 got_worktree_rebase_pathlist_free(&merged_paths);
11799 if (error)
11800 goto done;
11803 if (upa.conflicts > 0 || upa.missing > 0 ||
11804 upa.not_deleted > 0 || upa.unversioned > 0) {
11805 error = got_worktree_histedit_postpone(worktree, fileindex);
11806 if (error)
11807 goto done;
11808 if (upa.conflicts > 0 && upa.missing == 0 &&
11809 upa.not_deleted == 0 && upa.unversioned == 0) {
11810 error = got_error_msg(GOT_ERR_CONFLICTS,
11811 "conflicts must be resolved before histedit "
11812 "can continue");
11813 } else if (upa.conflicts > 0) {
11814 error = got_error_msg(GOT_ERR_CONFLICTS,
11815 "conflicts must be resolved before histedit "
11816 "can continue; changes destined for some "
11817 "files were not yet merged and should be "
11818 "merged manually if required before the "
11819 "histedit operation is continued");
11820 } else {
11821 error = got_error_msg(GOT_ERR_CONFLICTS,
11822 "changes destined for some files were not "
11823 "yet merged and should be merged manually "
11824 "if required before the histedit operation "
11825 "is continued");
11827 } else
11828 error = histedit_complete(worktree, fileindex, tmp_branch,
11829 branch, repo);
11830 done:
11831 free(cwd);
11832 free(committer);
11833 free(gitconfig_path);
11834 got_object_id_queue_free(&commits);
11835 histedit_free_list(&histedit_cmds);
11836 free(head_commit_id);
11837 free(base_commit_id);
11838 free(resume_commit_id);
11839 if (commit)
11840 got_object_commit_close(commit);
11841 if (branch)
11842 got_ref_close(branch);
11843 if (tmp_branch)
11844 got_ref_close(tmp_branch);
11845 if (worktree)
11846 got_worktree_close(worktree);
11847 if (repo) {
11848 const struct got_error *close_err = got_repo_close(repo);
11849 if (error == NULL)
11850 error = close_err;
11852 if (pack_fds) {
11853 const struct got_error *pack_err =
11854 got_repo_pack_fds_close(pack_fds);
11855 if (error == NULL)
11856 error = pack_err;
11858 return error;
11861 __dead static void
11862 usage_integrate(void)
11864 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11865 exit(1);
11868 static const struct got_error *
11869 cmd_integrate(int argc, char *argv[])
11871 const struct got_error *error = NULL;
11872 struct got_repository *repo = NULL;
11873 struct got_worktree *worktree = NULL;
11874 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11875 const char *branch_arg = NULL;
11876 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11877 struct got_fileindex *fileindex = NULL;
11878 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11879 int ch;
11880 struct got_update_progress_arg upa;
11881 int *pack_fds = NULL;
11883 while ((ch = getopt(argc, argv, "")) != -1) {
11884 switch (ch) {
11885 default:
11886 usage_integrate();
11887 /* NOTREACHED */
11891 argc -= optind;
11892 argv += optind;
11894 if (argc != 1)
11895 usage_integrate();
11896 branch_arg = argv[0];
11897 #ifndef PROFILE
11898 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11899 "unveil", NULL) == -1)
11900 err(1, "pledge");
11901 #endif
11902 cwd = getcwd(NULL, 0);
11903 if (cwd == NULL) {
11904 error = got_error_from_errno("getcwd");
11905 goto done;
11908 error = got_repo_pack_fds_open(&pack_fds);
11909 if (error != NULL)
11910 goto done;
11912 error = got_worktree_open(&worktree, cwd);
11913 if (error) {
11914 if (error->code == GOT_ERR_NOT_WORKTREE)
11915 error = wrap_not_worktree_error(error, "integrate",
11916 cwd);
11917 goto done;
11920 error = check_rebase_or_histedit_in_progress(worktree);
11921 if (error)
11922 goto done;
11924 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11925 NULL, pack_fds);
11926 if (error != NULL)
11927 goto done;
11929 error = apply_unveil(got_repo_get_path(repo), 0,
11930 got_worktree_get_root_path(worktree));
11931 if (error)
11932 goto done;
11934 error = check_merge_in_progress(worktree, repo);
11935 if (error)
11936 goto done;
11938 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11939 error = got_error_from_errno("asprintf");
11940 goto done;
11943 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11944 &base_branch_ref, worktree, refname, repo);
11945 if (error)
11946 goto done;
11948 refname = strdup(got_ref_get_name(branch_ref));
11949 if (refname == NULL) {
11950 error = got_error_from_errno("strdup");
11951 got_worktree_integrate_abort(worktree, fileindex, repo,
11952 branch_ref, base_branch_ref);
11953 goto done;
11955 base_refname = strdup(got_ref_get_name(base_branch_ref));
11956 if (base_refname == NULL) {
11957 error = got_error_from_errno("strdup");
11958 got_worktree_integrate_abort(worktree, fileindex, repo,
11959 branch_ref, base_branch_ref);
11960 goto done;
11962 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
11963 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
11964 got_worktree_integrate_abort(worktree, fileindex, repo,
11965 branch_ref, base_branch_ref);
11966 goto done;
11969 error = got_ref_resolve(&commit_id, repo, branch_ref);
11970 if (error)
11971 goto done;
11973 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11974 if (error)
11975 goto done;
11977 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11978 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11979 "specified branch has already been integrated");
11980 got_worktree_integrate_abort(worktree, fileindex, repo,
11981 branch_ref, base_branch_ref);
11982 goto done;
11985 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11986 if (error) {
11987 if (error->code == GOT_ERR_ANCESTRY)
11988 error = got_error(GOT_ERR_REBASE_REQUIRED);
11989 got_worktree_integrate_abort(worktree, fileindex, repo,
11990 branch_ref, base_branch_ref);
11991 goto done;
11994 memset(&upa, 0, sizeof(upa));
11995 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11996 branch_ref, base_branch_ref, update_progress, &upa,
11997 check_cancelled, NULL);
11998 if (error)
11999 goto done;
12001 printf("Integrated %s into %s\n", refname, base_refname);
12002 print_update_progress_stats(&upa);
12003 done:
12004 if (repo) {
12005 const struct got_error *close_err = got_repo_close(repo);
12006 if (error == NULL)
12007 error = close_err;
12009 if (worktree)
12010 got_worktree_close(worktree);
12011 if (pack_fds) {
12012 const struct got_error *pack_err =
12013 got_repo_pack_fds_close(pack_fds);
12014 if (error == NULL)
12015 error = pack_err;
12017 free(cwd);
12018 free(base_commit_id);
12019 free(commit_id);
12020 free(refname);
12021 free(base_refname);
12022 return error;
12025 __dead static void
12026 usage_merge(void)
12028 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12029 exit(1);
12032 static const struct got_error *
12033 cmd_merge(int argc, char *argv[])
12035 const struct got_error *error = NULL;
12036 struct got_worktree *worktree = NULL;
12037 struct got_repository *repo = NULL;
12038 struct got_fileindex *fileindex = NULL;
12039 char *cwd = NULL, *id_str = NULL, *author = NULL;
12040 struct got_reference *branch = NULL, *wt_branch = NULL;
12041 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12042 struct got_object_id *wt_branch_tip = NULL;
12043 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12044 int interrupt_merge = 0;
12045 struct got_update_progress_arg upa;
12046 struct got_object_id *merge_commit_id = NULL;
12047 char *branch_name = NULL;
12048 int *pack_fds = NULL;
12050 memset(&upa, 0, sizeof(upa));
12052 while ((ch = getopt(argc, argv, "acn")) != -1) {
12053 switch (ch) {
12054 case 'a':
12055 abort_merge = 1;
12056 break;
12057 case 'c':
12058 continue_merge = 1;
12059 break;
12060 case 'n':
12061 interrupt_merge = 1;
12062 break;
12063 default:
12064 usage_rebase();
12065 /* NOTREACHED */
12069 argc -= optind;
12070 argv += optind;
12072 #ifndef PROFILE
12073 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12074 "unveil", NULL) == -1)
12075 err(1, "pledge");
12076 #endif
12078 if (abort_merge && continue_merge)
12079 option_conflict('a', 'c');
12080 if (abort_merge || continue_merge) {
12081 if (argc != 0)
12082 usage_merge();
12083 } else if (argc != 1)
12084 usage_merge();
12086 cwd = getcwd(NULL, 0);
12087 if (cwd == NULL) {
12088 error = got_error_from_errno("getcwd");
12089 goto done;
12092 error = got_repo_pack_fds_open(&pack_fds);
12093 if (error != NULL)
12094 goto done;
12096 error = got_worktree_open(&worktree, cwd);
12097 if (error) {
12098 if (error->code == GOT_ERR_NOT_WORKTREE)
12099 error = wrap_not_worktree_error(error,
12100 "merge", cwd);
12101 goto done;
12104 error = got_repo_open(&repo,
12105 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12106 pack_fds);
12107 if (error != NULL)
12108 goto done;
12110 error = apply_unveil(got_repo_get_path(repo), 0,
12111 worktree ? got_worktree_get_root_path(worktree) : NULL);
12112 if (error)
12113 goto done;
12115 error = check_rebase_or_histedit_in_progress(worktree);
12116 if (error)
12117 goto done;
12119 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12120 repo);
12121 if (error)
12122 goto done;
12124 if (abort_merge) {
12125 if (!merge_in_progress) {
12126 error = got_error(GOT_ERR_NOT_MERGING);
12127 goto done;
12129 error = got_worktree_merge_continue(&branch_name,
12130 &branch_tip, &fileindex, worktree, repo);
12131 if (error)
12132 goto done;
12133 error = got_worktree_merge_abort(worktree, fileindex, repo,
12134 abort_progress, &upa);
12135 if (error)
12136 goto done;
12137 printf("Merge of %s aborted\n", branch_name);
12138 goto done; /* nothing else to do */
12141 error = get_author(&author, repo, worktree);
12142 if (error)
12143 goto done;
12145 if (continue_merge) {
12146 if (!merge_in_progress) {
12147 error = got_error(GOT_ERR_NOT_MERGING);
12148 goto done;
12150 error = got_worktree_merge_continue(&branch_name,
12151 &branch_tip, &fileindex, worktree, repo);
12152 if (error)
12153 goto done;
12154 } else {
12155 error = got_ref_open(&branch, repo, argv[0], 0);
12156 if (error != NULL)
12157 goto done;
12158 branch_name = strdup(got_ref_get_name(branch));
12159 if (branch_name == NULL) {
12160 error = got_error_from_errno("strdup");
12161 goto done;
12163 error = got_ref_resolve(&branch_tip, repo, branch);
12164 if (error)
12165 goto done;
12168 error = got_ref_open(&wt_branch, repo,
12169 got_worktree_get_head_ref_name(worktree), 0);
12170 if (error)
12171 goto done;
12172 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12173 if (error)
12174 goto done;
12175 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12176 wt_branch_tip, branch_tip, 0, repo,
12177 check_cancelled, NULL);
12178 if (error && error->code != GOT_ERR_ANCESTRY)
12179 goto done;
12181 if (!continue_merge) {
12182 error = check_path_prefix(wt_branch_tip, branch_tip,
12183 got_worktree_get_path_prefix(worktree),
12184 GOT_ERR_MERGE_PATH, repo);
12185 if (error)
12186 goto done;
12187 if (yca_id) {
12188 error = check_same_branch(wt_branch_tip, branch,
12189 yca_id, repo);
12190 if (error) {
12191 if (error->code != GOT_ERR_ANCESTRY)
12192 goto done;
12193 error = NULL;
12194 } else {
12195 static char msg[512];
12196 snprintf(msg, sizeof(msg),
12197 "cannot create a merge commit because "
12198 "%s is based on %s; %s can be integrated "
12199 "with 'got integrate' instead", branch_name,
12200 got_worktree_get_head_ref_name(worktree),
12201 branch_name);
12202 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12203 goto done;
12206 error = got_worktree_merge_prepare(&fileindex, worktree,
12207 branch, repo);
12208 if (error)
12209 goto done;
12211 error = got_worktree_merge_branch(worktree, fileindex,
12212 yca_id, branch_tip, repo, update_progress, &upa,
12213 check_cancelled, NULL);
12214 if (error)
12215 goto done;
12216 print_merge_progress_stats(&upa);
12217 if (!upa.did_something) {
12218 error = got_worktree_merge_abort(worktree, fileindex,
12219 repo, abort_progress, &upa);
12220 if (error)
12221 goto done;
12222 printf("Already up-to-date\n");
12223 goto done;
12227 if (interrupt_merge) {
12228 error = got_worktree_merge_postpone(worktree, fileindex);
12229 if (error)
12230 goto done;
12231 printf("Merge of %s interrupted on request\n", branch_name);
12232 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12233 upa.not_deleted > 0 || upa.unversioned > 0) {
12234 error = got_worktree_merge_postpone(worktree, fileindex);
12235 if (error)
12236 goto done;
12237 if (upa.conflicts > 0 && upa.missing == 0 &&
12238 upa.not_deleted == 0 && upa.unversioned == 0) {
12239 error = got_error_msg(GOT_ERR_CONFLICTS,
12240 "conflicts must be resolved before merging "
12241 "can continue");
12242 } else if (upa.conflicts > 0) {
12243 error = got_error_msg(GOT_ERR_CONFLICTS,
12244 "conflicts must be resolved before merging "
12245 "can continue; changes destined for some "
12246 "files were not yet merged and "
12247 "should be merged manually if required before the "
12248 "merge operation is continued");
12249 } else {
12250 error = got_error_msg(GOT_ERR_CONFLICTS,
12251 "changes destined for some "
12252 "files were not yet merged and should be "
12253 "merged manually if required before the "
12254 "merge operation is continued");
12256 goto done;
12257 } else {
12258 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12259 fileindex, author, NULL, 1, branch_tip, branch_name,
12260 repo, continue_merge ? print_status : NULL, NULL);
12261 if (error)
12262 goto done;
12263 error = got_worktree_merge_complete(worktree, fileindex, repo);
12264 if (error)
12265 goto done;
12266 error = got_object_id_str(&id_str, merge_commit_id);
12267 if (error)
12268 goto done;
12269 printf("Merged %s into %s: %s\n", branch_name,
12270 got_worktree_get_head_ref_name(worktree),
12271 id_str);
12274 done:
12275 free(id_str);
12276 free(merge_commit_id);
12277 free(author);
12278 free(branch_tip);
12279 free(branch_name);
12280 free(yca_id);
12281 if (branch)
12282 got_ref_close(branch);
12283 if (wt_branch)
12284 got_ref_close(wt_branch);
12285 if (worktree)
12286 got_worktree_close(worktree);
12287 if (repo) {
12288 const struct got_error *close_err = got_repo_close(repo);
12289 if (error == NULL)
12290 error = close_err;
12292 if (pack_fds) {
12293 const struct got_error *pack_err =
12294 got_repo_pack_fds_close(pack_fds);
12295 if (error == NULL)
12296 error = pack_err;
12298 return error;
12301 __dead static void
12302 usage_stage(void)
12304 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12305 "[path ...]\n", getprogname());
12306 exit(1);
12309 static const struct got_error *
12310 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12311 const char *path, struct got_object_id *blob_id,
12312 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12313 int dirfd, const char *de_name)
12315 const struct got_error *err = NULL;
12316 char *id_str = NULL;
12318 if (staged_status != GOT_STATUS_ADD &&
12319 staged_status != GOT_STATUS_MODIFY &&
12320 staged_status != GOT_STATUS_DELETE)
12321 return NULL;
12323 if (staged_status == GOT_STATUS_ADD ||
12324 staged_status == GOT_STATUS_MODIFY)
12325 err = got_object_id_str(&id_str, staged_blob_id);
12326 else
12327 err = got_object_id_str(&id_str, blob_id);
12328 if (err)
12329 return err;
12331 printf("%s %c %s\n", id_str, staged_status, path);
12332 free(id_str);
12333 return NULL;
12336 static const struct got_error *
12337 cmd_stage(int argc, char *argv[])
12339 const struct got_error *error = NULL;
12340 struct got_repository *repo = NULL;
12341 struct got_worktree *worktree = NULL;
12342 char *cwd = NULL;
12343 struct got_pathlist_head paths;
12344 struct got_pathlist_entry *pe;
12345 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12346 FILE *patch_script_file = NULL;
12347 const char *patch_script_path = NULL;
12348 struct choose_patch_arg cpa;
12349 int *pack_fds = NULL;
12351 TAILQ_INIT(&paths);
12353 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12354 switch (ch) {
12355 case 'F':
12356 patch_script_path = optarg;
12357 break;
12358 case 'l':
12359 list_stage = 1;
12360 break;
12361 case 'p':
12362 pflag = 1;
12363 break;
12364 case 'S':
12365 allow_bad_symlinks = 1;
12366 break;
12367 default:
12368 usage_stage();
12369 /* NOTREACHED */
12373 argc -= optind;
12374 argv += optind;
12376 #ifndef PROFILE
12377 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12378 "unveil", NULL) == -1)
12379 err(1, "pledge");
12380 #endif
12381 if (list_stage && (pflag || patch_script_path))
12382 errx(1, "-l option cannot be used with other options");
12383 if (patch_script_path && !pflag)
12384 errx(1, "-F option can only be used together with -p option");
12386 cwd = getcwd(NULL, 0);
12387 if (cwd == NULL) {
12388 error = got_error_from_errno("getcwd");
12389 goto done;
12392 error = got_repo_pack_fds_open(&pack_fds);
12393 if (error != NULL)
12394 goto done;
12396 error = got_worktree_open(&worktree, cwd);
12397 if (error) {
12398 if (error->code == GOT_ERR_NOT_WORKTREE)
12399 error = wrap_not_worktree_error(error, "stage", cwd);
12400 goto done;
12403 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12404 NULL, pack_fds);
12405 if (error != NULL)
12406 goto done;
12408 if (patch_script_path) {
12409 patch_script_file = fopen(patch_script_path, "re");
12410 if (patch_script_file == NULL) {
12411 error = got_error_from_errno2("fopen",
12412 patch_script_path);
12413 goto done;
12416 error = apply_unveil(got_repo_get_path(repo), 0,
12417 got_worktree_get_root_path(worktree));
12418 if (error)
12419 goto done;
12421 error = check_merge_in_progress(worktree, repo);
12422 if (error)
12423 goto done;
12425 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12426 if (error)
12427 goto done;
12429 if (list_stage)
12430 error = got_worktree_status(worktree, &paths, repo, 0,
12431 print_stage, NULL, check_cancelled, NULL);
12432 else {
12433 cpa.patch_script_file = patch_script_file;
12434 cpa.action = "stage";
12435 error = got_worktree_stage(worktree, &paths,
12436 pflag ? NULL : print_status, NULL,
12437 pflag ? choose_patch : NULL, &cpa,
12438 allow_bad_symlinks, repo);
12440 done:
12441 if (patch_script_file && fclose(patch_script_file) == EOF &&
12442 error == NULL)
12443 error = got_error_from_errno2("fclose", patch_script_path);
12444 if (repo) {
12445 const struct got_error *close_err = got_repo_close(repo);
12446 if (error == NULL)
12447 error = close_err;
12449 if (worktree)
12450 got_worktree_close(worktree);
12451 if (pack_fds) {
12452 const struct got_error *pack_err =
12453 got_repo_pack_fds_close(pack_fds);
12454 if (error == NULL)
12455 error = pack_err;
12457 TAILQ_FOREACH(pe, &paths, entry)
12458 free((char *)pe->path);
12459 got_pathlist_free(&paths);
12460 free(cwd);
12461 return error;
12464 __dead static void
12465 usage_unstage(void)
12467 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12468 "[path ...]\n", getprogname());
12469 exit(1);
12473 static const struct got_error *
12474 cmd_unstage(int argc, char *argv[])
12476 const struct got_error *error = NULL;
12477 struct got_repository *repo = NULL;
12478 struct got_worktree *worktree = NULL;
12479 char *cwd = NULL;
12480 struct got_pathlist_head paths;
12481 struct got_pathlist_entry *pe;
12482 int ch, pflag = 0;
12483 struct got_update_progress_arg upa;
12484 FILE *patch_script_file = NULL;
12485 const char *patch_script_path = NULL;
12486 struct choose_patch_arg cpa;
12487 int *pack_fds = NULL;
12489 TAILQ_INIT(&paths);
12491 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12492 switch (ch) {
12493 case 'F':
12494 patch_script_path = optarg;
12495 break;
12496 case 'p':
12497 pflag = 1;
12498 break;
12499 default:
12500 usage_unstage();
12501 /* NOTREACHED */
12505 argc -= optind;
12506 argv += optind;
12508 #ifndef PROFILE
12509 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12510 "unveil", NULL) == -1)
12511 err(1, "pledge");
12512 #endif
12513 if (patch_script_path && !pflag)
12514 errx(1, "-F option can only be used together with -p option");
12516 cwd = getcwd(NULL, 0);
12517 if (cwd == NULL) {
12518 error = got_error_from_errno("getcwd");
12519 goto done;
12522 error = got_repo_pack_fds_open(&pack_fds);
12523 if (error != NULL)
12524 goto done;
12526 error = got_worktree_open(&worktree, cwd);
12527 if (error) {
12528 if (error->code == GOT_ERR_NOT_WORKTREE)
12529 error = wrap_not_worktree_error(error, "unstage", cwd);
12530 goto done;
12533 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12534 NULL, pack_fds);
12535 if (error != NULL)
12536 goto done;
12538 if (patch_script_path) {
12539 patch_script_file = fopen(patch_script_path, "re");
12540 if (patch_script_file == NULL) {
12541 error = got_error_from_errno2("fopen",
12542 patch_script_path);
12543 goto done;
12547 error = apply_unveil(got_repo_get_path(repo), 0,
12548 got_worktree_get_root_path(worktree));
12549 if (error)
12550 goto done;
12552 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12553 if (error)
12554 goto done;
12556 cpa.patch_script_file = patch_script_file;
12557 cpa.action = "unstage";
12558 memset(&upa, 0, sizeof(upa));
12559 error = got_worktree_unstage(worktree, &paths, update_progress,
12560 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12561 if (!error)
12562 print_merge_progress_stats(&upa);
12563 done:
12564 if (patch_script_file && fclose(patch_script_file) == EOF &&
12565 error == NULL)
12566 error = got_error_from_errno2("fclose", patch_script_path);
12567 if (repo) {
12568 const struct got_error *close_err = got_repo_close(repo);
12569 if (error == NULL)
12570 error = close_err;
12572 if (worktree)
12573 got_worktree_close(worktree);
12574 if (pack_fds) {
12575 const struct got_error *pack_err =
12576 got_repo_pack_fds_close(pack_fds);
12577 if (error == NULL)
12578 error = pack_err;
12580 TAILQ_FOREACH(pe, &paths, entry)
12581 free((char *)pe->path);
12582 got_pathlist_free(&paths);
12583 free(cwd);
12584 return error;
12587 __dead static void
12588 usage_cat(void)
12590 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12591 "arg ...\n", getprogname());
12592 exit(1);
12595 static const struct got_error *
12596 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12598 const struct got_error *err;
12599 struct got_blob_object *blob;
12600 int fd = -1;
12602 fd = got_opentempfd();
12603 if (fd == -1)
12604 return got_error_from_errno("got_opentempfd");
12606 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12607 if (err)
12608 goto done;
12610 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12611 done:
12612 if (fd != -1 && close(fd) == -1 && err == NULL)
12613 err = got_error_from_errno("close");
12614 if (blob)
12615 got_object_blob_close(blob);
12616 return err;
12619 static const struct got_error *
12620 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12622 const struct got_error *err;
12623 struct got_tree_object *tree;
12624 int nentries, i;
12626 err = got_object_open_as_tree(&tree, repo, id);
12627 if (err)
12628 return err;
12630 nentries = got_object_tree_get_nentries(tree);
12631 for (i = 0; i < nentries; i++) {
12632 struct got_tree_entry *te;
12633 char *id_str;
12634 if (sigint_received || sigpipe_received)
12635 break;
12636 te = got_object_tree_get_entry(tree, i);
12637 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12638 if (err)
12639 break;
12640 fprintf(outfile, "%s %.7o %s\n", id_str,
12641 got_tree_entry_get_mode(te),
12642 got_tree_entry_get_name(te));
12643 free(id_str);
12646 got_object_tree_close(tree);
12647 return err;
12650 static const struct got_error *
12651 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12653 const struct got_error *err;
12654 struct got_commit_object *commit;
12655 const struct got_object_id_queue *parent_ids;
12656 struct got_object_qid *pid;
12657 char *id_str = NULL;
12658 const char *logmsg = NULL;
12659 char gmtoff[6];
12661 err = got_object_open_as_commit(&commit, repo, id);
12662 if (err)
12663 return err;
12665 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12666 if (err)
12667 goto done;
12669 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12670 parent_ids = got_object_commit_get_parent_ids(commit);
12671 fprintf(outfile, "numparents %d\n",
12672 got_object_commit_get_nparents(commit));
12673 STAILQ_FOREACH(pid, parent_ids, entry) {
12674 char *pid_str;
12675 err = got_object_id_str(&pid_str, &pid->id);
12676 if (err)
12677 goto done;
12678 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12679 free(pid_str);
12681 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12682 got_object_commit_get_author_gmtoff(commit));
12683 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12684 got_object_commit_get_author(commit),
12685 (long long)got_object_commit_get_author_time(commit),
12686 gmtoff);
12688 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12689 got_object_commit_get_committer_gmtoff(commit));
12690 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12691 got_object_commit_get_committer(commit),
12692 (long long)got_object_commit_get_committer_time(commit),
12693 gmtoff);
12695 logmsg = got_object_commit_get_logmsg_raw(commit);
12696 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12697 fprintf(outfile, "%s", logmsg);
12698 done:
12699 free(id_str);
12700 got_object_commit_close(commit);
12701 return err;
12704 static const struct got_error *
12705 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12707 const struct got_error *err;
12708 struct got_tag_object *tag;
12709 char *id_str = NULL;
12710 const char *tagmsg = NULL;
12711 char gmtoff[6];
12713 err = got_object_open_as_tag(&tag, repo, id);
12714 if (err)
12715 return err;
12717 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12718 if (err)
12719 goto done;
12721 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12723 switch (got_object_tag_get_object_type(tag)) {
12724 case GOT_OBJ_TYPE_BLOB:
12725 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12726 GOT_OBJ_LABEL_BLOB);
12727 break;
12728 case GOT_OBJ_TYPE_TREE:
12729 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12730 GOT_OBJ_LABEL_TREE);
12731 break;
12732 case GOT_OBJ_TYPE_COMMIT:
12733 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12734 GOT_OBJ_LABEL_COMMIT);
12735 break;
12736 case GOT_OBJ_TYPE_TAG:
12737 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12738 GOT_OBJ_LABEL_TAG);
12739 break;
12740 default:
12741 break;
12744 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12745 got_object_tag_get_name(tag));
12747 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12748 got_object_tag_get_tagger_gmtoff(tag));
12749 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12750 got_object_tag_get_tagger(tag),
12751 (long long)got_object_tag_get_tagger_time(tag),
12752 gmtoff);
12754 tagmsg = got_object_tag_get_message(tag);
12755 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12756 fprintf(outfile, "%s", tagmsg);
12757 done:
12758 free(id_str);
12759 got_object_tag_close(tag);
12760 return err;
12763 static const struct got_error *
12764 cmd_cat(int argc, char *argv[])
12766 const struct got_error *error;
12767 struct got_repository *repo = NULL;
12768 struct got_worktree *worktree = NULL;
12769 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12770 const char *commit_id_str = NULL;
12771 struct got_object_id *id = NULL, *commit_id = NULL;
12772 struct got_commit_object *commit = NULL;
12773 int ch, obj_type, i, force_path = 0;
12774 struct got_reflist_head refs;
12775 int *pack_fds = NULL;
12777 TAILQ_INIT(&refs);
12779 #ifndef PROFILE
12780 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12781 NULL) == -1)
12782 err(1, "pledge");
12783 #endif
12785 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12786 switch (ch) {
12787 case 'c':
12788 commit_id_str = optarg;
12789 break;
12790 case 'P':
12791 force_path = 1;
12792 break;
12793 case 'r':
12794 repo_path = realpath(optarg, NULL);
12795 if (repo_path == NULL)
12796 return got_error_from_errno2("realpath",
12797 optarg);
12798 got_path_strip_trailing_slashes(repo_path);
12799 break;
12800 default:
12801 usage_cat();
12802 /* NOTREACHED */
12806 argc -= optind;
12807 argv += optind;
12809 cwd = getcwd(NULL, 0);
12810 if (cwd == NULL) {
12811 error = got_error_from_errno("getcwd");
12812 goto done;
12815 error = got_repo_pack_fds_open(&pack_fds);
12816 if (error != NULL)
12817 goto done;
12819 if (repo_path == NULL) {
12820 error = got_worktree_open(&worktree, cwd);
12821 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12822 goto done;
12823 if (worktree) {
12824 repo_path = strdup(
12825 got_worktree_get_repo_path(worktree));
12826 if (repo_path == NULL) {
12827 error = got_error_from_errno("strdup");
12828 goto done;
12831 /* Release work tree lock. */
12832 got_worktree_close(worktree);
12833 worktree = NULL;
12837 if (repo_path == NULL) {
12838 repo_path = strdup(cwd);
12839 if (repo_path == NULL)
12840 return got_error_from_errno("strdup");
12843 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12844 free(repo_path);
12845 if (error != NULL)
12846 goto done;
12848 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12849 if (error)
12850 goto done;
12852 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12853 if (error)
12854 goto done;
12856 if (commit_id_str == NULL)
12857 commit_id_str = GOT_REF_HEAD;
12858 error = got_repo_match_object_id(&commit_id, NULL,
12859 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12860 if (error)
12861 goto done;
12863 error = got_object_open_as_commit(&commit, repo, commit_id);
12864 if (error)
12865 goto done;
12867 for (i = 0; i < argc; i++) {
12868 if (force_path) {
12869 error = got_object_id_by_path(&id, repo, commit,
12870 argv[i]);
12871 if (error)
12872 break;
12873 } else {
12874 error = got_repo_match_object_id(&id, &label, argv[i],
12875 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12876 repo);
12877 if (error) {
12878 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12879 error->code != GOT_ERR_NOT_REF)
12880 break;
12881 error = got_object_id_by_path(&id, repo,
12882 commit, argv[i]);
12883 if (error)
12884 break;
12888 error = got_object_get_type(&obj_type, repo, id);
12889 if (error)
12890 break;
12892 switch (obj_type) {
12893 case GOT_OBJ_TYPE_BLOB:
12894 error = cat_blob(id, repo, stdout);
12895 break;
12896 case GOT_OBJ_TYPE_TREE:
12897 error = cat_tree(id, repo, stdout);
12898 break;
12899 case GOT_OBJ_TYPE_COMMIT:
12900 error = cat_commit(id, repo, stdout);
12901 break;
12902 case GOT_OBJ_TYPE_TAG:
12903 error = cat_tag(id, repo, stdout);
12904 break;
12905 default:
12906 error = got_error(GOT_ERR_OBJ_TYPE);
12907 break;
12909 if (error)
12910 break;
12911 free(label);
12912 label = NULL;
12913 free(id);
12914 id = NULL;
12916 done:
12917 free(label);
12918 free(id);
12919 free(commit_id);
12920 if (commit)
12921 got_object_commit_close(commit);
12922 if (worktree)
12923 got_worktree_close(worktree);
12924 if (repo) {
12925 const struct got_error *close_err = got_repo_close(repo);
12926 if (error == NULL)
12927 error = close_err;
12929 if (pack_fds) {
12930 const struct got_error *pack_err =
12931 got_repo_pack_fds_close(pack_fds);
12932 if (error == NULL)
12933 error = pack_err;
12936 got_ref_list_free(&refs);
12937 return error;
12940 __dead static void
12941 usage_info(void)
12943 fprintf(stderr, "usage: %s info [path ...]\n",
12944 getprogname());
12945 exit(1);
12948 static const struct got_error *
12949 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12950 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12951 struct got_object_id *commit_id)
12953 const struct got_error *err = NULL;
12954 char *id_str = NULL;
12955 char datebuf[128];
12956 struct tm mytm, *tm;
12957 struct got_pathlist_head *paths = arg;
12958 struct got_pathlist_entry *pe;
12961 * Clear error indication from any of the path arguments which
12962 * would cause this file index entry to be displayed.
12964 TAILQ_FOREACH(pe, paths, entry) {
12965 if (got_path_cmp(path, pe->path, strlen(path),
12966 pe->path_len) == 0 ||
12967 got_path_is_child(path, pe->path, pe->path_len))
12968 pe->data = NULL; /* no error */
12971 printf(GOT_COMMIT_SEP_STR);
12972 if (S_ISLNK(mode))
12973 printf("symlink: %s\n", path);
12974 else if (S_ISREG(mode)) {
12975 printf("file: %s\n", path);
12976 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12977 } else if (S_ISDIR(mode))
12978 printf("directory: %s\n", path);
12979 else
12980 printf("something: %s\n", path);
12982 tm = localtime_r(&mtime, &mytm);
12983 if (tm == NULL)
12984 return NULL;
12985 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12986 return got_error(GOT_ERR_NO_SPACE);
12987 printf("timestamp: %s\n", datebuf);
12989 if (blob_id) {
12990 err = got_object_id_str(&id_str, blob_id);
12991 if (err)
12992 return err;
12993 printf("based on blob: %s\n", id_str);
12994 free(id_str);
12997 if (staged_blob_id) {
12998 err = got_object_id_str(&id_str, staged_blob_id);
12999 if (err)
13000 return err;
13001 printf("based on staged blob: %s\n", id_str);
13002 free(id_str);
13005 if (commit_id) {
13006 err = got_object_id_str(&id_str, commit_id);
13007 if (err)
13008 return err;
13009 printf("based on commit: %s\n", id_str);
13010 free(id_str);
13013 return NULL;
13016 static const struct got_error *
13017 cmd_info(int argc, char *argv[])
13019 const struct got_error *error = NULL;
13020 struct got_worktree *worktree = NULL;
13021 char *cwd = NULL, *id_str = NULL;
13022 struct got_pathlist_head paths;
13023 struct got_pathlist_entry *pe;
13024 char *uuidstr = NULL;
13025 int ch, show_files = 0;
13027 TAILQ_INIT(&paths);
13029 while ((ch = getopt(argc, argv, "")) != -1) {
13030 switch (ch) {
13031 default:
13032 usage_info();
13033 /* NOTREACHED */
13037 argc -= optind;
13038 argv += optind;
13040 #ifndef PROFILE
13041 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13042 NULL) == -1)
13043 err(1, "pledge");
13044 #endif
13045 cwd = getcwd(NULL, 0);
13046 if (cwd == NULL) {
13047 error = got_error_from_errno("getcwd");
13048 goto done;
13051 error = got_worktree_open(&worktree, cwd);
13052 if (error) {
13053 if (error->code == GOT_ERR_NOT_WORKTREE)
13054 error = wrap_not_worktree_error(error, "info", cwd);
13055 goto done;
13058 #ifndef PROFILE
13059 /* Remove "wpath cpath proc exec sendfd" promises. */
13060 if (pledge("stdio rpath flock unveil", NULL) == -1)
13061 err(1, "pledge");
13062 #endif
13063 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13064 if (error)
13065 goto done;
13067 if (argc >= 1) {
13068 error = get_worktree_paths_from_argv(&paths, argc, argv,
13069 worktree);
13070 if (error)
13071 goto done;
13072 show_files = 1;
13075 error = got_object_id_str(&id_str,
13076 got_worktree_get_base_commit_id(worktree));
13077 if (error)
13078 goto done;
13080 error = got_worktree_get_uuid(&uuidstr, worktree);
13081 if (error)
13082 goto done;
13084 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13085 printf("work tree base commit: %s\n", id_str);
13086 printf("work tree path prefix: %s\n",
13087 got_worktree_get_path_prefix(worktree));
13088 printf("work tree branch reference: %s\n",
13089 got_worktree_get_head_ref_name(worktree));
13090 printf("work tree UUID: %s\n", uuidstr);
13091 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13093 if (show_files) {
13094 struct got_pathlist_entry *pe;
13095 TAILQ_FOREACH(pe, &paths, entry) {
13096 if (pe->path_len == 0)
13097 continue;
13099 * Assume this path will fail. This will be corrected
13100 * in print_path_info() in case the path does suceeed.
13102 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13104 error = got_worktree_path_info(worktree, &paths,
13105 print_path_info, &paths, check_cancelled, NULL);
13106 if (error)
13107 goto done;
13108 TAILQ_FOREACH(pe, &paths, entry) {
13109 if (pe->data != NULL) {
13110 const struct got_error *perr;
13112 perr = pe->data;
13113 error = got_error_fmt(perr->code, "%s",
13114 pe->path);
13115 break;
13119 done:
13120 if (worktree)
13121 got_worktree_close(worktree);
13122 TAILQ_FOREACH(pe, &paths, entry)
13123 free((char *)pe->path);
13124 got_pathlist_free(&paths);
13125 free(cwd);
13126 free(id_str);
13127 free(uuidstr);
13128 return error;