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] [-m message] "
351 "[-r repository-path] [-I pattern] path\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 [-a] [-b branch] [-l] [-m] [-q] [-v] "
991 "[-R reference] 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 [-a] [-b branch] [-d] [-l] "
2039 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
2040 "[remote-repository-name]\n",
2041 getprogname());
2042 exit(1);
2045 static const struct got_error *
2046 delete_missing_ref(struct got_reference *ref,
2047 int verbosity, struct got_repository *repo)
2049 const struct got_error *err = NULL;
2050 struct got_object_id *id = NULL;
2051 char *id_str = NULL;
2053 if (got_ref_is_symbolic(ref)) {
2054 err = got_ref_delete(ref, repo);
2055 if (err)
2056 return err;
2057 if (verbosity >= 0) {
2058 printf("Deleted %s: %s\n",
2059 got_ref_get_name(ref),
2060 got_ref_get_symref_target(ref));
2062 } else {
2063 err = got_ref_resolve(&id, repo, ref);
2064 if (err)
2065 return err;
2066 err = got_object_id_str(&id_str, id);
2067 if (err)
2068 goto done;
2070 err = got_ref_delete(ref, repo);
2071 if (err)
2072 goto done;
2073 if (verbosity >= 0) {
2074 printf("Deleted %s: %s\n",
2075 got_ref_get_name(ref), id_str);
2078 done:
2079 free(id);
2080 free(id_str);
2081 return NULL;
2084 static const struct got_error *
2085 delete_missing_refs(struct got_pathlist_head *their_refs,
2086 struct got_pathlist_head *their_symrefs,
2087 const struct got_remote_repo *remote,
2088 int verbosity, struct got_repository *repo)
2090 const struct got_error *err = NULL, *unlock_err;
2091 struct got_reflist_head my_refs;
2092 struct got_reflist_entry *re;
2093 struct got_pathlist_entry *pe;
2094 char *remote_namespace = NULL;
2095 char *local_refname = NULL;
2097 TAILQ_INIT(&my_refs);
2099 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2100 == -1)
2101 return got_error_from_errno("asprintf");
2103 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2104 if (err)
2105 goto done;
2107 TAILQ_FOREACH(re, &my_refs, entry) {
2108 const char *refname = got_ref_get_name(re->ref);
2109 const char *their_refname;
2111 if (remote->mirror_references) {
2112 their_refname = refname;
2113 } else {
2114 if (strncmp(refname, remote_namespace,
2115 strlen(remote_namespace)) == 0) {
2116 if (strcmp(refname + strlen(remote_namespace),
2117 GOT_REF_HEAD) == 0)
2118 continue;
2119 if (asprintf(&local_refname, "refs/heads/%s",
2120 refname + strlen(remote_namespace)) == -1) {
2121 err = got_error_from_errno("asprintf");
2122 goto done;
2124 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2125 continue;
2127 their_refname = local_refname;
2130 TAILQ_FOREACH(pe, their_refs, entry) {
2131 if (strcmp(their_refname, pe->path) == 0)
2132 break;
2134 if (pe != NULL)
2135 continue;
2137 TAILQ_FOREACH(pe, their_symrefs, entry) {
2138 if (strcmp(their_refname, pe->path) == 0)
2139 break;
2141 if (pe != NULL)
2142 continue;
2144 err = delete_missing_ref(re->ref, verbosity, repo);
2145 if (err)
2146 break;
2148 if (local_refname) {
2149 struct got_reference *ref;
2150 err = got_ref_open(&ref, repo, local_refname, 1);
2151 if (err) {
2152 if (err->code != GOT_ERR_NOT_REF)
2153 break;
2154 free(local_refname);
2155 local_refname = NULL;
2156 continue;
2158 err = delete_missing_ref(ref, verbosity, repo);
2159 if (err)
2160 break;
2161 unlock_err = got_ref_unlock(ref);
2162 got_ref_close(ref);
2163 if (unlock_err && err == NULL) {
2164 err = unlock_err;
2165 break;
2168 free(local_refname);
2169 local_refname = NULL;
2172 done:
2173 free(remote_namespace);
2174 free(local_refname);
2175 return err;
2178 static const struct got_error *
2179 update_wanted_ref(const char *refname, struct got_object_id *id,
2180 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2182 const struct got_error *err, *unlock_err;
2183 char *remote_refname;
2184 struct got_reference *ref;
2186 if (strncmp("refs/", refname, 5) == 0)
2187 refname += 5;
2189 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2190 remote_repo_name, refname) == -1)
2191 return got_error_from_errno("asprintf");
2193 err = got_ref_open(&ref, repo, remote_refname, 1);
2194 if (err) {
2195 if (err->code != GOT_ERR_NOT_REF)
2196 goto done;
2197 err = create_ref(remote_refname, id, verbosity, repo);
2198 } else {
2199 err = update_ref(ref, id, 0, verbosity, repo);
2200 unlock_err = got_ref_unlock(ref);
2201 if (unlock_err && err == NULL)
2202 err = unlock_err;
2203 got_ref_close(ref);
2205 done:
2206 free(remote_refname);
2207 return err;
2210 static const struct got_error *
2211 delete_ref(struct got_repository *repo, struct got_reference *ref)
2213 const struct got_error *err = NULL;
2214 struct got_object_id *id = NULL;
2215 char *id_str = NULL;
2216 const char *target;
2218 if (got_ref_is_symbolic(ref)) {
2219 target = got_ref_get_symref_target(ref);
2220 } else {
2221 err = got_ref_resolve(&id, repo, ref);
2222 if (err)
2223 goto done;
2224 err = got_object_id_str(&id_str, id);
2225 if (err)
2226 goto done;
2227 target = id_str;
2230 err = got_ref_delete(ref, repo);
2231 if (err)
2232 goto done;
2234 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2235 done:
2236 free(id);
2237 free(id_str);
2238 return err;
2241 static const struct got_error *
2242 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2244 const struct got_error *err = NULL;
2245 struct got_reflist_head refs;
2246 struct got_reflist_entry *re;
2247 char *prefix;
2249 TAILQ_INIT(&refs);
2251 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2252 err = got_error_from_errno("asprintf");
2253 goto done;
2255 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2256 if (err)
2257 goto done;
2259 TAILQ_FOREACH(re, &refs, entry)
2260 delete_ref(repo, re->ref);
2261 done:
2262 got_ref_list_free(&refs);
2263 return err;
2266 static const struct got_error *
2267 cmd_fetch(int argc, char *argv[])
2269 const struct got_error *error = NULL, *unlock_err;
2270 char *cwd = NULL, *repo_path = NULL;
2271 const char *remote_name;
2272 char *proto = NULL, *host = NULL, *port = NULL;
2273 char *repo_name = NULL, *server_path = NULL;
2274 const struct got_remote_repo *remotes, *remote = NULL;
2275 int nremotes;
2276 char *id_str = NULL;
2277 struct got_repository *repo = NULL;
2278 struct got_worktree *worktree = NULL;
2279 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2280 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2281 struct got_pathlist_entry *pe;
2282 struct got_object_id *pack_hash = NULL;
2283 int i, ch, fetchfd = -1, fetchstatus;
2284 pid_t fetchpid = -1;
2285 struct got_fetch_progress_arg fpa;
2286 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2287 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2288 int *pack_fds = NULL;
2290 TAILQ_INIT(&refs);
2291 TAILQ_INIT(&symrefs);
2292 TAILQ_INIT(&wanted_branches);
2293 TAILQ_INIT(&wanted_refs);
2295 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2296 switch (ch) {
2297 case 'a':
2298 fetch_all_branches = 1;
2299 break;
2300 case 'b':
2301 error = got_pathlist_append(&wanted_branches,
2302 optarg, NULL);
2303 if (error)
2304 return error;
2305 break;
2306 case 'd':
2307 delete_refs = 1;
2308 break;
2309 case 'l':
2310 list_refs_only = 1;
2311 break;
2312 case 'r':
2313 repo_path = realpath(optarg, NULL);
2314 if (repo_path == NULL)
2315 return got_error_from_errno2("realpath",
2316 optarg);
2317 got_path_strip_trailing_slashes(repo_path);
2318 break;
2319 case 't':
2320 replace_tags = 1;
2321 break;
2322 case 'v':
2323 if (verbosity < 0)
2324 verbosity = 0;
2325 else if (verbosity < 3)
2326 verbosity++;
2327 break;
2328 case 'q':
2329 verbosity = -1;
2330 break;
2331 case 'R':
2332 error = got_pathlist_append(&wanted_refs,
2333 optarg, NULL);
2334 if (error)
2335 return error;
2336 break;
2337 case 'X':
2338 delete_remote = 1;
2339 break;
2340 default:
2341 usage_fetch();
2342 break;
2345 argc -= optind;
2346 argv += optind;
2348 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2349 option_conflict('a', 'b');
2350 if (list_refs_only) {
2351 if (!TAILQ_EMPTY(&wanted_branches))
2352 option_conflict('l', 'b');
2353 if (fetch_all_branches)
2354 option_conflict('l', 'a');
2355 if (delete_refs)
2356 option_conflict('l', 'd');
2357 if (delete_remote)
2358 option_conflict('l', 'X');
2360 if (delete_remote) {
2361 if (fetch_all_branches)
2362 option_conflict('X', 'a');
2363 if (!TAILQ_EMPTY(&wanted_branches))
2364 option_conflict('X', 'b');
2365 if (delete_refs)
2366 option_conflict('X', 'd');
2367 if (replace_tags)
2368 option_conflict('X', 't');
2369 if (!TAILQ_EMPTY(&wanted_refs))
2370 option_conflict('X', 'R');
2373 if (argc == 0) {
2374 if (delete_remote)
2375 errx(1, "-X option requires a remote name");
2376 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2377 } else if (argc == 1)
2378 remote_name = argv[0];
2379 else
2380 usage_fetch();
2382 cwd = getcwd(NULL, 0);
2383 if (cwd == NULL) {
2384 error = got_error_from_errno("getcwd");
2385 goto done;
2388 error = got_repo_pack_fds_open(&pack_fds);
2389 if (error != NULL)
2390 goto done;
2392 if (repo_path == NULL) {
2393 error = got_worktree_open(&worktree, cwd);
2394 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2395 goto done;
2396 else
2397 error = NULL;
2398 if (worktree) {
2399 repo_path =
2400 strdup(got_worktree_get_repo_path(worktree));
2401 if (repo_path == NULL)
2402 error = got_error_from_errno("strdup");
2403 if (error)
2404 goto done;
2405 } else {
2406 repo_path = strdup(cwd);
2407 if (repo_path == NULL) {
2408 error = got_error_from_errno("strdup");
2409 goto done;
2414 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2415 if (error)
2416 goto done;
2418 if (delete_remote) {
2419 error = delete_refs_for_remote(repo, remote_name);
2420 goto done; /* nothing else to do */
2423 if (worktree) {
2424 worktree_conf = got_worktree_get_gotconfig(worktree);
2425 if (worktree_conf) {
2426 got_gotconfig_get_remotes(&nremotes, &remotes,
2427 worktree_conf);
2428 for (i = 0; i < nremotes; i++) {
2429 if (strcmp(remotes[i].name, remote_name) == 0) {
2430 remote = &remotes[i];
2431 break;
2436 if (remote == NULL) {
2437 repo_conf = got_repo_get_gotconfig(repo);
2438 if (repo_conf) {
2439 got_gotconfig_get_remotes(&nremotes, &remotes,
2440 repo_conf);
2441 for (i = 0; i < nremotes; i++) {
2442 if (strcmp(remotes[i].name, remote_name) == 0) {
2443 remote = &remotes[i];
2444 break;
2449 if (remote == NULL) {
2450 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2451 for (i = 0; i < nremotes; i++) {
2452 if (strcmp(remotes[i].name, remote_name) == 0) {
2453 remote = &remotes[i];
2454 break;
2458 if (remote == NULL) {
2459 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2460 goto done;
2463 if (TAILQ_EMPTY(&wanted_branches)) {
2464 if (!fetch_all_branches)
2465 fetch_all_branches = remote->fetch_all_branches;
2466 for (i = 0; i < remote->nfetch_branches; i++) {
2467 got_pathlist_append(&wanted_branches,
2468 remote->fetch_branches[i], NULL);
2471 if (TAILQ_EMPTY(&wanted_refs)) {
2472 for (i = 0; i < remote->nfetch_refs; i++) {
2473 got_pathlist_append(&wanted_refs,
2474 remote->fetch_refs[i], NULL);
2478 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2479 &repo_name, remote->fetch_url);
2480 if (error)
2481 goto done;
2483 if (strcmp(proto, "git") == 0) {
2484 #ifndef PROFILE
2485 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2486 "sendfd dns inet unveil", NULL) == -1)
2487 err(1, "pledge");
2488 #endif
2489 } else if (strcmp(proto, "git+ssh") == 0 ||
2490 strcmp(proto, "ssh") == 0) {
2491 #ifndef PROFILE
2492 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2493 "sendfd unveil", NULL) == -1)
2494 err(1, "pledge");
2495 #endif
2496 } else if (strcmp(proto, "http") == 0 ||
2497 strcmp(proto, "git+http") == 0) {
2498 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2499 goto done;
2500 } else {
2501 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2502 goto done;
2505 error = got_dial_apply_unveil(proto);
2506 if (error)
2507 goto done;
2509 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2510 if (error)
2511 goto done;
2513 if (verbosity >= 0)
2514 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2515 port ? ":" : "", port ? port : "");
2517 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2518 server_path, verbosity);
2519 if (error)
2520 goto done;
2522 fpa.last_scaled_size[0] = '\0';
2523 fpa.last_p_indexed = -1;
2524 fpa.last_p_resolved = -1;
2525 fpa.verbosity = verbosity;
2526 fpa.repo = repo;
2527 fpa.create_configs = 0;
2528 fpa.configs_created = 0;
2529 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2530 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2531 remote->mirror_references, fetch_all_branches, &wanted_branches,
2532 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2533 fetch_progress, &fpa);
2534 if (error)
2535 goto done;
2537 if (list_refs_only) {
2538 error = list_remote_refs(&symrefs, &refs);
2539 goto done;
2542 if (pack_hash == NULL) {
2543 if (verbosity >= 0)
2544 printf("Already up-to-date\n");
2545 } else if (verbosity >= 0) {
2546 error = got_object_id_str(&id_str, pack_hash);
2547 if (error)
2548 goto done;
2549 printf("\nFetched %s.pack\n", id_str);
2550 free(id_str);
2551 id_str = NULL;
2554 /* Update references provided with the pack file. */
2555 TAILQ_FOREACH(pe, &refs, entry) {
2556 const char *refname = pe->path;
2557 struct got_object_id *id = pe->data;
2558 struct got_reference *ref;
2559 char *remote_refname;
2561 if (is_wanted_ref(&wanted_refs, refname) &&
2562 !remote->mirror_references) {
2563 error = update_wanted_ref(refname, id,
2564 remote->name, verbosity, repo);
2565 if (error)
2566 goto done;
2567 continue;
2570 if (remote->mirror_references ||
2571 strncmp("refs/tags/", refname, 10) == 0) {
2572 error = got_ref_open(&ref, repo, refname, 1);
2573 if (error) {
2574 if (error->code != GOT_ERR_NOT_REF)
2575 goto done;
2576 error = create_ref(refname, id, verbosity,
2577 repo);
2578 if (error)
2579 goto done;
2580 } else {
2581 error = update_ref(ref, id, replace_tags,
2582 verbosity, repo);
2583 unlock_err = got_ref_unlock(ref);
2584 if (unlock_err && error == NULL)
2585 error = unlock_err;
2586 got_ref_close(ref);
2587 if (error)
2588 goto done;
2590 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2591 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2592 remote_name, refname + 11) == -1) {
2593 error = got_error_from_errno("asprintf");
2594 goto done;
2597 error = got_ref_open(&ref, repo, remote_refname, 1);
2598 if (error) {
2599 if (error->code != GOT_ERR_NOT_REF)
2600 goto done;
2601 error = create_ref(remote_refname, id,
2602 verbosity, repo);
2603 if (error)
2604 goto done;
2605 } else {
2606 error = update_ref(ref, id, replace_tags,
2607 verbosity, repo);
2608 unlock_err = got_ref_unlock(ref);
2609 if (unlock_err && error == NULL)
2610 error = unlock_err;
2611 got_ref_close(ref);
2612 if (error)
2613 goto done;
2616 /* Also create a local branch if none exists yet. */
2617 error = got_ref_open(&ref, repo, refname, 1);
2618 if (error) {
2619 if (error->code != GOT_ERR_NOT_REF)
2620 goto done;
2621 error = create_ref(refname, id, verbosity,
2622 repo);
2623 if (error)
2624 goto done;
2625 } else {
2626 unlock_err = got_ref_unlock(ref);
2627 if (unlock_err && error == NULL)
2628 error = unlock_err;
2629 got_ref_close(ref);
2633 if (delete_refs) {
2634 error = delete_missing_refs(&refs, &symrefs, remote,
2635 verbosity, repo);
2636 if (error)
2637 goto done;
2640 if (!remote->mirror_references) {
2641 /* Update remote HEAD reference if the server provided one. */
2642 TAILQ_FOREACH(pe, &symrefs, entry) {
2643 struct got_reference *target_ref;
2644 const char *refname = pe->path;
2645 const char *target = pe->data;
2646 char *remote_refname = NULL, *remote_target = NULL;
2648 if (strcmp(refname, GOT_REF_HEAD) != 0)
2649 continue;
2651 if (strncmp("refs/heads/", target, 11) != 0)
2652 continue;
2654 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2655 remote->name, refname) == -1) {
2656 error = got_error_from_errno("asprintf");
2657 goto done;
2659 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2660 remote->name, target + 11) == -1) {
2661 error = got_error_from_errno("asprintf");
2662 free(remote_refname);
2663 goto done;
2666 error = got_ref_open(&target_ref, repo, remote_target,
2667 0);
2668 if (error) {
2669 free(remote_refname);
2670 free(remote_target);
2671 if (error->code == GOT_ERR_NOT_REF) {
2672 error = NULL;
2673 continue;
2675 goto done;
2677 error = update_symref(remote_refname, target_ref,
2678 verbosity, repo);
2679 free(remote_refname);
2680 free(remote_target);
2681 got_ref_close(target_ref);
2682 if (error)
2683 goto done;
2686 done:
2687 if (fetchpid > 0) {
2688 if (kill(fetchpid, SIGTERM) == -1)
2689 error = got_error_from_errno("kill");
2690 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2691 error = got_error_from_errno("waitpid");
2693 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2694 error = got_error_from_errno("close");
2695 if (repo) {
2696 const struct got_error *close_err = got_repo_close(repo);
2697 if (error == NULL)
2698 error = close_err;
2700 if (worktree)
2701 got_worktree_close(worktree);
2702 if (pack_fds) {
2703 const struct got_error *pack_err =
2704 got_repo_pack_fds_close(pack_fds);
2705 if (error == NULL)
2706 error = pack_err;
2708 TAILQ_FOREACH(pe, &refs, entry) {
2709 free((void *)pe->path);
2710 free(pe->data);
2712 got_pathlist_free(&refs);
2713 TAILQ_FOREACH(pe, &symrefs, entry) {
2714 free((void *)pe->path);
2715 free(pe->data);
2717 got_pathlist_free(&symrefs);
2718 got_pathlist_free(&wanted_branches);
2719 got_pathlist_free(&wanted_refs);
2720 free(id_str);
2721 free(cwd);
2722 free(repo_path);
2723 free(pack_hash);
2724 free(proto);
2725 free(host);
2726 free(port);
2727 free(server_path);
2728 free(repo_name);
2729 return error;
2733 __dead static void
2734 usage_checkout(void)
2736 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2737 "[-p prefix] [-q] repository-path [worktree-path]\n",
2738 getprogname());
2739 exit(1);
2742 static void
2743 show_worktree_base_ref_warning(void)
2745 fprintf(stderr, "%s: warning: could not create a reference "
2746 "to the work tree's base commit; the commit could be "
2747 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2748 "repository writable and running 'got update' will prevent this\n",
2749 getprogname());
2752 struct got_checkout_progress_arg {
2753 const char *worktree_path;
2754 int had_base_commit_ref_error;
2755 int verbosity;
2758 static const struct got_error *
2759 checkout_progress(void *arg, unsigned char status, const char *path)
2761 struct got_checkout_progress_arg *a = arg;
2763 /* Base commit bump happens silently. */
2764 if (status == GOT_STATUS_BUMP_BASE)
2765 return NULL;
2767 if (status == GOT_STATUS_BASE_REF_ERR) {
2768 a->had_base_commit_ref_error = 1;
2769 return NULL;
2772 while (path[0] == '/')
2773 path++;
2775 if (a->verbosity >= 0)
2776 printf("%c %s/%s\n", status, a->worktree_path, path);
2778 return NULL;
2781 static const struct got_error *
2782 check_cancelled(void *arg)
2784 if (sigint_received || sigpipe_received)
2785 return got_error(GOT_ERR_CANCELLED);
2786 return NULL;
2789 static const struct got_error *
2790 check_linear_ancestry(struct got_object_id *commit_id,
2791 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2792 struct got_repository *repo)
2794 const struct got_error *err = NULL;
2795 struct got_object_id *yca_id;
2797 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2798 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2799 if (err)
2800 return err;
2802 if (yca_id == NULL)
2803 return got_error(GOT_ERR_ANCESTRY);
2806 * Require a straight line of history between the target commit
2807 * and the work tree's base commit.
2809 * Non-linear situations such as this require a rebase:
2811 * (commit) D F (base_commit)
2812 * \ /
2813 * C E
2814 * \ /
2815 * B (yca)
2816 * |
2817 * A
2819 * 'got update' only handles linear cases:
2820 * Update forwards in time: A (base/yca) - B - C - D (commit)
2821 * Update backwards in time: D (base) - C - B - A (commit/yca)
2823 if (allow_forwards_in_time_only) {
2824 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2825 return got_error(GOT_ERR_ANCESTRY);
2826 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2827 got_object_id_cmp(base_commit_id, yca_id) != 0)
2828 return got_error(GOT_ERR_ANCESTRY);
2830 free(yca_id);
2831 return NULL;
2834 static const struct got_error *
2835 check_same_branch(struct got_object_id *commit_id,
2836 struct got_reference *head_ref, struct got_object_id *yca_id,
2837 struct got_repository *repo)
2839 const struct got_error *err = NULL;
2840 struct got_commit_graph *graph = NULL;
2841 struct got_object_id *head_commit_id = NULL;
2842 int is_same_branch = 0;
2844 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2845 if (err)
2846 goto done;
2848 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2849 is_same_branch = 1;
2850 goto done;
2852 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2853 is_same_branch = 1;
2854 goto done;
2857 err = got_commit_graph_open(&graph, "/", 1);
2858 if (err)
2859 goto done;
2861 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2862 check_cancelled, NULL);
2863 if (err)
2864 goto done;
2866 for (;;) {
2867 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 (id) {
2877 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2878 break;
2879 if (got_object_id_cmp(id, commit_id) == 0) {
2880 is_same_branch = 1;
2881 break;
2885 done:
2886 if (graph)
2887 got_commit_graph_close(graph);
2888 free(head_commit_id);
2889 if (!err && !is_same_branch)
2890 err = got_error(GOT_ERR_ANCESTRY);
2891 return err;
2894 static const struct got_error *
2895 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2897 static char msg[512];
2898 const char *branch_name;
2900 if (got_ref_is_symbolic(ref))
2901 branch_name = got_ref_get_symref_target(ref);
2902 else
2903 branch_name = got_ref_get_name(ref);
2905 if (strncmp("refs/heads/", branch_name, 11) == 0)
2906 branch_name += 11;
2908 snprintf(msg, sizeof(msg),
2909 "target commit is not contained in branch '%s'; "
2910 "the branch to use must be specified with -b; "
2911 "if necessary a new branch can be created for "
2912 "this commit with 'got branch -c %s BRANCH_NAME'",
2913 branch_name, commit_id_str);
2915 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2918 static const struct got_error *
2919 cmd_checkout(int argc, char *argv[])
2921 const struct got_error *error = NULL;
2922 struct got_repository *repo = NULL;
2923 struct got_reference *head_ref = NULL, *ref = NULL;
2924 struct got_worktree *worktree = NULL;
2925 char *repo_path = NULL;
2926 char *worktree_path = NULL;
2927 const char *path_prefix = "";
2928 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2929 char *commit_id_str = NULL;
2930 struct got_object_id *commit_id = NULL;
2931 char *cwd = NULL;
2932 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2933 struct got_pathlist_head paths;
2934 struct got_checkout_progress_arg cpa;
2935 int *pack_fds = NULL;
2937 TAILQ_INIT(&paths);
2939 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2940 switch (ch) {
2941 case 'b':
2942 branch_name = optarg;
2943 break;
2944 case 'c':
2945 commit_id_str = strdup(optarg);
2946 if (commit_id_str == NULL)
2947 return got_error_from_errno("strdup");
2948 break;
2949 case 'E':
2950 allow_nonempty = 1;
2951 break;
2952 case 'p':
2953 path_prefix = optarg;
2954 break;
2955 case 'q':
2956 verbosity = -1;
2957 break;
2958 default:
2959 usage_checkout();
2960 /* NOTREACHED */
2964 argc -= optind;
2965 argv += optind;
2967 #ifndef PROFILE
2968 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2969 "unveil", NULL) == -1)
2970 err(1, "pledge");
2971 #endif
2972 if (argc == 1) {
2973 char *base, *dotgit;
2974 const char *path;
2975 repo_path = realpath(argv[0], NULL);
2976 if (repo_path == NULL)
2977 return got_error_from_errno2("realpath", argv[0]);
2978 cwd = getcwd(NULL, 0);
2979 if (cwd == NULL) {
2980 error = got_error_from_errno("getcwd");
2981 goto done;
2983 if (path_prefix[0])
2984 path = path_prefix;
2985 else
2986 path = repo_path;
2987 error = got_path_basename(&base, path);
2988 if (error)
2989 goto done;
2990 dotgit = strstr(base, ".git");
2991 if (dotgit)
2992 *dotgit = '\0';
2993 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2994 error = got_error_from_errno("asprintf");
2995 free(base);
2996 goto done;
2998 free(base);
2999 } else if (argc == 2) {
3000 repo_path = realpath(argv[0], NULL);
3001 if (repo_path == NULL) {
3002 error = got_error_from_errno2("realpath", argv[0]);
3003 goto done;
3005 worktree_path = realpath(argv[1], NULL);
3006 if (worktree_path == NULL) {
3007 if (errno != ENOENT) {
3008 error = got_error_from_errno2("realpath",
3009 argv[1]);
3010 goto done;
3012 worktree_path = strdup(argv[1]);
3013 if (worktree_path == NULL) {
3014 error = got_error_from_errno("strdup");
3015 goto done;
3018 } else
3019 usage_checkout();
3021 got_path_strip_trailing_slashes(repo_path);
3022 got_path_strip_trailing_slashes(worktree_path);
3024 error = got_repo_pack_fds_open(&pack_fds);
3025 if (error != NULL)
3026 goto done;
3028 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3029 if (error != NULL)
3030 goto done;
3032 /* Pre-create work tree path for unveil(2) */
3033 error = got_path_mkdir(worktree_path);
3034 if (error) {
3035 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3036 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3037 goto done;
3038 if (!allow_nonempty &&
3039 !got_path_dir_is_empty(worktree_path)) {
3040 error = got_error_path(worktree_path,
3041 GOT_ERR_DIR_NOT_EMPTY);
3042 goto done;
3046 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3047 if (error)
3048 goto done;
3050 error = got_ref_open(&head_ref, repo, branch_name, 0);
3051 if (error != NULL)
3052 goto done;
3054 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3055 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3056 goto done;
3058 error = got_worktree_open(&worktree, worktree_path);
3059 if (error != NULL)
3060 goto done;
3062 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3063 path_prefix);
3064 if (error != NULL)
3065 goto done;
3066 if (!same_path_prefix) {
3067 error = got_error(GOT_ERR_PATH_PREFIX);
3068 goto done;
3071 if (commit_id_str) {
3072 struct got_reflist_head refs;
3073 TAILQ_INIT(&refs);
3074 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3075 NULL);
3076 if (error)
3077 goto done;
3078 error = got_repo_match_object_id(&commit_id, NULL,
3079 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3080 got_ref_list_free(&refs);
3081 if (error)
3082 goto done;
3083 error = check_linear_ancestry(commit_id,
3084 got_worktree_get_base_commit_id(worktree), 0, repo);
3085 if (error != NULL) {
3086 if (error->code == GOT_ERR_ANCESTRY) {
3087 error = checkout_ancestry_error(
3088 head_ref, commit_id_str);
3090 goto done;
3092 error = check_same_branch(commit_id, head_ref, NULL, repo);
3093 if (error) {
3094 if (error->code == GOT_ERR_ANCESTRY) {
3095 error = checkout_ancestry_error(
3096 head_ref, commit_id_str);
3098 goto done;
3100 error = got_worktree_set_base_commit_id(worktree, repo,
3101 commit_id);
3102 if (error)
3103 goto done;
3104 /* Expand potentially abbreviated commit ID string. */
3105 free(commit_id_str);
3106 error = got_object_id_str(&commit_id_str, commit_id);
3107 if (error)
3108 goto done;
3109 } else {
3110 commit_id = got_object_id_dup(
3111 got_worktree_get_base_commit_id(worktree));
3112 if (commit_id == NULL) {
3113 error = got_error_from_errno("got_object_id_dup");
3114 goto done;
3116 error = got_object_id_str(&commit_id_str, commit_id);
3117 if (error)
3118 goto done;
3121 error = got_pathlist_append(&paths, "", NULL);
3122 if (error)
3123 goto done;
3124 cpa.worktree_path = worktree_path;
3125 cpa.had_base_commit_ref_error = 0;
3126 cpa.verbosity = verbosity;
3127 error = got_worktree_checkout_files(worktree, &paths, repo,
3128 checkout_progress, &cpa, check_cancelled, NULL);
3129 if (error != NULL)
3130 goto done;
3132 if (got_ref_is_symbolic(head_ref)) {
3133 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3134 if (error)
3135 goto done;
3136 refname = got_ref_get_name(ref);
3137 } else
3138 refname = got_ref_get_name(head_ref);
3139 printf("Checked out %s: %s\n", refname, commit_id_str);
3140 printf("Now shut up and hack\n");
3141 if (cpa.had_base_commit_ref_error)
3142 show_worktree_base_ref_warning();
3143 done:
3144 if (pack_fds) {
3145 const struct got_error *pack_err =
3146 got_repo_pack_fds_close(pack_fds);
3147 if (error == NULL)
3148 error = pack_err;
3150 if (head_ref)
3151 got_ref_close(head_ref);
3152 if (ref)
3153 got_ref_close(ref);
3154 got_pathlist_free(&paths);
3155 free(commit_id_str);
3156 free(commit_id);
3157 free(repo_path);
3158 free(worktree_path);
3159 free(cwd);
3160 return error;
3163 struct got_update_progress_arg {
3164 int did_something;
3165 int conflicts;
3166 int obstructed;
3167 int not_updated;
3168 int missing;
3169 int not_deleted;
3170 int unversioned;
3171 int verbosity;
3174 static void
3175 print_update_progress_stats(struct got_update_progress_arg *upa)
3177 if (!upa->did_something)
3178 return;
3180 if (upa->conflicts > 0)
3181 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3182 if (upa->obstructed > 0)
3183 printf("File paths obstructed by a non-regular file: %d\n",
3184 upa->obstructed);
3185 if (upa->not_updated > 0)
3186 printf("Files not updated because of existing merge "
3187 "conflicts: %d\n", upa->not_updated);
3191 * The meaning of some status codes differs between merge-style operations and
3192 * update operations. For example, the ! status code means "file was missing"
3193 * if changes were merged into the work tree, and "missing file was restored"
3194 * if the work tree was updated. This function should be used by any operation
3195 * which merges changes into the work tree without updating the work tree.
3197 static void
3198 print_merge_progress_stats(struct got_update_progress_arg *upa)
3200 if (!upa->did_something)
3201 return;
3203 if (upa->conflicts > 0)
3204 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3205 if (upa->obstructed > 0)
3206 printf("File paths obstructed by a non-regular file: %d\n",
3207 upa->obstructed);
3208 if (upa->missing > 0)
3209 printf("Files which had incoming changes but could not be "
3210 "found in the work tree: %d\n", upa->missing);
3211 if (upa->not_deleted > 0)
3212 printf("Files not deleted due to differences in deleted "
3213 "content: %d\n", upa->not_deleted);
3214 if (upa->unversioned > 0)
3215 printf("Files not merged because an unversioned file was "
3216 "found in the work tree: %d\n", upa->unversioned);
3219 __dead static void
3220 usage_update(void)
3222 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3223 "[path ...]\n",
3224 getprogname());
3225 exit(1);
3228 static const struct got_error *
3229 update_progress(void *arg, unsigned char status, const char *path)
3231 struct got_update_progress_arg *upa = arg;
3233 if (status == GOT_STATUS_EXISTS ||
3234 status == GOT_STATUS_BASE_REF_ERR)
3235 return NULL;
3237 upa->did_something = 1;
3239 /* Base commit bump happens silently. */
3240 if (status == GOT_STATUS_BUMP_BASE)
3241 return NULL;
3243 if (status == GOT_STATUS_CONFLICT)
3244 upa->conflicts++;
3245 if (status == GOT_STATUS_OBSTRUCTED)
3246 upa->obstructed++;
3247 if (status == GOT_STATUS_CANNOT_UPDATE)
3248 upa->not_updated++;
3249 if (status == GOT_STATUS_MISSING)
3250 upa->missing++;
3251 if (status == GOT_STATUS_CANNOT_DELETE)
3252 upa->not_deleted++;
3253 if (status == GOT_STATUS_UNVERSIONED)
3254 upa->unversioned++;
3256 while (path[0] == '/')
3257 path++;
3258 if (upa->verbosity >= 0)
3259 printf("%c %s\n", status, path);
3261 return NULL;
3264 static const struct got_error *
3265 switch_head_ref(struct got_reference *head_ref,
3266 struct got_object_id *commit_id, struct got_worktree *worktree,
3267 struct got_repository *repo)
3269 const struct got_error *err = NULL;
3270 char *base_id_str;
3271 int ref_has_moved = 0;
3273 /* Trivial case: switching between two different references. */
3274 if (strcmp(got_ref_get_name(head_ref),
3275 got_worktree_get_head_ref_name(worktree)) != 0) {
3276 printf("Switching work tree from %s to %s\n",
3277 got_worktree_get_head_ref_name(worktree),
3278 got_ref_get_name(head_ref));
3279 return got_worktree_set_head_ref(worktree, head_ref);
3282 err = check_linear_ancestry(commit_id,
3283 got_worktree_get_base_commit_id(worktree), 0, repo);
3284 if (err) {
3285 if (err->code != GOT_ERR_ANCESTRY)
3286 return err;
3287 ref_has_moved = 1;
3289 if (!ref_has_moved)
3290 return NULL;
3292 /* Switching to a rebased branch with the same reference name. */
3293 err = got_object_id_str(&base_id_str,
3294 got_worktree_get_base_commit_id(worktree));
3295 if (err)
3296 return err;
3297 printf("Reference %s now points at a different branch\n",
3298 got_worktree_get_head_ref_name(worktree));
3299 printf("Switching work tree from %s to %s\n", base_id_str,
3300 got_worktree_get_head_ref_name(worktree));
3301 return NULL;
3304 static const struct got_error *
3305 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3307 const struct got_error *err;
3308 int in_progress;
3310 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3311 if (err)
3312 return err;
3313 if (in_progress)
3314 return got_error(GOT_ERR_REBASING);
3316 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3317 if (err)
3318 return err;
3319 if (in_progress)
3320 return got_error(GOT_ERR_HISTEDIT_BUSY);
3322 return NULL;
3325 static const struct got_error *
3326 check_merge_in_progress(struct got_worktree *worktree,
3327 struct got_repository *repo)
3329 const struct got_error *err;
3330 int in_progress;
3332 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3333 if (err)
3334 return err;
3335 if (in_progress)
3336 return got_error(GOT_ERR_MERGE_BUSY);
3338 return NULL;
3341 static const struct got_error *
3342 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3343 char *argv[], struct got_worktree *worktree)
3345 const struct got_error *err = NULL;
3346 char *path;
3347 struct got_pathlist_entry *new;
3348 int i;
3350 if (argc == 0) {
3351 path = strdup("");
3352 if (path == NULL)
3353 return got_error_from_errno("strdup");
3354 return got_pathlist_append(paths, path, NULL);
3357 for (i = 0; i < argc; i++) {
3358 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3359 if (err)
3360 break;
3361 err = got_pathlist_insert(&new, paths, path, NULL);
3362 if (err || new == NULL /* duplicate */) {
3363 free(path);
3364 if (err)
3365 break;
3369 return err;
3372 static const struct got_error *
3373 wrap_not_worktree_error(const struct got_error *orig_err,
3374 const char *cmdname, const char *path)
3376 const struct got_error *err;
3377 struct got_repository *repo;
3378 static char msg[512];
3379 int *pack_fds = NULL;
3381 err = got_repo_pack_fds_open(&pack_fds);
3382 if (err)
3383 return err;
3385 err = got_repo_open(&repo, path, NULL, pack_fds);
3386 if (err)
3387 return orig_err;
3389 snprintf(msg, sizeof(msg),
3390 "'got %s' needs a work tree in addition to a git repository\n"
3391 "Work trees can be checked out from this Git repository with "
3392 "'got checkout'.\n"
3393 "The got(1) manual page contains more information.", cmdname);
3394 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3395 got_repo_close(repo);
3396 if (pack_fds) {
3397 const struct got_error *pack_err =
3398 got_repo_pack_fds_close(pack_fds);
3399 if (err == NULL)
3400 err = pack_err;
3402 return err;
3405 static const struct got_error *
3406 cmd_update(int argc, char *argv[])
3408 const struct got_error *error = NULL;
3409 struct got_repository *repo = NULL;
3410 struct got_worktree *worktree = NULL;
3411 char *worktree_path = NULL;
3412 struct got_object_id *commit_id = NULL;
3413 char *commit_id_str = NULL;
3414 const char *branch_name = NULL;
3415 struct got_reference *head_ref = NULL;
3416 struct got_pathlist_head paths;
3417 struct got_pathlist_entry *pe;
3418 int ch, verbosity = 0;
3419 struct got_update_progress_arg upa;
3420 int *pack_fds = NULL;
3422 TAILQ_INIT(&paths);
3424 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3425 switch (ch) {
3426 case 'b':
3427 branch_name = optarg;
3428 break;
3429 case 'c':
3430 commit_id_str = strdup(optarg);
3431 if (commit_id_str == NULL)
3432 return got_error_from_errno("strdup");
3433 break;
3434 case 'q':
3435 verbosity = -1;
3436 break;
3437 default:
3438 usage_update();
3439 /* NOTREACHED */
3443 argc -= optind;
3444 argv += optind;
3446 #ifndef PROFILE
3447 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3448 "unveil", NULL) == -1)
3449 err(1, "pledge");
3450 #endif
3451 worktree_path = getcwd(NULL, 0);
3452 if (worktree_path == NULL) {
3453 error = got_error_from_errno("getcwd");
3454 goto done;
3457 error = got_repo_pack_fds_open(&pack_fds);
3458 if (error != NULL)
3459 goto done;
3461 error = got_worktree_open(&worktree, worktree_path);
3462 if (error) {
3463 if (error->code == GOT_ERR_NOT_WORKTREE)
3464 error = wrap_not_worktree_error(error, "update",
3465 worktree_path);
3466 goto done;
3469 error = check_rebase_or_histedit_in_progress(worktree);
3470 if (error)
3471 goto done;
3473 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3474 NULL, pack_fds);
3475 if (error != NULL)
3476 goto done;
3478 error = apply_unveil(got_repo_get_path(repo), 0,
3479 got_worktree_get_root_path(worktree));
3480 if (error)
3481 goto done;
3483 error = check_merge_in_progress(worktree, repo);
3484 if (error)
3485 goto done;
3487 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3488 if (error)
3489 goto done;
3491 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3492 got_worktree_get_head_ref_name(worktree), 0);
3493 if (error != NULL)
3494 goto done;
3495 if (commit_id_str == NULL) {
3496 error = got_ref_resolve(&commit_id, repo, head_ref);
3497 if (error != NULL)
3498 goto done;
3499 error = got_object_id_str(&commit_id_str, commit_id);
3500 if (error != NULL)
3501 goto done;
3502 } else {
3503 struct got_reflist_head refs;
3504 TAILQ_INIT(&refs);
3505 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3506 NULL);
3507 if (error)
3508 goto done;
3509 error = got_repo_match_object_id(&commit_id, NULL,
3510 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3511 got_ref_list_free(&refs);
3512 free(commit_id_str);
3513 commit_id_str = NULL;
3514 if (error)
3515 goto done;
3516 error = got_object_id_str(&commit_id_str, commit_id);
3517 if (error)
3518 goto done;
3521 if (branch_name) {
3522 struct got_object_id *head_commit_id;
3523 TAILQ_FOREACH(pe, &paths, entry) {
3524 if (pe->path_len == 0)
3525 continue;
3526 error = got_error_msg(GOT_ERR_BAD_PATH,
3527 "switching between branches requires that "
3528 "the entire work tree gets updated");
3529 goto done;
3531 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3532 if (error)
3533 goto done;
3534 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3535 repo);
3536 free(head_commit_id);
3537 if (error != NULL)
3538 goto done;
3539 error = check_same_branch(commit_id, head_ref, NULL, repo);
3540 if (error)
3541 goto done;
3542 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3543 if (error)
3544 goto done;
3545 } else {
3546 error = check_linear_ancestry(commit_id,
3547 got_worktree_get_base_commit_id(worktree), 0, repo);
3548 if (error != NULL) {
3549 if (error->code == GOT_ERR_ANCESTRY)
3550 error = got_error(GOT_ERR_BRANCH_MOVED);
3551 goto done;
3553 error = check_same_branch(commit_id, head_ref, NULL, repo);
3554 if (error)
3555 goto done;
3558 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3559 commit_id) != 0) {
3560 error = got_worktree_set_base_commit_id(worktree, repo,
3561 commit_id);
3562 if (error)
3563 goto done;
3566 memset(&upa, 0, sizeof(upa));
3567 upa.verbosity = verbosity;
3568 error = got_worktree_checkout_files(worktree, &paths, repo,
3569 update_progress, &upa, check_cancelled, NULL);
3570 if (error != NULL)
3571 goto done;
3573 if (upa.did_something) {
3574 printf("Updated to %s: %s\n",
3575 got_worktree_get_head_ref_name(worktree), commit_id_str);
3576 } else
3577 printf("Already up-to-date\n");
3579 print_update_progress_stats(&upa);
3580 done:
3581 if (pack_fds) {
3582 const struct got_error *pack_err =
3583 got_repo_pack_fds_close(pack_fds);
3584 if (error == NULL)
3585 error = pack_err;
3587 free(worktree_path);
3588 TAILQ_FOREACH(pe, &paths, entry)
3589 free((char *)pe->path);
3590 got_pathlist_free(&paths);
3591 free(commit_id);
3592 free(commit_id_str);
3593 return error;
3596 static const struct got_error *
3597 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3598 const char *path, int diff_context, int ignore_whitespace,
3599 int force_text_diff, struct got_repository *repo, FILE *outfile)
3601 const struct got_error *err = NULL;
3602 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3603 FILE *f1 = NULL, *f2 = NULL;
3604 int fd1 = -1, fd2 = -1;
3606 fd1 = got_opentempfd();
3607 if (fd1 == -1)
3608 return got_error_from_errno("got_opentempfd");
3609 fd2 = got_opentempfd();
3610 if (fd2 == -1) {
3611 err = got_error_from_errno("got_opentempfd");
3612 goto done;
3615 if (blob_id1) {
3616 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3617 fd1);
3618 if (err)
3619 goto done;
3622 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3623 if (err)
3624 goto done;
3626 f1 = got_opentemp();
3627 if (f1 == NULL) {
3628 err = got_error_from_errno("got_opentemp");
3629 goto done;
3631 f2 = got_opentemp();
3632 if (f2 == NULL) {
3633 err = got_error_from_errno("got_opentemp");
3634 goto done;
3637 while (path[0] == '/')
3638 path++;
3639 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3640 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3641 force_text_diff, outfile);
3642 done:
3643 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3644 err = got_error_from_errno("close");
3645 if (blob1)
3646 got_object_blob_close(blob1);
3647 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3648 err = got_error_from_errno("close");
3649 got_object_blob_close(blob2);
3650 if (f1 && fclose(f1) == EOF && err == NULL)
3651 err = got_error_from_errno("fclose");
3652 if (f2 && fclose(f2) == EOF && err == NULL)
3653 err = got_error_from_errno("fclose");
3654 return err;
3657 static const struct got_error *
3658 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3659 const char *path, int diff_context, int ignore_whitespace,
3660 int force_text_diff, struct got_repository *repo, FILE *outfile)
3662 const struct got_error *err = NULL;
3663 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3664 struct got_diff_blob_output_unidiff_arg arg;
3665 FILE *f1 = NULL, *f2 = NULL;
3666 int fd1 = -1, fd2 = -1;
3668 if (tree_id1) {
3669 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3670 if (err)
3671 goto done;
3672 fd1 = got_opentempfd();
3673 if (fd1 == -1) {
3674 err = got_error_from_errno("got_opentempfd");
3675 goto done;
3679 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3680 if (err)
3681 goto done;
3683 f1 = got_opentemp();
3684 if (f1 == NULL) {
3685 err = got_error_from_errno("got_opentemp");
3686 goto done;
3689 f2 = got_opentemp();
3690 if (f2 == NULL) {
3691 err = got_error_from_errno("got_opentemp");
3692 goto done;
3694 fd2 = got_opentempfd();
3695 if (fd2 == -1) {
3696 err = got_error_from_errno("got_opentempfd");
3697 goto done;
3699 arg.diff_context = diff_context;
3700 arg.ignore_whitespace = ignore_whitespace;
3701 arg.force_text_diff = force_text_diff;
3702 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3703 arg.outfile = outfile;
3704 arg.lines = NULL;
3705 arg.nlines = 0;
3706 while (path[0] == '/')
3707 path++;
3708 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3709 got_diff_blob_output_unidiff, &arg, 1);
3710 done:
3711 if (tree1)
3712 got_object_tree_close(tree1);
3713 if (tree2)
3714 got_object_tree_close(tree2);
3715 if (f1 && fclose(f1) == EOF && err == NULL)
3716 err = got_error_from_errno("fclose");
3717 if (f2 && fclose(f2) == EOF && err == NULL)
3718 err = got_error_from_errno("fclose");
3719 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3720 err = got_error_from_errno("close");
3721 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3722 err = got_error_from_errno("close");
3723 return err;
3726 static const struct got_error *
3727 get_changed_paths(struct got_pathlist_head *paths,
3728 struct got_commit_object *commit, struct got_repository *repo)
3730 const struct got_error *err = NULL;
3731 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3732 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3733 struct got_object_qid *qid;
3735 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3736 if (qid != NULL) {
3737 struct got_commit_object *pcommit;
3738 err = got_object_open_as_commit(&pcommit, repo,
3739 &qid->id);
3740 if (err)
3741 return err;
3743 tree_id1 = got_object_id_dup(
3744 got_object_commit_get_tree_id(pcommit));
3745 if (tree_id1 == NULL) {
3746 got_object_commit_close(pcommit);
3747 return got_error_from_errno("got_object_id_dup");
3749 got_object_commit_close(pcommit);
3753 if (tree_id1) {
3754 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3755 if (err)
3756 goto done;
3759 tree_id2 = got_object_commit_get_tree_id(commit);
3760 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3761 if (err)
3762 goto done;
3764 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3765 got_diff_tree_collect_changed_paths, paths, 0);
3766 done:
3767 if (tree1)
3768 got_object_tree_close(tree1);
3769 if (tree2)
3770 got_object_tree_close(tree2);
3771 free(tree_id1);
3772 return err;
3775 static const struct got_error *
3776 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3777 const char *path, int diff_context, struct got_repository *repo,
3778 FILE *outfile)
3780 const struct got_error *err = NULL;
3781 struct got_commit_object *pcommit = NULL;
3782 char *id_str1 = NULL, *id_str2 = NULL;
3783 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3784 struct got_object_qid *qid;
3786 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3787 if (qid != NULL) {
3788 err = got_object_open_as_commit(&pcommit, repo,
3789 &qid->id);
3790 if (err)
3791 return err;
3792 err = got_object_id_str(&id_str1, &qid->id);
3793 if (err)
3794 goto done;
3797 err = got_object_id_str(&id_str2, id);
3798 if (err)
3799 goto done;
3801 if (path && path[0] != '\0') {
3802 int obj_type;
3803 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3804 if (err)
3805 goto done;
3806 if (pcommit) {
3807 err = got_object_id_by_path(&obj_id1, repo,
3808 pcommit, path);
3809 if (err) {
3810 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3811 free(obj_id2);
3812 goto done;
3816 err = got_object_get_type(&obj_type, repo, obj_id2);
3817 if (err) {
3818 free(obj_id2);
3819 goto done;
3821 fprintf(outfile,
3822 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3823 fprintf(outfile, "commit - %s\n",
3824 id_str1 ? id_str1 : "/dev/null");
3825 fprintf(outfile, "commit + %s\n", id_str2);
3826 switch (obj_type) {
3827 case GOT_OBJ_TYPE_BLOB:
3828 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3829 0, 0, repo, outfile);
3830 break;
3831 case GOT_OBJ_TYPE_TREE:
3832 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3833 0, 0, repo, outfile);
3834 break;
3835 default:
3836 err = got_error(GOT_ERR_OBJ_TYPE);
3837 break;
3839 free(obj_id1);
3840 free(obj_id2);
3841 } else {
3842 obj_id2 = got_object_commit_get_tree_id(commit);
3843 if (pcommit)
3844 obj_id1 = got_object_commit_get_tree_id(pcommit);
3845 fprintf(outfile,
3846 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3847 fprintf(outfile, "commit - %s\n",
3848 id_str1 ? id_str1 : "/dev/null");
3849 fprintf(outfile, "commit + %s\n", id_str2);
3850 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3851 repo, outfile);
3853 done:
3854 free(id_str1);
3855 free(id_str2);
3856 if (pcommit)
3857 got_object_commit_close(pcommit);
3858 return err;
3861 static char *
3862 get_datestr(time_t *time, char *datebuf)
3864 struct tm mytm, *tm;
3865 char *p, *s;
3867 tm = gmtime_r(time, &mytm);
3868 if (tm == NULL)
3869 return NULL;
3870 s = asctime_r(tm, datebuf);
3871 if (s == NULL)
3872 return NULL;
3873 p = strchr(s, '\n');
3874 if (p)
3875 *p = '\0';
3876 return s;
3879 static const struct got_error *
3880 match_commit(int *have_match, struct got_object_id *id,
3881 struct got_commit_object *commit, regex_t *regex)
3883 const struct got_error *err = NULL;
3884 regmatch_t regmatch;
3885 char *id_str = NULL, *logmsg = NULL;
3887 *have_match = 0;
3889 err = got_object_id_str(&id_str, id);
3890 if (err)
3891 return err;
3893 err = got_object_commit_get_logmsg(&logmsg, commit);
3894 if (err)
3895 goto done;
3897 if (regexec(regex, got_object_commit_get_author(commit), 1,
3898 &regmatch, 0) == 0 ||
3899 regexec(regex, got_object_commit_get_committer(commit), 1,
3900 &regmatch, 0) == 0 ||
3901 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3902 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3903 *have_match = 1;
3904 done:
3905 free(id_str);
3906 free(logmsg);
3907 return err;
3910 static void
3911 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3912 regex_t *regex)
3914 regmatch_t regmatch;
3915 struct got_pathlist_entry *pe;
3917 *have_match = 0;
3919 TAILQ_FOREACH(pe, changed_paths, entry) {
3920 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3921 *have_match = 1;
3922 break;
3927 static const struct got_error *
3928 match_patch(int *have_match, struct got_commit_object *commit,
3929 struct got_object_id *id, const char *path, int diff_context,
3930 struct got_repository *repo, regex_t *regex, FILE *f)
3932 const struct got_error *err = NULL;
3933 char *line = NULL;
3934 size_t linesize = 0;
3935 regmatch_t regmatch;
3937 *have_match = 0;
3939 err = got_opentemp_truncate(f);
3940 if (err)
3941 return err;
3943 err = print_patch(commit, id, path, diff_context, repo, f);
3944 if (err)
3945 goto done;
3947 if (fseeko(f, 0L, SEEK_SET) == -1) {
3948 err = got_error_from_errno("fseeko");
3949 goto done;
3952 while (getline(&line, &linesize, f) != -1) {
3953 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3954 *have_match = 1;
3955 break;
3958 done:
3959 free(line);
3960 return err;
3963 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3965 static const struct got_error*
3966 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3967 struct got_object_id *id, struct got_repository *repo,
3968 int local_only)
3970 static const struct got_error *err = NULL;
3971 struct got_reflist_entry *re;
3972 char *s;
3973 const char *name;
3975 *refs_str = NULL;
3977 TAILQ_FOREACH(re, refs, entry) {
3978 struct got_tag_object *tag = NULL;
3979 struct got_object_id *ref_id;
3980 int cmp;
3982 name = got_ref_get_name(re->ref);
3983 if (strcmp(name, GOT_REF_HEAD) == 0)
3984 continue;
3985 if (strncmp(name, "refs/", 5) == 0)
3986 name += 5;
3987 if (strncmp(name, "got/", 4) == 0)
3988 continue;
3989 if (strncmp(name, "heads/", 6) == 0)
3990 name += 6;
3991 if (strncmp(name, "remotes/", 8) == 0) {
3992 if (local_only)
3993 continue;
3994 name += 8;
3995 s = strstr(name, "/" GOT_REF_HEAD);
3996 if (s != NULL && s[strlen(s)] == '\0')
3997 continue;
3999 err = got_ref_resolve(&ref_id, repo, re->ref);
4000 if (err)
4001 break;
4002 if (strncmp(name, "tags/", 5) == 0) {
4003 err = got_object_open_as_tag(&tag, repo, ref_id);
4004 if (err) {
4005 if (err->code != GOT_ERR_OBJ_TYPE) {
4006 free(ref_id);
4007 break;
4009 /* Ref points at something other than a tag. */
4010 err = NULL;
4011 tag = NULL;
4014 cmp = got_object_id_cmp(tag ?
4015 got_object_tag_get_object_id(tag) : ref_id, id);
4016 free(ref_id);
4017 if (tag)
4018 got_object_tag_close(tag);
4019 if (cmp != 0)
4020 continue;
4021 s = *refs_str;
4022 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4023 s ? ", " : "", name) == -1) {
4024 err = got_error_from_errno("asprintf");
4025 free(s);
4026 *refs_str = NULL;
4027 break;
4029 free(s);
4032 return err;
4035 static const struct got_error *
4036 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4037 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4039 const struct got_error *err = NULL;
4040 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4041 char *comma, *s, *nl;
4042 struct got_reflist_head *refs;
4043 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4044 struct tm tm;
4045 time_t committer_time;
4047 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4048 if (refs) {
4049 err = build_refs_str(&ref_str, refs, id, repo, 1);
4050 if (err)
4051 return err;
4053 /* Display the first matching ref only. */
4054 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4055 *comma = '\0';
4058 if (ref_str == NULL) {
4059 err = got_object_id_str(&id_str, id);
4060 if (err)
4061 return err;
4064 committer_time = got_object_commit_get_committer_time(commit);
4065 if (gmtime_r(&committer_time, &tm) == NULL) {
4066 err = got_error_from_errno("gmtime_r");
4067 goto done;
4069 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4070 err = got_error(GOT_ERR_NO_SPACE);
4071 goto done;
4074 err = got_object_commit_get_logmsg(&logmsg0, commit);
4075 if (err)
4076 goto done;
4078 s = logmsg0;
4079 while (isspace((unsigned char)s[0]))
4080 s++;
4082 nl = strchr(s, '\n');
4083 if (nl) {
4084 *nl = '\0';
4087 if (ref_str)
4088 printf("%s%-7s %s\n", datebuf, ref_str, s);
4089 else
4090 printf("%s%.7s %s\n", datebuf, id_str, s);
4092 if (fflush(stdout) != 0 && err == NULL)
4093 err = got_error_from_errno("fflush");
4094 done:
4095 free(id_str);
4096 free(ref_str);
4097 free(logmsg0);
4098 return err;
4101 static const struct got_error *
4102 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4103 struct got_repository *repo, const char *path,
4104 struct got_pathlist_head *changed_paths, int show_patch,
4105 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4106 const char *custom_refs_str)
4108 const struct got_error *err = NULL;
4109 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4110 char datebuf[26];
4111 time_t committer_time;
4112 const char *author, *committer;
4113 char *refs_str = NULL;
4115 err = got_object_id_str(&id_str, id);
4116 if (err)
4117 return err;
4119 if (custom_refs_str == NULL) {
4120 struct got_reflist_head *refs;
4121 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4122 if (refs) {
4123 err = build_refs_str(&refs_str, refs, id, repo, 0);
4124 if (err)
4125 goto done;
4129 printf(GOT_COMMIT_SEP_STR);
4130 if (custom_refs_str)
4131 printf("commit %s (%s)\n", id_str, custom_refs_str);
4132 else
4133 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4134 refs_str ? refs_str : "", refs_str ? ")" : "");
4135 free(id_str);
4136 id_str = NULL;
4137 free(refs_str);
4138 refs_str = NULL;
4139 printf("from: %s\n", got_object_commit_get_author(commit));
4140 committer_time = got_object_commit_get_committer_time(commit);
4141 datestr = get_datestr(&committer_time, datebuf);
4142 if (datestr)
4143 printf("date: %s UTC\n", datestr);
4144 author = got_object_commit_get_author(commit);
4145 committer = got_object_commit_get_committer(commit);
4146 if (strcmp(author, committer) != 0)
4147 printf("via: %s\n", committer);
4148 if (got_object_commit_get_nparents(commit) > 1) {
4149 const struct got_object_id_queue *parent_ids;
4150 struct got_object_qid *qid;
4151 int n = 1;
4152 parent_ids = got_object_commit_get_parent_ids(commit);
4153 STAILQ_FOREACH(qid, parent_ids, entry) {
4154 err = got_object_id_str(&id_str, &qid->id);
4155 if (err)
4156 goto done;
4157 printf("parent %d: %s\n", n++, id_str);
4158 free(id_str);
4159 id_str = NULL;
4163 err = got_object_commit_get_logmsg(&logmsg0, commit);
4164 if (err)
4165 goto done;
4167 logmsg = logmsg0;
4168 do {
4169 line = strsep(&logmsg, "\n");
4170 if (line)
4171 printf(" %s\n", line);
4172 } while (line);
4173 free(logmsg0);
4175 if (changed_paths) {
4176 struct got_pathlist_entry *pe;
4177 TAILQ_FOREACH(pe, changed_paths, entry) {
4178 struct got_diff_changed_path *cp = pe->data;
4179 printf(" %c %s\n", cp->status, pe->path);
4181 printf("\n");
4183 if (show_patch) {
4184 err = print_patch(commit, id, path, diff_context, repo, stdout);
4185 if (err == 0)
4186 printf("\n");
4189 if (fflush(stdout) != 0 && err == NULL)
4190 err = got_error_from_errno("fflush");
4191 done:
4192 free(id_str);
4193 free(refs_str);
4194 return err;
4197 static const struct got_error *
4198 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4199 struct got_repository *repo, const char *path, int show_changed_paths,
4200 int show_patch, const char *search_pattern, int diff_context, int limit,
4201 int log_branches, int reverse_display_order,
4202 struct got_reflist_object_id_map *refs_idmap, int one_line,
4203 FILE *tmpfile)
4205 const struct got_error *err;
4206 struct got_commit_graph *graph;
4207 regex_t regex;
4208 int have_match;
4209 struct got_object_id_queue reversed_commits;
4210 struct got_object_qid *qid;
4211 struct got_commit_object *commit;
4212 struct got_pathlist_head changed_paths;
4213 struct got_pathlist_entry *pe;
4215 STAILQ_INIT(&reversed_commits);
4216 TAILQ_INIT(&changed_paths);
4218 if (search_pattern && regcomp(&regex, search_pattern,
4219 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4220 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4222 err = got_commit_graph_open(&graph, path, !log_branches);
4223 if (err)
4224 return err;
4225 err = got_commit_graph_iter_start(graph, root_id, repo,
4226 check_cancelled, NULL);
4227 if (err)
4228 goto done;
4229 for (;;) {
4230 struct got_object_id *id;
4232 if (sigint_received || sigpipe_received)
4233 break;
4235 err = got_commit_graph_iter_next(&id, graph, repo,
4236 check_cancelled, NULL);
4237 if (err) {
4238 if (err->code == GOT_ERR_ITER_COMPLETED)
4239 err = NULL;
4240 break;
4242 if (id == NULL)
4243 break;
4245 err = got_object_open_as_commit(&commit, repo, id);
4246 if (err)
4247 break;
4249 if (show_changed_paths && !reverse_display_order) {
4250 err = get_changed_paths(&changed_paths, commit, repo);
4251 if (err)
4252 break;
4255 if (search_pattern) {
4256 err = match_commit(&have_match, id, commit, &regex);
4257 if (err) {
4258 got_object_commit_close(commit);
4259 break;
4261 if (have_match == 0 && show_changed_paths)
4262 match_changed_paths(&have_match,
4263 &changed_paths, &regex);
4264 if (have_match == 0 && show_patch) {
4265 err = match_patch(&have_match, commit, id,
4266 path, diff_context, repo, &regex,
4267 tmpfile);
4268 if (err)
4269 break;
4271 if (have_match == 0) {
4272 got_object_commit_close(commit);
4273 TAILQ_FOREACH(pe, &changed_paths, entry) {
4274 free((char *)pe->path);
4275 free(pe->data);
4277 got_pathlist_free(&changed_paths);
4278 continue;
4282 if (reverse_display_order) {
4283 err = got_object_qid_alloc(&qid, id);
4284 if (err)
4285 break;
4286 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4287 got_object_commit_close(commit);
4288 } else {
4289 if (one_line)
4290 err = print_commit_oneline(commit, id,
4291 repo, refs_idmap);
4292 else
4293 err = print_commit(commit, id, repo, path,
4294 show_changed_paths ? &changed_paths : NULL,
4295 show_patch, diff_context, refs_idmap, NULL);
4296 got_object_commit_close(commit);
4297 if (err)
4298 break;
4300 if ((limit && --limit == 0) ||
4301 (end_id && got_object_id_cmp(id, end_id) == 0))
4302 break;
4304 TAILQ_FOREACH(pe, &changed_paths, entry) {
4305 free((char *)pe->path);
4306 free(pe->data);
4308 got_pathlist_free(&changed_paths);
4310 if (reverse_display_order) {
4311 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4312 err = got_object_open_as_commit(&commit, repo,
4313 &qid->id);
4314 if (err)
4315 break;
4316 if (show_changed_paths) {
4317 err = get_changed_paths(&changed_paths,
4318 commit, repo);
4319 if (err)
4320 break;
4322 if (one_line)
4323 err = print_commit_oneline(commit, &qid->id,
4324 repo, refs_idmap);
4325 else
4326 err = print_commit(commit, &qid->id, repo, path,
4327 show_changed_paths ? &changed_paths : NULL,
4328 show_patch, diff_context, refs_idmap, NULL);
4329 got_object_commit_close(commit);
4330 if (err)
4331 break;
4332 TAILQ_FOREACH(pe, &changed_paths, entry) {
4333 free((char *)pe->path);
4334 free(pe->data);
4336 got_pathlist_free(&changed_paths);
4339 done:
4340 while (!STAILQ_EMPTY(&reversed_commits)) {
4341 qid = STAILQ_FIRST(&reversed_commits);
4342 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4343 got_object_qid_free(qid);
4345 TAILQ_FOREACH(pe, &changed_paths, entry) {
4346 free((char *)pe->path);
4347 free(pe->data);
4349 got_pathlist_free(&changed_paths);
4350 if (search_pattern)
4351 regfree(&regex);
4352 got_commit_graph_close(graph);
4353 return err;
4356 __dead static void
4357 usage_log(void)
4359 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4360 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4361 "[-r repository-path] [-R] [path]\n", getprogname());
4362 exit(1);
4365 static int
4366 get_default_log_limit(void)
4368 const char *got_default_log_limit;
4369 long long n;
4370 const char *errstr;
4372 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4373 if (got_default_log_limit == NULL)
4374 return 0;
4375 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4376 if (errstr != NULL)
4377 return 0;
4378 return n;
4381 static const struct got_error *
4382 cmd_log(int argc, char *argv[])
4384 const struct got_error *error;
4385 struct got_repository *repo = NULL;
4386 struct got_worktree *worktree = NULL;
4387 struct got_object_id *start_id = NULL, *end_id = NULL;
4388 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4389 const char *start_commit = NULL, *end_commit = NULL;
4390 const char *search_pattern = NULL;
4391 int diff_context = -1, ch;
4392 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4393 int reverse_display_order = 0, one_line = 0;
4394 const char *errstr;
4395 struct got_reflist_head refs;
4396 struct got_reflist_object_id_map *refs_idmap = NULL;
4397 FILE *tmpfile = NULL;
4398 int *pack_fds = NULL;
4400 TAILQ_INIT(&refs);
4402 #ifndef PROFILE
4403 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4404 NULL)
4405 == -1)
4406 err(1, "pledge");
4407 #endif
4409 limit = get_default_log_limit();
4411 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4412 switch (ch) {
4413 case 'p':
4414 show_patch = 1;
4415 break;
4416 case 'P':
4417 show_changed_paths = 1;
4418 break;
4419 case 'c':
4420 start_commit = optarg;
4421 break;
4422 case 'C':
4423 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4424 &errstr);
4425 if (errstr != NULL)
4426 errx(1, "number of context lines is %s: %s",
4427 errstr, optarg);
4428 break;
4429 case 'l':
4430 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4431 if (errstr != NULL)
4432 errx(1, "number of commits is %s: %s",
4433 errstr, optarg);
4434 break;
4435 case 'b':
4436 log_branches = 1;
4437 break;
4438 case 'r':
4439 repo_path = realpath(optarg, NULL);
4440 if (repo_path == NULL)
4441 return got_error_from_errno2("realpath",
4442 optarg);
4443 got_path_strip_trailing_slashes(repo_path);
4444 break;
4445 case 'R':
4446 reverse_display_order = 1;
4447 break;
4448 case 's':
4449 one_line = 1;
4450 break;
4451 case 'S':
4452 search_pattern = optarg;
4453 break;
4454 case 'x':
4455 end_commit = optarg;
4456 break;
4457 default:
4458 usage_log();
4459 /* NOTREACHED */
4463 argc -= optind;
4464 argv += optind;
4466 if (diff_context == -1)
4467 diff_context = 3;
4468 else if (!show_patch)
4469 errx(1, "-C requires -p");
4471 if (one_line && (show_patch || show_changed_paths))
4472 errx(1, "cannot use -s with -p or -P");
4474 cwd = getcwd(NULL, 0);
4475 if (cwd == NULL) {
4476 error = got_error_from_errno("getcwd");
4477 goto done;
4480 error = got_repo_pack_fds_open(&pack_fds);
4481 if (error != NULL)
4482 goto done;
4484 if (repo_path == NULL) {
4485 error = got_worktree_open(&worktree, cwd);
4486 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4487 goto done;
4488 error = NULL;
4491 if (argc == 1) {
4492 if (worktree) {
4493 error = got_worktree_resolve_path(&path, worktree,
4494 argv[0]);
4495 if (error)
4496 goto done;
4497 } else {
4498 path = strdup(argv[0]);
4499 if (path == NULL) {
4500 error = got_error_from_errno("strdup");
4501 goto done;
4504 } else if (argc != 0)
4505 usage_log();
4507 if (repo_path == NULL) {
4508 repo_path = worktree ?
4509 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4511 if (repo_path == NULL) {
4512 error = got_error_from_errno("strdup");
4513 goto done;
4516 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4517 if (error != NULL)
4518 goto done;
4520 error = apply_unveil(got_repo_get_path(repo), 1,
4521 worktree ? got_worktree_get_root_path(worktree) : NULL);
4522 if (error)
4523 goto done;
4525 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4526 if (error)
4527 goto done;
4529 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4530 if (error)
4531 goto done;
4533 if (start_commit == NULL) {
4534 struct got_reference *head_ref;
4535 struct got_commit_object *commit = NULL;
4536 error = got_ref_open(&head_ref, repo,
4537 worktree ? got_worktree_get_head_ref_name(worktree)
4538 : GOT_REF_HEAD, 0);
4539 if (error != NULL)
4540 goto done;
4541 error = got_ref_resolve(&start_id, repo, head_ref);
4542 got_ref_close(head_ref);
4543 if (error != NULL)
4544 goto done;
4545 error = got_object_open_as_commit(&commit, repo,
4546 start_id);
4547 if (error != NULL)
4548 goto done;
4549 got_object_commit_close(commit);
4550 } else {
4551 error = got_repo_match_object_id(&start_id, NULL,
4552 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4553 if (error != NULL)
4554 goto done;
4556 if (end_commit != NULL) {
4557 error = got_repo_match_object_id(&end_id, NULL,
4558 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4559 if (error != NULL)
4560 goto done;
4563 if (worktree) {
4565 * If a path was specified on the command line it was resolved
4566 * to a path in the work tree above. Prepend the work tree's
4567 * path prefix to obtain the corresponding in-repository path.
4569 if (path) {
4570 const char *prefix;
4571 prefix = got_worktree_get_path_prefix(worktree);
4572 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4573 (path[0] != '\0') ? "/" : "", path) == -1) {
4574 error = got_error_from_errno("asprintf");
4575 goto done;
4578 } else
4579 error = got_repo_map_path(&in_repo_path, repo,
4580 path ? path : "");
4581 if (error != NULL)
4582 goto done;
4583 if (in_repo_path) {
4584 free(path);
4585 path = in_repo_path;
4588 if (worktree) {
4589 /* Release work tree lock. */
4590 got_worktree_close(worktree);
4591 worktree = NULL;
4594 if (search_pattern && show_patch) {
4595 tmpfile = got_opentemp();
4596 if (tmpfile == NULL) {
4597 error = got_error_from_errno("got_opentemp");
4598 goto done;
4602 error = print_commits(start_id, end_id, repo, path ? path : "",
4603 show_changed_paths, show_patch, search_pattern, diff_context,
4604 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4605 tmpfile);
4606 done:
4607 free(path);
4608 free(repo_path);
4609 free(cwd);
4610 if (worktree)
4611 got_worktree_close(worktree);
4612 if (repo) {
4613 const struct got_error *close_err = got_repo_close(repo);
4614 if (error == NULL)
4615 error = close_err;
4617 if (pack_fds) {
4618 const struct got_error *pack_err =
4619 got_repo_pack_fds_close(pack_fds);
4620 if (error == NULL)
4621 error = pack_err;
4623 if (refs_idmap)
4624 got_reflist_object_id_map_free(refs_idmap);
4625 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4626 error = got_error_from_errno("fclose");
4627 got_ref_list_free(&refs);
4628 return error;
4631 __dead static void
4632 usage_diff(void)
4634 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4635 "[-r repository-path] [-s] [-w] [-P] "
4636 "[object1 object2 | path ...]\n", getprogname());
4637 exit(1);
4640 struct print_diff_arg {
4641 struct got_repository *repo;
4642 struct got_worktree *worktree;
4643 int diff_context;
4644 const char *id_str;
4645 int header_shown;
4646 int diff_staged;
4647 enum got_diff_algorithm diff_algo;
4648 int ignore_whitespace;
4649 int force_text_diff;
4650 FILE *f1;
4651 FILE *f2;
4655 * Create a file which contains the target path of a symlink so we can feed
4656 * it as content to the diff engine.
4658 static const struct got_error *
4659 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4660 const char *abspath)
4662 const struct got_error *err = NULL;
4663 char target_path[PATH_MAX];
4664 ssize_t target_len, outlen;
4666 *fd = -1;
4668 if (dirfd != -1) {
4669 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4670 if (target_len == -1)
4671 return got_error_from_errno2("readlinkat", abspath);
4672 } else {
4673 target_len = readlink(abspath, target_path, PATH_MAX);
4674 if (target_len == -1)
4675 return got_error_from_errno2("readlink", abspath);
4678 *fd = got_opentempfd();
4679 if (*fd == -1)
4680 return got_error_from_errno("got_opentempfd");
4682 outlen = write(*fd, target_path, target_len);
4683 if (outlen == -1) {
4684 err = got_error_from_errno("got_opentempfd");
4685 goto done;
4688 if (lseek(*fd, 0, SEEK_SET) == -1) {
4689 err = got_error_from_errno2("lseek", abspath);
4690 goto done;
4692 done:
4693 if (err) {
4694 close(*fd);
4695 *fd = -1;
4697 return err;
4700 static const struct got_error *
4701 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4702 const char *path, struct got_object_id *blob_id,
4703 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4704 int dirfd, const char *de_name)
4706 struct print_diff_arg *a = arg;
4707 const struct got_error *err = NULL;
4708 struct got_blob_object *blob1 = NULL;
4709 int fd = -1, fd1 = -1, fd2 = -1;
4710 FILE *f2 = NULL;
4711 char *abspath = NULL, *label1 = NULL;
4712 struct stat sb;
4713 off_t size1 = 0;
4714 int f2_exists = 1;
4716 if (a->diff_staged) {
4717 if (staged_status != GOT_STATUS_MODIFY &&
4718 staged_status != GOT_STATUS_ADD &&
4719 staged_status != GOT_STATUS_DELETE)
4720 return NULL;
4721 } else {
4722 if (staged_status == GOT_STATUS_DELETE)
4723 return NULL;
4724 if (status == GOT_STATUS_NONEXISTENT)
4725 return got_error_set_errno(ENOENT, path);
4726 if (status != GOT_STATUS_MODIFY &&
4727 status != GOT_STATUS_ADD &&
4728 status != GOT_STATUS_DELETE &&
4729 status != GOT_STATUS_CONFLICT)
4730 return NULL;
4733 err = got_opentemp_truncate(a->f1);
4734 if (err)
4735 return got_error_from_errno("got_opentemp_truncate");
4736 err = got_opentemp_truncate(a->f2);
4737 if (err)
4738 return got_error_from_errno("got_opentemp_truncate");
4740 if (!a->header_shown) {
4741 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4742 got_worktree_get_root_path(a->worktree));
4743 printf("commit - %s\n", a->id_str);
4744 printf("path + %s%s\n",
4745 got_worktree_get_root_path(a->worktree),
4746 a->diff_staged ? " (staged changes)" : "");
4747 a->header_shown = 1;
4750 if (a->diff_staged) {
4751 const char *label1 = NULL, *label2 = NULL;
4752 switch (staged_status) {
4753 case GOT_STATUS_MODIFY:
4754 label1 = path;
4755 label2 = path;
4756 break;
4757 case GOT_STATUS_ADD:
4758 label2 = path;
4759 break;
4760 case GOT_STATUS_DELETE:
4761 label1 = path;
4762 break;
4763 default:
4764 return got_error(GOT_ERR_FILE_STATUS);
4766 fd1 = got_opentempfd();
4767 if (fd1 == -1) {
4768 err = got_error_from_errno("got_opentempfd");
4769 goto done;
4771 fd2 = got_opentempfd();
4772 if (fd2 == -1) {
4773 err = got_error_from_errno("got_opentempfd");
4774 goto done;
4776 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4777 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4778 a->diff_algo, a->diff_context, a->ignore_whitespace,
4779 a->force_text_diff, a->repo, stdout);
4780 goto done;
4783 fd1 = got_opentempfd();
4784 if (fd1 == -1) {
4785 err = got_error_from_errno("got_opentempfd");
4786 goto done;
4789 if (staged_status == GOT_STATUS_ADD ||
4790 staged_status == GOT_STATUS_MODIFY) {
4791 char *id_str;
4792 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4793 8192, fd1);
4794 if (err)
4795 goto done;
4796 err = got_object_id_str(&id_str, staged_blob_id);
4797 if (err)
4798 goto done;
4799 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4800 err = got_error_from_errno("asprintf");
4801 free(id_str);
4802 goto done;
4804 free(id_str);
4805 } else if (status != GOT_STATUS_ADD) {
4806 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4807 fd1);
4808 if (err)
4809 goto done;
4812 if (status != GOT_STATUS_DELETE) {
4813 if (asprintf(&abspath, "%s/%s",
4814 got_worktree_get_root_path(a->worktree), path) == -1) {
4815 err = got_error_from_errno("asprintf");
4816 goto done;
4819 if (dirfd != -1) {
4820 fd = openat(dirfd, de_name,
4821 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4822 if (fd == -1) {
4823 if (!got_err_open_nofollow_on_symlink()) {
4824 err = got_error_from_errno2("openat",
4825 abspath);
4826 goto done;
4828 err = get_symlink_target_file(&fd, dirfd,
4829 de_name, abspath);
4830 if (err)
4831 goto done;
4833 } else {
4834 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4835 if (fd == -1) {
4836 if (!got_err_open_nofollow_on_symlink()) {
4837 err = got_error_from_errno2("open",
4838 abspath);
4839 goto done;
4841 err = get_symlink_target_file(&fd, dirfd,
4842 de_name, abspath);
4843 if (err)
4844 goto done;
4847 if (fstat(fd, &sb) == -1) {
4848 err = got_error_from_errno2("fstat", abspath);
4849 goto done;
4851 f2 = fdopen(fd, "r");
4852 if (f2 == NULL) {
4853 err = got_error_from_errno2("fdopen", abspath);
4854 goto done;
4856 fd = -1;
4857 } else {
4858 sb.st_size = 0;
4859 f2_exists = 0;
4862 if (blob1) {
4863 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4864 a->f1, blob1);
4865 if (err)
4866 goto done;
4869 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4870 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4871 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4872 done:
4873 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4874 err = got_error_from_errno("close");
4875 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4876 err = got_error_from_errno("close");
4877 if (blob1)
4878 got_object_blob_close(blob1);
4879 if (fd != -1 && close(fd) == -1 && err == NULL)
4880 err = got_error_from_errno("close");
4881 if (f2 && fclose(f2) == EOF && err == NULL)
4882 err = got_error_from_errno("fclose");
4883 free(abspath);
4884 return err;
4887 static const struct got_error *
4888 cmd_diff(int argc, char *argv[])
4890 const struct got_error *error;
4891 struct got_repository *repo = NULL;
4892 struct got_worktree *worktree = NULL;
4893 char *cwd = NULL, *repo_path = NULL;
4894 const char *commit_args[2] = { NULL, NULL };
4895 int ncommit_args = 0;
4896 struct got_object_id *ids[2] = { NULL, NULL };
4897 char *labels[2] = { NULL, NULL };
4898 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4899 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4900 int force_text_diff = 0, force_path = 0, rflag = 0;
4901 const char *errstr;
4902 struct got_reflist_head refs;
4903 struct got_pathlist_head paths;
4904 struct got_pathlist_entry *pe;
4905 FILE *f1 = NULL, *f2 = NULL;
4906 int fd1 = -1, fd2 = -1;
4907 int *pack_fds = NULL;
4909 TAILQ_INIT(&refs);
4910 TAILQ_INIT(&paths);
4912 #ifndef PROFILE
4913 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4914 NULL) == -1)
4915 err(1, "pledge");
4916 #endif
4918 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4919 switch (ch) {
4920 case 'a':
4921 force_text_diff = 1;
4922 break;
4923 case 'c':
4924 if (ncommit_args >= 2)
4925 errx(1, "too many -c options used");
4926 commit_args[ncommit_args++] = optarg;
4927 break;
4928 case 'C':
4929 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4930 &errstr);
4931 if (errstr != NULL)
4932 errx(1, "number of context lines is %s: %s",
4933 errstr, optarg);
4934 break;
4935 case 'r':
4936 repo_path = realpath(optarg, NULL);
4937 if (repo_path == NULL)
4938 return got_error_from_errno2("realpath",
4939 optarg);
4940 got_path_strip_trailing_slashes(repo_path);
4941 rflag = 1;
4942 break;
4943 case 's':
4944 diff_staged = 1;
4945 break;
4946 case 'w':
4947 ignore_whitespace = 1;
4948 break;
4949 case 'P':
4950 force_path = 1;
4951 break;
4952 default:
4953 usage_diff();
4954 /* NOTREACHED */
4958 argc -= optind;
4959 argv += optind;
4961 cwd = getcwd(NULL, 0);
4962 if (cwd == NULL) {
4963 error = got_error_from_errno("getcwd");
4964 goto done;
4967 error = got_repo_pack_fds_open(&pack_fds);
4968 if (error != NULL)
4969 goto done;
4971 if (repo_path == NULL) {
4972 error = got_worktree_open(&worktree, cwd);
4973 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4974 goto done;
4975 else
4976 error = NULL;
4977 if (worktree) {
4978 repo_path =
4979 strdup(got_worktree_get_repo_path(worktree));
4980 if (repo_path == NULL) {
4981 error = got_error_from_errno("strdup");
4982 goto done;
4984 } else {
4985 repo_path = strdup(cwd);
4986 if (repo_path == NULL) {
4987 error = got_error_from_errno("strdup");
4988 goto done;
4993 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4994 free(repo_path);
4995 if (error != NULL)
4996 goto done;
4998 if (rflag || worktree == NULL || ncommit_args > 0) {
4999 if (force_path) {
5000 error = got_error_msg(GOT_ERR_NOT_IMPL,
5001 "-P option can only be used when diffing "
5002 "a work tree");
5003 goto done;
5005 if (diff_staged) {
5006 error = got_error_msg(GOT_ERR_NOT_IMPL,
5007 "-s option can only be used when diffing "
5008 "a work tree");
5009 goto done;
5013 error = apply_unveil(got_repo_get_path(repo), 1,
5014 worktree ? got_worktree_get_root_path(worktree) : NULL);
5015 if (error)
5016 goto done;
5018 if ((!force_path && argc == 2) || ncommit_args > 0) {
5019 int obj_type = (ncommit_args > 0 ?
5020 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5021 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5022 NULL);
5023 if (error)
5024 goto done;
5025 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5026 const char *arg;
5027 if (ncommit_args > 0)
5028 arg = commit_args[i];
5029 else
5030 arg = argv[i];
5031 error = got_repo_match_object_id(&ids[i], &labels[i],
5032 arg, obj_type, &refs, repo);
5033 if (error) {
5034 if (error->code != GOT_ERR_NOT_REF &&
5035 error->code != GOT_ERR_NO_OBJ)
5036 goto done;
5037 if (ncommit_args > 0)
5038 goto done;
5039 error = NULL;
5040 break;
5045 f1 = got_opentemp();
5046 if (f1 == NULL) {
5047 error = got_error_from_errno("got_opentemp");
5048 goto done;
5051 f2 = got_opentemp();
5052 if (f2 == NULL) {
5053 error = got_error_from_errno("got_opentemp");
5054 goto done;
5057 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5058 struct print_diff_arg arg;
5059 char *id_str;
5061 if (worktree == NULL) {
5062 if (argc == 2 && ids[0] == NULL) {
5063 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5064 goto done;
5065 } else if (argc == 2 && ids[1] == NULL) {
5066 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5067 goto done;
5068 } else if (argc > 0) {
5069 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5070 "%s", "specified paths cannot be resolved");
5071 goto done;
5072 } else {
5073 error = got_error(GOT_ERR_NOT_WORKTREE);
5074 goto done;
5078 error = get_worktree_paths_from_argv(&paths, argc, argv,
5079 worktree);
5080 if (error)
5081 goto done;
5083 error = got_object_id_str(&id_str,
5084 got_worktree_get_base_commit_id(worktree));
5085 if (error)
5086 goto done;
5087 arg.repo = repo;
5088 arg.worktree = worktree;
5089 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5090 arg.diff_context = diff_context;
5091 arg.id_str = id_str;
5092 arg.header_shown = 0;
5093 arg.diff_staged = diff_staged;
5094 arg.ignore_whitespace = ignore_whitespace;
5095 arg.force_text_diff = force_text_diff;
5096 arg.f1 = f1;
5097 arg.f2 = f2;
5099 error = got_worktree_status(worktree, &paths, repo, 0,
5100 print_diff, &arg, check_cancelled, NULL);
5101 free(id_str);
5102 goto done;
5105 if (ncommit_args == 1) {
5106 struct got_commit_object *commit;
5107 error = got_object_open_as_commit(&commit, repo, ids[0]);
5108 if (error)
5109 goto done;
5111 labels[1] = labels[0];
5112 ids[1] = ids[0];
5113 if (got_object_commit_get_nparents(commit) > 0) {
5114 const struct got_object_id_queue *pids;
5115 struct got_object_qid *pid;
5116 pids = got_object_commit_get_parent_ids(commit);
5117 pid = STAILQ_FIRST(pids);
5118 ids[0] = got_object_id_dup(&pid->id);
5119 if (ids[0] == NULL) {
5120 error = got_error_from_errno(
5121 "got_object_id_dup");
5122 got_object_commit_close(commit);
5123 goto done;
5125 error = got_object_id_str(&labels[0], ids[0]);
5126 if (error) {
5127 got_object_commit_close(commit);
5128 goto done;
5130 } else {
5131 ids[0] = NULL;
5132 labels[0] = strdup("/dev/null");
5133 if (labels[0] == NULL) {
5134 error = got_error_from_errno("strdup");
5135 got_object_commit_close(commit);
5136 goto done;
5140 got_object_commit_close(commit);
5143 if (ncommit_args == 0 && argc > 2) {
5144 error = got_error_msg(GOT_ERR_BAD_PATH,
5145 "path arguments cannot be used when diffing two objects");
5146 goto done;
5149 if (ids[0]) {
5150 error = got_object_get_type(&type1, repo, ids[0]);
5151 if (error)
5152 goto done;
5155 error = got_object_get_type(&type2, repo, ids[1]);
5156 if (error)
5157 goto done;
5158 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5159 error = got_error(GOT_ERR_OBJ_TYPE);
5160 goto done;
5162 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5163 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5164 "path arguments cannot be used when diffing blobs");
5165 goto done;
5168 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5169 char *in_repo_path;
5170 struct got_pathlist_entry *new;
5171 if (worktree) {
5172 const char *prefix;
5173 char *p;
5174 error = got_worktree_resolve_path(&p, worktree,
5175 argv[i]);
5176 if (error)
5177 goto done;
5178 prefix = got_worktree_get_path_prefix(worktree);
5179 while (prefix[0] == '/')
5180 prefix++;
5181 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5182 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5183 p) == -1) {
5184 error = got_error_from_errno("asprintf");
5185 free(p);
5186 goto done;
5188 free(p);
5189 } else {
5190 char *mapped_path, *s;
5191 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5192 if (error)
5193 goto done;
5194 s = mapped_path;
5195 while (s[0] == '/')
5196 s++;
5197 in_repo_path = strdup(s);
5198 if (in_repo_path == NULL) {
5199 error = got_error_from_errno("asprintf");
5200 free(mapped_path);
5201 goto done;
5203 free(mapped_path);
5206 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5207 if (error || new == NULL /* duplicate */)
5208 free(in_repo_path);
5209 if (error)
5210 goto done;
5213 if (worktree) {
5214 /* Release work tree lock. */
5215 got_worktree_close(worktree);
5216 worktree = NULL;
5219 fd1 = got_opentempfd();
5220 if (fd1 == -1) {
5221 error = got_error_from_errno("got_opentempfd");
5222 goto done;
5225 fd2 = got_opentempfd();
5226 if (fd2 == -1) {
5227 error = got_error_from_errno("got_opentempfd");
5228 goto done;
5231 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5232 case GOT_OBJ_TYPE_BLOB:
5233 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5234 fd1, fd2, ids[0], ids[1], NULL, NULL,
5235 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5236 ignore_whitespace, force_text_diff, repo, stdout);
5237 break;
5238 case GOT_OBJ_TYPE_TREE:
5239 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5240 ids[0], ids[1], &paths, "", "",
5241 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5242 ignore_whitespace, force_text_diff, repo, stdout);
5243 break;
5244 case GOT_OBJ_TYPE_COMMIT:
5245 printf("diff %s %s\n", labels[0], labels[1]);
5246 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5247 fd1, fd2, ids[0], ids[1], &paths,
5248 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5249 ignore_whitespace, force_text_diff, repo, stdout);
5250 break;
5251 default:
5252 error = got_error(GOT_ERR_OBJ_TYPE);
5254 done:
5255 free(labels[0]);
5256 free(labels[1]);
5257 free(ids[0]);
5258 free(ids[1]);
5259 if (worktree)
5260 got_worktree_close(worktree);
5261 if (repo) {
5262 const struct got_error *close_err = got_repo_close(repo);
5263 if (error == NULL)
5264 error = close_err;
5266 if (pack_fds) {
5267 const struct got_error *pack_err =
5268 got_repo_pack_fds_close(pack_fds);
5269 if (error == NULL)
5270 error = pack_err;
5272 TAILQ_FOREACH(pe, &paths, entry)
5273 free((char *)pe->path);
5274 got_pathlist_free(&paths);
5275 got_ref_list_free(&refs);
5276 if (f1 && fclose(f1) == EOF && error == NULL)
5277 error = got_error_from_errno("fclose");
5278 if (f2 && fclose(f2) == EOF && error == NULL)
5279 error = got_error_from_errno("fclose");
5280 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5281 error = got_error_from_errno("close");
5282 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5283 error = got_error_from_errno("close");
5284 return error;
5287 __dead static void
5288 usage_blame(void)
5290 fprintf(stderr,
5291 "usage: %s blame [-c commit] [-r repository-path] path\n",
5292 getprogname());
5293 exit(1);
5296 struct blame_line {
5297 int annotated;
5298 char *id_str;
5299 char *committer;
5300 char datebuf[11]; /* YYYY-MM-DD + NUL */
5303 struct blame_cb_args {
5304 struct blame_line *lines;
5305 int nlines;
5306 int nlines_prec;
5307 int lineno_cur;
5308 off_t *line_offsets;
5309 FILE *f;
5310 struct got_repository *repo;
5313 static const struct got_error *
5314 blame_cb(void *arg, int nlines, int lineno,
5315 struct got_commit_object *commit, struct got_object_id *id)
5317 const struct got_error *err = NULL;
5318 struct blame_cb_args *a = arg;
5319 struct blame_line *bline;
5320 char *line = NULL;
5321 size_t linesize = 0;
5322 off_t offset;
5323 struct tm tm;
5324 time_t committer_time;
5326 if (nlines != a->nlines ||
5327 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5328 return got_error(GOT_ERR_RANGE);
5330 if (sigint_received)
5331 return got_error(GOT_ERR_ITER_COMPLETED);
5333 if (lineno == -1)
5334 return NULL; /* no change in this commit */
5336 /* Annotate this line. */
5337 bline = &a->lines[lineno - 1];
5338 if (bline->annotated)
5339 return NULL;
5340 err = got_object_id_str(&bline->id_str, id);
5341 if (err)
5342 return err;
5344 bline->committer = strdup(got_object_commit_get_committer(commit));
5345 if (bline->committer == NULL) {
5346 err = got_error_from_errno("strdup");
5347 goto done;
5350 committer_time = got_object_commit_get_committer_time(commit);
5351 if (gmtime_r(&committer_time, &tm) == NULL)
5352 return got_error_from_errno("gmtime_r");
5353 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5354 &tm) == 0) {
5355 err = got_error(GOT_ERR_NO_SPACE);
5356 goto done;
5358 bline->annotated = 1;
5360 /* Print lines annotated so far. */
5361 bline = &a->lines[a->lineno_cur - 1];
5362 if (!bline->annotated)
5363 goto done;
5365 offset = a->line_offsets[a->lineno_cur - 1];
5366 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5367 err = got_error_from_errno("fseeko");
5368 goto done;
5371 while (bline->annotated) {
5372 char *smallerthan, *at, *nl, *committer;
5373 size_t len;
5375 if (getline(&line, &linesize, a->f) == -1) {
5376 if (ferror(a->f))
5377 err = got_error_from_errno("getline");
5378 break;
5381 committer = bline->committer;
5382 smallerthan = strchr(committer, '<');
5383 if (smallerthan && smallerthan[1] != '\0')
5384 committer = smallerthan + 1;
5385 at = strchr(committer, '@');
5386 if (at)
5387 *at = '\0';
5388 len = strlen(committer);
5389 if (len >= 9)
5390 committer[8] = '\0';
5392 nl = strchr(line, '\n');
5393 if (nl)
5394 *nl = '\0';
5395 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5396 bline->id_str, bline->datebuf, committer, line);
5398 a->lineno_cur++;
5399 bline = &a->lines[a->lineno_cur - 1];
5401 done:
5402 free(line);
5403 return err;
5406 static const struct got_error *
5407 cmd_blame(int argc, char *argv[])
5409 const struct got_error *error;
5410 struct got_repository *repo = NULL;
5411 struct got_worktree *worktree = NULL;
5412 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5413 char *link_target = NULL;
5414 struct got_object_id *obj_id = NULL;
5415 struct got_object_id *commit_id = NULL;
5416 struct got_commit_object *commit = NULL;
5417 struct got_blob_object *blob = NULL;
5418 char *commit_id_str = NULL;
5419 struct blame_cb_args bca;
5420 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5421 off_t filesize;
5422 int *pack_fds = NULL;
5423 FILE *f1 = NULL, *f2 = NULL;
5425 fd1 = got_opentempfd();
5426 if (fd1 == -1)
5427 return got_error_from_errno("got_opentempfd");
5429 memset(&bca, 0, sizeof(bca));
5431 #ifndef PROFILE
5432 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5433 NULL) == -1)
5434 err(1, "pledge");
5435 #endif
5437 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5438 switch (ch) {
5439 case 'c':
5440 commit_id_str = optarg;
5441 break;
5442 case 'r':
5443 repo_path = realpath(optarg, NULL);
5444 if (repo_path == NULL)
5445 return got_error_from_errno2("realpath",
5446 optarg);
5447 got_path_strip_trailing_slashes(repo_path);
5448 break;
5449 default:
5450 usage_blame();
5451 /* NOTREACHED */
5455 argc -= optind;
5456 argv += optind;
5458 if (argc == 1)
5459 path = argv[0];
5460 else
5461 usage_blame();
5463 cwd = getcwd(NULL, 0);
5464 if (cwd == NULL) {
5465 error = got_error_from_errno("getcwd");
5466 goto done;
5469 error = got_repo_pack_fds_open(&pack_fds);
5470 if (error != NULL)
5471 goto done;
5473 if (repo_path == NULL) {
5474 error = got_worktree_open(&worktree, cwd);
5475 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5476 goto done;
5477 else
5478 error = NULL;
5479 if (worktree) {
5480 repo_path =
5481 strdup(got_worktree_get_repo_path(worktree));
5482 if (repo_path == NULL) {
5483 error = got_error_from_errno("strdup");
5484 if (error)
5485 goto done;
5487 } else {
5488 repo_path = strdup(cwd);
5489 if (repo_path == NULL) {
5490 error = got_error_from_errno("strdup");
5491 goto done;
5496 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5497 if (error != NULL)
5498 goto done;
5500 if (worktree) {
5501 const char *prefix = got_worktree_get_path_prefix(worktree);
5502 char *p;
5504 error = got_worktree_resolve_path(&p, worktree, path);
5505 if (error)
5506 goto done;
5507 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5508 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5509 p) == -1) {
5510 error = got_error_from_errno("asprintf");
5511 free(p);
5512 goto done;
5514 free(p);
5515 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5516 } else {
5517 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5518 if (error)
5519 goto done;
5520 error = got_repo_map_path(&in_repo_path, repo, path);
5522 if (error)
5523 goto done;
5525 if (commit_id_str == NULL) {
5526 struct got_reference *head_ref;
5527 error = got_ref_open(&head_ref, repo, worktree ?
5528 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5529 if (error != NULL)
5530 goto done;
5531 error = got_ref_resolve(&commit_id, repo, head_ref);
5532 got_ref_close(head_ref);
5533 if (error != NULL)
5534 goto done;
5535 } else {
5536 struct got_reflist_head refs;
5537 TAILQ_INIT(&refs);
5538 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5539 NULL);
5540 if (error)
5541 goto done;
5542 error = got_repo_match_object_id(&commit_id, NULL,
5543 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5544 got_ref_list_free(&refs);
5545 if (error)
5546 goto done;
5549 if (worktree) {
5550 /* Release work tree lock. */
5551 got_worktree_close(worktree);
5552 worktree = NULL;
5555 error = got_object_open_as_commit(&commit, repo, commit_id);
5556 if (error)
5557 goto done;
5559 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5560 commit, repo);
5561 if (error)
5562 goto done;
5564 error = got_object_id_by_path(&obj_id, repo, commit,
5565 link_target ? link_target : in_repo_path);
5566 if (error)
5567 goto done;
5569 error = got_object_get_type(&obj_type, repo, obj_id);
5570 if (error)
5571 goto done;
5573 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5574 error = got_error_path(link_target ? link_target : in_repo_path,
5575 GOT_ERR_OBJ_TYPE);
5576 goto done;
5579 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5580 if (error)
5581 goto done;
5582 bca.f = got_opentemp();
5583 if (bca.f == NULL) {
5584 error = got_error_from_errno("got_opentemp");
5585 goto done;
5587 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5588 &bca.line_offsets, bca.f, blob);
5589 if (error || bca.nlines == 0)
5590 goto done;
5592 /* Don't include \n at EOF in the blame line count. */
5593 if (bca.line_offsets[bca.nlines - 1] == filesize)
5594 bca.nlines--;
5596 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5597 if (bca.lines == NULL) {
5598 error = got_error_from_errno("calloc");
5599 goto done;
5601 bca.lineno_cur = 1;
5602 bca.nlines_prec = 0;
5603 i = bca.nlines;
5604 while (i > 0) {
5605 i /= 10;
5606 bca.nlines_prec++;
5608 bca.repo = repo;
5610 fd2 = got_opentempfd();
5611 if (fd2 == -1) {
5612 error = got_error_from_errno("got_opentempfd");
5613 goto done;
5615 fd3 = got_opentempfd();
5616 if (fd3 == -1) {
5617 error = got_error_from_errno("got_opentempfd");
5618 goto done;
5620 f1 = got_opentemp();
5621 if (f1 == NULL) {
5622 error = got_error_from_errno("got_opentemp");
5623 goto done;
5625 f2 = got_opentemp();
5626 if (f2 == NULL) {
5627 error = got_error_from_errno("got_opentemp");
5628 goto done;
5630 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5631 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5632 check_cancelled, NULL, fd2, fd3, f1, f2);
5633 done:
5634 free(in_repo_path);
5635 free(link_target);
5636 free(repo_path);
5637 free(cwd);
5638 free(commit_id);
5639 free(obj_id);
5640 if (commit)
5641 got_object_commit_close(commit);
5643 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5644 error = got_error_from_errno("close");
5645 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5646 error = got_error_from_errno("close");
5647 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5648 error = got_error_from_errno("close");
5649 if (f1 && fclose(f1) == EOF && error == NULL)
5650 error = got_error_from_errno("fclose");
5651 if (f2 && fclose(f2) == EOF && error == NULL)
5652 error = got_error_from_errno("fclose");
5654 if (blob)
5655 got_object_blob_close(blob);
5656 if (worktree)
5657 got_worktree_close(worktree);
5658 if (repo) {
5659 const struct got_error *close_err = got_repo_close(repo);
5660 if (error == NULL)
5661 error = close_err;
5663 if (pack_fds) {
5664 const struct got_error *pack_err =
5665 got_repo_pack_fds_close(pack_fds);
5666 if (error == NULL)
5667 error = pack_err;
5669 if (bca.lines) {
5670 for (i = 0; i < bca.nlines; i++) {
5671 struct blame_line *bline = &bca.lines[i];
5672 free(bline->id_str);
5673 free(bline->committer);
5675 free(bca.lines);
5677 free(bca.line_offsets);
5678 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5679 error = got_error_from_errno("fclose");
5680 return error;
5683 __dead static void
5684 usage_tree(void)
5686 fprintf(stderr,
5687 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5688 getprogname());
5689 exit(1);
5692 static const struct got_error *
5693 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5694 const char *root_path, struct got_repository *repo)
5696 const struct got_error *err = NULL;
5697 int is_root_path = (strcmp(path, root_path) == 0);
5698 const char *modestr = "";
5699 mode_t mode = got_tree_entry_get_mode(te);
5700 char *link_target = NULL;
5702 path += strlen(root_path);
5703 while (path[0] == '/')
5704 path++;
5706 if (got_object_tree_entry_is_submodule(te))
5707 modestr = "$";
5708 else if (S_ISLNK(mode)) {
5709 int i;
5711 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5712 if (err)
5713 return err;
5714 for (i = 0; i < strlen(link_target); i++) {
5715 if (!isprint((unsigned char)link_target[i]))
5716 link_target[i] = '?';
5719 modestr = "@";
5721 else if (S_ISDIR(mode))
5722 modestr = "/";
5723 else if (mode & S_IXUSR)
5724 modestr = "*";
5726 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5727 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5728 link_target ? " -> ": "", link_target ? link_target : "");
5730 free(link_target);
5731 return NULL;
5734 static const struct got_error *
5735 print_tree(const char *path, struct got_commit_object *commit,
5736 int show_ids, int recurse, const char *root_path,
5737 struct got_repository *repo)
5739 const struct got_error *err = NULL;
5740 struct got_object_id *tree_id = NULL;
5741 struct got_tree_object *tree = NULL;
5742 int nentries, i;
5744 err = got_object_id_by_path(&tree_id, repo, commit, path);
5745 if (err)
5746 goto done;
5748 err = got_object_open_as_tree(&tree, repo, tree_id);
5749 if (err)
5750 goto done;
5751 nentries = got_object_tree_get_nentries(tree);
5752 for (i = 0; i < nentries; i++) {
5753 struct got_tree_entry *te;
5754 char *id = NULL;
5756 if (sigint_received || sigpipe_received)
5757 break;
5759 te = got_object_tree_get_entry(tree, i);
5760 if (show_ids) {
5761 char *id_str;
5762 err = got_object_id_str(&id_str,
5763 got_tree_entry_get_id(te));
5764 if (err)
5765 goto done;
5766 if (asprintf(&id, "%s ", id_str) == -1) {
5767 err = got_error_from_errno("asprintf");
5768 free(id_str);
5769 goto done;
5771 free(id_str);
5773 err = print_entry(te, id, path, root_path, repo);
5774 free(id);
5775 if (err)
5776 goto done;
5778 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5779 char *child_path;
5780 if (asprintf(&child_path, "%s%s%s", path,
5781 path[0] == '/' && path[1] == '\0' ? "" : "/",
5782 got_tree_entry_get_name(te)) == -1) {
5783 err = got_error_from_errno("asprintf");
5784 goto done;
5786 err = print_tree(child_path, commit, show_ids, 1,
5787 root_path, repo);
5788 free(child_path);
5789 if (err)
5790 goto done;
5793 done:
5794 if (tree)
5795 got_object_tree_close(tree);
5796 free(tree_id);
5797 return err;
5800 static const struct got_error *
5801 cmd_tree(int argc, char *argv[])
5803 const struct got_error *error;
5804 struct got_repository *repo = NULL;
5805 struct got_worktree *worktree = NULL;
5806 const char *path, *refname = NULL;
5807 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5808 struct got_object_id *commit_id = NULL;
5809 struct got_commit_object *commit = NULL;
5810 char *commit_id_str = NULL;
5811 int show_ids = 0, recurse = 0;
5812 int ch;
5813 int *pack_fds = NULL;
5815 #ifndef PROFILE
5816 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5817 NULL) == -1)
5818 err(1, "pledge");
5819 #endif
5821 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5822 switch (ch) {
5823 case 'c':
5824 commit_id_str = optarg;
5825 break;
5826 case 'r':
5827 repo_path = realpath(optarg, NULL);
5828 if (repo_path == NULL)
5829 return got_error_from_errno2("realpath",
5830 optarg);
5831 got_path_strip_trailing_slashes(repo_path);
5832 break;
5833 case 'i':
5834 show_ids = 1;
5835 break;
5836 case 'R':
5837 recurse = 1;
5838 break;
5839 default:
5840 usage_tree();
5841 /* NOTREACHED */
5845 argc -= optind;
5846 argv += optind;
5848 if (argc == 1)
5849 path = argv[0];
5850 else if (argc > 1)
5851 usage_tree();
5852 else
5853 path = NULL;
5855 cwd = getcwd(NULL, 0);
5856 if (cwd == NULL) {
5857 error = got_error_from_errno("getcwd");
5858 goto done;
5861 error = got_repo_pack_fds_open(&pack_fds);
5862 if (error != NULL)
5863 goto done;
5865 if (repo_path == NULL) {
5866 error = got_worktree_open(&worktree, cwd);
5867 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5868 goto done;
5869 else
5870 error = NULL;
5871 if (worktree) {
5872 repo_path =
5873 strdup(got_worktree_get_repo_path(worktree));
5874 if (repo_path == NULL)
5875 error = got_error_from_errno("strdup");
5876 if (error)
5877 goto done;
5878 } else {
5879 repo_path = strdup(cwd);
5880 if (repo_path == NULL) {
5881 error = got_error_from_errno("strdup");
5882 goto done;
5887 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5888 if (error != NULL)
5889 goto done;
5891 if (worktree) {
5892 const char *prefix = got_worktree_get_path_prefix(worktree);
5893 char *p;
5895 if (path == NULL)
5896 path = "";
5897 error = got_worktree_resolve_path(&p, worktree, path);
5898 if (error)
5899 goto done;
5900 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5901 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5902 p) == -1) {
5903 error = got_error_from_errno("asprintf");
5904 free(p);
5905 goto done;
5907 free(p);
5908 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5909 if (error)
5910 goto done;
5911 } else {
5912 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5913 if (error)
5914 goto done;
5915 if (path == NULL)
5916 path = "/";
5917 error = got_repo_map_path(&in_repo_path, repo, path);
5918 if (error != NULL)
5919 goto done;
5922 if (commit_id_str == NULL) {
5923 struct got_reference *head_ref;
5924 if (worktree)
5925 refname = got_worktree_get_head_ref_name(worktree);
5926 else
5927 refname = GOT_REF_HEAD;
5928 error = got_ref_open(&head_ref, repo, refname, 0);
5929 if (error != NULL)
5930 goto done;
5931 error = got_ref_resolve(&commit_id, repo, head_ref);
5932 got_ref_close(head_ref);
5933 if (error != NULL)
5934 goto done;
5935 } else {
5936 struct got_reflist_head refs;
5937 TAILQ_INIT(&refs);
5938 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5939 NULL);
5940 if (error)
5941 goto done;
5942 error = got_repo_match_object_id(&commit_id, NULL,
5943 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5944 got_ref_list_free(&refs);
5945 if (error)
5946 goto done;
5949 if (worktree) {
5950 /* Release work tree lock. */
5951 got_worktree_close(worktree);
5952 worktree = NULL;
5955 error = got_object_open_as_commit(&commit, repo, commit_id);
5956 if (error)
5957 goto done;
5959 error = print_tree(in_repo_path, commit, show_ids, recurse,
5960 in_repo_path, repo);
5961 done:
5962 free(in_repo_path);
5963 free(repo_path);
5964 free(cwd);
5965 free(commit_id);
5966 if (commit)
5967 got_object_commit_close(commit);
5968 if (worktree)
5969 got_worktree_close(worktree);
5970 if (repo) {
5971 const struct got_error *close_err = got_repo_close(repo);
5972 if (error == NULL)
5973 error = close_err;
5975 if (pack_fds) {
5976 const struct got_error *pack_err =
5977 got_repo_pack_fds_close(pack_fds);
5978 if (error == NULL)
5979 error = pack_err;
5981 return error;
5984 __dead static void
5985 usage_status(void)
5987 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5988 "[-S status-codes] [path ...]\n", getprogname());
5989 exit(1);
5992 struct got_status_arg {
5993 char *status_codes;
5994 int suppress;
5997 static const struct got_error *
5998 print_status(void *arg, unsigned char status, unsigned char staged_status,
5999 const char *path, struct got_object_id *blob_id,
6000 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6001 int dirfd, const char *de_name)
6003 struct got_status_arg *st = arg;
6005 if (status == staged_status && (status == GOT_STATUS_DELETE))
6006 status = GOT_STATUS_NO_CHANGE;
6007 if (st != NULL && st->status_codes) {
6008 size_t ncodes = strlen(st->status_codes);
6009 int i, j = 0;
6011 for (i = 0; i < ncodes ; i++) {
6012 if (st->suppress) {
6013 if (status == st->status_codes[i] ||
6014 staged_status == st->status_codes[i]) {
6015 j++;
6016 continue;
6018 } else {
6019 if (status == st->status_codes[i] ||
6020 staged_status == st->status_codes[i])
6021 break;
6025 if (st->suppress && j == 0)
6026 goto print;
6028 if (i == ncodes)
6029 return NULL;
6031 print:
6032 printf("%c%c %s\n", status, staged_status, path);
6033 return NULL;
6036 static const struct got_error *
6037 cmd_status(int argc, char *argv[])
6039 const struct got_error *error = NULL;
6040 struct got_repository *repo = NULL;
6041 struct got_worktree *worktree = NULL;
6042 struct got_status_arg st;
6043 char *cwd = NULL;
6044 struct got_pathlist_head paths;
6045 struct got_pathlist_entry *pe;
6046 int ch, i, no_ignores = 0;
6047 int *pack_fds = NULL;
6049 TAILQ_INIT(&paths);
6051 memset(&st, 0, sizeof(st));
6052 st.status_codes = NULL;
6053 st.suppress = 0;
6055 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6056 switch (ch) {
6057 case 'I':
6058 no_ignores = 1;
6059 break;
6060 case 'S':
6061 if (st.status_codes != NULL && st.suppress == 0)
6062 option_conflict('S', 's');
6063 st.suppress = 1;
6064 /* fallthrough */
6065 case 's':
6066 for (i = 0; i < strlen(optarg); i++) {
6067 switch (optarg[i]) {
6068 case GOT_STATUS_MODIFY:
6069 case GOT_STATUS_ADD:
6070 case GOT_STATUS_DELETE:
6071 case GOT_STATUS_CONFLICT:
6072 case GOT_STATUS_MISSING:
6073 case GOT_STATUS_OBSTRUCTED:
6074 case GOT_STATUS_UNVERSIONED:
6075 case GOT_STATUS_MODE_CHANGE:
6076 case GOT_STATUS_NONEXISTENT:
6077 break;
6078 default:
6079 errx(1, "invalid status code '%c'",
6080 optarg[i]);
6083 if (ch == 's' && st.suppress)
6084 option_conflict('s', 'S');
6085 st.status_codes = optarg;
6086 break;
6087 default:
6088 usage_status();
6089 /* NOTREACHED */
6093 argc -= optind;
6094 argv += optind;
6096 #ifndef PROFILE
6097 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6098 NULL) == -1)
6099 err(1, "pledge");
6100 #endif
6101 cwd = getcwd(NULL, 0);
6102 if (cwd == NULL) {
6103 error = got_error_from_errno("getcwd");
6104 goto done;
6107 error = got_repo_pack_fds_open(&pack_fds);
6108 if (error != NULL)
6109 goto done;
6111 error = got_worktree_open(&worktree, cwd);
6112 if (error) {
6113 if (error->code == GOT_ERR_NOT_WORKTREE)
6114 error = wrap_not_worktree_error(error, "status", cwd);
6115 goto done;
6118 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6119 NULL, pack_fds);
6120 if (error != NULL)
6121 goto done;
6123 error = apply_unveil(got_repo_get_path(repo), 1,
6124 got_worktree_get_root_path(worktree));
6125 if (error)
6126 goto done;
6128 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6129 if (error)
6130 goto done;
6132 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6133 print_status, &st, check_cancelled, NULL);
6134 done:
6135 if (pack_fds) {
6136 const struct got_error *pack_err =
6137 got_repo_pack_fds_close(pack_fds);
6138 if (error == NULL)
6139 error = pack_err;
6142 TAILQ_FOREACH(pe, &paths, entry)
6143 free((char *)pe->path);
6144 got_pathlist_free(&paths);
6145 free(cwd);
6146 return error;
6149 __dead static void
6150 usage_ref(void)
6152 fprintf(stderr,
6153 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6154 "[-s reference] [-d] [name]\n",
6155 getprogname());
6156 exit(1);
6159 static const struct got_error *
6160 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6162 static const struct got_error *err = NULL;
6163 struct got_reflist_head refs;
6164 struct got_reflist_entry *re;
6166 TAILQ_INIT(&refs);
6167 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6168 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6169 repo);
6170 if (err)
6171 return err;
6173 TAILQ_FOREACH(re, &refs, entry) {
6174 char *refstr;
6175 refstr = got_ref_to_str(re->ref);
6176 if (refstr == NULL) {
6177 err = got_error_from_errno("got_ref_to_str");
6178 break;
6180 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6181 free(refstr);
6184 got_ref_list_free(&refs);
6185 return err;
6188 static const struct got_error *
6189 delete_ref_by_name(struct got_repository *repo, const char *refname)
6191 const struct got_error *err;
6192 struct got_reference *ref;
6194 err = got_ref_open(&ref, repo, refname, 0);
6195 if (err)
6196 return err;
6198 err = delete_ref(repo, ref);
6199 got_ref_close(ref);
6200 return err;
6203 static const struct got_error *
6204 add_ref(struct got_repository *repo, const char *refname, const char *target)
6206 const struct got_error *err = NULL;
6207 struct got_object_id *id = NULL;
6208 struct got_reference *ref = NULL;
6209 struct got_reflist_head refs;
6212 * Don't let the user create a reference name with a leading '-'.
6213 * While technically a valid reference name, this case is usually
6214 * an unintended typo.
6216 if (refname[0] == '-')
6217 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6219 TAILQ_INIT(&refs);
6220 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6221 if (err)
6222 goto done;
6223 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6224 &refs, repo);
6225 got_ref_list_free(&refs);
6226 if (err)
6227 goto done;
6229 err = got_ref_alloc(&ref, refname, id);
6230 if (err)
6231 goto done;
6233 err = got_ref_write(ref, repo);
6234 done:
6235 if (ref)
6236 got_ref_close(ref);
6237 free(id);
6238 return err;
6241 static const struct got_error *
6242 add_symref(struct got_repository *repo, const char *refname, const char *target)
6244 const struct got_error *err = NULL;
6245 struct got_reference *ref = NULL;
6246 struct got_reference *target_ref = NULL;
6249 * Don't let the user create a reference name with a leading '-'.
6250 * While technically a valid reference name, this case is usually
6251 * an unintended typo.
6253 if (refname[0] == '-')
6254 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6256 err = got_ref_open(&target_ref, repo, target, 0);
6257 if (err)
6258 return err;
6260 err = got_ref_alloc_symref(&ref, refname, target_ref);
6261 if (err)
6262 goto done;
6264 err = got_ref_write(ref, repo);
6265 done:
6266 if (target_ref)
6267 got_ref_close(target_ref);
6268 if (ref)
6269 got_ref_close(ref);
6270 return err;
6273 static const struct got_error *
6274 cmd_ref(int argc, char *argv[])
6276 const struct got_error *error = NULL;
6277 struct got_repository *repo = NULL;
6278 struct got_worktree *worktree = NULL;
6279 char *cwd = NULL, *repo_path = NULL;
6280 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6281 const char *obj_arg = NULL, *symref_target= NULL;
6282 char *refname = NULL;
6283 int *pack_fds = NULL;
6285 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6286 switch (ch) {
6287 case 'c':
6288 obj_arg = optarg;
6289 break;
6290 case 'd':
6291 do_delete = 1;
6292 break;
6293 case 'r':
6294 repo_path = realpath(optarg, NULL);
6295 if (repo_path == NULL)
6296 return got_error_from_errno2("realpath",
6297 optarg);
6298 got_path_strip_trailing_slashes(repo_path);
6299 break;
6300 case 'l':
6301 do_list = 1;
6302 break;
6303 case 's':
6304 symref_target = optarg;
6305 break;
6306 case 't':
6307 sort_by_time = 1;
6308 break;
6309 default:
6310 usage_ref();
6311 /* NOTREACHED */
6315 if (obj_arg && do_list)
6316 option_conflict('c', 'l');
6317 if (obj_arg && do_delete)
6318 option_conflict('c', 'd');
6319 if (obj_arg && symref_target)
6320 option_conflict('c', 's');
6321 if (symref_target && do_delete)
6322 option_conflict('s', 'd');
6323 if (symref_target && do_list)
6324 option_conflict('s', 'l');
6325 if (do_delete && do_list)
6326 option_conflict('d', 'l');
6327 if (sort_by_time && !do_list)
6328 errx(1, "-t option requires -l option");
6330 argc -= optind;
6331 argv += optind;
6333 if (do_list) {
6334 if (argc != 0 && argc != 1)
6335 usage_ref();
6336 if (argc == 1) {
6337 refname = strdup(argv[0]);
6338 if (refname == NULL) {
6339 error = got_error_from_errno("strdup");
6340 goto done;
6343 } else {
6344 if (argc != 1)
6345 usage_ref();
6346 refname = strdup(argv[0]);
6347 if (refname == NULL) {
6348 error = got_error_from_errno("strdup");
6349 goto done;
6353 if (refname)
6354 got_path_strip_trailing_slashes(refname);
6356 #ifndef PROFILE
6357 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6358 "sendfd unveil", NULL) == -1)
6359 err(1, "pledge");
6360 #endif
6361 cwd = getcwd(NULL, 0);
6362 if (cwd == NULL) {
6363 error = got_error_from_errno("getcwd");
6364 goto done;
6367 error = got_repo_pack_fds_open(&pack_fds);
6368 if (error != NULL)
6369 goto done;
6371 if (repo_path == NULL) {
6372 error = got_worktree_open(&worktree, cwd);
6373 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6374 goto done;
6375 else
6376 error = NULL;
6377 if (worktree) {
6378 repo_path =
6379 strdup(got_worktree_get_repo_path(worktree));
6380 if (repo_path == NULL)
6381 error = got_error_from_errno("strdup");
6382 if (error)
6383 goto done;
6384 } else {
6385 repo_path = strdup(cwd);
6386 if (repo_path == NULL) {
6387 error = got_error_from_errno("strdup");
6388 goto done;
6393 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6394 if (error != NULL)
6395 goto done;
6397 #ifndef PROFILE
6398 if (do_list) {
6399 /* Remove "cpath" promise. */
6400 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6401 NULL) == -1)
6402 err(1, "pledge");
6404 #endif
6406 error = apply_unveil(got_repo_get_path(repo), do_list,
6407 worktree ? got_worktree_get_root_path(worktree) : NULL);
6408 if (error)
6409 goto done;
6411 if (do_list)
6412 error = list_refs(repo, refname, sort_by_time);
6413 else if (do_delete)
6414 error = delete_ref_by_name(repo, refname);
6415 else if (symref_target)
6416 error = add_symref(repo, refname, symref_target);
6417 else {
6418 if (obj_arg == NULL)
6419 usage_ref();
6420 error = add_ref(repo, refname, obj_arg);
6422 done:
6423 free(refname);
6424 if (repo) {
6425 const struct got_error *close_err = got_repo_close(repo);
6426 if (error == NULL)
6427 error = close_err;
6429 if (worktree)
6430 got_worktree_close(worktree);
6431 if (pack_fds) {
6432 const struct got_error *pack_err =
6433 got_repo_pack_fds_close(pack_fds);
6434 if (error == NULL)
6435 error = pack_err;
6437 free(cwd);
6438 free(repo_path);
6439 return error;
6442 __dead static void
6443 usage_branch(void)
6445 fprintf(stderr,
6446 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6447 "[-n] [name]\n", getprogname());
6448 exit(1);
6451 static const struct got_error *
6452 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6453 struct got_reference *ref)
6455 const struct got_error *err = NULL;
6456 const char *refname, *marker = " ";
6457 char *refstr;
6459 refname = got_ref_get_name(ref);
6460 if (worktree && strcmp(refname,
6461 got_worktree_get_head_ref_name(worktree)) == 0) {
6462 struct got_object_id *id = NULL;
6464 err = got_ref_resolve(&id, repo, ref);
6465 if (err)
6466 return err;
6467 if (got_object_id_cmp(id,
6468 got_worktree_get_base_commit_id(worktree)) == 0)
6469 marker = "* ";
6470 else
6471 marker = "~ ";
6472 free(id);
6475 if (strncmp(refname, "refs/heads/", 11) == 0)
6476 refname += 11;
6477 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6478 refname += 18;
6479 if (strncmp(refname, "refs/remotes/", 13) == 0)
6480 refname += 13;
6482 refstr = got_ref_to_str(ref);
6483 if (refstr == NULL)
6484 return got_error_from_errno("got_ref_to_str");
6486 printf("%s%s: %s\n", marker, refname, refstr);
6487 free(refstr);
6488 return NULL;
6491 static const struct got_error *
6492 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6494 const char *refname;
6496 if (worktree == NULL)
6497 return got_error(GOT_ERR_NOT_WORKTREE);
6499 refname = got_worktree_get_head_ref_name(worktree);
6501 if (strncmp(refname, "refs/heads/", 11) == 0)
6502 refname += 11;
6503 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6504 refname += 18;
6506 printf("%s\n", refname);
6508 return NULL;
6511 static const struct got_error *
6512 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6513 int sort_by_time)
6515 static const struct got_error *err = NULL;
6516 struct got_reflist_head refs;
6517 struct got_reflist_entry *re;
6518 struct got_reference *temp_ref = NULL;
6519 int rebase_in_progress, histedit_in_progress;
6521 TAILQ_INIT(&refs);
6523 if (worktree) {
6524 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6525 worktree);
6526 if (err)
6527 return err;
6529 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6530 worktree);
6531 if (err)
6532 return err;
6534 if (rebase_in_progress || histedit_in_progress) {
6535 err = got_ref_open(&temp_ref, repo,
6536 got_worktree_get_head_ref_name(worktree), 0);
6537 if (err)
6538 return err;
6539 list_branch(repo, worktree, temp_ref);
6540 got_ref_close(temp_ref);
6544 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6545 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6546 repo);
6547 if (err)
6548 return err;
6550 TAILQ_FOREACH(re, &refs, entry)
6551 list_branch(repo, worktree, re->ref);
6553 got_ref_list_free(&refs);
6555 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6556 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6557 repo);
6558 if (err)
6559 return err;
6561 TAILQ_FOREACH(re, &refs, entry)
6562 list_branch(repo, worktree, re->ref);
6564 got_ref_list_free(&refs);
6566 return NULL;
6569 static const struct got_error *
6570 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6571 const char *branch_name)
6573 const struct got_error *err = NULL;
6574 struct got_reference *ref = NULL;
6575 char *refname, *remote_refname = NULL;
6577 if (strncmp(branch_name, "refs/", 5) == 0)
6578 branch_name += 5;
6579 if (strncmp(branch_name, "heads/", 6) == 0)
6580 branch_name += 6;
6581 else if (strncmp(branch_name, "remotes/", 8) == 0)
6582 branch_name += 8;
6584 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6585 return got_error_from_errno("asprintf");
6587 if (asprintf(&remote_refname, "refs/remotes/%s",
6588 branch_name) == -1) {
6589 err = got_error_from_errno("asprintf");
6590 goto done;
6593 err = got_ref_open(&ref, repo, refname, 0);
6594 if (err) {
6595 const struct got_error *err2;
6596 if (err->code != GOT_ERR_NOT_REF)
6597 goto done;
6599 * Keep 'err' intact such that if neither branch exists
6600 * we report "refs/heads" rather than "refs/remotes" in
6601 * our error message.
6603 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6604 if (err2)
6605 goto done;
6606 err = NULL;
6609 if (worktree &&
6610 strcmp(got_worktree_get_head_ref_name(worktree),
6611 got_ref_get_name(ref)) == 0) {
6612 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6613 "will not delete this work tree's current branch");
6614 goto done;
6617 err = delete_ref(repo, ref);
6618 done:
6619 if (ref)
6620 got_ref_close(ref);
6621 free(refname);
6622 free(remote_refname);
6623 return err;
6626 static const struct got_error *
6627 add_branch(struct got_repository *repo, const char *branch_name,
6628 struct got_object_id *base_commit_id)
6630 const struct got_error *err = NULL;
6631 struct got_reference *ref = NULL;
6632 char *base_refname = NULL, *refname = NULL;
6635 * Don't let the user create a branch name with a leading '-'.
6636 * While technically a valid reference name, this case is usually
6637 * an unintended typo.
6639 if (branch_name[0] == '-')
6640 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6642 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6643 branch_name += 11;
6645 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6646 err = got_error_from_errno("asprintf");
6647 goto done;
6650 err = got_ref_open(&ref, repo, refname, 0);
6651 if (err == NULL) {
6652 err = got_error(GOT_ERR_BRANCH_EXISTS);
6653 goto done;
6654 } else if (err->code != GOT_ERR_NOT_REF)
6655 goto done;
6657 err = got_ref_alloc(&ref, refname, base_commit_id);
6658 if (err)
6659 goto done;
6661 err = got_ref_write(ref, repo);
6662 done:
6663 if (ref)
6664 got_ref_close(ref);
6665 free(base_refname);
6666 free(refname);
6667 return err;
6670 static const struct got_error *
6671 cmd_branch(int argc, char *argv[])
6673 const struct got_error *error = NULL;
6674 struct got_repository *repo = NULL;
6675 struct got_worktree *worktree = NULL;
6676 char *cwd = NULL, *repo_path = NULL;
6677 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6678 const char *delref = NULL, *commit_id_arg = NULL;
6679 struct got_reference *ref = NULL;
6680 struct got_pathlist_head paths;
6681 struct got_pathlist_entry *pe;
6682 struct got_object_id *commit_id = NULL;
6683 char *commit_id_str = NULL;
6684 int *pack_fds = NULL;
6686 TAILQ_INIT(&paths);
6688 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6689 switch (ch) {
6690 case 'c':
6691 commit_id_arg = optarg;
6692 break;
6693 case 'd':
6694 delref = optarg;
6695 break;
6696 case 'r':
6697 repo_path = realpath(optarg, NULL);
6698 if (repo_path == NULL)
6699 return got_error_from_errno2("realpath",
6700 optarg);
6701 got_path_strip_trailing_slashes(repo_path);
6702 break;
6703 case 'l':
6704 do_list = 1;
6705 break;
6706 case 'n':
6707 do_update = 0;
6708 break;
6709 case 't':
6710 sort_by_time = 1;
6711 break;
6712 default:
6713 usage_branch();
6714 /* NOTREACHED */
6718 if (do_list && delref)
6719 option_conflict('l', 'd');
6720 if (sort_by_time && !do_list)
6721 errx(1, "-t option requires -l option");
6723 argc -= optind;
6724 argv += optind;
6726 if (!do_list && !delref && argc == 0)
6727 do_show = 1;
6729 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6730 errx(1, "-c option can only be used when creating a branch");
6732 if (do_list || delref) {
6733 if (argc > 0)
6734 usage_branch();
6735 } else if (!do_show && argc != 1)
6736 usage_branch();
6738 #ifndef PROFILE
6739 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6740 "sendfd unveil", NULL) == -1)
6741 err(1, "pledge");
6742 #endif
6743 cwd = getcwd(NULL, 0);
6744 if (cwd == NULL) {
6745 error = got_error_from_errno("getcwd");
6746 goto done;
6749 error = got_repo_pack_fds_open(&pack_fds);
6750 if (error != NULL)
6751 goto done;
6753 if (repo_path == NULL) {
6754 error = got_worktree_open(&worktree, cwd);
6755 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6756 goto done;
6757 else
6758 error = NULL;
6759 if (worktree) {
6760 repo_path =
6761 strdup(got_worktree_get_repo_path(worktree));
6762 if (repo_path == NULL)
6763 error = got_error_from_errno("strdup");
6764 if (error)
6765 goto done;
6766 } else {
6767 repo_path = strdup(cwd);
6768 if (repo_path == NULL) {
6769 error = got_error_from_errno("strdup");
6770 goto done;
6775 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6776 if (error != NULL)
6777 goto done;
6779 #ifndef PROFILE
6780 if (do_list || do_show) {
6781 /* Remove "cpath" promise. */
6782 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6783 NULL) == -1)
6784 err(1, "pledge");
6786 #endif
6788 error = apply_unveil(got_repo_get_path(repo), do_list,
6789 worktree ? got_worktree_get_root_path(worktree) : NULL);
6790 if (error)
6791 goto done;
6793 if (do_show)
6794 error = show_current_branch(repo, worktree);
6795 else if (do_list)
6796 error = list_branches(repo, worktree, sort_by_time);
6797 else if (delref)
6798 error = delete_branch(repo, worktree, delref);
6799 else {
6800 struct got_reflist_head refs;
6801 TAILQ_INIT(&refs);
6802 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6803 NULL);
6804 if (error)
6805 goto done;
6806 if (commit_id_arg == NULL)
6807 commit_id_arg = worktree ?
6808 got_worktree_get_head_ref_name(worktree) :
6809 GOT_REF_HEAD;
6810 error = got_repo_match_object_id(&commit_id, NULL,
6811 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6812 got_ref_list_free(&refs);
6813 if (error)
6814 goto done;
6815 error = add_branch(repo, argv[0], commit_id);
6816 if (error)
6817 goto done;
6818 if (worktree && do_update) {
6819 struct got_update_progress_arg upa;
6820 char *branch_refname = NULL;
6822 error = got_object_id_str(&commit_id_str, commit_id);
6823 if (error)
6824 goto done;
6825 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6826 worktree);
6827 if (error)
6828 goto done;
6829 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6830 == -1) {
6831 error = got_error_from_errno("asprintf");
6832 goto done;
6834 error = got_ref_open(&ref, repo, branch_refname, 0);
6835 free(branch_refname);
6836 if (error)
6837 goto done;
6838 error = switch_head_ref(ref, commit_id, worktree,
6839 repo);
6840 if (error)
6841 goto done;
6842 error = got_worktree_set_base_commit_id(worktree, repo,
6843 commit_id);
6844 if (error)
6845 goto done;
6846 memset(&upa, 0, sizeof(upa));
6847 error = got_worktree_checkout_files(worktree, &paths,
6848 repo, update_progress, &upa, check_cancelled,
6849 NULL);
6850 if (error)
6851 goto done;
6852 if (upa.did_something) {
6853 printf("Updated to %s: %s\n",
6854 got_worktree_get_head_ref_name(worktree),
6855 commit_id_str);
6857 print_update_progress_stats(&upa);
6860 done:
6861 if (ref)
6862 got_ref_close(ref);
6863 if (repo) {
6864 const struct got_error *close_err = got_repo_close(repo);
6865 if (error == NULL)
6866 error = close_err;
6868 if (worktree)
6869 got_worktree_close(worktree);
6870 if (pack_fds) {
6871 const struct got_error *pack_err =
6872 got_repo_pack_fds_close(pack_fds);
6873 if (error == NULL)
6874 error = pack_err;
6876 free(cwd);
6877 free(repo_path);
6878 free(commit_id);
6879 free(commit_id_str);
6880 TAILQ_FOREACH(pe, &paths, entry)
6881 free((char *)pe->path);
6882 got_pathlist_free(&paths);
6883 return error;
6887 __dead static void
6888 usage_tag(void)
6890 fprintf(stderr,
6891 "usage: %s tag [-c commit] [-r repository] [-l] "
6892 "[-m message] [-s signer-id] [-v] [-V] name\n",
6893 getprogname());
6894 exit(1);
6897 #if 0
6898 static const struct got_error *
6899 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6901 const struct got_error *err = NULL;
6902 struct got_reflist_entry *re, *se, *new;
6903 struct got_object_id *re_id, *se_id;
6904 struct got_tag_object *re_tag, *se_tag;
6905 time_t re_time, se_time;
6907 STAILQ_FOREACH(re, tags, entry) {
6908 se = STAILQ_FIRST(sorted);
6909 if (se == NULL) {
6910 err = got_reflist_entry_dup(&new, re);
6911 if (err)
6912 return err;
6913 STAILQ_INSERT_HEAD(sorted, new, entry);
6914 continue;
6915 } else {
6916 err = got_ref_resolve(&re_id, repo, re->ref);
6917 if (err)
6918 break;
6919 err = got_object_open_as_tag(&re_tag, repo, re_id);
6920 free(re_id);
6921 if (err)
6922 break;
6923 re_time = got_object_tag_get_tagger_time(re_tag);
6924 got_object_tag_close(re_tag);
6927 while (se) {
6928 err = got_ref_resolve(&se_id, repo, re->ref);
6929 if (err)
6930 break;
6931 err = got_object_open_as_tag(&se_tag, repo, se_id);
6932 free(se_id);
6933 if (err)
6934 break;
6935 se_time = got_object_tag_get_tagger_time(se_tag);
6936 got_object_tag_close(se_tag);
6938 if (se_time > re_time) {
6939 err = got_reflist_entry_dup(&new, re);
6940 if (err)
6941 return err;
6942 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6943 break;
6945 se = STAILQ_NEXT(se, entry);
6946 continue;
6949 done:
6950 return err;
6952 #endif
6954 static const struct got_error *
6955 get_tag_refname(char **refname, const char *tag_name)
6957 const struct got_error *err;
6959 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6960 *refname = strdup(tag_name);
6961 if (*refname == NULL)
6962 return got_error_from_errno("strdup");
6963 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6964 err = got_error_from_errno("asprintf");
6965 *refname = NULL;
6966 return err;
6969 return NULL;
6972 static const struct got_error *
6973 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6974 const char *allowed_signers, const char *revoked_signers, int verbosity)
6976 static const struct got_error *err = NULL;
6977 struct got_reflist_head refs;
6978 struct got_reflist_entry *re;
6979 char *wanted_refname = NULL;
6980 int bad_sigs = 0;
6982 TAILQ_INIT(&refs);
6984 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6985 if (err)
6986 return err;
6988 if (tag_name) {
6989 struct got_reference *ref;
6990 err = get_tag_refname(&wanted_refname, tag_name);
6991 if (err)
6992 goto done;
6993 /* Wanted tag reference should exist. */
6994 err = got_ref_open(&ref, repo, wanted_refname, 0);
6995 if (err)
6996 goto done;
6997 got_ref_close(ref);
7000 TAILQ_FOREACH(re, &refs, entry) {
7001 const char *refname;
7002 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7003 char datebuf[26];
7004 const char *tagger, *ssh_sig = NULL;
7005 char *sig_msg = NULL;
7006 time_t tagger_time;
7007 struct got_object_id *id;
7008 struct got_tag_object *tag;
7009 struct got_commit_object *commit = NULL;
7011 refname = got_ref_get_name(re->ref);
7012 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7013 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7014 continue;
7015 refname += 10;
7016 refstr = got_ref_to_str(re->ref);
7017 if (refstr == NULL) {
7018 err = got_error_from_errno("got_ref_to_str");
7019 break;
7022 err = got_ref_resolve(&id, repo, re->ref);
7023 if (err)
7024 break;
7025 err = got_object_open_as_tag(&tag, repo, id);
7026 if (err) {
7027 if (err->code != GOT_ERR_OBJ_TYPE) {
7028 free(id);
7029 break;
7031 /* "lightweight" tag */
7032 err = got_object_open_as_commit(&commit, repo, id);
7033 if (err) {
7034 free(id);
7035 break;
7037 tagger = got_object_commit_get_committer(commit);
7038 tagger_time =
7039 got_object_commit_get_committer_time(commit);
7040 err = got_object_id_str(&id_str, id);
7041 free(id);
7042 if (err)
7043 break;
7044 } else {
7045 free(id);
7046 tagger = got_object_tag_get_tagger(tag);
7047 tagger_time = got_object_tag_get_tagger_time(tag);
7048 err = got_object_id_str(&id_str,
7049 got_object_tag_get_object_id(tag));
7050 if (err)
7051 break;
7054 if (verify_tags) {
7055 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7056 got_object_tag_get_message(tag));
7057 if (ssh_sig && allowed_signers == NULL) {
7058 err = got_error_msg(
7059 GOT_ERR_VERIFY_TAG_SIGNATURE,
7060 "SSH signature verification requires "
7061 "setting allowed_signers in "
7062 "got.conf(5)");
7063 break;
7067 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7068 free(refstr);
7069 printf("from: %s\n", tagger);
7070 datestr = get_datestr(&tagger_time, datebuf);
7071 if (datestr)
7072 printf("date: %s UTC\n", datestr);
7073 if (commit)
7074 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7075 else {
7076 switch (got_object_tag_get_object_type(tag)) {
7077 case GOT_OBJ_TYPE_BLOB:
7078 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7079 id_str);
7080 break;
7081 case GOT_OBJ_TYPE_TREE:
7082 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7083 id_str);
7084 break;
7085 case GOT_OBJ_TYPE_COMMIT:
7086 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7087 id_str);
7088 break;
7089 case GOT_OBJ_TYPE_TAG:
7090 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7091 id_str);
7092 break;
7093 default:
7094 break;
7097 free(id_str);
7099 if (ssh_sig) {
7100 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7101 allowed_signers, revoked_signers, verbosity);
7102 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7103 bad_sigs = 1;
7104 else if (err)
7105 break;
7106 printf("signature: %s", sig_msg);
7107 free(sig_msg);
7108 sig_msg = NULL;
7111 if (commit) {
7112 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7113 if (err)
7114 break;
7115 got_object_commit_close(commit);
7116 } else {
7117 tagmsg0 = strdup(got_object_tag_get_message(tag));
7118 got_object_tag_close(tag);
7119 if (tagmsg0 == NULL) {
7120 err = got_error_from_errno("strdup");
7121 break;
7125 tagmsg = tagmsg0;
7126 do {
7127 line = strsep(&tagmsg, "\n");
7128 if (line)
7129 printf(" %s\n", line);
7130 } while (line);
7131 free(tagmsg0);
7133 done:
7134 got_ref_list_free(&refs);
7135 free(wanted_refname);
7137 if (err == NULL && bad_sigs)
7138 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7139 return err;
7142 static const struct got_error *
7143 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7144 const char *tag_name, const char *repo_path)
7146 const struct got_error *err = NULL;
7147 char *template = NULL, *initial_content = NULL;
7148 char *editor = NULL;
7149 int initial_content_len;
7150 int fd = -1;
7152 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7153 err = got_error_from_errno("asprintf");
7154 goto done;
7157 initial_content_len = asprintf(&initial_content,
7158 "\n# tagging commit %s as %s\n",
7159 commit_id_str, tag_name);
7160 if (initial_content_len == -1) {
7161 err = got_error_from_errno("asprintf");
7162 goto done;
7165 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7166 if (err)
7167 goto done;
7169 if (write(fd, initial_content, initial_content_len) == -1) {
7170 err = got_error_from_errno2("write", *tagmsg_path);
7171 goto done;
7174 err = get_editor(&editor);
7175 if (err)
7176 goto done;
7177 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7178 initial_content_len, 1);
7179 done:
7180 free(initial_content);
7181 free(template);
7182 free(editor);
7184 if (fd != -1 && close(fd) == -1 && err == NULL)
7185 err = got_error_from_errno2("close", *tagmsg_path);
7187 if (err) {
7188 free(*tagmsg);
7189 *tagmsg = NULL;
7191 return err;
7194 static const struct got_error *
7195 add_tag(struct got_repository *repo, const char *tagger,
7196 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7197 const char *signer_id, int verbosity)
7199 const struct got_error *err = NULL;
7200 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7201 char *label = NULL, *commit_id_str = NULL;
7202 struct got_reference *ref = NULL;
7203 char *refname = NULL, *tagmsg = NULL;
7204 char *tagmsg_path = NULL, *tag_id_str = NULL;
7205 int preserve_tagmsg = 0;
7206 struct got_reflist_head refs;
7208 TAILQ_INIT(&refs);
7211 * Don't let the user create a tag name with a leading '-'.
7212 * While technically a valid reference name, this case is usually
7213 * an unintended typo.
7215 if (tag_name[0] == '-')
7216 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7218 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7219 if (err)
7220 goto done;
7222 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7223 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7224 if (err)
7225 goto done;
7227 err = got_object_id_str(&commit_id_str, commit_id);
7228 if (err)
7229 goto done;
7231 err = get_tag_refname(&refname, tag_name);
7232 if (err)
7233 goto done;
7234 if (strncmp("refs/tags/", tag_name, 10) == 0)
7235 tag_name += 10;
7237 err = got_ref_open(&ref, repo, refname, 0);
7238 if (err == NULL) {
7239 err = got_error(GOT_ERR_TAG_EXISTS);
7240 goto done;
7241 } else if (err->code != GOT_ERR_NOT_REF)
7242 goto done;
7244 if (tagmsg_arg == NULL) {
7245 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7246 tag_name, got_repo_get_path(repo));
7247 if (err) {
7248 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7249 tagmsg_path != NULL)
7250 preserve_tagmsg = 1;
7251 goto done;
7253 /* Editor is done; we can now apply unveil(2) */
7254 err = got_sigs_apply_unveil();
7255 if (err)
7256 goto done;
7257 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7258 if (err)
7259 goto done;
7262 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7263 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7264 verbosity);
7265 if (err) {
7266 if (tagmsg_path)
7267 preserve_tagmsg = 1;
7268 goto done;
7271 err = got_ref_alloc(&ref, refname, tag_id);
7272 if (err) {
7273 if (tagmsg_path)
7274 preserve_tagmsg = 1;
7275 goto done;
7278 err = got_ref_write(ref, repo);
7279 if (err) {
7280 if (tagmsg_path)
7281 preserve_tagmsg = 1;
7282 goto done;
7285 err = got_object_id_str(&tag_id_str, tag_id);
7286 if (err) {
7287 if (tagmsg_path)
7288 preserve_tagmsg = 1;
7289 goto done;
7291 printf("Created tag %s\n", tag_id_str);
7292 done:
7293 if (preserve_tagmsg) {
7294 fprintf(stderr, "%s: tag message preserved in %s\n",
7295 getprogname(), tagmsg_path);
7296 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7297 err = got_error_from_errno2("unlink", tagmsg_path);
7298 free(tag_id_str);
7299 if (ref)
7300 got_ref_close(ref);
7301 free(commit_id);
7302 free(commit_id_str);
7303 free(refname);
7304 free(tagmsg);
7305 free(tagmsg_path);
7306 got_ref_list_free(&refs);
7307 return err;
7310 static const struct got_error *
7311 cmd_tag(int argc, char *argv[])
7313 const struct got_error *error = NULL;
7314 struct got_repository *repo = NULL;
7315 struct got_worktree *worktree = NULL;
7316 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7317 char *gitconfig_path = NULL, *tagger = NULL;
7318 char *allowed_signers = NULL, *revoked_signers = NULL;
7319 char *signer_id = NULL;
7320 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7321 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7322 int *pack_fds = NULL;
7324 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7325 switch (ch) {
7326 case 'c':
7327 commit_id_arg = optarg;
7328 break;
7329 case 'm':
7330 tagmsg = optarg;
7331 break;
7332 case 'r':
7333 repo_path = realpath(optarg, NULL);
7334 if (repo_path == NULL) {
7335 error = got_error_from_errno2("realpath",
7336 optarg);
7337 goto done;
7339 got_path_strip_trailing_slashes(repo_path);
7340 break;
7341 case 'l':
7342 do_list = 1;
7343 break;
7344 case 's':
7345 signer_id = strdup(optarg);
7346 if (signer_id == NULL) {
7347 error = got_error_from_errno("strdup");
7348 goto done;
7350 break;
7351 case 'V':
7352 verify_tags = 1;
7353 break;
7354 case 'v':
7355 if (verbosity < 0)
7356 verbosity = 0;
7357 else if (verbosity < 3)
7358 verbosity++;
7359 break;
7360 default:
7361 usage_tag();
7362 /* NOTREACHED */
7366 argc -= optind;
7367 argv += optind;
7369 if (do_list || verify_tags) {
7370 if (commit_id_arg != NULL)
7371 errx(1,
7372 "-c option can only be used when creating a tag");
7373 if (tagmsg) {
7374 if (do_list)
7375 option_conflict('l', 'm');
7376 else
7377 option_conflict('V', 'm');
7379 if (signer_id) {
7380 if (do_list)
7381 option_conflict('l', 's');
7382 else
7383 option_conflict('V', 's');
7385 if (argc > 1)
7386 usage_tag();
7387 } else if (argc != 1)
7388 usage_tag();
7390 if (argc == 1)
7391 tag_name = argv[0];
7393 #ifndef PROFILE
7394 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7395 "sendfd unveil", NULL) == -1)
7396 err(1, "pledge");
7397 #endif
7398 cwd = getcwd(NULL, 0);
7399 if (cwd == NULL) {
7400 error = got_error_from_errno("getcwd");
7401 goto done;
7404 error = got_repo_pack_fds_open(&pack_fds);
7405 if (error != NULL)
7406 goto done;
7408 if (repo_path == NULL) {
7409 error = got_worktree_open(&worktree, cwd);
7410 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7411 goto done;
7412 else
7413 error = NULL;
7414 if (worktree) {
7415 repo_path =
7416 strdup(got_worktree_get_repo_path(worktree));
7417 if (repo_path == NULL)
7418 error = got_error_from_errno("strdup");
7419 if (error)
7420 goto done;
7421 } else {
7422 repo_path = strdup(cwd);
7423 if (repo_path == NULL) {
7424 error = got_error_from_errno("strdup");
7425 goto done;
7430 if (do_list || verify_tags) {
7431 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7432 if (error != NULL)
7433 goto done;
7434 error = get_allowed_signers(&allowed_signers, repo, worktree);
7435 if (error)
7436 goto done;
7437 error = get_revoked_signers(&revoked_signers, repo, worktree);
7438 if (error)
7439 goto done;
7440 if (worktree) {
7441 /* Release work tree lock. */
7442 got_worktree_close(worktree);
7443 worktree = NULL;
7447 * Remove "cpath" promise unless needed for signature tmpfile
7448 * creation.
7450 if (verify_tags)
7451 got_sigs_apply_unveil();
7452 else {
7453 #ifndef PROFILE
7454 if (pledge("stdio rpath wpath flock proc exec sendfd "
7455 "unveil", NULL) == -1)
7456 err(1, "pledge");
7457 #endif
7459 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7460 if (error)
7461 goto done;
7462 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7463 revoked_signers, verbosity);
7464 } else {
7465 error = get_gitconfig_path(&gitconfig_path);
7466 if (error)
7467 goto done;
7468 error = got_repo_open(&repo, repo_path, gitconfig_path,
7469 pack_fds);
7470 if (error != NULL)
7471 goto done;
7473 error = get_author(&tagger, repo, worktree);
7474 if (error)
7475 goto done;
7476 if (signer_id == NULL) {
7477 error = get_signer_id(&signer_id, repo, worktree);
7478 if (error)
7479 goto done;
7482 if (tagmsg) {
7483 if (signer_id) {
7484 error = got_sigs_apply_unveil();
7485 if (error)
7486 goto done;
7488 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7489 if (error)
7490 goto done;
7493 if (commit_id_arg == NULL) {
7494 struct got_reference *head_ref;
7495 struct got_object_id *commit_id;
7496 error = got_ref_open(&head_ref, repo,
7497 worktree ? got_worktree_get_head_ref_name(worktree)
7498 : GOT_REF_HEAD, 0);
7499 if (error)
7500 goto done;
7501 error = got_ref_resolve(&commit_id, repo, head_ref);
7502 got_ref_close(head_ref);
7503 if (error)
7504 goto done;
7505 error = got_object_id_str(&commit_id_str, commit_id);
7506 free(commit_id);
7507 if (error)
7508 goto done;
7511 if (worktree) {
7512 /* Release work tree lock. */
7513 got_worktree_close(worktree);
7514 worktree = NULL;
7517 error = add_tag(repo, tagger, tag_name,
7518 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7519 signer_id, verbosity);
7521 done:
7522 if (repo) {
7523 const struct got_error *close_err = got_repo_close(repo);
7524 if (error == NULL)
7525 error = close_err;
7527 if (worktree)
7528 got_worktree_close(worktree);
7529 if (pack_fds) {
7530 const struct got_error *pack_err =
7531 got_repo_pack_fds_close(pack_fds);
7532 if (error == NULL)
7533 error = pack_err;
7535 free(cwd);
7536 free(repo_path);
7537 free(gitconfig_path);
7538 free(commit_id_str);
7539 free(tagger);
7540 free(allowed_signers);
7541 free(revoked_signers);
7542 free(signer_id);
7543 return error;
7546 __dead static void
7547 usage_add(void)
7549 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7550 getprogname());
7551 exit(1);
7554 static const struct got_error *
7555 add_progress(void *arg, unsigned char status, const char *path)
7557 while (path[0] == '/')
7558 path++;
7559 printf("%c %s\n", status, path);
7560 return NULL;
7563 static const struct got_error *
7564 cmd_add(int argc, char *argv[])
7566 const struct got_error *error = NULL;
7567 struct got_repository *repo = NULL;
7568 struct got_worktree *worktree = NULL;
7569 char *cwd = NULL;
7570 struct got_pathlist_head paths;
7571 struct got_pathlist_entry *pe;
7572 int ch, can_recurse = 0, no_ignores = 0;
7573 int *pack_fds = NULL;
7575 TAILQ_INIT(&paths);
7577 while ((ch = getopt(argc, argv, "IR")) != -1) {
7578 switch (ch) {
7579 case 'I':
7580 no_ignores = 1;
7581 break;
7582 case 'R':
7583 can_recurse = 1;
7584 break;
7585 default:
7586 usage_add();
7587 /* NOTREACHED */
7591 argc -= optind;
7592 argv += optind;
7594 #ifndef PROFILE
7595 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7596 NULL) == -1)
7597 err(1, "pledge");
7598 #endif
7599 if (argc < 1)
7600 usage_add();
7602 cwd = getcwd(NULL, 0);
7603 if (cwd == NULL) {
7604 error = got_error_from_errno("getcwd");
7605 goto done;
7608 error = got_repo_pack_fds_open(&pack_fds);
7609 if (error != NULL)
7610 goto done;
7612 error = got_worktree_open(&worktree, cwd);
7613 if (error) {
7614 if (error->code == GOT_ERR_NOT_WORKTREE)
7615 error = wrap_not_worktree_error(error, "add", cwd);
7616 goto done;
7619 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7620 NULL, pack_fds);
7621 if (error != NULL)
7622 goto done;
7624 error = apply_unveil(got_repo_get_path(repo), 1,
7625 got_worktree_get_root_path(worktree));
7626 if (error)
7627 goto done;
7629 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7630 if (error)
7631 goto done;
7633 if (!can_recurse) {
7634 char *ondisk_path;
7635 struct stat sb;
7636 TAILQ_FOREACH(pe, &paths, entry) {
7637 if (asprintf(&ondisk_path, "%s/%s",
7638 got_worktree_get_root_path(worktree),
7639 pe->path) == -1) {
7640 error = got_error_from_errno("asprintf");
7641 goto done;
7643 if (lstat(ondisk_path, &sb) == -1) {
7644 if (errno == ENOENT) {
7645 free(ondisk_path);
7646 continue;
7648 error = got_error_from_errno2("lstat",
7649 ondisk_path);
7650 free(ondisk_path);
7651 goto done;
7653 free(ondisk_path);
7654 if (S_ISDIR(sb.st_mode)) {
7655 error = got_error_msg(GOT_ERR_BAD_PATH,
7656 "adding directories requires -R option");
7657 goto done;
7662 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7663 NULL, repo, no_ignores);
7664 done:
7665 if (repo) {
7666 const struct got_error *close_err = got_repo_close(repo);
7667 if (error == NULL)
7668 error = close_err;
7670 if (worktree)
7671 got_worktree_close(worktree);
7672 if (pack_fds) {
7673 const struct got_error *pack_err =
7674 got_repo_pack_fds_close(pack_fds);
7675 if (error == NULL)
7676 error = pack_err;
7678 TAILQ_FOREACH(pe, &paths, entry)
7679 free((char *)pe->path);
7680 got_pathlist_free(&paths);
7681 free(cwd);
7682 return error;
7685 __dead static void
7686 usage_remove(void)
7688 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7689 "path ...\n", getprogname());
7690 exit(1);
7693 static const struct got_error *
7694 print_remove_status(void *arg, unsigned char status,
7695 unsigned char staged_status, const char *path)
7697 while (path[0] == '/')
7698 path++;
7699 if (status == GOT_STATUS_NONEXISTENT)
7700 return NULL;
7701 if (status == staged_status && (status == GOT_STATUS_DELETE))
7702 status = GOT_STATUS_NO_CHANGE;
7703 printf("%c%c %s\n", status, staged_status, path);
7704 return NULL;
7707 static const struct got_error *
7708 cmd_remove(int argc, char *argv[])
7710 const struct got_error *error = NULL;
7711 struct got_worktree *worktree = NULL;
7712 struct got_repository *repo = NULL;
7713 const char *status_codes = NULL;
7714 char *cwd = NULL;
7715 struct got_pathlist_head paths;
7716 struct got_pathlist_entry *pe;
7717 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7718 int ignore_missing_paths = 0;
7719 int *pack_fds = NULL;
7721 TAILQ_INIT(&paths);
7723 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7724 switch (ch) {
7725 case 'f':
7726 delete_local_mods = 1;
7727 ignore_missing_paths = 1;
7728 break;
7729 case 'k':
7730 keep_on_disk = 1;
7731 break;
7732 case 'R':
7733 can_recurse = 1;
7734 break;
7735 case 's':
7736 for (i = 0; i < strlen(optarg); i++) {
7737 switch (optarg[i]) {
7738 case GOT_STATUS_MODIFY:
7739 delete_local_mods = 1;
7740 break;
7741 case GOT_STATUS_MISSING:
7742 ignore_missing_paths = 1;
7743 break;
7744 default:
7745 errx(1, "invalid status code '%c'",
7746 optarg[i]);
7749 status_codes = optarg;
7750 break;
7751 default:
7752 usage_remove();
7753 /* NOTREACHED */
7757 argc -= optind;
7758 argv += optind;
7760 #ifndef PROFILE
7761 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7762 NULL) == -1)
7763 err(1, "pledge");
7764 #endif
7765 if (argc < 1)
7766 usage_remove();
7768 cwd = getcwd(NULL, 0);
7769 if (cwd == NULL) {
7770 error = got_error_from_errno("getcwd");
7771 goto done;
7774 error = got_repo_pack_fds_open(&pack_fds);
7775 if (error != NULL)
7776 goto done;
7778 error = got_worktree_open(&worktree, cwd);
7779 if (error) {
7780 if (error->code == GOT_ERR_NOT_WORKTREE)
7781 error = wrap_not_worktree_error(error, "remove", cwd);
7782 goto done;
7785 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7786 NULL, pack_fds);
7787 if (error)
7788 goto done;
7790 error = apply_unveil(got_repo_get_path(repo), 1,
7791 got_worktree_get_root_path(worktree));
7792 if (error)
7793 goto done;
7795 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7796 if (error)
7797 goto done;
7799 if (!can_recurse) {
7800 char *ondisk_path;
7801 struct stat sb;
7802 TAILQ_FOREACH(pe, &paths, entry) {
7803 if (asprintf(&ondisk_path, "%s/%s",
7804 got_worktree_get_root_path(worktree),
7805 pe->path) == -1) {
7806 error = got_error_from_errno("asprintf");
7807 goto done;
7809 if (lstat(ondisk_path, &sb) == -1) {
7810 if (errno == ENOENT) {
7811 free(ondisk_path);
7812 continue;
7814 error = got_error_from_errno2("lstat",
7815 ondisk_path);
7816 free(ondisk_path);
7817 goto done;
7819 free(ondisk_path);
7820 if (S_ISDIR(sb.st_mode)) {
7821 error = got_error_msg(GOT_ERR_BAD_PATH,
7822 "removing directories requires -R option");
7823 goto done;
7828 error = got_worktree_schedule_delete(worktree, &paths,
7829 delete_local_mods, status_codes, print_remove_status, NULL,
7830 repo, keep_on_disk, ignore_missing_paths);
7831 done:
7832 if (repo) {
7833 const struct got_error *close_err = got_repo_close(repo);
7834 if (error == NULL)
7835 error = close_err;
7837 if (worktree)
7838 got_worktree_close(worktree);
7839 if (pack_fds) {
7840 const struct got_error *pack_err =
7841 got_repo_pack_fds_close(pack_fds);
7842 if (error == NULL)
7843 error = pack_err;
7845 TAILQ_FOREACH(pe, &paths, entry)
7846 free((char *)pe->path);
7847 got_pathlist_free(&paths);
7848 free(cwd);
7849 return error;
7852 __dead static void
7853 usage_patch(void)
7855 fprintf(stderr, "usage: %s patch [-c commit] [-n] [-p strip-count] "
7856 "[-R] [patchfile]\n", getprogname());
7857 exit(1);
7860 static const struct got_error *
7861 patch_from_stdin(int *patchfd)
7863 const struct got_error *err = NULL;
7864 ssize_t r;
7865 char *path, buf[BUFSIZ];
7866 sig_t sighup, sigint, sigquit;
7868 err = got_opentemp_named_fd(&path, patchfd,
7869 GOT_TMPDIR_STR "/got-patch");
7870 if (err)
7871 return err;
7872 unlink(path);
7873 free(path);
7875 sighup = signal(SIGHUP, SIG_DFL);
7876 sigint = signal(SIGINT, SIG_DFL);
7877 sigquit = signal(SIGQUIT, SIG_DFL);
7879 for (;;) {
7880 r = read(0, buf, sizeof(buf));
7881 if (r == -1) {
7882 err = got_error_from_errno("read");
7883 break;
7885 if (r == 0)
7886 break;
7887 if (write(*patchfd, buf, r) == -1) {
7888 err = got_error_from_errno("write");
7889 break;
7893 signal(SIGHUP, sighup);
7894 signal(SIGINT, sigint);
7895 signal(SIGQUIT, sigquit);
7897 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7898 err = got_error_from_errno("lseek");
7900 if (err != NULL) {
7901 close(*patchfd);
7902 *patchfd = -1;
7905 return err;
7908 static const struct got_error *
7909 patch_progress(void *arg, const char *old, const char *new,
7910 unsigned char status, const struct got_error *error, int old_from,
7911 int old_lines, int new_from, int new_lines, int offset,
7912 int ws_mangled, const struct got_error *hunk_err)
7914 const char *path = new == NULL ? old : new;
7916 while (*path == '/')
7917 path++;
7919 if (status != 0)
7920 printf("%c %s\n", status, path);
7922 if (error != NULL)
7923 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7925 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7926 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7927 old_lines, new_from, new_lines);
7928 if (hunk_err != NULL)
7929 printf("%s\n", hunk_err->msg);
7930 else if (offset != 0)
7931 printf("applied with offset %d\n", offset);
7932 else
7933 printf("hunk contains mangled whitespace\n");
7936 return NULL;
7939 static const struct got_error *
7940 cmd_patch(int argc, char *argv[])
7942 const struct got_error *error = NULL, *close_error = NULL;
7943 struct got_worktree *worktree = NULL;
7944 struct got_repository *repo = NULL;
7945 struct got_reflist_head refs;
7946 struct got_object_id *commit_id = NULL;
7947 const char *commit_id_str = NULL;
7948 struct stat sb;
7949 const char *errstr;
7950 char *cwd = NULL;
7951 int ch, nop = 0, strip = -1, reverse = 0;
7952 int patchfd;
7953 int *pack_fds = NULL;
7955 TAILQ_INIT(&refs);
7957 #ifndef PROFILE
7958 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7959 "unveil", NULL) == -1)
7960 err(1, "pledge");
7961 #endif
7963 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7964 switch (ch) {
7965 case 'c':
7966 commit_id_str = optarg;
7967 break;
7968 case 'n':
7969 nop = 1;
7970 break;
7971 case 'p':
7972 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7973 if (errstr != NULL)
7974 errx(1, "pathname strip count is %s: %s",
7975 errstr, optarg);
7976 break;
7977 case 'R':
7978 reverse = 1;
7979 break;
7980 default:
7981 usage_patch();
7982 /* NOTREACHED */
7986 argc -= optind;
7987 argv += optind;
7989 if (argc == 0) {
7990 error = patch_from_stdin(&patchfd);
7991 if (error)
7992 return error;
7993 } else if (argc == 1) {
7994 patchfd = open(argv[0], O_RDONLY);
7995 if (patchfd == -1) {
7996 error = got_error_from_errno2("open", argv[0]);
7997 return error;
7999 if (fstat(patchfd, &sb) == -1) {
8000 error = got_error_from_errno2("fstat", argv[0]);
8001 goto done;
8003 if (!S_ISREG(sb.st_mode)) {
8004 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8005 goto done;
8007 } else
8008 usage_patch();
8010 if ((cwd = getcwd(NULL, 0)) == NULL) {
8011 error = got_error_from_errno("getcwd");
8012 goto done;
8015 error = got_repo_pack_fds_open(&pack_fds);
8016 if (error != NULL)
8017 goto done;
8019 error = got_worktree_open(&worktree, cwd);
8020 if (error != NULL)
8021 goto done;
8023 const char *repo_path = got_worktree_get_repo_path(worktree);
8024 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8025 if (error != NULL)
8026 goto done;
8028 error = apply_unveil(got_repo_get_path(repo), 0,
8029 got_worktree_get_root_path(worktree));
8030 if (error != NULL)
8031 goto done;
8033 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8034 if (error)
8035 goto done;
8037 if (commit_id_str != NULL) {
8038 error = got_repo_match_object_id(&commit_id, NULL,
8039 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8040 if (error)
8041 goto done;
8044 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8045 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8047 done:
8048 got_ref_list_free(&refs);
8049 free(commit_id);
8050 if (repo) {
8051 close_error = got_repo_close(repo);
8052 if (error == NULL)
8053 error = close_error;
8055 if (worktree != NULL) {
8056 close_error = got_worktree_close(worktree);
8057 if (error == NULL)
8058 error = close_error;
8060 if (pack_fds) {
8061 const struct got_error *pack_err =
8062 got_repo_pack_fds_close(pack_fds);
8063 if (error == NULL)
8064 error = pack_err;
8066 free(cwd);
8067 return error;
8070 __dead static void
8071 usage_revert(void)
8073 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
8074 "path ...\n", getprogname());
8075 exit(1);
8078 static const struct got_error *
8079 revert_progress(void *arg, unsigned char status, const char *path)
8081 if (status == GOT_STATUS_UNVERSIONED)
8082 return NULL;
8084 while (path[0] == '/')
8085 path++;
8086 printf("%c %s\n", status, path);
8087 return NULL;
8090 struct choose_patch_arg {
8091 FILE *patch_script_file;
8092 const char *action;
8095 static const struct got_error *
8096 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8097 int nchanges, const char *action)
8099 const struct got_error *err;
8100 char *line = NULL;
8101 size_t linesize = 0;
8102 ssize_t linelen;
8104 switch (status) {
8105 case GOT_STATUS_ADD:
8106 printf("A %s\n%s this addition? [y/n] ", path, action);
8107 break;
8108 case GOT_STATUS_DELETE:
8109 printf("D %s\n%s this deletion? [y/n] ", path, action);
8110 break;
8111 case GOT_STATUS_MODIFY:
8112 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8113 return got_error_from_errno("fseek");
8114 printf(GOT_COMMIT_SEP_STR);
8115 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8116 printf("%s", line);
8117 if (linelen == -1 && ferror(patch_file)) {
8118 err = got_error_from_errno("getline");
8119 free(line);
8120 return err;
8122 free(line);
8123 printf(GOT_COMMIT_SEP_STR);
8124 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8125 path, n, nchanges, action);
8126 break;
8127 default:
8128 return got_error_path(path, GOT_ERR_FILE_STATUS);
8131 return NULL;
8134 static const struct got_error *
8135 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8136 FILE *patch_file, int n, int nchanges)
8138 const struct got_error *err = NULL;
8139 char *line = NULL;
8140 size_t linesize = 0;
8141 ssize_t linelen;
8142 int resp = ' ';
8143 struct choose_patch_arg *a = arg;
8145 *choice = GOT_PATCH_CHOICE_NONE;
8147 if (a->patch_script_file) {
8148 char *nl;
8149 err = show_change(status, path, patch_file, n, nchanges,
8150 a->action);
8151 if (err)
8152 return err;
8153 linelen = getline(&line, &linesize, a->patch_script_file);
8154 if (linelen == -1) {
8155 if (ferror(a->patch_script_file))
8156 return got_error_from_errno("getline");
8157 return NULL;
8159 nl = strchr(line, '\n');
8160 if (nl)
8161 *nl = '\0';
8162 if (strcmp(line, "y") == 0) {
8163 *choice = GOT_PATCH_CHOICE_YES;
8164 printf("y\n");
8165 } else if (strcmp(line, "n") == 0) {
8166 *choice = GOT_PATCH_CHOICE_NO;
8167 printf("n\n");
8168 } else if (strcmp(line, "q") == 0 &&
8169 status == GOT_STATUS_MODIFY) {
8170 *choice = GOT_PATCH_CHOICE_QUIT;
8171 printf("q\n");
8172 } else
8173 printf("invalid response '%s'\n", line);
8174 free(line);
8175 return NULL;
8178 while (resp != 'y' && resp != 'n' && resp != 'q') {
8179 err = show_change(status, path, patch_file, n, nchanges,
8180 a->action);
8181 if (err)
8182 return err;
8183 resp = getchar();
8184 if (resp == '\n')
8185 resp = getchar();
8186 if (status == GOT_STATUS_MODIFY) {
8187 if (resp != 'y' && resp != 'n' && resp != 'q') {
8188 printf("invalid response '%c'\n", resp);
8189 resp = ' ';
8191 } else if (resp != 'y' && resp != 'n') {
8192 printf("invalid response '%c'\n", resp);
8193 resp = ' ';
8197 if (resp == 'y')
8198 *choice = GOT_PATCH_CHOICE_YES;
8199 else if (resp == 'n')
8200 *choice = GOT_PATCH_CHOICE_NO;
8201 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8202 *choice = GOT_PATCH_CHOICE_QUIT;
8204 return NULL;
8207 static const struct got_error *
8208 cmd_revert(int argc, char *argv[])
8210 const struct got_error *error = NULL;
8211 struct got_worktree *worktree = NULL;
8212 struct got_repository *repo = NULL;
8213 char *cwd = NULL, *path = NULL;
8214 struct got_pathlist_head paths;
8215 struct got_pathlist_entry *pe;
8216 int ch, can_recurse = 0, pflag = 0;
8217 FILE *patch_script_file = NULL;
8218 const char *patch_script_path = NULL;
8219 struct choose_patch_arg cpa;
8220 int *pack_fds = NULL;
8222 TAILQ_INIT(&paths);
8224 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8225 switch (ch) {
8226 case 'p':
8227 pflag = 1;
8228 break;
8229 case 'F':
8230 patch_script_path = optarg;
8231 break;
8232 case 'R':
8233 can_recurse = 1;
8234 break;
8235 default:
8236 usage_revert();
8237 /* NOTREACHED */
8241 argc -= optind;
8242 argv += optind;
8244 #ifndef PROFILE
8245 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8246 "unveil", NULL) == -1)
8247 err(1, "pledge");
8248 #endif
8249 if (argc < 1)
8250 usage_revert();
8251 if (patch_script_path && !pflag)
8252 errx(1, "-F option can only be used together with -p option");
8254 cwd = getcwd(NULL, 0);
8255 if (cwd == NULL) {
8256 error = got_error_from_errno("getcwd");
8257 goto done;
8260 error = got_repo_pack_fds_open(&pack_fds);
8261 if (error != NULL)
8262 goto done;
8264 error = got_worktree_open(&worktree, cwd);
8265 if (error) {
8266 if (error->code == GOT_ERR_NOT_WORKTREE)
8267 error = wrap_not_worktree_error(error, "revert", cwd);
8268 goto done;
8271 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8272 NULL, pack_fds);
8273 if (error != NULL)
8274 goto done;
8276 if (patch_script_path) {
8277 patch_script_file = fopen(patch_script_path, "re");
8278 if (patch_script_file == NULL) {
8279 error = got_error_from_errno2("fopen",
8280 patch_script_path);
8281 goto done;
8284 error = apply_unveil(got_repo_get_path(repo), 1,
8285 got_worktree_get_root_path(worktree));
8286 if (error)
8287 goto done;
8289 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8290 if (error)
8291 goto done;
8293 if (!can_recurse) {
8294 char *ondisk_path;
8295 struct stat sb;
8296 TAILQ_FOREACH(pe, &paths, entry) {
8297 if (asprintf(&ondisk_path, "%s/%s",
8298 got_worktree_get_root_path(worktree),
8299 pe->path) == -1) {
8300 error = got_error_from_errno("asprintf");
8301 goto done;
8303 if (lstat(ondisk_path, &sb) == -1) {
8304 if (errno == ENOENT) {
8305 free(ondisk_path);
8306 continue;
8308 error = got_error_from_errno2("lstat",
8309 ondisk_path);
8310 free(ondisk_path);
8311 goto done;
8313 free(ondisk_path);
8314 if (S_ISDIR(sb.st_mode)) {
8315 error = got_error_msg(GOT_ERR_BAD_PATH,
8316 "reverting directories requires -R option");
8317 goto done;
8322 cpa.patch_script_file = patch_script_file;
8323 cpa.action = "revert";
8324 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8325 pflag ? choose_patch : NULL, &cpa, repo);
8326 done:
8327 if (patch_script_file && fclose(patch_script_file) == EOF &&
8328 error == NULL)
8329 error = got_error_from_errno2("fclose", patch_script_path);
8330 if (repo) {
8331 const struct got_error *close_err = got_repo_close(repo);
8332 if (error == NULL)
8333 error = close_err;
8335 if (worktree)
8336 got_worktree_close(worktree);
8337 if (pack_fds) {
8338 const struct got_error *pack_err =
8339 got_repo_pack_fds_close(pack_fds);
8340 if (error == NULL)
8341 error = pack_err;
8343 free(path);
8344 free(cwd);
8345 return error;
8348 __dead static void
8349 usage_commit(void)
8351 fprintf(stderr, "usage: %s commit [-A author] [-F path] [-m msg] "
8352 "[-N] [-S] [path ...]\n", getprogname());
8353 exit(1);
8356 struct collect_commit_logmsg_arg {
8357 const char *cmdline_log;
8358 const char *prepared_log;
8359 int non_interactive;
8360 const char *editor;
8361 const char *worktree_path;
8362 const char *branch_name;
8363 const char *repo_path;
8364 char *logmsg_path;
8368 static const struct got_error *
8369 read_prepared_logmsg(char **logmsg, const char *path)
8371 const struct got_error *err = NULL;
8372 FILE *f = NULL;
8373 struct stat sb;
8374 size_t r;
8376 *logmsg = NULL;
8377 memset(&sb, 0, sizeof(sb));
8379 f = fopen(path, "re");
8380 if (f == NULL)
8381 return got_error_from_errno2("fopen", path);
8383 if (fstat(fileno(f), &sb) == -1) {
8384 err = got_error_from_errno2("fstat", path);
8385 goto done;
8387 if (sb.st_size == 0) {
8388 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8389 goto done;
8392 *logmsg = malloc(sb.st_size + 1);
8393 if (*logmsg == NULL) {
8394 err = got_error_from_errno("malloc");
8395 goto done;
8398 r = fread(*logmsg, 1, sb.st_size, f);
8399 if (r != sb.st_size) {
8400 if (ferror(f))
8401 err = got_error_from_errno2("fread", path);
8402 else
8403 err = got_error(GOT_ERR_IO);
8404 goto done;
8406 (*logmsg)[sb.st_size] = '\0';
8407 done:
8408 if (fclose(f) == EOF && err == NULL)
8409 err = got_error_from_errno2("fclose", path);
8410 if (err) {
8411 free(*logmsg);
8412 *logmsg = NULL;
8414 return err;
8418 static const struct got_error *
8419 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8420 void *arg)
8422 char *initial_content = NULL;
8423 struct got_pathlist_entry *pe;
8424 const struct got_error *err = NULL;
8425 char *template = NULL;
8426 struct collect_commit_logmsg_arg *a = arg;
8427 int initial_content_len;
8428 int fd = -1;
8429 size_t len;
8431 /* if a message was specified on the command line, just use it */
8432 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8433 len = strlen(a->cmdline_log) + 1;
8434 *logmsg = malloc(len + 1);
8435 if (*logmsg == NULL)
8436 return got_error_from_errno("malloc");
8437 strlcpy(*logmsg, a->cmdline_log, len);
8438 return NULL;
8439 } else if (a->prepared_log != NULL && a->non_interactive)
8440 return read_prepared_logmsg(logmsg, a->prepared_log);
8442 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8443 return got_error_from_errno("asprintf");
8445 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8446 if (err)
8447 goto done;
8449 if (a->prepared_log) {
8450 char *msg;
8451 err = read_prepared_logmsg(&msg, a->prepared_log);
8452 if (err)
8453 goto done;
8454 if (write(fd, msg, strlen(msg)) == -1) {
8455 err = got_error_from_errno2("write", a->logmsg_path);
8456 free(msg);
8457 goto done;
8459 free(msg);
8462 initial_content_len = asprintf(&initial_content,
8463 "\n# changes to be committed on branch %s:\n",
8464 a->branch_name);
8465 if (initial_content_len == -1) {
8466 err = got_error_from_errno("asprintf");
8467 goto done;
8470 if (write(fd, initial_content, initial_content_len) == -1) {
8471 err = got_error_from_errno2("write", a->logmsg_path);
8472 goto done;
8475 TAILQ_FOREACH(pe, commitable_paths, entry) {
8476 struct got_commitable *ct = pe->data;
8477 dprintf(fd, "# %c %s\n",
8478 got_commitable_get_status(ct),
8479 got_commitable_get_path(ct));
8482 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8483 initial_content_len, a->prepared_log ? 0 : 1);
8484 done:
8485 free(initial_content);
8486 free(template);
8488 if (fd != -1 && close(fd) == -1 && err == NULL)
8489 err = got_error_from_errno2("close", a->logmsg_path);
8491 /* Editor is done; we can now apply unveil(2) */
8492 if (err == NULL)
8493 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8494 if (err) {
8495 free(*logmsg);
8496 *logmsg = NULL;
8498 return err;
8501 static const struct got_error *
8502 cmd_commit(int argc, char *argv[])
8504 const struct got_error *error = NULL;
8505 struct got_worktree *worktree = NULL;
8506 struct got_repository *repo = NULL;
8507 char *cwd = NULL, *id_str = NULL;
8508 struct got_object_id *id = NULL;
8509 const char *logmsg = NULL;
8510 char *prepared_logmsg = NULL;
8511 struct collect_commit_logmsg_arg cl_arg;
8512 const char *author = NULL;
8513 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8514 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8515 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8516 struct got_pathlist_head paths;
8517 int *pack_fds = NULL;
8519 TAILQ_INIT(&paths);
8520 cl_arg.logmsg_path = NULL;
8522 while ((ch = getopt(argc, argv, "A:F:m:NS")) != -1) {
8523 switch (ch) {
8524 case 'A':
8525 author = optarg;
8526 error = valid_author(author);
8527 if (error)
8528 return error;
8529 break;
8530 case 'F':
8531 if (logmsg != NULL)
8532 option_conflict('F', 'm');
8533 prepared_logmsg = realpath(optarg, NULL);
8534 if (prepared_logmsg == NULL)
8535 return got_error_from_errno2("realpath",
8536 optarg);
8537 break;
8538 case 'm':
8539 if (prepared_logmsg)
8540 option_conflict('m', 'F');
8541 logmsg = optarg;
8542 break;
8543 case 'N':
8544 non_interactive = 1;
8545 break;
8546 case 'S':
8547 allow_bad_symlinks = 1;
8548 break;
8549 default:
8550 usage_commit();
8551 /* NOTREACHED */
8555 argc -= optind;
8556 argv += optind;
8558 #ifndef PROFILE
8559 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8560 "unveil", NULL) == -1)
8561 err(1, "pledge");
8562 #endif
8563 cwd = getcwd(NULL, 0);
8564 if (cwd == NULL) {
8565 error = got_error_from_errno("getcwd");
8566 goto done;
8569 error = got_repo_pack_fds_open(&pack_fds);
8570 if (error != NULL)
8571 goto done;
8573 error = got_worktree_open(&worktree, cwd);
8574 if (error) {
8575 if (error->code == GOT_ERR_NOT_WORKTREE)
8576 error = wrap_not_worktree_error(error, "commit", cwd);
8577 goto done;
8580 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8581 if (error)
8582 goto done;
8583 if (rebase_in_progress) {
8584 error = got_error(GOT_ERR_REBASING);
8585 goto done;
8588 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8589 worktree);
8590 if (error)
8591 goto done;
8593 error = get_gitconfig_path(&gitconfig_path);
8594 if (error)
8595 goto done;
8596 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8597 gitconfig_path, pack_fds);
8598 if (error != NULL)
8599 goto done;
8601 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8602 if (error)
8603 goto done;
8604 if (merge_in_progress) {
8605 error = got_error(GOT_ERR_MERGE_BUSY);
8606 goto done;
8609 error = get_author(&committer, repo, worktree);
8610 if (error)
8611 goto done;
8613 if (author != NULL && !strcmp(committer, author)) {
8614 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8615 goto done;
8618 if (author == NULL)
8619 author = committer;
8622 * unveil(2) traverses exec(2); if an editor is used we have
8623 * to apply unveil after the log message has been written.
8625 if (logmsg == NULL || strlen(logmsg) == 0)
8626 error = get_editor(&editor);
8627 else
8628 error = apply_unveil(got_repo_get_path(repo), 0,
8629 got_worktree_get_root_path(worktree));
8630 if (error)
8631 goto done;
8633 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8634 if (error)
8635 goto done;
8637 cl_arg.editor = editor;
8638 cl_arg.cmdline_log = logmsg;
8639 cl_arg.prepared_log = prepared_logmsg;
8640 cl_arg.non_interactive = non_interactive;
8641 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8642 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8643 if (!histedit_in_progress) {
8644 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8645 error = got_error(GOT_ERR_COMMIT_BRANCH);
8646 goto done;
8648 cl_arg.branch_name += 11;
8650 cl_arg.repo_path = got_repo_get_path(repo);
8651 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8652 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8653 print_status, NULL, repo);
8654 if (error) {
8655 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8656 cl_arg.logmsg_path != NULL)
8657 preserve_logmsg = 1;
8658 goto done;
8661 error = got_object_id_str(&id_str, id);
8662 if (error)
8663 goto done;
8664 printf("Created commit %s\n", id_str);
8665 done:
8666 if (preserve_logmsg) {
8667 fprintf(stderr, "%s: log message preserved in %s\n",
8668 getprogname(), cl_arg.logmsg_path);
8669 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8670 error == NULL)
8671 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8672 free(cl_arg.logmsg_path);
8673 if (repo) {
8674 const struct got_error *close_err = got_repo_close(repo);
8675 if (error == NULL)
8676 error = close_err;
8678 if (worktree)
8679 got_worktree_close(worktree);
8680 if (pack_fds) {
8681 const struct got_error *pack_err =
8682 got_repo_pack_fds_close(pack_fds);
8683 if (error == NULL)
8684 error = pack_err;
8686 free(cwd);
8687 free(id_str);
8688 free(gitconfig_path);
8689 free(editor);
8690 free(committer);
8691 free(prepared_logmsg);
8692 return error;
8695 __dead static void
8696 usage_send(void)
8698 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8699 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8700 "[remote-repository]\n", getprogname());
8701 exit(1);
8704 static void
8705 print_load_info(int print_colored, int print_found, int print_trees,
8706 int ncolored, int nfound, int ntrees)
8708 if (print_colored) {
8709 printf("%d commit%s colored", ncolored,
8710 ncolored == 1 ? "" : "s");
8712 if (print_found) {
8713 printf("%s%d object%s found",
8714 ncolored > 0 ? "; " : "",
8715 nfound, nfound == 1 ? "" : "s");
8717 if (print_trees) {
8718 printf("; %d tree%s scanned", ntrees,
8719 ntrees == 1 ? "" : "s");
8723 struct got_send_progress_arg {
8724 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8725 int verbosity;
8726 int last_ncolored;
8727 int last_nfound;
8728 int last_ntrees;
8729 int loading_done;
8730 int last_ncommits;
8731 int last_nobj_total;
8732 int last_p_deltify;
8733 int last_p_written;
8734 int last_p_sent;
8735 int printed_something;
8736 int sent_something;
8737 struct got_pathlist_head *delete_branches;
8740 static const struct got_error *
8741 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8742 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8743 int nobj_written, off_t bytes_sent, const char *refname, int success)
8745 struct got_send_progress_arg *a = arg;
8746 char scaled_packsize[FMT_SCALED_STRSIZE];
8747 char scaled_sent[FMT_SCALED_STRSIZE];
8748 int p_deltify = 0, p_written = 0, p_sent = 0;
8749 int print_colored = 0, print_found = 0, print_trees = 0;
8750 int print_searching = 0, print_total = 0;
8751 int print_deltify = 0, print_written = 0, print_sent = 0;
8753 if (a->verbosity < 0)
8754 return NULL;
8756 if (refname) {
8757 const char *status = success ? "accepted" : "rejected";
8759 if (success) {
8760 struct got_pathlist_entry *pe;
8761 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8762 const char *branchname = pe->path;
8763 if (got_path_cmp(branchname, refname,
8764 strlen(branchname), strlen(refname)) == 0) {
8765 status = "deleted";
8766 a->sent_something = 1;
8767 break;
8772 if (a->printed_something)
8773 putchar('\n');
8774 printf("Server has %s %s", status, refname);
8775 a->printed_something = 1;
8776 return NULL;
8779 if (a->last_ncolored != ncolored) {
8780 print_colored = 1;
8781 a->last_ncolored = ncolored;
8784 if (a->last_nfound != nfound) {
8785 print_colored = 1;
8786 print_found = 1;
8787 a->last_nfound = nfound;
8790 if (a->last_ntrees != ntrees) {
8791 print_colored = 1;
8792 print_found = 1;
8793 print_trees = 1;
8794 a->last_ntrees = ntrees;
8797 if ((print_colored || print_found || print_trees) &&
8798 !a->loading_done) {
8799 printf("\r");
8800 print_load_info(print_colored, print_found, print_trees,
8801 ncolored, nfound, ntrees);
8802 a->printed_something = 1;
8803 fflush(stdout);
8804 return NULL;
8805 } else if (!a->loading_done) {
8806 printf("\r");
8807 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8808 printf("\n");
8809 a->loading_done = 1;
8812 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8813 return got_error_from_errno("fmt_scaled");
8814 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8815 return got_error_from_errno("fmt_scaled");
8817 if (a->last_ncommits != ncommits) {
8818 print_searching = 1;
8819 a->last_ncommits = ncommits;
8822 if (a->last_nobj_total != nobj_total) {
8823 print_searching = 1;
8824 print_total = 1;
8825 a->last_nobj_total = nobj_total;
8828 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8829 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8830 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8831 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8832 return got_error(GOT_ERR_NO_SPACE);
8835 if (nobj_deltify > 0 || nobj_written > 0) {
8836 if (nobj_deltify > 0) {
8837 p_deltify = (nobj_deltify * 100) / nobj_total;
8838 if (p_deltify != a->last_p_deltify) {
8839 a->last_p_deltify = p_deltify;
8840 print_searching = 1;
8841 print_total = 1;
8842 print_deltify = 1;
8845 if (nobj_written > 0) {
8846 p_written = (nobj_written * 100) / nobj_total;
8847 if (p_written != a->last_p_written) {
8848 a->last_p_written = p_written;
8849 print_searching = 1;
8850 print_total = 1;
8851 print_deltify = 1;
8852 print_written = 1;
8857 if (bytes_sent > 0) {
8858 p_sent = (bytes_sent * 100) / packfile_size;
8859 if (p_sent != a->last_p_sent) {
8860 a->last_p_sent = p_sent;
8861 print_searching = 1;
8862 print_total = 1;
8863 print_deltify = 1;
8864 print_written = 1;
8865 print_sent = 1;
8867 a->sent_something = 1;
8870 if (print_searching || print_total || print_deltify || print_written ||
8871 print_sent)
8872 printf("\r");
8873 if (print_searching)
8874 printf("packing %d reference%s", ncommits,
8875 ncommits == 1 ? "" : "s");
8876 if (print_total)
8877 printf("; %d object%s", nobj_total,
8878 nobj_total == 1 ? "" : "s");
8879 if (print_deltify)
8880 printf("; deltify: %d%%", p_deltify);
8881 if (print_sent)
8882 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8883 scaled_packsize, p_sent);
8884 else if (print_written)
8885 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8886 scaled_packsize, p_written);
8887 if (print_searching || print_total || print_deltify ||
8888 print_written || print_sent) {
8889 a->printed_something = 1;
8890 fflush(stdout);
8892 return NULL;
8895 static const struct got_error *
8896 cmd_send(int argc, char *argv[])
8898 const struct got_error *error = NULL;
8899 char *cwd = NULL, *repo_path = NULL;
8900 const char *remote_name;
8901 char *proto = NULL, *host = NULL, *port = NULL;
8902 char *repo_name = NULL, *server_path = NULL;
8903 const struct got_remote_repo *remotes, *remote = NULL;
8904 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8905 struct got_repository *repo = NULL;
8906 struct got_worktree *worktree = NULL;
8907 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8908 struct got_pathlist_head branches;
8909 struct got_pathlist_head tags;
8910 struct got_reflist_head all_branches;
8911 struct got_reflist_head all_tags;
8912 struct got_pathlist_head delete_args;
8913 struct got_pathlist_head delete_branches;
8914 struct got_reflist_entry *re;
8915 struct got_pathlist_entry *pe;
8916 int i, ch, sendfd = -1, sendstatus;
8917 pid_t sendpid = -1;
8918 struct got_send_progress_arg spa;
8919 int verbosity = 0, overwrite_refs = 0;
8920 int send_all_branches = 0, send_all_tags = 0;
8921 struct got_reference *ref = NULL;
8922 int *pack_fds = NULL;
8924 TAILQ_INIT(&branches);
8925 TAILQ_INIT(&tags);
8926 TAILQ_INIT(&all_branches);
8927 TAILQ_INIT(&all_tags);
8928 TAILQ_INIT(&delete_args);
8929 TAILQ_INIT(&delete_branches);
8931 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8932 switch (ch) {
8933 case 'a':
8934 send_all_branches = 1;
8935 break;
8936 case 'b':
8937 error = got_pathlist_append(&branches, optarg, NULL);
8938 if (error)
8939 return error;
8940 nbranches++;
8941 break;
8942 case 'd':
8943 error = got_pathlist_append(&delete_args, optarg, NULL);
8944 if (error)
8945 return error;
8946 break;
8947 case 'f':
8948 overwrite_refs = 1;
8949 break;
8950 case 'r':
8951 repo_path = realpath(optarg, NULL);
8952 if (repo_path == NULL)
8953 return got_error_from_errno2("realpath",
8954 optarg);
8955 got_path_strip_trailing_slashes(repo_path);
8956 break;
8957 case 't':
8958 error = got_pathlist_append(&tags, optarg, NULL);
8959 if (error)
8960 return error;
8961 ntags++;
8962 break;
8963 case 'T':
8964 send_all_tags = 1;
8965 break;
8966 case 'v':
8967 if (verbosity < 0)
8968 verbosity = 0;
8969 else if (verbosity < 3)
8970 verbosity++;
8971 break;
8972 case 'q':
8973 verbosity = -1;
8974 break;
8975 default:
8976 usage_send();
8977 /* NOTREACHED */
8980 argc -= optind;
8981 argv += optind;
8983 if (send_all_branches && !TAILQ_EMPTY(&branches))
8984 option_conflict('a', 'b');
8985 if (send_all_tags && !TAILQ_EMPTY(&tags))
8986 option_conflict('T', 't');
8989 if (argc == 0)
8990 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8991 else if (argc == 1)
8992 remote_name = argv[0];
8993 else
8994 usage_send();
8996 cwd = getcwd(NULL, 0);
8997 if (cwd == NULL) {
8998 error = got_error_from_errno("getcwd");
8999 goto done;
9002 error = got_repo_pack_fds_open(&pack_fds);
9003 if (error != NULL)
9004 goto done;
9006 if (repo_path == NULL) {
9007 error = got_worktree_open(&worktree, cwd);
9008 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9009 goto done;
9010 else
9011 error = NULL;
9012 if (worktree) {
9013 repo_path =
9014 strdup(got_worktree_get_repo_path(worktree));
9015 if (repo_path == NULL)
9016 error = got_error_from_errno("strdup");
9017 if (error)
9018 goto done;
9019 } else {
9020 repo_path = strdup(cwd);
9021 if (repo_path == NULL) {
9022 error = got_error_from_errno("strdup");
9023 goto done;
9028 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9029 if (error)
9030 goto done;
9032 if (worktree) {
9033 worktree_conf = got_worktree_get_gotconfig(worktree);
9034 if (worktree_conf) {
9035 got_gotconfig_get_remotes(&nremotes, &remotes,
9036 worktree_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 repo_conf = got_repo_get_gotconfig(repo);
9047 if (repo_conf) {
9048 got_gotconfig_get_remotes(&nremotes, &remotes,
9049 repo_conf);
9050 for (i = 0; i < nremotes; i++) {
9051 if (strcmp(remotes[i].name, remote_name) == 0) {
9052 remote = &remotes[i];
9053 break;
9058 if (remote == NULL) {
9059 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9060 for (i = 0; i < nremotes; i++) {
9061 if (strcmp(remotes[i].name, remote_name) == 0) {
9062 remote = &remotes[i];
9063 break;
9067 if (remote == NULL) {
9068 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9069 goto done;
9072 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9073 &repo_name, remote->send_url);
9074 if (error)
9075 goto done;
9077 if (strcmp(proto, "git") == 0) {
9078 #ifndef PROFILE
9079 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9080 "sendfd dns inet unveil", NULL) == -1)
9081 err(1, "pledge");
9082 #endif
9083 } else if (strcmp(proto, "git+ssh") == 0 ||
9084 strcmp(proto, "ssh") == 0) {
9085 #ifndef PROFILE
9086 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9087 "sendfd unveil", NULL) == -1)
9088 err(1, "pledge");
9089 #endif
9090 } else if (strcmp(proto, "http") == 0 ||
9091 strcmp(proto, "git+http") == 0) {
9092 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9093 goto done;
9094 } else {
9095 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9096 goto done;
9099 error = got_dial_apply_unveil(proto);
9100 if (error)
9101 goto done;
9103 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9104 if (error)
9105 goto done;
9107 if (send_all_branches) {
9108 error = got_ref_list(&all_branches, repo, "refs/heads",
9109 got_ref_cmp_by_name, NULL);
9110 if (error)
9111 goto done;
9112 TAILQ_FOREACH(re, &all_branches, entry) {
9113 const char *branchname = got_ref_get_name(re->ref);
9114 error = got_pathlist_append(&branches,
9115 branchname, NULL);
9116 if (error)
9117 goto done;
9118 nbranches++;
9120 } else if (nbranches == 0) {
9121 for (i = 0; i < remote->nsend_branches; i++) {
9122 got_pathlist_append(&branches,
9123 remote->send_branches[i], NULL);
9127 if (send_all_tags) {
9128 error = got_ref_list(&all_tags, repo, "refs/tags",
9129 got_ref_cmp_by_name, NULL);
9130 if (error)
9131 goto done;
9132 TAILQ_FOREACH(re, &all_tags, entry) {
9133 const char *tagname = got_ref_get_name(re->ref);
9134 error = got_pathlist_append(&tags,
9135 tagname, NULL);
9136 if (error)
9137 goto done;
9138 ntags++;
9143 * To prevent accidents only branches in refs/heads/ can be deleted
9144 * with 'got send -d'.
9145 * Deleting anything else requires local repository access or Git.
9147 TAILQ_FOREACH(pe, &delete_args, entry) {
9148 const char *branchname = pe->path;
9149 char *s;
9150 struct got_pathlist_entry *new;
9151 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9152 s = strdup(branchname);
9153 if (s == NULL) {
9154 error = got_error_from_errno("strdup");
9155 goto done;
9157 } else {
9158 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9159 error = got_error_from_errno("asprintf");
9160 goto done;
9163 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9164 if (error || new == NULL /* duplicate */)
9165 free(s);
9166 if (error)
9167 goto done;
9168 ndelete_branches++;
9171 if (nbranches == 0 && ndelete_branches == 0) {
9172 struct got_reference *head_ref;
9173 if (worktree)
9174 error = got_ref_open(&head_ref, repo,
9175 got_worktree_get_head_ref_name(worktree), 0);
9176 else
9177 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9178 if (error)
9179 goto done;
9180 if (got_ref_is_symbolic(head_ref)) {
9181 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9182 got_ref_close(head_ref);
9183 if (error)
9184 goto done;
9185 } else
9186 ref = head_ref;
9187 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9188 NULL);
9189 if (error)
9190 goto done;
9191 nbranches++;
9194 if (verbosity >= 0)
9195 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9196 port ? ":" : "", port ? port : "");
9198 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9199 server_path, verbosity);
9200 if (error)
9201 goto done;
9203 memset(&spa, 0, sizeof(spa));
9204 spa.last_scaled_packsize[0] = '\0';
9205 spa.last_p_deltify = -1;
9206 spa.last_p_written = -1;
9207 spa.verbosity = verbosity;
9208 spa.delete_branches = &delete_branches;
9209 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9210 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9211 check_cancelled, NULL);
9212 if (spa.printed_something)
9213 putchar('\n');
9214 if (error)
9215 goto done;
9216 if (!spa.sent_something && verbosity >= 0)
9217 printf("Already up-to-date\n");
9218 done:
9219 if (sendpid > 0) {
9220 if (kill(sendpid, SIGTERM) == -1)
9221 error = got_error_from_errno("kill");
9222 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9223 error = got_error_from_errno("waitpid");
9225 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9226 error = got_error_from_errno("close");
9227 if (repo) {
9228 const struct got_error *close_err = got_repo_close(repo);
9229 if (error == NULL)
9230 error = close_err;
9232 if (worktree)
9233 got_worktree_close(worktree);
9234 if (pack_fds) {
9235 const struct got_error *pack_err =
9236 got_repo_pack_fds_close(pack_fds);
9237 if (error == NULL)
9238 error = pack_err;
9240 if (ref)
9241 got_ref_close(ref);
9242 got_pathlist_free(&branches);
9243 got_pathlist_free(&tags);
9244 got_ref_list_free(&all_branches);
9245 got_ref_list_free(&all_tags);
9246 got_pathlist_free(&delete_args);
9247 TAILQ_FOREACH(pe, &delete_branches, entry)
9248 free((char *)pe->path);
9249 got_pathlist_free(&delete_branches);
9250 free(cwd);
9251 free(repo_path);
9252 free(proto);
9253 free(host);
9254 free(port);
9255 free(server_path);
9256 free(repo_name);
9257 return error;
9260 __dead static void
9261 usage_cherrypick(void)
9263 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9264 exit(1);
9267 static const struct got_error *
9268 cmd_cherrypick(int argc, char *argv[])
9270 const struct got_error *error = NULL;
9271 struct got_worktree *worktree = NULL;
9272 struct got_repository *repo = NULL;
9273 char *cwd = NULL, *commit_id_str = NULL;
9274 struct got_object_id *commit_id = NULL;
9275 struct got_commit_object *commit = NULL;
9276 struct got_object_qid *pid;
9277 int ch;
9278 struct got_update_progress_arg upa;
9279 int *pack_fds = NULL;
9281 while ((ch = getopt(argc, argv, "")) != -1) {
9282 switch (ch) {
9283 default:
9284 usage_cherrypick();
9285 /* NOTREACHED */
9289 argc -= optind;
9290 argv += optind;
9292 #ifndef PROFILE
9293 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9294 "unveil", NULL) == -1)
9295 err(1, "pledge");
9296 #endif
9297 if (argc != 1)
9298 usage_cherrypick();
9300 cwd = getcwd(NULL, 0);
9301 if (cwd == NULL) {
9302 error = got_error_from_errno("getcwd");
9303 goto done;
9306 error = got_repo_pack_fds_open(&pack_fds);
9307 if (error != NULL)
9308 goto done;
9310 error = got_worktree_open(&worktree, cwd);
9311 if (error) {
9312 if (error->code == GOT_ERR_NOT_WORKTREE)
9313 error = wrap_not_worktree_error(error, "cherrypick",
9314 cwd);
9315 goto done;
9318 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9319 NULL, pack_fds);
9320 if (error != NULL)
9321 goto done;
9323 error = apply_unveil(got_repo_get_path(repo), 0,
9324 got_worktree_get_root_path(worktree));
9325 if (error)
9326 goto done;
9328 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9329 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9330 if (error)
9331 goto done;
9332 error = got_object_id_str(&commit_id_str, commit_id);
9333 if (error)
9334 goto done;
9336 error = got_object_open_as_commit(&commit, repo, commit_id);
9337 if (error)
9338 goto done;
9339 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9340 memset(&upa, 0, sizeof(upa));
9341 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9342 commit_id, repo, update_progress, &upa, check_cancelled,
9343 NULL);
9344 if (error != NULL)
9345 goto done;
9347 if (upa.did_something)
9348 printf("Merged commit %s\n", commit_id_str);
9349 print_merge_progress_stats(&upa);
9350 done:
9351 if (commit)
9352 got_object_commit_close(commit);
9353 free(commit_id_str);
9354 if (worktree)
9355 got_worktree_close(worktree);
9356 if (repo) {
9357 const struct got_error *close_err = got_repo_close(repo);
9358 if (error == NULL)
9359 error = close_err;
9361 if (pack_fds) {
9362 const struct got_error *pack_err =
9363 got_repo_pack_fds_close(pack_fds);
9364 if (error == NULL)
9365 error = pack_err;
9368 return error;
9371 __dead static void
9372 usage_backout(void)
9374 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9375 exit(1);
9378 static const struct got_error *
9379 cmd_backout(int argc, char *argv[])
9381 const struct got_error *error = NULL;
9382 struct got_worktree *worktree = NULL;
9383 struct got_repository *repo = NULL;
9384 char *cwd = NULL, *commit_id_str = NULL;
9385 struct got_object_id *commit_id = NULL;
9386 struct got_commit_object *commit = NULL;
9387 struct got_object_qid *pid;
9388 int ch;
9389 struct got_update_progress_arg upa;
9390 int *pack_fds = NULL;
9392 while ((ch = getopt(argc, argv, "")) != -1) {
9393 switch (ch) {
9394 default:
9395 usage_backout();
9396 /* NOTREACHED */
9400 argc -= optind;
9401 argv += optind;
9403 #ifndef PROFILE
9404 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9405 "unveil", NULL) == -1)
9406 err(1, "pledge");
9407 #endif
9408 if (argc != 1)
9409 usage_backout();
9411 cwd = getcwd(NULL, 0);
9412 if (cwd == NULL) {
9413 error = got_error_from_errno("getcwd");
9414 goto done;
9417 error = got_repo_pack_fds_open(&pack_fds);
9418 if (error != NULL)
9419 goto done;
9421 error = got_worktree_open(&worktree, cwd);
9422 if (error) {
9423 if (error->code == GOT_ERR_NOT_WORKTREE)
9424 error = wrap_not_worktree_error(error, "backout", cwd);
9425 goto done;
9428 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9429 NULL, pack_fds);
9430 if (error != NULL)
9431 goto done;
9433 error = apply_unveil(got_repo_get_path(repo), 0,
9434 got_worktree_get_root_path(worktree));
9435 if (error)
9436 goto done;
9438 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9439 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9440 if (error)
9441 goto done;
9442 error = got_object_id_str(&commit_id_str, commit_id);
9443 if (error)
9444 goto done;
9446 error = got_object_open_as_commit(&commit, repo, commit_id);
9447 if (error)
9448 goto done;
9449 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9450 if (pid == NULL) {
9451 error = got_error(GOT_ERR_ROOT_COMMIT);
9452 goto done;
9455 memset(&upa, 0, sizeof(upa));
9456 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9457 repo, update_progress, &upa, check_cancelled, NULL);
9458 if (error != NULL)
9459 goto done;
9461 if (upa.did_something)
9462 printf("Backed out commit %s\n", commit_id_str);
9463 print_merge_progress_stats(&upa);
9464 done:
9465 if (commit)
9466 got_object_commit_close(commit);
9467 free(commit_id_str);
9468 if (worktree)
9469 got_worktree_close(worktree);
9470 if (repo) {
9471 const struct got_error *close_err = got_repo_close(repo);
9472 if (error == NULL)
9473 error = close_err;
9475 if (pack_fds) {
9476 const struct got_error *pack_err =
9477 got_repo_pack_fds_close(pack_fds);
9478 if (error == NULL)
9479 error = pack_err;
9481 return error;
9484 __dead static void
9485 usage_rebase(void)
9487 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9488 getprogname());
9489 exit(1);
9492 static void
9493 trim_logmsg(char *logmsg, int limit)
9495 char *nl;
9496 size_t len;
9498 len = strlen(logmsg);
9499 if (len > limit)
9500 len = limit;
9501 logmsg[len] = '\0';
9502 nl = strchr(logmsg, '\n');
9503 if (nl)
9504 *nl = '\0';
9507 static const struct got_error *
9508 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9510 const struct got_error *err;
9511 char *logmsg0 = NULL;
9512 const char *s;
9514 err = got_object_commit_get_logmsg(&logmsg0, commit);
9515 if (err)
9516 return err;
9518 s = logmsg0;
9519 while (isspace((unsigned char)s[0]))
9520 s++;
9522 *logmsg = strdup(s);
9523 if (*logmsg == NULL) {
9524 err = got_error_from_errno("strdup");
9525 goto done;
9528 trim_logmsg(*logmsg, limit);
9529 done:
9530 free(logmsg0);
9531 return err;
9534 static const struct got_error *
9535 show_rebase_merge_conflict(struct got_object_id *id,
9536 struct got_repository *repo)
9538 const struct got_error *err;
9539 struct got_commit_object *commit = NULL;
9540 char *id_str = NULL, *logmsg = NULL;
9542 err = got_object_open_as_commit(&commit, repo, id);
9543 if (err)
9544 return err;
9546 err = got_object_id_str(&id_str, id);
9547 if (err)
9548 goto done;
9550 id_str[12] = '\0';
9552 err = get_short_logmsg(&logmsg, 42, commit);
9553 if (err)
9554 goto done;
9556 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9557 done:
9558 free(id_str);
9559 got_object_commit_close(commit);
9560 free(logmsg);
9561 return err;
9564 static const struct got_error *
9565 show_rebase_progress(struct got_commit_object *commit,
9566 struct got_object_id *old_id, struct got_object_id *new_id)
9568 const struct got_error *err;
9569 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9571 err = got_object_id_str(&old_id_str, old_id);
9572 if (err)
9573 goto done;
9575 if (new_id) {
9576 err = got_object_id_str(&new_id_str, new_id);
9577 if (err)
9578 goto done;
9581 old_id_str[12] = '\0';
9582 if (new_id_str)
9583 new_id_str[12] = '\0';
9585 err = get_short_logmsg(&logmsg, 42, commit);
9586 if (err)
9587 goto done;
9589 printf("%s -> %s: %s\n", old_id_str,
9590 new_id_str ? new_id_str : "no-op change", logmsg);
9591 done:
9592 free(old_id_str);
9593 free(new_id_str);
9594 free(logmsg);
9595 return err;
9598 static const struct got_error *
9599 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9600 struct got_reference *branch, struct got_reference *new_base_branch,
9601 struct got_reference *tmp_branch, struct got_repository *repo,
9602 int create_backup)
9604 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9605 return got_worktree_rebase_complete(worktree, fileindex,
9606 new_base_branch, tmp_branch, branch, repo, create_backup);
9609 static const struct got_error *
9610 rebase_commit(struct got_pathlist_head *merged_paths,
9611 struct got_worktree *worktree, struct got_fileindex *fileindex,
9612 struct got_reference *tmp_branch, const char *committer,
9613 struct got_object_id *commit_id, struct got_repository *repo)
9615 const struct got_error *error;
9616 struct got_commit_object *commit;
9617 struct got_object_id *new_commit_id;
9619 error = got_object_open_as_commit(&commit, repo, commit_id);
9620 if (error)
9621 return error;
9623 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9624 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9625 repo);
9626 if (error) {
9627 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9628 goto done;
9629 error = show_rebase_progress(commit, commit_id, NULL);
9630 } else {
9631 error = show_rebase_progress(commit, commit_id, new_commit_id);
9632 free(new_commit_id);
9634 done:
9635 got_object_commit_close(commit);
9636 return error;
9639 struct check_path_prefix_arg {
9640 const char *path_prefix;
9641 size_t len;
9642 int errcode;
9645 static const struct got_error *
9646 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9647 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9648 struct got_object_id *id1, struct got_object_id *id2,
9649 const char *path1, const char *path2,
9650 mode_t mode1, mode_t mode2, struct got_repository *repo)
9652 struct check_path_prefix_arg *a = arg;
9654 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9655 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9656 return got_error(a->errcode);
9658 return NULL;
9661 static const struct got_error *
9662 check_path_prefix(struct got_object_id *parent_id,
9663 struct got_object_id *commit_id, const char *path_prefix,
9664 int errcode, struct got_repository *repo)
9666 const struct got_error *err;
9667 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9668 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9669 struct check_path_prefix_arg cpp_arg;
9671 if (got_path_is_root_dir(path_prefix))
9672 return NULL;
9674 err = got_object_open_as_commit(&commit, repo, commit_id);
9675 if (err)
9676 goto done;
9678 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9679 if (err)
9680 goto done;
9682 err = got_object_open_as_tree(&tree1, repo,
9683 got_object_commit_get_tree_id(parent_commit));
9684 if (err)
9685 goto done;
9687 err = got_object_open_as_tree(&tree2, repo,
9688 got_object_commit_get_tree_id(commit));
9689 if (err)
9690 goto done;
9692 cpp_arg.path_prefix = path_prefix;
9693 while (cpp_arg.path_prefix[0] == '/')
9694 cpp_arg.path_prefix++;
9695 cpp_arg.len = strlen(cpp_arg.path_prefix);
9696 cpp_arg.errcode = errcode;
9697 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9698 check_path_prefix_in_diff, &cpp_arg, 0);
9699 done:
9700 if (tree1)
9701 got_object_tree_close(tree1);
9702 if (tree2)
9703 got_object_tree_close(tree2);
9704 if (commit)
9705 got_object_commit_close(commit);
9706 if (parent_commit)
9707 got_object_commit_close(parent_commit);
9708 return err;
9711 static const struct got_error *
9712 collect_commits(struct got_object_id_queue *commits,
9713 struct got_object_id *initial_commit_id,
9714 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9715 const char *path_prefix, int path_prefix_errcode,
9716 struct got_repository *repo)
9718 const struct got_error *err = NULL;
9719 struct got_commit_graph *graph = NULL;
9720 struct got_object_id *parent_id = NULL;
9721 struct got_object_qid *qid;
9722 struct got_object_id *commit_id = initial_commit_id;
9724 err = got_commit_graph_open(&graph, "/", 1);
9725 if (err)
9726 return err;
9728 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9729 check_cancelled, NULL);
9730 if (err)
9731 goto done;
9732 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9733 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9734 check_cancelled, NULL);
9735 if (err) {
9736 if (err->code == GOT_ERR_ITER_COMPLETED) {
9737 err = got_error_msg(GOT_ERR_ANCESTRY,
9738 "ran out of commits to rebase before "
9739 "youngest common ancestor commit has "
9740 "been reached?!?");
9742 goto done;
9743 } else {
9744 err = check_path_prefix(parent_id, commit_id,
9745 path_prefix, path_prefix_errcode, repo);
9746 if (err)
9747 goto done;
9749 err = got_object_qid_alloc(&qid, commit_id);
9750 if (err)
9751 goto done;
9752 STAILQ_INSERT_HEAD(commits, qid, entry);
9753 commit_id = parent_id;
9756 done:
9757 got_commit_graph_close(graph);
9758 return err;
9761 static const struct got_error *
9762 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9764 const struct got_error *err = NULL;
9765 time_t committer_time;
9766 struct tm tm;
9767 char datebuf[11]; /* YYYY-MM-DD + NUL */
9768 char *author0 = NULL, *author, *smallerthan;
9769 char *logmsg0 = NULL, *logmsg, *newline;
9771 committer_time = got_object_commit_get_committer_time(commit);
9772 if (gmtime_r(&committer_time, &tm) == NULL)
9773 return got_error_from_errno("gmtime_r");
9774 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9775 return got_error(GOT_ERR_NO_SPACE);
9777 author0 = strdup(got_object_commit_get_author(commit));
9778 if (author0 == NULL)
9779 return got_error_from_errno("strdup");
9780 author = author0;
9781 smallerthan = strchr(author, '<');
9782 if (smallerthan && smallerthan[1] != '\0')
9783 author = smallerthan + 1;
9784 author[strcspn(author, "@>")] = '\0';
9786 err = got_object_commit_get_logmsg(&logmsg0, commit);
9787 if (err)
9788 goto done;
9789 logmsg = logmsg0;
9790 while (*logmsg == '\n')
9791 logmsg++;
9792 newline = strchr(logmsg, '\n');
9793 if (newline)
9794 *newline = '\0';
9796 if (asprintf(brief_str, "%s %s %s",
9797 datebuf, author, logmsg) == -1)
9798 err = got_error_from_errno("asprintf");
9799 done:
9800 free(author0);
9801 free(logmsg0);
9802 return err;
9805 static const struct got_error *
9806 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9807 struct got_repository *repo)
9809 const struct got_error *err;
9810 char *id_str;
9812 err = got_object_id_str(&id_str, id);
9813 if (err)
9814 return err;
9816 err = got_ref_delete(ref, repo);
9817 if (err)
9818 goto done;
9820 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9821 done:
9822 free(id_str);
9823 return err;
9826 static const struct got_error *
9827 print_backup_ref(const char *branch_name, const char *new_id_str,
9828 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9829 struct got_reflist_object_id_map *refs_idmap,
9830 struct got_repository *repo)
9832 const struct got_error *err = NULL;
9833 struct got_reflist_head *refs;
9834 char *refs_str = NULL;
9835 struct got_object_id *new_commit_id = NULL;
9836 struct got_commit_object *new_commit = NULL;
9837 char *new_commit_brief_str = NULL;
9838 struct got_object_id *yca_id = NULL;
9839 struct got_commit_object *yca_commit = NULL;
9840 char *yca_id_str = NULL, *yca_brief_str = NULL;
9841 char *custom_refs_str;
9843 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9844 return got_error_from_errno("asprintf");
9846 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9847 0, 0, refs_idmap, custom_refs_str);
9848 if (err)
9849 goto done;
9851 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9852 if (err)
9853 goto done;
9855 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9856 if (refs) {
9857 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9858 if (err)
9859 goto done;
9862 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9863 if (err)
9864 goto done;
9866 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9867 if (err)
9868 goto done;
9870 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9871 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9872 if (err)
9873 goto done;
9875 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9876 refs_str ? " (" : "", refs_str ? refs_str : "",
9877 refs_str ? ")" : "", new_commit_brief_str);
9878 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9879 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9880 free(refs_str);
9881 refs_str = NULL;
9883 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9884 if (err)
9885 goto done;
9887 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9888 if (err)
9889 goto done;
9891 err = got_object_id_str(&yca_id_str, yca_id);
9892 if (err)
9893 goto done;
9895 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9896 if (refs) {
9897 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9898 if (err)
9899 goto done;
9901 printf("history forked at %s%s%s%s\n %s\n",
9902 yca_id_str,
9903 refs_str ? " (" : "", refs_str ? refs_str : "",
9904 refs_str ? ")" : "", yca_brief_str);
9906 done:
9907 free(custom_refs_str);
9908 free(new_commit_id);
9909 free(refs_str);
9910 free(yca_id);
9911 free(yca_id_str);
9912 free(yca_brief_str);
9913 if (new_commit)
9914 got_object_commit_close(new_commit);
9915 if (yca_commit)
9916 got_object_commit_close(yca_commit);
9918 return NULL;
9921 static const struct got_error *
9922 process_backup_refs(const char *backup_ref_prefix,
9923 const char *wanted_branch_name,
9924 int delete, struct got_repository *repo)
9926 const struct got_error *err;
9927 struct got_reflist_head refs, backup_refs;
9928 struct got_reflist_entry *re;
9929 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9930 struct got_object_id *old_commit_id = NULL;
9931 char *branch_name = NULL;
9932 struct got_commit_object *old_commit = NULL;
9933 struct got_reflist_object_id_map *refs_idmap = NULL;
9934 int wanted_branch_found = 0;
9936 TAILQ_INIT(&refs);
9937 TAILQ_INIT(&backup_refs);
9939 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9940 if (err)
9941 return err;
9943 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9944 if (err)
9945 goto done;
9947 if (wanted_branch_name) {
9948 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9949 wanted_branch_name += 11;
9952 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9953 got_ref_cmp_by_commit_timestamp_descending, repo);
9954 if (err)
9955 goto done;
9957 TAILQ_FOREACH(re, &backup_refs, entry) {
9958 const char *refname = got_ref_get_name(re->ref);
9959 char *slash;
9961 err = check_cancelled(NULL);
9962 if (err)
9963 break;
9965 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9966 if (err)
9967 break;
9969 err = got_object_open_as_commit(&old_commit, repo,
9970 old_commit_id);
9971 if (err)
9972 break;
9974 if (strncmp(backup_ref_prefix, refname,
9975 backup_ref_prefix_len) == 0)
9976 refname += backup_ref_prefix_len;
9978 while (refname[0] == '/')
9979 refname++;
9981 branch_name = strdup(refname);
9982 if (branch_name == NULL) {
9983 err = got_error_from_errno("strdup");
9984 break;
9986 slash = strrchr(branch_name, '/');
9987 if (slash) {
9988 *slash = '\0';
9989 refname += strlen(branch_name) + 1;
9992 if (wanted_branch_name == NULL ||
9993 strcmp(wanted_branch_name, branch_name) == 0) {
9994 wanted_branch_found = 1;
9995 if (delete) {
9996 err = delete_backup_ref(re->ref,
9997 old_commit_id, repo);
9998 } else {
9999 err = print_backup_ref(branch_name, refname,
10000 old_commit_id, old_commit, refs_idmap,
10001 repo);
10003 if (err)
10004 break;
10007 free(old_commit_id);
10008 old_commit_id = NULL;
10009 free(branch_name);
10010 branch_name = NULL;
10011 got_object_commit_close(old_commit);
10012 old_commit = NULL;
10015 if (wanted_branch_name && !wanted_branch_found) {
10016 err = got_error_fmt(GOT_ERR_NOT_REF,
10017 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10019 done:
10020 if (refs_idmap)
10021 got_reflist_object_id_map_free(refs_idmap);
10022 got_ref_list_free(&refs);
10023 got_ref_list_free(&backup_refs);
10024 free(old_commit_id);
10025 free(branch_name);
10026 if (old_commit)
10027 got_object_commit_close(old_commit);
10028 return err;
10031 static const struct got_error *
10032 abort_progress(void *arg, unsigned char status, const char *path)
10035 * Unversioned files should not clutter progress output when
10036 * an operation is aborted.
10038 if (status == GOT_STATUS_UNVERSIONED)
10039 return NULL;
10041 return update_progress(arg, status, path);
10044 static const struct got_error *
10045 cmd_rebase(int argc, char *argv[])
10047 const struct got_error *error = NULL;
10048 struct got_worktree *worktree = NULL;
10049 struct got_repository *repo = NULL;
10050 struct got_fileindex *fileindex = NULL;
10051 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10052 struct got_reference *branch = NULL;
10053 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10054 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10055 struct got_object_id *resume_commit_id = NULL;
10056 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10057 struct got_commit_object *commit = NULL;
10058 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10059 int histedit_in_progress = 0, merge_in_progress = 0;
10060 int create_backup = 1, list_backups = 0, delete_backups = 0;
10061 struct got_object_id_queue commits;
10062 struct got_pathlist_head merged_paths;
10063 const struct got_object_id_queue *parent_ids;
10064 struct got_object_qid *qid, *pid;
10065 struct got_update_progress_arg upa;
10066 int *pack_fds = NULL;
10068 STAILQ_INIT(&commits);
10069 TAILQ_INIT(&merged_paths);
10070 memset(&upa, 0, sizeof(upa));
10072 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10073 switch (ch) {
10074 case 'a':
10075 abort_rebase = 1;
10076 break;
10077 case 'c':
10078 continue_rebase = 1;
10079 break;
10080 case 'l':
10081 list_backups = 1;
10082 break;
10083 case 'X':
10084 delete_backups = 1;
10085 break;
10086 default:
10087 usage_rebase();
10088 /* NOTREACHED */
10092 argc -= optind;
10093 argv += optind;
10095 #ifndef PROFILE
10096 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10097 "unveil", NULL) == -1)
10098 err(1, "pledge");
10099 #endif
10100 if (list_backups) {
10101 if (abort_rebase)
10102 option_conflict('l', 'a');
10103 if (continue_rebase)
10104 option_conflict('l', 'c');
10105 if (delete_backups)
10106 option_conflict('l', 'X');
10107 if (argc != 0 && argc != 1)
10108 usage_rebase();
10109 } else if (delete_backups) {
10110 if (abort_rebase)
10111 option_conflict('X', 'a');
10112 if (continue_rebase)
10113 option_conflict('X', 'c');
10114 if (list_backups)
10115 option_conflict('l', 'X');
10116 if (argc != 0 && argc != 1)
10117 usage_rebase();
10118 } else {
10119 if (abort_rebase && continue_rebase)
10120 usage_rebase();
10121 else if (abort_rebase || continue_rebase) {
10122 if (argc != 0)
10123 usage_rebase();
10124 } else if (argc != 1)
10125 usage_rebase();
10128 cwd = getcwd(NULL, 0);
10129 if (cwd == NULL) {
10130 error = got_error_from_errno("getcwd");
10131 goto done;
10134 error = got_repo_pack_fds_open(&pack_fds);
10135 if (error != NULL)
10136 goto done;
10138 error = got_worktree_open(&worktree, cwd);
10139 if (error) {
10140 if (list_backups || delete_backups) {
10141 if (error->code != GOT_ERR_NOT_WORKTREE)
10142 goto done;
10143 } else {
10144 if (error->code == GOT_ERR_NOT_WORKTREE)
10145 error = wrap_not_worktree_error(error,
10146 "rebase", cwd);
10147 goto done;
10151 error = get_gitconfig_path(&gitconfig_path);
10152 if (error)
10153 goto done;
10154 error = got_repo_open(&repo,
10155 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10156 gitconfig_path, pack_fds);
10157 if (error != NULL)
10158 goto done;
10160 error = get_author(&committer, repo, worktree);
10161 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10162 goto done;
10164 error = apply_unveil(got_repo_get_path(repo), 0,
10165 worktree ? got_worktree_get_root_path(worktree) : NULL);
10166 if (error)
10167 goto done;
10169 if (list_backups || delete_backups) {
10170 error = process_backup_refs(
10171 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10172 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10173 goto done; /* nothing else to do */
10176 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10177 worktree);
10178 if (error)
10179 goto done;
10180 if (histedit_in_progress) {
10181 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10182 goto done;
10185 error = got_worktree_merge_in_progress(&merge_in_progress,
10186 worktree, repo);
10187 if (error)
10188 goto done;
10189 if (merge_in_progress) {
10190 error = got_error(GOT_ERR_MERGE_BUSY);
10191 goto done;
10194 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10195 if (error)
10196 goto done;
10198 if (abort_rebase) {
10199 if (!rebase_in_progress) {
10200 error = got_error(GOT_ERR_NOT_REBASING);
10201 goto done;
10203 error = got_worktree_rebase_continue(&resume_commit_id,
10204 &new_base_branch, &tmp_branch, &branch, &fileindex,
10205 worktree, repo);
10206 if (error)
10207 goto done;
10208 printf("Switching work tree to %s\n",
10209 got_ref_get_symref_target(new_base_branch));
10210 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10211 new_base_branch, abort_progress, &upa);
10212 if (error)
10213 goto done;
10214 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10215 print_merge_progress_stats(&upa);
10216 goto done; /* nothing else to do */
10219 if (continue_rebase) {
10220 if (!rebase_in_progress) {
10221 error = got_error(GOT_ERR_NOT_REBASING);
10222 goto done;
10224 error = got_worktree_rebase_continue(&resume_commit_id,
10225 &new_base_branch, &tmp_branch, &branch, &fileindex,
10226 worktree, repo);
10227 if (error)
10228 goto done;
10230 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10231 committer, resume_commit_id, repo);
10232 if (error)
10233 goto done;
10235 yca_id = got_object_id_dup(resume_commit_id);
10236 if (yca_id == NULL) {
10237 error = got_error_from_errno("got_object_id_dup");
10238 goto done;
10240 } else {
10241 error = got_ref_open(&branch, repo, argv[0], 0);
10242 if (error != NULL)
10243 goto done;
10246 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10247 if (error)
10248 goto done;
10250 if (!continue_rebase) {
10251 struct got_object_id *base_commit_id;
10253 base_commit_id = got_worktree_get_base_commit_id(worktree);
10254 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10255 base_commit_id, branch_head_commit_id, 1, repo,
10256 check_cancelled, NULL);
10257 if (error)
10258 goto done;
10259 if (yca_id == NULL) {
10260 error = got_error_msg(GOT_ERR_ANCESTRY,
10261 "specified branch shares no common ancestry "
10262 "with work tree's branch");
10263 goto done;
10266 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10267 if (error) {
10268 if (error->code != GOT_ERR_ANCESTRY)
10269 goto done;
10270 error = NULL;
10271 } else {
10272 struct got_pathlist_head paths;
10273 printf("%s is already based on %s\n",
10274 got_ref_get_name(branch),
10275 got_worktree_get_head_ref_name(worktree));
10276 error = switch_head_ref(branch, branch_head_commit_id,
10277 worktree, repo);
10278 if (error)
10279 goto done;
10280 error = got_worktree_set_base_commit_id(worktree, repo,
10281 branch_head_commit_id);
10282 if (error)
10283 goto done;
10284 TAILQ_INIT(&paths);
10285 error = got_pathlist_append(&paths, "", NULL);
10286 if (error)
10287 goto done;
10288 error = got_worktree_checkout_files(worktree,
10289 &paths, repo, update_progress, &upa,
10290 check_cancelled, NULL);
10291 got_pathlist_free(&paths);
10292 if (error)
10293 goto done;
10294 if (upa.did_something) {
10295 char *id_str;
10296 error = got_object_id_str(&id_str,
10297 branch_head_commit_id);
10298 if (error)
10299 goto done;
10300 printf("Updated to %s: %s\n",
10301 got_worktree_get_head_ref_name(worktree),
10302 id_str);
10303 free(id_str);
10304 } else
10305 printf("Already up-to-date\n");
10306 print_update_progress_stats(&upa);
10307 goto done;
10311 commit_id = branch_head_commit_id;
10312 error = got_object_open_as_commit(&commit, repo, commit_id);
10313 if (error)
10314 goto done;
10316 parent_ids = got_object_commit_get_parent_ids(commit);
10317 pid = STAILQ_FIRST(parent_ids);
10318 if (pid == NULL) {
10319 error = got_error(GOT_ERR_EMPTY_REBASE);
10320 goto done;
10322 error = collect_commits(&commits, commit_id, &pid->id,
10323 yca_id, got_worktree_get_path_prefix(worktree),
10324 GOT_ERR_REBASE_PATH, repo);
10325 got_object_commit_close(commit);
10326 commit = NULL;
10327 if (error)
10328 goto done;
10330 if (!continue_rebase) {
10331 error = got_worktree_rebase_prepare(&new_base_branch,
10332 &tmp_branch, &fileindex, worktree, branch, repo);
10333 if (error)
10334 goto done;
10337 if (STAILQ_EMPTY(&commits)) {
10338 if (continue_rebase) {
10339 error = rebase_complete(worktree, fileindex,
10340 branch, new_base_branch, tmp_branch, repo,
10341 create_backup);
10342 goto done;
10343 } else {
10344 /* Fast-forward the reference of the branch. */
10345 struct got_object_id *new_head_commit_id;
10346 char *id_str;
10347 error = got_ref_resolve(&new_head_commit_id, repo,
10348 new_base_branch);
10349 if (error)
10350 goto done;
10351 error = got_object_id_str(&id_str, new_head_commit_id);
10352 if (error)
10353 goto done;
10354 printf("Forwarding %s to commit %s\n",
10355 got_ref_get_name(branch), id_str);
10356 free(id_str);
10357 error = got_ref_change_ref(branch,
10358 new_head_commit_id);
10359 if (error)
10360 goto done;
10361 /* No backup needed since objects did not change. */
10362 create_backup = 0;
10366 pid = NULL;
10367 STAILQ_FOREACH(qid, &commits, entry) {
10369 commit_id = &qid->id;
10370 parent_id = pid ? &pid->id : yca_id;
10371 pid = qid;
10373 memset(&upa, 0, sizeof(upa));
10374 error = got_worktree_rebase_merge_files(&merged_paths,
10375 worktree, fileindex, parent_id, commit_id, repo,
10376 update_progress, &upa, check_cancelled, NULL);
10377 if (error)
10378 goto done;
10380 print_merge_progress_stats(&upa);
10381 if (upa.conflicts > 0 || upa.missing > 0 ||
10382 upa.not_deleted > 0 || upa.unversioned > 0) {
10383 if (upa.conflicts > 0) {
10384 error = show_rebase_merge_conflict(&qid->id,
10385 repo);
10386 if (error)
10387 goto done;
10389 got_worktree_rebase_pathlist_free(&merged_paths);
10390 break;
10393 error = rebase_commit(&merged_paths, worktree, fileindex,
10394 tmp_branch, committer, commit_id, repo);
10395 got_worktree_rebase_pathlist_free(&merged_paths);
10396 if (error)
10397 goto done;
10400 if (upa.conflicts > 0 || upa.missing > 0 ||
10401 upa.not_deleted > 0 || upa.unversioned > 0) {
10402 error = got_worktree_rebase_postpone(worktree, fileindex);
10403 if (error)
10404 goto done;
10405 if (upa.conflicts > 0 && upa.missing == 0 &&
10406 upa.not_deleted == 0 && upa.unversioned == 0) {
10407 error = got_error_msg(GOT_ERR_CONFLICTS,
10408 "conflicts must be resolved before rebasing "
10409 "can continue");
10410 } else if (upa.conflicts > 0) {
10411 error = got_error_msg(GOT_ERR_CONFLICTS,
10412 "conflicts must be resolved before rebasing "
10413 "can continue; changes destined for some "
10414 "files were not yet merged and should be "
10415 "merged manually if required before the "
10416 "rebase operation is continued");
10417 } else {
10418 error = got_error_msg(GOT_ERR_CONFLICTS,
10419 "changes destined for some files were not "
10420 "yet merged and should be merged manually "
10421 "if required before the rebase operation "
10422 "is continued");
10424 } else
10425 error = rebase_complete(worktree, fileindex, branch,
10426 new_base_branch, tmp_branch, repo, create_backup);
10427 done:
10428 free(cwd);
10429 free(committer);
10430 free(gitconfig_path);
10431 got_object_id_queue_free(&commits);
10432 free(branch_head_commit_id);
10433 free(resume_commit_id);
10434 free(yca_id);
10435 if (commit)
10436 got_object_commit_close(commit);
10437 if (branch)
10438 got_ref_close(branch);
10439 if (new_base_branch)
10440 got_ref_close(new_base_branch);
10441 if (tmp_branch)
10442 got_ref_close(tmp_branch);
10443 if (worktree)
10444 got_worktree_close(worktree);
10445 if (repo) {
10446 const struct got_error *close_err = got_repo_close(repo);
10447 if (error == NULL)
10448 error = close_err;
10450 if (pack_fds) {
10451 const struct got_error *pack_err =
10452 got_repo_pack_fds_close(pack_fds);
10453 if (error == NULL)
10454 error = pack_err;
10456 return error;
10459 __dead static void
10460 usage_histedit(void)
10462 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10463 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10464 getprogname());
10465 exit(1);
10468 #define GOT_HISTEDIT_PICK 'p'
10469 #define GOT_HISTEDIT_EDIT 'e'
10470 #define GOT_HISTEDIT_FOLD 'f'
10471 #define GOT_HISTEDIT_DROP 'd'
10472 #define GOT_HISTEDIT_MESG 'm'
10474 static const struct got_histedit_cmd {
10475 unsigned char code;
10476 const char *name;
10477 const char *desc;
10478 } got_histedit_cmds[] = {
10479 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10480 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10481 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10482 "be used" },
10483 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10484 { GOT_HISTEDIT_MESG, "mesg",
10485 "single-line log message for commit above (open editor if empty)" },
10488 struct got_histedit_list_entry {
10489 TAILQ_ENTRY(got_histedit_list_entry) entry;
10490 struct got_object_id *commit_id;
10491 const struct got_histedit_cmd *cmd;
10492 char *logmsg;
10494 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10496 static const struct got_error *
10497 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10498 FILE *f, struct got_repository *repo)
10500 const struct got_error *err = NULL;
10501 char *logmsg = NULL, *id_str = NULL;
10502 struct got_commit_object *commit = NULL;
10503 int n;
10505 err = got_object_open_as_commit(&commit, repo, commit_id);
10506 if (err)
10507 goto done;
10509 err = get_short_logmsg(&logmsg, 34, commit);
10510 if (err)
10511 goto done;
10513 err = got_object_id_str(&id_str, commit_id);
10514 if (err)
10515 goto done;
10517 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10518 if (n < 0)
10519 err = got_ferror(f, GOT_ERR_IO);
10520 done:
10521 if (commit)
10522 got_object_commit_close(commit);
10523 free(id_str);
10524 free(logmsg);
10525 return err;
10528 static const struct got_error *
10529 histedit_write_commit_list(struct got_object_id_queue *commits,
10530 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10531 struct got_repository *repo)
10533 const struct got_error *err = NULL;
10534 struct got_object_qid *qid;
10535 const char *histedit_cmd = NULL;
10537 if (STAILQ_EMPTY(commits))
10538 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10540 STAILQ_FOREACH(qid, commits, entry) {
10541 histedit_cmd = got_histedit_cmds[0].name;
10542 if (edit_only)
10543 histedit_cmd = "edit";
10544 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10545 histedit_cmd = "fold";
10546 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10547 if (err)
10548 break;
10549 if (edit_logmsg_only) {
10550 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10551 if (n < 0) {
10552 err = got_ferror(f, GOT_ERR_IO);
10553 break;
10558 return err;
10561 static const struct got_error *
10562 write_cmd_list(FILE *f, const char *branch_name,
10563 struct got_object_id_queue *commits)
10565 const struct got_error *err = NULL;
10566 size_t i;
10567 int n;
10568 char *id_str;
10569 struct got_object_qid *qid;
10571 qid = STAILQ_FIRST(commits);
10572 err = got_object_id_str(&id_str, &qid->id);
10573 if (err)
10574 return err;
10576 n = fprintf(f,
10577 "# Editing the history of branch '%s' starting at\n"
10578 "# commit %s\n"
10579 "# Commits will be processed in order from top to "
10580 "bottom of this file.\n", branch_name, id_str);
10581 if (n < 0) {
10582 err = got_ferror(f, GOT_ERR_IO);
10583 goto done;
10586 n = fprintf(f, "# Available histedit commands:\n");
10587 if (n < 0) {
10588 err = got_ferror(f, GOT_ERR_IO);
10589 goto done;
10592 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10593 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10594 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10595 cmd->desc);
10596 if (n < 0) {
10597 err = got_ferror(f, GOT_ERR_IO);
10598 break;
10601 done:
10602 free(id_str);
10603 return err;
10606 static const struct got_error *
10607 histedit_syntax_error(int lineno)
10609 static char msg[42];
10610 int ret;
10612 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10613 lineno);
10614 if (ret == -1 || ret >= sizeof(msg))
10615 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10617 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10620 static const struct got_error *
10621 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10622 char *logmsg, struct got_repository *repo)
10624 const struct got_error *err;
10625 struct got_commit_object *folded_commit = NULL;
10626 char *id_str, *folded_logmsg = NULL;
10628 err = got_object_id_str(&id_str, hle->commit_id);
10629 if (err)
10630 return err;
10632 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10633 if (err)
10634 goto done;
10636 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10637 if (err)
10638 goto done;
10639 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10640 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10641 folded_logmsg) == -1) {
10642 err = got_error_from_errno("asprintf");
10644 done:
10645 if (folded_commit)
10646 got_object_commit_close(folded_commit);
10647 free(id_str);
10648 free(folded_logmsg);
10649 return err;
10652 static struct got_histedit_list_entry *
10653 get_folded_commits(struct got_histedit_list_entry *hle)
10655 struct got_histedit_list_entry *prev, *folded = NULL;
10657 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10658 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10659 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10660 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10661 folded = prev;
10662 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10665 return folded;
10668 static const struct got_error *
10669 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10670 struct got_repository *repo)
10672 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10673 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10674 const struct got_error *err = NULL;
10675 struct got_commit_object *commit = NULL;
10676 int logmsg_len;
10677 int fd;
10678 struct got_histedit_list_entry *folded = NULL;
10680 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10681 if (err)
10682 return err;
10684 folded = get_folded_commits(hle);
10685 if (folded) {
10686 while (folded != hle) {
10687 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10688 folded = TAILQ_NEXT(folded, entry);
10689 continue;
10691 err = append_folded_commit_msg(&new_msg, folded,
10692 logmsg, repo);
10693 if (err)
10694 goto done;
10695 free(logmsg);
10696 logmsg = new_msg;
10697 folded = TAILQ_NEXT(folded, entry);
10701 err = got_object_id_str(&id_str, hle->commit_id);
10702 if (err)
10703 goto done;
10704 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10705 if (err)
10706 goto done;
10707 logmsg_len = asprintf(&new_msg,
10708 "%s\n# original log message of commit %s: %s",
10709 logmsg ? logmsg : "", id_str, orig_logmsg);
10710 if (logmsg_len == -1) {
10711 err = got_error_from_errno("asprintf");
10712 goto done;
10714 free(logmsg);
10715 logmsg = new_msg;
10717 err = got_object_id_str(&id_str, hle->commit_id);
10718 if (err)
10719 goto done;
10721 err = got_opentemp_named_fd(&logmsg_path, &fd,
10722 GOT_TMPDIR_STR "/got-logmsg");
10723 if (err)
10724 goto done;
10726 write(fd, logmsg, logmsg_len);
10727 close(fd);
10729 err = get_editor(&editor);
10730 if (err)
10731 goto done;
10733 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10734 logmsg_len, 0);
10735 if (err) {
10736 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10737 goto done;
10738 err = NULL;
10739 hle->logmsg = strdup(new_msg);
10740 if (hle->logmsg == NULL)
10741 err = got_error_from_errno("strdup");
10743 done:
10744 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10745 err = got_error_from_errno2("unlink", logmsg_path);
10746 free(logmsg_path);
10747 free(logmsg);
10748 free(orig_logmsg);
10749 free(editor);
10750 if (commit)
10751 got_object_commit_close(commit);
10752 return err;
10755 static const struct got_error *
10756 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10757 FILE *f, struct got_repository *repo)
10759 const struct got_error *err = NULL;
10760 char *line = NULL, *p, *end;
10761 size_t i, size;
10762 ssize_t len;
10763 int lineno = 0, lastcmd = -1;
10764 const struct got_histedit_cmd *cmd;
10765 struct got_object_id *commit_id = NULL;
10766 struct got_histedit_list_entry *hle = NULL;
10768 for (;;) {
10769 len = getline(&line, &size, f);
10770 if (len == -1) {
10771 const struct got_error *getline_err;
10772 if (feof(f))
10773 break;
10774 getline_err = got_error_from_errno("getline");
10775 err = got_ferror(f, getline_err->code);
10776 break;
10778 lineno++;
10779 p = line;
10780 while (isspace((unsigned char)p[0]))
10781 p++;
10782 if (p[0] == '#' || p[0] == '\0') {
10783 free(line);
10784 line = NULL;
10785 continue;
10787 cmd = NULL;
10788 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10789 cmd = &got_histedit_cmds[i];
10790 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10791 isspace((unsigned char)p[strlen(cmd->name)])) {
10792 p += strlen(cmd->name);
10793 break;
10795 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10796 p++;
10797 break;
10800 if (i == nitems(got_histedit_cmds)) {
10801 err = histedit_syntax_error(lineno);
10802 break;
10804 while (isspace((unsigned char)p[0]))
10805 p++;
10806 if (cmd->code == GOT_HISTEDIT_MESG) {
10807 if (lastcmd != GOT_HISTEDIT_PICK &&
10808 lastcmd != GOT_HISTEDIT_EDIT) {
10809 err = got_error(GOT_ERR_HISTEDIT_CMD);
10810 break;
10812 if (p[0] == '\0') {
10813 err = histedit_edit_logmsg(hle, repo);
10814 if (err)
10815 break;
10816 } else {
10817 hle->logmsg = strdup(p);
10818 if (hle->logmsg == NULL) {
10819 err = got_error_from_errno("strdup");
10820 break;
10823 free(line);
10824 line = NULL;
10825 lastcmd = cmd->code;
10826 continue;
10827 } else {
10828 end = p;
10829 while (end[0] && !isspace((unsigned char)end[0]))
10830 end++;
10831 *end = '\0';
10833 err = got_object_resolve_id_str(&commit_id, repo, p);
10834 if (err) {
10835 /* override error code */
10836 err = histedit_syntax_error(lineno);
10837 break;
10840 hle = malloc(sizeof(*hle));
10841 if (hle == NULL) {
10842 err = got_error_from_errno("malloc");
10843 break;
10845 hle->cmd = cmd;
10846 hle->commit_id = commit_id;
10847 hle->logmsg = NULL;
10848 commit_id = NULL;
10849 free(line);
10850 line = NULL;
10851 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10852 lastcmd = cmd->code;
10855 free(line);
10856 free(commit_id);
10857 return err;
10860 static const struct got_error *
10861 histedit_check_script(struct got_histedit_list *histedit_cmds,
10862 struct got_object_id_queue *commits, struct got_repository *repo)
10864 const struct got_error *err = NULL;
10865 struct got_object_qid *qid;
10866 struct got_histedit_list_entry *hle;
10867 static char msg[92];
10868 char *id_str;
10870 if (TAILQ_EMPTY(histedit_cmds))
10871 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10872 "histedit script contains no commands");
10873 if (STAILQ_EMPTY(commits))
10874 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10876 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10877 struct got_histedit_list_entry *hle2;
10878 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10879 if (hle == hle2)
10880 continue;
10881 if (got_object_id_cmp(hle->commit_id,
10882 hle2->commit_id) != 0)
10883 continue;
10884 err = got_object_id_str(&id_str, hle->commit_id);
10885 if (err)
10886 return err;
10887 snprintf(msg, sizeof(msg), "commit %s is listed "
10888 "more than once in histedit script", id_str);
10889 free(id_str);
10890 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10894 STAILQ_FOREACH(qid, commits, entry) {
10895 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10896 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10897 break;
10899 if (hle == NULL) {
10900 err = got_object_id_str(&id_str, &qid->id);
10901 if (err)
10902 return err;
10903 snprintf(msg, sizeof(msg),
10904 "commit %s missing from histedit script", id_str);
10905 free(id_str);
10906 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10910 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10911 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10912 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10913 "last commit in histedit script cannot be folded");
10915 return NULL;
10918 static const struct got_error *
10919 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10920 const char *path, struct got_object_id_queue *commits,
10921 struct got_repository *repo)
10923 const struct got_error *err = NULL;
10924 char *editor;
10925 FILE *f = NULL;
10927 err = get_editor(&editor);
10928 if (err)
10929 return err;
10931 if (spawn_editor(editor, path) == -1) {
10932 err = got_error_from_errno("failed spawning editor");
10933 goto done;
10936 f = fopen(path, "re");
10937 if (f == NULL) {
10938 err = got_error_from_errno("fopen");
10939 goto done;
10941 err = histedit_parse_list(histedit_cmds, f, repo);
10942 if (err)
10943 goto done;
10945 err = histedit_check_script(histedit_cmds, commits, repo);
10946 done:
10947 if (f && fclose(f) == EOF && err == NULL)
10948 err = got_error_from_errno("fclose");
10949 free(editor);
10950 return err;
10953 static const struct got_error *
10954 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10955 struct got_object_id_queue *, const char *, const char *,
10956 struct got_repository *);
10958 static const struct got_error *
10959 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10960 struct got_object_id_queue *commits, const char *branch_name,
10961 int edit_logmsg_only, int fold_only, int edit_only,
10962 struct got_repository *repo)
10964 const struct got_error *err;
10965 FILE *f = NULL;
10966 char *path = NULL;
10968 err = got_opentemp_named(&path, &f, "got-histedit");
10969 if (err)
10970 return err;
10972 err = write_cmd_list(f, branch_name, commits);
10973 if (err)
10974 goto done;
10976 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10977 fold_only, edit_only, repo);
10978 if (err)
10979 goto done;
10981 if (edit_logmsg_only || fold_only || edit_only) {
10982 rewind(f);
10983 err = histedit_parse_list(histedit_cmds, f, repo);
10984 } else {
10985 if (fclose(f) == EOF) {
10986 err = got_error_from_errno("fclose");
10987 goto done;
10989 f = NULL;
10990 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10991 if (err) {
10992 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10993 err->code != GOT_ERR_HISTEDIT_CMD)
10994 goto done;
10995 err = histedit_edit_list_retry(histedit_cmds, err,
10996 commits, path, branch_name, repo);
10999 done:
11000 if (f && fclose(f) == EOF && err == NULL)
11001 err = got_error_from_errno("fclose");
11002 if (path && unlink(path) != 0 && err == NULL)
11003 err = got_error_from_errno2("unlink", path);
11004 free(path);
11005 return err;
11008 static const struct got_error *
11009 histedit_save_list(struct got_histedit_list *histedit_cmds,
11010 struct got_worktree *worktree, struct got_repository *repo)
11012 const struct got_error *err = NULL;
11013 char *path = NULL;
11014 FILE *f = NULL;
11015 struct got_histedit_list_entry *hle;
11016 struct got_commit_object *commit = NULL;
11018 err = got_worktree_get_histedit_script_path(&path, worktree);
11019 if (err)
11020 return err;
11022 f = fopen(path, "we");
11023 if (f == NULL) {
11024 err = got_error_from_errno2("fopen", path);
11025 goto done;
11027 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11028 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11029 repo);
11030 if (err)
11031 break;
11033 if (hle->logmsg) {
11034 int n = fprintf(f, "%c %s\n",
11035 GOT_HISTEDIT_MESG, hle->logmsg);
11036 if (n < 0) {
11037 err = got_ferror(f, GOT_ERR_IO);
11038 break;
11042 done:
11043 if (f && fclose(f) == EOF && err == NULL)
11044 err = got_error_from_errno("fclose");
11045 free(path);
11046 if (commit)
11047 got_object_commit_close(commit);
11048 return err;
11051 static void
11052 histedit_free_list(struct got_histedit_list *histedit_cmds)
11054 struct got_histedit_list_entry *hle;
11056 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11057 TAILQ_REMOVE(histedit_cmds, hle, entry);
11058 free(hle);
11062 static const struct got_error *
11063 histedit_load_list(struct got_histedit_list *histedit_cmds,
11064 const char *path, struct got_repository *repo)
11066 const struct got_error *err = NULL;
11067 FILE *f = NULL;
11069 f = fopen(path, "re");
11070 if (f == NULL) {
11071 err = got_error_from_errno2("fopen", path);
11072 goto done;
11075 err = histedit_parse_list(histedit_cmds, f, repo);
11076 done:
11077 if (f && fclose(f) == EOF && err == NULL)
11078 err = got_error_from_errno("fclose");
11079 return err;
11082 static const struct got_error *
11083 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11084 const struct got_error *edit_err, struct got_object_id_queue *commits,
11085 const char *path, const char *branch_name, struct got_repository *repo)
11087 const struct got_error *err = NULL, *prev_err = edit_err;
11088 int resp = ' ';
11090 while (resp != 'c' && resp != 'r' && resp != 'a') {
11091 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11092 "or (a)bort: ", getprogname(), prev_err->msg);
11093 resp = getchar();
11094 if (resp == '\n')
11095 resp = getchar();
11096 if (resp == 'c') {
11097 histedit_free_list(histedit_cmds);
11098 err = histedit_run_editor(histedit_cmds, path, commits,
11099 repo);
11100 if (err) {
11101 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11102 err->code != GOT_ERR_HISTEDIT_CMD)
11103 break;
11104 prev_err = err;
11105 resp = ' ';
11106 continue;
11108 break;
11109 } else if (resp == 'r') {
11110 histedit_free_list(histedit_cmds);
11111 err = histedit_edit_script(histedit_cmds,
11112 commits, branch_name, 0, 0, 0, repo);
11113 if (err) {
11114 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11115 err->code != GOT_ERR_HISTEDIT_CMD)
11116 break;
11117 prev_err = err;
11118 resp = ' ';
11119 continue;
11121 break;
11122 } else if (resp == 'a') {
11123 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11124 break;
11125 } else
11126 printf("invalid response '%c'\n", resp);
11129 return err;
11132 static const struct got_error *
11133 histedit_complete(struct got_worktree *worktree,
11134 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11135 struct got_reference *branch, struct got_repository *repo)
11137 printf("Switching work tree to %s\n",
11138 got_ref_get_symref_target(branch));
11139 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11140 branch, repo);
11143 static const struct got_error *
11144 show_histedit_progress(struct got_commit_object *commit,
11145 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11147 const struct got_error *err;
11148 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11150 err = got_object_id_str(&old_id_str, hle->commit_id);
11151 if (err)
11152 goto done;
11154 if (new_id) {
11155 err = got_object_id_str(&new_id_str, new_id);
11156 if (err)
11157 goto done;
11160 old_id_str[12] = '\0';
11161 if (new_id_str)
11162 new_id_str[12] = '\0';
11164 if (hle->logmsg) {
11165 logmsg = strdup(hle->logmsg);
11166 if (logmsg == NULL) {
11167 err = got_error_from_errno("strdup");
11168 goto done;
11170 trim_logmsg(logmsg, 42);
11171 } else {
11172 err = get_short_logmsg(&logmsg, 42, commit);
11173 if (err)
11174 goto done;
11177 switch (hle->cmd->code) {
11178 case GOT_HISTEDIT_PICK:
11179 case GOT_HISTEDIT_EDIT:
11180 printf("%s -> %s: %s\n", old_id_str,
11181 new_id_str ? new_id_str : "no-op change", logmsg);
11182 break;
11183 case GOT_HISTEDIT_DROP:
11184 case GOT_HISTEDIT_FOLD:
11185 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11186 logmsg);
11187 break;
11188 default:
11189 break;
11191 done:
11192 free(old_id_str);
11193 free(new_id_str);
11194 return err;
11197 static const struct got_error *
11198 histedit_commit(struct got_pathlist_head *merged_paths,
11199 struct got_worktree *worktree, struct got_fileindex *fileindex,
11200 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11201 const char *committer, struct got_repository *repo)
11203 const struct got_error *err;
11204 struct got_commit_object *commit;
11205 struct got_object_id *new_commit_id;
11207 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11208 && hle->logmsg == NULL) {
11209 err = histedit_edit_logmsg(hle, repo);
11210 if (err)
11211 return err;
11214 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11215 if (err)
11216 return err;
11218 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11219 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11220 hle->logmsg, repo);
11221 if (err) {
11222 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11223 goto done;
11224 err = show_histedit_progress(commit, hle, NULL);
11225 } else {
11226 err = show_histedit_progress(commit, hle, new_commit_id);
11227 free(new_commit_id);
11229 done:
11230 got_object_commit_close(commit);
11231 return err;
11234 static const struct got_error *
11235 histedit_skip_commit(struct got_histedit_list_entry *hle,
11236 struct got_worktree *worktree, struct got_repository *repo)
11238 const struct got_error *error;
11239 struct got_commit_object *commit;
11241 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11242 repo);
11243 if (error)
11244 return error;
11246 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11247 if (error)
11248 return error;
11250 error = show_histedit_progress(commit, hle, NULL);
11251 got_object_commit_close(commit);
11252 return error;
11255 static const struct got_error *
11256 check_local_changes(void *arg, unsigned char status,
11257 unsigned char staged_status, const char *path,
11258 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11259 struct got_object_id *commit_id, int dirfd, const char *de_name)
11261 int *have_local_changes = arg;
11263 switch (status) {
11264 case GOT_STATUS_ADD:
11265 case GOT_STATUS_DELETE:
11266 case GOT_STATUS_MODIFY:
11267 case GOT_STATUS_CONFLICT:
11268 *have_local_changes = 1;
11269 return got_error(GOT_ERR_CANCELLED);
11270 default:
11271 break;
11274 switch (staged_status) {
11275 case GOT_STATUS_ADD:
11276 case GOT_STATUS_DELETE:
11277 case GOT_STATUS_MODIFY:
11278 *have_local_changes = 1;
11279 return got_error(GOT_ERR_CANCELLED);
11280 default:
11281 break;
11284 return NULL;
11287 static const struct got_error *
11288 cmd_histedit(int argc, char *argv[])
11290 const struct got_error *error = NULL;
11291 struct got_worktree *worktree = NULL;
11292 struct got_fileindex *fileindex = NULL;
11293 struct got_repository *repo = NULL;
11294 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11295 struct got_reference *branch = NULL;
11296 struct got_reference *tmp_branch = NULL;
11297 struct got_object_id *resume_commit_id = NULL;
11298 struct got_object_id *base_commit_id = NULL;
11299 struct got_object_id *head_commit_id = NULL;
11300 struct got_commit_object *commit = NULL;
11301 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11302 struct got_update_progress_arg upa;
11303 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11304 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11305 int list_backups = 0, delete_backups = 0;
11306 const char *edit_script_path = NULL;
11307 struct got_object_id_queue commits;
11308 struct got_pathlist_head merged_paths;
11309 const struct got_object_id_queue *parent_ids;
11310 struct got_object_qid *pid;
11311 struct got_histedit_list histedit_cmds;
11312 struct got_histedit_list_entry *hle;
11313 int *pack_fds = NULL;
11315 STAILQ_INIT(&commits);
11316 TAILQ_INIT(&histedit_cmds);
11317 TAILQ_INIT(&merged_paths);
11318 memset(&upa, 0, sizeof(upa));
11320 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11321 switch (ch) {
11322 case 'a':
11323 abort_edit = 1;
11324 break;
11325 case 'c':
11326 continue_edit = 1;
11327 break;
11328 case 'e':
11329 edit_only = 1;
11330 break;
11331 case 'f':
11332 fold_only = 1;
11333 break;
11334 case 'F':
11335 edit_script_path = optarg;
11336 break;
11337 case 'm':
11338 edit_logmsg_only = 1;
11339 break;
11340 case 'l':
11341 list_backups = 1;
11342 break;
11343 case 'X':
11344 delete_backups = 1;
11345 break;
11346 default:
11347 usage_histedit();
11348 /* NOTREACHED */
11352 argc -= optind;
11353 argv += optind;
11355 #ifndef PROFILE
11356 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11357 "unveil", NULL) == -1)
11358 err(1, "pledge");
11359 #endif
11360 if (abort_edit && continue_edit)
11361 option_conflict('a', 'c');
11362 if (edit_script_path && edit_logmsg_only)
11363 option_conflict('F', 'm');
11364 if (abort_edit && edit_logmsg_only)
11365 option_conflict('a', 'm');
11366 if (continue_edit && edit_logmsg_only)
11367 option_conflict('c', 'm');
11368 if (abort_edit && fold_only)
11369 option_conflict('a', 'f');
11370 if (continue_edit && fold_only)
11371 option_conflict('c', 'f');
11372 if (fold_only && edit_logmsg_only)
11373 option_conflict('f', 'm');
11374 if (edit_script_path && fold_only)
11375 option_conflict('F', 'f');
11376 if (abort_edit && edit_only)
11377 option_conflict('a', 'e');
11378 if (continue_edit && edit_only)
11379 option_conflict('c', 'e');
11380 if (edit_only && edit_logmsg_only)
11381 option_conflict('e', 'm');
11382 if (edit_script_path && edit_only)
11383 option_conflict('F', 'e');
11384 if (list_backups) {
11385 if (abort_edit)
11386 option_conflict('l', 'a');
11387 if (continue_edit)
11388 option_conflict('l', 'c');
11389 if (edit_script_path)
11390 option_conflict('l', 'F');
11391 if (edit_logmsg_only)
11392 option_conflict('l', 'm');
11393 if (fold_only)
11394 option_conflict('l', 'f');
11395 if (edit_only)
11396 option_conflict('l', 'e');
11397 if (delete_backups)
11398 option_conflict('l', 'X');
11399 if (argc != 0 && argc != 1)
11400 usage_histedit();
11401 } else if (delete_backups) {
11402 if (abort_edit)
11403 option_conflict('X', 'a');
11404 if (continue_edit)
11405 option_conflict('X', 'c');
11406 if (edit_script_path)
11407 option_conflict('X', 'F');
11408 if (edit_logmsg_only)
11409 option_conflict('X', 'm');
11410 if (fold_only)
11411 option_conflict('X', 'f');
11412 if (edit_only)
11413 option_conflict('X', 'e');
11414 if (list_backups)
11415 option_conflict('X', 'l');
11416 if (argc != 0 && argc != 1)
11417 usage_histedit();
11418 } else if (argc != 0)
11419 usage_histedit();
11422 * This command cannot apply unveil(2) in all cases because the
11423 * user may choose to run an editor to edit the histedit script
11424 * and to edit individual commit log messages.
11425 * unveil(2) traverses exec(2); if an editor is used we have to
11426 * apply unveil after edit script and log messages have been written.
11427 * XXX TODO: Make use of unveil(2) where possible.
11430 cwd = getcwd(NULL, 0);
11431 if (cwd == NULL) {
11432 error = got_error_from_errno("getcwd");
11433 goto done;
11436 error = got_repo_pack_fds_open(&pack_fds);
11437 if (error != NULL)
11438 goto done;
11440 error = got_worktree_open(&worktree, cwd);
11441 if (error) {
11442 if (list_backups || delete_backups) {
11443 if (error->code != GOT_ERR_NOT_WORKTREE)
11444 goto done;
11445 } else {
11446 if (error->code == GOT_ERR_NOT_WORKTREE)
11447 error = wrap_not_worktree_error(error,
11448 "histedit", cwd);
11449 goto done;
11453 if (list_backups || delete_backups) {
11454 error = got_repo_open(&repo,
11455 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11456 NULL, pack_fds);
11457 if (error != NULL)
11458 goto done;
11459 error = apply_unveil(got_repo_get_path(repo), 0,
11460 worktree ? got_worktree_get_root_path(worktree) : NULL);
11461 if (error)
11462 goto done;
11463 error = process_backup_refs(
11464 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11465 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11466 goto done; /* nothing else to do */
11469 error = get_gitconfig_path(&gitconfig_path);
11470 if (error)
11471 goto done;
11472 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11473 gitconfig_path, pack_fds);
11474 if (error != NULL)
11475 goto done;
11477 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11478 if (error)
11479 goto done;
11480 if (rebase_in_progress) {
11481 error = got_error(GOT_ERR_REBASING);
11482 goto done;
11485 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11486 repo);
11487 if (error)
11488 goto done;
11489 if (merge_in_progress) {
11490 error = got_error(GOT_ERR_MERGE_BUSY);
11491 goto done;
11494 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11495 if (error)
11496 goto done;
11498 if (edit_in_progress && edit_logmsg_only) {
11499 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11500 "histedit operation is in progress in this "
11501 "work tree and must be continued or aborted "
11502 "before the -m option can be used");
11503 goto done;
11505 if (edit_in_progress && fold_only) {
11506 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11507 "histedit operation is in progress in this "
11508 "work tree and must be continued or aborted "
11509 "before the -f option can be used");
11510 goto done;
11512 if (edit_in_progress && edit_only) {
11513 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11514 "histedit operation is in progress in this "
11515 "work tree and must be continued or aborted "
11516 "before the -e option can be used");
11517 goto done;
11520 if (edit_in_progress && abort_edit) {
11521 error = got_worktree_histedit_continue(&resume_commit_id,
11522 &tmp_branch, &branch, &base_commit_id, &fileindex,
11523 worktree, repo);
11524 if (error)
11525 goto done;
11526 printf("Switching work tree to %s\n",
11527 got_ref_get_symref_target(branch));
11528 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11529 branch, base_commit_id, abort_progress, &upa);
11530 if (error)
11531 goto done;
11532 printf("Histedit of %s aborted\n",
11533 got_ref_get_symref_target(branch));
11534 print_merge_progress_stats(&upa);
11535 goto done; /* nothing else to do */
11536 } else if (abort_edit) {
11537 error = got_error(GOT_ERR_NOT_HISTEDIT);
11538 goto done;
11541 error = get_author(&committer, repo, worktree);
11542 if (error)
11543 goto done;
11545 if (continue_edit) {
11546 char *path;
11548 if (!edit_in_progress) {
11549 error = got_error(GOT_ERR_NOT_HISTEDIT);
11550 goto done;
11553 error = got_worktree_get_histedit_script_path(&path, worktree);
11554 if (error)
11555 goto done;
11557 error = histedit_load_list(&histedit_cmds, path, repo);
11558 free(path);
11559 if (error)
11560 goto done;
11562 error = got_worktree_histedit_continue(&resume_commit_id,
11563 &tmp_branch, &branch, &base_commit_id, &fileindex,
11564 worktree, repo);
11565 if (error)
11566 goto done;
11568 error = got_ref_resolve(&head_commit_id, repo, branch);
11569 if (error)
11570 goto done;
11572 error = got_object_open_as_commit(&commit, repo,
11573 head_commit_id);
11574 if (error)
11575 goto done;
11576 parent_ids = got_object_commit_get_parent_ids(commit);
11577 pid = STAILQ_FIRST(parent_ids);
11578 if (pid == NULL) {
11579 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11580 goto done;
11582 error = collect_commits(&commits, head_commit_id, &pid->id,
11583 base_commit_id, got_worktree_get_path_prefix(worktree),
11584 GOT_ERR_HISTEDIT_PATH, repo);
11585 got_object_commit_close(commit);
11586 commit = NULL;
11587 if (error)
11588 goto done;
11589 } else {
11590 if (edit_in_progress) {
11591 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11592 goto done;
11595 error = got_ref_open(&branch, repo,
11596 got_worktree_get_head_ref_name(worktree), 0);
11597 if (error != NULL)
11598 goto done;
11600 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11601 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11602 "will not edit commit history of a branch outside "
11603 "the \"refs/heads/\" reference namespace");
11604 goto done;
11607 error = got_ref_resolve(&head_commit_id, repo, branch);
11608 got_ref_close(branch);
11609 branch = NULL;
11610 if (error)
11611 goto done;
11613 error = got_object_open_as_commit(&commit, repo,
11614 head_commit_id);
11615 if (error)
11616 goto done;
11617 parent_ids = got_object_commit_get_parent_ids(commit);
11618 pid = STAILQ_FIRST(parent_ids);
11619 if (pid == NULL) {
11620 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11621 goto done;
11623 error = collect_commits(&commits, head_commit_id, &pid->id,
11624 got_worktree_get_base_commit_id(worktree),
11625 got_worktree_get_path_prefix(worktree),
11626 GOT_ERR_HISTEDIT_PATH, repo);
11627 got_object_commit_close(commit);
11628 commit = NULL;
11629 if (error)
11630 goto done;
11632 if (STAILQ_EMPTY(&commits)) {
11633 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11634 goto done;
11637 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11638 &base_commit_id, &fileindex, worktree, repo);
11639 if (error)
11640 goto done;
11642 if (edit_script_path) {
11643 error = histedit_load_list(&histedit_cmds,
11644 edit_script_path, repo);
11645 if (error) {
11646 got_worktree_histedit_abort(worktree, fileindex,
11647 repo, branch, base_commit_id,
11648 abort_progress, &upa);
11649 print_merge_progress_stats(&upa);
11650 goto done;
11652 } else {
11653 const char *branch_name;
11654 branch_name = got_ref_get_symref_target(branch);
11655 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11656 branch_name += 11;
11657 error = histedit_edit_script(&histedit_cmds, &commits,
11658 branch_name, edit_logmsg_only, fold_only,
11659 edit_only, repo);
11660 if (error) {
11661 got_worktree_histedit_abort(worktree, fileindex,
11662 repo, branch, base_commit_id,
11663 abort_progress, &upa);
11664 print_merge_progress_stats(&upa);
11665 goto done;
11670 error = histedit_save_list(&histedit_cmds, worktree,
11671 repo);
11672 if (error) {
11673 got_worktree_histedit_abort(worktree, fileindex,
11674 repo, branch, base_commit_id,
11675 abort_progress, &upa);
11676 print_merge_progress_stats(&upa);
11677 goto done;
11682 error = histedit_check_script(&histedit_cmds, &commits, repo);
11683 if (error)
11684 goto done;
11686 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11687 if (resume_commit_id) {
11688 if (got_object_id_cmp(hle->commit_id,
11689 resume_commit_id) != 0)
11690 continue;
11692 resume_commit_id = NULL;
11693 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11694 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11695 error = histedit_skip_commit(hle, worktree,
11696 repo);
11697 if (error)
11698 goto done;
11699 } else {
11700 struct got_pathlist_head paths;
11701 int have_changes = 0;
11703 TAILQ_INIT(&paths);
11704 error = got_pathlist_append(&paths, "", NULL);
11705 if (error)
11706 goto done;
11707 error = got_worktree_status(worktree, &paths,
11708 repo, 0, check_local_changes, &have_changes,
11709 check_cancelled, NULL);
11710 got_pathlist_free(&paths);
11711 if (error) {
11712 if (error->code != GOT_ERR_CANCELLED)
11713 goto done;
11714 if (sigint_received || sigpipe_received)
11715 goto done;
11717 if (have_changes) {
11718 error = histedit_commit(NULL, worktree,
11719 fileindex, tmp_branch, hle,
11720 committer, repo);
11721 if (error)
11722 goto done;
11723 } else {
11724 error = got_object_open_as_commit(
11725 &commit, repo, hle->commit_id);
11726 if (error)
11727 goto done;
11728 error = show_histedit_progress(commit,
11729 hle, NULL);
11730 got_object_commit_close(commit);
11731 commit = NULL;
11732 if (error)
11733 goto done;
11736 continue;
11739 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11740 error = histedit_skip_commit(hle, worktree, repo);
11741 if (error)
11742 goto done;
11743 continue;
11746 error = got_object_open_as_commit(&commit, repo,
11747 hle->commit_id);
11748 if (error)
11749 goto done;
11750 parent_ids = got_object_commit_get_parent_ids(commit);
11751 pid = STAILQ_FIRST(parent_ids);
11753 error = got_worktree_histedit_merge_files(&merged_paths,
11754 worktree, fileindex, &pid->id, hle->commit_id, repo,
11755 update_progress, &upa, check_cancelled, NULL);
11756 if (error)
11757 goto done;
11758 got_object_commit_close(commit);
11759 commit = NULL;
11761 print_merge_progress_stats(&upa);
11762 if (upa.conflicts > 0 || upa.missing > 0 ||
11763 upa.not_deleted > 0 || upa.unversioned > 0) {
11764 if (upa.conflicts > 0) {
11765 error = show_rebase_merge_conflict(
11766 hle->commit_id, repo);
11767 if (error)
11768 goto done;
11770 got_worktree_rebase_pathlist_free(&merged_paths);
11771 break;
11774 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11775 char *id_str;
11776 error = got_object_id_str(&id_str, hle->commit_id);
11777 if (error)
11778 goto done;
11779 printf("Stopping histedit for amending commit %s\n",
11780 id_str);
11781 free(id_str);
11782 got_worktree_rebase_pathlist_free(&merged_paths);
11783 error = got_worktree_histedit_postpone(worktree,
11784 fileindex);
11785 goto done;
11788 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11789 error = histedit_skip_commit(hle, worktree, repo);
11790 if (error)
11791 goto done;
11792 continue;
11795 error = histedit_commit(&merged_paths, worktree, fileindex,
11796 tmp_branch, hle, committer, repo);
11797 got_worktree_rebase_pathlist_free(&merged_paths);
11798 if (error)
11799 goto done;
11802 if (upa.conflicts > 0 || upa.missing > 0 ||
11803 upa.not_deleted > 0 || upa.unversioned > 0) {
11804 error = got_worktree_histedit_postpone(worktree, fileindex);
11805 if (error)
11806 goto done;
11807 if (upa.conflicts > 0 && upa.missing == 0 &&
11808 upa.not_deleted == 0 && upa.unversioned == 0) {
11809 error = got_error_msg(GOT_ERR_CONFLICTS,
11810 "conflicts must be resolved before histedit "
11811 "can continue");
11812 } else if (upa.conflicts > 0) {
11813 error = got_error_msg(GOT_ERR_CONFLICTS,
11814 "conflicts must be resolved before histedit "
11815 "can continue; changes destined for some "
11816 "files were not yet merged and should be "
11817 "merged manually if required before the "
11818 "histedit operation is continued");
11819 } else {
11820 error = got_error_msg(GOT_ERR_CONFLICTS,
11821 "changes destined for some files were not "
11822 "yet merged and should be merged manually "
11823 "if required before the histedit operation "
11824 "is continued");
11826 } else
11827 error = histedit_complete(worktree, fileindex, tmp_branch,
11828 branch, repo);
11829 done:
11830 free(cwd);
11831 free(committer);
11832 free(gitconfig_path);
11833 got_object_id_queue_free(&commits);
11834 histedit_free_list(&histedit_cmds);
11835 free(head_commit_id);
11836 free(base_commit_id);
11837 free(resume_commit_id);
11838 if (commit)
11839 got_object_commit_close(commit);
11840 if (branch)
11841 got_ref_close(branch);
11842 if (tmp_branch)
11843 got_ref_close(tmp_branch);
11844 if (worktree)
11845 got_worktree_close(worktree);
11846 if (repo) {
11847 const struct got_error *close_err = got_repo_close(repo);
11848 if (error == NULL)
11849 error = close_err;
11851 if (pack_fds) {
11852 const struct got_error *pack_err =
11853 got_repo_pack_fds_close(pack_fds);
11854 if (error == NULL)
11855 error = pack_err;
11857 return error;
11860 __dead static void
11861 usage_integrate(void)
11863 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11864 exit(1);
11867 static const struct got_error *
11868 cmd_integrate(int argc, char *argv[])
11870 const struct got_error *error = NULL;
11871 struct got_repository *repo = NULL;
11872 struct got_worktree *worktree = NULL;
11873 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11874 const char *branch_arg = NULL;
11875 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11876 struct got_fileindex *fileindex = NULL;
11877 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11878 int ch;
11879 struct got_update_progress_arg upa;
11880 int *pack_fds = NULL;
11882 while ((ch = getopt(argc, argv, "")) != -1) {
11883 switch (ch) {
11884 default:
11885 usage_integrate();
11886 /* NOTREACHED */
11890 argc -= optind;
11891 argv += optind;
11893 if (argc != 1)
11894 usage_integrate();
11895 branch_arg = argv[0];
11896 #ifndef PROFILE
11897 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11898 "unveil", NULL) == -1)
11899 err(1, "pledge");
11900 #endif
11901 cwd = getcwd(NULL, 0);
11902 if (cwd == NULL) {
11903 error = got_error_from_errno("getcwd");
11904 goto done;
11907 error = got_repo_pack_fds_open(&pack_fds);
11908 if (error != NULL)
11909 goto done;
11911 error = got_worktree_open(&worktree, cwd);
11912 if (error) {
11913 if (error->code == GOT_ERR_NOT_WORKTREE)
11914 error = wrap_not_worktree_error(error, "integrate",
11915 cwd);
11916 goto done;
11919 error = check_rebase_or_histedit_in_progress(worktree);
11920 if (error)
11921 goto done;
11923 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11924 NULL, pack_fds);
11925 if (error != NULL)
11926 goto done;
11928 error = apply_unveil(got_repo_get_path(repo), 0,
11929 got_worktree_get_root_path(worktree));
11930 if (error)
11931 goto done;
11933 error = check_merge_in_progress(worktree, repo);
11934 if (error)
11935 goto done;
11937 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11938 error = got_error_from_errno("asprintf");
11939 goto done;
11942 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11943 &base_branch_ref, worktree, refname, repo);
11944 if (error)
11945 goto done;
11947 refname = strdup(got_ref_get_name(branch_ref));
11948 if (refname == NULL) {
11949 error = got_error_from_errno("strdup");
11950 got_worktree_integrate_abort(worktree, fileindex, repo,
11951 branch_ref, base_branch_ref);
11952 goto done;
11954 base_refname = strdup(got_ref_get_name(base_branch_ref));
11955 if (base_refname == NULL) {
11956 error = got_error_from_errno("strdup");
11957 got_worktree_integrate_abort(worktree, fileindex, repo,
11958 branch_ref, base_branch_ref);
11959 goto done;
11962 error = got_ref_resolve(&commit_id, repo, branch_ref);
11963 if (error)
11964 goto done;
11966 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11967 if (error)
11968 goto done;
11970 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11971 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11972 "specified branch has already been integrated");
11973 got_worktree_integrate_abort(worktree, fileindex, repo,
11974 branch_ref, base_branch_ref);
11975 goto done;
11978 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11979 if (error) {
11980 if (error->code == GOT_ERR_ANCESTRY)
11981 error = got_error(GOT_ERR_REBASE_REQUIRED);
11982 got_worktree_integrate_abort(worktree, fileindex, repo,
11983 branch_ref, base_branch_ref);
11984 goto done;
11987 memset(&upa, 0, sizeof(upa));
11988 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11989 branch_ref, base_branch_ref, update_progress, &upa,
11990 check_cancelled, NULL);
11991 if (error)
11992 goto done;
11994 printf("Integrated %s into %s\n", refname, base_refname);
11995 print_update_progress_stats(&upa);
11996 done:
11997 if (repo) {
11998 const struct got_error *close_err = got_repo_close(repo);
11999 if (error == NULL)
12000 error = close_err;
12002 if (worktree)
12003 got_worktree_close(worktree);
12004 if (pack_fds) {
12005 const struct got_error *pack_err =
12006 got_repo_pack_fds_close(pack_fds);
12007 if (error == NULL)
12008 error = pack_err;
12010 free(cwd);
12011 free(base_commit_id);
12012 free(commit_id);
12013 free(refname);
12014 free(base_refname);
12015 return error;
12018 __dead static void
12019 usage_merge(void)
12021 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
12022 getprogname());
12023 exit(1);
12026 static const struct got_error *
12027 cmd_merge(int argc, char *argv[])
12029 const struct got_error *error = NULL;
12030 struct got_worktree *worktree = NULL;
12031 struct got_repository *repo = NULL;
12032 struct got_fileindex *fileindex = NULL;
12033 char *cwd = NULL, *id_str = NULL, *author = NULL;
12034 struct got_reference *branch = NULL, *wt_branch = NULL;
12035 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12036 struct got_object_id *wt_branch_tip = NULL;
12037 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12038 int interrupt_merge = 0;
12039 struct got_update_progress_arg upa;
12040 struct got_object_id *merge_commit_id = NULL;
12041 char *branch_name = NULL;
12042 int *pack_fds = NULL;
12044 memset(&upa, 0, sizeof(upa));
12046 while ((ch = getopt(argc, argv, "acn")) != -1) {
12047 switch (ch) {
12048 case 'a':
12049 abort_merge = 1;
12050 break;
12051 case 'c':
12052 continue_merge = 1;
12053 break;
12054 case 'n':
12055 interrupt_merge = 1;
12056 break;
12057 default:
12058 usage_rebase();
12059 /* NOTREACHED */
12063 argc -= optind;
12064 argv += optind;
12066 #ifndef PROFILE
12067 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12068 "unveil", NULL) == -1)
12069 err(1, "pledge");
12070 #endif
12072 if (abort_merge && continue_merge)
12073 option_conflict('a', 'c');
12074 if (abort_merge || continue_merge) {
12075 if (argc != 0)
12076 usage_merge();
12077 } else if (argc != 1)
12078 usage_merge();
12080 cwd = getcwd(NULL, 0);
12081 if (cwd == NULL) {
12082 error = got_error_from_errno("getcwd");
12083 goto done;
12086 error = got_repo_pack_fds_open(&pack_fds);
12087 if (error != NULL)
12088 goto done;
12090 error = got_worktree_open(&worktree, cwd);
12091 if (error) {
12092 if (error->code == GOT_ERR_NOT_WORKTREE)
12093 error = wrap_not_worktree_error(error,
12094 "merge", cwd);
12095 goto done;
12098 error = got_repo_open(&repo,
12099 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12100 pack_fds);
12101 if (error != NULL)
12102 goto done;
12104 error = apply_unveil(got_repo_get_path(repo), 0,
12105 worktree ? got_worktree_get_root_path(worktree) : NULL);
12106 if (error)
12107 goto done;
12109 error = check_rebase_or_histedit_in_progress(worktree);
12110 if (error)
12111 goto done;
12113 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12114 repo);
12115 if (error)
12116 goto done;
12118 if (abort_merge) {
12119 if (!merge_in_progress) {
12120 error = got_error(GOT_ERR_NOT_MERGING);
12121 goto done;
12123 error = got_worktree_merge_continue(&branch_name,
12124 &branch_tip, &fileindex, worktree, repo);
12125 if (error)
12126 goto done;
12127 error = got_worktree_merge_abort(worktree, fileindex, repo,
12128 abort_progress, &upa);
12129 if (error)
12130 goto done;
12131 printf("Merge of %s aborted\n", branch_name);
12132 goto done; /* nothing else to do */
12135 error = get_author(&author, repo, worktree);
12136 if (error)
12137 goto done;
12139 if (continue_merge) {
12140 if (!merge_in_progress) {
12141 error = got_error(GOT_ERR_NOT_MERGING);
12142 goto done;
12144 error = got_worktree_merge_continue(&branch_name,
12145 &branch_tip, &fileindex, worktree, repo);
12146 if (error)
12147 goto done;
12148 } else {
12149 error = got_ref_open(&branch, repo, argv[0], 0);
12150 if (error != NULL)
12151 goto done;
12152 branch_name = strdup(got_ref_get_name(branch));
12153 if (branch_name == NULL) {
12154 error = got_error_from_errno("strdup");
12155 goto done;
12157 error = got_ref_resolve(&branch_tip, repo, branch);
12158 if (error)
12159 goto done;
12162 error = got_ref_open(&wt_branch, repo,
12163 got_worktree_get_head_ref_name(worktree), 0);
12164 if (error)
12165 goto done;
12166 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12167 if (error)
12168 goto done;
12169 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12170 wt_branch_tip, branch_tip, 0, repo,
12171 check_cancelled, NULL);
12172 if (error && error->code != GOT_ERR_ANCESTRY)
12173 goto done;
12175 if (!continue_merge) {
12176 error = check_path_prefix(wt_branch_tip, branch_tip,
12177 got_worktree_get_path_prefix(worktree),
12178 GOT_ERR_MERGE_PATH, repo);
12179 if (error)
12180 goto done;
12181 if (yca_id) {
12182 error = check_same_branch(wt_branch_tip, branch,
12183 yca_id, repo);
12184 if (error) {
12185 if (error->code != GOT_ERR_ANCESTRY)
12186 goto done;
12187 error = NULL;
12188 } else {
12189 static char msg[512];
12190 snprintf(msg, sizeof(msg),
12191 "cannot create a merge commit because "
12192 "%s is based on %s; %s can be integrated "
12193 "with 'got integrate' instead", branch_name,
12194 got_worktree_get_head_ref_name(worktree),
12195 branch_name);
12196 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12197 goto done;
12200 error = got_worktree_merge_prepare(&fileindex, worktree,
12201 branch, repo);
12202 if (error)
12203 goto done;
12205 error = got_worktree_merge_branch(worktree, fileindex,
12206 yca_id, branch_tip, repo, update_progress, &upa,
12207 check_cancelled, NULL);
12208 if (error)
12209 goto done;
12210 print_merge_progress_stats(&upa);
12211 if (!upa.did_something) {
12212 error = got_worktree_merge_abort(worktree, fileindex,
12213 repo, abort_progress, &upa);
12214 if (error)
12215 goto done;
12216 printf("Already up-to-date\n");
12217 goto done;
12221 if (interrupt_merge) {
12222 error = got_worktree_merge_postpone(worktree, fileindex);
12223 if (error)
12224 goto done;
12225 printf("Merge of %s interrupted on request\n", branch_name);
12226 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12227 upa.not_deleted > 0 || upa.unversioned > 0) {
12228 error = got_worktree_merge_postpone(worktree, fileindex);
12229 if (error)
12230 goto done;
12231 if (upa.conflicts > 0 && upa.missing == 0 &&
12232 upa.not_deleted == 0 && upa.unversioned == 0) {
12233 error = got_error_msg(GOT_ERR_CONFLICTS,
12234 "conflicts must be resolved before merging "
12235 "can continue");
12236 } else if (upa.conflicts > 0) {
12237 error = got_error_msg(GOT_ERR_CONFLICTS,
12238 "conflicts must be resolved before merging "
12239 "can continue; changes destined for some "
12240 "files were not yet merged and "
12241 "should be merged manually if required before the "
12242 "merge operation is continued");
12243 } else {
12244 error = got_error_msg(GOT_ERR_CONFLICTS,
12245 "changes destined for some "
12246 "files were not yet merged and should be "
12247 "merged manually if required before the "
12248 "merge operation is continued");
12250 goto done;
12251 } else {
12252 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12253 fileindex, author, NULL, 1, branch_tip, branch_name,
12254 repo, continue_merge ? print_status : NULL, NULL);
12255 if (error)
12256 goto done;
12257 error = got_worktree_merge_complete(worktree, fileindex, repo);
12258 if (error)
12259 goto done;
12260 error = got_object_id_str(&id_str, merge_commit_id);
12261 if (error)
12262 goto done;
12263 printf("Merged %s into %s: %s\n", branch_name,
12264 got_worktree_get_head_ref_name(worktree),
12265 id_str);
12268 done:
12269 free(id_str);
12270 free(merge_commit_id);
12271 free(author);
12272 free(branch_tip);
12273 free(branch_name);
12274 free(yca_id);
12275 if (branch)
12276 got_ref_close(branch);
12277 if (wt_branch)
12278 got_ref_close(wt_branch);
12279 if (worktree)
12280 got_worktree_close(worktree);
12281 if (repo) {
12282 const struct got_error *close_err = got_repo_close(repo);
12283 if (error == NULL)
12284 error = close_err;
12286 if (pack_fds) {
12287 const struct got_error *pack_err =
12288 got_repo_pack_fds_close(pack_fds);
12289 if (error == NULL)
12290 error = pack_err;
12292 return error;
12295 __dead static void
12296 usage_stage(void)
12298 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12299 "[-S] [file-path ...]\n",
12300 getprogname());
12301 exit(1);
12304 static const struct got_error *
12305 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12306 const char *path, struct got_object_id *blob_id,
12307 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12308 int dirfd, const char *de_name)
12310 const struct got_error *err = NULL;
12311 char *id_str = NULL;
12313 if (staged_status != GOT_STATUS_ADD &&
12314 staged_status != GOT_STATUS_MODIFY &&
12315 staged_status != GOT_STATUS_DELETE)
12316 return NULL;
12318 if (staged_status == GOT_STATUS_ADD ||
12319 staged_status == GOT_STATUS_MODIFY)
12320 err = got_object_id_str(&id_str, staged_blob_id);
12321 else
12322 err = got_object_id_str(&id_str, blob_id);
12323 if (err)
12324 return err;
12326 printf("%s %c %s\n", id_str, staged_status, path);
12327 free(id_str);
12328 return NULL;
12331 static const struct got_error *
12332 cmd_stage(int argc, char *argv[])
12334 const struct got_error *error = NULL;
12335 struct got_repository *repo = NULL;
12336 struct got_worktree *worktree = NULL;
12337 char *cwd = NULL;
12338 struct got_pathlist_head paths;
12339 struct got_pathlist_entry *pe;
12340 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12341 FILE *patch_script_file = NULL;
12342 const char *patch_script_path = NULL;
12343 struct choose_patch_arg cpa;
12344 int *pack_fds = NULL;
12346 TAILQ_INIT(&paths);
12348 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12349 switch (ch) {
12350 case 'l':
12351 list_stage = 1;
12352 break;
12353 case 'p':
12354 pflag = 1;
12355 break;
12356 case 'F':
12357 patch_script_path = optarg;
12358 break;
12359 case 'S':
12360 allow_bad_symlinks = 1;
12361 break;
12362 default:
12363 usage_stage();
12364 /* NOTREACHED */
12368 argc -= optind;
12369 argv += optind;
12371 #ifndef PROFILE
12372 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12373 "unveil", NULL) == -1)
12374 err(1, "pledge");
12375 #endif
12376 if (list_stage && (pflag || patch_script_path))
12377 errx(1, "-l option cannot be used with other options");
12378 if (patch_script_path && !pflag)
12379 errx(1, "-F option can only be used together with -p option");
12381 cwd = getcwd(NULL, 0);
12382 if (cwd == NULL) {
12383 error = got_error_from_errno("getcwd");
12384 goto done;
12387 error = got_repo_pack_fds_open(&pack_fds);
12388 if (error != NULL)
12389 goto done;
12391 error = got_worktree_open(&worktree, cwd);
12392 if (error) {
12393 if (error->code == GOT_ERR_NOT_WORKTREE)
12394 error = wrap_not_worktree_error(error, "stage", cwd);
12395 goto done;
12398 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12399 NULL, pack_fds);
12400 if (error != NULL)
12401 goto done;
12403 if (patch_script_path) {
12404 patch_script_file = fopen(patch_script_path, "re");
12405 if (patch_script_file == NULL) {
12406 error = got_error_from_errno2("fopen",
12407 patch_script_path);
12408 goto done;
12411 error = apply_unveil(got_repo_get_path(repo), 0,
12412 got_worktree_get_root_path(worktree));
12413 if (error)
12414 goto done;
12416 error = check_merge_in_progress(worktree, repo);
12417 if (error)
12418 goto done;
12420 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12421 if (error)
12422 goto done;
12424 if (list_stage)
12425 error = got_worktree_status(worktree, &paths, repo, 0,
12426 print_stage, NULL, check_cancelled, NULL);
12427 else {
12428 cpa.patch_script_file = patch_script_file;
12429 cpa.action = "stage";
12430 error = got_worktree_stage(worktree, &paths,
12431 pflag ? NULL : print_status, NULL,
12432 pflag ? choose_patch : NULL, &cpa,
12433 allow_bad_symlinks, repo);
12435 done:
12436 if (patch_script_file && fclose(patch_script_file) == EOF &&
12437 error == NULL)
12438 error = got_error_from_errno2("fclose", patch_script_path);
12439 if (repo) {
12440 const struct got_error *close_err = got_repo_close(repo);
12441 if (error == NULL)
12442 error = close_err;
12444 if (worktree)
12445 got_worktree_close(worktree);
12446 if (pack_fds) {
12447 const struct got_error *pack_err =
12448 got_repo_pack_fds_close(pack_fds);
12449 if (error == NULL)
12450 error = pack_err;
12452 TAILQ_FOREACH(pe, &paths, entry)
12453 free((char *)pe->path);
12454 got_pathlist_free(&paths);
12455 free(cwd);
12456 return error;
12459 __dead static void
12460 usage_unstage(void)
12462 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12463 "[file-path ...]\n",
12464 getprogname());
12465 exit(1);
12469 static const struct got_error *
12470 cmd_unstage(int argc, char *argv[])
12472 const struct got_error *error = NULL;
12473 struct got_repository *repo = NULL;
12474 struct got_worktree *worktree = NULL;
12475 char *cwd = NULL;
12476 struct got_pathlist_head paths;
12477 struct got_pathlist_entry *pe;
12478 int ch, pflag = 0;
12479 struct got_update_progress_arg upa;
12480 FILE *patch_script_file = NULL;
12481 const char *patch_script_path = NULL;
12482 struct choose_patch_arg cpa;
12483 int *pack_fds = NULL;
12485 TAILQ_INIT(&paths);
12487 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12488 switch (ch) {
12489 case 'p':
12490 pflag = 1;
12491 break;
12492 case 'F':
12493 patch_script_path = optarg;
12494 break;
12495 default:
12496 usage_unstage();
12497 /* NOTREACHED */
12501 argc -= optind;
12502 argv += optind;
12504 #ifndef PROFILE
12505 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12506 "unveil", NULL) == -1)
12507 err(1, "pledge");
12508 #endif
12509 if (patch_script_path && !pflag)
12510 errx(1, "-F option can only be used together with -p option");
12512 cwd = getcwd(NULL, 0);
12513 if (cwd == NULL) {
12514 error = got_error_from_errno("getcwd");
12515 goto done;
12518 error = got_repo_pack_fds_open(&pack_fds);
12519 if (error != NULL)
12520 goto done;
12522 error = got_worktree_open(&worktree, cwd);
12523 if (error) {
12524 if (error->code == GOT_ERR_NOT_WORKTREE)
12525 error = wrap_not_worktree_error(error, "unstage", cwd);
12526 goto done;
12529 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12530 NULL, pack_fds);
12531 if (error != NULL)
12532 goto done;
12534 if (patch_script_path) {
12535 patch_script_file = fopen(patch_script_path, "re");
12536 if (patch_script_file == NULL) {
12537 error = got_error_from_errno2("fopen",
12538 patch_script_path);
12539 goto done;
12543 error = apply_unveil(got_repo_get_path(repo), 0,
12544 got_worktree_get_root_path(worktree));
12545 if (error)
12546 goto done;
12548 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12549 if (error)
12550 goto done;
12552 cpa.patch_script_file = patch_script_file;
12553 cpa.action = "unstage";
12554 memset(&upa, 0, sizeof(upa));
12555 error = got_worktree_unstage(worktree, &paths, update_progress,
12556 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12557 if (!error)
12558 print_merge_progress_stats(&upa);
12559 done:
12560 if (patch_script_file && fclose(patch_script_file) == EOF &&
12561 error == NULL)
12562 error = got_error_from_errno2("fclose", patch_script_path);
12563 if (repo) {
12564 const struct got_error *close_err = got_repo_close(repo);
12565 if (error == NULL)
12566 error = close_err;
12568 if (worktree)
12569 got_worktree_close(worktree);
12570 if (pack_fds) {
12571 const struct got_error *pack_err =
12572 got_repo_pack_fds_close(pack_fds);
12573 if (error == NULL)
12574 error = pack_err;
12576 TAILQ_FOREACH(pe, &paths, entry)
12577 free((char *)pe->path);
12578 got_pathlist_free(&paths);
12579 free(cwd);
12580 return error;
12583 __dead static void
12584 usage_cat(void)
12586 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12587 "arg1 [arg2 ...]\n", getprogname());
12588 exit(1);
12591 static const struct got_error *
12592 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12594 const struct got_error *err;
12595 struct got_blob_object *blob;
12596 int fd = -1;
12598 fd = got_opentempfd();
12599 if (fd == -1)
12600 return got_error_from_errno("got_opentempfd");
12602 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12603 if (err)
12604 goto done;
12606 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12607 done:
12608 if (fd != -1 && close(fd) == -1 && err == NULL)
12609 err = got_error_from_errno("close");
12610 if (blob)
12611 got_object_blob_close(blob);
12612 return err;
12615 static const struct got_error *
12616 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12618 const struct got_error *err;
12619 struct got_tree_object *tree;
12620 int nentries, i;
12622 err = got_object_open_as_tree(&tree, repo, id);
12623 if (err)
12624 return err;
12626 nentries = got_object_tree_get_nentries(tree);
12627 for (i = 0; i < nentries; i++) {
12628 struct got_tree_entry *te;
12629 char *id_str;
12630 if (sigint_received || sigpipe_received)
12631 break;
12632 te = got_object_tree_get_entry(tree, i);
12633 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12634 if (err)
12635 break;
12636 fprintf(outfile, "%s %.7o %s\n", id_str,
12637 got_tree_entry_get_mode(te),
12638 got_tree_entry_get_name(te));
12639 free(id_str);
12642 got_object_tree_close(tree);
12643 return err;
12646 static const struct got_error *
12647 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12649 const struct got_error *err;
12650 struct got_commit_object *commit;
12651 const struct got_object_id_queue *parent_ids;
12652 struct got_object_qid *pid;
12653 char *id_str = NULL;
12654 const char *logmsg = NULL;
12655 char gmtoff[6];
12657 err = got_object_open_as_commit(&commit, repo, id);
12658 if (err)
12659 return err;
12661 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12662 if (err)
12663 goto done;
12665 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12666 parent_ids = got_object_commit_get_parent_ids(commit);
12667 fprintf(outfile, "numparents %d\n",
12668 got_object_commit_get_nparents(commit));
12669 STAILQ_FOREACH(pid, parent_ids, entry) {
12670 char *pid_str;
12671 err = got_object_id_str(&pid_str, &pid->id);
12672 if (err)
12673 goto done;
12674 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12675 free(pid_str);
12677 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12678 got_object_commit_get_author_gmtoff(commit));
12679 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12680 got_object_commit_get_author(commit),
12681 (long long)got_object_commit_get_author_time(commit),
12682 gmtoff);
12684 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12685 got_object_commit_get_committer_gmtoff(commit));
12686 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12687 got_object_commit_get_committer(commit),
12688 (long long)got_object_commit_get_committer_time(commit),
12689 gmtoff);
12691 logmsg = got_object_commit_get_logmsg_raw(commit);
12692 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12693 fprintf(outfile, "%s", logmsg);
12694 done:
12695 free(id_str);
12696 got_object_commit_close(commit);
12697 return err;
12700 static const struct got_error *
12701 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12703 const struct got_error *err;
12704 struct got_tag_object *tag;
12705 char *id_str = NULL;
12706 const char *tagmsg = NULL;
12707 char gmtoff[6];
12709 err = got_object_open_as_tag(&tag, repo, id);
12710 if (err)
12711 return err;
12713 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12714 if (err)
12715 goto done;
12717 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12719 switch (got_object_tag_get_object_type(tag)) {
12720 case GOT_OBJ_TYPE_BLOB:
12721 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12722 GOT_OBJ_LABEL_BLOB);
12723 break;
12724 case GOT_OBJ_TYPE_TREE:
12725 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12726 GOT_OBJ_LABEL_TREE);
12727 break;
12728 case GOT_OBJ_TYPE_COMMIT:
12729 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12730 GOT_OBJ_LABEL_COMMIT);
12731 break;
12732 case GOT_OBJ_TYPE_TAG:
12733 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12734 GOT_OBJ_LABEL_TAG);
12735 break;
12736 default:
12737 break;
12740 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12741 got_object_tag_get_name(tag));
12743 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12744 got_object_tag_get_tagger_gmtoff(tag));
12745 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12746 got_object_tag_get_tagger(tag),
12747 (long long)got_object_tag_get_tagger_time(tag),
12748 gmtoff);
12750 tagmsg = got_object_tag_get_message(tag);
12751 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12752 fprintf(outfile, "%s", tagmsg);
12753 done:
12754 free(id_str);
12755 got_object_tag_close(tag);
12756 return err;
12759 static const struct got_error *
12760 cmd_cat(int argc, char *argv[])
12762 const struct got_error *error;
12763 struct got_repository *repo = NULL;
12764 struct got_worktree *worktree = NULL;
12765 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12766 const char *commit_id_str = NULL;
12767 struct got_object_id *id = NULL, *commit_id = NULL;
12768 struct got_commit_object *commit = NULL;
12769 int ch, obj_type, i, force_path = 0;
12770 struct got_reflist_head refs;
12771 int *pack_fds = NULL;
12773 TAILQ_INIT(&refs);
12775 #ifndef PROFILE
12776 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12777 NULL) == -1)
12778 err(1, "pledge");
12779 #endif
12781 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12782 switch (ch) {
12783 case 'c':
12784 commit_id_str = optarg;
12785 break;
12786 case 'r':
12787 repo_path = realpath(optarg, NULL);
12788 if (repo_path == NULL)
12789 return got_error_from_errno2("realpath",
12790 optarg);
12791 got_path_strip_trailing_slashes(repo_path);
12792 break;
12793 case 'P':
12794 force_path = 1;
12795 break;
12796 default:
12797 usage_cat();
12798 /* NOTREACHED */
12802 argc -= optind;
12803 argv += optind;
12805 cwd = getcwd(NULL, 0);
12806 if (cwd == NULL) {
12807 error = got_error_from_errno("getcwd");
12808 goto done;
12811 error = got_repo_pack_fds_open(&pack_fds);
12812 if (error != NULL)
12813 goto done;
12815 if (repo_path == NULL) {
12816 error = got_worktree_open(&worktree, cwd);
12817 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12818 goto done;
12819 if (worktree) {
12820 repo_path = strdup(
12821 got_worktree_get_repo_path(worktree));
12822 if (repo_path == NULL) {
12823 error = got_error_from_errno("strdup");
12824 goto done;
12827 /* Release work tree lock. */
12828 got_worktree_close(worktree);
12829 worktree = NULL;
12833 if (repo_path == NULL) {
12834 repo_path = strdup(cwd);
12835 if (repo_path == NULL)
12836 return got_error_from_errno("strdup");
12839 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12840 free(repo_path);
12841 if (error != NULL)
12842 goto done;
12844 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12845 if (error)
12846 goto done;
12848 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12849 if (error)
12850 goto done;
12852 if (commit_id_str == NULL)
12853 commit_id_str = GOT_REF_HEAD;
12854 error = got_repo_match_object_id(&commit_id, NULL,
12855 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12856 if (error)
12857 goto done;
12859 error = got_object_open_as_commit(&commit, repo, commit_id);
12860 if (error)
12861 goto done;
12863 for (i = 0; i < argc; i++) {
12864 if (force_path) {
12865 error = got_object_id_by_path(&id, repo, commit,
12866 argv[i]);
12867 if (error)
12868 break;
12869 } else {
12870 error = got_repo_match_object_id(&id, &label, argv[i],
12871 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12872 repo);
12873 if (error) {
12874 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12875 error->code != GOT_ERR_NOT_REF)
12876 break;
12877 error = got_object_id_by_path(&id, repo,
12878 commit, argv[i]);
12879 if (error)
12880 break;
12884 error = got_object_get_type(&obj_type, repo, id);
12885 if (error)
12886 break;
12888 switch (obj_type) {
12889 case GOT_OBJ_TYPE_BLOB:
12890 error = cat_blob(id, repo, stdout);
12891 break;
12892 case GOT_OBJ_TYPE_TREE:
12893 error = cat_tree(id, repo, stdout);
12894 break;
12895 case GOT_OBJ_TYPE_COMMIT:
12896 error = cat_commit(id, repo, stdout);
12897 break;
12898 case GOT_OBJ_TYPE_TAG:
12899 error = cat_tag(id, repo, stdout);
12900 break;
12901 default:
12902 error = got_error(GOT_ERR_OBJ_TYPE);
12903 break;
12905 if (error)
12906 break;
12907 free(label);
12908 label = NULL;
12909 free(id);
12910 id = NULL;
12912 done:
12913 free(label);
12914 free(id);
12915 free(commit_id);
12916 if (commit)
12917 got_object_commit_close(commit);
12918 if (worktree)
12919 got_worktree_close(worktree);
12920 if (repo) {
12921 const struct got_error *close_err = got_repo_close(repo);
12922 if (error == NULL)
12923 error = close_err;
12925 if (pack_fds) {
12926 const struct got_error *pack_err =
12927 got_repo_pack_fds_close(pack_fds);
12928 if (error == NULL)
12929 error = pack_err;
12932 got_ref_list_free(&refs);
12933 return error;
12936 __dead static void
12937 usage_info(void)
12939 fprintf(stderr, "usage: %s info [path ...]\n",
12940 getprogname());
12941 exit(1);
12944 static const struct got_error *
12945 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12946 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12947 struct got_object_id *commit_id)
12949 const struct got_error *err = NULL;
12950 char *id_str = NULL;
12951 char datebuf[128];
12952 struct tm mytm, *tm;
12953 struct got_pathlist_head *paths = arg;
12954 struct got_pathlist_entry *pe;
12957 * Clear error indication from any of the path arguments which
12958 * would cause this file index entry to be displayed.
12960 TAILQ_FOREACH(pe, paths, entry) {
12961 if (got_path_cmp(path, pe->path, strlen(path),
12962 pe->path_len) == 0 ||
12963 got_path_is_child(path, pe->path, pe->path_len))
12964 pe->data = NULL; /* no error */
12967 printf(GOT_COMMIT_SEP_STR);
12968 if (S_ISLNK(mode))
12969 printf("symlink: %s\n", path);
12970 else if (S_ISREG(mode)) {
12971 printf("file: %s\n", path);
12972 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12973 } else if (S_ISDIR(mode))
12974 printf("directory: %s\n", path);
12975 else
12976 printf("something: %s\n", path);
12978 tm = localtime_r(&mtime, &mytm);
12979 if (tm == NULL)
12980 return NULL;
12981 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12982 return got_error(GOT_ERR_NO_SPACE);
12983 printf("timestamp: %s\n", datebuf);
12985 if (blob_id) {
12986 err = got_object_id_str(&id_str, blob_id);
12987 if (err)
12988 return err;
12989 printf("based on blob: %s\n", id_str);
12990 free(id_str);
12993 if (staged_blob_id) {
12994 err = got_object_id_str(&id_str, staged_blob_id);
12995 if (err)
12996 return err;
12997 printf("based on staged blob: %s\n", id_str);
12998 free(id_str);
13001 if (commit_id) {
13002 err = got_object_id_str(&id_str, commit_id);
13003 if (err)
13004 return err;
13005 printf("based on commit: %s\n", id_str);
13006 free(id_str);
13009 return NULL;
13012 static const struct got_error *
13013 cmd_info(int argc, char *argv[])
13015 const struct got_error *error = NULL;
13016 struct got_worktree *worktree = NULL;
13017 char *cwd = NULL, *id_str = NULL;
13018 struct got_pathlist_head paths;
13019 struct got_pathlist_entry *pe;
13020 char *uuidstr = NULL;
13021 int ch, show_files = 0;
13023 TAILQ_INIT(&paths);
13025 while ((ch = getopt(argc, argv, "")) != -1) {
13026 switch (ch) {
13027 default:
13028 usage_info();
13029 /* NOTREACHED */
13033 argc -= optind;
13034 argv += optind;
13036 #ifndef PROFILE
13037 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13038 NULL) == -1)
13039 err(1, "pledge");
13040 #endif
13041 cwd = getcwd(NULL, 0);
13042 if (cwd == NULL) {
13043 error = got_error_from_errno("getcwd");
13044 goto done;
13047 error = got_worktree_open(&worktree, cwd);
13048 if (error) {
13049 if (error->code == GOT_ERR_NOT_WORKTREE)
13050 error = wrap_not_worktree_error(error, "info", cwd);
13051 goto done;
13054 #ifndef PROFILE
13055 /* Remove "wpath cpath proc exec sendfd" promises. */
13056 if (pledge("stdio rpath flock unveil", NULL) == -1)
13057 err(1, "pledge");
13058 #endif
13059 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13060 if (error)
13061 goto done;
13063 if (argc >= 1) {
13064 error = get_worktree_paths_from_argv(&paths, argc, argv,
13065 worktree);
13066 if (error)
13067 goto done;
13068 show_files = 1;
13071 error = got_object_id_str(&id_str,
13072 got_worktree_get_base_commit_id(worktree));
13073 if (error)
13074 goto done;
13076 error = got_worktree_get_uuid(&uuidstr, worktree);
13077 if (error)
13078 goto done;
13080 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13081 printf("work tree base commit: %s\n", id_str);
13082 printf("work tree path prefix: %s\n",
13083 got_worktree_get_path_prefix(worktree));
13084 printf("work tree branch reference: %s\n",
13085 got_worktree_get_head_ref_name(worktree));
13086 printf("work tree UUID: %s\n", uuidstr);
13087 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13089 if (show_files) {
13090 struct got_pathlist_entry *pe;
13091 TAILQ_FOREACH(pe, &paths, entry) {
13092 if (pe->path_len == 0)
13093 continue;
13095 * Assume this path will fail. This will be corrected
13096 * in print_path_info() in case the path does suceeed.
13098 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13100 error = got_worktree_path_info(worktree, &paths,
13101 print_path_info, &paths, check_cancelled, NULL);
13102 if (error)
13103 goto done;
13104 TAILQ_FOREACH(pe, &paths, entry) {
13105 if (pe->data != NULL) {
13106 const struct got_error *perr;
13108 perr = pe->data;
13109 error = got_error_fmt(perr->code, "%s",
13110 pe->path);
13111 break;
13115 done:
13116 if (worktree)
13117 got_worktree_close(worktree);
13118 TAILQ_FOREACH(pe, &paths, entry)
13119 free((char *)pe->path);
13120 got_pathlist_free(&paths);
13121 free(cwd);
13122 free(id_str);
13123 free(uuidstr);
13124 return error;