Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (*author++ != '<')
566 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
567 while (*author && *author != '\n' && *author != '<' && *author != '>')
568 author++;
569 if (strcmp(author, ">") != 0)
570 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
571 return NULL;
574 static const struct got_error *
575 get_author(char **author, struct got_repository *repo,
576 struct got_worktree *worktree)
578 const struct got_error *err = NULL;
579 const char *got_author = NULL, *name, *email;
580 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
582 *author = NULL;
584 if (worktree)
585 worktree_conf = got_worktree_get_gotconfig(worktree);
586 repo_conf = got_repo_get_gotconfig(repo);
588 /*
589 * Priority of potential author information sources, from most
590 * significant to least significant:
591 * 1) work tree's .got/got.conf file
592 * 2) repository's got.conf file
593 * 3) repository's git config file
594 * 4) environment variables
595 * 5) global git config files (in user's home directory or /etc)
596 */
598 if (worktree_conf)
599 got_author = got_gotconfig_get_author(worktree_conf);
600 if (got_author == NULL)
601 got_author = got_gotconfig_get_author(repo_conf);
602 if (got_author == NULL) {
603 name = got_repo_get_gitconfig_author_name(repo);
604 email = got_repo_get_gitconfig_author_email(repo);
605 if (name && email) {
606 if (asprintf(author, "%s <%s>", name, email) == -1)
607 return got_error_from_errno("asprintf");
608 return NULL;
611 got_author = getenv("GOT_AUTHOR");
612 if (got_author == NULL) {
613 name = got_repo_get_global_gitconfig_author_name(repo);
614 email = got_repo_get_global_gitconfig_author_email(
615 repo);
616 if (name && email) {
617 if (asprintf(author, "%s <%s>", name, email)
618 == -1)
619 return got_error_from_errno("asprintf");
620 return NULL;
622 /* TODO: Look up user in password database? */
623 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
627 *author = strdup(got_author);
628 if (*author == NULL)
629 return got_error_from_errno("strdup");
631 err = valid_author(*author);
632 if (err) {
633 free(*author);
634 *author = NULL;
636 return err;
639 static const struct got_error *
640 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
641 struct got_worktree *worktree)
643 const char *got_allowed_signers = NULL;
644 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
646 *allowed_signers = NULL;
648 if (worktree)
649 worktree_conf = got_worktree_get_gotconfig(worktree);
650 repo_conf = got_repo_get_gotconfig(repo);
652 /*
653 * Priority of potential author information sources, from most
654 * significant to least significant:
655 * 1) work tree's .got/got.conf file
656 * 2) repository's got.conf file
657 */
659 if (worktree_conf)
660 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
661 worktree_conf);
662 if (got_allowed_signers == NULL)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 repo_conf);
666 if (got_allowed_signers) {
667 *allowed_signers = strdup(got_allowed_signers);
668 if (*allowed_signers == NULL)
669 return got_error_from_errno("strdup");
671 return NULL;
674 static const struct got_error *
675 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
676 struct got_worktree *worktree)
678 const char *got_revoked_signers = NULL;
679 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
681 *revoked_signers = NULL;
683 if (worktree)
684 worktree_conf = got_worktree_get_gotconfig(worktree);
685 repo_conf = got_repo_get_gotconfig(repo);
687 /*
688 * Priority of potential author information sources, from most
689 * significant to least significant:
690 * 1) work tree's .got/got.conf file
691 * 2) repository's got.conf file
692 */
694 if (worktree_conf)
695 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
696 worktree_conf);
697 if (got_revoked_signers == NULL)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 repo_conf);
701 if (got_revoked_signers) {
702 *revoked_signers = strdup(got_revoked_signers);
703 if (*revoked_signers == NULL)
704 return got_error_from_errno("strdup");
706 return NULL;
709 static const struct got_error *
710 get_signer_id(char **signer_id, struct got_repository *repo,
711 struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 *signer_id = NULL;
718 if (worktree)
719 worktree_conf = got_worktree_get_gotconfig(worktree);
720 repo_conf = got_repo_get_gotconfig(repo);
722 /*
723 * Priority of potential author information sources, from most
724 * significant to least significant:
725 * 1) work tree's .got/got.conf file
726 * 2) repository's got.conf file
727 */
729 if (worktree_conf)
730 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
731 if (got_signer_id == NULL)
732 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
734 if (got_signer_id) {
735 *signer_id = strdup(got_signer_id);
736 if (*signer_id == NULL)
737 return got_error_from_errno("strdup");
739 return NULL;
742 static const struct got_error *
743 get_gitconfig_path(char **gitconfig_path)
745 const char *homedir = getenv("HOME");
747 *gitconfig_path = NULL;
748 if (homedir) {
749 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
750 return got_error_from_errno("asprintf");
753 return NULL;
756 static const struct got_error *
757 cmd_import(int argc, char *argv[])
759 const struct got_error *error = NULL;
760 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
761 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
762 const char *branch_name = "main";
763 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
764 struct got_repository *repo = NULL;
765 struct got_reference *branch_ref = NULL, *head_ref = NULL;
766 struct got_object_id *new_commit_id = NULL;
767 int ch;
768 struct got_pathlist_head ignores;
769 struct got_pathlist_entry *pe;
770 int preserve_logmsg = 0;
771 int *pack_fds = NULL;
773 TAILQ_INIT(&ignores);
775 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
776 switch (ch) {
777 case 'b':
778 branch_name = optarg;
779 break;
780 case 'm':
781 logmsg = strdup(optarg);
782 if (logmsg == NULL) {
783 error = got_error_from_errno("strdup");
784 goto done;
786 break;
787 case 'r':
788 repo_path = realpath(optarg, NULL);
789 if (repo_path == NULL) {
790 error = got_error_from_errno2("realpath",
791 optarg);
792 goto done;
794 break;
795 case 'I':
796 if (optarg[0] == '\0')
797 break;
798 error = got_pathlist_insert(&pe, &ignores, optarg,
799 NULL);
800 if (error)
801 goto done;
802 break;
803 default:
804 usage_import();
805 /* NOTREACHED */
809 argc -= optind;
810 argv += optind;
812 #ifndef PROFILE
813 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
814 "unveil",
815 NULL) == -1)
816 err(1, "pledge");
817 #endif
818 if (argc != 1)
819 usage_import();
821 if (repo_path == NULL) {
822 repo_path = getcwd(NULL, 0);
823 if (repo_path == NULL)
824 return got_error_from_errno("getcwd");
826 got_path_strip_trailing_slashes(repo_path);
827 error = get_gitconfig_path(&gitconfig_path);
828 if (error)
829 goto done;
830 error = got_repo_pack_fds_open(&pack_fds);
831 if (error != NULL)
832 goto done;
833 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
834 if (error)
835 goto done;
837 error = get_author(&author, repo, NULL);
838 if (error)
839 return error;
841 /*
842 * Don't let the user create a branch name with a leading '-'.
843 * While technically a valid reference name, this case is usually
844 * an unintended typo.
845 */
846 if (branch_name[0] == '-')
847 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
849 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
850 error = got_error_from_errno("asprintf");
851 goto done;
854 error = got_ref_open(&branch_ref, repo, refname, 0);
855 if (error) {
856 if (error->code != GOT_ERR_NOT_REF)
857 goto done;
858 } else {
859 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
860 "import target branch already exists");
861 goto done;
864 path_dir = realpath(argv[0], NULL);
865 if (path_dir == NULL) {
866 error = got_error_from_errno2("realpath", argv[0]);
867 goto done;
869 got_path_strip_trailing_slashes(path_dir);
871 /*
872 * unveil(2) traverses exec(2); if an editor is used we have
873 * to apply unveil after the log message has been written.
874 */
875 if (logmsg == NULL || strlen(logmsg) == 0) {
876 error = get_editor(&editor);
877 if (error)
878 goto done;
879 free(logmsg);
880 error = collect_import_msg(&logmsg, &logmsg_path, editor,
881 path_dir, refname);
882 if (error) {
883 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
884 logmsg_path != NULL)
885 preserve_logmsg = 1;
886 goto done;
890 if (unveil(path_dir, "r") != 0) {
891 error = got_error_from_errno2("unveil", path_dir);
892 if (logmsg_path)
893 preserve_logmsg = 1;
894 goto done;
897 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
898 if (error) {
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = got_repo_import(&new_commit_id, path_dir, logmsg,
905 author, &ignores, repo, import_progress, NULL);
906 if (error) {
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_write(branch_ref, repo);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_object_id_str(&id_str, new_commit_id);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
934 if (error) {
935 if (error->code != GOT_ERR_NOT_REF) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
942 branch_ref);
943 if (error) {
944 if (logmsg_path)
945 preserve_logmsg = 1;
946 goto done;
949 error = got_ref_write(head_ref, repo);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
957 printf("Created branch %s with commit %s\n",
958 got_ref_get_name(branch_ref), id_str);
959 done:
960 if (pack_fds) {
961 const struct got_error *pack_err =
962 got_repo_pack_fds_close(pack_fds);
963 if (error == NULL)
964 error = pack_err;
966 if (preserve_logmsg) {
967 fprintf(stderr, "%s: log message preserved in %s\n",
968 getprogname(), logmsg_path);
969 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
970 error = got_error_from_errno2("unlink", logmsg_path);
971 free(logmsg);
972 free(logmsg_path);
973 free(repo_path);
974 free(editor);
975 free(refname);
976 free(new_commit_id);
977 free(id_str);
978 free(author);
979 free(gitconfig_path);
980 if (branch_ref)
981 got_ref_close(branch_ref);
982 if (head_ref)
983 got_ref_close(head_ref);
984 return error;
987 __dead static void
988 usage_clone(void)
990 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
991 "repository-URL [directory]\n", getprogname());
992 exit(1);
995 struct got_fetch_progress_arg {
996 char last_scaled_size[FMT_SCALED_STRSIZE];
997 int last_p_indexed;
998 int last_p_resolved;
999 int verbosity;
1001 struct got_repository *repo;
1003 int create_configs;
1004 int configs_created;
1005 struct {
1006 struct got_pathlist_head *symrefs;
1007 struct got_pathlist_head *wanted_branches;
1008 struct got_pathlist_head *wanted_refs;
1009 const char *proto;
1010 const char *host;
1011 const char *port;
1012 const char *remote_repo_path;
1013 const char *git_url;
1014 int fetch_all_branches;
1015 int mirror_references;
1016 } config_info;
1019 /* XXX forward declaration */
1020 static const struct got_error *
1021 create_config_files(const char *proto, const char *host, const char *port,
1022 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1023 int mirror_references, struct got_pathlist_head *symrefs,
1024 struct got_pathlist_head *wanted_branches,
1025 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1027 static const struct got_error *
1028 fetch_progress(void *arg, const char *message, off_t packfile_size,
1029 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1031 const struct got_error *err = NULL;
1032 struct got_fetch_progress_arg *a = arg;
1033 char scaled_size[FMT_SCALED_STRSIZE];
1034 int p_indexed, p_resolved;
1035 int print_size = 0, print_indexed = 0, print_resolved = 0;
1038 * In order to allow a failed clone to be resumed with 'got fetch'
1039 * we try to create configuration files as soon as possible.
1040 * Once the server has sent information about its default branch
1041 * we have all required information.
1043 if (a->create_configs && !a->configs_created &&
1044 !TAILQ_EMPTY(a->config_info.symrefs)) {
1045 err = create_config_files(a->config_info.proto,
1046 a->config_info.host, a->config_info.port,
1047 a->config_info.remote_repo_path,
1048 a->config_info.git_url,
1049 a->config_info.fetch_all_branches,
1050 a->config_info.mirror_references,
1051 a->config_info.symrefs,
1052 a->config_info.wanted_branches,
1053 a->config_info.wanted_refs, a->repo);
1054 if (err)
1055 return err;
1056 a->configs_created = 1;
1059 if (a->verbosity < 0)
1060 return NULL;
1062 if (message && message[0] != '\0') {
1063 printf("\rserver: %s", message);
1064 fflush(stdout);
1065 return NULL;
1068 if (packfile_size > 0 || nobj_indexed > 0) {
1069 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1070 (a->last_scaled_size[0] == '\0' ||
1071 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1072 print_size = 1;
1073 if (strlcpy(a->last_scaled_size, scaled_size,
1074 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1075 return got_error(GOT_ERR_NO_SPACE);
1077 if (nobj_indexed > 0) {
1078 p_indexed = (nobj_indexed * 100) / nobj_total;
1079 if (p_indexed != a->last_p_indexed) {
1080 a->last_p_indexed = p_indexed;
1081 print_indexed = 1;
1082 print_size = 1;
1085 if (nobj_resolved > 0) {
1086 p_resolved = (nobj_resolved * 100) /
1087 (nobj_total - nobj_loose);
1088 if (p_resolved != a->last_p_resolved) {
1089 a->last_p_resolved = p_resolved;
1090 print_resolved = 1;
1091 print_indexed = 1;
1092 print_size = 1;
1097 if (print_size || print_indexed || print_resolved)
1098 printf("\r");
1099 if (print_size)
1100 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1101 if (print_indexed)
1102 printf("; indexing %d%%", p_indexed);
1103 if (print_resolved)
1104 printf("; resolving deltas %d%%", p_resolved);
1105 if (print_size || print_indexed || print_resolved)
1106 fflush(stdout);
1108 return NULL;
1111 static const struct got_error *
1112 create_symref(const char *refname, struct got_reference *target_ref,
1113 int verbosity, struct got_repository *repo)
1115 const struct got_error *err;
1116 struct got_reference *head_symref;
1118 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1119 if (err)
1120 return err;
1122 err = got_ref_write(head_symref, repo);
1123 if (err == NULL && verbosity > 0) {
1124 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1125 got_ref_get_name(target_ref));
1127 got_ref_close(head_symref);
1128 return err;
1131 static const struct got_error *
1132 list_remote_refs(struct got_pathlist_head *symrefs,
1133 struct got_pathlist_head *refs)
1135 const struct got_error *err;
1136 struct got_pathlist_entry *pe;
1138 TAILQ_FOREACH(pe, symrefs, entry) {
1139 const char *refname = pe->path;
1140 const char *targetref = pe->data;
1142 printf("%s: %s\n", refname, targetref);
1145 TAILQ_FOREACH(pe, refs, entry) {
1146 const char *refname = pe->path;
1147 struct got_object_id *id = pe->data;
1148 char *id_str;
1150 err = got_object_id_str(&id_str, id);
1151 if (err)
1152 return err;
1153 printf("%s: %s\n", refname, id_str);
1154 free(id_str);
1157 return NULL;
1160 static const struct got_error *
1161 create_ref(const char *refname, struct got_object_id *id,
1162 int verbosity, struct got_repository *repo)
1164 const struct got_error *err = NULL;
1165 struct got_reference *ref;
1166 char *id_str;
1168 err = got_object_id_str(&id_str, id);
1169 if (err)
1170 return err;
1172 err = got_ref_alloc(&ref, refname, id);
1173 if (err)
1174 goto done;
1176 err = got_ref_write(ref, repo);
1177 got_ref_close(ref);
1179 if (err == NULL && verbosity >= 0)
1180 printf("Created reference %s: %s\n", refname, id_str);
1181 done:
1182 free(id_str);
1183 return err;
1186 static int
1187 match_wanted_ref(const char *refname, const char *wanted_ref)
1189 if (strncmp(refname, "refs/", 5) != 0)
1190 return 0;
1191 refname += 5;
1194 * Prevent fetching of references that won't make any
1195 * sense outside of the remote repository's context.
1197 if (strncmp(refname, "got/", 4) == 0)
1198 return 0;
1199 if (strncmp(refname, "remotes/", 8) == 0)
1200 return 0;
1202 if (strncmp(wanted_ref, "refs/", 5) == 0)
1203 wanted_ref += 5;
1205 /* Allow prefix match. */
1206 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1207 return 1;
1209 /* Allow exact match. */
1210 return (strcmp(refname, wanted_ref) == 0);
1213 static int
1214 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1216 struct got_pathlist_entry *pe;
1218 TAILQ_FOREACH(pe, wanted_refs, entry) {
1219 if (match_wanted_ref(refname, pe->path))
1220 return 1;
1223 return 0;
1226 static const struct got_error *
1227 create_wanted_ref(const char *refname, struct got_object_id *id,
1228 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1230 const struct got_error *err;
1231 char *remote_refname;
1233 if (strncmp("refs/", refname, 5) == 0)
1234 refname += 5;
1236 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1237 remote_repo_name, refname) == -1)
1238 return got_error_from_errno("asprintf");
1240 err = create_ref(remote_refname, id, verbosity, repo);
1241 free(remote_refname);
1242 return err;
1245 static const struct got_error *
1246 create_gotconfig(const char *proto, const char *host, const char *port,
1247 const char *remote_repo_path, const char *default_branch,
1248 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1249 struct got_pathlist_head *wanted_refs, int mirror_references,
1250 struct got_repository *repo)
1252 const struct got_error *err = NULL;
1253 char *gotconfig_path = NULL;
1254 char *gotconfig = NULL;
1255 FILE *gotconfig_file = NULL;
1256 const char *branchname = NULL;
1257 char *branches = NULL, *refs = NULL;
1258 ssize_t n;
1260 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1261 struct got_pathlist_entry *pe;
1262 TAILQ_FOREACH(pe, wanted_branches, entry) {
1263 char *s;
1264 branchname = pe->path;
1265 if (strncmp(branchname, "refs/heads/", 11) == 0)
1266 branchname += 11;
1267 if (asprintf(&s, "%s\"%s\" ",
1268 branches ? branches : "", branchname) == -1) {
1269 err = got_error_from_errno("asprintf");
1270 goto done;
1272 free(branches);
1273 branches = s;
1275 } else if (!fetch_all_branches && default_branch) {
1276 branchname = default_branch;
1277 if (strncmp(branchname, "refs/heads/", 11) == 0)
1278 branchname += 11;
1279 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1280 err = got_error_from_errno("asprintf");
1281 goto done;
1284 if (!TAILQ_EMPTY(wanted_refs)) {
1285 struct got_pathlist_entry *pe;
1286 TAILQ_FOREACH(pe, wanted_refs, entry) {
1287 char *s;
1288 const char *refname = pe->path;
1289 if (strncmp(refname, "refs/", 5) == 0)
1290 branchname += 5;
1291 if (asprintf(&s, "%s\"%s\" ",
1292 refs ? refs : "", refname) == -1) {
1293 err = got_error_from_errno("asprintf");
1294 goto done;
1296 free(refs);
1297 refs = s;
1301 /* Create got.conf(5). */
1302 gotconfig_path = got_repo_get_path_gotconfig(repo);
1303 if (gotconfig_path == NULL) {
1304 err = got_error_from_errno("got_repo_get_path_gotconfig");
1305 goto done;
1307 gotconfig_file = fopen(gotconfig_path, "ae");
1308 if (gotconfig_file == NULL) {
1309 err = got_error_from_errno2("fopen", gotconfig_path);
1310 goto done;
1312 if (asprintf(&gotconfig,
1313 "remote \"%s\" {\n"
1314 "\tserver %s\n"
1315 "\tprotocol %s\n"
1316 "%s%s%s"
1317 "\trepository \"%s\"\n"
1318 "%s%s%s"
1319 "%s%s%s"
1320 "%s"
1321 "%s"
1322 "}\n",
1323 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1324 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1325 remote_repo_path, branches ? "\tbranch { " : "",
1326 branches ? branches : "", branches ? "}\n" : "",
1327 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1328 mirror_references ? "\tmirror_references yes\n" : "",
1329 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1330 err = got_error_from_errno("asprintf");
1331 goto done;
1333 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1334 if (n != strlen(gotconfig)) {
1335 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1336 goto done;
1339 done:
1340 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1341 err = got_error_from_errno2("fclose", gotconfig_path);
1342 free(gotconfig_path);
1343 free(branches);
1344 return err;
1347 static const struct got_error *
1348 create_gitconfig(const char *git_url, const char *default_branch,
1349 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1350 struct got_pathlist_head *wanted_refs, int mirror_references,
1351 struct got_repository *repo)
1353 const struct got_error *err = NULL;
1354 char *gitconfig_path = NULL;
1355 char *gitconfig = NULL;
1356 FILE *gitconfig_file = NULL;
1357 char *branches = NULL, *refs = NULL;
1358 const char *branchname;
1359 ssize_t n;
1361 /* Create a config file Git can understand. */
1362 gitconfig_path = got_repo_get_path_gitconfig(repo);
1363 if (gitconfig_path == NULL) {
1364 err = got_error_from_errno("got_repo_get_path_gitconfig");
1365 goto done;
1367 gitconfig_file = fopen(gitconfig_path, "ae");
1368 if (gitconfig_file == NULL) {
1369 err = got_error_from_errno2("fopen", gitconfig_path);
1370 goto done;
1372 if (fetch_all_branches) {
1373 if (mirror_references) {
1374 if (asprintf(&branches,
1375 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1376 err = got_error_from_errno("asprintf");
1377 goto done;
1379 } else if (asprintf(&branches,
1380 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1381 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1382 err = got_error_from_errno("asprintf");
1383 goto done;
1385 } else if (!TAILQ_EMPTY(wanted_branches)) {
1386 struct got_pathlist_entry *pe;
1387 TAILQ_FOREACH(pe, wanted_branches, entry) {
1388 char *s;
1389 branchname = pe->path;
1390 if (strncmp(branchname, "refs/heads/", 11) == 0)
1391 branchname += 11;
1392 if (mirror_references) {
1393 if (asprintf(&s,
1394 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1395 branches ? branches : "",
1396 branchname, branchname) == -1) {
1397 err = got_error_from_errno("asprintf");
1398 goto done;
1400 } else if (asprintf(&s,
1401 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1402 branches ? branches : "",
1403 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1404 branchname) == -1) {
1405 err = got_error_from_errno("asprintf");
1406 goto done;
1408 free(branches);
1409 branches = s;
1411 } else {
1413 * If the server specified a default branch, use just that one.
1414 * Otherwise fall back to fetching all branches on next fetch.
1416 if (default_branch) {
1417 branchname = default_branch;
1418 if (strncmp(branchname, "refs/heads/", 11) == 0)
1419 branchname += 11;
1420 } else
1421 branchname = "*"; /* fall back to all branches */
1422 if (mirror_references) {
1423 if (asprintf(&branches,
1424 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1425 branchname, branchname) == -1) {
1426 err = got_error_from_errno("asprintf");
1427 goto done;
1429 } else if (asprintf(&branches,
1430 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1431 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1432 branchname) == -1) {
1433 err = got_error_from_errno("asprintf");
1434 goto done;
1437 if (!TAILQ_EMPTY(wanted_refs)) {
1438 struct got_pathlist_entry *pe;
1439 TAILQ_FOREACH(pe, wanted_refs, entry) {
1440 char *s;
1441 const char *refname = pe->path;
1442 if (strncmp(refname, "refs/", 5) == 0)
1443 refname += 5;
1444 if (mirror_references) {
1445 if (asprintf(&s,
1446 "%s\tfetch = refs/%s:refs/%s\n",
1447 refs ? refs : "", refname, refname) == -1) {
1448 err = got_error_from_errno("asprintf");
1449 goto done;
1451 } else if (asprintf(&s,
1452 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1453 refs ? refs : "",
1454 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1455 refname) == -1) {
1456 err = got_error_from_errno("asprintf");
1457 goto done;
1459 free(refs);
1460 refs = s;
1464 if (asprintf(&gitconfig,
1465 "[remote \"%s\"]\n"
1466 "\turl = %s\n"
1467 "%s"
1468 "%s"
1469 "\tfetch = refs/tags/*:refs/tags/*\n",
1470 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1471 refs ? refs : "") == -1) {
1472 err = got_error_from_errno("asprintf");
1473 goto done;
1475 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1476 if (n != strlen(gitconfig)) {
1477 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1478 goto done;
1480 done:
1481 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1482 err = got_error_from_errno2("fclose", gitconfig_path);
1483 free(gitconfig_path);
1484 free(branches);
1485 return err;
1488 static const struct got_error *
1489 create_config_files(const char *proto, const char *host, const char *port,
1490 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1491 int mirror_references, struct got_pathlist_head *symrefs,
1492 struct got_pathlist_head *wanted_branches,
1493 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1495 const struct got_error *err = NULL;
1496 const char *default_branch = NULL;
1497 struct got_pathlist_entry *pe;
1500 * If we asked for a set of wanted branches then use the first
1501 * one of those.
1503 if (!TAILQ_EMPTY(wanted_branches)) {
1504 pe = TAILQ_FIRST(wanted_branches);
1505 default_branch = pe->path;
1506 } else {
1507 /* First HEAD ref listed by server is the default branch. */
1508 TAILQ_FOREACH(pe, symrefs, entry) {
1509 const char *refname = pe->path;
1510 const char *target = pe->data;
1512 if (strcmp(refname, GOT_REF_HEAD) != 0)
1513 continue;
1515 default_branch = target;
1516 break;
1520 /* Create got.conf(5). */
1521 err = create_gotconfig(proto, host, port, remote_repo_path,
1522 default_branch, fetch_all_branches, wanted_branches,
1523 wanted_refs, mirror_references, repo);
1524 if (err)
1525 return err;
1527 /* Create a config file Git can understand. */
1528 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1529 wanted_branches, wanted_refs, mirror_references, repo);
1532 static const struct got_error *
1533 cmd_clone(int argc, char *argv[])
1535 const struct got_error *error = NULL;
1536 const char *uri, *dirname;
1537 char *proto, *host, *port, *repo_name, *server_path;
1538 char *default_destdir = NULL, *id_str = NULL;
1539 const char *repo_path;
1540 struct got_repository *repo = NULL;
1541 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1542 struct got_pathlist_entry *pe;
1543 struct got_object_id *pack_hash = NULL;
1544 int ch, fetchfd = -1, fetchstatus;
1545 pid_t fetchpid = -1;
1546 struct got_fetch_progress_arg fpa;
1547 char *git_url = NULL;
1548 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1549 int list_refs_only = 0;
1550 int *pack_fds = NULL;
1552 TAILQ_INIT(&refs);
1553 TAILQ_INIT(&symrefs);
1554 TAILQ_INIT(&wanted_branches);
1555 TAILQ_INIT(&wanted_refs);
1557 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1558 switch (ch) {
1559 case 'a':
1560 fetch_all_branches = 1;
1561 break;
1562 case 'b':
1563 error = got_pathlist_append(&wanted_branches,
1564 optarg, NULL);
1565 if (error)
1566 return error;
1567 break;
1568 case 'l':
1569 list_refs_only = 1;
1570 break;
1571 case 'm':
1572 mirror_references = 1;
1573 break;
1574 case 'v':
1575 if (verbosity < 0)
1576 verbosity = 0;
1577 else if (verbosity < 3)
1578 verbosity++;
1579 break;
1580 case 'q':
1581 verbosity = -1;
1582 break;
1583 case 'R':
1584 error = got_pathlist_append(&wanted_refs,
1585 optarg, NULL);
1586 if (error)
1587 return error;
1588 break;
1589 default:
1590 usage_clone();
1591 break;
1594 argc -= optind;
1595 argv += optind;
1597 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1598 option_conflict('a', 'b');
1599 if (list_refs_only) {
1600 if (!TAILQ_EMPTY(&wanted_branches))
1601 option_conflict('l', 'b');
1602 if (fetch_all_branches)
1603 option_conflict('l', 'a');
1604 if (mirror_references)
1605 option_conflict('l', 'm');
1606 if (!TAILQ_EMPTY(&wanted_refs))
1607 option_conflict('l', 'R');
1610 uri = argv[0];
1612 if (argc == 1)
1613 dirname = NULL;
1614 else if (argc == 2)
1615 dirname = argv[1];
1616 else
1617 usage_clone();
1619 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1620 &repo_name, uri);
1621 if (error)
1622 goto done;
1624 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1625 host, port ? ":" : "", port ? port : "",
1626 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1627 error = got_error_from_errno("asprintf");
1628 goto done;
1631 if (strcmp(proto, "git") == 0) {
1632 #ifndef PROFILE
1633 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1634 "sendfd dns inet unveil", NULL) == -1)
1635 err(1, "pledge");
1636 #endif
1637 } else if (strcmp(proto, "git+ssh") == 0 ||
1638 strcmp(proto, "ssh") == 0) {
1639 #ifndef PROFILE
1640 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1641 "sendfd unveil", NULL) == -1)
1642 err(1, "pledge");
1643 #endif
1644 } else if (strcmp(proto, "http") == 0 ||
1645 strcmp(proto, "git+http") == 0) {
1646 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1647 goto done;
1648 } else {
1649 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1650 goto done;
1652 if (dirname == NULL) {
1653 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1654 error = got_error_from_errno("asprintf");
1655 goto done;
1657 repo_path = default_destdir;
1658 } else
1659 repo_path = dirname;
1661 if (!list_refs_only) {
1662 error = got_path_mkdir(repo_path);
1663 if (error &&
1664 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1665 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1666 goto done;
1667 if (!got_path_dir_is_empty(repo_path)) {
1668 error = got_error_path(repo_path,
1669 GOT_ERR_DIR_NOT_EMPTY);
1670 goto done;
1674 error = got_dial_apply_unveil(proto);
1675 if (error)
1676 goto done;
1678 error = apply_unveil(repo_path, 0, NULL);
1679 if (error)
1680 goto done;
1682 if (verbosity >= 0)
1683 printf("Connecting to %s%s%s\n", host,
1684 port ? ":" : "", port ? port : "");
1686 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1687 server_path, verbosity);
1688 if (error)
1689 goto done;
1691 if (!list_refs_only) {
1692 error = got_repo_init(repo_path);
1693 if (error)
1694 goto done;
1695 error = got_repo_pack_fds_open(&pack_fds);
1696 if (error != NULL)
1697 goto done;
1698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1699 if (error)
1700 goto done;
1703 fpa.last_scaled_size[0] = '\0';
1704 fpa.last_p_indexed = -1;
1705 fpa.last_p_resolved = -1;
1706 fpa.verbosity = verbosity;
1707 fpa.create_configs = 1;
1708 fpa.configs_created = 0;
1709 fpa.repo = repo;
1710 fpa.config_info.symrefs = &symrefs;
1711 fpa.config_info.wanted_branches = &wanted_branches;
1712 fpa.config_info.wanted_refs = &wanted_refs;
1713 fpa.config_info.proto = proto;
1714 fpa.config_info.host = host;
1715 fpa.config_info.port = port;
1716 fpa.config_info.remote_repo_path = server_path;
1717 fpa.config_info.git_url = git_url;
1718 fpa.config_info.fetch_all_branches = fetch_all_branches;
1719 fpa.config_info.mirror_references = mirror_references;
1720 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1721 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1722 fetch_all_branches, &wanted_branches, &wanted_refs,
1723 list_refs_only, verbosity, fetchfd, repo,
1724 fetch_progress, &fpa);
1725 if (error)
1726 goto done;
1728 if (list_refs_only) {
1729 error = list_remote_refs(&symrefs, &refs);
1730 goto done;
1733 if (pack_hash == NULL) {
1734 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1735 "server sent an empty pack file");
1736 goto done;
1738 error = got_object_id_str(&id_str, pack_hash);
1739 if (error)
1740 goto done;
1741 if (verbosity >= 0)
1742 printf("\nFetched %s.pack\n", id_str);
1743 free(id_str);
1745 /* Set up references provided with the pack file. */
1746 TAILQ_FOREACH(pe, &refs, entry) {
1747 const char *refname = pe->path;
1748 struct got_object_id *id = pe->data;
1749 char *remote_refname;
1751 if (is_wanted_ref(&wanted_refs, refname) &&
1752 !mirror_references) {
1753 error = create_wanted_ref(refname, id,
1754 GOT_FETCH_DEFAULT_REMOTE_NAME,
1755 verbosity - 1, repo);
1756 if (error)
1757 goto done;
1758 continue;
1761 error = create_ref(refname, id, verbosity - 1, repo);
1762 if (error)
1763 goto done;
1765 if (mirror_references)
1766 continue;
1768 if (strncmp("refs/heads/", refname, 11) != 0)
1769 continue;
1771 if (asprintf(&remote_refname,
1772 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1773 refname + 11) == -1) {
1774 error = got_error_from_errno("asprintf");
1775 goto done;
1777 error = create_ref(remote_refname, id, verbosity - 1, repo);
1778 free(remote_refname);
1779 if (error)
1780 goto done;
1783 /* Set the HEAD reference if the server provided one. */
1784 TAILQ_FOREACH(pe, &symrefs, entry) {
1785 struct got_reference *target_ref;
1786 const char *refname = pe->path;
1787 const char *target = pe->data;
1788 char *remote_refname = NULL, *remote_target = NULL;
1790 if (strcmp(refname, GOT_REF_HEAD) != 0)
1791 continue;
1793 error = got_ref_open(&target_ref, repo, target, 0);
1794 if (error) {
1795 if (error->code == GOT_ERR_NOT_REF) {
1796 error = NULL;
1797 continue;
1799 goto done;
1802 error = create_symref(refname, target_ref, verbosity, repo);
1803 got_ref_close(target_ref);
1804 if (error)
1805 goto done;
1807 if (mirror_references)
1808 continue;
1810 if (strncmp("refs/heads/", target, 11) != 0)
1811 continue;
1813 if (asprintf(&remote_refname,
1814 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1815 refname) == -1) {
1816 error = got_error_from_errno("asprintf");
1817 goto done;
1819 if (asprintf(&remote_target,
1820 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1821 target + 11) == -1) {
1822 error = got_error_from_errno("asprintf");
1823 free(remote_refname);
1824 goto done;
1826 error = got_ref_open(&target_ref, repo, remote_target, 0);
1827 if (error) {
1828 free(remote_refname);
1829 free(remote_target);
1830 if (error->code == GOT_ERR_NOT_REF) {
1831 error = NULL;
1832 continue;
1834 goto done;
1836 error = create_symref(remote_refname, target_ref,
1837 verbosity - 1, repo);
1838 free(remote_refname);
1839 free(remote_target);
1840 got_ref_close(target_ref);
1841 if (error)
1842 goto done;
1844 if (pe == NULL) {
1846 * We failed to set the HEAD reference. If we asked for
1847 * a set of wanted branches use the first of one of those
1848 * which could be fetched instead.
1850 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1851 const char *target = pe->path;
1852 struct got_reference *target_ref;
1854 error = got_ref_open(&target_ref, repo, target, 0);
1855 if (error) {
1856 if (error->code == GOT_ERR_NOT_REF) {
1857 error = NULL;
1858 continue;
1860 goto done;
1863 error = create_symref(GOT_REF_HEAD, target_ref,
1864 verbosity, repo);
1865 got_ref_close(target_ref);
1866 if (error)
1867 goto done;
1868 break;
1872 if (verbosity >= 0)
1873 printf("Created %s repository '%s'\n",
1874 mirror_references ? "mirrored" : "cloned", repo_path);
1875 done:
1876 if (pack_fds) {
1877 const struct got_error *pack_err =
1878 got_repo_pack_fds_close(pack_fds);
1879 if (error == NULL)
1880 error = pack_err;
1882 if (fetchpid > 0) {
1883 if (kill(fetchpid, SIGTERM) == -1)
1884 error = got_error_from_errno("kill");
1885 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1886 error = got_error_from_errno("waitpid");
1888 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1889 error = got_error_from_errno("close");
1890 if (repo) {
1891 const struct got_error *close_err = got_repo_close(repo);
1892 if (error == NULL)
1893 error = close_err;
1895 TAILQ_FOREACH(pe, &refs, entry) {
1896 free((void *)pe->path);
1897 free(pe->data);
1899 got_pathlist_free(&refs);
1900 TAILQ_FOREACH(pe, &symrefs, entry) {
1901 free((void *)pe->path);
1902 free(pe->data);
1904 got_pathlist_free(&symrefs);
1905 got_pathlist_free(&wanted_branches);
1906 got_pathlist_free(&wanted_refs);
1907 free(pack_hash);
1908 free(proto);
1909 free(host);
1910 free(port);
1911 free(server_path);
1912 free(repo_name);
1913 free(default_destdir);
1914 free(git_url);
1915 return error;
1918 static const struct got_error *
1919 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1920 int replace_tags, int verbosity, struct got_repository *repo)
1922 const struct got_error *err = NULL;
1923 char *new_id_str = NULL;
1924 struct got_object_id *old_id = NULL;
1926 err = got_object_id_str(&new_id_str, new_id);
1927 if (err)
1928 goto done;
1930 if (!replace_tags &&
1931 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1932 err = got_ref_resolve(&old_id, repo, ref);
1933 if (err)
1934 goto done;
1935 if (got_object_id_cmp(old_id, new_id) == 0)
1936 goto done;
1937 if (verbosity >= 0) {
1938 printf("Rejecting update of existing tag %s: %s\n",
1939 got_ref_get_name(ref), new_id_str);
1941 goto done;
1944 if (got_ref_is_symbolic(ref)) {
1945 if (verbosity >= 0) {
1946 printf("Replacing reference %s: %s\n",
1947 got_ref_get_name(ref),
1948 got_ref_get_symref_target(ref));
1950 err = got_ref_change_symref_to_ref(ref, new_id);
1951 if (err)
1952 goto done;
1953 err = got_ref_write(ref, repo);
1954 if (err)
1955 goto done;
1956 } else {
1957 err = got_ref_resolve(&old_id, repo, ref);
1958 if (err)
1959 goto done;
1960 if (got_object_id_cmp(old_id, new_id) == 0)
1961 goto done;
1963 err = got_ref_change_ref(ref, new_id);
1964 if (err)
1965 goto done;
1966 err = got_ref_write(ref, repo);
1967 if (err)
1968 goto done;
1971 if (verbosity >= 0)
1972 printf("Updated %s: %s\n", got_ref_get_name(ref),
1973 new_id_str);
1974 done:
1975 free(old_id);
1976 free(new_id_str);
1977 return err;
1980 static const struct got_error *
1981 update_symref(const char *refname, struct got_reference *target_ref,
1982 int verbosity, struct got_repository *repo)
1984 const struct got_error *err = NULL, *unlock_err;
1985 struct got_reference *symref;
1986 int symref_is_locked = 0;
1988 err = got_ref_open(&symref, repo, refname, 1);
1989 if (err) {
1990 if (err->code != GOT_ERR_NOT_REF)
1991 return err;
1992 err = got_ref_alloc_symref(&symref, refname, target_ref);
1993 if (err)
1994 goto done;
1996 err = got_ref_write(symref, repo);
1997 if (err)
1998 goto done;
2000 if (verbosity >= 0)
2001 printf("Created reference %s: %s\n",
2002 got_ref_get_name(symref),
2003 got_ref_get_symref_target(symref));
2004 } else {
2005 symref_is_locked = 1;
2007 if (strcmp(got_ref_get_symref_target(symref),
2008 got_ref_get_name(target_ref)) == 0)
2009 goto done;
2011 err = got_ref_change_symref(symref,
2012 got_ref_get_name(target_ref));
2013 if (err)
2014 goto done;
2016 err = got_ref_write(symref, repo);
2017 if (err)
2018 goto done;
2020 if (verbosity >= 0)
2021 printf("Updated %s: %s\n", got_ref_get_name(symref),
2022 got_ref_get_symref_target(symref));
2025 done:
2026 if (symref_is_locked) {
2027 unlock_err = got_ref_unlock(symref);
2028 if (unlock_err && err == NULL)
2029 err = unlock_err;
2031 got_ref_close(symref);
2032 return err;
2035 __dead static void
2036 usage_fetch(void)
2038 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2039 "[-R reference] [-r repository-path] [remote-repository]\n",
2040 getprogname());
2041 exit(1);
2044 static const struct got_error *
2045 delete_missing_ref(struct got_reference *ref,
2046 int verbosity, struct got_repository *repo)
2048 const struct got_error *err = NULL;
2049 struct got_object_id *id = NULL;
2050 char *id_str = NULL;
2052 if (got_ref_is_symbolic(ref)) {
2053 err = got_ref_delete(ref, repo);
2054 if (err)
2055 return err;
2056 if (verbosity >= 0) {
2057 printf("Deleted %s: %s\n",
2058 got_ref_get_name(ref),
2059 got_ref_get_symref_target(ref));
2061 } else {
2062 err = got_ref_resolve(&id, repo, ref);
2063 if (err)
2064 return err;
2065 err = got_object_id_str(&id_str, id);
2066 if (err)
2067 goto done;
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 goto done;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref), id_str);
2077 done:
2078 free(id);
2079 free(id_str);
2080 return NULL;
2083 static const struct got_error *
2084 delete_missing_refs(struct got_pathlist_head *their_refs,
2085 struct got_pathlist_head *their_symrefs,
2086 const struct got_remote_repo *remote,
2087 int verbosity, struct got_repository *repo)
2089 const struct got_error *err = NULL, *unlock_err;
2090 struct got_reflist_head my_refs;
2091 struct got_reflist_entry *re;
2092 struct got_pathlist_entry *pe;
2093 char *remote_namespace = NULL;
2094 char *local_refname = NULL;
2096 TAILQ_INIT(&my_refs);
2098 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2099 == -1)
2100 return got_error_from_errno("asprintf");
2102 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2103 if (err)
2104 goto done;
2106 TAILQ_FOREACH(re, &my_refs, entry) {
2107 const char *refname = got_ref_get_name(re->ref);
2108 const char *their_refname;
2110 if (remote->mirror_references) {
2111 their_refname = refname;
2112 } else {
2113 if (strncmp(refname, remote_namespace,
2114 strlen(remote_namespace)) == 0) {
2115 if (strcmp(refname + strlen(remote_namespace),
2116 GOT_REF_HEAD) == 0)
2117 continue;
2118 if (asprintf(&local_refname, "refs/heads/%s",
2119 refname + strlen(remote_namespace)) == -1) {
2120 err = got_error_from_errno("asprintf");
2121 goto done;
2123 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2124 continue;
2126 their_refname = local_refname;
2129 TAILQ_FOREACH(pe, their_refs, entry) {
2130 if (strcmp(their_refname, pe->path) == 0)
2131 break;
2133 if (pe != NULL)
2134 continue;
2136 TAILQ_FOREACH(pe, their_symrefs, entry) {
2137 if (strcmp(their_refname, pe->path) == 0)
2138 break;
2140 if (pe != NULL)
2141 continue;
2143 err = delete_missing_ref(re->ref, verbosity, repo);
2144 if (err)
2145 break;
2147 if (local_refname) {
2148 struct got_reference *ref;
2149 err = got_ref_open(&ref, repo, local_refname, 1);
2150 if (err) {
2151 if (err->code != GOT_ERR_NOT_REF)
2152 break;
2153 free(local_refname);
2154 local_refname = NULL;
2155 continue;
2157 err = delete_missing_ref(ref, verbosity, repo);
2158 if (err)
2159 break;
2160 unlock_err = got_ref_unlock(ref);
2161 got_ref_close(ref);
2162 if (unlock_err && err == NULL) {
2163 err = unlock_err;
2164 break;
2167 free(local_refname);
2168 local_refname = NULL;
2171 done:
2172 free(remote_namespace);
2173 free(local_refname);
2174 return err;
2177 static const struct got_error *
2178 update_wanted_ref(const char *refname, struct got_object_id *id,
2179 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2181 const struct got_error *err, *unlock_err;
2182 char *remote_refname;
2183 struct got_reference *ref;
2185 if (strncmp("refs/", refname, 5) == 0)
2186 refname += 5;
2188 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2189 remote_repo_name, refname) == -1)
2190 return got_error_from_errno("asprintf");
2192 err = got_ref_open(&ref, repo, remote_refname, 1);
2193 if (err) {
2194 if (err->code != GOT_ERR_NOT_REF)
2195 goto done;
2196 err = create_ref(remote_refname, id, verbosity, repo);
2197 } else {
2198 err = update_ref(ref, id, 0, verbosity, repo);
2199 unlock_err = got_ref_unlock(ref);
2200 if (unlock_err && err == NULL)
2201 err = unlock_err;
2202 got_ref_close(ref);
2204 done:
2205 free(remote_refname);
2206 return err;
2209 static const struct got_error *
2210 delete_ref(struct got_repository *repo, struct got_reference *ref)
2212 const struct got_error *err = NULL;
2213 struct got_object_id *id = NULL;
2214 char *id_str = NULL;
2215 const char *target;
2217 if (got_ref_is_symbolic(ref)) {
2218 target = got_ref_get_symref_target(ref);
2219 } else {
2220 err = got_ref_resolve(&id, repo, ref);
2221 if (err)
2222 goto done;
2223 err = got_object_id_str(&id_str, id);
2224 if (err)
2225 goto done;
2226 target = id_str;
2229 err = got_ref_delete(ref, repo);
2230 if (err)
2231 goto done;
2233 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2234 done:
2235 free(id);
2236 free(id_str);
2237 return err;
2240 static const struct got_error *
2241 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2243 const struct got_error *err = NULL;
2244 struct got_reflist_head refs;
2245 struct got_reflist_entry *re;
2246 char *prefix;
2248 TAILQ_INIT(&refs);
2250 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2251 err = got_error_from_errno("asprintf");
2252 goto done;
2254 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2255 if (err)
2256 goto done;
2258 TAILQ_FOREACH(re, &refs, entry)
2259 delete_ref(repo, re->ref);
2260 done:
2261 got_ref_list_free(&refs);
2262 return err;
2265 static const struct got_error *
2266 cmd_fetch(int argc, char *argv[])
2268 const struct got_error *error = NULL, *unlock_err;
2269 char *cwd = NULL, *repo_path = NULL;
2270 const char *remote_name;
2271 char *proto = NULL, *host = NULL, *port = NULL;
2272 char *repo_name = NULL, *server_path = NULL;
2273 const struct got_remote_repo *remotes, *remote = NULL;
2274 int nremotes;
2275 char *id_str = NULL;
2276 struct got_repository *repo = NULL;
2277 struct got_worktree *worktree = NULL;
2278 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2279 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2280 struct got_pathlist_entry *pe;
2281 struct got_object_id *pack_hash = NULL;
2282 int i, ch, fetchfd = -1, fetchstatus;
2283 pid_t fetchpid = -1;
2284 struct got_fetch_progress_arg fpa;
2285 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2286 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2287 int *pack_fds = NULL;
2289 TAILQ_INIT(&refs);
2290 TAILQ_INIT(&symrefs);
2291 TAILQ_INIT(&wanted_branches);
2292 TAILQ_INIT(&wanted_refs);
2294 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2295 switch (ch) {
2296 case 'a':
2297 fetch_all_branches = 1;
2298 break;
2299 case 'b':
2300 error = got_pathlist_append(&wanted_branches,
2301 optarg, NULL);
2302 if (error)
2303 return error;
2304 break;
2305 case 'd':
2306 delete_refs = 1;
2307 break;
2308 case 'l':
2309 list_refs_only = 1;
2310 break;
2311 case 'r':
2312 repo_path = realpath(optarg, NULL);
2313 if (repo_path == NULL)
2314 return got_error_from_errno2("realpath",
2315 optarg);
2316 got_path_strip_trailing_slashes(repo_path);
2317 break;
2318 case 't':
2319 replace_tags = 1;
2320 break;
2321 case 'v':
2322 if (verbosity < 0)
2323 verbosity = 0;
2324 else if (verbosity < 3)
2325 verbosity++;
2326 break;
2327 case 'q':
2328 verbosity = -1;
2329 break;
2330 case 'R':
2331 error = got_pathlist_append(&wanted_refs,
2332 optarg, NULL);
2333 if (error)
2334 return error;
2335 break;
2336 case 'X':
2337 delete_remote = 1;
2338 break;
2339 default:
2340 usage_fetch();
2341 break;
2344 argc -= optind;
2345 argv += optind;
2347 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2348 option_conflict('a', 'b');
2349 if (list_refs_only) {
2350 if (!TAILQ_EMPTY(&wanted_branches))
2351 option_conflict('l', 'b');
2352 if (fetch_all_branches)
2353 option_conflict('l', 'a');
2354 if (delete_refs)
2355 option_conflict('l', 'd');
2356 if (delete_remote)
2357 option_conflict('l', 'X');
2359 if (delete_remote) {
2360 if (fetch_all_branches)
2361 option_conflict('X', 'a');
2362 if (!TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('X', 'b');
2364 if (delete_refs)
2365 option_conflict('X', 'd');
2366 if (replace_tags)
2367 option_conflict('X', 't');
2368 if (!TAILQ_EMPTY(&wanted_refs))
2369 option_conflict('X', 'R');
2372 if (argc == 0) {
2373 if (delete_remote)
2374 errx(1, "-X option requires a remote name");
2375 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2376 } else if (argc == 1)
2377 remote_name = argv[0];
2378 else
2379 usage_fetch();
2381 cwd = getcwd(NULL, 0);
2382 if (cwd == NULL) {
2383 error = got_error_from_errno("getcwd");
2384 goto done;
2387 error = got_repo_pack_fds_open(&pack_fds);
2388 if (error != NULL)
2389 goto done;
2391 if (repo_path == NULL) {
2392 error = got_worktree_open(&worktree, cwd);
2393 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2394 goto done;
2395 else
2396 error = NULL;
2397 if (worktree) {
2398 repo_path =
2399 strdup(got_worktree_get_repo_path(worktree));
2400 if (repo_path == NULL)
2401 error = got_error_from_errno("strdup");
2402 if (error)
2403 goto done;
2404 } else {
2405 repo_path = strdup(cwd);
2406 if (repo_path == NULL) {
2407 error = got_error_from_errno("strdup");
2408 goto done;
2413 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2414 if (error)
2415 goto done;
2417 if (delete_remote) {
2418 error = delete_refs_for_remote(repo, remote_name);
2419 goto done; /* nothing else to do */
2422 if (worktree) {
2423 worktree_conf = got_worktree_get_gotconfig(worktree);
2424 if (worktree_conf) {
2425 got_gotconfig_get_remotes(&nremotes, &remotes,
2426 worktree_conf);
2427 for (i = 0; i < nremotes; i++) {
2428 if (strcmp(remotes[i].name, remote_name) == 0) {
2429 remote = &remotes[i];
2430 break;
2435 if (remote == NULL) {
2436 repo_conf = got_repo_get_gotconfig(repo);
2437 if (repo_conf) {
2438 got_gotconfig_get_remotes(&nremotes, &remotes,
2439 repo_conf);
2440 for (i = 0; i < nremotes; i++) {
2441 if (strcmp(remotes[i].name, remote_name) == 0) {
2442 remote = &remotes[i];
2443 break;
2448 if (remote == NULL) {
2449 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 remote = &remotes[i];
2453 break;
2457 if (remote == NULL) {
2458 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2459 goto done;
2462 if (TAILQ_EMPTY(&wanted_branches)) {
2463 if (!fetch_all_branches)
2464 fetch_all_branches = remote->fetch_all_branches;
2465 for (i = 0; i < remote->nfetch_branches; i++) {
2466 got_pathlist_append(&wanted_branches,
2467 remote->fetch_branches[i], NULL);
2470 if (TAILQ_EMPTY(&wanted_refs)) {
2471 for (i = 0; i < remote->nfetch_refs; i++) {
2472 got_pathlist_append(&wanted_refs,
2473 remote->fetch_refs[i], NULL);
2477 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2478 &repo_name, remote->fetch_url);
2479 if (error)
2480 goto done;
2482 if (strcmp(proto, "git") == 0) {
2483 #ifndef PROFILE
2484 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2485 "sendfd dns inet unveil", NULL) == -1)
2486 err(1, "pledge");
2487 #endif
2488 } else if (strcmp(proto, "git+ssh") == 0 ||
2489 strcmp(proto, "ssh") == 0) {
2490 #ifndef PROFILE
2491 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2492 "sendfd unveil", NULL) == -1)
2493 err(1, "pledge");
2494 #endif
2495 } else if (strcmp(proto, "http") == 0 ||
2496 strcmp(proto, "git+http") == 0) {
2497 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2498 goto done;
2499 } else {
2500 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2501 goto done;
2504 error = got_dial_apply_unveil(proto);
2505 if (error)
2506 goto done;
2508 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2509 if (error)
2510 goto done;
2512 if (verbosity >= 0)
2513 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2514 port ? ":" : "", port ? port : "");
2516 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2517 server_path, verbosity);
2518 if (error)
2519 goto done;
2521 fpa.last_scaled_size[0] = '\0';
2522 fpa.last_p_indexed = -1;
2523 fpa.last_p_resolved = -1;
2524 fpa.verbosity = verbosity;
2525 fpa.repo = repo;
2526 fpa.create_configs = 0;
2527 fpa.configs_created = 0;
2528 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2529 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2530 remote->mirror_references, fetch_all_branches, &wanted_branches,
2531 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2532 fetch_progress, &fpa);
2533 if (error)
2534 goto done;
2536 if (list_refs_only) {
2537 error = list_remote_refs(&symrefs, &refs);
2538 goto done;
2541 if (pack_hash == NULL) {
2542 if (verbosity >= 0)
2543 printf("Already up-to-date\n");
2544 } else if (verbosity >= 0) {
2545 error = got_object_id_str(&id_str, pack_hash);
2546 if (error)
2547 goto done;
2548 printf("\nFetched %s.pack\n", id_str);
2549 free(id_str);
2550 id_str = NULL;
2553 /* Update references provided with the pack file. */
2554 TAILQ_FOREACH(pe, &refs, entry) {
2555 const char *refname = pe->path;
2556 struct got_object_id *id = pe->data;
2557 struct got_reference *ref;
2558 char *remote_refname;
2560 if (is_wanted_ref(&wanted_refs, refname) &&
2561 !remote->mirror_references) {
2562 error = update_wanted_ref(refname, id,
2563 remote->name, verbosity, repo);
2564 if (error)
2565 goto done;
2566 continue;
2569 if (remote->mirror_references ||
2570 strncmp("refs/tags/", refname, 10) == 0) {
2571 error = got_ref_open(&ref, repo, refname, 1);
2572 if (error) {
2573 if (error->code != GOT_ERR_NOT_REF)
2574 goto done;
2575 error = create_ref(refname, id, verbosity,
2576 repo);
2577 if (error)
2578 goto done;
2579 } else {
2580 error = update_ref(ref, id, replace_tags,
2581 verbosity, repo);
2582 unlock_err = got_ref_unlock(ref);
2583 if (unlock_err && error == NULL)
2584 error = unlock_err;
2585 got_ref_close(ref);
2586 if (error)
2587 goto done;
2589 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2590 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2591 remote_name, refname + 11) == -1) {
2592 error = got_error_from_errno("asprintf");
2593 goto done;
2596 error = got_ref_open(&ref, repo, remote_refname, 1);
2597 if (error) {
2598 if (error->code != GOT_ERR_NOT_REF)
2599 goto done;
2600 error = create_ref(remote_refname, id,
2601 verbosity, repo);
2602 if (error)
2603 goto done;
2604 } else {
2605 error = update_ref(ref, id, replace_tags,
2606 verbosity, repo);
2607 unlock_err = got_ref_unlock(ref);
2608 if (unlock_err && error == NULL)
2609 error = unlock_err;
2610 got_ref_close(ref);
2611 if (error)
2612 goto done;
2615 /* Also create a local branch if none exists yet. */
2616 error = got_ref_open(&ref, repo, refname, 1);
2617 if (error) {
2618 if (error->code != GOT_ERR_NOT_REF)
2619 goto done;
2620 error = create_ref(refname, id, verbosity,
2621 repo);
2622 if (error)
2623 goto done;
2624 } else {
2625 unlock_err = got_ref_unlock(ref);
2626 if (unlock_err && error == NULL)
2627 error = unlock_err;
2628 got_ref_close(ref);
2632 if (delete_refs) {
2633 error = delete_missing_refs(&refs, &symrefs, remote,
2634 verbosity, repo);
2635 if (error)
2636 goto done;
2639 if (!remote->mirror_references) {
2640 /* Update remote HEAD reference if the server provided one. */
2641 TAILQ_FOREACH(pe, &symrefs, entry) {
2642 struct got_reference *target_ref;
2643 const char *refname = pe->path;
2644 const char *target = pe->data;
2645 char *remote_refname = NULL, *remote_target = NULL;
2647 if (strcmp(refname, GOT_REF_HEAD) != 0)
2648 continue;
2650 if (strncmp("refs/heads/", target, 11) != 0)
2651 continue;
2653 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2654 remote->name, refname) == -1) {
2655 error = got_error_from_errno("asprintf");
2656 goto done;
2658 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2659 remote->name, target + 11) == -1) {
2660 error = got_error_from_errno("asprintf");
2661 free(remote_refname);
2662 goto done;
2665 error = got_ref_open(&target_ref, repo, remote_target,
2666 0);
2667 if (error) {
2668 free(remote_refname);
2669 free(remote_target);
2670 if (error->code == GOT_ERR_NOT_REF) {
2671 error = NULL;
2672 continue;
2674 goto done;
2676 error = update_symref(remote_refname, target_ref,
2677 verbosity, repo);
2678 free(remote_refname);
2679 free(remote_target);
2680 got_ref_close(target_ref);
2681 if (error)
2682 goto done;
2685 done:
2686 if (fetchpid > 0) {
2687 if (kill(fetchpid, SIGTERM) == -1)
2688 error = got_error_from_errno("kill");
2689 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2690 error = got_error_from_errno("waitpid");
2692 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2693 error = got_error_from_errno("close");
2694 if (repo) {
2695 const struct got_error *close_err = got_repo_close(repo);
2696 if (error == NULL)
2697 error = close_err;
2699 if (worktree)
2700 got_worktree_close(worktree);
2701 if (pack_fds) {
2702 const struct got_error *pack_err =
2703 got_repo_pack_fds_close(pack_fds);
2704 if (error == NULL)
2705 error = pack_err;
2707 TAILQ_FOREACH(pe, &refs, entry) {
2708 free((void *)pe->path);
2709 free(pe->data);
2711 got_pathlist_free(&refs);
2712 TAILQ_FOREACH(pe, &symrefs, entry) {
2713 free((void *)pe->path);
2714 free(pe->data);
2716 got_pathlist_free(&symrefs);
2717 got_pathlist_free(&wanted_branches);
2718 got_pathlist_free(&wanted_refs);
2719 free(id_str);
2720 free(cwd);
2721 free(repo_path);
2722 free(pack_hash);
2723 free(proto);
2724 free(host);
2725 free(port);
2726 free(server_path);
2727 free(repo_name);
2728 return error;
2732 __dead static void
2733 usage_checkout(void)
2735 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2736 "[-p path-prefix] repository-path [work-tree-path]\n",
2737 getprogname());
2738 exit(1);
2741 static void
2742 show_worktree_base_ref_warning(void)
2744 fprintf(stderr, "%s: warning: could not create a reference "
2745 "to the work tree's base commit; the commit could be "
2746 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2747 "repository writable and running 'got update' will prevent this\n",
2748 getprogname());
2751 struct got_checkout_progress_arg {
2752 const char *worktree_path;
2753 int had_base_commit_ref_error;
2754 int verbosity;
2757 static const struct got_error *
2758 checkout_progress(void *arg, unsigned char status, const char *path)
2760 struct got_checkout_progress_arg *a = arg;
2762 /* Base commit bump happens silently. */
2763 if (status == GOT_STATUS_BUMP_BASE)
2764 return NULL;
2766 if (status == GOT_STATUS_BASE_REF_ERR) {
2767 a->had_base_commit_ref_error = 1;
2768 return NULL;
2771 while (path[0] == '/')
2772 path++;
2774 if (a->verbosity >= 0)
2775 printf("%c %s/%s\n", status, a->worktree_path, path);
2777 return NULL;
2780 static const struct got_error *
2781 check_cancelled(void *arg)
2783 if (sigint_received || sigpipe_received)
2784 return got_error(GOT_ERR_CANCELLED);
2785 return NULL;
2788 static const struct got_error *
2789 check_linear_ancestry(struct got_object_id *commit_id,
2790 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2791 struct got_repository *repo)
2793 const struct got_error *err = NULL;
2794 struct got_object_id *yca_id;
2796 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2797 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2798 if (err)
2799 return err;
2801 if (yca_id == NULL)
2802 return got_error(GOT_ERR_ANCESTRY);
2805 * Require a straight line of history between the target commit
2806 * and the work tree's base commit.
2808 * Non-linear situations such as this require a rebase:
2810 * (commit) D F (base_commit)
2811 * \ /
2812 * C E
2813 * \ /
2814 * B (yca)
2815 * |
2816 * A
2818 * 'got update' only handles linear cases:
2819 * Update forwards in time: A (base/yca) - B - C - D (commit)
2820 * Update backwards in time: D (base) - C - B - A (commit/yca)
2822 if (allow_forwards_in_time_only) {
2823 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2824 return got_error(GOT_ERR_ANCESTRY);
2825 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2826 got_object_id_cmp(base_commit_id, yca_id) != 0)
2827 return got_error(GOT_ERR_ANCESTRY);
2829 free(yca_id);
2830 return NULL;
2833 static const struct got_error *
2834 check_same_branch(struct got_object_id *commit_id,
2835 struct got_reference *head_ref, struct got_object_id *yca_id,
2836 struct got_repository *repo)
2838 const struct got_error *err = NULL;
2839 struct got_commit_graph *graph = NULL;
2840 struct got_object_id *head_commit_id = NULL;
2841 int is_same_branch = 0;
2843 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2844 if (err)
2845 goto done;
2847 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2848 is_same_branch = 1;
2849 goto done;
2851 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2852 is_same_branch = 1;
2853 goto done;
2856 err = got_commit_graph_open(&graph, "/", 1);
2857 if (err)
2858 goto done;
2860 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2861 check_cancelled, NULL);
2862 if (err)
2863 goto done;
2865 for (;;) {
2866 struct got_object_id id;
2868 err = got_commit_graph_iter_next(&id, graph, repo,
2869 check_cancelled, NULL);
2870 if (err) {
2871 if (err->code == GOT_ERR_ITER_COMPLETED)
2872 err = NULL;
2873 break;
2876 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2877 break;
2878 if (got_object_id_cmp(&id, commit_id) == 0) {
2879 is_same_branch = 1;
2880 break;
2883 done:
2884 if (graph)
2885 got_commit_graph_close(graph);
2886 free(head_commit_id);
2887 if (!err && !is_same_branch)
2888 err = got_error(GOT_ERR_ANCESTRY);
2889 return err;
2892 static const struct got_error *
2893 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2895 static char msg[512];
2896 const char *branch_name;
2898 if (got_ref_is_symbolic(ref))
2899 branch_name = got_ref_get_symref_target(ref);
2900 else
2901 branch_name = got_ref_get_name(ref);
2903 if (strncmp("refs/heads/", branch_name, 11) == 0)
2904 branch_name += 11;
2906 snprintf(msg, sizeof(msg),
2907 "target commit is not contained in branch '%s'; "
2908 "the branch to use must be specified with -b; "
2909 "if necessary a new branch can be created for "
2910 "this commit with 'got branch -c %s BRANCH_NAME'",
2911 branch_name, commit_id_str);
2913 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2916 static const struct got_error *
2917 cmd_checkout(int argc, char *argv[])
2919 const struct got_error *error = NULL;
2920 struct got_repository *repo = NULL;
2921 struct got_reference *head_ref = NULL, *ref = NULL;
2922 struct got_worktree *worktree = NULL;
2923 char *repo_path = NULL;
2924 char *worktree_path = NULL;
2925 const char *path_prefix = "";
2926 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2927 char *commit_id_str = NULL;
2928 struct got_object_id *commit_id = NULL;
2929 char *cwd = NULL;
2930 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2931 struct got_pathlist_head paths;
2932 struct got_checkout_progress_arg cpa;
2933 int *pack_fds = NULL;
2935 TAILQ_INIT(&paths);
2937 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2938 switch (ch) {
2939 case 'b':
2940 branch_name = optarg;
2941 break;
2942 case 'c':
2943 commit_id_str = strdup(optarg);
2944 if (commit_id_str == NULL)
2945 return got_error_from_errno("strdup");
2946 break;
2947 case 'E':
2948 allow_nonempty = 1;
2949 break;
2950 case 'p':
2951 path_prefix = optarg;
2952 break;
2953 case 'q':
2954 verbosity = -1;
2955 break;
2956 default:
2957 usage_checkout();
2958 /* NOTREACHED */
2962 argc -= optind;
2963 argv += optind;
2965 #ifndef PROFILE
2966 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2967 "unveil", NULL) == -1)
2968 err(1, "pledge");
2969 #endif
2970 if (argc == 1) {
2971 char *base, *dotgit;
2972 const char *path;
2973 repo_path = realpath(argv[0], NULL);
2974 if (repo_path == NULL)
2975 return got_error_from_errno2("realpath", argv[0]);
2976 cwd = getcwd(NULL, 0);
2977 if (cwd == NULL) {
2978 error = got_error_from_errno("getcwd");
2979 goto done;
2981 if (path_prefix[0])
2982 path = path_prefix;
2983 else
2984 path = repo_path;
2985 error = got_path_basename(&base, path);
2986 if (error)
2987 goto done;
2988 dotgit = strstr(base, ".git");
2989 if (dotgit)
2990 *dotgit = '\0';
2991 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2992 error = got_error_from_errno("asprintf");
2993 free(base);
2994 goto done;
2996 free(base);
2997 } else if (argc == 2) {
2998 repo_path = realpath(argv[0], NULL);
2999 if (repo_path == NULL) {
3000 error = got_error_from_errno2("realpath", argv[0]);
3001 goto done;
3003 worktree_path = realpath(argv[1], NULL);
3004 if (worktree_path == NULL) {
3005 if (errno != ENOENT) {
3006 error = got_error_from_errno2("realpath",
3007 argv[1]);
3008 goto done;
3010 worktree_path = strdup(argv[1]);
3011 if (worktree_path == NULL) {
3012 error = got_error_from_errno("strdup");
3013 goto done;
3016 } else
3017 usage_checkout();
3019 got_path_strip_trailing_slashes(repo_path);
3020 got_path_strip_trailing_slashes(worktree_path);
3022 error = got_repo_pack_fds_open(&pack_fds);
3023 if (error != NULL)
3024 goto done;
3026 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3027 if (error != NULL)
3028 goto done;
3030 /* Pre-create work tree path for unveil(2) */
3031 error = got_path_mkdir(worktree_path);
3032 if (error) {
3033 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3034 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3035 goto done;
3036 if (!allow_nonempty &&
3037 !got_path_dir_is_empty(worktree_path)) {
3038 error = got_error_path(worktree_path,
3039 GOT_ERR_DIR_NOT_EMPTY);
3040 goto done;
3044 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3045 if (error)
3046 goto done;
3048 error = got_ref_open(&head_ref, repo, branch_name, 0);
3049 if (error != NULL)
3050 goto done;
3052 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3053 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3054 goto done;
3056 error = got_worktree_open(&worktree, worktree_path);
3057 if (error != NULL)
3058 goto done;
3060 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3061 path_prefix);
3062 if (error != NULL)
3063 goto done;
3064 if (!same_path_prefix) {
3065 error = got_error(GOT_ERR_PATH_PREFIX);
3066 goto done;
3069 if (commit_id_str) {
3070 struct got_reflist_head refs;
3071 TAILQ_INIT(&refs);
3072 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3073 NULL);
3074 if (error)
3075 goto done;
3076 error = got_repo_match_object_id(&commit_id, NULL,
3077 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3078 got_ref_list_free(&refs);
3079 if (error)
3080 goto done;
3081 error = check_linear_ancestry(commit_id,
3082 got_worktree_get_base_commit_id(worktree), 0, repo);
3083 if (error != NULL) {
3084 if (error->code == GOT_ERR_ANCESTRY) {
3085 error = checkout_ancestry_error(
3086 head_ref, commit_id_str);
3088 goto done;
3090 error = check_same_branch(commit_id, head_ref, NULL, repo);
3091 if (error) {
3092 if (error->code == GOT_ERR_ANCESTRY) {
3093 error = checkout_ancestry_error(
3094 head_ref, commit_id_str);
3096 goto done;
3098 error = got_worktree_set_base_commit_id(worktree, repo,
3099 commit_id);
3100 if (error)
3101 goto done;
3102 /* Expand potentially abbreviated commit ID string. */
3103 free(commit_id_str);
3104 error = got_object_id_str(&commit_id_str, commit_id);
3105 if (error)
3106 goto done;
3107 } else {
3108 commit_id = got_object_id_dup(
3109 got_worktree_get_base_commit_id(worktree));
3110 if (commit_id == NULL) {
3111 error = got_error_from_errno("got_object_id_dup");
3112 goto done;
3114 error = got_object_id_str(&commit_id_str, commit_id);
3115 if (error)
3116 goto done;
3119 error = got_pathlist_append(&paths, "", NULL);
3120 if (error)
3121 goto done;
3122 cpa.worktree_path = worktree_path;
3123 cpa.had_base_commit_ref_error = 0;
3124 cpa.verbosity = verbosity;
3125 error = got_worktree_checkout_files(worktree, &paths, repo,
3126 checkout_progress, &cpa, check_cancelled, NULL);
3127 if (error != NULL)
3128 goto done;
3130 if (got_ref_is_symbolic(head_ref)) {
3131 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3132 if (error)
3133 goto done;
3134 refname = got_ref_get_name(ref);
3135 } else
3136 refname = got_ref_get_name(head_ref);
3137 printf("Checked out %s: %s\n", refname, commit_id_str);
3138 printf("Now shut up and hack\n");
3139 if (cpa.had_base_commit_ref_error)
3140 show_worktree_base_ref_warning();
3141 done:
3142 if (pack_fds) {
3143 const struct got_error *pack_err =
3144 got_repo_pack_fds_close(pack_fds);
3145 if (error == NULL)
3146 error = pack_err;
3148 if (head_ref)
3149 got_ref_close(head_ref);
3150 if (ref)
3151 got_ref_close(ref);
3152 got_pathlist_free(&paths);
3153 free(commit_id_str);
3154 free(commit_id);
3155 free(repo_path);
3156 free(worktree_path);
3157 free(cwd);
3158 return error;
3161 struct got_update_progress_arg {
3162 int did_something;
3163 int conflicts;
3164 int obstructed;
3165 int not_updated;
3166 int missing;
3167 int not_deleted;
3168 int unversioned;
3169 int verbosity;
3172 static void
3173 print_update_progress_stats(struct got_update_progress_arg *upa)
3175 if (!upa->did_something)
3176 return;
3178 if (upa->conflicts > 0)
3179 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3180 if (upa->obstructed > 0)
3181 printf("File paths obstructed by a non-regular file: %d\n",
3182 upa->obstructed);
3183 if (upa->not_updated > 0)
3184 printf("Files not updated because of existing merge "
3185 "conflicts: %d\n", upa->not_updated);
3189 * The meaning of some status codes differs between merge-style operations and
3190 * update operations. For example, the ! status code means "file was missing"
3191 * if changes were merged into the work tree, and "missing file was restored"
3192 * if the work tree was updated. This function should be used by any operation
3193 * which merges changes into the work tree without updating the work tree.
3195 static void
3196 print_merge_progress_stats(struct got_update_progress_arg *upa)
3198 if (!upa->did_something)
3199 return;
3201 if (upa->conflicts > 0)
3202 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3203 if (upa->obstructed > 0)
3204 printf("File paths obstructed by a non-regular file: %d\n",
3205 upa->obstructed);
3206 if (upa->missing > 0)
3207 printf("Files which had incoming changes but could not be "
3208 "found in the work tree: %d\n", upa->missing);
3209 if (upa->not_deleted > 0)
3210 printf("Files not deleted due to differences in deleted "
3211 "content: %d\n", upa->not_deleted);
3212 if (upa->unversioned > 0)
3213 printf("Files not merged because an unversioned file was "
3214 "found in the work tree: %d\n", upa->unversioned);
3217 __dead static void
3218 usage_update(void)
3220 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3221 "[path ...]\n", getprogname());
3222 exit(1);
3225 static const struct got_error *
3226 update_progress(void *arg, unsigned char status, const char *path)
3228 struct got_update_progress_arg *upa = arg;
3230 if (status == GOT_STATUS_EXISTS ||
3231 status == GOT_STATUS_BASE_REF_ERR)
3232 return NULL;
3234 upa->did_something = 1;
3236 /* Base commit bump happens silently. */
3237 if (status == GOT_STATUS_BUMP_BASE)
3238 return NULL;
3240 if (status == GOT_STATUS_CONFLICT)
3241 upa->conflicts++;
3242 if (status == GOT_STATUS_OBSTRUCTED)
3243 upa->obstructed++;
3244 if (status == GOT_STATUS_CANNOT_UPDATE)
3245 upa->not_updated++;
3246 if (status == GOT_STATUS_MISSING)
3247 upa->missing++;
3248 if (status == GOT_STATUS_CANNOT_DELETE)
3249 upa->not_deleted++;
3250 if (status == GOT_STATUS_UNVERSIONED)
3251 upa->unversioned++;
3253 while (path[0] == '/')
3254 path++;
3255 if (upa->verbosity >= 0)
3256 printf("%c %s\n", status, path);
3258 return NULL;
3261 static const struct got_error *
3262 switch_head_ref(struct got_reference *head_ref,
3263 struct got_object_id *commit_id, struct got_worktree *worktree,
3264 struct got_repository *repo)
3266 const struct got_error *err = NULL;
3267 char *base_id_str;
3268 int ref_has_moved = 0;
3270 /* Trivial case: switching between two different references. */
3271 if (strcmp(got_ref_get_name(head_ref),
3272 got_worktree_get_head_ref_name(worktree)) != 0) {
3273 printf("Switching work tree from %s to %s\n",
3274 got_worktree_get_head_ref_name(worktree),
3275 got_ref_get_name(head_ref));
3276 return got_worktree_set_head_ref(worktree, head_ref);
3279 err = check_linear_ancestry(commit_id,
3280 got_worktree_get_base_commit_id(worktree), 0, repo);
3281 if (err) {
3282 if (err->code != GOT_ERR_ANCESTRY)
3283 return err;
3284 ref_has_moved = 1;
3286 if (!ref_has_moved)
3287 return NULL;
3289 /* Switching to a rebased branch with the same reference name. */
3290 err = got_object_id_str(&base_id_str,
3291 got_worktree_get_base_commit_id(worktree));
3292 if (err)
3293 return err;
3294 printf("Reference %s now points at a different branch\n",
3295 got_worktree_get_head_ref_name(worktree));
3296 printf("Switching work tree from %s to %s\n", base_id_str,
3297 got_worktree_get_head_ref_name(worktree));
3298 return NULL;
3301 static const struct got_error *
3302 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3304 const struct got_error *err;
3305 int in_progress;
3307 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3308 if (err)
3309 return err;
3310 if (in_progress)
3311 return got_error(GOT_ERR_REBASING);
3313 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3314 if (err)
3315 return err;
3316 if (in_progress)
3317 return got_error(GOT_ERR_HISTEDIT_BUSY);
3319 return NULL;
3322 static const struct got_error *
3323 check_merge_in_progress(struct got_worktree *worktree,
3324 struct got_repository *repo)
3326 const struct got_error *err;
3327 int in_progress;
3329 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3330 if (err)
3331 return err;
3332 if (in_progress)
3333 return got_error(GOT_ERR_MERGE_BUSY);
3335 return NULL;
3338 static const struct got_error *
3339 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3340 char *argv[], struct got_worktree *worktree)
3342 const struct got_error *err = NULL;
3343 char *path;
3344 struct got_pathlist_entry *new;
3345 int i;
3347 if (argc == 0) {
3348 path = strdup("");
3349 if (path == NULL)
3350 return got_error_from_errno("strdup");
3351 return got_pathlist_append(paths, path, NULL);
3354 for (i = 0; i < argc; i++) {
3355 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3356 if (err)
3357 break;
3358 err = got_pathlist_insert(&new, paths, path, NULL);
3359 if (err || new == NULL /* duplicate */) {
3360 free(path);
3361 if (err)
3362 break;
3366 return err;
3369 static const struct got_error *
3370 wrap_not_worktree_error(const struct got_error *orig_err,
3371 const char *cmdname, const char *path)
3373 const struct got_error *err;
3374 struct got_repository *repo;
3375 static char msg[512];
3376 int *pack_fds = NULL;
3378 err = got_repo_pack_fds_open(&pack_fds);
3379 if (err)
3380 return err;
3382 err = got_repo_open(&repo, path, NULL, pack_fds);
3383 if (err)
3384 return orig_err;
3386 snprintf(msg, sizeof(msg),
3387 "'got %s' needs a work tree in addition to a git repository\n"
3388 "Work trees can be checked out from this Git repository with "
3389 "'got checkout'.\n"
3390 "The got(1) manual page contains more information.", cmdname);
3391 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3392 got_repo_close(repo);
3393 if (pack_fds) {
3394 const struct got_error *pack_err =
3395 got_repo_pack_fds_close(pack_fds);
3396 if (err == NULL)
3397 err = pack_err;
3399 return err;
3402 static const struct got_error *
3403 cmd_update(int argc, char *argv[])
3405 const struct got_error *error = NULL;
3406 struct got_repository *repo = NULL;
3407 struct got_worktree *worktree = NULL;
3408 char *worktree_path = NULL;
3409 struct got_object_id *commit_id = NULL;
3410 char *commit_id_str = NULL;
3411 const char *branch_name = NULL;
3412 struct got_reference *head_ref = NULL;
3413 struct got_pathlist_head paths;
3414 struct got_pathlist_entry *pe;
3415 int ch, verbosity = 0;
3416 struct got_update_progress_arg upa;
3417 int *pack_fds = NULL;
3419 TAILQ_INIT(&paths);
3421 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3422 switch (ch) {
3423 case 'b':
3424 branch_name = optarg;
3425 break;
3426 case 'c':
3427 commit_id_str = strdup(optarg);
3428 if (commit_id_str == NULL)
3429 return got_error_from_errno("strdup");
3430 break;
3431 case 'q':
3432 verbosity = -1;
3433 break;
3434 default:
3435 usage_update();
3436 /* NOTREACHED */
3440 argc -= optind;
3441 argv += optind;
3443 #ifndef PROFILE
3444 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3445 "unveil", NULL) == -1)
3446 err(1, "pledge");
3447 #endif
3448 worktree_path = getcwd(NULL, 0);
3449 if (worktree_path == NULL) {
3450 error = got_error_from_errno("getcwd");
3451 goto done;
3454 error = got_repo_pack_fds_open(&pack_fds);
3455 if (error != NULL)
3456 goto done;
3458 error = got_worktree_open(&worktree, worktree_path);
3459 if (error) {
3460 if (error->code == GOT_ERR_NOT_WORKTREE)
3461 error = wrap_not_worktree_error(error, "update",
3462 worktree_path);
3463 goto done;
3466 error = check_rebase_or_histedit_in_progress(worktree);
3467 if (error)
3468 goto done;
3470 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3471 NULL, pack_fds);
3472 if (error != NULL)
3473 goto done;
3475 error = apply_unveil(got_repo_get_path(repo), 0,
3476 got_worktree_get_root_path(worktree));
3477 if (error)
3478 goto done;
3480 error = check_merge_in_progress(worktree, repo);
3481 if (error)
3482 goto done;
3484 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3485 if (error)
3486 goto done;
3488 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3489 got_worktree_get_head_ref_name(worktree), 0);
3490 if (error != NULL)
3491 goto done;
3492 if (commit_id_str == NULL) {
3493 error = got_ref_resolve(&commit_id, repo, head_ref);
3494 if (error != NULL)
3495 goto done;
3496 error = got_object_id_str(&commit_id_str, commit_id);
3497 if (error != NULL)
3498 goto done;
3499 } else {
3500 struct got_reflist_head refs;
3501 TAILQ_INIT(&refs);
3502 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3503 NULL);
3504 if (error)
3505 goto done;
3506 error = got_repo_match_object_id(&commit_id, NULL,
3507 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3508 got_ref_list_free(&refs);
3509 free(commit_id_str);
3510 commit_id_str = NULL;
3511 if (error)
3512 goto done;
3513 error = got_object_id_str(&commit_id_str, commit_id);
3514 if (error)
3515 goto done;
3518 if (branch_name) {
3519 struct got_object_id *head_commit_id;
3520 TAILQ_FOREACH(pe, &paths, entry) {
3521 if (pe->path_len == 0)
3522 continue;
3523 error = got_error_msg(GOT_ERR_BAD_PATH,
3524 "switching between branches requires that "
3525 "the entire work tree gets updated");
3526 goto done;
3528 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3529 if (error)
3530 goto done;
3531 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3532 repo);
3533 free(head_commit_id);
3534 if (error != NULL)
3535 goto done;
3536 error = check_same_branch(commit_id, head_ref, NULL, repo);
3537 if (error)
3538 goto done;
3539 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3540 if (error)
3541 goto done;
3542 } else {
3543 error = check_linear_ancestry(commit_id,
3544 got_worktree_get_base_commit_id(worktree), 0, repo);
3545 if (error != NULL) {
3546 if (error->code == GOT_ERR_ANCESTRY)
3547 error = got_error(GOT_ERR_BRANCH_MOVED);
3548 goto done;
3550 error = check_same_branch(commit_id, head_ref, NULL, repo);
3551 if (error)
3552 goto done;
3555 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3556 commit_id) != 0) {
3557 error = got_worktree_set_base_commit_id(worktree, repo,
3558 commit_id);
3559 if (error)
3560 goto done;
3563 memset(&upa, 0, sizeof(upa));
3564 upa.verbosity = verbosity;
3565 error = got_worktree_checkout_files(worktree, &paths, repo,
3566 update_progress, &upa, check_cancelled, NULL);
3567 if (error != NULL)
3568 goto done;
3570 if (upa.did_something) {
3571 printf("Updated to %s: %s\n",
3572 got_worktree_get_head_ref_name(worktree), commit_id_str);
3573 } else
3574 printf("Already up-to-date\n");
3576 print_update_progress_stats(&upa);
3577 done:
3578 if (pack_fds) {
3579 const struct got_error *pack_err =
3580 got_repo_pack_fds_close(pack_fds);
3581 if (error == NULL)
3582 error = pack_err;
3584 free(worktree_path);
3585 TAILQ_FOREACH(pe, &paths, entry)
3586 free((char *)pe->path);
3587 got_pathlist_free(&paths);
3588 free(commit_id);
3589 free(commit_id_str);
3590 return error;
3593 static const struct got_error *
3594 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3595 const char *path, int diff_context, int ignore_whitespace,
3596 int force_text_diff, struct got_repository *repo, FILE *outfile)
3598 const struct got_error *err = NULL;
3599 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3600 FILE *f1 = NULL, *f2 = NULL;
3601 int fd1 = -1, fd2 = -1;
3603 fd1 = got_opentempfd();
3604 if (fd1 == -1)
3605 return got_error_from_errno("got_opentempfd");
3606 fd2 = got_opentempfd();
3607 if (fd2 == -1) {
3608 err = got_error_from_errno("got_opentempfd");
3609 goto done;
3612 if (blob_id1) {
3613 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3614 fd1);
3615 if (err)
3616 goto done;
3619 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3620 if (err)
3621 goto done;
3623 f1 = got_opentemp();
3624 if (f1 == NULL) {
3625 err = got_error_from_errno("got_opentemp");
3626 goto done;
3628 f2 = got_opentemp();
3629 if (f2 == NULL) {
3630 err = got_error_from_errno("got_opentemp");
3631 goto done;
3634 while (path[0] == '/')
3635 path++;
3636 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3637 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3638 force_text_diff, outfile);
3639 done:
3640 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3641 err = got_error_from_errno("close");
3642 if (blob1)
3643 got_object_blob_close(blob1);
3644 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3645 err = got_error_from_errno("close");
3646 got_object_blob_close(blob2);
3647 if (f1 && fclose(f1) == EOF && err == NULL)
3648 err = got_error_from_errno("fclose");
3649 if (f2 && fclose(f2) == EOF && err == NULL)
3650 err = got_error_from_errno("fclose");
3651 return err;
3654 static const struct got_error *
3655 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3656 const char *path, int diff_context, int ignore_whitespace,
3657 int force_text_diff, struct got_repository *repo, FILE *outfile)
3659 const struct got_error *err = NULL;
3660 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3661 struct got_diff_blob_output_unidiff_arg arg;
3662 FILE *f1 = NULL, *f2 = NULL;
3663 int fd1 = -1, fd2 = -1;
3665 if (tree_id1) {
3666 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3667 if (err)
3668 goto done;
3669 fd1 = got_opentempfd();
3670 if (fd1 == -1) {
3671 err = got_error_from_errno("got_opentempfd");
3672 goto done;
3676 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3677 if (err)
3678 goto done;
3680 f1 = got_opentemp();
3681 if (f1 == NULL) {
3682 err = got_error_from_errno("got_opentemp");
3683 goto done;
3686 f2 = got_opentemp();
3687 if (f2 == NULL) {
3688 err = got_error_from_errno("got_opentemp");
3689 goto done;
3691 fd2 = got_opentempfd();
3692 if (fd2 == -1) {
3693 err = got_error_from_errno("got_opentempfd");
3694 goto done;
3696 arg.diff_context = diff_context;
3697 arg.ignore_whitespace = ignore_whitespace;
3698 arg.force_text_diff = force_text_diff;
3699 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3700 arg.outfile = outfile;
3701 arg.lines = NULL;
3702 arg.nlines = 0;
3703 while (path[0] == '/')
3704 path++;
3705 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3706 got_diff_blob_output_unidiff, &arg, 1);
3707 done:
3708 if (tree1)
3709 got_object_tree_close(tree1);
3710 if (tree2)
3711 got_object_tree_close(tree2);
3712 if (f1 && fclose(f1) == EOF && err == NULL)
3713 err = got_error_from_errno("fclose");
3714 if (f2 && fclose(f2) == EOF && err == NULL)
3715 err = got_error_from_errno("fclose");
3716 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3717 err = got_error_from_errno("close");
3718 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3719 err = got_error_from_errno("close");
3720 return err;
3723 static const struct got_error *
3724 get_changed_paths(struct got_pathlist_head *paths,
3725 struct got_commit_object *commit, struct got_repository *repo)
3727 const struct got_error *err = NULL;
3728 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3729 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3730 struct got_object_qid *qid;
3732 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3733 if (qid != NULL) {
3734 struct got_commit_object *pcommit;
3735 err = got_object_open_as_commit(&pcommit, repo,
3736 &qid->id);
3737 if (err)
3738 return err;
3740 tree_id1 = got_object_id_dup(
3741 got_object_commit_get_tree_id(pcommit));
3742 if (tree_id1 == NULL) {
3743 got_object_commit_close(pcommit);
3744 return got_error_from_errno("got_object_id_dup");
3746 got_object_commit_close(pcommit);
3750 if (tree_id1) {
3751 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3752 if (err)
3753 goto done;
3756 tree_id2 = got_object_commit_get_tree_id(commit);
3757 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3758 if (err)
3759 goto done;
3761 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3762 got_diff_tree_collect_changed_paths, paths, 0);
3763 done:
3764 if (tree1)
3765 got_object_tree_close(tree1);
3766 if (tree2)
3767 got_object_tree_close(tree2);
3768 free(tree_id1);
3769 return err;
3772 static const struct got_error *
3773 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3774 const char *path, int diff_context, struct got_repository *repo,
3775 FILE *outfile)
3777 const struct got_error *err = NULL;
3778 struct got_commit_object *pcommit = NULL;
3779 char *id_str1 = NULL, *id_str2 = NULL;
3780 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3781 struct got_object_qid *qid;
3783 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3784 if (qid != NULL) {
3785 err = got_object_open_as_commit(&pcommit, repo,
3786 &qid->id);
3787 if (err)
3788 return err;
3789 err = got_object_id_str(&id_str1, &qid->id);
3790 if (err)
3791 goto done;
3794 err = got_object_id_str(&id_str2, id);
3795 if (err)
3796 goto done;
3798 if (path && path[0] != '\0') {
3799 int obj_type;
3800 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3801 if (err)
3802 goto done;
3803 if (pcommit) {
3804 err = got_object_id_by_path(&obj_id1, repo,
3805 pcommit, path);
3806 if (err) {
3807 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3808 free(obj_id2);
3809 goto done;
3813 err = got_object_get_type(&obj_type, repo, obj_id2);
3814 if (err) {
3815 free(obj_id2);
3816 goto done;
3818 fprintf(outfile,
3819 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3820 fprintf(outfile, "commit - %s\n",
3821 id_str1 ? id_str1 : "/dev/null");
3822 fprintf(outfile, "commit + %s\n", id_str2);
3823 switch (obj_type) {
3824 case GOT_OBJ_TYPE_BLOB:
3825 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3826 0, 0, repo, outfile);
3827 break;
3828 case GOT_OBJ_TYPE_TREE:
3829 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3830 0, 0, repo, outfile);
3831 break;
3832 default:
3833 err = got_error(GOT_ERR_OBJ_TYPE);
3834 break;
3836 free(obj_id1);
3837 free(obj_id2);
3838 } else {
3839 obj_id2 = got_object_commit_get_tree_id(commit);
3840 if (pcommit)
3841 obj_id1 = got_object_commit_get_tree_id(pcommit);
3842 fprintf(outfile,
3843 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3844 fprintf(outfile, "commit - %s\n",
3845 id_str1 ? id_str1 : "/dev/null");
3846 fprintf(outfile, "commit + %s\n", id_str2);
3847 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3848 repo, outfile);
3850 done:
3851 free(id_str1);
3852 free(id_str2);
3853 if (pcommit)
3854 got_object_commit_close(pcommit);
3855 return err;
3858 static char *
3859 get_datestr(time_t *time, char *datebuf)
3861 struct tm mytm, *tm;
3862 char *p, *s;
3864 tm = gmtime_r(time, &mytm);
3865 if (tm == NULL)
3866 return NULL;
3867 s = asctime_r(tm, datebuf);
3868 if (s == NULL)
3869 return NULL;
3870 p = strchr(s, '\n');
3871 if (p)
3872 *p = '\0';
3873 return s;
3876 static const struct got_error *
3877 match_commit(int *have_match, struct got_object_id *id,
3878 struct got_commit_object *commit, regex_t *regex)
3880 const struct got_error *err = NULL;
3881 regmatch_t regmatch;
3882 char *id_str = NULL, *logmsg = NULL;
3884 *have_match = 0;
3886 err = got_object_id_str(&id_str, id);
3887 if (err)
3888 return err;
3890 err = got_object_commit_get_logmsg(&logmsg, commit);
3891 if (err)
3892 goto done;
3894 if (regexec(regex, got_object_commit_get_author(commit), 1,
3895 &regmatch, 0) == 0 ||
3896 regexec(regex, got_object_commit_get_committer(commit), 1,
3897 &regmatch, 0) == 0 ||
3898 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3899 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3900 *have_match = 1;
3901 done:
3902 free(id_str);
3903 free(logmsg);
3904 return err;
3907 static void
3908 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3909 regex_t *regex)
3911 regmatch_t regmatch;
3912 struct got_pathlist_entry *pe;
3914 *have_match = 0;
3916 TAILQ_FOREACH(pe, changed_paths, entry) {
3917 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3918 *have_match = 1;
3919 break;
3924 static const struct got_error *
3925 match_patch(int *have_match, struct got_commit_object *commit,
3926 struct got_object_id *id, const char *path, int diff_context,
3927 struct got_repository *repo, regex_t *regex, FILE *f)
3929 const struct got_error *err = NULL;
3930 char *line = NULL;
3931 size_t linesize = 0;
3932 regmatch_t regmatch;
3934 *have_match = 0;
3936 err = got_opentemp_truncate(f);
3937 if (err)
3938 return err;
3940 err = print_patch(commit, id, path, diff_context, repo, f);
3941 if (err)
3942 goto done;
3944 if (fseeko(f, 0L, SEEK_SET) == -1) {
3945 err = got_error_from_errno("fseeko");
3946 goto done;
3949 while (getline(&line, &linesize, f) != -1) {
3950 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3951 *have_match = 1;
3952 break;
3955 done:
3956 free(line);
3957 return err;
3960 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3962 static const struct got_error*
3963 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3964 struct got_object_id *id, struct got_repository *repo,
3965 int local_only)
3967 static const struct got_error *err = NULL;
3968 struct got_reflist_entry *re;
3969 char *s;
3970 const char *name;
3972 *refs_str = NULL;
3974 TAILQ_FOREACH(re, refs, entry) {
3975 struct got_tag_object *tag = NULL;
3976 struct got_object_id *ref_id;
3977 int cmp;
3979 name = got_ref_get_name(re->ref);
3980 if (strcmp(name, GOT_REF_HEAD) == 0)
3981 continue;
3982 if (strncmp(name, "refs/", 5) == 0)
3983 name += 5;
3984 if (strncmp(name, "got/", 4) == 0)
3985 continue;
3986 if (strncmp(name, "heads/", 6) == 0)
3987 name += 6;
3988 if (strncmp(name, "remotes/", 8) == 0) {
3989 if (local_only)
3990 continue;
3991 name += 8;
3992 s = strstr(name, "/" GOT_REF_HEAD);
3993 if (s != NULL && s[strlen(s)] == '\0')
3994 continue;
3996 err = got_ref_resolve(&ref_id, repo, re->ref);
3997 if (err)
3998 break;
3999 if (strncmp(name, "tags/", 5) == 0) {
4000 err = got_object_open_as_tag(&tag, repo, ref_id);
4001 if (err) {
4002 if (err->code != GOT_ERR_OBJ_TYPE) {
4003 free(ref_id);
4004 break;
4006 /* Ref points at something other than a tag. */
4007 err = NULL;
4008 tag = NULL;
4011 cmp = got_object_id_cmp(tag ?
4012 got_object_tag_get_object_id(tag) : ref_id, id);
4013 free(ref_id);
4014 if (tag)
4015 got_object_tag_close(tag);
4016 if (cmp != 0)
4017 continue;
4018 s = *refs_str;
4019 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4020 s ? ", " : "", name) == -1) {
4021 err = got_error_from_errno("asprintf");
4022 free(s);
4023 *refs_str = NULL;
4024 break;
4026 free(s);
4029 return err;
4032 static const struct got_error *
4033 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4034 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4036 const struct got_error *err = NULL;
4037 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4038 char *comma, *s, *nl;
4039 struct got_reflist_head *refs;
4040 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4041 struct tm tm;
4042 time_t committer_time;
4044 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4045 if (refs) {
4046 err = build_refs_str(&ref_str, refs, id, repo, 1);
4047 if (err)
4048 return err;
4050 /* Display the first matching ref only. */
4051 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4052 *comma = '\0';
4055 if (ref_str == NULL) {
4056 err = got_object_id_str(&id_str, id);
4057 if (err)
4058 return err;
4061 committer_time = got_object_commit_get_committer_time(commit);
4062 if (gmtime_r(&committer_time, &tm) == NULL) {
4063 err = got_error_from_errno("gmtime_r");
4064 goto done;
4066 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4067 err = got_error(GOT_ERR_NO_SPACE);
4068 goto done;
4071 err = got_object_commit_get_logmsg(&logmsg0, commit);
4072 if (err)
4073 goto done;
4075 s = logmsg0;
4076 while (isspace((unsigned char)s[0]))
4077 s++;
4079 nl = strchr(s, '\n');
4080 if (nl) {
4081 *nl = '\0';
4084 if (ref_str)
4085 printf("%s%-7s %s\n", datebuf, ref_str, s);
4086 else
4087 printf("%s%.7s %s\n", datebuf, id_str, s);
4089 if (fflush(stdout) != 0 && err == NULL)
4090 err = got_error_from_errno("fflush");
4091 done:
4092 free(id_str);
4093 free(ref_str);
4094 free(logmsg0);
4095 return err;
4098 static const struct got_error *
4099 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4100 struct got_repository *repo, const char *path,
4101 struct got_pathlist_head *changed_paths, int show_patch,
4102 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4103 const char *custom_refs_str)
4105 const struct got_error *err = NULL;
4106 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4107 char datebuf[26];
4108 time_t committer_time;
4109 const char *author, *committer;
4110 char *refs_str = NULL;
4112 err = got_object_id_str(&id_str, id);
4113 if (err)
4114 return err;
4116 if (custom_refs_str == NULL) {
4117 struct got_reflist_head *refs;
4118 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4119 if (refs) {
4120 err = build_refs_str(&refs_str, refs, id, repo, 0);
4121 if (err)
4122 goto done;
4126 printf(GOT_COMMIT_SEP_STR);
4127 if (custom_refs_str)
4128 printf("commit %s (%s)\n", id_str, custom_refs_str);
4129 else
4130 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4131 refs_str ? refs_str : "", refs_str ? ")" : "");
4132 free(id_str);
4133 id_str = NULL;
4134 free(refs_str);
4135 refs_str = NULL;
4136 printf("from: %s\n", got_object_commit_get_author(commit));
4137 committer_time = got_object_commit_get_committer_time(commit);
4138 datestr = get_datestr(&committer_time, datebuf);
4139 if (datestr)
4140 printf("date: %s UTC\n", datestr);
4141 author = got_object_commit_get_author(commit);
4142 committer = got_object_commit_get_committer(commit);
4143 if (strcmp(author, committer) != 0)
4144 printf("via: %s\n", committer);
4145 if (got_object_commit_get_nparents(commit) > 1) {
4146 const struct got_object_id_queue *parent_ids;
4147 struct got_object_qid *qid;
4148 int n = 1;
4149 parent_ids = got_object_commit_get_parent_ids(commit);
4150 STAILQ_FOREACH(qid, parent_ids, entry) {
4151 err = got_object_id_str(&id_str, &qid->id);
4152 if (err)
4153 goto done;
4154 printf("parent %d: %s\n", n++, id_str);
4155 free(id_str);
4156 id_str = NULL;
4160 err = got_object_commit_get_logmsg(&logmsg0, commit);
4161 if (err)
4162 goto done;
4164 logmsg = logmsg0;
4165 do {
4166 line = strsep(&logmsg, "\n");
4167 if (line)
4168 printf(" %s\n", line);
4169 } while (line);
4170 free(logmsg0);
4172 if (changed_paths) {
4173 struct got_pathlist_entry *pe;
4174 TAILQ_FOREACH(pe, changed_paths, entry) {
4175 struct got_diff_changed_path *cp = pe->data;
4176 printf(" %c %s\n", cp->status, pe->path);
4178 printf("\n");
4180 if (show_patch) {
4181 err = print_patch(commit, id, path, diff_context, repo, stdout);
4182 if (err == 0)
4183 printf("\n");
4186 if (fflush(stdout) != 0 && err == NULL)
4187 err = got_error_from_errno("fflush");
4188 done:
4189 free(id_str);
4190 free(refs_str);
4191 return err;
4194 static const struct got_error *
4195 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4196 struct got_repository *repo, const char *path, int show_changed_paths,
4197 int show_patch, const char *search_pattern, int diff_context, int limit,
4198 int log_branches, int reverse_display_order,
4199 struct got_reflist_object_id_map *refs_idmap, int one_line,
4200 FILE *tmpfile)
4202 const struct got_error *err;
4203 struct got_commit_graph *graph;
4204 regex_t regex;
4205 int have_match;
4206 struct got_object_id_queue reversed_commits;
4207 struct got_object_qid *qid;
4208 struct got_commit_object *commit;
4209 struct got_pathlist_head changed_paths;
4210 struct got_pathlist_entry *pe;
4212 STAILQ_INIT(&reversed_commits);
4213 TAILQ_INIT(&changed_paths);
4215 if (search_pattern && regcomp(&regex, search_pattern,
4216 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4217 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4219 err = got_commit_graph_open(&graph, path, !log_branches);
4220 if (err)
4221 return err;
4222 err = got_commit_graph_iter_start(graph, root_id, repo,
4223 check_cancelled, NULL);
4224 if (err)
4225 goto done;
4226 for (;;) {
4227 struct got_object_id id;
4229 if (sigint_received || sigpipe_received)
4230 break;
4232 err = got_commit_graph_iter_next(&id, graph, repo,
4233 check_cancelled, NULL);
4234 if (err) {
4235 if (err->code == GOT_ERR_ITER_COMPLETED)
4236 err = NULL;
4237 break;
4240 err = got_object_open_as_commit(&commit, repo, &id);
4241 if (err)
4242 break;
4244 if (show_changed_paths && !reverse_display_order) {
4245 err = get_changed_paths(&changed_paths, commit, repo);
4246 if (err)
4247 break;
4250 if (search_pattern) {
4251 err = match_commit(&have_match, &id, commit, &regex);
4252 if (err) {
4253 got_object_commit_close(commit);
4254 break;
4256 if (have_match == 0 && show_changed_paths)
4257 match_changed_paths(&have_match,
4258 &changed_paths, &regex);
4259 if (have_match == 0 && show_patch) {
4260 err = match_patch(&have_match, commit, &id,
4261 path, diff_context, repo, &regex,
4262 tmpfile);
4263 if (err)
4264 break;
4266 if (have_match == 0) {
4267 got_object_commit_close(commit);
4268 TAILQ_FOREACH(pe, &changed_paths, entry) {
4269 free((char *)pe->path);
4270 free(pe->data);
4272 got_pathlist_free(&changed_paths);
4273 continue;
4277 if (reverse_display_order) {
4278 err = got_object_qid_alloc(&qid, &id);
4279 if (err)
4280 break;
4281 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4282 got_object_commit_close(commit);
4283 } else {
4284 if (one_line)
4285 err = print_commit_oneline(commit, &id,
4286 repo, refs_idmap);
4287 else
4288 err = print_commit(commit, &id, repo, path,
4289 show_changed_paths ? &changed_paths : NULL,
4290 show_patch, diff_context, refs_idmap, NULL);
4291 got_object_commit_close(commit);
4292 if (err)
4293 break;
4295 if ((limit && --limit == 0) ||
4296 (end_id && got_object_id_cmp(&id, end_id) == 0))
4297 break;
4299 TAILQ_FOREACH(pe, &changed_paths, entry) {
4300 free((char *)pe->path);
4301 free(pe->data);
4303 got_pathlist_free(&changed_paths);
4305 if (reverse_display_order) {
4306 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4307 err = got_object_open_as_commit(&commit, repo,
4308 &qid->id);
4309 if (err)
4310 break;
4311 if (show_changed_paths) {
4312 err = get_changed_paths(&changed_paths,
4313 commit, repo);
4314 if (err)
4315 break;
4317 if (one_line)
4318 err = print_commit_oneline(commit, &qid->id,
4319 repo, refs_idmap);
4320 else
4321 err = print_commit(commit, &qid->id, repo, path,
4322 show_changed_paths ? &changed_paths : NULL,
4323 show_patch, diff_context, refs_idmap, NULL);
4324 got_object_commit_close(commit);
4325 if (err)
4326 break;
4327 TAILQ_FOREACH(pe, &changed_paths, entry) {
4328 free((char *)pe->path);
4329 free(pe->data);
4331 got_pathlist_free(&changed_paths);
4334 done:
4335 while (!STAILQ_EMPTY(&reversed_commits)) {
4336 qid = STAILQ_FIRST(&reversed_commits);
4337 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4338 got_object_qid_free(qid);
4340 TAILQ_FOREACH(pe, &changed_paths, entry) {
4341 free((char *)pe->path);
4342 free(pe->data);
4344 got_pathlist_free(&changed_paths);
4345 if (search_pattern)
4346 regfree(&regex);
4347 got_commit_graph_close(graph);
4348 return err;
4351 __dead static void
4352 usage_log(void)
4354 fprintf(stderr, "usage: %s log [-bPpRs] [-C number] [-c commit] [-l N] "
4355 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4356 getprogname());
4357 exit(1);
4360 static int
4361 get_default_log_limit(void)
4363 const char *got_default_log_limit;
4364 long long n;
4365 const char *errstr;
4367 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4368 if (got_default_log_limit == NULL)
4369 return 0;
4370 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4371 if (errstr != NULL)
4372 return 0;
4373 return n;
4376 static const struct got_error *
4377 cmd_log(int argc, char *argv[])
4379 const struct got_error *error;
4380 struct got_repository *repo = NULL;
4381 struct got_worktree *worktree = NULL;
4382 struct got_object_id *start_id = NULL, *end_id = NULL;
4383 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4384 const char *start_commit = NULL, *end_commit = NULL;
4385 const char *search_pattern = NULL;
4386 int diff_context = -1, ch;
4387 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4388 int reverse_display_order = 0, one_line = 0;
4389 const char *errstr;
4390 struct got_reflist_head refs;
4391 struct got_reflist_object_id_map *refs_idmap = NULL;
4392 FILE *tmpfile = NULL;
4393 int *pack_fds = NULL;
4395 TAILQ_INIT(&refs);
4397 #ifndef PROFILE
4398 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4399 NULL)
4400 == -1)
4401 err(1, "pledge");
4402 #endif
4404 limit = get_default_log_limit();
4406 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4407 switch (ch) {
4408 case 'p':
4409 show_patch = 1;
4410 break;
4411 case 'P':
4412 show_changed_paths = 1;
4413 break;
4414 case 'c':
4415 start_commit = optarg;
4416 break;
4417 case 'C':
4418 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4419 &errstr);
4420 if (errstr != NULL)
4421 errx(1, "number of context lines is %s: %s",
4422 errstr, optarg);
4423 break;
4424 case 'l':
4425 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4426 if (errstr != NULL)
4427 errx(1, "number of commits is %s: %s",
4428 errstr, optarg);
4429 break;
4430 case 'b':
4431 log_branches = 1;
4432 break;
4433 case 'r':
4434 repo_path = realpath(optarg, NULL);
4435 if (repo_path == NULL)
4436 return got_error_from_errno2("realpath",
4437 optarg);
4438 got_path_strip_trailing_slashes(repo_path);
4439 break;
4440 case 'R':
4441 reverse_display_order = 1;
4442 break;
4443 case 's':
4444 one_line = 1;
4445 break;
4446 case 'S':
4447 search_pattern = optarg;
4448 break;
4449 case 'x':
4450 end_commit = optarg;
4451 break;
4452 default:
4453 usage_log();
4454 /* NOTREACHED */
4458 argc -= optind;
4459 argv += optind;
4461 if (diff_context == -1)
4462 diff_context = 3;
4463 else if (!show_patch)
4464 errx(1, "-C requires -p");
4466 if (one_line && (show_patch || show_changed_paths))
4467 errx(1, "cannot use -s with -p or -P");
4469 cwd = getcwd(NULL, 0);
4470 if (cwd == NULL) {
4471 error = got_error_from_errno("getcwd");
4472 goto done;
4475 error = got_repo_pack_fds_open(&pack_fds);
4476 if (error != NULL)
4477 goto done;
4479 if (repo_path == NULL) {
4480 error = got_worktree_open(&worktree, cwd);
4481 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4482 goto done;
4483 error = NULL;
4486 if (argc == 1) {
4487 if (worktree) {
4488 error = got_worktree_resolve_path(&path, worktree,
4489 argv[0]);
4490 if (error)
4491 goto done;
4492 } else {
4493 path = strdup(argv[0]);
4494 if (path == NULL) {
4495 error = got_error_from_errno("strdup");
4496 goto done;
4499 } else if (argc != 0)
4500 usage_log();
4502 if (repo_path == NULL) {
4503 repo_path = worktree ?
4504 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4506 if (repo_path == NULL) {
4507 error = got_error_from_errno("strdup");
4508 goto done;
4511 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4512 if (error != NULL)
4513 goto done;
4515 error = apply_unveil(got_repo_get_path(repo), 1,
4516 worktree ? got_worktree_get_root_path(worktree) : NULL);
4517 if (error)
4518 goto done;
4520 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4521 if (error)
4522 goto done;
4524 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4525 if (error)
4526 goto done;
4528 if (start_commit == NULL) {
4529 struct got_reference *head_ref;
4530 struct got_commit_object *commit = NULL;
4531 error = got_ref_open(&head_ref, repo,
4532 worktree ? got_worktree_get_head_ref_name(worktree)
4533 : GOT_REF_HEAD, 0);
4534 if (error != NULL)
4535 goto done;
4536 error = got_ref_resolve(&start_id, repo, head_ref);
4537 got_ref_close(head_ref);
4538 if (error != NULL)
4539 goto done;
4540 error = got_object_open_as_commit(&commit, repo,
4541 start_id);
4542 if (error != NULL)
4543 goto done;
4544 got_object_commit_close(commit);
4545 } else {
4546 error = got_repo_match_object_id(&start_id, NULL,
4547 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4548 if (error != NULL)
4549 goto done;
4551 if (end_commit != NULL) {
4552 error = got_repo_match_object_id(&end_id, NULL,
4553 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4554 if (error != NULL)
4555 goto done;
4558 if (worktree) {
4560 * If a path was specified on the command line it was resolved
4561 * to a path in the work tree above. Prepend the work tree's
4562 * path prefix to obtain the corresponding in-repository path.
4564 if (path) {
4565 const char *prefix;
4566 prefix = got_worktree_get_path_prefix(worktree);
4567 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4568 (path[0] != '\0') ? "/" : "", path) == -1) {
4569 error = got_error_from_errno("asprintf");
4570 goto done;
4573 } else
4574 error = got_repo_map_path(&in_repo_path, repo,
4575 path ? path : "");
4576 if (error != NULL)
4577 goto done;
4578 if (in_repo_path) {
4579 free(path);
4580 path = in_repo_path;
4583 if (worktree) {
4584 /* Release work tree lock. */
4585 got_worktree_close(worktree);
4586 worktree = NULL;
4589 if (search_pattern && show_patch) {
4590 tmpfile = got_opentemp();
4591 if (tmpfile == NULL) {
4592 error = got_error_from_errno("got_opentemp");
4593 goto done;
4597 error = print_commits(start_id, end_id, repo, path ? path : "",
4598 show_changed_paths, show_patch, search_pattern, diff_context,
4599 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4600 tmpfile);
4601 done:
4602 free(path);
4603 free(repo_path);
4604 free(cwd);
4605 if (worktree)
4606 got_worktree_close(worktree);
4607 if (repo) {
4608 const struct got_error *close_err = got_repo_close(repo);
4609 if (error == NULL)
4610 error = close_err;
4612 if (pack_fds) {
4613 const struct got_error *pack_err =
4614 got_repo_pack_fds_close(pack_fds);
4615 if (error == NULL)
4616 error = pack_err;
4618 if (refs_idmap)
4619 got_reflist_object_id_map_free(refs_idmap);
4620 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4621 error = got_error_from_errno("fclose");
4622 got_ref_list_free(&refs);
4623 return error;
4626 __dead static void
4627 usage_diff(void)
4629 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4630 "[-r repository-path] [object1 object2 | path ...]\n",
4631 getprogname());
4632 exit(1);
4635 struct print_diff_arg {
4636 struct got_repository *repo;
4637 struct got_worktree *worktree;
4638 int diff_context;
4639 const char *id_str;
4640 int header_shown;
4641 int diff_staged;
4642 enum got_diff_algorithm diff_algo;
4643 int ignore_whitespace;
4644 int force_text_diff;
4645 FILE *f1;
4646 FILE *f2;
4650 * Create a file which contains the target path of a symlink so we can feed
4651 * it as content to the diff engine.
4653 static const struct got_error *
4654 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4655 const char *abspath)
4657 const struct got_error *err = NULL;
4658 char target_path[PATH_MAX];
4659 ssize_t target_len, outlen;
4661 *fd = -1;
4663 if (dirfd != -1) {
4664 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4665 if (target_len == -1)
4666 return got_error_from_errno2("readlinkat", abspath);
4667 } else {
4668 target_len = readlink(abspath, target_path, PATH_MAX);
4669 if (target_len == -1)
4670 return got_error_from_errno2("readlink", abspath);
4673 *fd = got_opentempfd();
4674 if (*fd == -1)
4675 return got_error_from_errno("got_opentempfd");
4677 outlen = write(*fd, target_path, target_len);
4678 if (outlen == -1) {
4679 err = got_error_from_errno("got_opentempfd");
4680 goto done;
4683 if (lseek(*fd, 0, SEEK_SET) == -1) {
4684 err = got_error_from_errno2("lseek", abspath);
4685 goto done;
4687 done:
4688 if (err) {
4689 close(*fd);
4690 *fd = -1;
4692 return err;
4695 static const struct got_error *
4696 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4697 const char *path, struct got_object_id *blob_id,
4698 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4699 int dirfd, const char *de_name)
4701 struct print_diff_arg *a = arg;
4702 const struct got_error *err = NULL;
4703 struct got_blob_object *blob1 = NULL;
4704 int fd = -1, fd1 = -1, fd2 = -1;
4705 FILE *f2 = NULL;
4706 char *abspath = NULL, *label1 = NULL;
4707 struct stat sb;
4708 off_t size1 = 0;
4709 int f2_exists = 1;
4711 if (a->diff_staged) {
4712 if (staged_status != GOT_STATUS_MODIFY &&
4713 staged_status != GOT_STATUS_ADD &&
4714 staged_status != GOT_STATUS_DELETE)
4715 return NULL;
4716 } else {
4717 if (staged_status == GOT_STATUS_DELETE)
4718 return NULL;
4719 if (status == GOT_STATUS_NONEXISTENT)
4720 return got_error_set_errno(ENOENT, path);
4721 if (status != GOT_STATUS_MODIFY &&
4722 status != GOT_STATUS_ADD &&
4723 status != GOT_STATUS_DELETE &&
4724 status != GOT_STATUS_CONFLICT)
4725 return NULL;
4728 err = got_opentemp_truncate(a->f1);
4729 if (err)
4730 return got_error_from_errno("got_opentemp_truncate");
4731 err = got_opentemp_truncate(a->f2);
4732 if (err)
4733 return got_error_from_errno("got_opentemp_truncate");
4735 if (!a->header_shown) {
4736 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4737 got_worktree_get_root_path(a->worktree));
4738 printf("commit - %s\n", a->id_str);
4739 printf("path + %s%s\n",
4740 got_worktree_get_root_path(a->worktree),
4741 a->diff_staged ? " (staged changes)" : "");
4742 a->header_shown = 1;
4745 if (a->diff_staged) {
4746 const char *label1 = NULL, *label2 = NULL;
4747 switch (staged_status) {
4748 case GOT_STATUS_MODIFY:
4749 label1 = path;
4750 label2 = path;
4751 break;
4752 case GOT_STATUS_ADD:
4753 label2 = path;
4754 break;
4755 case GOT_STATUS_DELETE:
4756 label1 = path;
4757 break;
4758 default:
4759 return got_error(GOT_ERR_FILE_STATUS);
4761 fd1 = got_opentempfd();
4762 if (fd1 == -1) {
4763 err = got_error_from_errno("got_opentempfd");
4764 goto done;
4766 fd2 = got_opentempfd();
4767 if (fd2 == -1) {
4768 err = got_error_from_errno("got_opentempfd");
4769 goto done;
4771 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4772 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4773 a->diff_algo, a->diff_context, a->ignore_whitespace,
4774 a->force_text_diff, a->repo, stdout);
4775 goto done;
4778 fd1 = got_opentempfd();
4779 if (fd1 == -1) {
4780 err = got_error_from_errno("got_opentempfd");
4781 goto done;
4784 if (staged_status == GOT_STATUS_ADD ||
4785 staged_status == GOT_STATUS_MODIFY) {
4786 char *id_str;
4787 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4788 8192, fd1);
4789 if (err)
4790 goto done;
4791 err = got_object_id_str(&id_str, staged_blob_id);
4792 if (err)
4793 goto done;
4794 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4795 err = got_error_from_errno("asprintf");
4796 free(id_str);
4797 goto done;
4799 free(id_str);
4800 } else if (status != GOT_STATUS_ADD) {
4801 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4802 fd1);
4803 if (err)
4804 goto done;
4807 if (status != GOT_STATUS_DELETE) {
4808 if (asprintf(&abspath, "%s/%s",
4809 got_worktree_get_root_path(a->worktree), path) == -1) {
4810 err = got_error_from_errno("asprintf");
4811 goto done;
4814 if (dirfd != -1) {
4815 fd = openat(dirfd, de_name,
4816 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4817 if (fd == -1) {
4818 if (!got_err_open_nofollow_on_symlink()) {
4819 err = got_error_from_errno2("openat",
4820 abspath);
4821 goto done;
4823 err = get_symlink_target_file(&fd, dirfd,
4824 de_name, abspath);
4825 if (err)
4826 goto done;
4828 } else {
4829 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4830 if (fd == -1) {
4831 if (!got_err_open_nofollow_on_symlink()) {
4832 err = got_error_from_errno2("open",
4833 abspath);
4834 goto done;
4836 err = get_symlink_target_file(&fd, dirfd,
4837 de_name, abspath);
4838 if (err)
4839 goto done;
4842 if (fstat(fd, &sb) == -1) {
4843 err = got_error_from_errno2("fstat", abspath);
4844 goto done;
4846 f2 = fdopen(fd, "r");
4847 if (f2 == NULL) {
4848 err = got_error_from_errno2("fdopen", abspath);
4849 goto done;
4851 fd = -1;
4852 } else {
4853 sb.st_size = 0;
4854 f2_exists = 0;
4857 if (blob1) {
4858 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4859 a->f1, blob1);
4860 if (err)
4861 goto done;
4864 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4865 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4866 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4867 done:
4868 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4869 err = got_error_from_errno("close");
4870 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4871 err = got_error_from_errno("close");
4872 if (blob1)
4873 got_object_blob_close(blob1);
4874 if (fd != -1 && close(fd) == -1 && err == NULL)
4875 err = got_error_from_errno("close");
4876 if (f2 && fclose(f2) == EOF && err == NULL)
4877 err = got_error_from_errno("fclose");
4878 free(abspath);
4879 return err;
4882 static const struct got_error *
4883 cmd_diff(int argc, char *argv[])
4885 const struct got_error *error;
4886 struct got_repository *repo = NULL;
4887 struct got_worktree *worktree = NULL;
4888 char *cwd = NULL, *repo_path = NULL;
4889 const char *commit_args[2] = { NULL, NULL };
4890 int ncommit_args = 0;
4891 struct got_object_id *ids[2] = { NULL, NULL };
4892 char *labels[2] = { NULL, NULL };
4893 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4894 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4895 int force_text_diff = 0, force_path = 0, rflag = 0;
4896 const char *errstr;
4897 struct got_reflist_head refs;
4898 struct got_pathlist_head paths;
4899 struct got_pathlist_entry *pe;
4900 FILE *f1 = NULL, *f2 = NULL;
4901 int fd1 = -1, fd2 = -1;
4902 int *pack_fds = NULL;
4904 TAILQ_INIT(&refs);
4905 TAILQ_INIT(&paths);
4907 #ifndef PROFILE
4908 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4909 NULL) == -1)
4910 err(1, "pledge");
4911 #endif
4913 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4914 switch (ch) {
4915 case 'a':
4916 force_text_diff = 1;
4917 break;
4918 case 'c':
4919 if (ncommit_args >= 2)
4920 errx(1, "too many -c options used");
4921 commit_args[ncommit_args++] = optarg;
4922 break;
4923 case 'C':
4924 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4925 &errstr);
4926 if (errstr != NULL)
4927 errx(1, "number of context lines is %s: %s",
4928 errstr, optarg);
4929 break;
4930 case 'r':
4931 repo_path = realpath(optarg, NULL);
4932 if (repo_path == NULL)
4933 return got_error_from_errno2("realpath",
4934 optarg);
4935 got_path_strip_trailing_slashes(repo_path);
4936 rflag = 1;
4937 break;
4938 case 's':
4939 diff_staged = 1;
4940 break;
4941 case 'w':
4942 ignore_whitespace = 1;
4943 break;
4944 case 'P':
4945 force_path = 1;
4946 break;
4947 default:
4948 usage_diff();
4949 /* NOTREACHED */
4953 argc -= optind;
4954 argv += optind;
4956 cwd = getcwd(NULL, 0);
4957 if (cwd == NULL) {
4958 error = got_error_from_errno("getcwd");
4959 goto done;
4962 error = got_repo_pack_fds_open(&pack_fds);
4963 if (error != NULL)
4964 goto done;
4966 if (repo_path == NULL) {
4967 error = got_worktree_open(&worktree, cwd);
4968 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4969 goto done;
4970 else
4971 error = NULL;
4972 if (worktree) {
4973 repo_path =
4974 strdup(got_worktree_get_repo_path(worktree));
4975 if (repo_path == NULL) {
4976 error = got_error_from_errno("strdup");
4977 goto done;
4979 } else {
4980 repo_path = strdup(cwd);
4981 if (repo_path == NULL) {
4982 error = got_error_from_errno("strdup");
4983 goto done;
4988 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4989 free(repo_path);
4990 if (error != NULL)
4991 goto done;
4993 if (rflag || worktree == NULL || ncommit_args > 0) {
4994 if (force_path) {
4995 error = got_error_msg(GOT_ERR_NOT_IMPL,
4996 "-P option can only be used when diffing "
4997 "a work tree");
4998 goto done;
5000 if (diff_staged) {
5001 error = got_error_msg(GOT_ERR_NOT_IMPL,
5002 "-s option can only be used when diffing "
5003 "a work tree");
5004 goto done;
5008 error = apply_unveil(got_repo_get_path(repo), 1,
5009 worktree ? got_worktree_get_root_path(worktree) : NULL);
5010 if (error)
5011 goto done;
5013 if ((!force_path && argc == 2) || ncommit_args > 0) {
5014 int obj_type = (ncommit_args > 0 ?
5015 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5016 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5017 NULL);
5018 if (error)
5019 goto done;
5020 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5021 const char *arg;
5022 if (ncommit_args > 0)
5023 arg = commit_args[i];
5024 else
5025 arg = argv[i];
5026 error = got_repo_match_object_id(&ids[i], &labels[i],
5027 arg, obj_type, &refs, repo);
5028 if (error) {
5029 if (error->code != GOT_ERR_NOT_REF &&
5030 error->code != GOT_ERR_NO_OBJ)
5031 goto done;
5032 if (ncommit_args > 0)
5033 goto done;
5034 error = NULL;
5035 break;
5040 f1 = got_opentemp();
5041 if (f1 == NULL) {
5042 error = got_error_from_errno("got_opentemp");
5043 goto done;
5046 f2 = got_opentemp();
5047 if (f2 == NULL) {
5048 error = got_error_from_errno("got_opentemp");
5049 goto done;
5052 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5053 struct print_diff_arg arg;
5054 char *id_str;
5056 if (worktree == NULL) {
5057 if (argc == 2 && ids[0] == NULL) {
5058 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5059 goto done;
5060 } else if (argc == 2 && ids[1] == NULL) {
5061 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5062 goto done;
5063 } else if (argc > 0) {
5064 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5065 "%s", "specified paths cannot be resolved");
5066 goto done;
5067 } else {
5068 error = got_error(GOT_ERR_NOT_WORKTREE);
5069 goto done;
5073 error = get_worktree_paths_from_argv(&paths, argc, argv,
5074 worktree);
5075 if (error)
5076 goto done;
5078 error = got_object_id_str(&id_str,
5079 got_worktree_get_base_commit_id(worktree));
5080 if (error)
5081 goto done;
5082 arg.repo = repo;
5083 arg.worktree = worktree;
5084 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5085 arg.diff_context = diff_context;
5086 arg.id_str = id_str;
5087 arg.header_shown = 0;
5088 arg.diff_staged = diff_staged;
5089 arg.ignore_whitespace = ignore_whitespace;
5090 arg.force_text_diff = force_text_diff;
5091 arg.f1 = f1;
5092 arg.f2 = f2;
5094 error = got_worktree_status(worktree, &paths, repo, 0,
5095 print_diff, &arg, check_cancelled, NULL);
5096 free(id_str);
5097 goto done;
5100 if (ncommit_args == 1) {
5101 struct got_commit_object *commit;
5102 error = got_object_open_as_commit(&commit, repo, ids[0]);
5103 if (error)
5104 goto done;
5106 labels[1] = labels[0];
5107 ids[1] = ids[0];
5108 if (got_object_commit_get_nparents(commit) > 0) {
5109 const struct got_object_id_queue *pids;
5110 struct got_object_qid *pid;
5111 pids = got_object_commit_get_parent_ids(commit);
5112 pid = STAILQ_FIRST(pids);
5113 ids[0] = got_object_id_dup(&pid->id);
5114 if (ids[0] == NULL) {
5115 error = got_error_from_errno(
5116 "got_object_id_dup");
5117 got_object_commit_close(commit);
5118 goto done;
5120 error = got_object_id_str(&labels[0], ids[0]);
5121 if (error) {
5122 got_object_commit_close(commit);
5123 goto done;
5125 } else {
5126 ids[0] = NULL;
5127 labels[0] = strdup("/dev/null");
5128 if (labels[0] == NULL) {
5129 error = got_error_from_errno("strdup");
5130 got_object_commit_close(commit);
5131 goto done;
5135 got_object_commit_close(commit);
5138 if (ncommit_args == 0 && argc > 2) {
5139 error = got_error_msg(GOT_ERR_BAD_PATH,
5140 "path arguments cannot be used when diffing two objects");
5141 goto done;
5144 if (ids[0]) {
5145 error = got_object_get_type(&type1, repo, ids[0]);
5146 if (error)
5147 goto done;
5150 error = got_object_get_type(&type2, repo, ids[1]);
5151 if (error)
5152 goto done;
5153 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5154 error = got_error(GOT_ERR_OBJ_TYPE);
5155 goto done;
5157 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5158 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5159 "path arguments cannot be used when diffing blobs");
5160 goto done;
5163 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5164 char *in_repo_path;
5165 struct got_pathlist_entry *new;
5166 if (worktree) {
5167 const char *prefix;
5168 char *p;
5169 error = got_worktree_resolve_path(&p, worktree,
5170 argv[i]);
5171 if (error)
5172 goto done;
5173 prefix = got_worktree_get_path_prefix(worktree);
5174 while (prefix[0] == '/')
5175 prefix++;
5176 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5177 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5178 p) == -1) {
5179 error = got_error_from_errno("asprintf");
5180 free(p);
5181 goto done;
5183 free(p);
5184 } else {
5185 char *mapped_path, *s;
5186 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5187 if (error)
5188 goto done;
5189 s = mapped_path;
5190 while (s[0] == '/')
5191 s++;
5192 in_repo_path = strdup(s);
5193 if (in_repo_path == NULL) {
5194 error = got_error_from_errno("asprintf");
5195 free(mapped_path);
5196 goto done;
5198 free(mapped_path);
5201 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5202 if (error || new == NULL /* duplicate */)
5203 free(in_repo_path);
5204 if (error)
5205 goto done;
5208 if (worktree) {
5209 /* Release work tree lock. */
5210 got_worktree_close(worktree);
5211 worktree = NULL;
5214 fd1 = got_opentempfd();
5215 if (fd1 == -1) {
5216 error = got_error_from_errno("got_opentempfd");
5217 goto done;
5220 fd2 = got_opentempfd();
5221 if (fd2 == -1) {
5222 error = got_error_from_errno("got_opentempfd");
5223 goto done;
5226 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5227 case GOT_OBJ_TYPE_BLOB:
5228 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5229 fd1, fd2, ids[0], ids[1], NULL, NULL,
5230 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5231 ignore_whitespace, force_text_diff, repo, stdout);
5232 break;
5233 case GOT_OBJ_TYPE_TREE:
5234 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5235 ids[0], ids[1], &paths, "", "",
5236 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5237 ignore_whitespace, force_text_diff, repo, stdout);
5238 break;
5239 case GOT_OBJ_TYPE_COMMIT:
5240 printf("diff %s %s\n", labels[0], labels[1]);
5241 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5242 fd1, fd2, ids[0], ids[1], &paths,
5243 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5244 ignore_whitespace, force_text_diff, repo, stdout);
5245 break;
5246 default:
5247 error = got_error(GOT_ERR_OBJ_TYPE);
5249 done:
5250 free(labels[0]);
5251 free(labels[1]);
5252 free(ids[0]);
5253 free(ids[1]);
5254 if (worktree)
5255 got_worktree_close(worktree);
5256 if (repo) {
5257 const struct got_error *close_err = got_repo_close(repo);
5258 if (error == NULL)
5259 error = close_err;
5261 if (pack_fds) {
5262 const struct got_error *pack_err =
5263 got_repo_pack_fds_close(pack_fds);
5264 if (error == NULL)
5265 error = pack_err;
5267 TAILQ_FOREACH(pe, &paths, entry)
5268 free((char *)pe->path);
5269 got_pathlist_free(&paths);
5270 got_ref_list_free(&refs);
5271 if (f1 && fclose(f1) == EOF && error == NULL)
5272 error = got_error_from_errno("fclose");
5273 if (f2 && fclose(f2) == EOF && error == NULL)
5274 error = got_error_from_errno("fclose");
5275 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5276 error = got_error_from_errno("close");
5277 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5278 error = got_error_from_errno("close");
5279 return error;
5282 __dead static void
5283 usage_blame(void)
5285 fprintf(stderr,
5286 "usage: %s blame [-c commit] [-r repository-path] path\n",
5287 getprogname());
5288 exit(1);
5291 struct blame_line {
5292 int annotated;
5293 char *id_str;
5294 char *committer;
5295 char datebuf[11]; /* YYYY-MM-DD + NUL */
5298 struct blame_cb_args {
5299 struct blame_line *lines;
5300 int nlines;
5301 int nlines_prec;
5302 int lineno_cur;
5303 off_t *line_offsets;
5304 FILE *f;
5305 struct got_repository *repo;
5308 static const struct got_error *
5309 blame_cb(void *arg, int nlines, int lineno,
5310 struct got_commit_object *commit, struct got_object_id *id)
5312 const struct got_error *err = NULL;
5313 struct blame_cb_args *a = arg;
5314 struct blame_line *bline;
5315 char *line = NULL;
5316 size_t linesize = 0;
5317 off_t offset;
5318 struct tm tm;
5319 time_t committer_time;
5321 if (nlines != a->nlines ||
5322 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5323 return got_error(GOT_ERR_RANGE);
5325 if (sigint_received)
5326 return got_error(GOT_ERR_ITER_COMPLETED);
5328 if (lineno == -1)
5329 return NULL; /* no change in this commit */
5331 /* Annotate this line. */
5332 bline = &a->lines[lineno - 1];
5333 if (bline->annotated)
5334 return NULL;
5335 err = got_object_id_str(&bline->id_str, id);
5336 if (err)
5337 return err;
5339 bline->committer = strdup(got_object_commit_get_committer(commit));
5340 if (bline->committer == NULL) {
5341 err = got_error_from_errno("strdup");
5342 goto done;
5345 committer_time = got_object_commit_get_committer_time(commit);
5346 if (gmtime_r(&committer_time, &tm) == NULL)
5347 return got_error_from_errno("gmtime_r");
5348 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5349 &tm) == 0) {
5350 err = got_error(GOT_ERR_NO_SPACE);
5351 goto done;
5353 bline->annotated = 1;
5355 /* Print lines annotated so far. */
5356 bline = &a->lines[a->lineno_cur - 1];
5357 if (!bline->annotated)
5358 goto done;
5360 offset = a->line_offsets[a->lineno_cur - 1];
5361 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5362 err = got_error_from_errno("fseeko");
5363 goto done;
5366 while (a->lineno_cur <= a->nlines && bline->annotated) {
5367 char *smallerthan, *at, *nl, *committer;
5368 size_t len;
5370 if (getline(&line, &linesize, a->f) == -1) {
5371 if (ferror(a->f))
5372 err = got_error_from_errno("getline");
5373 break;
5376 committer = bline->committer;
5377 smallerthan = strchr(committer, '<');
5378 if (smallerthan && smallerthan[1] != '\0')
5379 committer = smallerthan + 1;
5380 at = strchr(committer, '@');
5381 if (at)
5382 *at = '\0';
5383 len = strlen(committer);
5384 if (len >= 9)
5385 committer[8] = '\0';
5387 nl = strchr(line, '\n');
5388 if (nl)
5389 *nl = '\0';
5390 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5391 bline->id_str, bline->datebuf, committer, line);
5393 a->lineno_cur++;
5394 bline = &a->lines[a->lineno_cur - 1];
5396 done:
5397 free(line);
5398 return err;
5401 static const struct got_error *
5402 cmd_blame(int argc, char *argv[])
5404 const struct got_error *error;
5405 struct got_repository *repo = NULL;
5406 struct got_worktree *worktree = NULL;
5407 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5408 char *link_target = NULL;
5409 struct got_object_id *obj_id = NULL;
5410 struct got_object_id *commit_id = NULL;
5411 struct got_commit_object *commit = NULL;
5412 struct got_blob_object *blob = NULL;
5413 char *commit_id_str = NULL;
5414 struct blame_cb_args bca;
5415 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5416 off_t filesize;
5417 int *pack_fds = NULL;
5418 FILE *f1 = NULL, *f2 = NULL;
5420 fd1 = got_opentempfd();
5421 if (fd1 == -1)
5422 return got_error_from_errno("got_opentempfd");
5424 memset(&bca, 0, sizeof(bca));
5426 #ifndef PROFILE
5427 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5428 NULL) == -1)
5429 err(1, "pledge");
5430 #endif
5432 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5433 switch (ch) {
5434 case 'c':
5435 commit_id_str = optarg;
5436 break;
5437 case 'r':
5438 repo_path = realpath(optarg, NULL);
5439 if (repo_path == NULL)
5440 return got_error_from_errno2("realpath",
5441 optarg);
5442 got_path_strip_trailing_slashes(repo_path);
5443 break;
5444 default:
5445 usage_blame();
5446 /* NOTREACHED */
5450 argc -= optind;
5451 argv += optind;
5453 if (argc == 1)
5454 path = argv[0];
5455 else
5456 usage_blame();
5458 cwd = getcwd(NULL, 0);
5459 if (cwd == NULL) {
5460 error = got_error_from_errno("getcwd");
5461 goto done;
5464 error = got_repo_pack_fds_open(&pack_fds);
5465 if (error != NULL)
5466 goto done;
5468 if (repo_path == NULL) {
5469 error = got_worktree_open(&worktree, cwd);
5470 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5471 goto done;
5472 else
5473 error = NULL;
5474 if (worktree) {
5475 repo_path =
5476 strdup(got_worktree_get_repo_path(worktree));
5477 if (repo_path == NULL) {
5478 error = got_error_from_errno("strdup");
5479 if (error)
5480 goto done;
5482 } else {
5483 repo_path = strdup(cwd);
5484 if (repo_path == NULL) {
5485 error = got_error_from_errno("strdup");
5486 goto done;
5491 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5492 if (error != NULL)
5493 goto done;
5495 if (worktree) {
5496 const char *prefix = got_worktree_get_path_prefix(worktree);
5497 char *p;
5499 error = got_worktree_resolve_path(&p, worktree, path);
5500 if (error)
5501 goto done;
5502 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5503 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5504 p) == -1) {
5505 error = got_error_from_errno("asprintf");
5506 free(p);
5507 goto done;
5509 free(p);
5510 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5511 } else {
5512 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5513 if (error)
5514 goto done;
5515 error = got_repo_map_path(&in_repo_path, repo, path);
5517 if (error)
5518 goto done;
5520 if (commit_id_str == NULL) {
5521 struct got_reference *head_ref;
5522 error = got_ref_open(&head_ref, repo, worktree ?
5523 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5524 if (error != NULL)
5525 goto done;
5526 error = got_ref_resolve(&commit_id, repo, head_ref);
5527 got_ref_close(head_ref);
5528 if (error != NULL)
5529 goto done;
5530 } else {
5531 struct got_reflist_head refs;
5532 TAILQ_INIT(&refs);
5533 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5534 NULL);
5535 if (error)
5536 goto done;
5537 error = got_repo_match_object_id(&commit_id, NULL,
5538 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5539 got_ref_list_free(&refs);
5540 if (error)
5541 goto done;
5544 if (worktree) {
5545 /* Release work tree lock. */
5546 got_worktree_close(worktree);
5547 worktree = NULL;
5550 error = got_object_open_as_commit(&commit, repo, commit_id);
5551 if (error)
5552 goto done;
5554 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5555 commit, repo);
5556 if (error)
5557 goto done;
5559 error = got_object_id_by_path(&obj_id, repo, commit,
5560 link_target ? link_target : in_repo_path);
5561 if (error)
5562 goto done;
5564 error = got_object_get_type(&obj_type, repo, obj_id);
5565 if (error)
5566 goto done;
5568 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5569 error = got_error_path(link_target ? link_target : in_repo_path,
5570 GOT_ERR_OBJ_TYPE);
5571 goto done;
5574 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5575 if (error)
5576 goto done;
5577 bca.f = got_opentemp();
5578 if (bca.f == NULL) {
5579 error = got_error_from_errno("got_opentemp");
5580 goto done;
5582 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5583 &bca.line_offsets, bca.f, blob);
5584 if (error || bca.nlines == 0)
5585 goto done;
5587 /* Don't include \n at EOF in the blame line count. */
5588 if (bca.line_offsets[bca.nlines - 1] == filesize)
5589 bca.nlines--;
5591 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5592 if (bca.lines == NULL) {
5593 error = got_error_from_errno("calloc");
5594 goto done;
5596 bca.lineno_cur = 1;
5597 bca.nlines_prec = 0;
5598 i = bca.nlines;
5599 while (i > 0) {
5600 i /= 10;
5601 bca.nlines_prec++;
5603 bca.repo = repo;
5605 fd2 = got_opentempfd();
5606 if (fd2 == -1) {
5607 error = got_error_from_errno("got_opentempfd");
5608 goto done;
5610 fd3 = got_opentempfd();
5611 if (fd3 == -1) {
5612 error = got_error_from_errno("got_opentempfd");
5613 goto done;
5615 f1 = got_opentemp();
5616 if (f1 == NULL) {
5617 error = got_error_from_errno("got_opentemp");
5618 goto done;
5620 f2 = got_opentemp();
5621 if (f2 == NULL) {
5622 error = got_error_from_errno("got_opentemp");
5623 goto done;
5625 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5626 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5627 check_cancelled, NULL, fd2, fd3, f1, f2);
5628 done:
5629 free(in_repo_path);
5630 free(link_target);
5631 free(repo_path);
5632 free(cwd);
5633 free(commit_id);
5634 free(obj_id);
5635 if (commit)
5636 got_object_commit_close(commit);
5638 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5639 error = got_error_from_errno("close");
5640 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5641 error = got_error_from_errno("close");
5642 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5643 error = got_error_from_errno("close");
5644 if (f1 && fclose(f1) == EOF && error == NULL)
5645 error = got_error_from_errno("fclose");
5646 if (f2 && fclose(f2) == EOF && error == NULL)
5647 error = got_error_from_errno("fclose");
5649 if (blob)
5650 got_object_blob_close(blob);
5651 if (worktree)
5652 got_worktree_close(worktree);
5653 if (repo) {
5654 const struct got_error *close_err = got_repo_close(repo);
5655 if (error == NULL)
5656 error = close_err;
5658 if (pack_fds) {
5659 const struct got_error *pack_err =
5660 got_repo_pack_fds_close(pack_fds);
5661 if (error == NULL)
5662 error = pack_err;
5664 if (bca.lines) {
5665 for (i = 0; i < bca.nlines; i++) {
5666 struct blame_line *bline = &bca.lines[i];
5667 free(bline->id_str);
5668 free(bline->committer);
5670 free(bca.lines);
5672 free(bca.line_offsets);
5673 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5674 error = got_error_from_errno("fclose");
5675 return error;
5678 __dead static void
5679 usage_tree(void)
5681 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5682 "[path]\n", getprogname());
5683 exit(1);
5686 static const struct got_error *
5687 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5688 const char *root_path, struct got_repository *repo)
5690 const struct got_error *err = NULL;
5691 int is_root_path = (strcmp(path, root_path) == 0);
5692 const char *modestr = "";
5693 mode_t mode = got_tree_entry_get_mode(te);
5694 char *link_target = NULL;
5696 path += strlen(root_path);
5697 while (path[0] == '/')
5698 path++;
5700 if (got_object_tree_entry_is_submodule(te))
5701 modestr = "$";
5702 else if (S_ISLNK(mode)) {
5703 int i;
5705 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5706 if (err)
5707 return err;
5708 for (i = 0; i < strlen(link_target); i++) {
5709 if (!isprint((unsigned char)link_target[i]))
5710 link_target[i] = '?';
5713 modestr = "@";
5715 else if (S_ISDIR(mode))
5716 modestr = "/";
5717 else if (mode & S_IXUSR)
5718 modestr = "*";
5720 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5721 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5722 link_target ? " -> ": "", link_target ? link_target : "");
5724 free(link_target);
5725 return NULL;
5728 static const struct got_error *
5729 print_tree(const char *path, struct got_commit_object *commit,
5730 int show_ids, int recurse, const char *root_path,
5731 struct got_repository *repo)
5733 const struct got_error *err = NULL;
5734 struct got_object_id *tree_id = NULL;
5735 struct got_tree_object *tree = NULL;
5736 int nentries, i;
5738 err = got_object_id_by_path(&tree_id, repo, commit, path);
5739 if (err)
5740 goto done;
5742 err = got_object_open_as_tree(&tree, repo, tree_id);
5743 if (err)
5744 goto done;
5745 nentries = got_object_tree_get_nentries(tree);
5746 for (i = 0; i < nentries; i++) {
5747 struct got_tree_entry *te;
5748 char *id = NULL;
5750 if (sigint_received || sigpipe_received)
5751 break;
5753 te = got_object_tree_get_entry(tree, i);
5754 if (show_ids) {
5755 char *id_str;
5756 err = got_object_id_str(&id_str,
5757 got_tree_entry_get_id(te));
5758 if (err)
5759 goto done;
5760 if (asprintf(&id, "%s ", id_str) == -1) {
5761 err = got_error_from_errno("asprintf");
5762 free(id_str);
5763 goto done;
5765 free(id_str);
5767 err = print_entry(te, id, path, root_path, repo);
5768 free(id);
5769 if (err)
5770 goto done;
5772 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5773 char *child_path;
5774 if (asprintf(&child_path, "%s%s%s", path,
5775 path[0] == '/' && path[1] == '\0' ? "" : "/",
5776 got_tree_entry_get_name(te)) == -1) {
5777 err = got_error_from_errno("asprintf");
5778 goto done;
5780 err = print_tree(child_path, commit, show_ids, 1,
5781 root_path, repo);
5782 free(child_path);
5783 if (err)
5784 goto done;
5787 done:
5788 if (tree)
5789 got_object_tree_close(tree);
5790 free(tree_id);
5791 return err;
5794 static const struct got_error *
5795 cmd_tree(int argc, char *argv[])
5797 const struct got_error *error;
5798 struct got_repository *repo = NULL;
5799 struct got_worktree *worktree = NULL;
5800 const char *path, *refname = NULL;
5801 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5802 struct got_object_id *commit_id = NULL;
5803 struct got_commit_object *commit = NULL;
5804 char *commit_id_str = NULL;
5805 int show_ids = 0, recurse = 0;
5806 int ch;
5807 int *pack_fds = NULL;
5809 #ifndef PROFILE
5810 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5811 NULL) == -1)
5812 err(1, "pledge");
5813 #endif
5815 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5816 switch (ch) {
5817 case 'c':
5818 commit_id_str = optarg;
5819 break;
5820 case 'r':
5821 repo_path = realpath(optarg, NULL);
5822 if (repo_path == NULL)
5823 return got_error_from_errno2("realpath",
5824 optarg);
5825 got_path_strip_trailing_slashes(repo_path);
5826 break;
5827 case 'i':
5828 show_ids = 1;
5829 break;
5830 case 'R':
5831 recurse = 1;
5832 break;
5833 default:
5834 usage_tree();
5835 /* NOTREACHED */
5839 argc -= optind;
5840 argv += optind;
5842 if (argc == 1)
5843 path = argv[0];
5844 else if (argc > 1)
5845 usage_tree();
5846 else
5847 path = NULL;
5849 cwd = getcwd(NULL, 0);
5850 if (cwd == NULL) {
5851 error = got_error_from_errno("getcwd");
5852 goto done;
5855 error = got_repo_pack_fds_open(&pack_fds);
5856 if (error != NULL)
5857 goto done;
5859 if (repo_path == NULL) {
5860 error = got_worktree_open(&worktree, cwd);
5861 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5862 goto done;
5863 else
5864 error = NULL;
5865 if (worktree) {
5866 repo_path =
5867 strdup(got_worktree_get_repo_path(worktree));
5868 if (repo_path == NULL)
5869 error = got_error_from_errno("strdup");
5870 if (error)
5871 goto done;
5872 } else {
5873 repo_path = strdup(cwd);
5874 if (repo_path == NULL) {
5875 error = got_error_from_errno("strdup");
5876 goto done;
5881 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5882 if (error != NULL)
5883 goto done;
5885 if (worktree) {
5886 const char *prefix = got_worktree_get_path_prefix(worktree);
5887 char *p;
5889 if (path == NULL)
5890 path = "";
5891 error = got_worktree_resolve_path(&p, worktree, path);
5892 if (error)
5893 goto done;
5894 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5895 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5896 p) == -1) {
5897 error = got_error_from_errno("asprintf");
5898 free(p);
5899 goto done;
5901 free(p);
5902 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5903 if (error)
5904 goto done;
5905 } else {
5906 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5907 if (error)
5908 goto done;
5909 if (path == NULL)
5910 path = "/";
5911 error = got_repo_map_path(&in_repo_path, repo, path);
5912 if (error != NULL)
5913 goto done;
5916 if (commit_id_str == NULL) {
5917 struct got_reference *head_ref;
5918 if (worktree)
5919 refname = got_worktree_get_head_ref_name(worktree);
5920 else
5921 refname = GOT_REF_HEAD;
5922 error = got_ref_open(&head_ref, repo, refname, 0);
5923 if (error != NULL)
5924 goto done;
5925 error = got_ref_resolve(&commit_id, repo, head_ref);
5926 got_ref_close(head_ref);
5927 if (error != NULL)
5928 goto done;
5929 } else {
5930 struct got_reflist_head refs;
5931 TAILQ_INIT(&refs);
5932 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5933 NULL);
5934 if (error)
5935 goto done;
5936 error = got_repo_match_object_id(&commit_id, NULL,
5937 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5938 got_ref_list_free(&refs);
5939 if (error)
5940 goto done;
5943 if (worktree) {
5944 /* Release work tree lock. */
5945 got_worktree_close(worktree);
5946 worktree = NULL;
5949 error = got_object_open_as_commit(&commit, repo, commit_id);
5950 if (error)
5951 goto done;
5953 error = print_tree(in_repo_path, commit, show_ids, recurse,
5954 in_repo_path, repo);
5955 done:
5956 free(in_repo_path);
5957 free(repo_path);
5958 free(cwd);
5959 free(commit_id);
5960 if (commit)
5961 got_object_commit_close(commit);
5962 if (worktree)
5963 got_worktree_close(worktree);
5964 if (repo) {
5965 const struct got_error *close_err = got_repo_close(repo);
5966 if (error == NULL)
5967 error = close_err;
5969 if (pack_fds) {
5970 const struct got_error *pack_err =
5971 got_repo_pack_fds_close(pack_fds);
5972 if (error == NULL)
5973 error = pack_err;
5975 return error;
5978 __dead static void
5979 usage_status(void)
5981 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5982 "[-s status-codes] [path ...]\n", getprogname());
5983 exit(1);
5986 struct got_status_arg {
5987 char *status_codes;
5988 int suppress;
5991 static const struct got_error *
5992 print_status(void *arg, unsigned char status, unsigned char staged_status,
5993 const char *path, struct got_object_id *blob_id,
5994 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5995 int dirfd, const char *de_name)
5997 struct got_status_arg *st = arg;
5999 if (status == staged_status && (status == GOT_STATUS_DELETE))
6000 status = GOT_STATUS_NO_CHANGE;
6001 if (st != NULL && st->status_codes) {
6002 size_t ncodes = strlen(st->status_codes);
6003 int i, j = 0;
6005 for (i = 0; i < ncodes ; i++) {
6006 if (st->suppress) {
6007 if (status == st->status_codes[i] ||
6008 staged_status == st->status_codes[i]) {
6009 j++;
6010 continue;
6012 } else {
6013 if (status == st->status_codes[i] ||
6014 staged_status == st->status_codes[i])
6015 break;
6019 if (st->suppress && j == 0)
6020 goto print;
6022 if (i == ncodes)
6023 return NULL;
6025 print:
6026 printf("%c%c %s\n", status, staged_status, path);
6027 return NULL;
6030 static const struct got_error *
6031 cmd_status(int argc, char *argv[])
6033 const struct got_error *error = NULL;
6034 struct got_repository *repo = NULL;
6035 struct got_worktree *worktree = NULL;
6036 struct got_status_arg st;
6037 char *cwd = NULL;
6038 struct got_pathlist_head paths;
6039 struct got_pathlist_entry *pe;
6040 int ch, i, no_ignores = 0;
6041 int *pack_fds = NULL;
6043 TAILQ_INIT(&paths);
6045 memset(&st, 0, sizeof(st));
6046 st.status_codes = NULL;
6047 st.suppress = 0;
6049 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6050 switch (ch) {
6051 case 'I':
6052 no_ignores = 1;
6053 break;
6054 case 'S':
6055 if (st.status_codes != NULL && st.suppress == 0)
6056 option_conflict('S', 's');
6057 st.suppress = 1;
6058 /* fallthrough */
6059 case 's':
6060 for (i = 0; i < strlen(optarg); i++) {
6061 switch (optarg[i]) {
6062 case GOT_STATUS_MODIFY:
6063 case GOT_STATUS_ADD:
6064 case GOT_STATUS_DELETE:
6065 case GOT_STATUS_CONFLICT:
6066 case GOT_STATUS_MISSING:
6067 case GOT_STATUS_OBSTRUCTED:
6068 case GOT_STATUS_UNVERSIONED:
6069 case GOT_STATUS_MODE_CHANGE:
6070 case GOT_STATUS_NONEXISTENT:
6071 break;
6072 default:
6073 errx(1, "invalid status code '%c'",
6074 optarg[i]);
6077 if (ch == 's' && st.suppress)
6078 option_conflict('s', 'S');
6079 st.status_codes = optarg;
6080 break;
6081 default:
6082 usage_status();
6083 /* NOTREACHED */
6087 argc -= optind;
6088 argv += optind;
6090 #ifndef PROFILE
6091 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6092 NULL) == -1)
6093 err(1, "pledge");
6094 #endif
6095 cwd = getcwd(NULL, 0);
6096 if (cwd == NULL) {
6097 error = got_error_from_errno("getcwd");
6098 goto done;
6101 error = got_repo_pack_fds_open(&pack_fds);
6102 if (error != NULL)
6103 goto done;
6105 error = got_worktree_open(&worktree, cwd);
6106 if (error) {
6107 if (error->code == GOT_ERR_NOT_WORKTREE)
6108 error = wrap_not_worktree_error(error, "status", cwd);
6109 goto done;
6112 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6113 NULL, pack_fds);
6114 if (error != NULL)
6115 goto done;
6117 error = apply_unveil(got_repo_get_path(repo), 1,
6118 got_worktree_get_root_path(worktree));
6119 if (error)
6120 goto done;
6122 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6123 if (error)
6124 goto done;
6126 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6127 print_status, &st, check_cancelled, NULL);
6128 done:
6129 if (pack_fds) {
6130 const struct got_error *pack_err =
6131 got_repo_pack_fds_close(pack_fds);
6132 if (error == NULL)
6133 error = pack_err;
6136 TAILQ_FOREACH(pe, &paths, entry)
6137 free((char *)pe->path);
6138 got_pathlist_free(&paths);
6139 free(cwd);
6140 return error;
6143 __dead static void
6144 usage_ref(void)
6146 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6147 "[-s reference] [name]\n", getprogname());
6148 exit(1);
6151 static const struct got_error *
6152 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6154 static const struct got_error *err = NULL;
6155 struct got_reflist_head refs;
6156 struct got_reflist_entry *re;
6158 TAILQ_INIT(&refs);
6159 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6160 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6161 repo);
6162 if (err)
6163 return err;
6165 TAILQ_FOREACH(re, &refs, entry) {
6166 char *refstr;
6167 refstr = got_ref_to_str(re->ref);
6168 if (refstr == NULL) {
6169 err = got_error_from_errno("got_ref_to_str");
6170 break;
6172 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6173 free(refstr);
6176 got_ref_list_free(&refs);
6177 return err;
6180 static const struct got_error *
6181 delete_ref_by_name(struct got_repository *repo, const char *refname)
6183 const struct got_error *err;
6184 struct got_reference *ref;
6186 err = got_ref_open(&ref, repo, refname, 0);
6187 if (err)
6188 return err;
6190 err = delete_ref(repo, ref);
6191 got_ref_close(ref);
6192 return err;
6195 static const struct got_error *
6196 add_ref(struct got_repository *repo, const char *refname, const char *target)
6198 const struct got_error *err = NULL;
6199 struct got_object_id *id = NULL;
6200 struct got_reference *ref = NULL;
6201 struct got_reflist_head refs;
6204 * Don't let the user create a reference name with a leading '-'.
6205 * While technically a valid reference name, this case is usually
6206 * an unintended typo.
6208 if (refname[0] == '-')
6209 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6211 TAILQ_INIT(&refs);
6212 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6213 if (err)
6214 goto done;
6215 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6216 &refs, repo);
6217 got_ref_list_free(&refs);
6218 if (err)
6219 goto done;
6221 err = got_ref_alloc(&ref, refname, id);
6222 if (err)
6223 goto done;
6225 err = got_ref_write(ref, repo);
6226 done:
6227 if (ref)
6228 got_ref_close(ref);
6229 free(id);
6230 return err;
6233 static const struct got_error *
6234 add_symref(struct got_repository *repo, const char *refname, const char *target)
6236 const struct got_error *err = NULL;
6237 struct got_reference *ref = NULL;
6238 struct got_reference *target_ref = NULL;
6241 * Don't let the user create a reference name with a leading '-'.
6242 * While technically a valid reference name, this case is usually
6243 * an unintended typo.
6245 if (refname[0] == '-')
6246 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6248 err = got_ref_open(&target_ref, repo, target, 0);
6249 if (err)
6250 return err;
6252 err = got_ref_alloc_symref(&ref, refname, target_ref);
6253 if (err)
6254 goto done;
6256 err = got_ref_write(ref, repo);
6257 done:
6258 if (target_ref)
6259 got_ref_close(target_ref);
6260 if (ref)
6261 got_ref_close(ref);
6262 return err;
6265 static const struct got_error *
6266 cmd_ref(int argc, char *argv[])
6268 const struct got_error *error = NULL;
6269 struct got_repository *repo = NULL;
6270 struct got_worktree *worktree = NULL;
6271 char *cwd = NULL, *repo_path = NULL;
6272 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6273 const char *obj_arg = NULL, *symref_target= NULL;
6274 char *refname = NULL;
6275 int *pack_fds = NULL;
6277 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6278 switch (ch) {
6279 case 'c':
6280 obj_arg = optarg;
6281 break;
6282 case 'd':
6283 do_delete = 1;
6284 break;
6285 case 'r':
6286 repo_path = realpath(optarg, NULL);
6287 if (repo_path == NULL)
6288 return got_error_from_errno2("realpath",
6289 optarg);
6290 got_path_strip_trailing_slashes(repo_path);
6291 break;
6292 case 'l':
6293 do_list = 1;
6294 break;
6295 case 's':
6296 symref_target = optarg;
6297 break;
6298 case 't':
6299 sort_by_time = 1;
6300 break;
6301 default:
6302 usage_ref();
6303 /* NOTREACHED */
6307 if (obj_arg && do_list)
6308 option_conflict('c', 'l');
6309 if (obj_arg && do_delete)
6310 option_conflict('c', 'd');
6311 if (obj_arg && symref_target)
6312 option_conflict('c', 's');
6313 if (symref_target && do_delete)
6314 option_conflict('s', 'd');
6315 if (symref_target && do_list)
6316 option_conflict('s', 'l');
6317 if (do_delete && do_list)
6318 option_conflict('d', 'l');
6319 if (sort_by_time && !do_list)
6320 errx(1, "-t option requires -l option");
6322 argc -= optind;
6323 argv += optind;
6325 if (do_list) {
6326 if (argc != 0 && argc != 1)
6327 usage_ref();
6328 if (argc == 1) {
6329 refname = strdup(argv[0]);
6330 if (refname == NULL) {
6331 error = got_error_from_errno("strdup");
6332 goto done;
6335 } else {
6336 if (argc != 1)
6337 usage_ref();
6338 refname = strdup(argv[0]);
6339 if (refname == NULL) {
6340 error = got_error_from_errno("strdup");
6341 goto done;
6345 if (refname)
6346 got_path_strip_trailing_slashes(refname);
6348 #ifndef PROFILE
6349 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6350 "sendfd unveil", NULL) == -1)
6351 err(1, "pledge");
6352 #endif
6353 cwd = getcwd(NULL, 0);
6354 if (cwd == NULL) {
6355 error = got_error_from_errno("getcwd");
6356 goto done;
6359 error = got_repo_pack_fds_open(&pack_fds);
6360 if (error != NULL)
6361 goto done;
6363 if (repo_path == NULL) {
6364 error = got_worktree_open(&worktree, cwd);
6365 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6366 goto done;
6367 else
6368 error = NULL;
6369 if (worktree) {
6370 repo_path =
6371 strdup(got_worktree_get_repo_path(worktree));
6372 if (repo_path == NULL)
6373 error = got_error_from_errno("strdup");
6374 if (error)
6375 goto done;
6376 } else {
6377 repo_path = strdup(cwd);
6378 if (repo_path == NULL) {
6379 error = got_error_from_errno("strdup");
6380 goto done;
6385 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6386 if (error != NULL)
6387 goto done;
6389 #ifndef PROFILE
6390 if (do_list) {
6391 /* Remove "cpath" promise. */
6392 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6393 NULL) == -1)
6394 err(1, "pledge");
6396 #endif
6398 error = apply_unveil(got_repo_get_path(repo), do_list,
6399 worktree ? got_worktree_get_root_path(worktree) : NULL);
6400 if (error)
6401 goto done;
6403 if (do_list)
6404 error = list_refs(repo, refname, sort_by_time);
6405 else if (do_delete)
6406 error = delete_ref_by_name(repo, refname);
6407 else if (symref_target)
6408 error = add_symref(repo, refname, symref_target);
6409 else {
6410 if (obj_arg == NULL)
6411 usage_ref();
6412 error = add_ref(repo, refname, obj_arg);
6414 done:
6415 free(refname);
6416 if (repo) {
6417 const struct got_error *close_err = got_repo_close(repo);
6418 if (error == NULL)
6419 error = close_err;
6421 if (worktree)
6422 got_worktree_close(worktree);
6423 if (pack_fds) {
6424 const struct got_error *pack_err =
6425 got_repo_pack_fds_close(pack_fds);
6426 if (error == NULL)
6427 error = pack_err;
6429 free(cwd);
6430 free(repo_path);
6431 return error;
6434 __dead static void
6435 usage_branch(void)
6437 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6438 "[-r repository-path] [name]\n", getprogname());
6439 exit(1);
6442 static const struct got_error *
6443 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6444 struct got_reference *ref)
6446 const struct got_error *err = NULL;
6447 const char *refname, *marker = " ";
6448 char *refstr;
6450 refname = got_ref_get_name(ref);
6451 if (worktree && strcmp(refname,
6452 got_worktree_get_head_ref_name(worktree)) == 0) {
6453 struct got_object_id *id = NULL;
6455 err = got_ref_resolve(&id, repo, ref);
6456 if (err)
6457 return err;
6458 if (got_object_id_cmp(id,
6459 got_worktree_get_base_commit_id(worktree)) == 0)
6460 marker = "* ";
6461 else
6462 marker = "~ ";
6463 free(id);
6466 if (strncmp(refname, "refs/heads/", 11) == 0)
6467 refname += 11;
6468 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6469 refname += 18;
6470 if (strncmp(refname, "refs/remotes/", 13) == 0)
6471 refname += 13;
6473 refstr = got_ref_to_str(ref);
6474 if (refstr == NULL)
6475 return got_error_from_errno("got_ref_to_str");
6477 printf("%s%s: %s\n", marker, refname, refstr);
6478 free(refstr);
6479 return NULL;
6482 static const struct got_error *
6483 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6485 const char *refname;
6487 if (worktree == NULL)
6488 return got_error(GOT_ERR_NOT_WORKTREE);
6490 refname = got_worktree_get_head_ref_name(worktree);
6492 if (strncmp(refname, "refs/heads/", 11) == 0)
6493 refname += 11;
6494 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6495 refname += 18;
6497 printf("%s\n", refname);
6499 return NULL;
6502 static const struct got_error *
6503 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6504 int sort_by_time)
6506 static const struct got_error *err = NULL;
6507 struct got_reflist_head refs;
6508 struct got_reflist_entry *re;
6509 struct got_reference *temp_ref = NULL;
6510 int rebase_in_progress, histedit_in_progress;
6512 TAILQ_INIT(&refs);
6514 if (worktree) {
6515 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6516 worktree);
6517 if (err)
6518 return err;
6520 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6521 worktree);
6522 if (err)
6523 return err;
6525 if (rebase_in_progress || histedit_in_progress) {
6526 err = got_ref_open(&temp_ref, repo,
6527 got_worktree_get_head_ref_name(worktree), 0);
6528 if (err)
6529 return err;
6530 list_branch(repo, worktree, temp_ref);
6531 got_ref_close(temp_ref);
6535 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6536 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6537 repo);
6538 if (err)
6539 return err;
6541 TAILQ_FOREACH(re, &refs, entry)
6542 list_branch(repo, worktree, re->ref);
6544 got_ref_list_free(&refs);
6546 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6547 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6548 repo);
6549 if (err)
6550 return err;
6552 TAILQ_FOREACH(re, &refs, entry)
6553 list_branch(repo, worktree, re->ref);
6555 got_ref_list_free(&refs);
6557 return NULL;
6560 static const struct got_error *
6561 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6562 const char *branch_name)
6564 const struct got_error *err = NULL;
6565 struct got_reference *ref = NULL;
6566 char *refname, *remote_refname = NULL;
6568 if (strncmp(branch_name, "refs/", 5) == 0)
6569 branch_name += 5;
6570 if (strncmp(branch_name, "heads/", 6) == 0)
6571 branch_name += 6;
6572 else if (strncmp(branch_name, "remotes/", 8) == 0)
6573 branch_name += 8;
6575 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6576 return got_error_from_errno("asprintf");
6578 if (asprintf(&remote_refname, "refs/remotes/%s",
6579 branch_name) == -1) {
6580 err = got_error_from_errno("asprintf");
6581 goto done;
6584 err = got_ref_open(&ref, repo, refname, 0);
6585 if (err) {
6586 const struct got_error *err2;
6587 if (err->code != GOT_ERR_NOT_REF)
6588 goto done;
6590 * Keep 'err' intact such that if neither branch exists
6591 * we report "refs/heads" rather than "refs/remotes" in
6592 * our error message.
6594 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6595 if (err2)
6596 goto done;
6597 err = NULL;
6600 if (worktree &&
6601 strcmp(got_worktree_get_head_ref_name(worktree),
6602 got_ref_get_name(ref)) == 0) {
6603 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6604 "will not delete this work tree's current branch");
6605 goto done;
6608 err = delete_ref(repo, ref);
6609 done:
6610 if (ref)
6611 got_ref_close(ref);
6612 free(refname);
6613 free(remote_refname);
6614 return err;
6617 static const struct got_error *
6618 add_branch(struct got_repository *repo, const char *branch_name,
6619 struct got_object_id *base_commit_id)
6621 const struct got_error *err = NULL;
6622 struct got_reference *ref = NULL;
6623 char *base_refname = NULL, *refname = NULL;
6626 * Don't let the user create a branch name with a leading '-'.
6627 * While technically a valid reference name, this case is usually
6628 * an unintended typo.
6630 if (branch_name[0] == '-')
6631 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6633 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6634 branch_name += 11;
6636 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6637 err = got_error_from_errno("asprintf");
6638 goto done;
6641 err = got_ref_open(&ref, repo, refname, 0);
6642 if (err == NULL) {
6643 err = got_error(GOT_ERR_BRANCH_EXISTS);
6644 goto done;
6645 } else if (err->code != GOT_ERR_NOT_REF)
6646 goto done;
6648 err = got_ref_alloc(&ref, refname, base_commit_id);
6649 if (err)
6650 goto done;
6652 err = got_ref_write(ref, repo);
6653 done:
6654 if (ref)
6655 got_ref_close(ref);
6656 free(base_refname);
6657 free(refname);
6658 return err;
6661 static const struct got_error *
6662 cmd_branch(int argc, char *argv[])
6664 const struct got_error *error = NULL;
6665 struct got_repository *repo = NULL;
6666 struct got_worktree *worktree = NULL;
6667 char *cwd = NULL, *repo_path = NULL;
6668 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6669 const char *delref = NULL, *commit_id_arg = NULL;
6670 struct got_reference *ref = NULL;
6671 struct got_pathlist_head paths;
6672 struct got_pathlist_entry *pe;
6673 struct got_object_id *commit_id = NULL;
6674 char *commit_id_str = NULL;
6675 int *pack_fds = NULL;
6677 TAILQ_INIT(&paths);
6679 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6680 switch (ch) {
6681 case 'c':
6682 commit_id_arg = optarg;
6683 break;
6684 case 'd':
6685 delref = optarg;
6686 break;
6687 case 'r':
6688 repo_path = realpath(optarg, NULL);
6689 if (repo_path == NULL)
6690 return got_error_from_errno2("realpath",
6691 optarg);
6692 got_path_strip_trailing_slashes(repo_path);
6693 break;
6694 case 'l':
6695 do_list = 1;
6696 break;
6697 case 'n':
6698 do_update = 0;
6699 break;
6700 case 't':
6701 sort_by_time = 1;
6702 break;
6703 default:
6704 usage_branch();
6705 /* NOTREACHED */
6709 if (do_list && delref)
6710 option_conflict('l', 'd');
6711 if (sort_by_time && !do_list)
6712 errx(1, "-t option requires -l option");
6714 argc -= optind;
6715 argv += optind;
6717 if (!do_list && !delref && argc == 0)
6718 do_show = 1;
6720 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6721 errx(1, "-c option can only be used when creating a branch");
6723 if (do_list || delref) {
6724 if (argc > 0)
6725 usage_branch();
6726 } else if (!do_show && argc != 1)
6727 usage_branch();
6729 #ifndef PROFILE
6730 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6731 "sendfd unveil", NULL) == -1)
6732 err(1, "pledge");
6733 #endif
6734 cwd = getcwd(NULL, 0);
6735 if (cwd == NULL) {
6736 error = got_error_from_errno("getcwd");
6737 goto done;
6740 error = got_repo_pack_fds_open(&pack_fds);
6741 if (error != NULL)
6742 goto done;
6744 if (repo_path == NULL) {
6745 error = got_worktree_open(&worktree, cwd);
6746 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6747 goto done;
6748 else
6749 error = NULL;
6750 if (worktree) {
6751 repo_path =
6752 strdup(got_worktree_get_repo_path(worktree));
6753 if (repo_path == NULL)
6754 error = got_error_from_errno("strdup");
6755 if (error)
6756 goto done;
6757 } else {
6758 repo_path = strdup(cwd);
6759 if (repo_path == NULL) {
6760 error = got_error_from_errno("strdup");
6761 goto done;
6766 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6767 if (error != NULL)
6768 goto done;
6770 #ifndef PROFILE
6771 if (do_list || do_show) {
6772 /* Remove "cpath" promise. */
6773 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6774 NULL) == -1)
6775 err(1, "pledge");
6777 #endif
6779 error = apply_unveil(got_repo_get_path(repo), do_list,
6780 worktree ? got_worktree_get_root_path(worktree) : NULL);
6781 if (error)
6782 goto done;
6784 if (do_show)
6785 error = show_current_branch(repo, worktree);
6786 else if (do_list)
6787 error = list_branches(repo, worktree, sort_by_time);
6788 else if (delref)
6789 error = delete_branch(repo, worktree, delref);
6790 else {
6791 struct got_reflist_head refs;
6792 TAILQ_INIT(&refs);
6793 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6794 NULL);
6795 if (error)
6796 goto done;
6797 if (commit_id_arg == NULL)
6798 commit_id_arg = worktree ?
6799 got_worktree_get_head_ref_name(worktree) :
6800 GOT_REF_HEAD;
6801 error = got_repo_match_object_id(&commit_id, NULL,
6802 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6803 got_ref_list_free(&refs);
6804 if (error)
6805 goto done;
6806 error = add_branch(repo, argv[0], commit_id);
6807 if (error)
6808 goto done;
6809 if (worktree && do_update) {
6810 struct got_update_progress_arg upa;
6811 char *branch_refname = NULL;
6813 error = got_object_id_str(&commit_id_str, commit_id);
6814 if (error)
6815 goto done;
6816 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6817 worktree);
6818 if (error)
6819 goto done;
6820 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6821 == -1) {
6822 error = got_error_from_errno("asprintf");
6823 goto done;
6825 error = got_ref_open(&ref, repo, branch_refname, 0);
6826 free(branch_refname);
6827 if (error)
6828 goto done;
6829 error = switch_head_ref(ref, commit_id, worktree,
6830 repo);
6831 if (error)
6832 goto done;
6833 error = got_worktree_set_base_commit_id(worktree, repo,
6834 commit_id);
6835 if (error)
6836 goto done;
6837 memset(&upa, 0, sizeof(upa));
6838 error = got_worktree_checkout_files(worktree, &paths,
6839 repo, update_progress, &upa, check_cancelled,
6840 NULL);
6841 if (error)
6842 goto done;
6843 if (upa.did_something) {
6844 printf("Updated to %s: %s\n",
6845 got_worktree_get_head_ref_name(worktree),
6846 commit_id_str);
6848 print_update_progress_stats(&upa);
6851 done:
6852 if (ref)
6853 got_ref_close(ref);
6854 if (repo) {
6855 const struct got_error *close_err = got_repo_close(repo);
6856 if (error == NULL)
6857 error = close_err;
6859 if (worktree)
6860 got_worktree_close(worktree);
6861 if (pack_fds) {
6862 const struct got_error *pack_err =
6863 got_repo_pack_fds_close(pack_fds);
6864 if (error == NULL)
6865 error = pack_err;
6867 free(cwd);
6868 free(repo_path);
6869 free(commit_id);
6870 free(commit_id_str);
6871 TAILQ_FOREACH(pe, &paths, entry)
6872 free((char *)pe->path);
6873 got_pathlist_free(&paths);
6874 return error;
6878 __dead static void
6879 usage_tag(void)
6881 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6882 "[-r repository-path] [-s signer-id] name\n", getprogname());
6883 exit(1);
6886 #if 0
6887 static const struct got_error *
6888 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6890 const struct got_error *err = NULL;
6891 struct got_reflist_entry *re, *se, *new;
6892 struct got_object_id *re_id, *se_id;
6893 struct got_tag_object *re_tag, *se_tag;
6894 time_t re_time, se_time;
6896 STAILQ_FOREACH(re, tags, entry) {
6897 se = STAILQ_FIRST(sorted);
6898 if (se == NULL) {
6899 err = got_reflist_entry_dup(&new, re);
6900 if (err)
6901 return err;
6902 STAILQ_INSERT_HEAD(sorted, new, entry);
6903 continue;
6904 } else {
6905 err = got_ref_resolve(&re_id, repo, re->ref);
6906 if (err)
6907 break;
6908 err = got_object_open_as_tag(&re_tag, repo, re_id);
6909 free(re_id);
6910 if (err)
6911 break;
6912 re_time = got_object_tag_get_tagger_time(re_tag);
6913 got_object_tag_close(re_tag);
6916 while (se) {
6917 err = got_ref_resolve(&se_id, repo, re->ref);
6918 if (err)
6919 break;
6920 err = got_object_open_as_tag(&se_tag, repo, se_id);
6921 free(se_id);
6922 if (err)
6923 break;
6924 se_time = got_object_tag_get_tagger_time(se_tag);
6925 got_object_tag_close(se_tag);
6927 if (se_time > re_time) {
6928 err = got_reflist_entry_dup(&new, re);
6929 if (err)
6930 return err;
6931 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6932 break;
6934 se = STAILQ_NEXT(se, entry);
6935 continue;
6938 done:
6939 return err;
6941 #endif
6943 static const struct got_error *
6944 get_tag_refname(char **refname, const char *tag_name)
6946 const struct got_error *err;
6948 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6949 *refname = strdup(tag_name);
6950 if (*refname == NULL)
6951 return got_error_from_errno("strdup");
6952 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6953 err = got_error_from_errno("asprintf");
6954 *refname = NULL;
6955 return err;
6958 return NULL;
6961 static const struct got_error *
6962 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6963 const char *allowed_signers, const char *revoked_signers, int verbosity)
6965 static const struct got_error *err = NULL;
6966 struct got_reflist_head refs;
6967 struct got_reflist_entry *re;
6968 char *wanted_refname = NULL;
6969 int bad_sigs = 0;
6971 TAILQ_INIT(&refs);
6973 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6974 if (err)
6975 return err;
6977 if (tag_name) {
6978 struct got_reference *ref;
6979 err = get_tag_refname(&wanted_refname, tag_name);
6980 if (err)
6981 goto done;
6982 /* Wanted tag reference should exist. */
6983 err = got_ref_open(&ref, repo, wanted_refname, 0);
6984 if (err)
6985 goto done;
6986 got_ref_close(ref);
6989 TAILQ_FOREACH(re, &refs, entry) {
6990 const char *refname;
6991 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6992 char datebuf[26];
6993 const char *tagger, *ssh_sig = NULL;
6994 char *sig_msg = NULL;
6995 time_t tagger_time;
6996 struct got_object_id *id;
6997 struct got_tag_object *tag;
6998 struct got_commit_object *commit = NULL;
7000 refname = got_ref_get_name(re->ref);
7001 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7002 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7003 continue;
7004 refname += 10;
7005 refstr = got_ref_to_str(re->ref);
7006 if (refstr == NULL) {
7007 err = got_error_from_errno("got_ref_to_str");
7008 break;
7011 err = got_ref_resolve(&id, repo, re->ref);
7012 if (err)
7013 break;
7014 err = got_object_open_as_tag(&tag, repo, id);
7015 if (err) {
7016 if (err->code != GOT_ERR_OBJ_TYPE) {
7017 free(id);
7018 break;
7020 /* "lightweight" tag */
7021 err = got_object_open_as_commit(&commit, repo, id);
7022 if (err) {
7023 free(id);
7024 break;
7026 tagger = got_object_commit_get_committer(commit);
7027 tagger_time =
7028 got_object_commit_get_committer_time(commit);
7029 err = got_object_id_str(&id_str, id);
7030 free(id);
7031 if (err)
7032 break;
7033 } else {
7034 free(id);
7035 tagger = got_object_tag_get_tagger(tag);
7036 tagger_time = got_object_tag_get_tagger_time(tag);
7037 err = got_object_id_str(&id_str,
7038 got_object_tag_get_object_id(tag));
7039 if (err)
7040 break;
7043 if (tag && verify_tags) {
7044 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7045 got_object_tag_get_message(tag));
7046 if (ssh_sig && allowed_signers == NULL) {
7047 err = got_error_msg(
7048 GOT_ERR_VERIFY_TAG_SIGNATURE,
7049 "SSH signature verification requires "
7050 "setting allowed_signers in "
7051 "got.conf(5)");
7052 break;
7056 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7057 free(refstr);
7058 printf("from: %s\n", tagger);
7059 datestr = get_datestr(&tagger_time, datebuf);
7060 if (datestr)
7061 printf("date: %s UTC\n", datestr);
7062 if (commit)
7063 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7064 else {
7065 switch (got_object_tag_get_object_type(tag)) {
7066 case GOT_OBJ_TYPE_BLOB:
7067 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7068 id_str);
7069 break;
7070 case GOT_OBJ_TYPE_TREE:
7071 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7072 id_str);
7073 break;
7074 case GOT_OBJ_TYPE_COMMIT:
7075 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7076 id_str);
7077 break;
7078 case GOT_OBJ_TYPE_TAG:
7079 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7080 id_str);
7081 break;
7082 default:
7083 break;
7086 free(id_str);
7088 if (ssh_sig) {
7089 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7090 allowed_signers, revoked_signers, verbosity);
7091 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7092 bad_sigs = 1;
7093 else if (err)
7094 break;
7095 printf("signature: %s", sig_msg);
7096 free(sig_msg);
7097 sig_msg = NULL;
7100 if (commit) {
7101 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7102 if (err)
7103 break;
7104 got_object_commit_close(commit);
7105 } else {
7106 tagmsg0 = strdup(got_object_tag_get_message(tag));
7107 got_object_tag_close(tag);
7108 if (tagmsg0 == NULL) {
7109 err = got_error_from_errno("strdup");
7110 break;
7114 tagmsg = tagmsg0;
7115 do {
7116 line = strsep(&tagmsg, "\n");
7117 if (line)
7118 printf(" %s\n", line);
7119 } while (line);
7120 free(tagmsg0);
7122 done:
7123 got_ref_list_free(&refs);
7124 free(wanted_refname);
7126 if (err == NULL && bad_sigs)
7127 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7128 return err;
7131 static const struct got_error *
7132 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7133 const char *tag_name, const char *repo_path)
7135 const struct got_error *err = NULL;
7136 char *template = NULL, *initial_content = NULL;
7137 char *editor = NULL;
7138 int initial_content_len;
7139 int fd = -1;
7141 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7142 err = got_error_from_errno("asprintf");
7143 goto done;
7146 initial_content_len = asprintf(&initial_content,
7147 "\n# tagging commit %s as %s\n",
7148 commit_id_str, tag_name);
7149 if (initial_content_len == -1) {
7150 err = got_error_from_errno("asprintf");
7151 goto done;
7154 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7155 if (err)
7156 goto done;
7158 if (write(fd, initial_content, initial_content_len) == -1) {
7159 err = got_error_from_errno2("write", *tagmsg_path);
7160 goto done;
7163 err = get_editor(&editor);
7164 if (err)
7165 goto done;
7166 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7167 initial_content_len, 1);
7168 done:
7169 free(initial_content);
7170 free(template);
7171 free(editor);
7173 if (fd != -1 && close(fd) == -1 && err == NULL)
7174 err = got_error_from_errno2("close", *tagmsg_path);
7176 if (err) {
7177 free(*tagmsg);
7178 *tagmsg = NULL;
7180 return err;
7183 static const struct got_error *
7184 add_tag(struct got_repository *repo, const char *tagger,
7185 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7186 const char *signer_id, int verbosity)
7188 const struct got_error *err = NULL;
7189 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7190 char *label = NULL, *commit_id_str = NULL;
7191 struct got_reference *ref = NULL;
7192 char *refname = NULL, *tagmsg = NULL;
7193 char *tagmsg_path = NULL, *tag_id_str = NULL;
7194 int preserve_tagmsg = 0;
7195 struct got_reflist_head refs;
7197 TAILQ_INIT(&refs);
7200 * Don't let the user create a tag name with a leading '-'.
7201 * While technically a valid reference name, this case is usually
7202 * an unintended typo.
7204 if (tag_name[0] == '-')
7205 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7207 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7208 if (err)
7209 goto done;
7211 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7212 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7213 if (err)
7214 goto done;
7216 err = got_object_id_str(&commit_id_str, commit_id);
7217 if (err)
7218 goto done;
7220 err = get_tag_refname(&refname, tag_name);
7221 if (err)
7222 goto done;
7223 if (strncmp("refs/tags/", tag_name, 10) == 0)
7224 tag_name += 10;
7226 err = got_ref_open(&ref, repo, refname, 0);
7227 if (err == NULL) {
7228 err = got_error(GOT_ERR_TAG_EXISTS);
7229 goto done;
7230 } else if (err->code != GOT_ERR_NOT_REF)
7231 goto done;
7233 if (tagmsg_arg == NULL) {
7234 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7235 tag_name, got_repo_get_path(repo));
7236 if (err) {
7237 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7238 tagmsg_path != NULL)
7239 preserve_tagmsg = 1;
7240 goto done;
7242 /* Editor is done; we can now apply unveil(2) */
7243 err = got_sigs_apply_unveil();
7244 if (err)
7245 goto done;
7246 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7247 if (err)
7248 goto done;
7251 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7252 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7253 verbosity);
7254 if (err) {
7255 if (tagmsg_path)
7256 preserve_tagmsg = 1;
7257 goto done;
7260 err = got_ref_alloc(&ref, refname, tag_id);
7261 if (err) {
7262 if (tagmsg_path)
7263 preserve_tagmsg = 1;
7264 goto done;
7267 err = got_ref_write(ref, repo);
7268 if (err) {
7269 if (tagmsg_path)
7270 preserve_tagmsg = 1;
7271 goto done;
7274 err = got_object_id_str(&tag_id_str, tag_id);
7275 if (err) {
7276 if (tagmsg_path)
7277 preserve_tagmsg = 1;
7278 goto done;
7280 printf("Created tag %s\n", tag_id_str);
7281 done:
7282 if (preserve_tagmsg) {
7283 fprintf(stderr, "%s: tag message preserved in %s\n",
7284 getprogname(), tagmsg_path);
7285 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7286 err = got_error_from_errno2("unlink", tagmsg_path);
7287 free(tag_id_str);
7288 if (ref)
7289 got_ref_close(ref);
7290 free(commit_id);
7291 free(commit_id_str);
7292 free(refname);
7293 free(tagmsg);
7294 free(tagmsg_path);
7295 got_ref_list_free(&refs);
7296 return err;
7299 static const struct got_error *
7300 cmd_tag(int argc, char *argv[])
7302 const struct got_error *error = NULL;
7303 struct got_repository *repo = NULL;
7304 struct got_worktree *worktree = NULL;
7305 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7306 char *gitconfig_path = NULL, *tagger = NULL;
7307 char *allowed_signers = NULL, *revoked_signers = NULL;
7308 char *signer_id = NULL;
7309 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7310 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7311 int *pack_fds = NULL;
7313 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7314 switch (ch) {
7315 case 'c':
7316 commit_id_arg = optarg;
7317 break;
7318 case 'm':
7319 tagmsg = optarg;
7320 break;
7321 case 'r':
7322 repo_path = realpath(optarg, NULL);
7323 if (repo_path == NULL) {
7324 error = got_error_from_errno2("realpath",
7325 optarg);
7326 goto done;
7328 got_path_strip_trailing_slashes(repo_path);
7329 break;
7330 case 'l':
7331 do_list = 1;
7332 break;
7333 case 's':
7334 signer_id = strdup(optarg);
7335 if (signer_id == NULL) {
7336 error = got_error_from_errno("strdup");
7337 goto done;
7339 break;
7340 case 'V':
7341 verify_tags = 1;
7342 break;
7343 case 'v':
7344 if (verbosity < 0)
7345 verbosity = 0;
7346 else if (verbosity < 3)
7347 verbosity++;
7348 break;
7349 default:
7350 usage_tag();
7351 /* NOTREACHED */
7355 argc -= optind;
7356 argv += optind;
7358 if (do_list || verify_tags) {
7359 if (commit_id_arg != NULL)
7360 errx(1,
7361 "-c option can only be used when creating a tag");
7362 if (tagmsg) {
7363 if (do_list)
7364 option_conflict('l', 'm');
7365 else
7366 option_conflict('V', 'm');
7368 if (signer_id) {
7369 if (do_list)
7370 option_conflict('l', 's');
7371 else
7372 option_conflict('V', 's');
7374 if (argc > 1)
7375 usage_tag();
7376 } else if (argc != 1)
7377 usage_tag();
7379 if (argc == 1)
7380 tag_name = argv[0];
7382 #ifndef PROFILE
7383 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7384 "sendfd unveil", NULL) == -1)
7385 err(1, "pledge");
7386 #endif
7387 cwd = getcwd(NULL, 0);
7388 if (cwd == NULL) {
7389 error = got_error_from_errno("getcwd");
7390 goto done;
7393 error = got_repo_pack_fds_open(&pack_fds);
7394 if (error != NULL)
7395 goto done;
7397 if (repo_path == NULL) {
7398 error = got_worktree_open(&worktree, cwd);
7399 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7400 goto done;
7401 else
7402 error = NULL;
7403 if (worktree) {
7404 repo_path =
7405 strdup(got_worktree_get_repo_path(worktree));
7406 if (repo_path == NULL)
7407 error = got_error_from_errno("strdup");
7408 if (error)
7409 goto done;
7410 } else {
7411 repo_path = strdup(cwd);
7412 if (repo_path == NULL) {
7413 error = got_error_from_errno("strdup");
7414 goto done;
7419 if (do_list || verify_tags) {
7420 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7421 if (error != NULL)
7422 goto done;
7423 error = get_allowed_signers(&allowed_signers, repo, worktree);
7424 if (error)
7425 goto done;
7426 error = get_revoked_signers(&revoked_signers, repo, worktree);
7427 if (error)
7428 goto done;
7429 if (worktree) {
7430 /* Release work tree lock. */
7431 got_worktree_close(worktree);
7432 worktree = NULL;
7436 * Remove "cpath" promise unless needed for signature tmpfile
7437 * creation.
7439 if (verify_tags)
7440 got_sigs_apply_unveil();
7441 else {
7442 #ifndef PROFILE
7443 if (pledge("stdio rpath wpath flock proc exec sendfd "
7444 "unveil", NULL) == -1)
7445 err(1, "pledge");
7446 #endif
7448 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7449 if (error)
7450 goto done;
7451 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7452 revoked_signers, verbosity);
7453 } else {
7454 error = get_gitconfig_path(&gitconfig_path);
7455 if (error)
7456 goto done;
7457 error = got_repo_open(&repo, repo_path, gitconfig_path,
7458 pack_fds);
7459 if (error != NULL)
7460 goto done;
7462 error = get_author(&tagger, repo, worktree);
7463 if (error)
7464 goto done;
7465 if (signer_id == NULL) {
7466 error = get_signer_id(&signer_id, repo, worktree);
7467 if (error)
7468 goto done;
7471 if (tagmsg) {
7472 if (signer_id) {
7473 error = got_sigs_apply_unveil();
7474 if (error)
7475 goto done;
7477 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7478 if (error)
7479 goto done;
7482 if (commit_id_arg == NULL) {
7483 struct got_reference *head_ref;
7484 struct got_object_id *commit_id;
7485 error = got_ref_open(&head_ref, repo,
7486 worktree ? got_worktree_get_head_ref_name(worktree)
7487 : GOT_REF_HEAD, 0);
7488 if (error)
7489 goto done;
7490 error = got_ref_resolve(&commit_id, repo, head_ref);
7491 got_ref_close(head_ref);
7492 if (error)
7493 goto done;
7494 error = got_object_id_str(&commit_id_str, commit_id);
7495 free(commit_id);
7496 if (error)
7497 goto done;
7500 if (worktree) {
7501 /* Release work tree lock. */
7502 got_worktree_close(worktree);
7503 worktree = NULL;
7506 error = add_tag(repo, tagger, tag_name,
7507 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7508 signer_id, verbosity);
7510 done:
7511 if (repo) {
7512 const struct got_error *close_err = got_repo_close(repo);
7513 if (error == NULL)
7514 error = close_err;
7516 if (worktree)
7517 got_worktree_close(worktree);
7518 if (pack_fds) {
7519 const struct got_error *pack_err =
7520 got_repo_pack_fds_close(pack_fds);
7521 if (error == NULL)
7522 error = pack_err;
7524 free(cwd);
7525 free(repo_path);
7526 free(gitconfig_path);
7527 free(commit_id_str);
7528 free(tagger);
7529 free(allowed_signers);
7530 free(revoked_signers);
7531 free(signer_id);
7532 return error;
7535 __dead static void
7536 usage_add(void)
7538 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7539 exit(1);
7542 static const struct got_error *
7543 add_progress(void *arg, unsigned char status, const char *path)
7545 while (path[0] == '/')
7546 path++;
7547 printf("%c %s\n", status, path);
7548 return NULL;
7551 static const struct got_error *
7552 cmd_add(int argc, char *argv[])
7554 const struct got_error *error = NULL;
7555 struct got_repository *repo = NULL;
7556 struct got_worktree *worktree = NULL;
7557 char *cwd = NULL;
7558 struct got_pathlist_head paths;
7559 struct got_pathlist_entry *pe;
7560 int ch, can_recurse = 0, no_ignores = 0;
7561 int *pack_fds = NULL;
7563 TAILQ_INIT(&paths);
7565 while ((ch = getopt(argc, argv, "IR")) != -1) {
7566 switch (ch) {
7567 case 'I':
7568 no_ignores = 1;
7569 break;
7570 case 'R':
7571 can_recurse = 1;
7572 break;
7573 default:
7574 usage_add();
7575 /* NOTREACHED */
7579 argc -= optind;
7580 argv += optind;
7582 #ifndef PROFILE
7583 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7584 NULL) == -1)
7585 err(1, "pledge");
7586 #endif
7587 if (argc < 1)
7588 usage_add();
7590 cwd = getcwd(NULL, 0);
7591 if (cwd == NULL) {
7592 error = got_error_from_errno("getcwd");
7593 goto done;
7596 error = got_repo_pack_fds_open(&pack_fds);
7597 if (error != NULL)
7598 goto done;
7600 error = got_worktree_open(&worktree, cwd);
7601 if (error) {
7602 if (error->code == GOT_ERR_NOT_WORKTREE)
7603 error = wrap_not_worktree_error(error, "add", cwd);
7604 goto done;
7607 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7608 NULL, pack_fds);
7609 if (error != NULL)
7610 goto done;
7612 error = apply_unveil(got_repo_get_path(repo), 1,
7613 got_worktree_get_root_path(worktree));
7614 if (error)
7615 goto done;
7617 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7618 if (error)
7619 goto done;
7621 if (!can_recurse) {
7622 char *ondisk_path;
7623 struct stat sb;
7624 TAILQ_FOREACH(pe, &paths, entry) {
7625 if (asprintf(&ondisk_path, "%s/%s",
7626 got_worktree_get_root_path(worktree),
7627 pe->path) == -1) {
7628 error = got_error_from_errno("asprintf");
7629 goto done;
7631 if (lstat(ondisk_path, &sb) == -1) {
7632 if (errno == ENOENT) {
7633 free(ondisk_path);
7634 continue;
7636 error = got_error_from_errno2("lstat",
7637 ondisk_path);
7638 free(ondisk_path);
7639 goto done;
7641 free(ondisk_path);
7642 if (S_ISDIR(sb.st_mode)) {
7643 error = got_error_msg(GOT_ERR_BAD_PATH,
7644 "adding directories requires -R option");
7645 goto done;
7650 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7651 NULL, repo, no_ignores);
7652 done:
7653 if (repo) {
7654 const struct got_error *close_err = got_repo_close(repo);
7655 if (error == NULL)
7656 error = close_err;
7658 if (worktree)
7659 got_worktree_close(worktree);
7660 if (pack_fds) {
7661 const struct got_error *pack_err =
7662 got_repo_pack_fds_close(pack_fds);
7663 if (error == NULL)
7664 error = pack_err;
7666 TAILQ_FOREACH(pe, &paths, entry)
7667 free((char *)pe->path);
7668 got_pathlist_free(&paths);
7669 free(cwd);
7670 return error;
7673 __dead static void
7674 usage_remove(void)
7676 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7677 getprogname());
7678 exit(1);
7681 static const struct got_error *
7682 print_remove_status(void *arg, unsigned char status,
7683 unsigned char staged_status, const char *path)
7685 while (path[0] == '/')
7686 path++;
7687 if (status == GOT_STATUS_NONEXISTENT)
7688 return NULL;
7689 if (status == staged_status && (status == GOT_STATUS_DELETE))
7690 status = GOT_STATUS_NO_CHANGE;
7691 printf("%c%c %s\n", status, staged_status, path);
7692 return NULL;
7695 static const struct got_error *
7696 cmd_remove(int argc, char *argv[])
7698 const struct got_error *error = NULL;
7699 struct got_worktree *worktree = NULL;
7700 struct got_repository *repo = NULL;
7701 const char *status_codes = NULL;
7702 char *cwd = NULL;
7703 struct got_pathlist_head paths;
7704 struct got_pathlist_entry *pe;
7705 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7706 int ignore_missing_paths = 0;
7707 int *pack_fds = NULL;
7709 TAILQ_INIT(&paths);
7711 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7712 switch (ch) {
7713 case 'f':
7714 delete_local_mods = 1;
7715 ignore_missing_paths = 1;
7716 break;
7717 case 'k':
7718 keep_on_disk = 1;
7719 break;
7720 case 'R':
7721 can_recurse = 1;
7722 break;
7723 case 's':
7724 for (i = 0; i < strlen(optarg); i++) {
7725 switch (optarg[i]) {
7726 case GOT_STATUS_MODIFY:
7727 delete_local_mods = 1;
7728 break;
7729 case GOT_STATUS_MISSING:
7730 ignore_missing_paths = 1;
7731 break;
7732 default:
7733 errx(1, "invalid status code '%c'",
7734 optarg[i]);
7737 status_codes = optarg;
7738 break;
7739 default:
7740 usage_remove();
7741 /* NOTREACHED */
7745 argc -= optind;
7746 argv += optind;
7748 #ifndef PROFILE
7749 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7750 NULL) == -1)
7751 err(1, "pledge");
7752 #endif
7753 if (argc < 1)
7754 usage_remove();
7756 cwd = getcwd(NULL, 0);
7757 if (cwd == NULL) {
7758 error = got_error_from_errno("getcwd");
7759 goto done;
7762 error = got_repo_pack_fds_open(&pack_fds);
7763 if (error != NULL)
7764 goto done;
7766 error = got_worktree_open(&worktree, cwd);
7767 if (error) {
7768 if (error->code == GOT_ERR_NOT_WORKTREE)
7769 error = wrap_not_worktree_error(error, "remove", cwd);
7770 goto done;
7773 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7774 NULL, pack_fds);
7775 if (error)
7776 goto done;
7778 error = apply_unveil(got_repo_get_path(repo), 1,
7779 got_worktree_get_root_path(worktree));
7780 if (error)
7781 goto done;
7783 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7784 if (error)
7785 goto done;
7787 if (!can_recurse) {
7788 char *ondisk_path;
7789 struct stat sb;
7790 TAILQ_FOREACH(pe, &paths, entry) {
7791 if (asprintf(&ondisk_path, "%s/%s",
7792 got_worktree_get_root_path(worktree),
7793 pe->path) == -1) {
7794 error = got_error_from_errno("asprintf");
7795 goto done;
7797 if (lstat(ondisk_path, &sb) == -1) {
7798 if (errno == ENOENT) {
7799 free(ondisk_path);
7800 continue;
7802 error = got_error_from_errno2("lstat",
7803 ondisk_path);
7804 free(ondisk_path);
7805 goto done;
7807 free(ondisk_path);
7808 if (S_ISDIR(sb.st_mode)) {
7809 error = got_error_msg(GOT_ERR_BAD_PATH,
7810 "removing directories requires -R option");
7811 goto done;
7816 error = got_worktree_schedule_delete(worktree, &paths,
7817 delete_local_mods, status_codes, print_remove_status, NULL,
7818 repo, keep_on_disk, ignore_missing_paths);
7819 done:
7820 if (repo) {
7821 const struct got_error *close_err = got_repo_close(repo);
7822 if (error == NULL)
7823 error = close_err;
7825 if (worktree)
7826 got_worktree_close(worktree);
7827 if (pack_fds) {
7828 const struct got_error *pack_err =
7829 got_repo_pack_fds_close(pack_fds);
7830 if (error == NULL)
7831 error = pack_err;
7833 TAILQ_FOREACH(pe, &paths, entry)
7834 free((char *)pe->path);
7835 got_pathlist_free(&paths);
7836 free(cwd);
7837 return error;
7840 __dead static void
7841 usage_patch(void)
7843 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7844 "[patchfile]\n", getprogname());
7845 exit(1);
7848 static const struct got_error *
7849 patch_from_stdin(int *patchfd)
7851 const struct got_error *err = NULL;
7852 ssize_t r;
7853 char *path, buf[BUFSIZ];
7854 sig_t sighup, sigint, sigquit;
7856 err = got_opentemp_named_fd(&path, patchfd,
7857 GOT_TMPDIR_STR "/got-patch");
7858 if (err)
7859 return err;
7860 unlink(path);
7861 free(path);
7863 sighup = signal(SIGHUP, SIG_DFL);
7864 sigint = signal(SIGINT, SIG_DFL);
7865 sigquit = signal(SIGQUIT, SIG_DFL);
7867 for (;;) {
7868 r = read(0, buf, sizeof(buf));
7869 if (r == -1) {
7870 err = got_error_from_errno("read");
7871 break;
7873 if (r == 0)
7874 break;
7875 if (write(*patchfd, buf, r) == -1) {
7876 err = got_error_from_errno("write");
7877 break;
7881 signal(SIGHUP, sighup);
7882 signal(SIGINT, sigint);
7883 signal(SIGQUIT, sigquit);
7885 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7886 err = got_error_from_errno("lseek");
7888 if (err != NULL) {
7889 close(*patchfd);
7890 *patchfd = -1;
7893 return err;
7896 static const struct got_error *
7897 patch_progress(void *arg, const char *old, const char *new,
7898 unsigned char status, const struct got_error *error, int old_from,
7899 int old_lines, int new_from, int new_lines, int offset,
7900 int ws_mangled, const struct got_error *hunk_err)
7902 const char *path = new == NULL ? old : new;
7904 while (*path == '/')
7905 path++;
7907 if (status != 0)
7908 printf("%c %s\n", status, path);
7910 if (error != NULL)
7911 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7913 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7914 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7915 old_lines, new_from, new_lines);
7916 if (hunk_err != NULL)
7917 printf("%s\n", hunk_err->msg);
7918 else if (offset != 0)
7919 printf("applied with offset %d\n", offset);
7920 else
7921 printf("hunk contains mangled whitespace\n");
7924 return NULL;
7927 static const struct got_error *
7928 cmd_patch(int argc, char *argv[])
7930 const struct got_error *error = NULL, *close_error = NULL;
7931 struct got_worktree *worktree = NULL;
7932 struct got_repository *repo = NULL;
7933 struct got_reflist_head refs;
7934 struct got_object_id *commit_id = NULL;
7935 const char *commit_id_str = NULL;
7936 struct stat sb;
7937 const char *errstr;
7938 char *cwd = NULL;
7939 int ch, nop = 0, strip = -1, reverse = 0;
7940 int patchfd;
7941 int *pack_fds = NULL;
7943 TAILQ_INIT(&refs);
7945 #ifndef PROFILE
7946 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7947 "unveil", NULL) == -1)
7948 err(1, "pledge");
7949 #endif
7951 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7952 switch (ch) {
7953 case 'c':
7954 commit_id_str = optarg;
7955 break;
7956 case 'n':
7957 nop = 1;
7958 break;
7959 case 'p':
7960 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7961 if (errstr != NULL)
7962 errx(1, "pathname strip count is %s: %s",
7963 errstr, optarg);
7964 break;
7965 case 'R':
7966 reverse = 1;
7967 break;
7968 default:
7969 usage_patch();
7970 /* NOTREACHED */
7974 argc -= optind;
7975 argv += optind;
7977 if (argc == 0) {
7978 error = patch_from_stdin(&patchfd);
7979 if (error)
7980 return error;
7981 } else if (argc == 1) {
7982 patchfd = open(argv[0], O_RDONLY);
7983 if (patchfd == -1) {
7984 error = got_error_from_errno2("open", argv[0]);
7985 return error;
7987 if (fstat(patchfd, &sb) == -1) {
7988 error = got_error_from_errno2("fstat", argv[0]);
7989 goto done;
7991 if (!S_ISREG(sb.st_mode)) {
7992 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
7993 goto done;
7995 } else
7996 usage_patch();
7998 if ((cwd = getcwd(NULL, 0)) == NULL) {
7999 error = got_error_from_errno("getcwd");
8000 goto done;
8003 error = got_repo_pack_fds_open(&pack_fds);
8004 if (error != NULL)
8005 goto done;
8007 error = got_worktree_open(&worktree, cwd);
8008 if (error != NULL)
8009 goto done;
8011 const char *repo_path = got_worktree_get_repo_path(worktree);
8012 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8013 if (error != NULL)
8014 goto done;
8016 error = apply_unveil(got_repo_get_path(repo), 0,
8017 got_worktree_get_root_path(worktree));
8018 if (error != NULL)
8019 goto done;
8021 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8022 if (error)
8023 goto done;
8025 if (commit_id_str != NULL) {
8026 error = got_repo_match_object_id(&commit_id, NULL,
8027 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8028 if (error)
8029 goto done;
8032 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8033 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8035 done:
8036 got_ref_list_free(&refs);
8037 free(commit_id);
8038 if (repo) {
8039 close_error = got_repo_close(repo);
8040 if (error == NULL)
8041 error = close_error;
8043 if (worktree != NULL) {
8044 close_error = got_worktree_close(worktree);
8045 if (error == NULL)
8046 error = close_error;
8048 if (pack_fds) {
8049 const struct got_error *pack_err =
8050 got_repo_pack_fds_close(pack_fds);
8051 if (error == NULL)
8052 error = pack_err;
8054 free(cwd);
8055 return error;
8058 __dead static void
8059 usage_revert(void)
8061 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8062 getprogname());
8063 exit(1);
8066 static const struct got_error *
8067 revert_progress(void *arg, unsigned char status, const char *path)
8069 if (status == GOT_STATUS_UNVERSIONED)
8070 return NULL;
8072 while (path[0] == '/')
8073 path++;
8074 printf("%c %s\n", status, path);
8075 return NULL;
8078 struct choose_patch_arg {
8079 FILE *patch_script_file;
8080 const char *action;
8083 static const struct got_error *
8084 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8085 int nchanges, const char *action)
8087 const struct got_error *err;
8088 char *line = NULL;
8089 size_t linesize = 0;
8090 ssize_t linelen;
8092 switch (status) {
8093 case GOT_STATUS_ADD:
8094 printf("A %s\n%s this addition? [y/n] ", path, action);
8095 break;
8096 case GOT_STATUS_DELETE:
8097 printf("D %s\n%s this deletion? [y/n] ", path, action);
8098 break;
8099 case GOT_STATUS_MODIFY:
8100 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8101 return got_error_from_errno("fseek");
8102 printf(GOT_COMMIT_SEP_STR);
8103 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8104 printf("%s", line);
8105 if (linelen == -1 && ferror(patch_file)) {
8106 err = got_error_from_errno("getline");
8107 free(line);
8108 return err;
8110 free(line);
8111 printf(GOT_COMMIT_SEP_STR);
8112 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8113 path, n, nchanges, action);
8114 break;
8115 default:
8116 return got_error_path(path, GOT_ERR_FILE_STATUS);
8119 fflush(stdout);
8120 return NULL;
8123 static const struct got_error *
8124 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8125 FILE *patch_file, int n, int nchanges)
8127 const struct got_error *err = NULL;
8128 char *line = NULL;
8129 size_t linesize = 0;
8130 ssize_t linelen;
8131 int resp = ' ';
8132 struct choose_patch_arg *a = arg;
8134 *choice = GOT_PATCH_CHOICE_NONE;
8136 if (a->patch_script_file) {
8137 char *nl;
8138 err = show_change(status, path, patch_file, n, nchanges,
8139 a->action);
8140 if (err)
8141 return err;
8142 linelen = getline(&line, &linesize, a->patch_script_file);
8143 if (linelen == -1) {
8144 if (ferror(a->patch_script_file))
8145 return got_error_from_errno("getline");
8146 return NULL;
8148 nl = strchr(line, '\n');
8149 if (nl)
8150 *nl = '\0';
8151 if (strcmp(line, "y") == 0) {
8152 *choice = GOT_PATCH_CHOICE_YES;
8153 printf("y\n");
8154 } else if (strcmp(line, "n") == 0) {
8155 *choice = GOT_PATCH_CHOICE_NO;
8156 printf("n\n");
8157 } else if (strcmp(line, "q") == 0 &&
8158 status == GOT_STATUS_MODIFY) {
8159 *choice = GOT_PATCH_CHOICE_QUIT;
8160 printf("q\n");
8161 } else
8162 printf("invalid response '%s'\n", line);
8163 free(line);
8164 return NULL;
8167 while (resp != 'y' && resp != 'n' && resp != 'q') {
8168 err = show_change(status, path, patch_file, n, nchanges,
8169 a->action);
8170 if (err)
8171 return err;
8172 resp = getchar();
8173 if (resp == '\n')
8174 resp = getchar();
8175 if (status == GOT_STATUS_MODIFY) {
8176 if (resp != 'y' && resp != 'n' && resp != 'q') {
8177 printf("invalid response '%c'\n", resp);
8178 resp = ' ';
8180 } else if (resp != 'y' && resp != 'n') {
8181 printf("invalid response '%c'\n", resp);
8182 resp = ' ';
8186 if (resp == 'y')
8187 *choice = GOT_PATCH_CHOICE_YES;
8188 else if (resp == 'n')
8189 *choice = GOT_PATCH_CHOICE_NO;
8190 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8191 *choice = GOT_PATCH_CHOICE_QUIT;
8193 return NULL;
8196 static const struct got_error *
8197 cmd_revert(int argc, char *argv[])
8199 const struct got_error *error = NULL;
8200 struct got_worktree *worktree = NULL;
8201 struct got_repository *repo = NULL;
8202 char *cwd = NULL, *path = NULL;
8203 struct got_pathlist_head paths;
8204 struct got_pathlist_entry *pe;
8205 int ch, can_recurse = 0, pflag = 0;
8206 FILE *patch_script_file = NULL;
8207 const char *patch_script_path = NULL;
8208 struct choose_patch_arg cpa;
8209 int *pack_fds = NULL;
8211 TAILQ_INIT(&paths);
8213 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8214 switch (ch) {
8215 case 'p':
8216 pflag = 1;
8217 break;
8218 case 'F':
8219 patch_script_path = optarg;
8220 break;
8221 case 'R':
8222 can_recurse = 1;
8223 break;
8224 default:
8225 usage_revert();
8226 /* NOTREACHED */
8230 argc -= optind;
8231 argv += optind;
8233 #ifndef PROFILE
8234 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8235 "unveil", NULL) == -1)
8236 err(1, "pledge");
8237 #endif
8238 if (argc < 1)
8239 usage_revert();
8240 if (patch_script_path && !pflag)
8241 errx(1, "-F option can only be used together with -p option");
8243 cwd = getcwd(NULL, 0);
8244 if (cwd == NULL) {
8245 error = got_error_from_errno("getcwd");
8246 goto done;
8249 error = got_repo_pack_fds_open(&pack_fds);
8250 if (error != NULL)
8251 goto done;
8253 error = got_worktree_open(&worktree, cwd);
8254 if (error) {
8255 if (error->code == GOT_ERR_NOT_WORKTREE)
8256 error = wrap_not_worktree_error(error, "revert", cwd);
8257 goto done;
8260 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8261 NULL, pack_fds);
8262 if (error != NULL)
8263 goto done;
8265 if (patch_script_path) {
8266 patch_script_file = fopen(patch_script_path, "re");
8267 if (patch_script_file == NULL) {
8268 error = got_error_from_errno2("fopen",
8269 patch_script_path);
8270 goto done;
8273 error = apply_unveil(got_repo_get_path(repo), 1,
8274 got_worktree_get_root_path(worktree));
8275 if (error)
8276 goto done;
8278 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8279 if (error)
8280 goto done;
8282 if (!can_recurse) {
8283 char *ondisk_path;
8284 struct stat sb;
8285 TAILQ_FOREACH(pe, &paths, entry) {
8286 if (asprintf(&ondisk_path, "%s/%s",
8287 got_worktree_get_root_path(worktree),
8288 pe->path) == -1) {
8289 error = got_error_from_errno("asprintf");
8290 goto done;
8292 if (lstat(ondisk_path, &sb) == -1) {
8293 if (errno == ENOENT) {
8294 free(ondisk_path);
8295 continue;
8297 error = got_error_from_errno2("lstat",
8298 ondisk_path);
8299 free(ondisk_path);
8300 goto done;
8302 free(ondisk_path);
8303 if (S_ISDIR(sb.st_mode)) {
8304 error = got_error_msg(GOT_ERR_BAD_PATH,
8305 "reverting directories requires -R option");
8306 goto done;
8311 cpa.patch_script_file = patch_script_file;
8312 cpa.action = "revert";
8313 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8314 pflag ? choose_patch : NULL, &cpa, repo);
8315 done:
8316 if (patch_script_file && fclose(patch_script_file) == EOF &&
8317 error == NULL)
8318 error = got_error_from_errno2("fclose", patch_script_path);
8319 if (repo) {
8320 const struct got_error *close_err = got_repo_close(repo);
8321 if (error == NULL)
8322 error = close_err;
8324 if (worktree)
8325 got_worktree_close(worktree);
8326 if (pack_fds) {
8327 const struct got_error *pack_err =
8328 got_repo_pack_fds_close(pack_fds);
8329 if (error == NULL)
8330 error = pack_err;
8332 free(path);
8333 free(cwd);
8334 return error;
8337 __dead static void
8338 usage_commit(void)
8340 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8341 "[-m message] [path ...]\n", getprogname());
8342 exit(1);
8345 struct collect_commit_logmsg_arg {
8346 const char *cmdline_log;
8347 const char *prepared_log;
8348 int non_interactive;
8349 const char *editor;
8350 const char *worktree_path;
8351 const char *branch_name;
8352 const char *repo_path;
8353 char *logmsg_path;
8357 static const struct got_error *
8358 read_prepared_logmsg(char **logmsg, const char *path)
8360 const struct got_error *err = NULL;
8361 FILE *f = NULL;
8362 struct stat sb;
8363 size_t r;
8365 *logmsg = NULL;
8366 memset(&sb, 0, sizeof(sb));
8368 f = fopen(path, "re");
8369 if (f == NULL)
8370 return got_error_from_errno2("fopen", path);
8372 if (fstat(fileno(f), &sb) == -1) {
8373 err = got_error_from_errno2("fstat", path);
8374 goto done;
8376 if (sb.st_size == 0) {
8377 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8378 goto done;
8381 *logmsg = malloc(sb.st_size + 1);
8382 if (*logmsg == NULL) {
8383 err = got_error_from_errno("malloc");
8384 goto done;
8387 r = fread(*logmsg, 1, sb.st_size, f);
8388 if (r != sb.st_size) {
8389 if (ferror(f))
8390 err = got_error_from_errno2("fread", path);
8391 else
8392 err = got_error(GOT_ERR_IO);
8393 goto done;
8395 (*logmsg)[sb.st_size] = '\0';
8396 done:
8397 if (fclose(f) == EOF && err == NULL)
8398 err = got_error_from_errno2("fclose", path);
8399 if (err) {
8400 free(*logmsg);
8401 *logmsg = NULL;
8403 return err;
8406 static const struct got_error *
8407 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8408 void *arg)
8410 char *initial_content = NULL;
8411 struct got_pathlist_entry *pe;
8412 const struct got_error *err = NULL;
8413 char *template = NULL;
8414 struct collect_commit_logmsg_arg *a = arg;
8415 int initial_content_len;
8416 int fd = -1;
8417 size_t len;
8419 /* if a message was specified on the command line, just use it */
8420 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8421 len = strlen(a->cmdline_log) + 1;
8422 *logmsg = malloc(len + 1);
8423 if (*logmsg == NULL)
8424 return got_error_from_errno("malloc");
8425 strlcpy(*logmsg, a->cmdline_log, len);
8426 return NULL;
8427 } else if (a->prepared_log != NULL && a->non_interactive)
8428 return read_prepared_logmsg(logmsg, a->prepared_log);
8430 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8431 return got_error_from_errno("asprintf");
8433 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8434 if (err)
8435 goto done;
8437 if (a->prepared_log) {
8438 char *msg;
8439 err = read_prepared_logmsg(&msg, a->prepared_log);
8440 if (err)
8441 goto done;
8442 if (write(fd, msg, strlen(msg)) == -1) {
8443 err = got_error_from_errno2("write", a->logmsg_path);
8444 free(msg);
8445 goto done;
8447 free(msg);
8450 initial_content_len = asprintf(&initial_content,
8451 "\n# changes to be committed on branch %s:\n",
8452 a->branch_name);
8453 if (initial_content_len == -1) {
8454 err = got_error_from_errno("asprintf");
8455 goto done;
8458 if (write(fd, initial_content, initial_content_len) == -1) {
8459 err = got_error_from_errno2("write", a->logmsg_path);
8460 goto done;
8463 TAILQ_FOREACH(pe, commitable_paths, entry) {
8464 struct got_commitable *ct = pe->data;
8465 dprintf(fd, "# %c %s\n",
8466 got_commitable_get_status(ct),
8467 got_commitable_get_path(ct));
8470 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8471 initial_content_len, a->prepared_log ? 0 : 1);
8472 done:
8473 free(initial_content);
8474 free(template);
8476 if (fd != -1 && close(fd) == -1 && err == NULL)
8477 err = got_error_from_errno2("close", a->logmsg_path);
8479 /* Editor is done; we can now apply unveil(2) */
8480 if (err == NULL)
8481 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8482 if (err) {
8483 free(*logmsg);
8484 *logmsg = NULL;
8486 return err;
8489 static const struct got_error *
8490 cmd_commit(int argc, char *argv[])
8492 const struct got_error *error = NULL;
8493 struct got_worktree *worktree = NULL;
8494 struct got_repository *repo = NULL;
8495 char *cwd = NULL, *id_str = NULL;
8496 struct got_object_id *id = NULL;
8497 const char *logmsg = NULL;
8498 char *prepared_logmsg = NULL;
8499 struct collect_commit_logmsg_arg cl_arg;
8500 const char *author = NULL;
8501 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8502 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8503 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8504 struct got_pathlist_head paths;
8505 int *pack_fds = NULL;
8507 TAILQ_INIT(&paths);
8508 cl_arg.logmsg_path = NULL;
8510 while ((ch = getopt(argc, argv, "A:F:m:NS")) != -1) {
8511 switch (ch) {
8512 case 'A':
8513 author = optarg;
8514 error = valid_author(author);
8515 if (error)
8516 return error;
8517 break;
8518 case 'F':
8519 if (logmsg != NULL)
8520 option_conflict('F', 'm');
8521 prepared_logmsg = realpath(optarg, NULL);
8522 if (prepared_logmsg == NULL)
8523 return got_error_from_errno2("realpath",
8524 optarg);
8525 break;
8526 case 'm':
8527 if (prepared_logmsg)
8528 option_conflict('m', 'F');
8529 logmsg = optarg;
8530 break;
8531 case 'N':
8532 non_interactive = 1;
8533 break;
8534 case 'S':
8535 allow_bad_symlinks = 1;
8536 break;
8537 default:
8538 usage_commit();
8539 /* NOTREACHED */
8543 argc -= optind;
8544 argv += optind;
8546 #ifndef PROFILE
8547 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8548 "unveil", NULL) == -1)
8549 err(1, "pledge");
8550 #endif
8551 cwd = getcwd(NULL, 0);
8552 if (cwd == NULL) {
8553 error = got_error_from_errno("getcwd");
8554 goto done;
8557 error = got_repo_pack_fds_open(&pack_fds);
8558 if (error != NULL)
8559 goto done;
8561 error = got_worktree_open(&worktree, cwd);
8562 if (error) {
8563 if (error->code == GOT_ERR_NOT_WORKTREE)
8564 error = wrap_not_worktree_error(error, "commit", cwd);
8565 goto done;
8568 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8569 if (error)
8570 goto done;
8571 if (rebase_in_progress) {
8572 error = got_error(GOT_ERR_REBASING);
8573 goto done;
8576 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8577 worktree);
8578 if (error)
8579 goto done;
8581 error = get_gitconfig_path(&gitconfig_path);
8582 if (error)
8583 goto done;
8584 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8585 gitconfig_path, pack_fds);
8586 if (error != NULL)
8587 goto done;
8589 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8590 if (error)
8591 goto done;
8592 if (merge_in_progress) {
8593 error = got_error(GOT_ERR_MERGE_BUSY);
8594 goto done;
8597 error = get_author(&committer, repo, worktree);
8598 if (error)
8599 goto done;
8601 if (author != NULL && !strcmp(committer, author)) {
8602 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8603 goto done;
8606 if (author == NULL)
8607 author = committer;
8610 * unveil(2) traverses exec(2); if an editor is used we have
8611 * to apply unveil after the log message has been written.
8613 if (logmsg == NULL || strlen(logmsg) == 0)
8614 error = get_editor(&editor);
8615 else
8616 error = apply_unveil(got_repo_get_path(repo), 0,
8617 got_worktree_get_root_path(worktree));
8618 if (error)
8619 goto done;
8621 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8622 if (error)
8623 goto done;
8625 cl_arg.editor = editor;
8626 cl_arg.cmdline_log = logmsg;
8627 cl_arg.prepared_log = prepared_logmsg;
8628 cl_arg.non_interactive = non_interactive;
8629 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8630 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8631 if (!histedit_in_progress) {
8632 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8633 error = got_error(GOT_ERR_COMMIT_BRANCH);
8634 goto done;
8636 cl_arg.branch_name += 11;
8638 cl_arg.repo_path = got_repo_get_path(repo);
8639 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8640 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8641 print_status, NULL, repo);
8642 if (error) {
8643 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8644 cl_arg.logmsg_path != NULL)
8645 preserve_logmsg = 1;
8646 goto done;
8649 error = got_object_id_str(&id_str, id);
8650 if (error)
8651 goto done;
8652 printf("Created commit %s\n", id_str);
8653 done:
8654 if (preserve_logmsg) {
8655 fprintf(stderr, "%s: log message preserved in %s\n",
8656 getprogname(), cl_arg.logmsg_path);
8657 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8658 error == NULL)
8659 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8660 free(cl_arg.logmsg_path);
8661 if (repo) {
8662 const struct got_error *close_err = got_repo_close(repo);
8663 if (error == NULL)
8664 error = close_err;
8666 if (worktree)
8667 got_worktree_close(worktree);
8668 if (pack_fds) {
8669 const struct got_error *pack_err =
8670 got_repo_pack_fds_close(pack_fds);
8671 if (error == NULL)
8672 error = pack_err;
8674 free(cwd);
8675 free(id_str);
8676 free(gitconfig_path);
8677 free(editor);
8678 free(committer);
8679 free(prepared_logmsg);
8680 return error;
8683 __dead static void
8684 usage_send(void)
8686 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8687 "[-r repository-path] [-t tag] [remote-repository]\n",
8688 getprogname());
8689 exit(1);
8692 static void
8693 print_load_info(int print_colored, int print_found, int print_trees,
8694 int ncolored, int nfound, int ntrees)
8696 if (print_colored) {
8697 printf("%d commit%s colored", ncolored,
8698 ncolored == 1 ? "" : "s");
8700 if (print_found) {
8701 printf("%s%d object%s found",
8702 ncolored > 0 ? "; " : "",
8703 nfound, nfound == 1 ? "" : "s");
8705 if (print_trees) {
8706 printf("; %d tree%s scanned", ntrees,
8707 ntrees == 1 ? "" : "s");
8711 struct got_send_progress_arg {
8712 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8713 int verbosity;
8714 int last_ncolored;
8715 int last_nfound;
8716 int last_ntrees;
8717 int loading_done;
8718 int last_ncommits;
8719 int last_nobj_total;
8720 int last_p_deltify;
8721 int last_p_written;
8722 int last_p_sent;
8723 int printed_something;
8724 int sent_something;
8725 struct got_pathlist_head *delete_branches;
8728 static const struct got_error *
8729 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8730 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8731 int nobj_written, off_t bytes_sent, const char *refname, int success)
8733 struct got_send_progress_arg *a = arg;
8734 char scaled_packsize[FMT_SCALED_STRSIZE];
8735 char scaled_sent[FMT_SCALED_STRSIZE];
8736 int p_deltify = 0, p_written = 0, p_sent = 0;
8737 int print_colored = 0, print_found = 0, print_trees = 0;
8738 int print_searching = 0, print_total = 0;
8739 int print_deltify = 0, print_written = 0, print_sent = 0;
8741 if (a->verbosity < 0)
8742 return NULL;
8744 if (refname) {
8745 const char *status = success ? "accepted" : "rejected";
8747 if (success) {
8748 struct got_pathlist_entry *pe;
8749 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8750 const char *branchname = pe->path;
8751 if (got_path_cmp(branchname, refname,
8752 strlen(branchname), strlen(refname)) == 0) {
8753 status = "deleted";
8754 a->sent_something = 1;
8755 break;
8760 if (a->printed_something)
8761 putchar('\n');
8762 printf("Server has %s %s", status, refname);
8763 a->printed_something = 1;
8764 return NULL;
8767 if (a->last_ncolored != ncolored) {
8768 print_colored = 1;
8769 a->last_ncolored = ncolored;
8772 if (a->last_nfound != nfound) {
8773 print_colored = 1;
8774 print_found = 1;
8775 a->last_nfound = nfound;
8778 if (a->last_ntrees != ntrees) {
8779 print_colored = 1;
8780 print_found = 1;
8781 print_trees = 1;
8782 a->last_ntrees = ntrees;
8785 if ((print_colored || print_found || print_trees) &&
8786 !a->loading_done) {
8787 printf("\r");
8788 print_load_info(print_colored, print_found, print_trees,
8789 ncolored, nfound, ntrees);
8790 a->printed_something = 1;
8791 fflush(stdout);
8792 return NULL;
8793 } else if (!a->loading_done) {
8794 printf("\r");
8795 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8796 printf("\n");
8797 a->loading_done = 1;
8800 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8801 return got_error_from_errno("fmt_scaled");
8802 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8803 return got_error_from_errno("fmt_scaled");
8805 if (a->last_ncommits != ncommits) {
8806 print_searching = 1;
8807 a->last_ncommits = ncommits;
8810 if (a->last_nobj_total != nobj_total) {
8811 print_searching = 1;
8812 print_total = 1;
8813 a->last_nobj_total = nobj_total;
8816 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8817 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8818 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8819 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8820 return got_error(GOT_ERR_NO_SPACE);
8823 if (nobj_deltify > 0 || nobj_written > 0) {
8824 if (nobj_deltify > 0) {
8825 p_deltify = (nobj_deltify * 100) / nobj_total;
8826 if (p_deltify != a->last_p_deltify) {
8827 a->last_p_deltify = p_deltify;
8828 print_searching = 1;
8829 print_total = 1;
8830 print_deltify = 1;
8833 if (nobj_written > 0) {
8834 p_written = (nobj_written * 100) / nobj_total;
8835 if (p_written != a->last_p_written) {
8836 a->last_p_written = p_written;
8837 print_searching = 1;
8838 print_total = 1;
8839 print_deltify = 1;
8840 print_written = 1;
8845 if (bytes_sent > 0) {
8846 p_sent = (bytes_sent * 100) / packfile_size;
8847 if (p_sent != a->last_p_sent) {
8848 a->last_p_sent = p_sent;
8849 print_searching = 1;
8850 print_total = 1;
8851 print_deltify = 1;
8852 print_written = 1;
8853 print_sent = 1;
8855 a->sent_something = 1;
8858 if (print_searching || print_total || print_deltify || print_written ||
8859 print_sent)
8860 printf("\r");
8861 if (print_searching)
8862 printf("packing %d reference%s", ncommits,
8863 ncommits == 1 ? "" : "s");
8864 if (print_total)
8865 printf("; %d object%s", nobj_total,
8866 nobj_total == 1 ? "" : "s");
8867 if (print_deltify)
8868 printf("; deltify: %d%%", p_deltify);
8869 if (print_sent)
8870 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8871 scaled_packsize, p_sent);
8872 else if (print_written)
8873 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8874 scaled_packsize, p_written);
8875 if (print_searching || print_total || print_deltify ||
8876 print_written || print_sent) {
8877 a->printed_something = 1;
8878 fflush(stdout);
8880 return NULL;
8883 static const struct got_error *
8884 cmd_send(int argc, char *argv[])
8886 const struct got_error *error = NULL;
8887 char *cwd = NULL, *repo_path = NULL;
8888 const char *remote_name;
8889 char *proto = NULL, *host = NULL, *port = NULL;
8890 char *repo_name = NULL, *server_path = NULL;
8891 const struct got_remote_repo *remotes, *remote = NULL;
8892 int nremotes, nbranches = 0, ndelete_branches = 0;
8893 struct got_repository *repo = NULL;
8894 struct got_worktree *worktree = NULL;
8895 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8896 struct got_pathlist_head branches;
8897 struct got_pathlist_head tags;
8898 struct got_reflist_head all_branches;
8899 struct got_reflist_head all_tags;
8900 struct got_pathlist_head delete_args;
8901 struct got_pathlist_head delete_branches;
8902 struct got_reflist_entry *re;
8903 struct got_pathlist_entry *pe;
8904 int i, ch, sendfd = -1, sendstatus;
8905 pid_t sendpid = -1;
8906 struct got_send_progress_arg spa;
8907 int verbosity = 0, overwrite_refs = 0;
8908 int send_all_branches = 0, send_all_tags = 0;
8909 struct got_reference *ref = NULL;
8910 int *pack_fds = NULL;
8912 TAILQ_INIT(&branches);
8913 TAILQ_INIT(&tags);
8914 TAILQ_INIT(&all_branches);
8915 TAILQ_INIT(&all_tags);
8916 TAILQ_INIT(&delete_args);
8917 TAILQ_INIT(&delete_branches);
8919 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8920 switch (ch) {
8921 case 'a':
8922 send_all_branches = 1;
8923 break;
8924 case 'b':
8925 error = got_pathlist_append(&branches, optarg, NULL);
8926 if (error)
8927 return error;
8928 nbranches++;
8929 break;
8930 case 'd':
8931 error = got_pathlist_append(&delete_args, optarg, NULL);
8932 if (error)
8933 return error;
8934 break;
8935 case 'f':
8936 overwrite_refs = 1;
8937 break;
8938 case 'r':
8939 repo_path = realpath(optarg, NULL);
8940 if (repo_path == NULL)
8941 return got_error_from_errno2("realpath",
8942 optarg);
8943 got_path_strip_trailing_slashes(repo_path);
8944 break;
8945 case 't':
8946 error = got_pathlist_append(&tags, optarg, NULL);
8947 if (error)
8948 return error;
8949 break;
8950 case 'T':
8951 send_all_tags = 1;
8952 break;
8953 case 'v':
8954 if (verbosity < 0)
8955 verbosity = 0;
8956 else if (verbosity < 3)
8957 verbosity++;
8958 break;
8959 case 'q':
8960 verbosity = -1;
8961 break;
8962 default:
8963 usage_send();
8964 /* NOTREACHED */
8967 argc -= optind;
8968 argv += optind;
8970 if (send_all_branches && !TAILQ_EMPTY(&branches))
8971 option_conflict('a', 'b');
8972 if (send_all_tags && !TAILQ_EMPTY(&tags))
8973 option_conflict('T', 't');
8976 if (argc == 0)
8977 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8978 else if (argc == 1)
8979 remote_name = argv[0];
8980 else
8981 usage_send();
8983 cwd = getcwd(NULL, 0);
8984 if (cwd == NULL) {
8985 error = got_error_from_errno("getcwd");
8986 goto done;
8989 error = got_repo_pack_fds_open(&pack_fds);
8990 if (error != NULL)
8991 goto done;
8993 if (repo_path == NULL) {
8994 error = got_worktree_open(&worktree, cwd);
8995 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8996 goto done;
8997 else
8998 error = NULL;
8999 if (worktree) {
9000 repo_path =
9001 strdup(got_worktree_get_repo_path(worktree));
9002 if (repo_path == NULL)
9003 error = got_error_from_errno("strdup");
9004 if (error)
9005 goto done;
9006 } else {
9007 repo_path = strdup(cwd);
9008 if (repo_path == NULL) {
9009 error = got_error_from_errno("strdup");
9010 goto done;
9015 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9016 if (error)
9017 goto done;
9019 if (worktree) {
9020 worktree_conf = got_worktree_get_gotconfig(worktree);
9021 if (worktree_conf) {
9022 got_gotconfig_get_remotes(&nremotes, &remotes,
9023 worktree_conf);
9024 for (i = 0; i < nremotes; i++) {
9025 if (strcmp(remotes[i].name, remote_name) == 0) {
9026 remote = &remotes[i];
9027 break;
9032 if (remote == NULL) {
9033 repo_conf = got_repo_get_gotconfig(repo);
9034 if (repo_conf) {
9035 got_gotconfig_get_remotes(&nremotes, &remotes,
9036 repo_conf);
9037 for (i = 0; i < nremotes; i++) {
9038 if (strcmp(remotes[i].name, remote_name) == 0) {
9039 remote = &remotes[i];
9040 break;
9045 if (remote == NULL) {
9046 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9047 for (i = 0; i < nremotes; i++) {
9048 if (strcmp(remotes[i].name, remote_name) == 0) {
9049 remote = &remotes[i];
9050 break;
9054 if (remote == NULL) {
9055 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9056 goto done;
9059 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9060 &repo_name, remote->send_url);
9061 if (error)
9062 goto done;
9064 if (strcmp(proto, "git") == 0) {
9065 #ifndef PROFILE
9066 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9067 "sendfd dns inet unveil", NULL) == -1)
9068 err(1, "pledge");
9069 #endif
9070 } else if (strcmp(proto, "git+ssh") == 0 ||
9071 strcmp(proto, "ssh") == 0) {
9072 #ifndef PROFILE
9073 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9074 "sendfd unveil", NULL) == -1)
9075 err(1, "pledge");
9076 #endif
9077 } else if (strcmp(proto, "http") == 0 ||
9078 strcmp(proto, "git+http") == 0) {
9079 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9080 goto done;
9081 } else {
9082 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9083 goto done;
9086 error = got_dial_apply_unveil(proto);
9087 if (error)
9088 goto done;
9090 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9091 if (error)
9092 goto done;
9094 if (send_all_branches) {
9095 error = got_ref_list(&all_branches, repo, "refs/heads",
9096 got_ref_cmp_by_name, NULL);
9097 if (error)
9098 goto done;
9099 TAILQ_FOREACH(re, &all_branches, entry) {
9100 const char *branchname = got_ref_get_name(re->ref);
9101 error = got_pathlist_append(&branches,
9102 branchname, NULL);
9103 if (error)
9104 goto done;
9105 nbranches++;
9107 } else if (nbranches == 0) {
9108 for (i = 0; i < remote->nsend_branches; i++) {
9109 got_pathlist_append(&branches,
9110 remote->send_branches[i], NULL);
9114 if (send_all_tags) {
9115 error = got_ref_list(&all_tags, repo, "refs/tags",
9116 got_ref_cmp_by_name, NULL);
9117 if (error)
9118 goto done;
9119 TAILQ_FOREACH(re, &all_tags, entry) {
9120 const char *tagname = got_ref_get_name(re->ref);
9121 error = got_pathlist_append(&tags,
9122 tagname, NULL);
9123 if (error)
9124 goto done;
9129 * To prevent accidents only branches in refs/heads/ can be deleted
9130 * with 'got send -d'.
9131 * Deleting anything else requires local repository access or Git.
9133 TAILQ_FOREACH(pe, &delete_args, entry) {
9134 const char *branchname = pe->path;
9135 char *s;
9136 struct got_pathlist_entry *new;
9137 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9138 s = strdup(branchname);
9139 if (s == NULL) {
9140 error = got_error_from_errno("strdup");
9141 goto done;
9143 } else {
9144 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9145 error = got_error_from_errno("asprintf");
9146 goto done;
9149 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9150 if (error || new == NULL /* duplicate */)
9151 free(s);
9152 if (error)
9153 goto done;
9154 ndelete_branches++;
9157 if (nbranches == 0 && ndelete_branches == 0) {
9158 struct got_reference *head_ref;
9159 if (worktree)
9160 error = got_ref_open(&head_ref, repo,
9161 got_worktree_get_head_ref_name(worktree), 0);
9162 else
9163 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9164 if (error)
9165 goto done;
9166 if (got_ref_is_symbolic(head_ref)) {
9167 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9168 got_ref_close(head_ref);
9169 if (error)
9170 goto done;
9171 } else
9172 ref = head_ref;
9173 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9174 NULL);
9175 if (error)
9176 goto done;
9177 nbranches++;
9180 if (verbosity >= 0)
9181 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9182 port ? ":" : "", port ? port : "");
9184 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9185 server_path, verbosity);
9186 if (error)
9187 goto done;
9189 memset(&spa, 0, sizeof(spa));
9190 spa.last_scaled_packsize[0] = '\0';
9191 spa.last_p_deltify = -1;
9192 spa.last_p_written = -1;
9193 spa.verbosity = verbosity;
9194 spa.delete_branches = &delete_branches;
9195 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9196 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9197 check_cancelled, NULL);
9198 if (spa.printed_something)
9199 putchar('\n');
9200 if (error)
9201 goto done;
9202 if (!spa.sent_something && verbosity >= 0)
9203 printf("Already up-to-date\n");
9204 done:
9205 if (sendpid > 0) {
9206 if (kill(sendpid, SIGTERM) == -1)
9207 error = got_error_from_errno("kill");
9208 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9209 error = got_error_from_errno("waitpid");
9211 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9212 error = got_error_from_errno("close");
9213 if (repo) {
9214 const struct got_error *close_err = got_repo_close(repo);
9215 if (error == NULL)
9216 error = close_err;
9218 if (worktree)
9219 got_worktree_close(worktree);
9220 if (pack_fds) {
9221 const struct got_error *pack_err =
9222 got_repo_pack_fds_close(pack_fds);
9223 if (error == NULL)
9224 error = pack_err;
9226 if (ref)
9227 got_ref_close(ref);
9228 got_pathlist_free(&branches);
9229 got_pathlist_free(&tags);
9230 got_ref_list_free(&all_branches);
9231 got_ref_list_free(&all_tags);
9232 got_pathlist_free(&delete_args);
9233 TAILQ_FOREACH(pe, &delete_branches, entry)
9234 free((char *)pe->path);
9235 got_pathlist_free(&delete_branches);
9236 free(cwd);
9237 free(repo_path);
9238 free(proto);
9239 free(host);
9240 free(port);
9241 free(server_path);
9242 free(repo_name);
9243 return error;
9246 __dead static void
9247 usage_cherrypick(void)
9249 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9250 exit(1);
9253 static const struct got_error *
9254 cmd_cherrypick(int argc, char *argv[])
9256 const struct got_error *error = NULL;
9257 struct got_worktree *worktree = NULL;
9258 struct got_repository *repo = NULL;
9259 char *cwd = NULL, *commit_id_str = NULL;
9260 struct got_object_id *commit_id = NULL;
9261 struct got_commit_object *commit = NULL;
9262 struct got_object_qid *pid;
9263 int ch;
9264 struct got_update_progress_arg upa;
9265 int *pack_fds = NULL;
9267 while ((ch = getopt(argc, argv, "")) != -1) {
9268 switch (ch) {
9269 default:
9270 usage_cherrypick();
9271 /* NOTREACHED */
9275 argc -= optind;
9276 argv += optind;
9278 #ifndef PROFILE
9279 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9280 "unveil", NULL) == -1)
9281 err(1, "pledge");
9282 #endif
9283 if (argc != 1)
9284 usage_cherrypick();
9286 cwd = getcwd(NULL, 0);
9287 if (cwd == NULL) {
9288 error = got_error_from_errno("getcwd");
9289 goto done;
9292 error = got_repo_pack_fds_open(&pack_fds);
9293 if (error != NULL)
9294 goto done;
9296 error = got_worktree_open(&worktree, cwd);
9297 if (error) {
9298 if (error->code == GOT_ERR_NOT_WORKTREE)
9299 error = wrap_not_worktree_error(error, "cherrypick",
9300 cwd);
9301 goto done;
9304 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9305 NULL, pack_fds);
9306 if (error != NULL)
9307 goto done;
9309 error = apply_unveil(got_repo_get_path(repo), 0,
9310 got_worktree_get_root_path(worktree));
9311 if (error)
9312 goto done;
9314 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9315 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9316 if (error)
9317 goto done;
9318 error = got_object_id_str(&commit_id_str, commit_id);
9319 if (error)
9320 goto done;
9322 error = got_object_open_as_commit(&commit, repo, commit_id);
9323 if (error)
9324 goto done;
9325 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9326 memset(&upa, 0, sizeof(upa));
9327 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9328 commit_id, repo, update_progress, &upa, check_cancelled,
9329 NULL);
9330 if (error != NULL)
9331 goto done;
9333 if (upa.did_something)
9334 printf("Merged commit %s\n", commit_id_str);
9335 print_merge_progress_stats(&upa);
9336 done:
9337 if (commit)
9338 got_object_commit_close(commit);
9339 free(commit_id_str);
9340 if (worktree)
9341 got_worktree_close(worktree);
9342 if (repo) {
9343 const struct got_error *close_err = got_repo_close(repo);
9344 if (error == NULL)
9345 error = close_err;
9347 if (pack_fds) {
9348 const struct got_error *pack_err =
9349 got_repo_pack_fds_close(pack_fds);
9350 if (error == NULL)
9351 error = pack_err;
9354 return error;
9357 __dead static void
9358 usage_backout(void)
9360 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9361 exit(1);
9364 static const struct got_error *
9365 cmd_backout(int argc, char *argv[])
9367 const struct got_error *error = NULL;
9368 struct got_worktree *worktree = NULL;
9369 struct got_repository *repo = NULL;
9370 char *cwd = NULL, *commit_id_str = NULL;
9371 struct got_object_id *commit_id = NULL;
9372 struct got_commit_object *commit = NULL;
9373 struct got_object_qid *pid;
9374 int ch;
9375 struct got_update_progress_arg upa;
9376 int *pack_fds = NULL;
9378 while ((ch = getopt(argc, argv, "")) != -1) {
9379 switch (ch) {
9380 default:
9381 usage_backout();
9382 /* NOTREACHED */
9386 argc -= optind;
9387 argv += optind;
9389 #ifndef PROFILE
9390 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9391 "unveil", NULL) == -1)
9392 err(1, "pledge");
9393 #endif
9394 if (argc != 1)
9395 usage_backout();
9397 cwd = getcwd(NULL, 0);
9398 if (cwd == NULL) {
9399 error = got_error_from_errno("getcwd");
9400 goto done;
9403 error = got_repo_pack_fds_open(&pack_fds);
9404 if (error != NULL)
9405 goto done;
9407 error = got_worktree_open(&worktree, cwd);
9408 if (error) {
9409 if (error->code == GOT_ERR_NOT_WORKTREE)
9410 error = wrap_not_worktree_error(error, "backout", cwd);
9411 goto done;
9414 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9415 NULL, pack_fds);
9416 if (error != NULL)
9417 goto done;
9419 error = apply_unveil(got_repo_get_path(repo), 0,
9420 got_worktree_get_root_path(worktree));
9421 if (error)
9422 goto done;
9424 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9425 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9426 if (error)
9427 goto done;
9428 error = got_object_id_str(&commit_id_str, commit_id);
9429 if (error)
9430 goto done;
9432 error = got_object_open_as_commit(&commit, repo, commit_id);
9433 if (error)
9434 goto done;
9435 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9436 if (pid == NULL) {
9437 error = got_error(GOT_ERR_ROOT_COMMIT);
9438 goto done;
9441 memset(&upa, 0, sizeof(upa));
9442 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9443 repo, update_progress, &upa, check_cancelled, NULL);
9444 if (error != NULL)
9445 goto done;
9447 if (upa.did_something)
9448 printf("Backed out commit %s\n", commit_id_str);
9449 print_merge_progress_stats(&upa);
9450 done:
9451 if (commit)
9452 got_object_commit_close(commit);
9453 free(commit_id_str);
9454 if (worktree)
9455 got_worktree_close(worktree);
9456 if (repo) {
9457 const struct got_error *close_err = got_repo_close(repo);
9458 if (error == NULL)
9459 error = close_err;
9461 if (pack_fds) {
9462 const struct got_error *pack_err =
9463 got_repo_pack_fds_close(pack_fds);
9464 if (error == NULL)
9465 error = pack_err;
9467 return error;
9470 __dead static void
9471 usage_rebase(void)
9473 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9474 exit(1);
9477 static void
9478 trim_logmsg(char *logmsg, int limit)
9480 char *nl;
9481 size_t len;
9483 len = strlen(logmsg);
9484 if (len > limit)
9485 len = limit;
9486 logmsg[len] = '\0';
9487 nl = strchr(logmsg, '\n');
9488 if (nl)
9489 *nl = '\0';
9492 static const struct got_error *
9493 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9495 const struct got_error *err;
9496 char *logmsg0 = NULL;
9497 const char *s;
9499 err = got_object_commit_get_logmsg(&logmsg0, commit);
9500 if (err)
9501 return err;
9503 s = logmsg0;
9504 while (isspace((unsigned char)s[0]))
9505 s++;
9507 *logmsg = strdup(s);
9508 if (*logmsg == NULL) {
9509 err = got_error_from_errno("strdup");
9510 goto done;
9513 trim_logmsg(*logmsg, limit);
9514 done:
9515 free(logmsg0);
9516 return err;
9519 static const struct got_error *
9520 show_rebase_merge_conflict(struct got_object_id *id,
9521 struct got_repository *repo)
9523 const struct got_error *err;
9524 struct got_commit_object *commit = NULL;
9525 char *id_str = NULL, *logmsg = NULL;
9527 err = got_object_open_as_commit(&commit, repo, id);
9528 if (err)
9529 return err;
9531 err = got_object_id_str(&id_str, id);
9532 if (err)
9533 goto done;
9535 id_str[12] = '\0';
9537 err = get_short_logmsg(&logmsg, 42, commit);
9538 if (err)
9539 goto done;
9541 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9542 done:
9543 free(id_str);
9544 got_object_commit_close(commit);
9545 free(logmsg);
9546 return err;
9549 static const struct got_error *
9550 show_rebase_progress(struct got_commit_object *commit,
9551 struct got_object_id *old_id, struct got_object_id *new_id)
9553 const struct got_error *err;
9554 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9556 err = got_object_id_str(&old_id_str, old_id);
9557 if (err)
9558 goto done;
9560 if (new_id) {
9561 err = got_object_id_str(&new_id_str, new_id);
9562 if (err)
9563 goto done;
9566 old_id_str[12] = '\0';
9567 if (new_id_str)
9568 new_id_str[12] = '\0';
9570 err = get_short_logmsg(&logmsg, 42, commit);
9571 if (err)
9572 goto done;
9574 printf("%s -> %s: %s\n", old_id_str,
9575 new_id_str ? new_id_str : "no-op change", logmsg);
9576 done:
9577 free(old_id_str);
9578 free(new_id_str);
9579 free(logmsg);
9580 return err;
9583 static const struct got_error *
9584 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9585 struct got_reference *branch, struct got_reference *new_base_branch,
9586 struct got_reference *tmp_branch, struct got_repository *repo,
9587 int create_backup)
9589 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9590 return got_worktree_rebase_complete(worktree, fileindex,
9591 new_base_branch, tmp_branch, branch, repo, create_backup);
9594 static const struct got_error *
9595 rebase_commit(struct got_pathlist_head *merged_paths,
9596 struct got_worktree *worktree, struct got_fileindex *fileindex,
9597 struct got_reference *tmp_branch, const char *committer,
9598 struct got_object_id *commit_id, struct got_repository *repo)
9600 const struct got_error *error;
9601 struct got_commit_object *commit;
9602 struct got_object_id *new_commit_id;
9604 error = got_object_open_as_commit(&commit, repo, commit_id);
9605 if (error)
9606 return error;
9608 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9609 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9610 repo);
9611 if (error) {
9612 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9613 goto done;
9614 error = show_rebase_progress(commit, commit_id, NULL);
9615 } else {
9616 error = show_rebase_progress(commit, commit_id, new_commit_id);
9617 free(new_commit_id);
9619 done:
9620 got_object_commit_close(commit);
9621 return error;
9624 struct check_path_prefix_arg {
9625 const char *path_prefix;
9626 size_t len;
9627 int errcode;
9630 static const struct got_error *
9631 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9632 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9633 struct got_object_id *id1, struct got_object_id *id2,
9634 const char *path1, const char *path2,
9635 mode_t mode1, mode_t mode2, struct got_repository *repo)
9637 struct check_path_prefix_arg *a = arg;
9639 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9640 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9641 return got_error(a->errcode);
9643 return NULL;
9646 static const struct got_error *
9647 check_path_prefix(struct got_object_id *parent_id,
9648 struct got_object_id *commit_id, const char *path_prefix,
9649 int errcode, struct got_repository *repo)
9651 const struct got_error *err;
9652 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9653 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9654 struct check_path_prefix_arg cpp_arg;
9656 if (got_path_is_root_dir(path_prefix))
9657 return NULL;
9659 err = got_object_open_as_commit(&commit, repo, commit_id);
9660 if (err)
9661 goto done;
9663 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9664 if (err)
9665 goto done;
9667 err = got_object_open_as_tree(&tree1, repo,
9668 got_object_commit_get_tree_id(parent_commit));
9669 if (err)
9670 goto done;
9672 err = got_object_open_as_tree(&tree2, repo,
9673 got_object_commit_get_tree_id(commit));
9674 if (err)
9675 goto done;
9677 cpp_arg.path_prefix = path_prefix;
9678 while (cpp_arg.path_prefix[0] == '/')
9679 cpp_arg.path_prefix++;
9680 cpp_arg.len = strlen(cpp_arg.path_prefix);
9681 cpp_arg.errcode = errcode;
9682 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9683 check_path_prefix_in_diff, &cpp_arg, 0);
9684 done:
9685 if (tree1)
9686 got_object_tree_close(tree1);
9687 if (tree2)
9688 got_object_tree_close(tree2);
9689 if (commit)
9690 got_object_commit_close(commit);
9691 if (parent_commit)
9692 got_object_commit_close(parent_commit);
9693 return err;
9696 static const struct got_error *
9697 collect_commits(struct got_object_id_queue *commits,
9698 struct got_object_id *initial_commit_id,
9699 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9700 const char *path_prefix, int path_prefix_errcode,
9701 struct got_repository *repo)
9703 const struct got_error *err = NULL;
9704 struct got_commit_graph *graph = NULL;
9705 struct got_object_id parent_id, commit_id;
9706 struct got_object_qid *qid;
9708 err = got_commit_graph_open(&graph, "/", 1);
9709 if (err)
9710 return err;
9712 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9713 check_cancelled, NULL);
9714 if (err)
9715 goto done;
9717 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9718 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9719 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9720 check_cancelled, NULL);
9721 if (err) {
9722 if (err->code == GOT_ERR_ITER_COMPLETED) {
9723 err = got_error_msg(GOT_ERR_ANCESTRY,
9724 "ran out of commits to rebase before "
9725 "youngest common ancestor commit has "
9726 "been reached?!?");
9728 goto done;
9729 } else {
9730 err = check_path_prefix(&parent_id, &commit_id,
9731 path_prefix, path_prefix_errcode, repo);
9732 if (err)
9733 goto done;
9735 err = got_object_qid_alloc(&qid, &commit_id);
9736 if (err)
9737 goto done;
9738 STAILQ_INSERT_HEAD(commits, qid, entry);
9740 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9743 done:
9744 got_commit_graph_close(graph);
9745 return err;
9748 static const struct got_error *
9749 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9751 const struct got_error *err = NULL;
9752 time_t committer_time;
9753 struct tm tm;
9754 char datebuf[11]; /* YYYY-MM-DD + NUL */
9755 char *author0 = NULL, *author, *smallerthan;
9756 char *logmsg0 = NULL, *logmsg, *newline;
9758 committer_time = got_object_commit_get_committer_time(commit);
9759 if (gmtime_r(&committer_time, &tm) == NULL)
9760 return got_error_from_errno("gmtime_r");
9761 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9762 return got_error(GOT_ERR_NO_SPACE);
9764 author0 = strdup(got_object_commit_get_author(commit));
9765 if (author0 == NULL)
9766 return got_error_from_errno("strdup");
9767 author = author0;
9768 smallerthan = strchr(author, '<');
9769 if (smallerthan && smallerthan[1] != '\0')
9770 author = smallerthan + 1;
9771 author[strcspn(author, "@>")] = '\0';
9773 err = got_object_commit_get_logmsg(&logmsg0, commit);
9774 if (err)
9775 goto done;
9776 logmsg = logmsg0;
9777 while (*logmsg == '\n')
9778 logmsg++;
9779 newline = strchr(logmsg, '\n');
9780 if (newline)
9781 *newline = '\0';
9783 if (asprintf(brief_str, "%s %s %s",
9784 datebuf, author, logmsg) == -1)
9785 err = got_error_from_errno("asprintf");
9786 done:
9787 free(author0);
9788 free(logmsg0);
9789 return err;
9792 static const struct got_error *
9793 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9794 struct got_repository *repo)
9796 const struct got_error *err;
9797 char *id_str;
9799 err = got_object_id_str(&id_str, id);
9800 if (err)
9801 return err;
9803 err = got_ref_delete(ref, repo);
9804 if (err)
9805 goto done;
9807 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9808 done:
9809 free(id_str);
9810 return err;
9813 static const struct got_error *
9814 print_backup_ref(const char *branch_name, const char *new_id_str,
9815 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9816 struct got_reflist_object_id_map *refs_idmap,
9817 struct got_repository *repo)
9819 const struct got_error *err = NULL;
9820 struct got_reflist_head *refs;
9821 char *refs_str = NULL;
9822 struct got_object_id *new_commit_id = NULL;
9823 struct got_commit_object *new_commit = NULL;
9824 char *new_commit_brief_str = NULL;
9825 struct got_object_id *yca_id = NULL;
9826 struct got_commit_object *yca_commit = NULL;
9827 char *yca_id_str = NULL, *yca_brief_str = NULL;
9828 char *custom_refs_str;
9830 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9831 return got_error_from_errno("asprintf");
9833 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9834 0, 0, refs_idmap, custom_refs_str);
9835 if (err)
9836 goto done;
9838 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9839 if (err)
9840 goto done;
9842 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9843 if (refs) {
9844 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9845 if (err)
9846 goto done;
9849 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9850 if (err)
9851 goto done;
9853 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9854 if (err)
9855 goto done;
9857 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9858 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9859 if (err)
9860 goto done;
9862 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9863 refs_str ? " (" : "", refs_str ? refs_str : "",
9864 refs_str ? ")" : "", new_commit_brief_str);
9865 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9866 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9867 free(refs_str);
9868 refs_str = NULL;
9870 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9871 if (err)
9872 goto done;
9874 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9875 if (err)
9876 goto done;
9878 err = got_object_id_str(&yca_id_str, yca_id);
9879 if (err)
9880 goto done;
9882 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9883 if (refs) {
9884 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9885 if (err)
9886 goto done;
9888 printf("history forked at %s%s%s%s\n %s\n",
9889 yca_id_str,
9890 refs_str ? " (" : "", refs_str ? refs_str : "",
9891 refs_str ? ")" : "", yca_brief_str);
9893 done:
9894 free(custom_refs_str);
9895 free(new_commit_id);
9896 free(refs_str);
9897 free(yca_id);
9898 free(yca_id_str);
9899 free(yca_brief_str);
9900 if (new_commit)
9901 got_object_commit_close(new_commit);
9902 if (yca_commit)
9903 got_object_commit_close(yca_commit);
9905 return NULL;
9908 static const struct got_error *
9909 process_backup_refs(const char *backup_ref_prefix,
9910 const char *wanted_branch_name,
9911 int delete, struct got_repository *repo)
9913 const struct got_error *err;
9914 struct got_reflist_head refs, backup_refs;
9915 struct got_reflist_entry *re;
9916 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9917 struct got_object_id *old_commit_id = NULL;
9918 char *branch_name = NULL;
9919 struct got_commit_object *old_commit = NULL;
9920 struct got_reflist_object_id_map *refs_idmap = NULL;
9921 int wanted_branch_found = 0;
9923 TAILQ_INIT(&refs);
9924 TAILQ_INIT(&backup_refs);
9926 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9927 if (err)
9928 return err;
9930 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9931 if (err)
9932 goto done;
9934 if (wanted_branch_name) {
9935 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9936 wanted_branch_name += 11;
9939 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9940 got_ref_cmp_by_commit_timestamp_descending, repo);
9941 if (err)
9942 goto done;
9944 TAILQ_FOREACH(re, &backup_refs, entry) {
9945 const char *refname = got_ref_get_name(re->ref);
9946 char *slash;
9948 err = check_cancelled(NULL);
9949 if (err)
9950 break;
9952 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9953 if (err)
9954 break;
9956 err = got_object_open_as_commit(&old_commit, repo,
9957 old_commit_id);
9958 if (err)
9959 break;
9961 if (strncmp(backup_ref_prefix, refname,
9962 backup_ref_prefix_len) == 0)
9963 refname += backup_ref_prefix_len;
9965 while (refname[0] == '/')
9966 refname++;
9968 branch_name = strdup(refname);
9969 if (branch_name == NULL) {
9970 err = got_error_from_errno("strdup");
9971 break;
9973 slash = strrchr(branch_name, '/');
9974 if (slash) {
9975 *slash = '\0';
9976 refname += strlen(branch_name) + 1;
9979 if (wanted_branch_name == NULL ||
9980 strcmp(wanted_branch_name, branch_name) == 0) {
9981 wanted_branch_found = 1;
9982 if (delete) {
9983 err = delete_backup_ref(re->ref,
9984 old_commit_id, repo);
9985 } else {
9986 err = print_backup_ref(branch_name, refname,
9987 old_commit_id, old_commit, refs_idmap,
9988 repo);
9990 if (err)
9991 break;
9994 free(old_commit_id);
9995 old_commit_id = NULL;
9996 free(branch_name);
9997 branch_name = NULL;
9998 got_object_commit_close(old_commit);
9999 old_commit = NULL;
10002 if (wanted_branch_name && !wanted_branch_found) {
10003 err = got_error_fmt(GOT_ERR_NOT_REF,
10004 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10006 done:
10007 if (refs_idmap)
10008 got_reflist_object_id_map_free(refs_idmap);
10009 got_ref_list_free(&refs);
10010 got_ref_list_free(&backup_refs);
10011 free(old_commit_id);
10012 free(branch_name);
10013 if (old_commit)
10014 got_object_commit_close(old_commit);
10015 return err;
10018 static const struct got_error *
10019 abort_progress(void *arg, unsigned char status, const char *path)
10022 * Unversioned files should not clutter progress output when
10023 * an operation is aborted.
10025 if (status == GOT_STATUS_UNVERSIONED)
10026 return NULL;
10028 return update_progress(arg, status, path);
10031 static const struct got_error *
10032 cmd_rebase(int argc, char *argv[])
10034 const struct got_error *error = NULL;
10035 struct got_worktree *worktree = NULL;
10036 struct got_repository *repo = NULL;
10037 struct got_fileindex *fileindex = NULL;
10038 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10039 struct got_reference *branch = NULL;
10040 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10041 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10042 struct got_object_id *resume_commit_id = NULL;
10043 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10044 struct got_commit_object *commit = NULL;
10045 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10046 int histedit_in_progress = 0, merge_in_progress = 0;
10047 int create_backup = 1, list_backups = 0, delete_backups = 0;
10048 struct got_object_id_queue commits;
10049 struct got_pathlist_head merged_paths;
10050 const struct got_object_id_queue *parent_ids;
10051 struct got_object_qid *qid, *pid;
10052 struct got_update_progress_arg upa;
10053 int *pack_fds = NULL;
10055 STAILQ_INIT(&commits);
10056 TAILQ_INIT(&merged_paths);
10057 memset(&upa, 0, sizeof(upa));
10059 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10060 switch (ch) {
10061 case 'a':
10062 abort_rebase = 1;
10063 break;
10064 case 'c':
10065 continue_rebase = 1;
10066 break;
10067 case 'l':
10068 list_backups = 1;
10069 break;
10070 case 'X':
10071 delete_backups = 1;
10072 break;
10073 default:
10074 usage_rebase();
10075 /* NOTREACHED */
10079 argc -= optind;
10080 argv += optind;
10082 #ifndef PROFILE
10083 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10084 "unveil", NULL) == -1)
10085 err(1, "pledge");
10086 #endif
10087 if (list_backups) {
10088 if (abort_rebase)
10089 option_conflict('l', 'a');
10090 if (continue_rebase)
10091 option_conflict('l', 'c');
10092 if (delete_backups)
10093 option_conflict('l', 'X');
10094 if (argc != 0 && argc != 1)
10095 usage_rebase();
10096 } else if (delete_backups) {
10097 if (abort_rebase)
10098 option_conflict('X', 'a');
10099 if (continue_rebase)
10100 option_conflict('X', 'c');
10101 if (list_backups)
10102 option_conflict('l', 'X');
10103 if (argc != 0 && argc != 1)
10104 usage_rebase();
10105 } else {
10106 if (abort_rebase && continue_rebase)
10107 usage_rebase();
10108 else if (abort_rebase || continue_rebase) {
10109 if (argc != 0)
10110 usage_rebase();
10111 } else if (argc != 1)
10112 usage_rebase();
10115 cwd = getcwd(NULL, 0);
10116 if (cwd == NULL) {
10117 error = got_error_from_errno("getcwd");
10118 goto done;
10121 error = got_repo_pack_fds_open(&pack_fds);
10122 if (error != NULL)
10123 goto done;
10125 error = got_worktree_open(&worktree, cwd);
10126 if (error) {
10127 if (list_backups || delete_backups) {
10128 if (error->code != GOT_ERR_NOT_WORKTREE)
10129 goto done;
10130 } else {
10131 if (error->code == GOT_ERR_NOT_WORKTREE)
10132 error = wrap_not_worktree_error(error,
10133 "rebase", cwd);
10134 goto done;
10138 error = get_gitconfig_path(&gitconfig_path);
10139 if (error)
10140 goto done;
10141 error = got_repo_open(&repo,
10142 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10143 gitconfig_path, pack_fds);
10144 if (error != NULL)
10145 goto done;
10147 error = get_author(&committer, repo, worktree);
10148 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10149 goto done;
10151 error = apply_unveil(got_repo_get_path(repo), 0,
10152 worktree ? got_worktree_get_root_path(worktree) : NULL);
10153 if (error)
10154 goto done;
10156 if (list_backups || delete_backups) {
10157 error = process_backup_refs(
10158 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10159 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10160 goto done; /* nothing else to do */
10163 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10164 worktree);
10165 if (error)
10166 goto done;
10167 if (histedit_in_progress) {
10168 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10169 goto done;
10172 error = got_worktree_merge_in_progress(&merge_in_progress,
10173 worktree, repo);
10174 if (error)
10175 goto done;
10176 if (merge_in_progress) {
10177 error = got_error(GOT_ERR_MERGE_BUSY);
10178 goto done;
10181 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10182 if (error)
10183 goto done;
10185 if (abort_rebase) {
10186 if (!rebase_in_progress) {
10187 error = got_error(GOT_ERR_NOT_REBASING);
10188 goto done;
10190 error = got_worktree_rebase_continue(&resume_commit_id,
10191 &new_base_branch, &tmp_branch, &branch, &fileindex,
10192 worktree, repo);
10193 if (error)
10194 goto done;
10195 printf("Switching work tree to %s\n",
10196 got_ref_get_symref_target(new_base_branch));
10197 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10198 new_base_branch, abort_progress, &upa);
10199 if (error)
10200 goto done;
10201 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10202 print_merge_progress_stats(&upa);
10203 goto done; /* nothing else to do */
10206 if (continue_rebase) {
10207 if (!rebase_in_progress) {
10208 error = got_error(GOT_ERR_NOT_REBASING);
10209 goto done;
10211 error = got_worktree_rebase_continue(&resume_commit_id,
10212 &new_base_branch, &tmp_branch, &branch, &fileindex,
10213 worktree, repo);
10214 if (error)
10215 goto done;
10217 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10218 committer, resume_commit_id, repo);
10219 if (error)
10220 goto done;
10222 yca_id = got_object_id_dup(resume_commit_id);
10223 if (yca_id == NULL) {
10224 error = got_error_from_errno("got_object_id_dup");
10225 goto done;
10227 } else {
10228 error = got_ref_open(&branch, repo, argv[0], 0);
10229 if (error != NULL)
10230 goto done;
10231 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10232 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10233 "will not rebase a branch which lives outside "
10234 "the \"refs/heads/\" reference namespace");
10235 goto done;
10239 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10240 if (error)
10241 goto done;
10243 if (!continue_rebase) {
10244 struct got_object_id *base_commit_id;
10246 base_commit_id = got_worktree_get_base_commit_id(worktree);
10247 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10248 base_commit_id, branch_head_commit_id, 1, repo,
10249 check_cancelled, NULL);
10250 if (error)
10251 goto done;
10252 if (yca_id == NULL) {
10253 error = got_error_msg(GOT_ERR_ANCESTRY,
10254 "specified branch shares no common ancestry "
10255 "with work tree's branch");
10256 goto done;
10259 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10260 if (error) {
10261 if (error->code != GOT_ERR_ANCESTRY)
10262 goto done;
10263 error = NULL;
10264 } else {
10265 struct got_pathlist_head paths;
10266 printf("%s is already based on %s\n",
10267 got_ref_get_name(branch),
10268 got_worktree_get_head_ref_name(worktree));
10269 error = switch_head_ref(branch, branch_head_commit_id,
10270 worktree, repo);
10271 if (error)
10272 goto done;
10273 error = got_worktree_set_base_commit_id(worktree, repo,
10274 branch_head_commit_id);
10275 if (error)
10276 goto done;
10277 TAILQ_INIT(&paths);
10278 error = got_pathlist_append(&paths, "", NULL);
10279 if (error)
10280 goto done;
10281 error = got_worktree_checkout_files(worktree,
10282 &paths, repo, update_progress, &upa,
10283 check_cancelled, NULL);
10284 got_pathlist_free(&paths);
10285 if (error)
10286 goto done;
10287 if (upa.did_something) {
10288 char *id_str;
10289 error = got_object_id_str(&id_str,
10290 branch_head_commit_id);
10291 if (error)
10292 goto done;
10293 printf("Updated to %s: %s\n",
10294 got_worktree_get_head_ref_name(worktree),
10295 id_str);
10296 free(id_str);
10297 } else
10298 printf("Already up-to-date\n");
10299 print_update_progress_stats(&upa);
10300 goto done;
10304 commit_id = branch_head_commit_id;
10305 error = got_object_open_as_commit(&commit, repo, commit_id);
10306 if (error)
10307 goto done;
10309 parent_ids = got_object_commit_get_parent_ids(commit);
10310 pid = STAILQ_FIRST(parent_ids);
10311 if (pid == NULL) {
10312 error = got_error(GOT_ERR_EMPTY_REBASE);
10313 goto done;
10315 error = collect_commits(&commits, commit_id, &pid->id,
10316 yca_id, got_worktree_get_path_prefix(worktree),
10317 GOT_ERR_REBASE_PATH, repo);
10318 got_object_commit_close(commit);
10319 commit = NULL;
10320 if (error)
10321 goto done;
10323 if (!continue_rebase) {
10324 error = got_worktree_rebase_prepare(&new_base_branch,
10325 &tmp_branch, &fileindex, worktree, branch, repo);
10326 if (error)
10327 goto done;
10330 if (STAILQ_EMPTY(&commits)) {
10331 if (continue_rebase) {
10332 error = rebase_complete(worktree, fileindex,
10333 branch, new_base_branch, tmp_branch, repo,
10334 create_backup);
10335 goto done;
10336 } else {
10337 /* Fast-forward the reference of the branch. */
10338 struct got_object_id *new_head_commit_id;
10339 char *id_str;
10340 error = got_ref_resolve(&new_head_commit_id, repo,
10341 new_base_branch);
10342 if (error)
10343 goto done;
10344 error = got_object_id_str(&id_str, new_head_commit_id);
10345 if (error)
10346 goto done;
10347 printf("Forwarding %s to commit %s\n",
10348 got_ref_get_name(branch), id_str);
10349 free(id_str);
10350 error = got_ref_change_ref(branch,
10351 new_head_commit_id);
10352 if (error)
10353 goto done;
10354 /* No backup needed since objects did not change. */
10355 create_backup = 0;
10359 pid = NULL;
10360 STAILQ_FOREACH(qid, &commits, entry) {
10362 commit_id = &qid->id;
10363 parent_id = pid ? &pid->id : yca_id;
10364 pid = qid;
10366 memset(&upa, 0, sizeof(upa));
10367 error = got_worktree_rebase_merge_files(&merged_paths,
10368 worktree, fileindex, parent_id, commit_id, repo,
10369 update_progress, &upa, check_cancelled, NULL);
10370 if (error)
10371 goto done;
10373 print_merge_progress_stats(&upa);
10374 if (upa.conflicts > 0 || upa.missing > 0 ||
10375 upa.not_deleted > 0 || upa.unversioned > 0) {
10376 if (upa.conflicts > 0) {
10377 error = show_rebase_merge_conflict(&qid->id,
10378 repo);
10379 if (error)
10380 goto done;
10382 got_worktree_rebase_pathlist_free(&merged_paths);
10383 break;
10386 error = rebase_commit(&merged_paths, worktree, fileindex,
10387 tmp_branch, committer, commit_id, repo);
10388 got_worktree_rebase_pathlist_free(&merged_paths);
10389 if (error)
10390 goto done;
10393 if (upa.conflicts > 0 || upa.missing > 0 ||
10394 upa.not_deleted > 0 || upa.unversioned > 0) {
10395 error = got_worktree_rebase_postpone(worktree, fileindex);
10396 if (error)
10397 goto done;
10398 if (upa.conflicts > 0 && upa.missing == 0 &&
10399 upa.not_deleted == 0 && upa.unversioned == 0) {
10400 error = got_error_msg(GOT_ERR_CONFLICTS,
10401 "conflicts must be resolved before rebasing "
10402 "can continue");
10403 } else if (upa.conflicts > 0) {
10404 error = got_error_msg(GOT_ERR_CONFLICTS,
10405 "conflicts must be resolved before rebasing "
10406 "can continue; changes destined for some "
10407 "files were not yet merged and should be "
10408 "merged manually if required before the "
10409 "rebase operation is continued");
10410 } else {
10411 error = got_error_msg(GOT_ERR_CONFLICTS,
10412 "changes destined for some files were not "
10413 "yet merged and should be merged manually "
10414 "if required before the rebase operation "
10415 "is continued");
10417 } else
10418 error = rebase_complete(worktree, fileindex, branch,
10419 new_base_branch, tmp_branch, repo, create_backup);
10420 done:
10421 free(cwd);
10422 free(committer);
10423 free(gitconfig_path);
10424 got_object_id_queue_free(&commits);
10425 free(branch_head_commit_id);
10426 free(resume_commit_id);
10427 free(yca_id);
10428 if (commit)
10429 got_object_commit_close(commit);
10430 if (branch)
10431 got_ref_close(branch);
10432 if (new_base_branch)
10433 got_ref_close(new_base_branch);
10434 if (tmp_branch)
10435 got_ref_close(tmp_branch);
10436 if (worktree)
10437 got_worktree_close(worktree);
10438 if (repo) {
10439 const struct got_error *close_err = got_repo_close(repo);
10440 if (error == NULL)
10441 error = close_err;
10443 if (pack_fds) {
10444 const struct got_error *pack_err =
10445 got_repo_pack_fds_close(pack_fds);
10446 if (error == NULL)
10447 error = pack_err;
10449 return error;
10452 __dead static void
10453 usage_histedit(void)
10455 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10456 "[branch]\n", getprogname());
10457 exit(1);
10460 #define GOT_HISTEDIT_PICK 'p'
10461 #define GOT_HISTEDIT_EDIT 'e'
10462 #define GOT_HISTEDIT_FOLD 'f'
10463 #define GOT_HISTEDIT_DROP 'd'
10464 #define GOT_HISTEDIT_MESG 'm'
10466 static const struct got_histedit_cmd {
10467 unsigned char code;
10468 const char *name;
10469 const char *desc;
10470 } got_histedit_cmds[] = {
10471 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10472 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10473 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10474 "be used" },
10475 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10476 { GOT_HISTEDIT_MESG, "mesg",
10477 "single-line log message for commit above (open editor if empty)" },
10480 struct got_histedit_list_entry {
10481 TAILQ_ENTRY(got_histedit_list_entry) entry;
10482 struct got_object_id *commit_id;
10483 const struct got_histedit_cmd *cmd;
10484 char *logmsg;
10486 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10488 static const struct got_error *
10489 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10490 FILE *f, struct got_repository *repo)
10492 const struct got_error *err = NULL;
10493 char *logmsg = NULL, *id_str = NULL;
10494 struct got_commit_object *commit = NULL;
10495 int n;
10497 err = got_object_open_as_commit(&commit, repo, commit_id);
10498 if (err)
10499 goto done;
10501 err = get_short_logmsg(&logmsg, 34, commit);
10502 if (err)
10503 goto done;
10505 err = got_object_id_str(&id_str, commit_id);
10506 if (err)
10507 goto done;
10509 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10510 if (n < 0)
10511 err = got_ferror(f, GOT_ERR_IO);
10512 done:
10513 if (commit)
10514 got_object_commit_close(commit);
10515 free(id_str);
10516 free(logmsg);
10517 return err;
10520 static const struct got_error *
10521 histedit_write_commit_list(struct got_object_id_queue *commits,
10522 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10523 struct got_repository *repo)
10525 const struct got_error *err = NULL;
10526 struct got_object_qid *qid;
10527 const char *histedit_cmd = NULL;
10529 if (STAILQ_EMPTY(commits))
10530 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10532 STAILQ_FOREACH(qid, commits, entry) {
10533 histedit_cmd = got_histedit_cmds[0].name;
10534 if (edit_only)
10535 histedit_cmd = "edit";
10536 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10537 histedit_cmd = "fold";
10538 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10539 if (err)
10540 break;
10541 if (edit_logmsg_only) {
10542 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10543 if (n < 0) {
10544 err = got_ferror(f, GOT_ERR_IO);
10545 break;
10550 return err;
10553 static const struct got_error *
10554 write_cmd_list(FILE *f, const char *branch_name,
10555 struct got_object_id_queue *commits)
10557 const struct got_error *err = NULL;
10558 size_t i;
10559 int n;
10560 char *id_str;
10561 struct got_object_qid *qid;
10563 qid = STAILQ_FIRST(commits);
10564 err = got_object_id_str(&id_str, &qid->id);
10565 if (err)
10566 return err;
10568 n = fprintf(f,
10569 "# Editing the history of branch '%s' starting at\n"
10570 "# commit %s\n"
10571 "# Commits will be processed in order from top to "
10572 "bottom of this file.\n", branch_name, id_str);
10573 if (n < 0) {
10574 err = got_ferror(f, GOT_ERR_IO);
10575 goto done;
10578 n = fprintf(f, "# Available histedit commands:\n");
10579 if (n < 0) {
10580 err = got_ferror(f, GOT_ERR_IO);
10581 goto done;
10584 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10585 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10586 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10587 cmd->desc);
10588 if (n < 0) {
10589 err = got_ferror(f, GOT_ERR_IO);
10590 break;
10593 done:
10594 free(id_str);
10595 return err;
10598 static const struct got_error *
10599 histedit_syntax_error(int lineno)
10601 static char msg[42];
10602 int ret;
10604 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10605 lineno);
10606 if (ret < 0 || (size_t)ret >= sizeof(msg))
10607 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10609 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10612 static const struct got_error *
10613 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10614 char *logmsg, struct got_repository *repo)
10616 const struct got_error *err;
10617 struct got_commit_object *folded_commit = NULL;
10618 char *id_str, *folded_logmsg = NULL;
10620 err = got_object_id_str(&id_str, hle->commit_id);
10621 if (err)
10622 return err;
10624 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10625 if (err)
10626 goto done;
10628 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10629 if (err)
10630 goto done;
10631 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10632 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10633 folded_logmsg) == -1) {
10634 err = got_error_from_errno("asprintf");
10636 done:
10637 if (folded_commit)
10638 got_object_commit_close(folded_commit);
10639 free(id_str);
10640 free(folded_logmsg);
10641 return err;
10644 static struct got_histedit_list_entry *
10645 get_folded_commits(struct got_histedit_list_entry *hle)
10647 struct got_histedit_list_entry *prev, *folded = NULL;
10649 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10650 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10651 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10652 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10653 folded = prev;
10654 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10657 return folded;
10660 static const struct got_error *
10661 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10662 struct got_repository *repo)
10664 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10665 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10666 const struct got_error *err = NULL;
10667 struct got_commit_object *commit = NULL;
10668 int logmsg_len;
10669 int fd;
10670 struct got_histedit_list_entry *folded = NULL;
10672 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10673 if (err)
10674 return err;
10676 folded = get_folded_commits(hle);
10677 if (folded) {
10678 while (folded != hle) {
10679 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10680 folded = TAILQ_NEXT(folded, entry);
10681 continue;
10683 err = append_folded_commit_msg(&new_msg, folded,
10684 logmsg, repo);
10685 if (err)
10686 goto done;
10687 free(logmsg);
10688 logmsg = new_msg;
10689 folded = TAILQ_NEXT(folded, entry);
10693 err = got_object_id_str(&id_str, hle->commit_id);
10694 if (err)
10695 goto done;
10696 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10697 if (err)
10698 goto done;
10699 logmsg_len = asprintf(&new_msg,
10700 "%s\n# original log message of commit %s: %s",
10701 logmsg ? logmsg : "", id_str, orig_logmsg);
10702 if (logmsg_len == -1) {
10703 err = got_error_from_errno("asprintf");
10704 goto done;
10706 free(logmsg);
10707 logmsg = new_msg;
10709 err = got_object_id_str(&id_str, hle->commit_id);
10710 if (err)
10711 goto done;
10713 err = got_opentemp_named_fd(&logmsg_path, &fd,
10714 GOT_TMPDIR_STR "/got-logmsg");
10715 if (err)
10716 goto done;
10718 write(fd, logmsg, logmsg_len);
10719 close(fd);
10721 err = get_editor(&editor);
10722 if (err)
10723 goto done;
10725 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10726 logmsg_len, 0);
10727 if (err) {
10728 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10729 goto done;
10730 err = NULL;
10731 hle->logmsg = strdup(new_msg);
10732 if (hle->logmsg == NULL)
10733 err = got_error_from_errno("strdup");
10735 done:
10736 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10737 err = got_error_from_errno2("unlink", logmsg_path);
10738 free(logmsg_path);
10739 free(logmsg);
10740 free(orig_logmsg);
10741 free(editor);
10742 if (commit)
10743 got_object_commit_close(commit);
10744 return err;
10747 static const struct got_error *
10748 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10749 FILE *f, struct got_repository *repo)
10751 const struct got_error *err = NULL;
10752 char *line = NULL, *p, *end;
10753 size_t i, size;
10754 ssize_t len;
10755 int lineno = 0, lastcmd = -1;
10756 const struct got_histedit_cmd *cmd;
10757 struct got_object_id *commit_id = NULL;
10758 struct got_histedit_list_entry *hle = NULL;
10760 for (;;) {
10761 len = getline(&line, &size, f);
10762 if (len == -1) {
10763 const struct got_error *getline_err;
10764 if (feof(f))
10765 break;
10766 getline_err = got_error_from_errno("getline");
10767 err = got_ferror(f, getline_err->code);
10768 break;
10770 lineno++;
10771 p = line;
10772 while (isspace((unsigned char)p[0]))
10773 p++;
10774 if (p[0] == '#' || p[0] == '\0') {
10775 free(line);
10776 line = NULL;
10777 continue;
10779 cmd = NULL;
10780 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10781 cmd = &got_histedit_cmds[i];
10782 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10783 isspace((unsigned char)p[strlen(cmd->name)])) {
10784 p += strlen(cmd->name);
10785 break;
10787 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10788 p++;
10789 break;
10792 if (i == nitems(got_histedit_cmds)) {
10793 err = histedit_syntax_error(lineno);
10794 break;
10796 while (isspace((unsigned char)p[0]))
10797 p++;
10798 if (cmd->code == GOT_HISTEDIT_MESG) {
10799 if (lastcmd != GOT_HISTEDIT_PICK &&
10800 lastcmd != GOT_HISTEDIT_EDIT) {
10801 err = got_error(GOT_ERR_HISTEDIT_CMD);
10802 break;
10804 if (p[0] == '\0') {
10805 err = histedit_edit_logmsg(hle, repo);
10806 if (err)
10807 break;
10808 } else {
10809 hle->logmsg = strdup(p);
10810 if (hle->logmsg == NULL) {
10811 err = got_error_from_errno("strdup");
10812 break;
10815 free(line);
10816 line = NULL;
10817 lastcmd = cmd->code;
10818 continue;
10819 } else {
10820 end = p;
10821 while (end[0] && !isspace((unsigned char)end[0]))
10822 end++;
10823 *end = '\0';
10825 err = got_object_resolve_id_str(&commit_id, repo, p);
10826 if (err) {
10827 /* override error code */
10828 err = histedit_syntax_error(lineno);
10829 break;
10832 hle = malloc(sizeof(*hle));
10833 if (hle == NULL) {
10834 err = got_error_from_errno("malloc");
10835 break;
10837 hle->cmd = cmd;
10838 hle->commit_id = commit_id;
10839 hle->logmsg = NULL;
10840 commit_id = NULL;
10841 free(line);
10842 line = NULL;
10843 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10844 lastcmd = cmd->code;
10847 free(line);
10848 free(commit_id);
10849 return err;
10852 static const struct got_error *
10853 histedit_check_script(struct got_histedit_list *histedit_cmds,
10854 struct got_object_id_queue *commits, struct got_repository *repo)
10856 const struct got_error *err = NULL;
10857 struct got_object_qid *qid;
10858 struct got_histedit_list_entry *hle;
10859 static char msg[92];
10860 char *id_str;
10862 if (TAILQ_EMPTY(histedit_cmds))
10863 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10864 "histedit script contains no commands");
10865 if (STAILQ_EMPTY(commits))
10866 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10868 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10869 struct got_histedit_list_entry *hle2;
10870 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10871 if (hle == hle2)
10872 continue;
10873 if (got_object_id_cmp(hle->commit_id,
10874 hle2->commit_id) != 0)
10875 continue;
10876 err = got_object_id_str(&id_str, hle->commit_id);
10877 if (err)
10878 return err;
10879 snprintf(msg, sizeof(msg), "commit %s is listed "
10880 "more than once in histedit script", id_str);
10881 free(id_str);
10882 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10886 STAILQ_FOREACH(qid, commits, entry) {
10887 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10888 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10889 break;
10891 if (hle == NULL) {
10892 err = got_object_id_str(&id_str, &qid->id);
10893 if (err)
10894 return err;
10895 snprintf(msg, sizeof(msg),
10896 "commit %s missing from histedit script", id_str);
10897 free(id_str);
10898 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10902 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10903 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10904 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10905 "last commit in histedit script cannot be folded");
10907 return NULL;
10910 static const struct got_error *
10911 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10912 const char *path, struct got_object_id_queue *commits,
10913 struct got_repository *repo)
10915 const struct got_error *err = NULL;
10916 char *editor;
10917 FILE *f = NULL;
10919 err = get_editor(&editor);
10920 if (err)
10921 return err;
10923 if (spawn_editor(editor, path) == -1) {
10924 err = got_error_from_errno("failed spawning editor");
10925 goto done;
10928 f = fopen(path, "re");
10929 if (f == NULL) {
10930 err = got_error_from_errno("fopen");
10931 goto done;
10933 err = histedit_parse_list(histedit_cmds, f, repo);
10934 if (err)
10935 goto done;
10937 err = histedit_check_script(histedit_cmds, commits, repo);
10938 done:
10939 if (f && fclose(f) == EOF && err == NULL)
10940 err = got_error_from_errno("fclose");
10941 free(editor);
10942 return err;
10945 static const struct got_error *
10946 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10947 struct got_object_id_queue *, const char *, const char *,
10948 struct got_repository *);
10950 static const struct got_error *
10951 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10952 struct got_object_id_queue *commits, const char *branch_name,
10953 int edit_logmsg_only, int fold_only, int edit_only,
10954 struct got_repository *repo)
10956 const struct got_error *err;
10957 FILE *f = NULL;
10958 char *path = NULL;
10960 err = got_opentemp_named(&path, &f, "got-histedit");
10961 if (err)
10962 return err;
10964 err = write_cmd_list(f, branch_name, commits);
10965 if (err)
10966 goto done;
10968 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10969 fold_only, edit_only, repo);
10970 if (err)
10971 goto done;
10973 if (edit_logmsg_only || fold_only || edit_only) {
10974 rewind(f);
10975 err = histedit_parse_list(histedit_cmds, f, repo);
10976 } else {
10977 if (fclose(f) == EOF) {
10978 err = got_error_from_errno("fclose");
10979 goto done;
10981 f = NULL;
10982 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10983 if (err) {
10984 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10985 err->code != GOT_ERR_HISTEDIT_CMD)
10986 goto done;
10987 err = histedit_edit_list_retry(histedit_cmds, err,
10988 commits, path, branch_name, repo);
10991 done:
10992 if (f && fclose(f) == EOF && err == NULL)
10993 err = got_error_from_errno("fclose");
10994 if (path && unlink(path) != 0 && err == NULL)
10995 err = got_error_from_errno2("unlink", path);
10996 free(path);
10997 return err;
11000 static const struct got_error *
11001 histedit_save_list(struct got_histedit_list *histedit_cmds,
11002 struct got_worktree *worktree, struct got_repository *repo)
11004 const struct got_error *err = NULL;
11005 char *path = NULL;
11006 FILE *f = NULL;
11007 struct got_histedit_list_entry *hle;
11008 struct got_commit_object *commit = NULL;
11010 err = got_worktree_get_histedit_script_path(&path, worktree);
11011 if (err)
11012 return err;
11014 f = fopen(path, "we");
11015 if (f == NULL) {
11016 err = got_error_from_errno2("fopen", path);
11017 goto done;
11019 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11020 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11021 repo);
11022 if (err)
11023 break;
11025 if (hle->logmsg) {
11026 int n = fprintf(f, "%c %s\n",
11027 GOT_HISTEDIT_MESG, hle->logmsg);
11028 if (n < 0) {
11029 err = got_ferror(f, GOT_ERR_IO);
11030 break;
11034 done:
11035 if (f && fclose(f) == EOF && err == NULL)
11036 err = got_error_from_errno("fclose");
11037 free(path);
11038 if (commit)
11039 got_object_commit_close(commit);
11040 return err;
11043 static void
11044 histedit_free_list(struct got_histedit_list *histedit_cmds)
11046 struct got_histedit_list_entry *hle;
11048 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11049 TAILQ_REMOVE(histedit_cmds, hle, entry);
11050 free(hle);
11054 static const struct got_error *
11055 histedit_load_list(struct got_histedit_list *histedit_cmds,
11056 const char *path, struct got_repository *repo)
11058 const struct got_error *err = NULL;
11059 FILE *f = NULL;
11061 f = fopen(path, "re");
11062 if (f == NULL) {
11063 err = got_error_from_errno2("fopen", path);
11064 goto done;
11067 err = histedit_parse_list(histedit_cmds, f, repo);
11068 done:
11069 if (f && fclose(f) == EOF && err == NULL)
11070 err = got_error_from_errno("fclose");
11071 return err;
11074 static const struct got_error *
11075 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11076 const struct got_error *edit_err, struct got_object_id_queue *commits,
11077 const char *path, const char *branch_name, struct got_repository *repo)
11079 const struct got_error *err = NULL, *prev_err = edit_err;
11080 int resp = ' ';
11082 while (resp != 'c' && resp != 'r' && resp != 'a') {
11083 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11084 "or (a)bort: ", getprogname(), prev_err->msg);
11085 resp = getchar();
11086 if (resp == '\n')
11087 resp = getchar();
11088 if (resp == 'c') {
11089 histedit_free_list(histedit_cmds);
11090 err = histedit_run_editor(histedit_cmds, path, commits,
11091 repo);
11092 if (err) {
11093 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11094 err->code != GOT_ERR_HISTEDIT_CMD)
11095 break;
11096 prev_err = err;
11097 resp = ' ';
11098 continue;
11100 break;
11101 } else if (resp == 'r') {
11102 histedit_free_list(histedit_cmds);
11103 err = histedit_edit_script(histedit_cmds,
11104 commits, branch_name, 0, 0, 0, repo);
11105 if (err) {
11106 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11107 err->code != GOT_ERR_HISTEDIT_CMD)
11108 break;
11109 prev_err = err;
11110 resp = ' ';
11111 continue;
11113 break;
11114 } else if (resp == 'a') {
11115 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11116 break;
11117 } else
11118 printf("invalid response '%c'\n", resp);
11121 return err;
11124 static const struct got_error *
11125 histedit_complete(struct got_worktree *worktree,
11126 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11127 struct got_reference *branch, struct got_repository *repo)
11129 printf("Switching work tree to %s\n",
11130 got_ref_get_symref_target(branch));
11131 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11132 branch, repo);
11135 static const struct got_error *
11136 show_histedit_progress(struct got_commit_object *commit,
11137 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11139 const struct got_error *err;
11140 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11142 err = got_object_id_str(&old_id_str, hle->commit_id);
11143 if (err)
11144 goto done;
11146 if (new_id) {
11147 err = got_object_id_str(&new_id_str, new_id);
11148 if (err)
11149 goto done;
11152 old_id_str[12] = '\0';
11153 if (new_id_str)
11154 new_id_str[12] = '\0';
11156 if (hle->logmsg) {
11157 logmsg = strdup(hle->logmsg);
11158 if (logmsg == NULL) {
11159 err = got_error_from_errno("strdup");
11160 goto done;
11162 trim_logmsg(logmsg, 42);
11163 } else {
11164 err = get_short_logmsg(&logmsg, 42, commit);
11165 if (err)
11166 goto done;
11169 switch (hle->cmd->code) {
11170 case GOT_HISTEDIT_PICK:
11171 case GOT_HISTEDIT_EDIT:
11172 printf("%s -> %s: %s\n", old_id_str,
11173 new_id_str ? new_id_str : "no-op change", logmsg);
11174 break;
11175 case GOT_HISTEDIT_DROP:
11176 case GOT_HISTEDIT_FOLD:
11177 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11178 logmsg);
11179 break;
11180 default:
11181 break;
11183 done:
11184 free(old_id_str);
11185 free(new_id_str);
11186 return err;
11189 static const struct got_error *
11190 histedit_commit(struct got_pathlist_head *merged_paths,
11191 struct got_worktree *worktree, struct got_fileindex *fileindex,
11192 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11193 const char *committer, struct got_repository *repo)
11195 const struct got_error *err;
11196 struct got_commit_object *commit;
11197 struct got_object_id *new_commit_id;
11199 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11200 && hle->logmsg == NULL) {
11201 err = histedit_edit_logmsg(hle, repo);
11202 if (err)
11203 return err;
11206 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11207 if (err)
11208 return err;
11210 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11211 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11212 hle->logmsg, repo);
11213 if (err) {
11214 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11215 goto done;
11216 err = show_histedit_progress(commit, hle, NULL);
11217 } else {
11218 err = show_histedit_progress(commit, hle, new_commit_id);
11219 free(new_commit_id);
11221 done:
11222 got_object_commit_close(commit);
11223 return err;
11226 static const struct got_error *
11227 histedit_skip_commit(struct got_histedit_list_entry *hle,
11228 struct got_worktree *worktree, struct got_repository *repo)
11230 const struct got_error *error;
11231 struct got_commit_object *commit;
11233 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11234 repo);
11235 if (error)
11236 return error;
11238 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11239 if (error)
11240 return error;
11242 error = show_histedit_progress(commit, hle, NULL);
11243 got_object_commit_close(commit);
11244 return error;
11247 static const struct got_error *
11248 check_local_changes(void *arg, unsigned char status,
11249 unsigned char staged_status, const char *path,
11250 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11251 struct got_object_id *commit_id, int dirfd, const char *de_name)
11253 int *have_local_changes = arg;
11255 switch (status) {
11256 case GOT_STATUS_ADD:
11257 case GOT_STATUS_DELETE:
11258 case GOT_STATUS_MODIFY:
11259 case GOT_STATUS_CONFLICT:
11260 *have_local_changes = 1;
11261 return got_error(GOT_ERR_CANCELLED);
11262 default:
11263 break;
11266 switch (staged_status) {
11267 case GOT_STATUS_ADD:
11268 case GOT_STATUS_DELETE:
11269 case GOT_STATUS_MODIFY:
11270 *have_local_changes = 1;
11271 return got_error(GOT_ERR_CANCELLED);
11272 default:
11273 break;
11276 return NULL;
11279 static const struct got_error *
11280 cmd_histedit(int argc, char *argv[])
11282 const struct got_error *error = NULL;
11283 struct got_worktree *worktree = NULL;
11284 struct got_fileindex *fileindex = NULL;
11285 struct got_repository *repo = NULL;
11286 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11287 struct got_reference *branch = NULL;
11288 struct got_reference *tmp_branch = NULL;
11289 struct got_object_id *resume_commit_id = NULL;
11290 struct got_object_id *base_commit_id = NULL;
11291 struct got_object_id *head_commit_id = NULL;
11292 struct got_commit_object *commit = NULL;
11293 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11294 struct got_update_progress_arg upa;
11295 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11296 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11297 int list_backups = 0, delete_backups = 0;
11298 const char *edit_script_path = NULL;
11299 struct got_object_id_queue commits;
11300 struct got_pathlist_head merged_paths;
11301 const struct got_object_id_queue *parent_ids;
11302 struct got_object_qid *pid;
11303 struct got_histedit_list histedit_cmds;
11304 struct got_histedit_list_entry *hle;
11305 int *pack_fds = NULL;
11307 STAILQ_INIT(&commits);
11308 TAILQ_INIT(&histedit_cmds);
11309 TAILQ_INIT(&merged_paths);
11310 memset(&upa, 0, sizeof(upa));
11312 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11313 switch (ch) {
11314 case 'a':
11315 abort_edit = 1;
11316 break;
11317 case 'c':
11318 continue_edit = 1;
11319 break;
11320 case 'e':
11321 edit_only = 1;
11322 break;
11323 case 'f':
11324 fold_only = 1;
11325 break;
11326 case 'F':
11327 edit_script_path = optarg;
11328 break;
11329 case 'm':
11330 edit_logmsg_only = 1;
11331 break;
11332 case 'l':
11333 list_backups = 1;
11334 break;
11335 case 'X':
11336 delete_backups = 1;
11337 break;
11338 default:
11339 usage_histedit();
11340 /* NOTREACHED */
11344 argc -= optind;
11345 argv += optind;
11347 #ifndef PROFILE
11348 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11349 "unveil", NULL) == -1)
11350 err(1, "pledge");
11351 #endif
11352 if (abort_edit && continue_edit)
11353 option_conflict('a', 'c');
11354 if (edit_script_path && edit_logmsg_only)
11355 option_conflict('F', 'm');
11356 if (abort_edit && edit_logmsg_only)
11357 option_conflict('a', 'm');
11358 if (continue_edit && edit_logmsg_only)
11359 option_conflict('c', 'm');
11360 if (abort_edit && fold_only)
11361 option_conflict('a', 'f');
11362 if (continue_edit && fold_only)
11363 option_conflict('c', 'f');
11364 if (fold_only && edit_logmsg_only)
11365 option_conflict('f', 'm');
11366 if (edit_script_path && fold_only)
11367 option_conflict('F', 'f');
11368 if (abort_edit && edit_only)
11369 option_conflict('a', 'e');
11370 if (continue_edit && edit_only)
11371 option_conflict('c', 'e');
11372 if (edit_only && edit_logmsg_only)
11373 option_conflict('e', 'm');
11374 if (edit_script_path && edit_only)
11375 option_conflict('F', 'e');
11376 if (list_backups) {
11377 if (abort_edit)
11378 option_conflict('l', 'a');
11379 if (continue_edit)
11380 option_conflict('l', 'c');
11381 if (edit_script_path)
11382 option_conflict('l', 'F');
11383 if (edit_logmsg_only)
11384 option_conflict('l', 'm');
11385 if (fold_only)
11386 option_conflict('l', 'f');
11387 if (edit_only)
11388 option_conflict('l', 'e');
11389 if (delete_backups)
11390 option_conflict('l', 'X');
11391 if (argc != 0 && argc != 1)
11392 usage_histedit();
11393 } else if (delete_backups) {
11394 if (abort_edit)
11395 option_conflict('X', 'a');
11396 if (continue_edit)
11397 option_conflict('X', 'c');
11398 if (edit_script_path)
11399 option_conflict('X', 'F');
11400 if (edit_logmsg_only)
11401 option_conflict('X', 'm');
11402 if (fold_only)
11403 option_conflict('X', 'f');
11404 if (edit_only)
11405 option_conflict('X', 'e');
11406 if (list_backups)
11407 option_conflict('X', 'l');
11408 if (argc != 0 && argc != 1)
11409 usage_histedit();
11410 } else if (argc != 0)
11411 usage_histedit();
11414 * This command cannot apply unveil(2) in all cases because the
11415 * user may choose to run an editor to edit the histedit script
11416 * and to edit individual commit log messages.
11417 * unveil(2) traverses exec(2); if an editor is used we have to
11418 * apply unveil after edit script and log messages have been written.
11419 * XXX TODO: Make use of unveil(2) where possible.
11422 cwd = getcwd(NULL, 0);
11423 if (cwd == NULL) {
11424 error = got_error_from_errno("getcwd");
11425 goto done;
11428 error = got_repo_pack_fds_open(&pack_fds);
11429 if (error != NULL)
11430 goto done;
11432 error = got_worktree_open(&worktree, cwd);
11433 if (error) {
11434 if (list_backups || delete_backups) {
11435 if (error->code != GOT_ERR_NOT_WORKTREE)
11436 goto done;
11437 } else {
11438 if (error->code == GOT_ERR_NOT_WORKTREE)
11439 error = wrap_not_worktree_error(error,
11440 "histedit", cwd);
11441 goto done;
11445 if (list_backups || delete_backups) {
11446 error = got_repo_open(&repo,
11447 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11448 NULL, pack_fds);
11449 if (error != NULL)
11450 goto done;
11451 error = apply_unveil(got_repo_get_path(repo), 0,
11452 worktree ? got_worktree_get_root_path(worktree) : NULL);
11453 if (error)
11454 goto done;
11455 error = process_backup_refs(
11456 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11457 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11458 goto done; /* nothing else to do */
11461 error = get_gitconfig_path(&gitconfig_path);
11462 if (error)
11463 goto done;
11464 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11465 gitconfig_path, pack_fds);
11466 if (error != NULL)
11467 goto done;
11469 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11470 if (error)
11471 goto done;
11472 if (rebase_in_progress) {
11473 error = got_error(GOT_ERR_REBASING);
11474 goto done;
11477 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11478 repo);
11479 if (error)
11480 goto done;
11481 if (merge_in_progress) {
11482 error = got_error(GOT_ERR_MERGE_BUSY);
11483 goto done;
11486 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11487 if (error)
11488 goto done;
11490 if (edit_in_progress && edit_logmsg_only) {
11491 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11492 "histedit operation is in progress in this "
11493 "work tree and must be continued or aborted "
11494 "before the -m option can be used");
11495 goto done;
11497 if (edit_in_progress && fold_only) {
11498 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11499 "histedit operation is in progress in this "
11500 "work tree and must be continued or aborted "
11501 "before the -f option can be used");
11502 goto done;
11504 if (edit_in_progress && edit_only) {
11505 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11506 "histedit operation is in progress in this "
11507 "work tree and must be continued or aborted "
11508 "before the -e option can be used");
11509 goto done;
11512 if (edit_in_progress && abort_edit) {
11513 error = got_worktree_histedit_continue(&resume_commit_id,
11514 &tmp_branch, &branch, &base_commit_id, &fileindex,
11515 worktree, repo);
11516 if (error)
11517 goto done;
11518 printf("Switching work tree to %s\n",
11519 got_ref_get_symref_target(branch));
11520 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11521 branch, base_commit_id, abort_progress, &upa);
11522 if (error)
11523 goto done;
11524 printf("Histedit of %s aborted\n",
11525 got_ref_get_symref_target(branch));
11526 print_merge_progress_stats(&upa);
11527 goto done; /* nothing else to do */
11528 } else if (abort_edit) {
11529 error = got_error(GOT_ERR_NOT_HISTEDIT);
11530 goto done;
11533 error = get_author(&committer, repo, worktree);
11534 if (error)
11535 goto done;
11537 if (continue_edit) {
11538 char *path;
11540 if (!edit_in_progress) {
11541 error = got_error(GOT_ERR_NOT_HISTEDIT);
11542 goto done;
11545 error = got_worktree_get_histedit_script_path(&path, worktree);
11546 if (error)
11547 goto done;
11549 error = histedit_load_list(&histedit_cmds, path, repo);
11550 free(path);
11551 if (error)
11552 goto done;
11554 error = got_worktree_histedit_continue(&resume_commit_id,
11555 &tmp_branch, &branch, &base_commit_id, &fileindex,
11556 worktree, repo);
11557 if (error)
11558 goto done;
11560 error = got_ref_resolve(&head_commit_id, repo, branch);
11561 if (error)
11562 goto done;
11564 error = got_object_open_as_commit(&commit, repo,
11565 head_commit_id);
11566 if (error)
11567 goto done;
11568 parent_ids = got_object_commit_get_parent_ids(commit);
11569 pid = STAILQ_FIRST(parent_ids);
11570 if (pid == NULL) {
11571 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11572 goto done;
11574 error = collect_commits(&commits, head_commit_id, &pid->id,
11575 base_commit_id, got_worktree_get_path_prefix(worktree),
11576 GOT_ERR_HISTEDIT_PATH, repo);
11577 got_object_commit_close(commit);
11578 commit = NULL;
11579 if (error)
11580 goto done;
11581 } else {
11582 if (edit_in_progress) {
11583 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11584 goto done;
11587 error = got_ref_open(&branch, repo,
11588 got_worktree_get_head_ref_name(worktree), 0);
11589 if (error != NULL)
11590 goto done;
11592 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11593 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11594 "will not edit commit history of a branch outside "
11595 "the \"refs/heads/\" reference namespace");
11596 goto done;
11599 error = got_ref_resolve(&head_commit_id, repo, branch);
11600 got_ref_close(branch);
11601 branch = NULL;
11602 if (error)
11603 goto done;
11605 error = got_object_open_as_commit(&commit, repo,
11606 head_commit_id);
11607 if (error)
11608 goto done;
11609 parent_ids = got_object_commit_get_parent_ids(commit);
11610 pid = STAILQ_FIRST(parent_ids);
11611 if (pid == NULL) {
11612 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11613 goto done;
11615 error = collect_commits(&commits, head_commit_id, &pid->id,
11616 got_worktree_get_base_commit_id(worktree),
11617 got_worktree_get_path_prefix(worktree),
11618 GOT_ERR_HISTEDIT_PATH, repo);
11619 got_object_commit_close(commit);
11620 commit = NULL;
11621 if (error)
11622 goto done;
11624 if (STAILQ_EMPTY(&commits)) {
11625 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11626 goto done;
11629 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11630 &base_commit_id, &fileindex, worktree, repo);
11631 if (error)
11632 goto done;
11634 if (edit_script_path) {
11635 error = histedit_load_list(&histedit_cmds,
11636 edit_script_path, repo);
11637 if (error) {
11638 got_worktree_histedit_abort(worktree, fileindex,
11639 repo, branch, base_commit_id,
11640 abort_progress, &upa);
11641 print_merge_progress_stats(&upa);
11642 goto done;
11644 } else {
11645 const char *branch_name;
11646 branch_name = got_ref_get_symref_target(branch);
11647 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11648 branch_name += 11;
11649 error = histedit_edit_script(&histedit_cmds, &commits,
11650 branch_name, edit_logmsg_only, fold_only,
11651 edit_only, repo);
11652 if (error) {
11653 got_worktree_histedit_abort(worktree, fileindex,
11654 repo, branch, base_commit_id,
11655 abort_progress, &upa);
11656 print_merge_progress_stats(&upa);
11657 goto done;
11662 error = histedit_save_list(&histedit_cmds, worktree,
11663 repo);
11664 if (error) {
11665 got_worktree_histedit_abort(worktree, fileindex,
11666 repo, branch, base_commit_id,
11667 abort_progress, &upa);
11668 print_merge_progress_stats(&upa);
11669 goto done;
11674 error = histedit_check_script(&histedit_cmds, &commits, repo);
11675 if (error)
11676 goto done;
11678 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11679 if (resume_commit_id) {
11680 if (got_object_id_cmp(hle->commit_id,
11681 resume_commit_id) != 0)
11682 continue;
11684 resume_commit_id = NULL;
11685 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11686 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11687 error = histedit_skip_commit(hle, worktree,
11688 repo);
11689 if (error)
11690 goto done;
11691 } else {
11692 struct got_pathlist_head paths;
11693 int have_changes = 0;
11695 TAILQ_INIT(&paths);
11696 error = got_pathlist_append(&paths, "", NULL);
11697 if (error)
11698 goto done;
11699 error = got_worktree_status(worktree, &paths,
11700 repo, 0, check_local_changes, &have_changes,
11701 check_cancelled, NULL);
11702 got_pathlist_free(&paths);
11703 if (error) {
11704 if (error->code != GOT_ERR_CANCELLED)
11705 goto done;
11706 if (sigint_received || sigpipe_received)
11707 goto done;
11709 if (have_changes) {
11710 error = histedit_commit(NULL, worktree,
11711 fileindex, tmp_branch, hle,
11712 committer, repo);
11713 if (error)
11714 goto done;
11715 } else {
11716 error = got_object_open_as_commit(
11717 &commit, repo, hle->commit_id);
11718 if (error)
11719 goto done;
11720 error = show_histedit_progress(commit,
11721 hle, NULL);
11722 got_object_commit_close(commit);
11723 commit = NULL;
11724 if (error)
11725 goto done;
11728 continue;
11731 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11732 error = histedit_skip_commit(hle, worktree, repo);
11733 if (error)
11734 goto done;
11735 continue;
11738 error = got_object_open_as_commit(&commit, repo,
11739 hle->commit_id);
11740 if (error)
11741 goto done;
11742 parent_ids = got_object_commit_get_parent_ids(commit);
11743 pid = STAILQ_FIRST(parent_ids);
11745 error = got_worktree_histedit_merge_files(&merged_paths,
11746 worktree, fileindex, &pid->id, hle->commit_id, repo,
11747 update_progress, &upa, check_cancelled, NULL);
11748 if (error)
11749 goto done;
11750 got_object_commit_close(commit);
11751 commit = NULL;
11753 print_merge_progress_stats(&upa);
11754 if (upa.conflicts > 0 || upa.missing > 0 ||
11755 upa.not_deleted > 0 || upa.unversioned > 0) {
11756 if (upa.conflicts > 0) {
11757 error = show_rebase_merge_conflict(
11758 hle->commit_id, repo);
11759 if (error)
11760 goto done;
11762 got_worktree_rebase_pathlist_free(&merged_paths);
11763 break;
11766 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11767 char *id_str;
11768 error = got_object_id_str(&id_str, hle->commit_id);
11769 if (error)
11770 goto done;
11771 printf("Stopping histedit for amending commit %s\n",
11772 id_str);
11773 free(id_str);
11774 got_worktree_rebase_pathlist_free(&merged_paths);
11775 error = got_worktree_histedit_postpone(worktree,
11776 fileindex);
11777 goto done;
11780 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11781 error = histedit_skip_commit(hle, worktree, repo);
11782 if (error)
11783 goto done;
11784 continue;
11787 error = histedit_commit(&merged_paths, worktree, fileindex,
11788 tmp_branch, hle, committer, repo);
11789 got_worktree_rebase_pathlist_free(&merged_paths);
11790 if (error)
11791 goto done;
11794 if (upa.conflicts > 0 || upa.missing > 0 ||
11795 upa.not_deleted > 0 || upa.unversioned > 0) {
11796 error = got_worktree_histedit_postpone(worktree, fileindex);
11797 if (error)
11798 goto done;
11799 if (upa.conflicts > 0 && upa.missing == 0 &&
11800 upa.not_deleted == 0 && upa.unversioned == 0) {
11801 error = got_error_msg(GOT_ERR_CONFLICTS,
11802 "conflicts must be resolved before histedit "
11803 "can continue");
11804 } else if (upa.conflicts > 0) {
11805 error = got_error_msg(GOT_ERR_CONFLICTS,
11806 "conflicts must be resolved before histedit "
11807 "can continue; changes destined for some "
11808 "files were not yet merged and should be "
11809 "merged manually if required before the "
11810 "histedit operation is continued");
11811 } else {
11812 error = got_error_msg(GOT_ERR_CONFLICTS,
11813 "changes destined for some files were not "
11814 "yet merged and should be merged manually "
11815 "if required before the histedit operation "
11816 "is continued");
11818 } else
11819 error = histedit_complete(worktree, fileindex, tmp_branch,
11820 branch, repo);
11821 done:
11822 free(cwd);
11823 free(committer);
11824 free(gitconfig_path);
11825 got_object_id_queue_free(&commits);
11826 histedit_free_list(&histedit_cmds);
11827 free(head_commit_id);
11828 free(base_commit_id);
11829 free(resume_commit_id);
11830 if (commit)
11831 got_object_commit_close(commit);
11832 if (branch)
11833 got_ref_close(branch);
11834 if (tmp_branch)
11835 got_ref_close(tmp_branch);
11836 if (worktree)
11837 got_worktree_close(worktree);
11838 if (repo) {
11839 const struct got_error *close_err = got_repo_close(repo);
11840 if (error == NULL)
11841 error = close_err;
11843 if (pack_fds) {
11844 const struct got_error *pack_err =
11845 got_repo_pack_fds_close(pack_fds);
11846 if (error == NULL)
11847 error = pack_err;
11849 return error;
11852 __dead static void
11853 usage_integrate(void)
11855 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11856 exit(1);
11859 static const struct got_error *
11860 cmd_integrate(int argc, char *argv[])
11862 const struct got_error *error = NULL;
11863 struct got_repository *repo = NULL;
11864 struct got_worktree *worktree = NULL;
11865 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11866 const char *branch_arg = NULL;
11867 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11868 struct got_fileindex *fileindex = NULL;
11869 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11870 int ch;
11871 struct got_update_progress_arg upa;
11872 int *pack_fds = NULL;
11874 while ((ch = getopt(argc, argv, "")) != -1) {
11875 switch (ch) {
11876 default:
11877 usage_integrate();
11878 /* NOTREACHED */
11882 argc -= optind;
11883 argv += optind;
11885 if (argc != 1)
11886 usage_integrate();
11887 branch_arg = argv[0];
11888 #ifndef PROFILE
11889 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11890 "unveil", NULL) == -1)
11891 err(1, "pledge");
11892 #endif
11893 cwd = getcwd(NULL, 0);
11894 if (cwd == NULL) {
11895 error = got_error_from_errno("getcwd");
11896 goto done;
11899 error = got_repo_pack_fds_open(&pack_fds);
11900 if (error != NULL)
11901 goto done;
11903 error = got_worktree_open(&worktree, cwd);
11904 if (error) {
11905 if (error->code == GOT_ERR_NOT_WORKTREE)
11906 error = wrap_not_worktree_error(error, "integrate",
11907 cwd);
11908 goto done;
11911 error = check_rebase_or_histedit_in_progress(worktree);
11912 if (error)
11913 goto done;
11915 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11916 NULL, pack_fds);
11917 if (error != NULL)
11918 goto done;
11920 error = apply_unveil(got_repo_get_path(repo), 0,
11921 got_worktree_get_root_path(worktree));
11922 if (error)
11923 goto done;
11925 error = check_merge_in_progress(worktree, repo);
11926 if (error)
11927 goto done;
11929 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11930 error = got_error_from_errno("asprintf");
11931 goto done;
11934 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11935 &base_branch_ref, worktree, refname, repo);
11936 if (error)
11937 goto done;
11939 refname = strdup(got_ref_get_name(branch_ref));
11940 if (refname == NULL) {
11941 error = got_error_from_errno("strdup");
11942 got_worktree_integrate_abort(worktree, fileindex, repo,
11943 branch_ref, base_branch_ref);
11944 goto done;
11946 base_refname = strdup(got_ref_get_name(base_branch_ref));
11947 if (base_refname == NULL) {
11948 error = got_error_from_errno("strdup");
11949 got_worktree_integrate_abort(worktree, fileindex, repo,
11950 branch_ref, base_branch_ref);
11951 goto done;
11954 error = got_ref_resolve(&commit_id, repo, branch_ref);
11955 if (error)
11956 goto done;
11958 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11959 if (error)
11960 goto done;
11962 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11963 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11964 "specified branch has already been integrated");
11965 got_worktree_integrate_abort(worktree, fileindex, repo,
11966 branch_ref, base_branch_ref);
11967 goto done;
11970 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11971 if (error) {
11972 if (error->code == GOT_ERR_ANCESTRY)
11973 error = got_error(GOT_ERR_REBASE_REQUIRED);
11974 got_worktree_integrate_abort(worktree, fileindex, repo,
11975 branch_ref, base_branch_ref);
11976 goto done;
11979 memset(&upa, 0, sizeof(upa));
11980 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11981 branch_ref, base_branch_ref, update_progress, &upa,
11982 check_cancelled, NULL);
11983 if (error)
11984 goto done;
11986 printf("Integrated %s into %s\n", refname, base_refname);
11987 print_update_progress_stats(&upa);
11988 done:
11989 if (repo) {
11990 const struct got_error *close_err = got_repo_close(repo);
11991 if (error == NULL)
11992 error = close_err;
11994 if (worktree)
11995 got_worktree_close(worktree);
11996 if (pack_fds) {
11997 const struct got_error *pack_err =
11998 got_repo_pack_fds_close(pack_fds);
11999 if (error == NULL)
12000 error = pack_err;
12002 free(cwd);
12003 free(base_commit_id);
12004 free(commit_id);
12005 free(refname);
12006 free(base_refname);
12007 return error;
12010 __dead static void
12011 usage_merge(void)
12013 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12014 exit(1);
12017 static const struct got_error *
12018 cmd_merge(int argc, char *argv[])
12020 const struct got_error *error = NULL;
12021 struct got_worktree *worktree = NULL;
12022 struct got_repository *repo = NULL;
12023 struct got_fileindex *fileindex = NULL;
12024 char *cwd = NULL, *id_str = NULL, *author = NULL;
12025 struct got_reference *branch = NULL, *wt_branch = NULL;
12026 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12027 struct got_object_id *wt_branch_tip = NULL;
12028 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12029 int interrupt_merge = 0;
12030 struct got_update_progress_arg upa;
12031 struct got_object_id *merge_commit_id = NULL;
12032 char *branch_name = NULL;
12033 int *pack_fds = NULL;
12035 memset(&upa, 0, sizeof(upa));
12037 while ((ch = getopt(argc, argv, "acn")) != -1) {
12038 switch (ch) {
12039 case 'a':
12040 abort_merge = 1;
12041 break;
12042 case 'c':
12043 continue_merge = 1;
12044 break;
12045 case 'n':
12046 interrupt_merge = 1;
12047 break;
12048 default:
12049 usage_rebase();
12050 /* NOTREACHED */
12054 argc -= optind;
12055 argv += optind;
12057 #ifndef PROFILE
12058 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12059 "unveil", NULL) == -1)
12060 err(1, "pledge");
12061 #endif
12063 if (abort_merge && continue_merge)
12064 option_conflict('a', 'c');
12065 if (abort_merge || continue_merge) {
12066 if (argc != 0)
12067 usage_merge();
12068 } else if (argc != 1)
12069 usage_merge();
12071 cwd = getcwd(NULL, 0);
12072 if (cwd == NULL) {
12073 error = got_error_from_errno("getcwd");
12074 goto done;
12077 error = got_repo_pack_fds_open(&pack_fds);
12078 if (error != NULL)
12079 goto done;
12081 error = got_worktree_open(&worktree, cwd);
12082 if (error) {
12083 if (error->code == GOT_ERR_NOT_WORKTREE)
12084 error = wrap_not_worktree_error(error,
12085 "merge", cwd);
12086 goto done;
12089 error = got_repo_open(&repo,
12090 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12091 pack_fds);
12092 if (error != NULL)
12093 goto done;
12095 error = apply_unveil(got_repo_get_path(repo), 0,
12096 worktree ? got_worktree_get_root_path(worktree) : NULL);
12097 if (error)
12098 goto done;
12100 error = check_rebase_or_histedit_in_progress(worktree);
12101 if (error)
12102 goto done;
12104 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12105 repo);
12106 if (error)
12107 goto done;
12109 if (abort_merge) {
12110 if (!merge_in_progress) {
12111 error = got_error(GOT_ERR_NOT_MERGING);
12112 goto done;
12114 error = got_worktree_merge_continue(&branch_name,
12115 &branch_tip, &fileindex, worktree, repo);
12116 if (error)
12117 goto done;
12118 error = got_worktree_merge_abort(worktree, fileindex, repo,
12119 abort_progress, &upa);
12120 if (error)
12121 goto done;
12122 printf("Merge of %s aborted\n", branch_name);
12123 goto done; /* nothing else to do */
12126 error = get_author(&author, repo, worktree);
12127 if (error)
12128 goto done;
12130 if (continue_merge) {
12131 if (!merge_in_progress) {
12132 error = got_error(GOT_ERR_NOT_MERGING);
12133 goto done;
12135 error = got_worktree_merge_continue(&branch_name,
12136 &branch_tip, &fileindex, worktree, repo);
12137 if (error)
12138 goto done;
12139 } else {
12140 error = got_ref_open(&branch, repo, argv[0], 0);
12141 if (error != NULL)
12142 goto done;
12143 branch_name = strdup(got_ref_get_name(branch));
12144 if (branch_name == NULL) {
12145 error = got_error_from_errno("strdup");
12146 goto done;
12148 error = got_ref_resolve(&branch_tip, repo, branch);
12149 if (error)
12150 goto done;
12153 error = got_ref_open(&wt_branch, repo,
12154 got_worktree_get_head_ref_name(worktree), 0);
12155 if (error)
12156 goto done;
12157 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12158 if (error)
12159 goto done;
12160 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12161 wt_branch_tip, branch_tip, 0, repo,
12162 check_cancelled, NULL);
12163 if (error && error->code != GOT_ERR_ANCESTRY)
12164 goto done;
12166 if (!continue_merge) {
12167 error = check_path_prefix(wt_branch_tip, branch_tip,
12168 got_worktree_get_path_prefix(worktree),
12169 GOT_ERR_MERGE_PATH, repo);
12170 if (error)
12171 goto done;
12172 if (yca_id) {
12173 error = check_same_branch(wt_branch_tip, branch,
12174 yca_id, repo);
12175 if (error) {
12176 if (error->code != GOT_ERR_ANCESTRY)
12177 goto done;
12178 error = NULL;
12179 } else {
12180 static char msg[512];
12181 snprintf(msg, sizeof(msg),
12182 "cannot create a merge commit because "
12183 "%s is based on %s; %s can be integrated "
12184 "with 'got integrate' instead", branch_name,
12185 got_worktree_get_head_ref_name(worktree),
12186 branch_name);
12187 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12188 goto done;
12191 error = got_worktree_merge_prepare(&fileindex, worktree,
12192 branch, repo);
12193 if (error)
12194 goto done;
12196 error = got_worktree_merge_branch(worktree, fileindex,
12197 yca_id, branch_tip, repo, update_progress, &upa,
12198 check_cancelled, NULL);
12199 if (error)
12200 goto done;
12201 print_merge_progress_stats(&upa);
12202 if (!upa.did_something) {
12203 error = got_worktree_merge_abort(worktree, fileindex,
12204 repo, abort_progress, &upa);
12205 if (error)
12206 goto done;
12207 printf("Already up-to-date\n");
12208 goto done;
12212 if (interrupt_merge) {
12213 error = got_worktree_merge_postpone(worktree, fileindex);
12214 if (error)
12215 goto done;
12216 printf("Merge of %s interrupted on request\n", branch_name);
12217 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12218 upa.not_deleted > 0 || upa.unversioned > 0) {
12219 error = got_worktree_merge_postpone(worktree, fileindex);
12220 if (error)
12221 goto done;
12222 if (upa.conflicts > 0 && upa.missing == 0 &&
12223 upa.not_deleted == 0 && upa.unversioned == 0) {
12224 error = got_error_msg(GOT_ERR_CONFLICTS,
12225 "conflicts must be resolved before merging "
12226 "can continue");
12227 } else if (upa.conflicts > 0) {
12228 error = got_error_msg(GOT_ERR_CONFLICTS,
12229 "conflicts must be resolved before merging "
12230 "can continue; changes destined for some "
12231 "files were not yet merged and "
12232 "should be merged manually if required before the "
12233 "merge operation is continued");
12234 } else {
12235 error = got_error_msg(GOT_ERR_CONFLICTS,
12236 "changes destined for some "
12237 "files were not yet merged and should be "
12238 "merged manually if required before the "
12239 "merge operation is continued");
12241 goto done;
12242 } else {
12243 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12244 fileindex, author, NULL, 1, branch_tip, branch_name,
12245 repo, continue_merge ? print_status : NULL, NULL);
12246 if (error)
12247 goto done;
12248 error = got_worktree_merge_complete(worktree, fileindex, repo);
12249 if (error)
12250 goto done;
12251 error = got_object_id_str(&id_str, merge_commit_id);
12252 if (error)
12253 goto done;
12254 printf("Merged %s into %s: %s\n", branch_name,
12255 got_worktree_get_head_ref_name(worktree),
12256 id_str);
12259 done:
12260 free(id_str);
12261 free(merge_commit_id);
12262 free(author);
12263 free(branch_tip);
12264 free(branch_name);
12265 free(yca_id);
12266 if (branch)
12267 got_ref_close(branch);
12268 if (wt_branch)
12269 got_ref_close(wt_branch);
12270 if (worktree)
12271 got_worktree_close(worktree);
12272 if (repo) {
12273 const struct got_error *close_err = got_repo_close(repo);
12274 if (error == NULL)
12275 error = close_err;
12277 if (pack_fds) {
12278 const struct got_error *pack_err =
12279 got_repo_pack_fds_close(pack_fds);
12280 if (error == NULL)
12281 error = pack_err;
12283 return error;
12286 __dead static void
12287 usage_stage(void)
12289 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12290 "[path ...]\n", getprogname());
12291 exit(1);
12294 static const struct got_error *
12295 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12296 const char *path, struct got_object_id *blob_id,
12297 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12298 int dirfd, const char *de_name)
12300 const struct got_error *err = NULL;
12301 char *id_str = NULL;
12303 if (staged_status != GOT_STATUS_ADD &&
12304 staged_status != GOT_STATUS_MODIFY &&
12305 staged_status != GOT_STATUS_DELETE)
12306 return NULL;
12308 if (staged_status == GOT_STATUS_ADD ||
12309 staged_status == GOT_STATUS_MODIFY)
12310 err = got_object_id_str(&id_str, staged_blob_id);
12311 else
12312 err = got_object_id_str(&id_str, blob_id);
12313 if (err)
12314 return err;
12316 printf("%s %c %s\n", id_str, staged_status, path);
12317 free(id_str);
12318 return NULL;
12321 static const struct got_error *
12322 cmd_stage(int argc, char *argv[])
12324 const struct got_error *error = NULL;
12325 struct got_repository *repo = NULL;
12326 struct got_worktree *worktree = NULL;
12327 char *cwd = NULL;
12328 struct got_pathlist_head paths;
12329 struct got_pathlist_entry *pe;
12330 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12331 FILE *patch_script_file = NULL;
12332 const char *patch_script_path = NULL;
12333 struct choose_patch_arg cpa;
12334 int *pack_fds = NULL;
12336 TAILQ_INIT(&paths);
12338 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12339 switch (ch) {
12340 case 'l':
12341 list_stage = 1;
12342 break;
12343 case 'p':
12344 pflag = 1;
12345 break;
12346 case 'F':
12347 patch_script_path = optarg;
12348 break;
12349 case 'S':
12350 allow_bad_symlinks = 1;
12351 break;
12352 default:
12353 usage_stage();
12354 /* NOTREACHED */
12358 argc -= optind;
12359 argv += optind;
12361 #ifndef PROFILE
12362 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12363 "unveil", NULL) == -1)
12364 err(1, "pledge");
12365 #endif
12366 if (list_stage && (pflag || patch_script_path))
12367 errx(1, "-l option cannot be used with other options");
12368 if (patch_script_path && !pflag)
12369 errx(1, "-F option can only be used together with -p option");
12371 cwd = getcwd(NULL, 0);
12372 if (cwd == NULL) {
12373 error = got_error_from_errno("getcwd");
12374 goto done;
12377 error = got_repo_pack_fds_open(&pack_fds);
12378 if (error != NULL)
12379 goto done;
12381 error = got_worktree_open(&worktree, cwd);
12382 if (error) {
12383 if (error->code == GOT_ERR_NOT_WORKTREE)
12384 error = wrap_not_worktree_error(error, "stage", cwd);
12385 goto done;
12388 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12389 NULL, pack_fds);
12390 if (error != NULL)
12391 goto done;
12393 if (patch_script_path) {
12394 patch_script_file = fopen(patch_script_path, "re");
12395 if (patch_script_file == NULL) {
12396 error = got_error_from_errno2("fopen",
12397 patch_script_path);
12398 goto done;
12401 error = apply_unveil(got_repo_get_path(repo), 0,
12402 got_worktree_get_root_path(worktree));
12403 if (error)
12404 goto done;
12406 error = check_merge_in_progress(worktree, repo);
12407 if (error)
12408 goto done;
12410 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12411 if (error)
12412 goto done;
12414 if (list_stage)
12415 error = got_worktree_status(worktree, &paths, repo, 0,
12416 print_stage, NULL, check_cancelled, NULL);
12417 else {
12418 cpa.patch_script_file = patch_script_file;
12419 cpa.action = "stage";
12420 error = got_worktree_stage(worktree, &paths,
12421 pflag ? NULL : print_status, NULL,
12422 pflag ? choose_patch : NULL, &cpa,
12423 allow_bad_symlinks, repo);
12425 done:
12426 if (patch_script_file && fclose(patch_script_file) == EOF &&
12427 error == NULL)
12428 error = got_error_from_errno2("fclose", patch_script_path);
12429 if (repo) {
12430 const struct got_error *close_err = got_repo_close(repo);
12431 if (error == NULL)
12432 error = close_err;
12434 if (worktree)
12435 got_worktree_close(worktree);
12436 if (pack_fds) {
12437 const struct got_error *pack_err =
12438 got_repo_pack_fds_close(pack_fds);
12439 if (error == NULL)
12440 error = pack_err;
12442 TAILQ_FOREACH(pe, &paths, entry)
12443 free((char *)pe->path);
12444 got_pathlist_free(&paths);
12445 free(cwd);
12446 return error;
12449 __dead static void
12450 usage_unstage(void)
12452 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12453 "[path ...]\n", getprogname());
12454 exit(1);
12458 static const struct got_error *
12459 cmd_unstage(int argc, char *argv[])
12461 const struct got_error *error = NULL;
12462 struct got_repository *repo = NULL;
12463 struct got_worktree *worktree = NULL;
12464 char *cwd = NULL;
12465 struct got_pathlist_head paths;
12466 struct got_pathlist_entry *pe;
12467 int ch, pflag = 0;
12468 struct got_update_progress_arg upa;
12469 FILE *patch_script_file = NULL;
12470 const char *patch_script_path = NULL;
12471 struct choose_patch_arg cpa;
12472 int *pack_fds = NULL;
12474 TAILQ_INIT(&paths);
12476 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12477 switch (ch) {
12478 case 'p':
12479 pflag = 1;
12480 break;
12481 case 'F':
12482 patch_script_path = optarg;
12483 break;
12484 default:
12485 usage_unstage();
12486 /* NOTREACHED */
12490 argc -= optind;
12491 argv += optind;
12493 #ifndef PROFILE
12494 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12495 "unveil", NULL) == -1)
12496 err(1, "pledge");
12497 #endif
12498 if (patch_script_path && !pflag)
12499 errx(1, "-F option can only be used together with -p option");
12501 cwd = getcwd(NULL, 0);
12502 if (cwd == NULL) {
12503 error = got_error_from_errno("getcwd");
12504 goto done;
12507 error = got_repo_pack_fds_open(&pack_fds);
12508 if (error != NULL)
12509 goto done;
12511 error = got_worktree_open(&worktree, cwd);
12512 if (error) {
12513 if (error->code == GOT_ERR_NOT_WORKTREE)
12514 error = wrap_not_worktree_error(error, "unstage", cwd);
12515 goto done;
12518 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12519 NULL, pack_fds);
12520 if (error != NULL)
12521 goto done;
12523 if (patch_script_path) {
12524 patch_script_file = fopen(patch_script_path, "re");
12525 if (patch_script_file == NULL) {
12526 error = got_error_from_errno2("fopen",
12527 patch_script_path);
12528 goto done;
12532 error = apply_unveil(got_repo_get_path(repo), 0,
12533 got_worktree_get_root_path(worktree));
12534 if (error)
12535 goto done;
12537 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12538 if (error)
12539 goto done;
12541 cpa.patch_script_file = patch_script_file;
12542 cpa.action = "unstage";
12543 memset(&upa, 0, sizeof(upa));
12544 error = got_worktree_unstage(worktree, &paths, update_progress,
12545 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12546 if (!error)
12547 print_merge_progress_stats(&upa);
12548 done:
12549 if (patch_script_file && fclose(patch_script_file) == EOF &&
12550 error == NULL)
12551 error = got_error_from_errno2("fclose", patch_script_path);
12552 if (repo) {
12553 const struct got_error *close_err = got_repo_close(repo);
12554 if (error == NULL)
12555 error = close_err;
12557 if (worktree)
12558 got_worktree_close(worktree);
12559 if (pack_fds) {
12560 const struct got_error *pack_err =
12561 got_repo_pack_fds_close(pack_fds);
12562 if (error == NULL)
12563 error = pack_err;
12565 TAILQ_FOREACH(pe, &paths, entry)
12566 free((char *)pe->path);
12567 got_pathlist_free(&paths);
12568 free(cwd);
12569 return error;
12572 __dead static void
12573 usage_cat(void)
12575 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12576 "arg ...\n", getprogname());
12577 exit(1);
12580 static const struct got_error *
12581 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12583 const struct got_error *err;
12584 struct got_blob_object *blob;
12585 int fd = -1;
12587 fd = got_opentempfd();
12588 if (fd == -1)
12589 return got_error_from_errno("got_opentempfd");
12591 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12592 if (err)
12593 goto done;
12595 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12596 done:
12597 if (fd != -1 && close(fd) == -1 && err == NULL)
12598 err = got_error_from_errno("close");
12599 if (blob)
12600 got_object_blob_close(blob);
12601 return err;
12604 static const struct got_error *
12605 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12607 const struct got_error *err;
12608 struct got_tree_object *tree;
12609 int nentries, i;
12611 err = got_object_open_as_tree(&tree, repo, id);
12612 if (err)
12613 return err;
12615 nentries = got_object_tree_get_nentries(tree);
12616 for (i = 0; i < nentries; i++) {
12617 struct got_tree_entry *te;
12618 char *id_str;
12619 if (sigint_received || sigpipe_received)
12620 break;
12621 te = got_object_tree_get_entry(tree, i);
12622 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12623 if (err)
12624 break;
12625 fprintf(outfile, "%s %.7o %s\n", id_str,
12626 got_tree_entry_get_mode(te),
12627 got_tree_entry_get_name(te));
12628 free(id_str);
12631 got_object_tree_close(tree);
12632 return err;
12635 static const struct got_error *
12636 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12638 const struct got_error *err;
12639 struct got_commit_object *commit;
12640 const struct got_object_id_queue *parent_ids;
12641 struct got_object_qid *pid;
12642 char *id_str = NULL;
12643 const char *logmsg = NULL;
12644 char gmtoff[6];
12646 err = got_object_open_as_commit(&commit, repo, id);
12647 if (err)
12648 return err;
12650 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12651 if (err)
12652 goto done;
12654 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12655 parent_ids = got_object_commit_get_parent_ids(commit);
12656 fprintf(outfile, "numparents %d\n",
12657 got_object_commit_get_nparents(commit));
12658 STAILQ_FOREACH(pid, parent_ids, entry) {
12659 char *pid_str;
12660 err = got_object_id_str(&pid_str, &pid->id);
12661 if (err)
12662 goto done;
12663 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12664 free(pid_str);
12666 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12667 got_object_commit_get_author_gmtoff(commit));
12668 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12669 got_object_commit_get_author(commit),
12670 (long long)got_object_commit_get_author_time(commit),
12671 gmtoff);
12673 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12674 got_object_commit_get_committer_gmtoff(commit));
12675 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12676 got_object_commit_get_committer(commit),
12677 (long long)got_object_commit_get_committer_time(commit),
12678 gmtoff);
12680 logmsg = got_object_commit_get_logmsg_raw(commit);
12681 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12682 fprintf(outfile, "%s", logmsg);
12683 done:
12684 free(id_str);
12685 got_object_commit_close(commit);
12686 return err;
12689 static const struct got_error *
12690 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12692 const struct got_error *err;
12693 struct got_tag_object *tag;
12694 char *id_str = NULL;
12695 const char *tagmsg = NULL;
12696 char gmtoff[6];
12698 err = got_object_open_as_tag(&tag, repo, id);
12699 if (err)
12700 return err;
12702 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12703 if (err)
12704 goto done;
12706 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12708 switch (got_object_tag_get_object_type(tag)) {
12709 case GOT_OBJ_TYPE_BLOB:
12710 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12711 GOT_OBJ_LABEL_BLOB);
12712 break;
12713 case GOT_OBJ_TYPE_TREE:
12714 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12715 GOT_OBJ_LABEL_TREE);
12716 break;
12717 case GOT_OBJ_TYPE_COMMIT:
12718 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12719 GOT_OBJ_LABEL_COMMIT);
12720 break;
12721 case GOT_OBJ_TYPE_TAG:
12722 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12723 GOT_OBJ_LABEL_TAG);
12724 break;
12725 default:
12726 break;
12729 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12730 got_object_tag_get_name(tag));
12732 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12733 got_object_tag_get_tagger_gmtoff(tag));
12734 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12735 got_object_tag_get_tagger(tag),
12736 (long long)got_object_tag_get_tagger_time(tag),
12737 gmtoff);
12739 tagmsg = got_object_tag_get_message(tag);
12740 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12741 fprintf(outfile, "%s", tagmsg);
12742 done:
12743 free(id_str);
12744 got_object_tag_close(tag);
12745 return err;
12748 static const struct got_error *
12749 cmd_cat(int argc, char *argv[])
12751 const struct got_error *error;
12752 struct got_repository *repo = NULL;
12753 struct got_worktree *worktree = NULL;
12754 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12755 const char *commit_id_str = NULL;
12756 struct got_object_id *id = NULL, *commit_id = NULL;
12757 struct got_commit_object *commit = NULL;
12758 int ch, obj_type, i, force_path = 0;
12759 struct got_reflist_head refs;
12760 int *pack_fds = NULL;
12762 TAILQ_INIT(&refs);
12764 #ifndef PROFILE
12765 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12766 NULL) == -1)
12767 err(1, "pledge");
12768 #endif
12770 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12771 switch (ch) {
12772 case 'c':
12773 commit_id_str = optarg;
12774 break;
12775 case 'r':
12776 repo_path = realpath(optarg, NULL);
12777 if (repo_path == NULL)
12778 return got_error_from_errno2("realpath",
12779 optarg);
12780 got_path_strip_trailing_slashes(repo_path);
12781 break;
12782 case 'P':
12783 force_path = 1;
12784 break;
12785 default:
12786 usage_cat();
12787 /* NOTREACHED */
12791 argc -= optind;
12792 argv += optind;
12794 cwd = getcwd(NULL, 0);
12795 if (cwd == NULL) {
12796 error = got_error_from_errno("getcwd");
12797 goto done;
12800 error = got_repo_pack_fds_open(&pack_fds);
12801 if (error != NULL)
12802 goto done;
12804 if (repo_path == NULL) {
12805 error = got_worktree_open(&worktree, cwd);
12806 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12807 goto done;
12808 if (worktree) {
12809 repo_path = strdup(
12810 got_worktree_get_repo_path(worktree));
12811 if (repo_path == NULL) {
12812 error = got_error_from_errno("strdup");
12813 goto done;
12816 /* Release work tree lock. */
12817 got_worktree_close(worktree);
12818 worktree = NULL;
12822 if (repo_path == NULL) {
12823 repo_path = strdup(cwd);
12824 if (repo_path == NULL)
12825 return got_error_from_errno("strdup");
12828 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12829 free(repo_path);
12830 if (error != NULL)
12831 goto done;
12833 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12834 if (error)
12835 goto done;
12837 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12838 if (error)
12839 goto done;
12841 if (commit_id_str == NULL)
12842 commit_id_str = GOT_REF_HEAD;
12843 error = got_repo_match_object_id(&commit_id, NULL,
12844 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12845 if (error)
12846 goto done;
12848 error = got_object_open_as_commit(&commit, repo, commit_id);
12849 if (error)
12850 goto done;
12852 for (i = 0; i < argc; i++) {
12853 if (force_path) {
12854 error = got_object_id_by_path(&id, repo, commit,
12855 argv[i]);
12856 if (error)
12857 break;
12858 } else {
12859 error = got_repo_match_object_id(&id, &label, argv[i],
12860 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12861 repo);
12862 if (error) {
12863 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12864 error->code != GOT_ERR_NOT_REF)
12865 break;
12866 error = got_object_id_by_path(&id, repo,
12867 commit, argv[i]);
12868 if (error)
12869 break;
12873 error = got_object_get_type(&obj_type, repo, id);
12874 if (error)
12875 break;
12877 switch (obj_type) {
12878 case GOT_OBJ_TYPE_BLOB:
12879 error = cat_blob(id, repo, stdout);
12880 break;
12881 case GOT_OBJ_TYPE_TREE:
12882 error = cat_tree(id, repo, stdout);
12883 break;
12884 case GOT_OBJ_TYPE_COMMIT:
12885 error = cat_commit(id, repo, stdout);
12886 break;
12887 case GOT_OBJ_TYPE_TAG:
12888 error = cat_tag(id, repo, stdout);
12889 break;
12890 default:
12891 error = got_error(GOT_ERR_OBJ_TYPE);
12892 break;
12894 if (error)
12895 break;
12896 free(label);
12897 label = NULL;
12898 free(id);
12899 id = NULL;
12901 done:
12902 free(label);
12903 free(id);
12904 free(commit_id);
12905 if (commit)
12906 got_object_commit_close(commit);
12907 if (worktree)
12908 got_worktree_close(worktree);
12909 if (repo) {
12910 const struct got_error *close_err = got_repo_close(repo);
12911 if (error == NULL)
12912 error = close_err;
12914 if (pack_fds) {
12915 const struct got_error *pack_err =
12916 got_repo_pack_fds_close(pack_fds);
12917 if (error == NULL)
12918 error = pack_err;
12921 got_ref_list_free(&refs);
12922 return error;
12925 __dead static void
12926 usage_info(void)
12928 fprintf(stderr, "usage: %s info [path ...]\n",
12929 getprogname());
12930 exit(1);
12933 static const struct got_error *
12934 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12935 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12936 struct got_object_id *commit_id)
12938 const struct got_error *err = NULL;
12939 char *id_str = NULL;
12940 char datebuf[128];
12941 struct tm mytm, *tm;
12942 struct got_pathlist_head *paths = arg;
12943 struct got_pathlist_entry *pe;
12946 * Clear error indication from any of the path arguments which
12947 * would cause this file index entry to be displayed.
12949 TAILQ_FOREACH(pe, paths, entry) {
12950 if (got_path_cmp(path, pe->path, strlen(path),
12951 pe->path_len) == 0 ||
12952 got_path_is_child(path, pe->path, pe->path_len))
12953 pe->data = NULL; /* no error */
12956 printf(GOT_COMMIT_SEP_STR);
12957 if (S_ISLNK(mode))
12958 printf("symlink: %s\n", path);
12959 else if (S_ISREG(mode)) {
12960 printf("file: %s\n", path);
12961 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12962 } else if (S_ISDIR(mode))
12963 printf("directory: %s\n", path);
12964 else
12965 printf("something: %s\n", path);
12967 tm = localtime_r(&mtime, &mytm);
12968 if (tm == NULL)
12969 return NULL;
12970 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12971 return got_error(GOT_ERR_NO_SPACE);
12972 printf("timestamp: %s\n", datebuf);
12974 if (blob_id) {
12975 err = got_object_id_str(&id_str, blob_id);
12976 if (err)
12977 return err;
12978 printf("based on blob: %s\n", id_str);
12979 free(id_str);
12982 if (staged_blob_id) {
12983 err = got_object_id_str(&id_str, staged_blob_id);
12984 if (err)
12985 return err;
12986 printf("based on staged blob: %s\n", id_str);
12987 free(id_str);
12990 if (commit_id) {
12991 err = got_object_id_str(&id_str, commit_id);
12992 if (err)
12993 return err;
12994 printf("based on commit: %s\n", id_str);
12995 free(id_str);
12998 return NULL;
13001 static const struct got_error *
13002 cmd_info(int argc, char *argv[])
13004 const struct got_error *error = NULL;
13005 struct got_worktree *worktree = NULL;
13006 char *cwd = NULL, *id_str = NULL;
13007 struct got_pathlist_head paths;
13008 struct got_pathlist_entry *pe;
13009 char *uuidstr = NULL;
13010 int ch, show_files = 0;
13012 TAILQ_INIT(&paths);
13014 while ((ch = getopt(argc, argv, "")) != -1) {
13015 switch (ch) {
13016 default:
13017 usage_info();
13018 /* NOTREACHED */
13022 argc -= optind;
13023 argv += optind;
13025 #ifndef PROFILE
13026 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13027 NULL) == -1)
13028 err(1, "pledge");
13029 #endif
13030 cwd = getcwd(NULL, 0);
13031 if (cwd == NULL) {
13032 error = got_error_from_errno("getcwd");
13033 goto done;
13036 error = got_worktree_open(&worktree, cwd);
13037 if (error) {
13038 if (error->code == GOT_ERR_NOT_WORKTREE)
13039 error = wrap_not_worktree_error(error, "info", cwd);
13040 goto done;
13043 #ifndef PROFILE
13044 /* Remove "wpath cpath proc exec sendfd" promises. */
13045 if (pledge("stdio rpath flock unveil", NULL) == -1)
13046 err(1, "pledge");
13047 #endif
13048 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13049 if (error)
13050 goto done;
13052 if (argc >= 1) {
13053 error = get_worktree_paths_from_argv(&paths, argc, argv,
13054 worktree);
13055 if (error)
13056 goto done;
13057 show_files = 1;
13060 error = got_object_id_str(&id_str,
13061 got_worktree_get_base_commit_id(worktree));
13062 if (error)
13063 goto done;
13065 error = got_worktree_get_uuid(&uuidstr, worktree);
13066 if (error)
13067 goto done;
13069 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13070 printf("work tree base commit: %s\n", id_str);
13071 printf("work tree path prefix: %s\n",
13072 got_worktree_get_path_prefix(worktree));
13073 printf("work tree branch reference: %s\n",
13074 got_worktree_get_head_ref_name(worktree));
13075 printf("work tree UUID: %s\n", uuidstr);
13076 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13078 if (show_files) {
13079 struct got_pathlist_entry *pe;
13080 TAILQ_FOREACH(pe, &paths, entry) {
13081 if (pe->path_len == 0)
13082 continue;
13084 * Assume this path will fail. This will be corrected
13085 * in print_path_info() in case the path does suceeed.
13087 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13089 error = got_worktree_path_info(worktree, &paths,
13090 print_path_info, &paths, check_cancelled, NULL);
13091 if (error)
13092 goto done;
13093 TAILQ_FOREACH(pe, &paths, entry) {
13094 if (pe->data != NULL) {
13095 const struct got_error *perr;
13097 perr = pe->data;
13098 error = got_error_fmt(perr->code, "%s",
13099 pe->path);
13100 break;
13104 done:
13105 if (worktree)
13106 got_worktree_close(worktree);
13107 TAILQ_FOREACH(pe, &paths, entry)
13108 free((char *)pe->path);
13109 got_pathlist_free(&paths);
13110 free(cwd);
13111 free(id_str);
13112 free(uuidstr);
13113 return error;