Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
42 #include "got_compat.h"
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-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 ssize_t linelen;
400 struct stat st, st2;
401 FILE *fp = NULL;
402 size_t len, logmsg_len;
403 char *initial_content_stripped = NULL, *buf = NULL, *s;
405 *logmsg = NULL;
407 if (stat(logmsg_path, &st) == -1)
408 return got_error_from_errno2("stat", logmsg_path);
410 if (spawn_editor(editor, logmsg_path) == -1)
411 return got_error_from_errno("failed spawning editor");
413 if (stat(logmsg_path, &st2) == -1)
414 return got_error_from_errno("stat");
416 if (require_modification &&
417 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
418 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
419 "no changes made to commit message, aborting");
421 /*
422 * Set up a stripped version of the initial content without comments
423 * and blank lines. We need this in order to check if the message
424 * has in fact been edited.
425 */
426 initial_content_stripped = malloc(initial_content_len + 1);
427 if (initial_content_stripped == NULL)
428 return got_error_from_errno("malloc");
429 initial_content_stripped[0] = '\0';
431 buf = strdup(initial_content);
432 if (buf == NULL) {
433 err = got_error_from_errno("strdup");
434 goto done;
436 s = buf;
437 len = 0;
438 while ((line = strsep(&s, "\n")) != NULL) {
439 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
440 continue; /* remove comments and leading empty lines */
441 len = strlcat(initial_content_stripped, line,
442 initial_content_len + 1);
443 if (len >= initial_content_len + 1) {
444 err = got_error(GOT_ERR_NO_SPACE);
445 goto done;
448 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
449 initial_content_stripped[len - 1] = '\0';
450 len--;
453 logmsg_len = st2.st_size;
454 *logmsg = malloc(logmsg_len + 1);
455 if (*logmsg == NULL)
456 return got_error_from_errno("malloc");
457 (*logmsg)[0] = '\0';
459 fp = fopen(logmsg_path, "re");
460 if (fp == NULL) {
461 err = got_error_from_errno("fopen");
462 goto done;
465 len = 0;
466 while ((linelen = getline(&line, &linesize, fp)) != -1) {
467 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
468 continue; /* remove comments and leading empty lines */
469 len = strlcat(*logmsg, line, logmsg_len + 1);
470 if (len >= logmsg_len + 1) {
471 err = got_error(GOT_ERR_NO_SPACE);
472 goto done;
475 free(line);
476 if (ferror(fp)) {
477 err = got_ferror(fp, GOT_ERR_IO);
478 goto done;
480 while (len > 0 && (*logmsg)[len - 1] == '\n') {
481 (*logmsg)[len - 1] = '\0';
482 len--;
485 if (len == 0) {
486 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
487 "commit message cannot be empty, aborting");
488 goto done;
490 if (require_modification &&
491 strcmp(*logmsg, initial_content_stripped) == 0)
492 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
493 "no changes made to commit message, aborting");
494 done:
495 free(initial_content_stripped);
496 free(buf);
497 if (fp && fclose(fp) == EOF && err == NULL)
498 err = got_error_from_errno("fclose");
499 if (err) {
500 free(*logmsg);
501 *logmsg = NULL;
503 return err;
506 static const struct got_error *
507 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
508 const char *path_dir, const char *branch_name)
510 char *initial_content = NULL;
511 const struct got_error *err = NULL;
512 int initial_content_len;
513 int fd = -1;
515 initial_content_len = asprintf(&initial_content,
516 "\n# %s to be imported to branch %s\n", path_dir,
517 branch_name);
518 if (initial_content_len == -1)
519 return got_error_from_errno("asprintf");
521 err = got_opentemp_named_fd(logmsg_path, &fd,
522 GOT_TMPDIR_STR "/got-importmsg");
523 if (err)
524 goto done;
526 if (write(fd, initial_content, initial_content_len) == -1) {
527 err = got_error_from_errno2("write", *logmsg_path);
528 goto done;
531 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
532 initial_content_len, 1);
533 done:
534 if (fd != -1 && close(fd) == -1 && err == NULL)
535 err = got_error_from_errno2("close", *logmsg_path);
536 free(initial_content);
537 if (err) {
538 free(*logmsg_path);
539 *logmsg_path = NULL;
541 return err;
544 static const struct got_error *
545 import_progress(void *arg, const char *path)
547 printf("A %s\n", path);
548 return NULL;
551 static const struct got_error *
552 valid_author(const char *author)
554 const char *email = author;
556 /*
557 * Git' expects the author (or committer) to be in the form
558 * "name <email>", which are mostly free form (see the
559 * "committer" description in git-fast-import(1)). We're only
560 * doing this to avoid git's object parser breaking on commits
561 * we create.
562 */
564 while (*author && *author != '\n' && *author != '<' && *author != '>')
565 author++;
566 if (*author++ != '<')
567 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
568 while (*author && *author != '\n' && *author != '<' && *author != '>')
569 author++;
570 if (strcmp(author, ">") != 0)
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 return NULL;
575 static const struct got_error *
576 get_author(char **author, struct got_repository *repo,
577 struct got_worktree *worktree)
579 const struct got_error *err = NULL;
580 const char *got_author = NULL, *name, *email;
581 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
583 *author = NULL;
585 if (worktree)
586 worktree_conf = got_worktree_get_gotconfig(worktree);
587 repo_conf = got_repo_get_gotconfig(repo);
589 /*
590 * Priority of potential author information sources, from most
591 * significant to least significant:
592 * 1) work tree's .got/got.conf file
593 * 2) repository's got.conf file
594 * 3) repository's git config file
595 * 4) environment variables
596 * 5) global git config files (in user's home directory or /etc)
597 */
599 if (worktree_conf)
600 got_author = got_gotconfig_get_author(worktree_conf);
601 if (got_author == NULL)
602 got_author = got_gotconfig_get_author(repo_conf);
603 if (got_author == NULL) {
604 name = got_repo_get_gitconfig_author_name(repo);
605 email = got_repo_get_gitconfig_author_email(repo);
606 if (name && email) {
607 if (asprintf(author, "%s <%s>", name, email) == -1)
608 return got_error_from_errno("asprintf");
609 return NULL;
612 got_author = getenv("GOT_AUTHOR");
613 if (got_author == NULL) {
614 name = got_repo_get_global_gitconfig_author_name(repo);
615 email = got_repo_get_global_gitconfig_author_email(
616 repo);
617 if (name && email) {
618 if (asprintf(author, "%s <%s>", name, email)
619 == -1)
620 return got_error_from_errno("asprintf");
621 return NULL;
623 /* TODO: Look up user in password database? */
624 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
628 *author = strdup(got_author);
629 if (*author == NULL)
630 return got_error_from_errno("strdup");
632 err = valid_author(*author);
633 if (err) {
634 free(*author);
635 *author = NULL;
637 return err;
640 static const struct got_error *
641 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const char *got_allowed_signers = NULL;
645 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
647 *allowed_signers = NULL;
649 if (worktree)
650 worktree_conf = got_worktree_get_gotconfig(worktree);
651 repo_conf = got_repo_get_gotconfig(repo);
653 /*
654 * Priority of potential author information sources, from most
655 * significant to least significant:
656 * 1) work tree's .got/got.conf file
657 * 2) repository's got.conf file
658 */
660 if (worktree_conf)
661 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
662 worktree_conf);
663 if (got_allowed_signers == NULL)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 repo_conf);
667 if (got_allowed_signers) {
668 *allowed_signers = strdup(got_allowed_signers);
669 if (*allowed_signers == NULL)
670 return got_error_from_errno("strdup");
672 return NULL;
675 static const struct got_error *
676 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
677 struct got_worktree *worktree)
679 const char *got_revoked_signers = NULL;
680 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
682 *revoked_signers = NULL;
684 if (worktree)
685 worktree_conf = got_worktree_get_gotconfig(worktree);
686 repo_conf = got_repo_get_gotconfig(repo);
688 /*
689 * Priority of potential author information sources, from most
690 * significant to least significant:
691 * 1) work tree's .got/got.conf file
692 * 2) repository's got.conf file
693 */
695 if (worktree_conf)
696 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
697 worktree_conf);
698 if (got_revoked_signers == NULL)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 repo_conf);
702 if (got_revoked_signers) {
703 *revoked_signers = strdup(got_revoked_signers);
704 if (*revoked_signers == NULL)
705 return got_error_from_errno("strdup");
707 return NULL;
710 static const struct got_error *
711 get_signer_id(char **signer_id, struct got_repository *repo,
712 struct got_worktree *worktree)
714 const char *got_signer_id = NULL;
715 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
717 *signer_id = NULL;
719 if (worktree)
720 worktree_conf = got_worktree_get_gotconfig(worktree);
721 repo_conf = got_repo_get_gotconfig(repo);
723 /*
724 * Priority of potential author information sources, from most
725 * significant to least significant:
726 * 1) work tree's .got/got.conf file
727 * 2) repository's got.conf file
728 */
730 if (worktree_conf)
731 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
732 if (got_signer_id == NULL)
733 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
735 if (got_signer_id) {
736 *signer_id = strdup(got_signer_id);
737 if (*signer_id == NULL)
738 return got_error_from_errno("strdup");
740 return NULL;
743 static const struct got_error *
744 get_gitconfig_path(char **gitconfig_path)
746 const char *homedir = getenv("HOME");
748 *gitconfig_path = NULL;
749 if (homedir) {
750 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
751 return got_error_from_errno("asprintf");
754 return NULL;
757 static const struct got_error *
758 cmd_import(int argc, char *argv[])
760 const struct got_error *error = NULL;
761 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
762 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
763 const char *branch_name = "main";
764 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
765 struct got_repository *repo = NULL;
766 struct got_reference *branch_ref = NULL, *head_ref = NULL;
767 struct got_object_id *new_commit_id = NULL;
768 int ch;
769 struct got_pathlist_head ignores;
770 struct got_pathlist_entry *pe;
771 int preserve_logmsg = 0;
772 int *pack_fds = NULL;
774 TAILQ_INIT(&ignores);
776 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'm':
782 logmsg = strdup(optarg);
783 if (logmsg == NULL) {
784 error = got_error_from_errno("strdup");
785 goto done;
787 break;
788 case 'r':
789 repo_path = realpath(optarg, NULL);
790 if (repo_path == NULL) {
791 error = got_error_from_errno2("realpath",
792 optarg);
793 goto done;
795 break;
796 case 'I':
797 if (optarg[0] == '\0')
798 break;
799 error = got_pathlist_insert(&pe, &ignores, optarg,
800 NULL);
801 if (error)
802 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 #ifndef PROFILE
814 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
815 "unveil",
816 NULL) == -1)
817 err(1, "pledge");
818 #endif
819 if (argc != 1)
820 usage_import();
822 if (repo_path == NULL) {
823 repo_path = getcwd(NULL, 0);
824 if (repo_path == NULL)
825 return got_error_from_errno("getcwd");
827 got_path_strip_trailing_slashes(repo_path);
828 error = get_gitconfig_path(&gitconfig_path);
829 if (error)
830 goto done;
831 error = got_repo_pack_fds_open(&pack_fds);
832 if (error != NULL)
833 goto done;
834 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
835 if (error)
836 goto done;
838 error = get_author(&author, repo, NULL);
839 if (error)
840 return error;
842 /*
843 * Don't let the user create a branch name with a leading '-'.
844 * While technically a valid reference name, this case is usually
845 * an unintended typo.
846 */
847 if (branch_name[0] == '-')
848 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
850 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
851 error = got_error_from_errno("asprintf");
852 goto done;
855 error = got_ref_open(&branch_ref, repo, refname, 0);
856 if (error) {
857 if (error->code != GOT_ERR_NOT_REF)
858 goto done;
859 } else {
860 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
861 "import target branch already exists");
862 goto done;
865 path_dir = realpath(argv[0], NULL);
866 if (path_dir == NULL) {
867 error = got_error_from_errno2("realpath", argv[0]);
868 goto done;
870 got_path_strip_trailing_slashes(path_dir);
872 /*
873 * unveil(2) traverses exec(2); if an editor is used we have
874 * to apply unveil after the log message has been written.
875 */
876 if (logmsg == NULL || strlen(logmsg) == 0) {
877 error = get_editor(&editor);
878 if (error)
879 goto done;
880 free(logmsg);
881 error = collect_import_msg(&logmsg, &logmsg_path, editor,
882 path_dir, refname);
883 if (error) {
884 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
885 logmsg_path != NULL)
886 preserve_logmsg = 1;
887 goto done;
891 if (unveil(path_dir, "r") != 0) {
892 error = got_error_from_errno2("unveil", path_dir);
893 if (logmsg_path)
894 preserve_logmsg = 1;
895 goto done;
898 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
899 if (error) {
900 if (logmsg_path)
901 preserve_logmsg = 1;
902 goto done;
905 error = got_repo_import(&new_commit_id, path_dir, logmsg,
906 author, &ignores, repo, import_progress, NULL);
907 if (error) {
908 if (logmsg_path)
909 preserve_logmsg = 1;
910 goto done;
913 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
914 if (error) {
915 if (logmsg_path)
916 preserve_logmsg = 1;
917 goto done;
920 error = got_ref_write(branch_ref, repo);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_object_id_str(&id_str, new_commit_id);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
935 if (error) {
936 if (error->code != GOT_ERR_NOT_REF) {
937 if (logmsg_path)
938 preserve_logmsg = 1;
939 goto done;
942 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
943 branch_ref);
944 if (error) {
945 if (logmsg_path)
946 preserve_logmsg = 1;
947 goto done;
950 error = got_ref_write(head_ref, repo);
951 if (error) {
952 if (logmsg_path)
953 preserve_logmsg = 1;
954 goto done;
958 printf("Created branch %s with commit %s\n",
959 got_ref_get_name(branch_ref), id_str);
960 done:
961 if (pack_fds) {
962 const struct got_error *pack_err =
963 got_repo_pack_fds_close(pack_fds);
964 if (error == NULL)
965 error = pack_err;
967 if (preserve_logmsg) {
968 fprintf(stderr, "%s: log message preserved in %s\n",
969 getprogname(), logmsg_path);
970 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
971 error = got_error_from_errno2("unlink", logmsg_path);
972 free(logmsg);
973 free(logmsg_path);
974 free(repo_path);
975 free(editor);
976 free(refname);
977 free(new_commit_id);
978 free(id_str);
979 free(author);
980 free(gitconfig_path);
981 if (branch_ref)
982 got_ref_close(branch_ref);
983 if (head_ref)
984 got_ref_close(head_ref);
985 return error;
988 __dead static void
989 usage_clone(void)
991 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
992 "[-R reference] repository-url [directory]\n", getprogname());
993 exit(1);
996 struct got_fetch_progress_arg {
997 char last_scaled_size[FMT_SCALED_STRSIZE];
998 int last_p_indexed;
999 int last_p_resolved;
1000 int verbosity;
1002 struct got_repository *repo;
1004 int create_configs;
1005 int configs_created;
1006 struct {
1007 struct got_pathlist_head *symrefs;
1008 struct got_pathlist_head *wanted_branches;
1009 struct got_pathlist_head *wanted_refs;
1010 const char *proto;
1011 const char *host;
1012 const char *port;
1013 const char *remote_repo_path;
1014 const char *git_url;
1015 int fetch_all_branches;
1016 int mirror_references;
1017 } config_info;
1020 /* XXX forward declaration */
1021 static const struct got_error *
1022 create_config_files(const char *proto, const char *host, const char *port,
1023 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1024 int mirror_references, struct got_pathlist_head *symrefs,
1025 struct got_pathlist_head *wanted_branches,
1026 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1028 static const struct got_error *
1029 fetch_progress(void *arg, const char *message, off_t packfile_size,
1030 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1032 const struct got_error *err = NULL;
1033 struct got_fetch_progress_arg *a = arg;
1034 char scaled_size[FMT_SCALED_STRSIZE];
1035 int p_indexed, p_resolved;
1036 int print_size = 0, print_indexed = 0, print_resolved = 0;
1039 * In order to allow a failed clone to be resumed with 'got fetch'
1040 * we try to create configuration files as soon as possible.
1041 * Once the server has sent information about its default branch
1042 * we have all required information.
1044 if (a->create_configs && !a->configs_created &&
1045 !TAILQ_EMPTY(a->config_info.symrefs)) {
1046 err = create_config_files(a->config_info.proto,
1047 a->config_info.host, a->config_info.port,
1048 a->config_info.remote_repo_path,
1049 a->config_info.git_url,
1050 a->config_info.fetch_all_branches,
1051 a->config_info.mirror_references,
1052 a->config_info.symrefs,
1053 a->config_info.wanted_branches,
1054 a->config_info.wanted_refs, a->repo);
1055 if (err)
1056 return err;
1057 a->configs_created = 1;
1060 if (a->verbosity < 0)
1061 return NULL;
1063 if (message && message[0] != '\0') {
1064 printf("\rserver: %s", message);
1065 fflush(stdout);
1066 return NULL;
1069 if (packfile_size > 0 || nobj_indexed > 0) {
1070 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1071 (a->last_scaled_size[0] == '\0' ||
1072 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1073 print_size = 1;
1074 if (strlcpy(a->last_scaled_size, scaled_size,
1075 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1076 return got_error(GOT_ERR_NO_SPACE);
1078 if (nobj_indexed > 0) {
1079 p_indexed = (nobj_indexed * 100) / nobj_total;
1080 if (p_indexed != a->last_p_indexed) {
1081 a->last_p_indexed = p_indexed;
1082 print_indexed = 1;
1083 print_size = 1;
1086 if (nobj_resolved > 0) {
1087 p_resolved = (nobj_resolved * 100) /
1088 (nobj_total - nobj_loose);
1089 if (p_resolved != a->last_p_resolved) {
1090 a->last_p_resolved = p_resolved;
1091 print_resolved = 1;
1092 print_indexed = 1;
1093 print_size = 1;
1098 if (print_size || print_indexed || print_resolved)
1099 printf("\r");
1100 if (print_size)
1101 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1102 if (print_indexed)
1103 printf("; indexing %d%%", p_indexed);
1104 if (print_resolved)
1105 printf("; resolving deltas %d%%", p_resolved);
1106 if (print_size || print_indexed || print_resolved)
1107 fflush(stdout);
1109 return NULL;
1112 static const struct got_error *
1113 create_symref(const char *refname, struct got_reference *target_ref,
1114 int verbosity, struct got_repository *repo)
1116 const struct got_error *err;
1117 struct got_reference *head_symref;
1119 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1120 if (err)
1121 return err;
1123 err = got_ref_write(head_symref, repo);
1124 if (err == NULL && verbosity > 0) {
1125 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1126 got_ref_get_name(target_ref));
1128 got_ref_close(head_symref);
1129 return err;
1132 static const struct got_error *
1133 list_remote_refs(struct got_pathlist_head *symrefs,
1134 struct got_pathlist_head *refs)
1136 const struct got_error *err;
1137 struct got_pathlist_entry *pe;
1139 TAILQ_FOREACH(pe, symrefs, entry) {
1140 const char *refname = pe->path;
1141 const char *targetref = pe->data;
1143 printf("%s: %s\n", refname, targetref);
1146 TAILQ_FOREACH(pe, refs, entry) {
1147 const char *refname = pe->path;
1148 struct got_object_id *id = pe->data;
1149 char *id_str;
1151 err = got_object_id_str(&id_str, id);
1152 if (err)
1153 return err;
1154 printf("%s: %s\n", refname, id_str);
1155 free(id_str);
1158 return NULL;
1161 static const struct got_error *
1162 create_ref(const char *refname, struct got_object_id *id,
1163 int verbosity, struct got_repository *repo)
1165 const struct got_error *err = NULL;
1166 struct got_reference *ref;
1167 char *id_str;
1169 err = got_object_id_str(&id_str, id);
1170 if (err)
1171 return err;
1173 err = got_ref_alloc(&ref, refname, id);
1174 if (err)
1175 goto done;
1177 err = got_ref_write(ref, repo);
1178 got_ref_close(ref);
1180 if (err == NULL && verbosity >= 0)
1181 printf("Created reference %s: %s\n", refname, id_str);
1182 done:
1183 free(id_str);
1184 return err;
1187 static int
1188 match_wanted_ref(const char *refname, const char *wanted_ref)
1190 if (strncmp(refname, "refs/", 5) != 0)
1191 return 0;
1192 refname += 5;
1195 * Prevent fetching of references that won't make any
1196 * sense outside of the remote repository's context.
1198 if (strncmp(refname, "got/", 4) == 0)
1199 return 0;
1200 if (strncmp(refname, "remotes/", 8) == 0)
1201 return 0;
1203 if (strncmp(wanted_ref, "refs/", 5) == 0)
1204 wanted_ref += 5;
1206 /* Allow prefix match. */
1207 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1208 return 1;
1210 /* Allow exact match. */
1211 return (strcmp(refname, wanted_ref) == 0);
1214 static int
1215 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1217 struct got_pathlist_entry *pe;
1219 TAILQ_FOREACH(pe, wanted_refs, entry) {
1220 if (match_wanted_ref(refname, pe->path))
1221 return 1;
1224 return 0;
1227 static const struct got_error *
1228 create_wanted_ref(const char *refname, struct got_object_id *id,
1229 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1231 const struct got_error *err;
1232 char *remote_refname;
1234 if (strncmp("refs/", refname, 5) == 0)
1235 refname += 5;
1237 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1238 remote_repo_name, refname) == -1)
1239 return got_error_from_errno("asprintf");
1241 err = create_ref(remote_refname, id, verbosity, repo);
1242 free(remote_refname);
1243 return err;
1246 static const struct got_error *
1247 create_gotconfig(const char *proto, const char *host, const char *port,
1248 const char *remote_repo_path, const char *default_branch,
1249 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1250 struct got_pathlist_head *wanted_refs, int mirror_references,
1251 struct got_repository *repo)
1253 const struct got_error *err = NULL;
1254 char *gotconfig_path = NULL;
1255 char *gotconfig = NULL;
1256 FILE *gotconfig_file = NULL;
1257 const char *branchname = NULL;
1258 char *branches = NULL, *refs = NULL;
1259 ssize_t n;
1261 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1262 struct got_pathlist_entry *pe;
1263 TAILQ_FOREACH(pe, wanted_branches, entry) {
1264 char *s;
1265 branchname = pe->path;
1266 if (strncmp(branchname, "refs/heads/", 11) == 0)
1267 branchname += 11;
1268 if (asprintf(&s, "%s\"%s\" ",
1269 branches ? branches : "", branchname) == -1) {
1270 err = got_error_from_errno("asprintf");
1271 goto done;
1273 free(branches);
1274 branches = s;
1276 } else if (!fetch_all_branches && default_branch) {
1277 branchname = default_branch;
1278 if (strncmp(branchname, "refs/heads/", 11) == 0)
1279 branchname += 11;
1280 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1281 err = got_error_from_errno("asprintf");
1282 goto done;
1285 if (!TAILQ_EMPTY(wanted_refs)) {
1286 struct got_pathlist_entry *pe;
1287 TAILQ_FOREACH(pe, wanted_refs, entry) {
1288 char *s;
1289 const char *refname = pe->path;
1290 if (strncmp(refname, "refs/", 5) == 0)
1291 branchname += 5;
1292 if (asprintf(&s, "%s\"%s\" ",
1293 refs ? refs : "", refname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1297 free(refs);
1298 refs = s;
1302 /* Create got.conf(5). */
1303 gotconfig_path = got_repo_get_path_gotconfig(repo);
1304 if (gotconfig_path == NULL) {
1305 err = got_error_from_errno("got_repo_get_path_gotconfig");
1306 goto done;
1308 gotconfig_file = fopen(gotconfig_path, "ae");
1309 if (gotconfig_file == NULL) {
1310 err = got_error_from_errno2("fopen", gotconfig_path);
1311 goto done;
1313 if (asprintf(&gotconfig,
1314 "remote \"%s\" {\n"
1315 "\tserver %s\n"
1316 "\tprotocol %s\n"
1317 "%s%s%s"
1318 "\trepository \"%s\"\n"
1319 "%s%s%s"
1320 "%s%s%s"
1321 "%s"
1322 "%s"
1323 "}\n",
1324 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1325 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1326 remote_repo_path, branches ? "\tbranch { " : "",
1327 branches ? branches : "", branches ? "}\n" : "",
1328 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1329 mirror_references ? "\tmirror_references yes\n" : "",
1330 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1331 err = got_error_from_errno("asprintf");
1332 goto done;
1334 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1335 if (n != strlen(gotconfig)) {
1336 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1337 goto done;
1340 done:
1341 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1342 err = got_error_from_errno2("fclose", gotconfig_path);
1343 free(gotconfig_path);
1344 free(branches);
1345 return err;
1348 static const struct got_error *
1349 create_gitconfig(const char *git_url, const char *default_branch,
1350 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1351 struct got_pathlist_head *wanted_refs, int mirror_references,
1352 struct got_repository *repo)
1354 const struct got_error *err = NULL;
1355 char *gitconfig_path = NULL;
1356 char *gitconfig = NULL;
1357 FILE *gitconfig_file = NULL;
1358 char *branches = NULL, *refs = NULL;
1359 const char *branchname;
1360 ssize_t n;
1362 /* Create a config file Git can understand. */
1363 gitconfig_path = got_repo_get_path_gitconfig(repo);
1364 if (gitconfig_path == NULL) {
1365 err = got_error_from_errno("got_repo_get_path_gitconfig");
1366 goto done;
1368 gitconfig_file = fopen(gitconfig_path, "ae");
1369 if (gitconfig_file == NULL) {
1370 err = got_error_from_errno2("fopen", gitconfig_path);
1371 goto done;
1373 if (fetch_all_branches) {
1374 if (mirror_references) {
1375 if (asprintf(&branches,
1376 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1377 err = got_error_from_errno("asprintf");
1378 goto done;
1380 } else if (asprintf(&branches,
1381 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1382 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1383 err = got_error_from_errno("asprintf");
1384 goto done;
1386 } else if (!TAILQ_EMPTY(wanted_branches)) {
1387 struct got_pathlist_entry *pe;
1388 TAILQ_FOREACH(pe, wanted_branches, entry) {
1389 char *s;
1390 branchname = pe->path;
1391 if (strncmp(branchname, "refs/heads/", 11) == 0)
1392 branchname += 11;
1393 if (mirror_references) {
1394 if (asprintf(&s,
1395 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1396 branches ? branches : "",
1397 branchname, branchname) == -1) {
1398 err = got_error_from_errno("asprintf");
1399 goto done;
1401 } else if (asprintf(&s,
1402 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1403 branches ? branches : "",
1404 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1405 branchname) == -1) {
1406 err = got_error_from_errno("asprintf");
1407 goto done;
1409 free(branches);
1410 branches = s;
1412 } else {
1414 * If the server specified a default branch, use just that one.
1415 * Otherwise fall back to fetching all branches on next fetch.
1417 if (default_branch) {
1418 branchname = default_branch;
1419 if (strncmp(branchname, "refs/heads/", 11) == 0)
1420 branchname += 11;
1421 } else
1422 branchname = "*"; /* fall back to all branches */
1423 if (mirror_references) {
1424 if (asprintf(&branches,
1425 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1426 branchname, branchname) == -1) {
1427 err = got_error_from_errno("asprintf");
1428 goto done;
1430 } else if (asprintf(&branches,
1431 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1432 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1433 branchname) == -1) {
1434 err = got_error_from_errno("asprintf");
1435 goto done;
1438 if (!TAILQ_EMPTY(wanted_refs)) {
1439 struct got_pathlist_entry *pe;
1440 TAILQ_FOREACH(pe, wanted_refs, entry) {
1441 char *s;
1442 const char *refname = pe->path;
1443 if (strncmp(refname, "refs/", 5) == 0)
1444 refname += 5;
1445 if (mirror_references) {
1446 if (asprintf(&s,
1447 "%s\tfetch = refs/%s:refs/%s\n",
1448 refs ? refs : "", refname, refname) == -1) {
1449 err = got_error_from_errno("asprintf");
1450 goto done;
1452 } else if (asprintf(&s,
1453 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1454 refs ? refs : "",
1455 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1456 refname) == -1) {
1457 err = got_error_from_errno("asprintf");
1458 goto done;
1460 free(refs);
1461 refs = s;
1465 if (asprintf(&gitconfig,
1466 "[remote \"%s\"]\n"
1467 "\turl = %s\n"
1468 "%s"
1469 "%s"
1470 "\tfetch = refs/tags/*:refs/tags/*\n",
1471 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1472 refs ? refs : "") == -1) {
1473 err = got_error_from_errno("asprintf");
1474 goto done;
1476 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1477 if (n != strlen(gitconfig)) {
1478 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1479 goto done;
1481 done:
1482 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1483 err = got_error_from_errno2("fclose", gitconfig_path);
1484 free(gitconfig_path);
1485 free(branches);
1486 return err;
1489 static const struct got_error *
1490 create_config_files(const char *proto, const char *host, const char *port,
1491 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1492 int mirror_references, struct got_pathlist_head *symrefs,
1493 struct got_pathlist_head *wanted_branches,
1494 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1496 const struct got_error *err = NULL;
1497 const char *default_branch = NULL;
1498 struct got_pathlist_entry *pe;
1501 * If we asked for a set of wanted branches then use the first
1502 * one of those.
1504 if (!TAILQ_EMPTY(wanted_branches)) {
1505 pe = TAILQ_FIRST(wanted_branches);
1506 default_branch = pe->path;
1507 } else {
1508 /* First HEAD ref listed by server is the default branch. */
1509 TAILQ_FOREACH(pe, symrefs, entry) {
1510 const char *refname = pe->path;
1511 const char *target = pe->data;
1513 if (strcmp(refname, GOT_REF_HEAD) != 0)
1514 continue;
1516 default_branch = target;
1517 break;
1521 /* Create got.conf(5). */
1522 err = create_gotconfig(proto, host, port, remote_repo_path,
1523 default_branch, fetch_all_branches, wanted_branches,
1524 wanted_refs, mirror_references, repo);
1525 if (err)
1526 return err;
1528 /* Create a config file Git can understand. */
1529 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1530 wanted_branches, wanted_refs, mirror_references, repo);
1533 static const struct got_error *
1534 cmd_clone(int argc, char *argv[])
1536 const struct got_error *error = NULL;
1537 const char *uri, *dirname;
1538 char *proto, *host, *port, *repo_name, *server_path;
1539 char *default_destdir = NULL, *id_str = NULL;
1540 const char *repo_path;
1541 struct got_repository *repo = NULL;
1542 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1543 struct got_pathlist_entry *pe;
1544 struct got_object_id *pack_hash = NULL;
1545 int ch, fetchfd = -1, fetchstatus;
1546 pid_t fetchpid = -1;
1547 struct got_fetch_progress_arg fpa;
1548 char *git_url = NULL;
1549 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1550 int list_refs_only = 0;
1551 int *pack_fds = NULL;
1553 TAILQ_INIT(&refs);
1554 TAILQ_INIT(&symrefs);
1555 TAILQ_INIT(&wanted_branches);
1556 TAILQ_INIT(&wanted_refs);
1558 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1559 switch (ch) {
1560 case 'a':
1561 fetch_all_branches = 1;
1562 break;
1563 case 'b':
1564 error = got_pathlist_append(&wanted_branches,
1565 optarg, NULL);
1566 if (error)
1567 return error;
1568 break;
1569 case 'l':
1570 list_refs_only = 1;
1571 break;
1572 case 'm':
1573 mirror_references = 1;
1574 break;
1575 case 'v':
1576 if (verbosity < 0)
1577 verbosity = 0;
1578 else if (verbosity < 3)
1579 verbosity++;
1580 break;
1581 case 'q':
1582 verbosity = -1;
1583 break;
1584 case 'R':
1585 error = got_pathlist_append(&wanted_refs,
1586 optarg, NULL);
1587 if (error)
1588 return error;
1589 break;
1590 default:
1591 usage_clone();
1592 break;
1595 argc -= optind;
1596 argv += optind;
1598 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1599 option_conflict('a', 'b');
1600 if (list_refs_only) {
1601 if (!TAILQ_EMPTY(&wanted_branches))
1602 option_conflict('l', 'b');
1603 if (fetch_all_branches)
1604 option_conflict('l', 'a');
1605 if (mirror_references)
1606 option_conflict('l', 'm');
1607 if (!TAILQ_EMPTY(&wanted_refs))
1608 option_conflict('l', 'R');
1611 uri = argv[0];
1613 if (argc == 1)
1614 dirname = NULL;
1615 else if (argc == 2)
1616 dirname = argv[1];
1617 else
1618 usage_clone();
1620 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1621 &repo_name, uri);
1622 if (error)
1623 goto done;
1625 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1626 host, port ? ":" : "", port ? port : "",
1627 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1628 error = got_error_from_errno("asprintf");
1629 goto done;
1632 if (strcmp(proto, "git") == 0) {
1633 #ifndef PROFILE
1634 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1635 "sendfd dns inet unveil", NULL) == -1)
1636 err(1, "pledge");
1637 #endif
1638 } else if (strcmp(proto, "git+ssh") == 0 ||
1639 strcmp(proto, "ssh") == 0) {
1640 #ifndef PROFILE
1641 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1642 "sendfd unveil", NULL) == -1)
1643 err(1, "pledge");
1644 #endif
1645 } else if (strcmp(proto, "http") == 0 ||
1646 strcmp(proto, "git+http") == 0) {
1647 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1648 goto done;
1649 } else {
1650 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1651 goto done;
1653 if (dirname == NULL) {
1654 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1655 error = got_error_from_errno("asprintf");
1656 goto done;
1658 repo_path = default_destdir;
1659 } else
1660 repo_path = dirname;
1662 if (!list_refs_only) {
1663 error = got_path_mkdir(repo_path);
1664 if (error &&
1665 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1666 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1667 goto done;
1668 if (!got_path_dir_is_empty(repo_path)) {
1669 error = got_error_path(repo_path,
1670 GOT_ERR_DIR_NOT_EMPTY);
1671 goto done;
1675 error = got_dial_apply_unveil(proto);
1676 if (error)
1677 goto done;
1679 error = apply_unveil(repo_path, 0, NULL);
1680 if (error)
1681 goto done;
1683 if (verbosity >= 0)
1684 printf("Connecting to %s%s%s\n", host,
1685 port ? ":" : "", port ? port : "");
1687 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1688 server_path, verbosity);
1689 if (error)
1690 goto done;
1692 if (!list_refs_only) {
1693 error = got_repo_init(repo_path);
1694 if (error)
1695 goto done;
1696 error = got_repo_pack_fds_open(&pack_fds);
1697 if (error != NULL)
1698 goto done;
1699 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1700 if (error)
1701 goto done;
1704 fpa.last_scaled_size[0] = '\0';
1705 fpa.last_p_indexed = -1;
1706 fpa.last_p_resolved = -1;
1707 fpa.verbosity = verbosity;
1708 fpa.create_configs = 1;
1709 fpa.configs_created = 0;
1710 fpa.repo = repo;
1711 fpa.config_info.symrefs = &symrefs;
1712 fpa.config_info.wanted_branches = &wanted_branches;
1713 fpa.config_info.wanted_refs = &wanted_refs;
1714 fpa.config_info.proto = proto;
1715 fpa.config_info.host = host;
1716 fpa.config_info.port = port;
1717 fpa.config_info.remote_repo_path = server_path;
1718 fpa.config_info.git_url = git_url;
1719 fpa.config_info.fetch_all_branches = fetch_all_branches;
1720 fpa.config_info.mirror_references = mirror_references;
1721 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1722 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1723 fetch_all_branches, &wanted_branches, &wanted_refs,
1724 list_refs_only, verbosity, fetchfd, repo,
1725 fetch_progress, &fpa);
1726 if (error)
1727 goto done;
1729 if (list_refs_only) {
1730 error = list_remote_refs(&symrefs, &refs);
1731 goto done;
1734 if (pack_hash == NULL) {
1735 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1736 "server sent an empty pack file");
1737 goto done;
1739 error = got_object_id_str(&id_str, pack_hash);
1740 if (error)
1741 goto done;
1742 if (verbosity >= 0)
1743 printf("\nFetched %s.pack\n", id_str);
1744 free(id_str);
1746 /* Set up references provided with the pack file. */
1747 TAILQ_FOREACH(pe, &refs, entry) {
1748 const char *refname = pe->path;
1749 struct got_object_id *id = pe->data;
1750 char *remote_refname;
1752 if (is_wanted_ref(&wanted_refs, refname) &&
1753 !mirror_references) {
1754 error = create_wanted_ref(refname, id,
1755 GOT_FETCH_DEFAULT_REMOTE_NAME,
1756 verbosity - 1, repo);
1757 if (error)
1758 goto done;
1759 continue;
1762 error = create_ref(refname, id, verbosity - 1, repo);
1763 if (error)
1764 goto done;
1766 if (mirror_references)
1767 continue;
1769 if (strncmp("refs/heads/", refname, 11) != 0)
1770 continue;
1772 if (asprintf(&remote_refname,
1773 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1774 refname + 11) == -1) {
1775 error = got_error_from_errno("asprintf");
1776 goto done;
1778 error = create_ref(remote_refname, id, verbosity - 1, repo);
1779 free(remote_refname);
1780 if (error)
1781 goto done;
1784 /* Set the HEAD reference if the server provided one. */
1785 TAILQ_FOREACH(pe, &symrefs, entry) {
1786 struct got_reference *target_ref;
1787 const char *refname = pe->path;
1788 const char *target = pe->data;
1789 char *remote_refname = NULL, *remote_target = NULL;
1791 if (strcmp(refname, GOT_REF_HEAD) != 0)
1792 continue;
1794 error = got_ref_open(&target_ref, repo, target, 0);
1795 if (error) {
1796 if (error->code == GOT_ERR_NOT_REF) {
1797 error = NULL;
1798 continue;
1800 goto done;
1803 error = create_symref(refname, target_ref, verbosity, repo);
1804 got_ref_close(target_ref);
1805 if (error)
1806 goto done;
1808 if (mirror_references)
1809 continue;
1811 if (strncmp("refs/heads/", target, 11) != 0)
1812 continue;
1814 if (asprintf(&remote_refname,
1815 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1816 refname) == -1) {
1817 error = got_error_from_errno("asprintf");
1818 goto done;
1820 if (asprintf(&remote_target,
1821 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1822 target + 11) == -1) {
1823 error = got_error_from_errno("asprintf");
1824 free(remote_refname);
1825 goto done;
1827 error = got_ref_open(&target_ref, repo, remote_target, 0);
1828 if (error) {
1829 free(remote_refname);
1830 free(remote_target);
1831 if (error->code == GOT_ERR_NOT_REF) {
1832 error = NULL;
1833 continue;
1835 goto done;
1837 error = create_symref(remote_refname, target_ref,
1838 verbosity - 1, repo);
1839 free(remote_refname);
1840 free(remote_target);
1841 got_ref_close(target_ref);
1842 if (error)
1843 goto done;
1845 if (pe == NULL) {
1847 * We failed to set the HEAD reference. If we asked for
1848 * a set of wanted branches use the first of one of those
1849 * which could be fetched instead.
1851 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1852 const char *target = pe->path;
1853 struct got_reference *target_ref;
1855 error = got_ref_open(&target_ref, repo, target, 0);
1856 if (error) {
1857 if (error->code == GOT_ERR_NOT_REF) {
1858 error = NULL;
1859 continue;
1861 goto done;
1864 error = create_symref(GOT_REF_HEAD, target_ref,
1865 verbosity, repo);
1866 got_ref_close(target_ref);
1867 if (error)
1868 goto done;
1869 break;
1873 if (verbosity >= 0)
1874 printf("Created %s repository '%s'\n",
1875 mirror_references ? "mirrored" : "cloned", repo_path);
1876 done:
1877 if (pack_fds) {
1878 const struct got_error *pack_err =
1879 got_repo_pack_fds_close(pack_fds);
1880 if (error == NULL)
1881 error = pack_err;
1883 if (fetchpid > 0) {
1884 if (kill(fetchpid, SIGTERM) == -1)
1885 error = got_error_from_errno("kill");
1886 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1887 error = got_error_from_errno("waitpid");
1889 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1890 error = got_error_from_errno("close");
1891 if (repo) {
1892 const struct got_error *close_err = got_repo_close(repo);
1893 if (error == NULL)
1894 error = close_err;
1896 TAILQ_FOREACH(pe, &refs, entry) {
1897 free((void *)pe->path);
1898 free(pe->data);
1900 got_pathlist_free(&refs);
1901 TAILQ_FOREACH(pe, &symrefs, entry) {
1902 free((void *)pe->path);
1903 free(pe->data);
1905 got_pathlist_free(&symrefs);
1906 got_pathlist_free(&wanted_branches);
1907 got_pathlist_free(&wanted_refs);
1908 free(pack_hash);
1909 free(proto);
1910 free(host);
1911 free(port);
1912 free(server_path);
1913 free(repo_name);
1914 free(default_destdir);
1915 free(git_url);
1916 return error;
1919 static const struct got_error *
1920 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1921 int replace_tags, int verbosity, struct got_repository *repo)
1923 const struct got_error *err = NULL;
1924 char *new_id_str = NULL;
1925 struct got_object_id *old_id = NULL;
1927 err = got_object_id_str(&new_id_str, new_id);
1928 if (err)
1929 goto done;
1931 if (!replace_tags &&
1932 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1933 err = got_ref_resolve(&old_id, repo, ref);
1934 if (err)
1935 goto done;
1936 if (got_object_id_cmp(old_id, new_id) == 0)
1937 goto done;
1938 if (verbosity >= 0) {
1939 printf("Rejecting update of existing tag %s: %s\n",
1940 got_ref_get_name(ref), new_id_str);
1942 goto done;
1945 if (got_ref_is_symbolic(ref)) {
1946 if (verbosity >= 0) {
1947 printf("Replacing reference %s: %s\n",
1948 got_ref_get_name(ref),
1949 got_ref_get_symref_target(ref));
1951 err = got_ref_change_symref_to_ref(ref, new_id);
1952 if (err)
1953 goto done;
1954 err = got_ref_write(ref, repo);
1955 if (err)
1956 goto done;
1957 } else {
1958 err = got_ref_resolve(&old_id, repo, ref);
1959 if (err)
1960 goto done;
1961 if (got_object_id_cmp(old_id, new_id) == 0)
1962 goto done;
1964 err = got_ref_change_ref(ref, new_id);
1965 if (err)
1966 goto done;
1967 err = got_ref_write(ref, repo);
1968 if (err)
1969 goto done;
1972 if (verbosity >= 0)
1973 printf("Updated %s: %s\n", got_ref_get_name(ref),
1974 new_id_str);
1975 done:
1976 free(old_id);
1977 free(new_id_str);
1978 return err;
1981 static const struct got_error *
1982 update_symref(const char *refname, struct got_reference *target_ref,
1983 int verbosity, struct got_repository *repo)
1985 const struct got_error *err = NULL, *unlock_err;
1986 struct got_reference *symref;
1987 int symref_is_locked = 0;
1989 err = got_ref_open(&symref, repo, refname, 1);
1990 if (err) {
1991 if (err->code != GOT_ERR_NOT_REF)
1992 return err;
1993 err = got_ref_alloc_symref(&symref, refname, target_ref);
1994 if (err)
1995 goto done;
1997 err = got_ref_write(symref, repo);
1998 if (err)
1999 goto done;
2001 if (verbosity >= 0)
2002 printf("Created reference %s: %s\n",
2003 got_ref_get_name(symref),
2004 got_ref_get_symref_target(symref));
2005 } else {
2006 symref_is_locked = 1;
2008 if (strcmp(got_ref_get_symref_target(symref),
2009 got_ref_get_name(target_ref)) == 0)
2010 goto done;
2012 err = got_ref_change_symref(symref,
2013 got_ref_get_name(target_ref));
2014 if (err)
2015 goto done;
2017 err = got_ref_write(symref, repo);
2018 if (err)
2019 goto done;
2021 if (verbosity >= 0)
2022 printf("Updated %s: %s\n", got_ref_get_name(symref),
2023 got_ref_get_symref_target(symref));
2026 done:
2027 if (symref_is_locked) {
2028 unlock_err = got_ref_unlock(symref);
2029 if (unlock_err && err == NULL)
2030 err = unlock_err;
2032 got_ref_close(symref);
2033 return err;
2036 __dead static void
2037 usage_fetch(void)
2039 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
2040 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
2041 "[remote-repository-name]\n",
2042 getprogname());
2043 exit(1);
2046 static const struct got_error *
2047 delete_missing_ref(struct got_reference *ref,
2048 int verbosity, struct got_repository *repo)
2050 const struct got_error *err = NULL;
2051 struct got_object_id *id = NULL;
2052 char *id_str = NULL;
2054 if (got_ref_is_symbolic(ref)) {
2055 err = got_ref_delete(ref, repo);
2056 if (err)
2057 return err;
2058 if (verbosity >= 0) {
2059 printf("Deleted %s: %s\n",
2060 got_ref_get_name(ref),
2061 got_ref_get_symref_target(ref));
2063 } else {
2064 err = got_ref_resolve(&id, repo, ref);
2065 if (err)
2066 return err;
2067 err = got_object_id_str(&id_str, id);
2068 if (err)
2069 goto done;
2071 err = got_ref_delete(ref, repo);
2072 if (err)
2073 goto done;
2074 if (verbosity >= 0) {
2075 printf("Deleted %s: %s\n",
2076 got_ref_get_name(ref), id_str);
2079 done:
2080 free(id);
2081 free(id_str);
2082 return NULL;
2085 static const struct got_error *
2086 delete_missing_refs(struct got_pathlist_head *their_refs,
2087 struct got_pathlist_head *their_symrefs,
2088 const struct got_remote_repo *remote,
2089 int verbosity, struct got_repository *repo)
2091 const struct got_error *err = NULL, *unlock_err;
2092 struct got_reflist_head my_refs;
2093 struct got_reflist_entry *re;
2094 struct got_pathlist_entry *pe;
2095 char *remote_namespace = NULL;
2096 char *local_refname = NULL;
2098 TAILQ_INIT(&my_refs);
2100 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2101 == -1)
2102 return got_error_from_errno("asprintf");
2104 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2105 if (err)
2106 goto done;
2108 TAILQ_FOREACH(re, &my_refs, entry) {
2109 const char *refname = got_ref_get_name(re->ref);
2110 const char *their_refname;
2112 if (remote->mirror_references) {
2113 their_refname = refname;
2114 } else {
2115 if (strncmp(refname, remote_namespace,
2116 strlen(remote_namespace)) == 0) {
2117 if (strcmp(refname + strlen(remote_namespace),
2118 GOT_REF_HEAD) == 0)
2119 continue;
2120 if (asprintf(&local_refname, "refs/heads/%s",
2121 refname + strlen(remote_namespace)) == -1) {
2122 err = got_error_from_errno("asprintf");
2123 goto done;
2125 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2126 continue;
2128 their_refname = local_refname;
2131 TAILQ_FOREACH(pe, their_refs, entry) {
2132 if (strcmp(their_refname, pe->path) == 0)
2133 break;
2135 if (pe != NULL)
2136 continue;
2138 TAILQ_FOREACH(pe, their_symrefs, entry) {
2139 if (strcmp(their_refname, pe->path) == 0)
2140 break;
2142 if (pe != NULL)
2143 continue;
2145 err = delete_missing_ref(re->ref, verbosity, repo);
2146 if (err)
2147 break;
2149 if (local_refname) {
2150 struct got_reference *ref;
2151 err = got_ref_open(&ref, repo, local_refname, 1);
2152 if (err) {
2153 if (err->code != GOT_ERR_NOT_REF)
2154 break;
2155 free(local_refname);
2156 local_refname = NULL;
2157 continue;
2159 err = delete_missing_ref(ref, verbosity, repo);
2160 if (err)
2161 break;
2162 unlock_err = got_ref_unlock(ref);
2163 got_ref_close(ref);
2164 if (unlock_err && err == NULL) {
2165 err = unlock_err;
2166 break;
2169 free(local_refname);
2170 local_refname = NULL;
2173 done:
2174 free(remote_namespace);
2175 free(local_refname);
2176 return err;
2179 static const struct got_error *
2180 update_wanted_ref(const char *refname, struct got_object_id *id,
2181 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2183 const struct got_error *err, *unlock_err;
2184 char *remote_refname;
2185 struct got_reference *ref;
2187 if (strncmp("refs/", refname, 5) == 0)
2188 refname += 5;
2190 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2191 remote_repo_name, refname) == -1)
2192 return got_error_from_errno("asprintf");
2194 err = got_ref_open(&ref, repo, remote_refname, 1);
2195 if (err) {
2196 if (err->code != GOT_ERR_NOT_REF)
2197 goto done;
2198 err = create_ref(remote_refname, id, verbosity, repo);
2199 } else {
2200 err = update_ref(ref, id, 0, verbosity, repo);
2201 unlock_err = got_ref_unlock(ref);
2202 if (unlock_err && err == NULL)
2203 err = unlock_err;
2204 got_ref_close(ref);
2206 done:
2207 free(remote_refname);
2208 return err;
2211 static const struct got_error *
2212 delete_ref(struct got_repository *repo, struct got_reference *ref)
2214 const struct got_error *err = NULL;
2215 struct got_object_id *id = NULL;
2216 char *id_str = NULL;
2217 const char *target;
2219 if (got_ref_is_symbolic(ref)) {
2220 target = got_ref_get_symref_target(ref);
2221 } else {
2222 err = got_ref_resolve(&id, repo, ref);
2223 if (err)
2224 goto done;
2225 err = got_object_id_str(&id_str, id);
2226 if (err)
2227 goto done;
2228 target = id_str;
2231 err = got_ref_delete(ref, repo);
2232 if (err)
2233 goto done;
2235 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2236 done:
2237 free(id);
2238 free(id_str);
2239 return err;
2242 static const struct got_error *
2243 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2245 const struct got_error *err = NULL;
2246 struct got_reflist_head refs;
2247 struct got_reflist_entry *re;
2248 char *prefix;
2250 TAILQ_INIT(&refs);
2252 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2253 err = got_error_from_errno("asprintf");
2254 goto done;
2256 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2257 if (err)
2258 goto done;
2260 TAILQ_FOREACH(re, &refs, entry)
2261 delete_ref(repo, re->ref);
2262 done:
2263 got_ref_list_free(&refs);
2264 return err;
2267 static const struct got_error *
2268 cmd_fetch(int argc, char *argv[])
2270 const struct got_error *error = NULL, *unlock_err;
2271 char *cwd = NULL, *repo_path = NULL;
2272 const char *remote_name;
2273 char *proto = NULL, *host = NULL, *port = NULL;
2274 char *repo_name = NULL, *server_path = NULL;
2275 const struct got_remote_repo *remotes, *remote = NULL;
2276 int nremotes;
2277 char *id_str = NULL;
2278 struct got_repository *repo = NULL;
2279 struct got_worktree *worktree = NULL;
2280 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2281 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2282 struct got_pathlist_entry *pe;
2283 struct got_object_id *pack_hash = NULL;
2284 int i, ch, fetchfd = -1, fetchstatus;
2285 pid_t fetchpid = -1;
2286 struct got_fetch_progress_arg fpa;
2287 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2288 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2289 int *pack_fds = NULL;
2291 TAILQ_INIT(&refs);
2292 TAILQ_INIT(&symrefs);
2293 TAILQ_INIT(&wanted_branches);
2294 TAILQ_INIT(&wanted_refs);
2296 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2297 switch (ch) {
2298 case 'a':
2299 fetch_all_branches = 1;
2300 break;
2301 case 'b':
2302 error = got_pathlist_append(&wanted_branches,
2303 optarg, NULL);
2304 if (error)
2305 return error;
2306 break;
2307 case 'd':
2308 delete_refs = 1;
2309 break;
2310 case 'l':
2311 list_refs_only = 1;
2312 break;
2313 case 'r':
2314 repo_path = realpath(optarg, NULL);
2315 if (repo_path == NULL)
2316 return got_error_from_errno2("realpath",
2317 optarg);
2318 got_path_strip_trailing_slashes(repo_path);
2319 break;
2320 case 't':
2321 replace_tags = 1;
2322 break;
2323 case 'v':
2324 if (verbosity < 0)
2325 verbosity = 0;
2326 else if (verbosity < 3)
2327 verbosity++;
2328 break;
2329 case 'q':
2330 verbosity = -1;
2331 break;
2332 case 'R':
2333 error = got_pathlist_append(&wanted_refs,
2334 optarg, NULL);
2335 if (error)
2336 return error;
2337 break;
2338 case 'X':
2339 delete_remote = 1;
2340 break;
2341 default:
2342 usage_fetch();
2343 break;
2346 argc -= optind;
2347 argv += optind;
2349 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2350 option_conflict('a', 'b');
2351 if (list_refs_only) {
2352 if (!TAILQ_EMPTY(&wanted_branches))
2353 option_conflict('l', 'b');
2354 if (fetch_all_branches)
2355 option_conflict('l', 'a');
2356 if (delete_refs)
2357 option_conflict('l', 'd');
2358 if (delete_remote)
2359 option_conflict('l', 'X');
2361 if (delete_remote) {
2362 if (fetch_all_branches)
2363 option_conflict('X', 'a');
2364 if (!TAILQ_EMPTY(&wanted_branches))
2365 option_conflict('X', 'b');
2366 if (delete_refs)
2367 option_conflict('X', 'd');
2368 if (replace_tags)
2369 option_conflict('X', 't');
2370 if (!TAILQ_EMPTY(&wanted_refs))
2371 option_conflict('X', 'R');
2374 if (argc == 0) {
2375 if (delete_remote)
2376 errx(1, "-X option requires a remote name");
2377 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2378 } else if (argc == 1)
2379 remote_name = argv[0];
2380 else
2381 usage_fetch();
2383 cwd = getcwd(NULL, 0);
2384 if (cwd == NULL) {
2385 error = got_error_from_errno("getcwd");
2386 goto done;
2389 error = got_repo_pack_fds_open(&pack_fds);
2390 if (error != NULL)
2391 goto done;
2393 if (repo_path == NULL) {
2394 error = got_worktree_open(&worktree, cwd);
2395 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2396 goto done;
2397 else
2398 error = NULL;
2399 if (worktree) {
2400 repo_path =
2401 strdup(got_worktree_get_repo_path(worktree));
2402 if (repo_path == NULL)
2403 error = got_error_from_errno("strdup");
2404 if (error)
2405 goto done;
2406 } else {
2407 repo_path = strdup(cwd);
2408 if (repo_path == NULL) {
2409 error = got_error_from_errno("strdup");
2410 goto done;
2415 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2416 if (error)
2417 goto done;
2419 if (delete_remote) {
2420 error = delete_refs_for_remote(repo, remote_name);
2421 goto done; /* nothing else to do */
2424 if (worktree) {
2425 worktree_conf = got_worktree_get_gotconfig(worktree);
2426 if (worktree_conf) {
2427 got_gotconfig_get_remotes(&nremotes, &remotes,
2428 worktree_conf);
2429 for (i = 0; i < nremotes; i++) {
2430 if (strcmp(remotes[i].name, remote_name) == 0) {
2431 remote = &remotes[i];
2432 break;
2437 if (remote == NULL) {
2438 repo_conf = got_repo_get_gotconfig(repo);
2439 if (repo_conf) {
2440 got_gotconfig_get_remotes(&nremotes, &remotes,
2441 repo_conf);
2442 for (i = 0; i < nremotes; i++) {
2443 if (strcmp(remotes[i].name, remote_name) == 0) {
2444 remote = &remotes[i];
2445 break;
2450 if (remote == NULL) {
2451 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2452 for (i = 0; i < nremotes; i++) {
2453 if (strcmp(remotes[i].name, remote_name) == 0) {
2454 remote = &remotes[i];
2455 break;
2459 if (remote == NULL) {
2460 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2461 goto done;
2464 if (TAILQ_EMPTY(&wanted_branches)) {
2465 if (!fetch_all_branches)
2466 fetch_all_branches = remote->fetch_all_branches;
2467 for (i = 0; i < remote->nfetch_branches; i++) {
2468 got_pathlist_append(&wanted_branches,
2469 remote->fetch_branches[i], NULL);
2472 if (TAILQ_EMPTY(&wanted_refs)) {
2473 for (i = 0; i < remote->nfetch_refs; i++) {
2474 got_pathlist_append(&wanted_refs,
2475 remote->fetch_refs[i], NULL);
2479 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2480 &repo_name, remote->fetch_url);
2481 if (error)
2482 goto done;
2484 if (strcmp(proto, "git") == 0) {
2485 #ifndef PROFILE
2486 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2487 "sendfd dns inet unveil", NULL) == -1)
2488 err(1, "pledge");
2489 #endif
2490 } else if (strcmp(proto, "git+ssh") == 0 ||
2491 strcmp(proto, "ssh") == 0) {
2492 #ifndef PROFILE
2493 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2494 "sendfd unveil", NULL) == -1)
2495 err(1, "pledge");
2496 #endif
2497 } else if (strcmp(proto, "http") == 0 ||
2498 strcmp(proto, "git+http") == 0) {
2499 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2500 goto done;
2501 } else {
2502 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2503 goto done;
2506 error = got_dial_apply_unveil(proto);
2507 if (error)
2508 goto done;
2510 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2511 if (error)
2512 goto done;
2514 if (verbosity >= 0)
2515 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2516 port ? ":" : "", port ? port : "");
2518 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2519 server_path, verbosity);
2520 if (error)
2521 goto done;
2523 fpa.last_scaled_size[0] = '\0';
2524 fpa.last_p_indexed = -1;
2525 fpa.last_p_resolved = -1;
2526 fpa.verbosity = verbosity;
2527 fpa.repo = repo;
2528 fpa.create_configs = 0;
2529 fpa.configs_created = 0;
2530 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2531 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2532 remote->mirror_references, fetch_all_branches, &wanted_branches,
2533 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2534 fetch_progress, &fpa);
2535 if (error)
2536 goto done;
2538 if (list_refs_only) {
2539 error = list_remote_refs(&symrefs, &refs);
2540 goto done;
2543 if (pack_hash == NULL) {
2544 if (verbosity >= 0)
2545 printf("Already up-to-date\n");
2546 } else if (verbosity >= 0) {
2547 error = got_object_id_str(&id_str, pack_hash);
2548 if (error)
2549 goto done;
2550 printf("\nFetched %s.pack\n", id_str);
2551 free(id_str);
2552 id_str = NULL;
2555 /* Update references provided with the pack file. */
2556 TAILQ_FOREACH(pe, &refs, entry) {
2557 const char *refname = pe->path;
2558 struct got_object_id *id = pe->data;
2559 struct got_reference *ref;
2560 char *remote_refname;
2562 if (is_wanted_ref(&wanted_refs, refname) &&
2563 !remote->mirror_references) {
2564 error = update_wanted_ref(refname, id,
2565 remote->name, verbosity, repo);
2566 if (error)
2567 goto done;
2568 continue;
2571 if (remote->mirror_references ||
2572 strncmp("refs/tags/", refname, 10) == 0) {
2573 error = got_ref_open(&ref, repo, refname, 1);
2574 if (error) {
2575 if (error->code != GOT_ERR_NOT_REF)
2576 goto done;
2577 error = create_ref(refname, id, verbosity,
2578 repo);
2579 if (error)
2580 goto done;
2581 } else {
2582 error = update_ref(ref, id, replace_tags,
2583 verbosity, repo);
2584 unlock_err = got_ref_unlock(ref);
2585 if (unlock_err && error == NULL)
2586 error = unlock_err;
2587 got_ref_close(ref);
2588 if (error)
2589 goto done;
2591 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2592 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2593 remote_name, refname + 11) == -1) {
2594 error = got_error_from_errno("asprintf");
2595 goto done;
2598 error = got_ref_open(&ref, repo, remote_refname, 1);
2599 if (error) {
2600 if (error->code != GOT_ERR_NOT_REF)
2601 goto done;
2602 error = create_ref(remote_refname, id,
2603 verbosity, repo);
2604 if (error)
2605 goto done;
2606 } else {
2607 error = update_ref(ref, id, replace_tags,
2608 verbosity, repo);
2609 unlock_err = got_ref_unlock(ref);
2610 if (unlock_err && error == NULL)
2611 error = unlock_err;
2612 got_ref_close(ref);
2613 if (error)
2614 goto done;
2617 /* Also create a local branch if none exists yet. */
2618 error = got_ref_open(&ref, repo, refname, 1);
2619 if (error) {
2620 if (error->code != GOT_ERR_NOT_REF)
2621 goto done;
2622 error = create_ref(refname, id, verbosity,
2623 repo);
2624 if (error)
2625 goto done;
2626 } else {
2627 unlock_err = got_ref_unlock(ref);
2628 if (unlock_err && error == NULL)
2629 error = unlock_err;
2630 got_ref_close(ref);
2634 if (delete_refs) {
2635 error = delete_missing_refs(&refs, &symrefs, remote,
2636 verbosity, repo);
2637 if (error)
2638 goto done;
2641 if (!remote->mirror_references) {
2642 /* Update remote HEAD reference if the server provided one. */
2643 TAILQ_FOREACH(pe, &symrefs, entry) {
2644 struct got_reference *target_ref;
2645 const char *refname = pe->path;
2646 const char *target = pe->data;
2647 char *remote_refname = NULL, *remote_target = NULL;
2649 if (strcmp(refname, GOT_REF_HEAD) != 0)
2650 continue;
2652 if (strncmp("refs/heads/", target, 11) != 0)
2653 continue;
2655 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2656 remote->name, refname) == -1) {
2657 error = got_error_from_errno("asprintf");
2658 goto done;
2660 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2661 remote->name, target + 11) == -1) {
2662 error = got_error_from_errno("asprintf");
2663 free(remote_refname);
2664 goto done;
2667 error = got_ref_open(&target_ref, repo, remote_target,
2668 0);
2669 if (error) {
2670 free(remote_refname);
2671 free(remote_target);
2672 if (error->code == GOT_ERR_NOT_REF) {
2673 error = NULL;
2674 continue;
2676 goto done;
2678 error = update_symref(remote_refname, target_ref,
2679 verbosity, repo);
2680 free(remote_refname);
2681 free(remote_target);
2682 got_ref_close(target_ref);
2683 if (error)
2684 goto done;
2687 done:
2688 if (fetchpid > 0) {
2689 if (kill(fetchpid, SIGTERM) == -1)
2690 error = got_error_from_errno("kill");
2691 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2692 error = got_error_from_errno("waitpid");
2694 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2695 error = got_error_from_errno("close");
2696 if (repo) {
2697 const struct got_error *close_err = got_repo_close(repo);
2698 if (error == NULL)
2699 error = close_err;
2701 if (worktree)
2702 got_worktree_close(worktree);
2703 if (pack_fds) {
2704 const struct got_error *pack_err =
2705 got_repo_pack_fds_close(pack_fds);
2706 if (error == NULL)
2707 error = pack_err;
2709 TAILQ_FOREACH(pe, &refs, entry) {
2710 free((void *)pe->path);
2711 free(pe->data);
2713 got_pathlist_free(&refs);
2714 TAILQ_FOREACH(pe, &symrefs, entry) {
2715 free((void *)pe->path);
2716 free(pe->data);
2718 got_pathlist_free(&symrefs);
2719 got_pathlist_free(&wanted_branches);
2720 got_pathlist_free(&wanted_refs);
2721 free(id_str);
2722 free(cwd);
2723 free(repo_path);
2724 free(pack_hash);
2725 free(proto);
2726 free(host);
2727 free(port);
2728 free(server_path);
2729 free(repo_name);
2730 return error;
2734 __dead static void
2735 usage_checkout(void)
2737 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2738 "[-p prefix] [-q] repository-path [worktree-path]\n",
2739 getprogname());
2740 exit(1);
2743 static void
2744 show_worktree_base_ref_warning(void)
2746 fprintf(stderr, "%s: warning: could not create a reference "
2747 "to the work tree's base commit; the commit could be "
2748 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2749 "repository writable and running 'got update' will prevent this\n",
2750 getprogname());
2753 struct got_checkout_progress_arg {
2754 const char *worktree_path;
2755 int had_base_commit_ref_error;
2756 int verbosity;
2759 static const struct got_error *
2760 checkout_progress(void *arg, unsigned char status, const char *path)
2762 struct got_checkout_progress_arg *a = arg;
2764 /* Base commit bump happens silently. */
2765 if (status == GOT_STATUS_BUMP_BASE)
2766 return NULL;
2768 if (status == GOT_STATUS_BASE_REF_ERR) {
2769 a->had_base_commit_ref_error = 1;
2770 return NULL;
2773 while (path[0] == '/')
2774 path++;
2776 if (a->verbosity >= 0)
2777 printf("%c %s/%s\n", status, a->worktree_path, path);
2779 return NULL;
2782 static const struct got_error *
2783 check_cancelled(void *arg)
2785 if (sigint_received || sigpipe_received)
2786 return got_error(GOT_ERR_CANCELLED);
2787 return NULL;
2790 static const struct got_error *
2791 check_linear_ancestry(struct got_object_id *commit_id,
2792 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2793 struct got_repository *repo)
2795 const struct got_error *err = NULL;
2796 struct got_object_id *yca_id;
2798 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2799 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2800 if (err)
2801 return err;
2803 if (yca_id == NULL)
2804 return got_error(GOT_ERR_ANCESTRY);
2807 * Require a straight line of history between the target commit
2808 * and the work tree's base commit.
2810 * Non-linear situations such as this require a rebase:
2812 * (commit) D F (base_commit)
2813 * \ /
2814 * C E
2815 * \ /
2816 * B (yca)
2817 * |
2818 * A
2820 * 'got update' only handles linear cases:
2821 * Update forwards in time: A (base/yca) - B - C - D (commit)
2822 * Update backwards in time: D (base) - C - B - A (commit/yca)
2824 if (allow_forwards_in_time_only) {
2825 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2826 return got_error(GOT_ERR_ANCESTRY);
2827 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2828 got_object_id_cmp(base_commit_id, yca_id) != 0)
2829 return got_error(GOT_ERR_ANCESTRY);
2831 free(yca_id);
2832 return NULL;
2835 static const struct got_error *
2836 check_same_branch(struct got_object_id *commit_id,
2837 struct got_reference *head_ref, struct got_object_id *yca_id,
2838 struct got_repository *repo)
2840 const struct got_error *err = NULL;
2841 struct got_commit_graph *graph = NULL;
2842 struct got_object_id *head_commit_id = NULL;
2843 int is_same_branch = 0;
2845 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2846 if (err)
2847 goto done;
2849 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2850 is_same_branch = 1;
2851 goto done;
2853 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2854 is_same_branch = 1;
2855 goto done;
2858 err = got_commit_graph_open(&graph, "/", 1);
2859 if (err)
2860 goto done;
2862 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2863 check_cancelled, NULL);
2864 if (err)
2865 goto done;
2867 for (;;) {
2868 struct got_object_id *id;
2869 err = got_commit_graph_iter_next(&id, graph, repo,
2870 check_cancelled, NULL);
2871 if (err) {
2872 if (err->code == GOT_ERR_ITER_COMPLETED)
2873 err = NULL;
2874 break;
2877 if (id) {
2878 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2879 break;
2880 if (got_object_id_cmp(id, commit_id) == 0) {
2881 is_same_branch = 1;
2882 break;
2886 done:
2887 if (graph)
2888 got_commit_graph_close(graph);
2889 free(head_commit_id);
2890 if (!err && !is_same_branch)
2891 err = got_error(GOT_ERR_ANCESTRY);
2892 return err;
2895 static const struct got_error *
2896 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2898 static char msg[512];
2899 const char *branch_name;
2901 if (got_ref_is_symbolic(ref))
2902 branch_name = got_ref_get_symref_target(ref);
2903 else
2904 branch_name = got_ref_get_name(ref);
2906 if (strncmp("refs/heads/", branch_name, 11) == 0)
2907 branch_name += 11;
2909 snprintf(msg, sizeof(msg),
2910 "target commit is not contained in branch '%s'; "
2911 "the branch to use must be specified with -b; "
2912 "if necessary a new branch can be created for "
2913 "this commit with 'got branch -c %s BRANCH_NAME'",
2914 branch_name, commit_id_str);
2916 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2919 static const struct got_error *
2920 cmd_checkout(int argc, char *argv[])
2922 const struct got_error *error = NULL;
2923 struct got_repository *repo = NULL;
2924 struct got_reference *head_ref = NULL, *ref = NULL;
2925 struct got_worktree *worktree = NULL;
2926 char *repo_path = NULL;
2927 char *worktree_path = NULL;
2928 const char *path_prefix = "";
2929 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2930 char *commit_id_str = NULL;
2931 struct got_object_id *commit_id = NULL;
2932 char *cwd = NULL;
2933 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2934 struct got_pathlist_head paths;
2935 struct got_checkout_progress_arg cpa;
2936 int *pack_fds = NULL;
2938 TAILQ_INIT(&paths);
2940 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2941 switch (ch) {
2942 case 'b':
2943 branch_name = optarg;
2944 break;
2945 case 'c':
2946 commit_id_str = strdup(optarg);
2947 if (commit_id_str == NULL)
2948 return got_error_from_errno("strdup");
2949 break;
2950 case 'E':
2951 allow_nonempty = 1;
2952 break;
2953 case 'p':
2954 path_prefix = optarg;
2955 break;
2956 case 'q':
2957 verbosity = -1;
2958 break;
2959 default:
2960 usage_checkout();
2961 /* NOTREACHED */
2965 argc -= optind;
2966 argv += optind;
2968 #ifndef PROFILE
2969 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2970 "unveil", NULL) == -1)
2971 err(1, "pledge");
2972 #endif
2973 if (argc == 1) {
2974 char *base, *dotgit;
2975 const char *path;
2976 repo_path = realpath(argv[0], NULL);
2977 if (repo_path == NULL)
2978 return got_error_from_errno2("realpath", argv[0]);
2979 cwd = getcwd(NULL, 0);
2980 if (cwd == NULL) {
2981 error = got_error_from_errno("getcwd");
2982 goto done;
2984 if (path_prefix[0])
2985 path = path_prefix;
2986 else
2987 path = repo_path;
2988 error = got_path_basename(&base, path);
2989 if (error)
2990 goto done;
2991 dotgit = strstr(base, ".git");
2992 if (dotgit)
2993 *dotgit = '\0';
2994 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2995 error = got_error_from_errno("asprintf");
2996 free(base);
2997 goto done;
2999 free(base);
3000 } else if (argc == 2) {
3001 repo_path = realpath(argv[0], NULL);
3002 if (repo_path == NULL) {
3003 error = got_error_from_errno2("realpath", argv[0]);
3004 goto done;
3006 worktree_path = realpath(argv[1], NULL);
3007 if (worktree_path == NULL) {
3008 if (errno != ENOENT) {
3009 error = got_error_from_errno2("realpath",
3010 argv[1]);
3011 goto done;
3013 worktree_path = strdup(argv[1]);
3014 if (worktree_path == NULL) {
3015 error = got_error_from_errno("strdup");
3016 goto done;
3019 } else
3020 usage_checkout();
3022 got_path_strip_trailing_slashes(repo_path);
3023 got_path_strip_trailing_slashes(worktree_path);
3025 error = got_repo_pack_fds_open(&pack_fds);
3026 if (error != NULL)
3027 goto done;
3029 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3030 if (error != NULL)
3031 goto done;
3033 /* Pre-create work tree path for unveil(2) */
3034 error = got_path_mkdir(worktree_path);
3035 if (error) {
3036 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3037 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3038 goto done;
3039 if (!allow_nonempty &&
3040 !got_path_dir_is_empty(worktree_path)) {
3041 error = got_error_path(worktree_path,
3042 GOT_ERR_DIR_NOT_EMPTY);
3043 goto done;
3047 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3048 if (error)
3049 goto done;
3051 error = got_ref_open(&head_ref, repo, branch_name, 0);
3052 if (error != NULL)
3053 goto done;
3055 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3056 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3057 goto done;
3059 error = got_worktree_open(&worktree, worktree_path);
3060 if (error != NULL)
3061 goto done;
3063 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3064 path_prefix);
3065 if (error != NULL)
3066 goto done;
3067 if (!same_path_prefix) {
3068 error = got_error(GOT_ERR_PATH_PREFIX);
3069 goto done;
3072 if (commit_id_str) {
3073 struct got_reflist_head refs;
3074 TAILQ_INIT(&refs);
3075 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3076 NULL);
3077 if (error)
3078 goto done;
3079 error = got_repo_match_object_id(&commit_id, NULL,
3080 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3081 got_ref_list_free(&refs);
3082 if (error)
3083 goto done;
3084 error = check_linear_ancestry(commit_id,
3085 got_worktree_get_base_commit_id(worktree), 0, repo);
3086 if (error != NULL) {
3087 if (error->code == GOT_ERR_ANCESTRY) {
3088 error = checkout_ancestry_error(
3089 head_ref, commit_id_str);
3091 goto done;
3093 error = check_same_branch(commit_id, head_ref, NULL, repo);
3094 if (error) {
3095 if (error->code == GOT_ERR_ANCESTRY) {
3096 error = checkout_ancestry_error(
3097 head_ref, commit_id_str);
3099 goto done;
3101 error = got_worktree_set_base_commit_id(worktree, repo,
3102 commit_id);
3103 if (error)
3104 goto done;
3105 /* Expand potentially abbreviated commit ID string. */
3106 free(commit_id_str);
3107 error = got_object_id_str(&commit_id_str, commit_id);
3108 if (error)
3109 goto done;
3110 } else {
3111 commit_id = got_object_id_dup(
3112 got_worktree_get_base_commit_id(worktree));
3113 if (commit_id == NULL) {
3114 error = got_error_from_errno("got_object_id_dup");
3115 goto done;
3117 error = got_object_id_str(&commit_id_str, commit_id);
3118 if (error)
3119 goto done;
3122 error = got_pathlist_append(&paths, "", NULL);
3123 if (error)
3124 goto done;
3125 cpa.worktree_path = worktree_path;
3126 cpa.had_base_commit_ref_error = 0;
3127 cpa.verbosity = verbosity;
3128 error = got_worktree_checkout_files(worktree, &paths, repo,
3129 checkout_progress, &cpa, check_cancelled, NULL);
3130 if (error != NULL)
3131 goto done;
3133 if (got_ref_is_symbolic(head_ref)) {
3134 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3135 if (error)
3136 goto done;
3137 refname = got_ref_get_name(ref);
3138 } else
3139 refname = got_ref_get_name(head_ref);
3140 printf("Checked out %s: %s\n", refname, commit_id_str);
3141 printf("Now shut up and hack\n");
3142 if (cpa.had_base_commit_ref_error)
3143 show_worktree_base_ref_warning();
3144 done:
3145 if (pack_fds) {
3146 const struct got_error *pack_err =
3147 got_repo_pack_fds_close(pack_fds);
3148 if (error == NULL)
3149 error = pack_err;
3151 if (head_ref)
3152 got_ref_close(head_ref);
3153 if (ref)
3154 got_ref_close(ref);
3155 got_pathlist_free(&paths);
3156 free(commit_id_str);
3157 free(commit_id);
3158 free(repo_path);
3159 free(worktree_path);
3160 free(cwd);
3161 return error;
3164 struct got_update_progress_arg {
3165 int did_something;
3166 int conflicts;
3167 int obstructed;
3168 int not_updated;
3169 int missing;
3170 int not_deleted;
3171 int unversioned;
3172 int verbosity;
3175 static void
3176 print_update_progress_stats(struct got_update_progress_arg *upa)
3178 if (!upa->did_something)
3179 return;
3181 if (upa->conflicts > 0)
3182 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3183 if (upa->obstructed > 0)
3184 printf("File paths obstructed by a non-regular file: %d\n",
3185 upa->obstructed);
3186 if (upa->not_updated > 0)
3187 printf("Files not updated because of existing merge "
3188 "conflicts: %d\n", upa->not_updated);
3192 * The meaning of some status codes differs between merge-style operations and
3193 * update operations. For example, the ! status code means "file was missing"
3194 * if changes were merged into the work tree, and "missing file was restored"
3195 * if the work tree was updated. This function should be used by any operation
3196 * which merges changes into the work tree without updating the work tree.
3198 static void
3199 print_merge_progress_stats(struct got_update_progress_arg *upa)
3201 if (!upa->did_something)
3202 return;
3204 if (upa->conflicts > 0)
3205 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3206 if (upa->obstructed > 0)
3207 printf("File paths obstructed by a non-regular file: %d\n",
3208 upa->obstructed);
3209 if (upa->missing > 0)
3210 printf("Files which had incoming changes but could not be "
3211 "found in the work tree: %d\n", upa->missing);
3212 if (upa->not_deleted > 0)
3213 printf("Files not deleted due to differences in deleted "
3214 "content: %d\n", upa->not_deleted);
3215 if (upa->unversioned > 0)
3216 printf("Files not merged because an unversioned file was "
3217 "found in the work tree: %d\n", upa->unversioned);
3220 __dead static void
3221 usage_update(void)
3223 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3224 "[path ...]\n",
3225 getprogname());
3226 exit(1);
3229 static const struct got_error *
3230 update_progress(void *arg, unsigned char status, const char *path)
3232 struct got_update_progress_arg *upa = arg;
3234 if (status == GOT_STATUS_EXISTS ||
3235 status == GOT_STATUS_BASE_REF_ERR)
3236 return NULL;
3238 upa->did_something = 1;
3240 /* Base commit bump happens silently. */
3241 if (status == GOT_STATUS_BUMP_BASE)
3242 return NULL;
3244 if (status == GOT_STATUS_CONFLICT)
3245 upa->conflicts++;
3246 if (status == GOT_STATUS_OBSTRUCTED)
3247 upa->obstructed++;
3248 if (status == GOT_STATUS_CANNOT_UPDATE)
3249 upa->not_updated++;
3250 if (status == GOT_STATUS_MISSING)
3251 upa->missing++;
3252 if (status == GOT_STATUS_CANNOT_DELETE)
3253 upa->not_deleted++;
3254 if (status == GOT_STATUS_UNVERSIONED)
3255 upa->unversioned++;
3257 while (path[0] == '/')
3258 path++;
3259 if (upa->verbosity >= 0)
3260 printf("%c %s\n", status, path);
3262 return NULL;
3265 static const struct got_error *
3266 switch_head_ref(struct got_reference *head_ref,
3267 struct got_object_id *commit_id, struct got_worktree *worktree,
3268 struct got_repository *repo)
3270 const struct got_error *err = NULL;
3271 char *base_id_str;
3272 int ref_has_moved = 0;
3274 /* Trivial case: switching between two different references. */
3275 if (strcmp(got_ref_get_name(head_ref),
3276 got_worktree_get_head_ref_name(worktree)) != 0) {
3277 printf("Switching work tree from %s to %s\n",
3278 got_worktree_get_head_ref_name(worktree),
3279 got_ref_get_name(head_ref));
3280 return got_worktree_set_head_ref(worktree, head_ref);
3283 err = check_linear_ancestry(commit_id,
3284 got_worktree_get_base_commit_id(worktree), 0, repo);
3285 if (err) {
3286 if (err->code != GOT_ERR_ANCESTRY)
3287 return err;
3288 ref_has_moved = 1;
3290 if (!ref_has_moved)
3291 return NULL;
3293 /* Switching to a rebased branch with the same reference name. */
3294 err = got_object_id_str(&base_id_str,
3295 got_worktree_get_base_commit_id(worktree));
3296 if (err)
3297 return err;
3298 printf("Reference %s now points at a different branch\n",
3299 got_worktree_get_head_ref_name(worktree));
3300 printf("Switching work tree from %s to %s\n", base_id_str,
3301 got_worktree_get_head_ref_name(worktree));
3302 return NULL;
3305 static const struct got_error *
3306 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3308 const struct got_error *err;
3309 int in_progress;
3311 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3312 if (err)
3313 return err;
3314 if (in_progress)
3315 return got_error(GOT_ERR_REBASING);
3317 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3318 if (err)
3319 return err;
3320 if (in_progress)
3321 return got_error(GOT_ERR_HISTEDIT_BUSY);
3323 return NULL;
3326 static const struct got_error *
3327 check_merge_in_progress(struct got_worktree *worktree,
3328 struct got_repository *repo)
3330 const struct got_error *err;
3331 int in_progress;
3333 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3334 if (err)
3335 return err;
3336 if (in_progress)
3337 return got_error(GOT_ERR_MERGE_BUSY);
3339 return NULL;
3342 static const struct got_error *
3343 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3344 char *argv[], struct got_worktree *worktree)
3346 const struct got_error *err = NULL;
3347 char *path;
3348 struct got_pathlist_entry *new;
3349 int i;
3351 if (argc == 0) {
3352 path = strdup("");
3353 if (path == NULL)
3354 return got_error_from_errno("strdup");
3355 return got_pathlist_append(paths, path, NULL);
3358 for (i = 0; i < argc; i++) {
3359 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3360 if (err)
3361 break;
3362 err = got_pathlist_insert(&new, paths, path, NULL);
3363 if (err || new == NULL /* duplicate */) {
3364 free(path);
3365 if (err)
3366 break;
3370 return err;
3373 static const struct got_error *
3374 wrap_not_worktree_error(const struct got_error *orig_err,
3375 const char *cmdname, const char *path)
3377 const struct got_error *err;
3378 struct got_repository *repo;
3379 static char msg[512];
3380 int *pack_fds = NULL;
3382 err = got_repo_pack_fds_open(&pack_fds);
3383 if (err)
3384 return err;
3386 err = got_repo_open(&repo, path, NULL, pack_fds);
3387 if (err)
3388 return orig_err;
3390 snprintf(msg, sizeof(msg),
3391 "'got %s' needs a work tree in addition to a git repository\n"
3392 "Work trees can be checked out from this Git repository with "
3393 "'got checkout'.\n"
3394 "The got(1) manual page contains more information.", cmdname);
3395 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3396 got_repo_close(repo);
3397 if (pack_fds) {
3398 const struct got_error *pack_err =
3399 got_repo_pack_fds_close(pack_fds);
3400 if (err == NULL)
3401 err = pack_err;
3403 return err;
3406 static const struct got_error *
3407 cmd_update(int argc, char *argv[])
3409 const struct got_error *error = NULL;
3410 struct got_repository *repo = NULL;
3411 struct got_worktree *worktree = NULL;
3412 char *worktree_path = NULL;
3413 struct got_object_id *commit_id = NULL;
3414 char *commit_id_str = NULL;
3415 const char *branch_name = NULL;
3416 struct got_reference *head_ref = NULL;
3417 struct got_pathlist_head paths;
3418 struct got_pathlist_entry *pe;
3419 int ch, verbosity = 0;
3420 struct got_update_progress_arg upa;
3421 int *pack_fds = NULL;
3423 TAILQ_INIT(&paths);
3425 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3426 switch (ch) {
3427 case 'b':
3428 branch_name = optarg;
3429 break;
3430 case 'c':
3431 commit_id_str = strdup(optarg);
3432 if (commit_id_str == NULL)
3433 return got_error_from_errno("strdup");
3434 break;
3435 case 'q':
3436 verbosity = -1;
3437 break;
3438 default:
3439 usage_update();
3440 /* NOTREACHED */
3444 argc -= optind;
3445 argv += optind;
3447 #ifndef PROFILE
3448 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3449 "unveil", NULL) == -1)
3450 err(1, "pledge");
3451 #endif
3452 worktree_path = getcwd(NULL, 0);
3453 if (worktree_path == NULL) {
3454 error = got_error_from_errno("getcwd");
3455 goto done;
3458 error = got_repo_pack_fds_open(&pack_fds);
3459 if (error != NULL)
3460 goto done;
3462 error = got_worktree_open(&worktree, worktree_path);
3463 if (error) {
3464 if (error->code == GOT_ERR_NOT_WORKTREE)
3465 error = wrap_not_worktree_error(error, "update",
3466 worktree_path);
3467 goto done;
3470 error = check_rebase_or_histedit_in_progress(worktree);
3471 if (error)
3472 goto done;
3474 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3475 NULL, pack_fds);
3476 if (error != NULL)
3477 goto done;
3479 error = apply_unveil(got_repo_get_path(repo), 0,
3480 got_worktree_get_root_path(worktree));
3481 if (error)
3482 goto done;
3484 error = check_merge_in_progress(worktree, repo);
3485 if (error)
3486 goto done;
3488 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3489 if (error)
3490 goto done;
3492 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3493 got_worktree_get_head_ref_name(worktree), 0);
3494 if (error != NULL)
3495 goto done;
3496 if (commit_id_str == NULL) {
3497 error = got_ref_resolve(&commit_id, repo, head_ref);
3498 if (error != NULL)
3499 goto done;
3500 error = got_object_id_str(&commit_id_str, commit_id);
3501 if (error != NULL)
3502 goto done;
3503 } else {
3504 struct got_reflist_head refs;
3505 TAILQ_INIT(&refs);
3506 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3507 NULL);
3508 if (error)
3509 goto done;
3510 error = got_repo_match_object_id(&commit_id, NULL,
3511 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3512 got_ref_list_free(&refs);
3513 free(commit_id_str);
3514 commit_id_str = NULL;
3515 if (error)
3516 goto done;
3517 error = got_object_id_str(&commit_id_str, commit_id);
3518 if (error)
3519 goto done;
3522 if (branch_name) {
3523 struct got_object_id *head_commit_id;
3524 TAILQ_FOREACH(pe, &paths, entry) {
3525 if (pe->path_len == 0)
3526 continue;
3527 error = got_error_msg(GOT_ERR_BAD_PATH,
3528 "switching between branches requires that "
3529 "the entire work tree gets updated");
3530 goto done;
3532 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3533 if (error)
3534 goto done;
3535 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3536 repo);
3537 free(head_commit_id);
3538 if (error != NULL)
3539 goto done;
3540 error = check_same_branch(commit_id, head_ref, NULL, repo);
3541 if (error)
3542 goto done;
3543 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3544 if (error)
3545 goto done;
3546 } else {
3547 error = check_linear_ancestry(commit_id,
3548 got_worktree_get_base_commit_id(worktree), 0, repo);
3549 if (error != NULL) {
3550 if (error->code == GOT_ERR_ANCESTRY)
3551 error = got_error(GOT_ERR_BRANCH_MOVED);
3552 goto done;
3554 error = check_same_branch(commit_id, head_ref, NULL, repo);
3555 if (error)
3556 goto done;
3559 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3560 commit_id) != 0) {
3561 error = got_worktree_set_base_commit_id(worktree, repo,
3562 commit_id);
3563 if (error)
3564 goto done;
3567 memset(&upa, 0, sizeof(upa));
3568 upa.verbosity = verbosity;
3569 error = got_worktree_checkout_files(worktree, &paths, repo,
3570 update_progress, &upa, check_cancelled, NULL);
3571 if (error != NULL)
3572 goto done;
3574 if (upa.did_something) {
3575 printf("Updated to %s: %s\n",
3576 got_worktree_get_head_ref_name(worktree), commit_id_str);
3577 } else
3578 printf("Already up-to-date\n");
3580 print_update_progress_stats(&upa);
3581 done:
3582 if (pack_fds) {
3583 const struct got_error *pack_err =
3584 got_repo_pack_fds_close(pack_fds);
3585 if (error == NULL)
3586 error = pack_err;
3588 free(worktree_path);
3589 TAILQ_FOREACH(pe, &paths, entry)
3590 free((char *)pe->path);
3591 got_pathlist_free(&paths);
3592 free(commit_id);
3593 free(commit_id_str);
3594 return error;
3597 static const struct got_error *
3598 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3599 const char *path, int diff_context, int ignore_whitespace,
3600 int force_text_diff, struct got_repository *repo, FILE *outfile)
3602 const struct got_error *err = NULL;
3603 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3604 FILE *f1 = NULL, *f2 = NULL;
3605 int fd1 = -1, fd2 = -1;
3607 fd1 = got_opentempfd();
3608 if (fd1 == -1)
3609 return got_error_from_errno("got_opentempfd");
3610 fd2 = got_opentempfd();
3611 if (fd2 == -1) {
3612 err = got_error_from_errno("got_opentempfd");
3613 goto done;
3616 if (blob_id1) {
3617 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3618 fd1);
3619 if (err)
3620 goto done;
3623 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3624 if (err)
3625 goto done;
3627 f1 = got_opentemp();
3628 if (f1 == NULL) {
3629 err = got_error_from_errno("got_opentemp");
3630 goto done;
3632 f2 = got_opentemp();
3633 if (f2 == NULL) {
3634 err = got_error_from_errno("got_opentemp");
3635 goto done;
3638 while (path[0] == '/')
3639 path++;
3640 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3641 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3642 force_text_diff, outfile);
3643 done:
3644 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3645 err = got_error_from_errno("close");
3646 if (blob1)
3647 got_object_blob_close(blob1);
3648 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3649 err = got_error_from_errno("close");
3650 got_object_blob_close(blob2);
3651 if (f1 && fclose(f1) == EOF && err == NULL)
3652 err = got_error_from_errno("fclose");
3653 if (f2 && fclose(f2) == EOF && err == NULL)
3654 err = got_error_from_errno("fclose");
3655 return err;
3658 static const struct got_error *
3659 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3660 const char *path, int diff_context, int ignore_whitespace,
3661 int force_text_diff, struct got_repository *repo, FILE *outfile)
3663 const struct got_error *err = NULL;
3664 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3665 struct got_diff_blob_output_unidiff_arg arg;
3666 FILE *f1 = NULL, *f2 = NULL;
3667 int fd1 = -1, fd2 = -1;
3669 if (tree_id1) {
3670 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3671 if (err)
3672 goto done;
3673 fd1 = got_opentempfd();
3674 if (fd1 == -1) {
3675 err = got_error_from_errno("got_opentempfd");
3676 goto done;
3680 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3681 if (err)
3682 goto done;
3684 f1 = got_opentemp();
3685 if (f1 == NULL) {
3686 err = got_error_from_errno("got_opentemp");
3687 goto done;
3690 f2 = got_opentemp();
3691 if (f2 == NULL) {
3692 err = got_error_from_errno("got_opentemp");
3693 goto done;
3695 fd2 = got_opentempfd();
3696 if (fd2 == -1) {
3697 err = got_error_from_errno("got_opentempfd");
3698 goto done;
3700 arg.diff_context = diff_context;
3701 arg.ignore_whitespace = ignore_whitespace;
3702 arg.force_text_diff = force_text_diff;
3703 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3704 arg.outfile = outfile;
3705 arg.line_offsets = NULL;
3706 arg.nlines = 0;
3707 while (path[0] == '/')
3708 path++;
3709 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3710 got_diff_blob_output_unidiff, &arg, 1);
3711 done:
3712 if (tree1)
3713 got_object_tree_close(tree1);
3714 if (tree2)
3715 got_object_tree_close(tree2);
3716 if (f1 && fclose(f1) == EOF && err == NULL)
3717 err = got_error_from_errno("fclose");
3718 if (f2 && fclose(f2) == EOF && err == NULL)
3719 err = got_error_from_errno("fclose");
3720 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3721 err = got_error_from_errno("close");
3722 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3723 err = got_error_from_errno("close");
3724 return err;
3727 static const struct got_error *
3728 get_changed_paths(struct got_pathlist_head *paths,
3729 struct got_commit_object *commit, struct got_repository *repo)
3731 const struct got_error *err = NULL;
3732 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3733 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3734 struct got_object_qid *qid;
3736 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3737 if (qid != NULL) {
3738 struct got_commit_object *pcommit;
3739 err = got_object_open_as_commit(&pcommit, repo,
3740 &qid->id);
3741 if (err)
3742 return err;
3744 tree_id1 = got_object_id_dup(
3745 got_object_commit_get_tree_id(pcommit));
3746 if (tree_id1 == NULL) {
3747 got_object_commit_close(pcommit);
3748 return got_error_from_errno("got_object_id_dup");
3750 got_object_commit_close(pcommit);
3754 if (tree_id1) {
3755 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3756 if (err)
3757 goto done;
3760 tree_id2 = got_object_commit_get_tree_id(commit);
3761 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3762 if (err)
3763 goto done;
3765 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3766 got_diff_tree_collect_changed_paths, paths, 0);
3767 done:
3768 if (tree1)
3769 got_object_tree_close(tree1);
3770 if (tree2)
3771 got_object_tree_close(tree2);
3772 free(tree_id1);
3773 return err;
3776 static const struct got_error *
3777 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3778 const char *path, int diff_context, struct got_repository *repo,
3779 FILE *outfile)
3781 const struct got_error *err = NULL;
3782 struct got_commit_object *pcommit = NULL;
3783 char *id_str1 = NULL, *id_str2 = NULL;
3784 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3785 struct got_object_qid *qid;
3787 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3788 if (qid != NULL) {
3789 err = got_object_open_as_commit(&pcommit, repo,
3790 &qid->id);
3791 if (err)
3792 return err;
3793 err = got_object_id_str(&id_str1, &qid->id);
3794 if (err)
3795 goto done;
3798 err = got_object_id_str(&id_str2, id);
3799 if (err)
3800 goto done;
3802 if (path && path[0] != '\0') {
3803 int obj_type;
3804 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3805 if (err)
3806 goto done;
3807 if (pcommit) {
3808 err = got_object_id_by_path(&obj_id1, repo,
3809 pcommit, path);
3810 if (err) {
3811 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3812 free(obj_id2);
3813 goto done;
3817 err = got_object_get_type(&obj_type, repo, obj_id2);
3818 if (err) {
3819 free(obj_id2);
3820 goto done;
3822 fprintf(outfile,
3823 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3824 fprintf(outfile, "commit - %s\n",
3825 id_str1 ? id_str1 : "/dev/null");
3826 fprintf(outfile, "commit + %s\n", id_str2);
3827 switch (obj_type) {
3828 case GOT_OBJ_TYPE_BLOB:
3829 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3830 0, 0, repo, outfile);
3831 break;
3832 case GOT_OBJ_TYPE_TREE:
3833 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3834 0, 0, repo, outfile);
3835 break;
3836 default:
3837 err = got_error(GOT_ERR_OBJ_TYPE);
3838 break;
3840 free(obj_id1);
3841 free(obj_id2);
3842 } else {
3843 obj_id2 = got_object_commit_get_tree_id(commit);
3844 if (pcommit)
3845 obj_id1 = got_object_commit_get_tree_id(pcommit);
3846 fprintf(outfile,
3847 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3848 fprintf(outfile, "commit - %s\n",
3849 id_str1 ? id_str1 : "/dev/null");
3850 fprintf(outfile, "commit + %s\n", id_str2);
3851 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3852 repo, outfile);
3854 done:
3855 free(id_str1);
3856 free(id_str2);
3857 if (pcommit)
3858 got_object_commit_close(pcommit);
3859 return err;
3862 static char *
3863 get_datestr(time_t *time, char *datebuf)
3865 struct tm mytm, *tm;
3866 char *p, *s;
3868 tm = gmtime_r(time, &mytm);
3869 if (tm == NULL)
3870 return NULL;
3871 s = asctime_r(tm, datebuf);
3872 if (s == NULL)
3873 return NULL;
3874 p = strchr(s, '\n');
3875 if (p)
3876 *p = '\0';
3877 return s;
3880 static const struct got_error *
3881 match_commit(int *have_match, struct got_object_id *id,
3882 struct got_commit_object *commit, regex_t *regex)
3884 const struct got_error *err = NULL;
3885 regmatch_t regmatch;
3886 char *id_str = NULL, *logmsg = NULL;
3888 *have_match = 0;
3890 err = got_object_id_str(&id_str, id);
3891 if (err)
3892 return err;
3894 err = got_object_commit_get_logmsg(&logmsg, commit);
3895 if (err)
3896 goto done;
3898 if (regexec(regex, got_object_commit_get_author(commit), 1,
3899 &regmatch, 0) == 0 ||
3900 regexec(regex, got_object_commit_get_committer(commit), 1,
3901 &regmatch, 0) == 0 ||
3902 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3903 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3904 *have_match = 1;
3905 done:
3906 free(id_str);
3907 free(logmsg);
3908 return err;
3911 static void
3912 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3913 regex_t *regex)
3915 regmatch_t regmatch;
3916 struct got_pathlist_entry *pe;
3918 *have_match = 0;
3920 TAILQ_FOREACH(pe, changed_paths, entry) {
3921 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3922 *have_match = 1;
3923 break;
3928 static const struct got_error *
3929 match_patch(int *have_match, struct got_commit_object *commit,
3930 struct got_object_id *id, const char *path, int diff_context,
3931 struct got_repository *repo, regex_t *regex, FILE *f)
3933 const struct got_error *err = NULL;
3934 char *line = NULL;
3935 size_t linesize = 0;
3936 ssize_t linelen;
3937 regmatch_t regmatch;
3939 *have_match = 0;
3941 err = got_opentemp_truncate(f);
3942 if (err)
3943 return err;
3945 err = print_patch(commit, id, path, diff_context, repo, f);
3946 if (err)
3947 goto done;
3949 if (fseeko(f, 0L, SEEK_SET) == -1) {
3950 err = got_error_from_errno("fseeko");
3951 goto done;
3954 while ((linelen = getline(&line, &linesize, f)) != -1) {
3955 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3956 *have_match = 1;
3957 break;
3960 done:
3961 free(line);
3962 return err;
3965 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3967 static const struct got_error*
3968 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3969 struct got_object_id *id, struct got_repository *repo,
3970 int local_only)
3972 static const struct got_error *err = NULL;
3973 struct got_reflist_entry *re;
3974 char *s;
3975 const char *name;
3977 *refs_str = NULL;
3979 TAILQ_FOREACH(re, refs, entry) {
3980 struct got_tag_object *tag = NULL;
3981 struct got_object_id *ref_id;
3982 int cmp;
3984 name = got_ref_get_name(re->ref);
3985 if (strcmp(name, GOT_REF_HEAD) == 0)
3986 continue;
3987 if (strncmp(name, "refs/", 5) == 0)
3988 name += 5;
3989 if (strncmp(name, "got/", 4) == 0)
3990 continue;
3991 if (strncmp(name, "heads/", 6) == 0)
3992 name += 6;
3993 if (strncmp(name, "remotes/", 8) == 0) {
3994 if (local_only)
3995 continue;
3996 name += 8;
3997 s = strstr(name, "/" GOT_REF_HEAD);
3998 if (s != NULL && s[strlen(s)] == '\0')
3999 continue;
4001 err = got_ref_resolve(&ref_id, repo, re->ref);
4002 if (err)
4003 break;
4004 if (strncmp(name, "tags/", 5) == 0) {
4005 err = got_object_open_as_tag(&tag, repo, ref_id);
4006 if (err) {
4007 if (err->code != GOT_ERR_OBJ_TYPE) {
4008 free(ref_id);
4009 break;
4011 /* Ref points at something other than a tag. */
4012 err = NULL;
4013 tag = NULL;
4016 cmp = got_object_id_cmp(tag ?
4017 got_object_tag_get_object_id(tag) : ref_id, id);
4018 free(ref_id);
4019 if (tag)
4020 got_object_tag_close(tag);
4021 if (cmp != 0)
4022 continue;
4023 s = *refs_str;
4024 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4025 s ? ", " : "", name) == -1) {
4026 err = got_error_from_errno("asprintf");
4027 free(s);
4028 *refs_str = NULL;
4029 break;
4031 free(s);
4034 return err;
4037 static const struct got_error *
4038 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4039 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4041 const struct got_error *err = NULL;
4042 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4043 char *comma, *s, *nl;
4044 struct got_reflist_head *refs;
4045 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4046 struct tm tm;
4047 time_t committer_time;
4049 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4050 if (refs) {
4051 err = build_refs_str(&ref_str, refs, id, repo, 1);
4052 if (err)
4053 return err;
4055 /* Display the first matching ref only. */
4056 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4057 *comma = '\0';
4060 if (ref_str == NULL) {
4061 err = got_object_id_str(&id_str, id);
4062 if (err)
4063 return err;
4066 committer_time = got_object_commit_get_committer_time(commit);
4067 if (gmtime_r(&committer_time, &tm) == NULL) {
4068 err = got_error_from_errno("gmtime_r");
4069 goto done;
4071 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4072 err = got_error(GOT_ERR_NO_SPACE);
4073 goto done;
4076 err = got_object_commit_get_logmsg(&logmsg0, commit);
4077 if (err)
4078 goto done;
4080 s = logmsg0;
4081 while (isspace((unsigned char)s[0]))
4082 s++;
4084 nl = strchr(s, '\n');
4085 if (nl) {
4086 *nl = '\0';
4089 if (ref_str)
4090 printf("%s%-7s %s\n", datebuf, ref_str, s);
4091 else
4092 printf("%s%.7s %s\n", datebuf, id_str, s);
4094 if (fflush(stdout) != 0 && err == NULL)
4095 err = got_error_from_errno("fflush");
4096 done:
4097 free(id_str);
4098 free(ref_str);
4099 free(logmsg0);
4100 return err;
4103 static const struct got_error *
4104 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4105 struct got_repository *repo, const char *path,
4106 struct got_pathlist_head *changed_paths, int show_patch,
4107 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4108 const char *custom_refs_str)
4110 const struct got_error *err = NULL;
4111 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4112 char datebuf[26];
4113 time_t committer_time;
4114 const char *author, *committer;
4115 char *refs_str = NULL;
4117 err = got_object_id_str(&id_str, id);
4118 if (err)
4119 return err;
4121 if (custom_refs_str == NULL) {
4122 struct got_reflist_head *refs;
4123 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4124 if (refs) {
4125 err = build_refs_str(&refs_str, refs, id, repo, 0);
4126 if (err)
4127 goto done;
4131 printf(GOT_COMMIT_SEP_STR);
4132 if (custom_refs_str)
4133 printf("commit %s (%s)\n", id_str, custom_refs_str);
4134 else
4135 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4136 refs_str ? refs_str : "", refs_str ? ")" : "");
4137 free(id_str);
4138 id_str = NULL;
4139 free(refs_str);
4140 refs_str = NULL;
4141 printf("from: %s\n", got_object_commit_get_author(commit));
4142 committer_time = got_object_commit_get_committer_time(commit);
4143 datestr = get_datestr(&committer_time, datebuf);
4144 if (datestr)
4145 printf("date: %s UTC\n", datestr);
4146 author = got_object_commit_get_author(commit);
4147 committer = got_object_commit_get_committer(commit);
4148 if (strcmp(author, committer) != 0)
4149 printf("via: %s\n", committer);
4150 if (got_object_commit_get_nparents(commit) > 1) {
4151 const struct got_object_id_queue *parent_ids;
4152 struct got_object_qid *qid;
4153 int n = 1;
4154 parent_ids = got_object_commit_get_parent_ids(commit);
4155 STAILQ_FOREACH(qid, parent_ids, entry) {
4156 err = got_object_id_str(&id_str, &qid->id);
4157 if (err)
4158 goto done;
4159 printf("parent %d: %s\n", n++, id_str);
4160 free(id_str);
4161 id_str = NULL;
4165 err = got_object_commit_get_logmsg(&logmsg0, commit);
4166 if (err)
4167 goto done;
4169 logmsg = logmsg0;
4170 do {
4171 line = strsep(&logmsg, "\n");
4172 if (line)
4173 printf(" %s\n", line);
4174 } while (line);
4175 free(logmsg0);
4177 if (changed_paths) {
4178 struct got_pathlist_entry *pe;
4179 TAILQ_FOREACH(pe, changed_paths, entry) {
4180 struct got_diff_changed_path *cp = pe->data;
4181 printf(" %c %s\n", cp->status, pe->path);
4183 printf("\n");
4185 if (show_patch) {
4186 err = print_patch(commit, id, path, diff_context, repo, stdout);
4187 if (err == 0)
4188 printf("\n");
4191 if (fflush(stdout) != 0 && err == NULL)
4192 err = got_error_from_errno("fflush");
4193 done:
4194 free(id_str);
4195 free(refs_str);
4196 return err;
4199 static const struct got_error *
4200 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4201 struct got_repository *repo, const char *path, int show_changed_paths,
4202 int show_patch, const char *search_pattern, int diff_context, int limit,
4203 int log_branches, int reverse_display_order,
4204 struct got_reflist_object_id_map *refs_idmap, int one_line,
4205 FILE *tmpfile)
4207 const struct got_error *err;
4208 struct got_commit_graph *graph;
4209 regex_t regex;
4210 int have_match;
4211 struct got_object_id_queue reversed_commits;
4212 struct got_object_qid *qid;
4213 struct got_commit_object *commit;
4214 struct got_pathlist_head changed_paths;
4215 struct got_pathlist_entry *pe;
4217 STAILQ_INIT(&reversed_commits);
4218 TAILQ_INIT(&changed_paths);
4220 if (search_pattern && regcomp(&regex, search_pattern,
4221 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4222 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4224 err = got_commit_graph_open(&graph, path, !log_branches);
4225 if (err)
4226 return err;
4227 err = got_commit_graph_iter_start(graph, root_id, repo,
4228 check_cancelled, NULL);
4229 if (err)
4230 goto done;
4231 for (;;) {
4232 struct got_object_id *id;
4234 if (sigint_received || sigpipe_received)
4235 break;
4237 err = got_commit_graph_iter_next(&id, graph, repo,
4238 check_cancelled, NULL);
4239 if (err) {
4240 if (err->code == GOT_ERR_ITER_COMPLETED)
4241 err = NULL;
4242 break;
4244 if (id == NULL)
4245 break;
4247 err = got_object_open_as_commit(&commit, repo, id);
4248 if (err)
4249 break;
4251 if (show_changed_paths && !reverse_display_order) {
4252 err = get_changed_paths(&changed_paths, commit, repo);
4253 if (err)
4254 break;
4257 if (search_pattern) {
4258 err = match_commit(&have_match, id, commit, &regex);
4259 if (err) {
4260 got_object_commit_close(commit);
4261 break;
4263 if (have_match == 0 && show_changed_paths)
4264 match_changed_paths(&have_match,
4265 &changed_paths, &regex);
4266 if (have_match == 0 && show_patch) {
4267 err = match_patch(&have_match, commit, id,
4268 path, diff_context, repo, &regex,
4269 tmpfile);
4270 if (err)
4271 break;
4273 if (have_match == 0) {
4274 got_object_commit_close(commit);
4275 TAILQ_FOREACH(pe, &changed_paths, entry) {
4276 free((char *)pe->path);
4277 free(pe->data);
4279 got_pathlist_free(&changed_paths);
4280 continue;
4284 if (reverse_display_order) {
4285 err = got_object_qid_alloc(&qid, id);
4286 if (err)
4287 break;
4288 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4289 got_object_commit_close(commit);
4290 } else {
4291 if (one_line)
4292 err = print_commit_oneline(commit, id,
4293 repo, refs_idmap);
4294 else
4295 err = print_commit(commit, id, repo, path,
4296 show_changed_paths ? &changed_paths : NULL,
4297 show_patch, diff_context, refs_idmap, NULL);
4298 got_object_commit_close(commit);
4299 if (err)
4300 break;
4302 if ((limit && --limit == 0) ||
4303 (end_id && got_object_id_cmp(id, end_id) == 0))
4304 break;
4306 TAILQ_FOREACH(pe, &changed_paths, entry) {
4307 free((char *)pe->path);
4308 free(pe->data);
4310 got_pathlist_free(&changed_paths);
4312 if (reverse_display_order) {
4313 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4314 err = got_object_open_as_commit(&commit, repo,
4315 &qid->id);
4316 if (err)
4317 break;
4318 if (show_changed_paths) {
4319 err = get_changed_paths(&changed_paths,
4320 commit, repo);
4321 if (err)
4322 break;
4324 if (one_line)
4325 err = print_commit_oneline(commit, &qid->id,
4326 repo, refs_idmap);
4327 else
4328 err = print_commit(commit, &qid->id, repo, path,
4329 show_changed_paths ? &changed_paths : NULL,
4330 show_patch, diff_context, refs_idmap, NULL);
4331 got_object_commit_close(commit);
4332 if (err)
4333 break;
4334 TAILQ_FOREACH(pe, &changed_paths, entry) {
4335 free((char *)pe->path);
4336 free(pe->data);
4338 got_pathlist_free(&changed_paths);
4341 done:
4342 while (!STAILQ_EMPTY(&reversed_commits)) {
4343 qid = STAILQ_FIRST(&reversed_commits);
4344 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4345 got_object_qid_free(qid);
4347 TAILQ_FOREACH(pe, &changed_paths, entry) {
4348 free((char *)pe->path);
4349 free(pe->data);
4351 got_pathlist_free(&changed_paths);
4352 if (search_pattern)
4353 regfree(&regex);
4354 got_commit_graph_close(graph);
4355 return err;
4358 __dead static void
4359 usage_log(void)
4361 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4362 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4363 "[-r repository-path] [-R] [path]\n", getprogname());
4364 exit(1);
4367 static int
4368 get_default_log_limit(void)
4370 const char *got_default_log_limit;
4371 long long n;
4372 const char *errstr;
4374 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4375 if (got_default_log_limit == NULL)
4376 return 0;
4377 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4378 if (errstr != NULL)
4379 return 0;
4380 return n;
4383 static const struct got_error *
4384 cmd_log(int argc, char *argv[])
4386 const struct got_error *error;
4387 struct got_repository *repo = NULL;
4388 struct got_worktree *worktree = NULL;
4389 struct got_object_id *start_id = NULL, *end_id = NULL;
4390 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4391 const char *start_commit = NULL, *end_commit = NULL;
4392 const char *search_pattern = NULL;
4393 int diff_context = -1, ch;
4394 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4395 int reverse_display_order = 0, one_line = 0;
4396 const char *errstr;
4397 struct got_reflist_head refs;
4398 struct got_reflist_object_id_map *refs_idmap = NULL;
4399 FILE *tmpfile = NULL;
4400 int *pack_fds = NULL;
4402 TAILQ_INIT(&refs);
4404 #ifndef PROFILE
4405 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4406 NULL)
4407 == -1)
4408 err(1, "pledge");
4409 #endif
4411 limit = get_default_log_limit();
4413 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4414 switch (ch) {
4415 case 'p':
4416 show_patch = 1;
4417 break;
4418 case 'P':
4419 show_changed_paths = 1;
4420 break;
4421 case 'c':
4422 start_commit = optarg;
4423 break;
4424 case 'C':
4425 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4426 &errstr);
4427 if (errstr != NULL)
4428 errx(1, "number of context lines is %s: %s",
4429 errstr, optarg);
4430 break;
4431 case 'l':
4432 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4433 if (errstr != NULL)
4434 errx(1, "number of commits is %s: %s",
4435 errstr, optarg);
4436 break;
4437 case 'b':
4438 log_branches = 1;
4439 break;
4440 case 'r':
4441 repo_path = realpath(optarg, NULL);
4442 if (repo_path == NULL)
4443 return got_error_from_errno2("realpath",
4444 optarg);
4445 got_path_strip_trailing_slashes(repo_path);
4446 break;
4447 case 'R':
4448 reverse_display_order = 1;
4449 break;
4450 case 's':
4451 one_line = 1;
4452 break;
4453 case 'S':
4454 search_pattern = optarg;
4455 break;
4456 case 'x':
4457 end_commit = optarg;
4458 break;
4459 default:
4460 usage_log();
4461 /* NOTREACHED */
4465 argc -= optind;
4466 argv += optind;
4468 if (diff_context == -1)
4469 diff_context = 3;
4470 else if (!show_patch)
4471 errx(1, "-C requires -p");
4473 if (one_line && (show_patch || show_changed_paths))
4474 errx(1, "cannot use -s with -p or -P");
4476 cwd = getcwd(NULL, 0);
4477 if (cwd == NULL) {
4478 error = got_error_from_errno("getcwd");
4479 goto done;
4482 error = got_repo_pack_fds_open(&pack_fds);
4483 if (error != NULL)
4484 goto done;
4486 if (repo_path == NULL) {
4487 error = got_worktree_open(&worktree, cwd);
4488 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4489 goto done;
4490 error = NULL;
4493 if (argc == 1) {
4494 if (worktree) {
4495 error = got_worktree_resolve_path(&path, worktree,
4496 argv[0]);
4497 if (error)
4498 goto done;
4499 } else {
4500 path = strdup(argv[0]);
4501 if (path == NULL) {
4502 error = got_error_from_errno("strdup");
4503 goto done;
4506 } else if (argc != 0)
4507 usage_log();
4509 if (repo_path == NULL) {
4510 repo_path = worktree ?
4511 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4513 if (repo_path == NULL) {
4514 error = got_error_from_errno("strdup");
4515 goto done;
4518 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4519 if (error != NULL)
4520 goto done;
4522 error = apply_unveil(got_repo_get_path(repo), 1,
4523 worktree ? got_worktree_get_root_path(worktree) : NULL);
4524 if (error)
4525 goto done;
4527 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4528 if (error)
4529 goto done;
4531 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4532 if (error)
4533 goto done;
4535 if (start_commit == NULL) {
4536 struct got_reference *head_ref;
4537 struct got_commit_object *commit = NULL;
4538 error = got_ref_open(&head_ref, repo,
4539 worktree ? got_worktree_get_head_ref_name(worktree)
4540 : GOT_REF_HEAD, 0);
4541 if (error != NULL)
4542 goto done;
4543 error = got_ref_resolve(&start_id, repo, head_ref);
4544 got_ref_close(head_ref);
4545 if (error != NULL)
4546 goto done;
4547 error = got_object_open_as_commit(&commit, repo,
4548 start_id);
4549 if (error != NULL)
4550 goto done;
4551 got_object_commit_close(commit);
4552 } else {
4553 error = got_repo_match_object_id(&start_id, NULL,
4554 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4555 if (error != NULL)
4556 goto done;
4558 if (end_commit != NULL) {
4559 error = got_repo_match_object_id(&end_id, NULL,
4560 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4561 if (error != NULL)
4562 goto done;
4565 if (worktree) {
4567 * If a path was specified on the command line it was resolved
4568 * to a path in the work tree above. Prepend the work tree's
4569 * path prefix to obtain the corresponding in-repository path.
4571 if (path) {
4572 const char *prefix;
4573 prefix = got_worktree_get_path_prefix(worktree);
4574 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4575 (path[0] != '\0') ? "/" : "", path) == -1) {
4576 error = got_error_from_errno("asprintf");
4577 goto done;
4580 } else
4581 error = got_repo_map_path(&in_repo_path, repo,
4582 path ? path : "");
4583 if (error != NULL)
4584 goto done;
4585 if (in_repo_path) {
4586 free(path);
4587 path = in_repo_path;
4590 if (worktree) {
4591 /* Release work tree lock. */
4592 got_worktree_close(worktree);
4593 worktree = NULL;
4596 if (search_pattern && show_patch) {
4597 tmpfile = got_opentemp();
4598 if (tmpfile == NULL) {
4599 error = got_error_from_errno("got_opentemp");
4600 goto done;
4604 error = print_commits(start_id, end_id, repo, path ? path : "",
4605 show_changed_paths, show_patch, search_pattern, diff_context,
4606 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4607 tmpfile);
4608 done:
4609 free(path);
4610 free(repo_path);
4611 free(cwd);
4612 if (worktree)
4613 got_worktree_close(worktree);
4614 if (repo) {
4615 const struct got_error *close_err = got_repo_close(repo);
4616 if (error == NULL)
4617 error = close_err;
4619 if (pack_fds) {
4620 const struct got_error *pack_err =
4621 got_repo_pack_fds_close(pack_fds);
4622 if (error == NULL)
4623 error = pack_err;
4625 if (refs_idmap)
4626 got_reflist_object_id_map_free(refs_idmap);
4627 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4628 error = got_error_from_errno("fclose");
4629 got_ref_list_free(&refs);
4630 return error;
4633 __dead static void
4634 usage_diff(void)
4636 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4637 "[-r repository-path] [-s] [-w] [-P] "
4638 "[object1 object2 | path ...]\n", getprogname());
4639 exit(1);
4642 struct print_diff_arg {
4643 struct got_repository *repo;
4644 struct got_worktree *worktree;
4645 int diff_context;
4646 const char *id_str;
4647 int header_shown;
4648 int diff_staged;
4649 enum got_diff_algorithm diff_algo;
4650 int ignore_whitespace;
4651 int force_text_diff;
4652 FILE *f1;
4653 FILE *f2;
4657 * Create a file which contains the target path of a symlink so we can feed
4658 * it as content to the diff engine.
4660 static const struct got_error *
4661 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4662 const char *abspath)
4664 const struct got_error *err = NULL;
4665 char target_path[PATH_MAX];
4666 ssize_t target_len, outlen;
4668 *fd = -1;
4670 if (dirfd != -1) {
4671 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4672 if (target_len == -1)
4673 return got_error_from_errno2("readlinkat", abspath);
4674 } else {
4675 target_len = readlink(abspath, target_path, PATH_MAX);
4676 if (target_len == -1)
4677 return got_error_from_errno2("readlink", abspath);
4680 *fd = got_opentempfd();
4681 if (*fd == -1)
4682 return got_error_from_errno("got_opentempfd");
4684 outlen = write(*fd, target_path, target_len);
4685 if (outlen == -1) {
4686 err = got_error_from_errno("got_opentempfd");
4687 goto done;
4690 if (lseek(*fd, 0, SEEK_SET) == -1) {
4691 err = got_error_from_errno2("lseek", abspath);
4692 goto done;
4694 done:
4695 if (err) {
4696 close(*fd);
4697 *fd = -1;
4699 return err;
4702 static const struct got_error *
4703 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4704 const char *path, struct got_object_id *blob_id,
4705 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4706 int dirfd, const char *de_name)
4708 struct print_diff_arg *a = arg;
4709 const struct got_error *err = NULL;
4710 struct got_blob_object *blob1 = NULL;
4711 int fd = -1, fd1 = -1, fd2 = -1;
4712 FILE *f2 = NULL;
4713 char *abspath = NULL, *label1 = NULL;
4714 struct stat sb;
4715 off_t size1 = 0;
4716 int f2_exists = 1;
4718 if (a->diff_staged) {
4719 if (staged_status != GOT_STATUS_MODIFY &&
4720 staged_status != GOT_STATUS_ADD &&
4721 staged_status != GOT_STATUS_DELETE)
4722 return NULL;
4723 } else {
4724 if (staged_status == GOT_STATUS_DELETE)
4725 return NULL;
4726 if (status == GOT_STATUS_NONEXISTENT)
4727 return got_error_set_errno(ENOENT, path);
4728 if (status != GOT_STATUS_MODIFY &&
4729 status != GOT_STATUS_ADD &&
4730 status != GOT_STATUS_DELETE &&
4731 status != GOT_STATUS_CONFLICT)
4732 return NULL;
4735 err = got_opentemp_truncate(a->f1);
4736 if (err)
4737 return got_error_from_errno("got_opentemp_truncate");
4738 err = got_opentemp_truncate(a->f2);
4739 if (err)
4740 return got_error_from_errno("got_opentemp_truncate");
4742 if (!a->header_shown) {
4743 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4744 got_worktree_get_root_path(a->worktree));
4745 printf("commit - %s\n", a->id_str);
4746 printf("path + %s%s\n",
4747 got_worktree_get_root_path(a->worktree),
4748 a->diff_staged ? " (staged changes)" : "");
4749 a->header_shown = 1;
4752 if (a->diff_staged) {
4753 const char *label1 = NULL, *label2 = NULL;
4754 switch (staged_status) {
4755 case GOT_STATUS_MODIFY:
4756 label1 = path;
4757 label2 = path;
4758 break;
4759 case GOT_STATUS_ADD:
4760 label2 = path;
4761 break;
4762 case GOT_STATUS_DELETE:
4763 label1 = path;
4764 break;
4765 default:
4766 return got_error(GOT_ERR_FILE_STATUS);
4768 fd1 = got_opentempfd();
4769 if (fd1 == -1) {
4770 err = got_error_from_errno("got_opentempfd");
4771 goto done;
4773 fd2 = got_opentempfd();
4774 if (fd2 == -1) {
4775 err = got_error_from_errno("got_opentempfd");
4776 goto done;
4778 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4779 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4780 a->diff_algo, a->diff_context, a->ignore_whitespace,
4781 a->force_text_diff, a->repo, stdout);
4782 goto done;
4785 fd1 = got_opentempfd();
4786 if (fd1 == -1) {
4787 err = got_error_from_errno("got_opentempfd");
4788 goto done;
4791 if (staged_status == GOT_STATUS_ADD ||
4792 staged_status == GOT_STATUS_MODIFY) {
4793 char *id_str;
4794 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4795 8192, fd1);
4796 if (err)
4797 goto done;
4798 err = got_object_id_str(&id_str, staged_blob_id);
4799 if (err)
4800 goto done;
4801 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4802 err = got_error_from_errno("asprintf");
4803 free(id_str);
4804 goto done;
4806 free(id_str);
4807 } else if (status != GOT_STATUS_ADD) {
4808 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4809 fd1);
4810 if (err)
4811 goto done;
4814 if (status != GOT_STATUS_DELETE) {
4815 if (asprintf(&abspath, "%s/%s",
4816 got_worktree_get_root_path(a->worktree), path) == -1) {
4817 err = got_error_from_errno("asprintf");
4818 goto done;
4821 if (dirfd != -1) {
4822 fd = openat(dirfd, de_name,
4823 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4824 if (fd == -1) {
4825 if (!got_err_open_nofollow_on_symlink()) {
4826 err = got_error_from_errno2("openat",
4827 abspath);
4828 goto done;
4830 err = get_symlink_target_file(&fd, dirfd,
4831 de_name, abspath);
4832 if (err)
4833 goto done;
4835 } else {
4836 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4837 if (fd == -1) {
4838 if (!got_err_open_nofollow_on_symlink()) {
4839 err = got_error_from_errno2("open",
4840 abspath);
4841 goto done;
4843 err = get_symlink_target_file(&fd, dirfd,
4844 de_name, abspath);
4845 if (err)
4846 goto done;
4849 if (fstat(fd, &sb) == -1) {
4850 err = got_error_from_errno2("fstat", abspath);
4851 goto done;
4853 f2 = fdopen(fd, "r");
4854 if (f2 == NULL) {
4855 err = got_error_from_errno2("fdopen", abspath);
4856 goto done;
4858 fd = -1;
4859 } else {
4860 sb.st_size = 0;
4861 f2_exists = 0;
4864 if (blob1) {
4865 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4866 a->f1, blob1);
4867 if (err)
4868 goto done;
4871 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4872 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4873 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4874 done:
4875 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4876 err = got_error_from_errno("close");
4877 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4878 err = got_error_from_errno("close");
4879 if (blob1)
4880 got_object_blob_close(blob1);
4881 if (fd != -1 && close(fd) == -1 && err == NULL)
4882 err = got_error_from_errno("close");
4883 if (f2 && fclose(f2) == EOF && err == NULL)
4884 err = got_error_from_errno("fclose");
4885 free(abspath);
4886 return err;
4889 static const struct got_error *
4890 cmd_diff(int argc, char *argv[])
4892 const struct got_error *error;
4893 struct got_repository *repo = NULL;
4894 struct got_worktree *worktree = NULL;
4895 char *cwd = NULL, *repo_path = NULL;
4896 const char *commit_args[2] = { NULL, NULL };
4897 int ncommit_args = 0;
4898 struct got_object_id *ids[2] = { NULL, NULL };
4899 char *labels[2] = { NULL, NULL };
4900 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4901 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4902 int force_text_diff = 0, force_path = 0, rflag = 0;
4903 const char *errstr;
4904 struct got_reflist_head refs;
4905 struct got_pathlist_head paths;
4906 struct got_pathlist_entry *pe;
4907 FILE *f1 = NULL, *f2 = NULL;
4908 int fd1 = -1, fd2 = -1;
4909 int *pack_fds = NULL;
4911 TAILQ_INIT(&refs);
4912 TAILQ_INIT(&paths);
4914 #ifndef PROFILE
4915 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4916 NULL) == -1)
4917 err(1, "pledge");
4918 #endif
4920 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4921 switch (ch) {
4922 case 'a':
4923 force_text_diff = 1;
4924 break;
4925 case 'c':
4926 if (ncommit_args >= 2)
4927 errx(1, "too many -c options used");
4928 commit_args[ncommit_args++] = optarg;
4929 break;
4930 case 'C':
4931 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4932 &errstr);
4933 if (errstr != NULL)
4934 errx(1, "number of context lines is %s: %s",
4935 errstr, optarg);
4936 break;
4937 case 'r':
4938 repo_path = realpath(optarg, NULL);
4939 if (repo_path == NULL)
4940 return got_error_from_errno2("realpath",
4941 optarg);
4942 got_path_strip_trailing_slashes(repo_path);
4943 rflag = 1;
4944 break;
4945 case 's':
4946 diff_staged = 1;
4947 break;
4948 case 'w':
4949 ignore_whitespace = 1;
4950 break;
4951 case 'P':
4952 force_path = 1;
4953 break;
4954 default:
4955 usage_diff();
4956 /* NOTREACHED */
4960 argc -= optind;
4961 argv += optind;
4963 cwd = getcwd(NULL, 0);
4964 if (cwd == NULL) {
4965 error = got_error_from_errno("getcwd");
4966 goto done;
4969 error = got_repo_pack_fds_open(&pack_fds);
4970 if (error != NULL)
4971 goto done;
4973 if (repo_path == NULL) {
4974 error = got_worktree_open(&worktree, cwd);
4975 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4976 goto done;
4977 else
4978 error = NULL;
4979 if (worktree) {
4980 repo_path =
4981 strdup(got_worktree_get_repo_path(worktree));
4982 if (repo_path == NULL) {
4983 error = got_error_from_errno("strdup");
4984 goto done;
4986 } else {
4987 repo_path = strdup(cwd);
4988 if (repo_path == NULL) {
4989 error = got_error_from_errno("strdup");
4990 goto done;
4995 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4996 free(repo_path);
4997 if (error != NULL)
4998 goto done;
5000 if (rflag || worktree == NULL || ncommit_args > 0) {
5001 if (force_path) {
5002 error = got_error_msg(GOT_ERR_NOT_IMPL,
5003 "-P option can only be used when diffing "
5004 "a work tree");
5005 goto done;
5007 if (diff_staged) {
5008 error = got_error_msg(GOT_ERR_NOT_IMPL,
5009 "-s option can only be used when diffing "
5010 "a work tree");
5011 goto done;
5015 error = apply_unveil(got_repo_get_path(repo), 1,
5016 worktree ? got_worktree_get_root_path(worktree) : NULL);
5017 if (error)
5018 goto done;
5020 if ((!force_path && argc == 2) || ncommit_args > 0) {
5021 int obj_type = (ncommit_args > 0 ?
5022 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5023 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5024 NULL);
5025 if (error)
5026 goto done;
5027 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5028 const char *arg;
5029 if (ncommit_args > 0)
5030 arg = commit_args[i];
5031 else
5032 arg = argv[i];
5033 error = got_repo_match_object_id(&ids[i], &labels[i],
5034 arg, obj_type, &refs, repo);
5035 if (error) {
5036 if (error->code != GOT_ERR_NOT_REF &&
5037 error->code != GOT_ERR_NO_OBJ)
5038 goto done;
5039 if (ncommit_args > 0)
5040 goto done;
5041 error = NULL;
5042 break;
5047 f1 = got_opentemp();
5048 if (f1 == NULL) {
5049 error = got_error_from_errno("got_opentemp");
5050 goto done;
5053 f2 = got_opentemp();
5054 if (f2 == NULL) {
5055 error = got_error_from_errno("got_opentemp");
5056 goto done;
5059 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5060 struct print_diff_arg arg;
5061 char *id_str;
5063 if (worktree == NULL) {
5064 if (argc == 2 && ids[0] == NULL) {
5065 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5066 goto done;
5067 } else if (argc == 2 && ids[1] == NULL) {
5068 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5069 goto done;
5070 } else if (argc > 0) {
5071 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5072 "%s", "specified paths cannot be resolved");
5073 goto done;
5074 } else {
5075 error = got_error(GOT_ERR_NOT_WORKTREE);
5076 goto done;
5080 error = get_worktree_paths_from_argv(&paths, argc, argv,
5081 worktree);
5082 if (error)
5083 goto done;
5085 error = got_object_id_str(&id_str,
5086 got_worktree_get_base_commit_id(worktree));
5087 if (error)
5088 goto done;
5089 arg.repo = repo;
5090 arg.worktree = worktree;
5091 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5092 arg.diff_context = diff_context;
5093 arg.id_str = id_str;
5094 arg.header_shown = 0;
5095 arg.diff_staged = diff_staged;
5096 arg.ignore_whitespace = ignore_whitespace;
5097 arg.force_text_diff = force_text_diff;
5098 arg.f1 = f1;
5099 arg.f2 = f2;
5101 error = got_worktree_status(worktree, &paths, repo, 0,
5102 print_diff, &arg, check_cancelled, NULL);
5103 free(id_str);
5104 goto done;
5107 if (ncommit_args == 1) {
5108 struct got_commit_object *commit;
5109 error = got_object_open_as_commit(&commit, repo, ids[0]);
5110 if (error)
5111 goto done;
5113 labels[1] = labels[0];
5114 ids[1] = ids[0];
5115 if (got_object_commit_get_nparents(commit) > 0) {
5116 const struct got_object_id_queue *pids;
5117 struct got_object_qid *pid;
5118 pids = got_object_commit_get_parent_ids(commit);
5119 pid = STAILQ_FIRST(pids);
5120 ids[0] = got_object_id_dup(&pid->id);
5121 if (ids[0] == NULL) {
5122 error = got_error_from_errno(
5123 "got_object_id_dup");
5124 got_object_commit_close(commit);
5125 goto done;
5127 error = got_object_id_str(&labels[0], ids[0]);
5128 if (error) {
5129 got_object_commit_close(commit);
5130 goto done;
5132 } else {
5133 ids[0] = NULL;
5134 labels[0] = strdup("/dev/null");
5135 if (labels[0] == NULL) {
5136 error = got_error_from_errno("strdup");
5137 got_object_commit_close(commit);
5138 goto done;
5142 got_object_commit_close(commit);
5145 if (ncommit_args == 0 && argc > 2) {
5146 error = got_error_msg(GOT_ERR_BAD_PATH,
5147 "path arguments cannot be used when diffing two objects");
5148 goto done;
5151 if (ids[0]) {
5152 error = got_object_get_type(&type1, repo, ids[0]);
5153 if (error)
5154 goto done;
5157 error = got_object_get_type(&type2, repo, ids[1]);
5158 if (error)
5159 goto done;
5160 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5161 error = got_error(GOT_ERR_OBJ_TYPE);
5162 goto done;
5164 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5165 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5166 "path arguments cannot be used when diffing blobs");
5167 goto done;
5170 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5171 char *in_repo_path;
5172 struct got_pathlist_entry *new;
5173 if (worktree) {
5174 const char *prefix;
5175 char *p;
5176 error = got_worktree_resolve_path(&p, worktree,
5177 argv[i]);
5178 if (error)
5179 goto done;
5180 prefix = got_worktree_get_path_prefix(worktree);
5181 while (prefix[0] == '/')
5182 prefix++;
5183 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5184 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5185 p) == -1) {
5186 error = got_error_from_errno("asprintf");
5187 free(p);
5188 goto done;
5190 free(p);
5191 } else {
5192 char *mapped_path, *s;
5193 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5194 if (error)
5195 goto done;
5196 s = mapped_path;
5197 while (s[0] == '/')
5198 s++;
5199 in_repo_path = strdup(s);
5200 if (in_repo_path == NULL) {
5201 error = got_error_from_errno("asprintf");
5202 free(mapped_path);
5203 goto done;
5205 free(mapped_path);
5208 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5209 if (error || new == NULL /* duplicate */)
5210 free(in_repo_path);
5211 if (error)
5212 goto done;
5215 if (worktree) {
5216 /* Release work tree lock. */
5217 got_worktree_close(worktree);
5218 worktree = NULL;
5221 fd1 = got_opentempfd();
5222 if (fd1 == -1) {
5223 error = got_error_from_errno("got_opentempfd");
5224 goto done;
5227 fd2 = got_opentempfd();
5228 if (fd2 == -1) {
5229 error = got_error_from_errno("got_opentempfd");
5230 goto done;
5233 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5234 case GOT_OBJ_TYPE_BLOB:
5235 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5236 fd1, fd2, ids[0], ids[1], NULL, NULL,
5237 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5238 ignore_whitespace, force_text_diff, repo, stdout);
5239 break;
5240 case GOT_OBJ_TYPE_TREE:
5241 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5242 ids[0], ids[1], &paths, "", "",
5243 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5244 ignore_whitespace, force_text_diff, repo, stdout);
5245 break;
5246 case GOT_OBJ_TYPE_COMMIT:
5247 printf("diff %s %s\n", labels[0], labels[1]);
5248 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5249 fd1, fd2, ids[0], ids[1], &paths,
5250 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5251 ignore_whitespace, force_text_diff, repo, stdout);
5252 break;
5253 default:
5254 error = got_error(GOT_ERR_OBJ_TYPE);
5256 done:
5257 free(labels[0]);
5258 free(labels[1]);
5259 free(ids[0]);
5260 free(ids[1]);
5261 if (worktree)
5262 got_worktree_close(worktree);
5263 if (repo) {
5264 const struct got_error *close_err = got_repo_close(repo);
5265 if (error == NULL)
5266 error = close_err;
5268 if (pack_fds) {
5269 const struct got_error *pack_err =
5270 got_repo_pack_fds_close(pack_fds);
5271 if (error == NULL)
5272 error = pack_err;
5274 TAILQ_FOREACH(pe, &paths, entry)
5275 free((char *)pe->path);
5276 got_pathlist_free(&paths);
5277 got_ref_list_free(&refs);
5278 if (f1 && fclose(f1) == EOF && error == NULL)
5279 error = got_error_from_errno("fclose");
5280 if (f2 && fclose(f2) == EOF && error == NULL)
5281 error = got_error_from_errno("fclose");
5282 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5283 error = got_error_from_errno("close");
5284 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5285 error = got_error_from_errno("close");
5286 return error;
5289 __dead static void
5290 usage_blame(void)
5292 fprintf(stderr,
5293 "usage: %s blame [-c commit] [-r repository-path] path\n",
5294 getprogname());
5295 exit(1);
5298 struct blame_line {
5299 int annotated;
5300 char *id_str;
5301 char *committer;
5302 char datebuf[11]; /* YYYY-MM-DD + NUL */
5305 struct blame_cb_args {
5306 struct blame_line *lines;
5307 int nlines;
5308 int nlines_prec;
5309 int lineno_cur;
5310 off_t *line_offsets;
5311 FILE *f;
5312 struct got_repository *repo;
5315 static const struct got_error *
5316 blame_cb(void *arg, int nlines, int lineno,
5317 struct got_commit_object *commit, struct got_object_id *id)
5319 const struct got_error *err = NULL;
5320 struct blame_cb_args *a = arg;
5321 struct blame_line *bline;
5322 char *line = NULL;
5323 size_t linesize = 0;
5324 off_t offset;
5325 struct tm tm;
5326 time_t committer_time;
5328 if (nlines != a->nlines ||
5329 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5330 return got_error(GOT_ERR_RANGE);
5332 if (sigint_received)
5333 return got_error(GOT_ERR_ITER_COMPLETED);
5335 if (lineno == -1)
5336 return NULL; /* no change in this commit */
5338 /* Annotate this line. */
5339 bline = &a->lines[lineno - 1];
5340 if (bline->annotated)
5341 return NULL;
5342 err = got_object_id_str(&bline->id_str, id);
5343 if (err)
5344 return err;
5346 bline->committer = strdup(got_object_commit_get_committer(commit));
5347 if (bline->committer == NULL) {
5348 err = got_error_from_errno("strdup");
5349 goto done;
5352 committer_time = got_object_commit_get_committer_time(commit);
5353 if (gmtime_r(&committer_time, &tm) == NULL)
5354 return got_error_from_errno("gmtime_r");
5355 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5356 &tm) == 0) {
5357 err = got_error(GOT_ERR_NO_SPACE);
5358 goto done;
5360 bline->annotated = 1;
5362 /* Print lines annotated so far. */
5363 bline = &a->lines[a->lineno_cur - 1];
5364 if (!bline->annotated)
5365 goto done;
5367 offset = a->line_offsets[a->lineno_cur - 1];
5368 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5369 err = got_error_from_errno("fseeko");
5370 goto done;
5373 while (bline->annotated) {
5374 char *smallerthan, *at, *nl, *committer;
5375 size_t len;
5377 if (getline(&line, &linesize, a->f) == -1) {
5378 if (ferror(a->f))
5379 err = got_error_from_errno("getline");
5380 break;
5383 committer = bline->committer;
5384 smallerthan = strchr(committer, '<');
5385 if (smallerthan && smallerthan[1] != '\0')
5386 committer = smallerthan + 1;
5387 at = strchr(committer, '@');
5388 if (at)
5389 *at = '\0';
5390 len = strlen(committer);
5391 if (len >= 9)
5392 committer[8] = '\0';
5394 nl = strchr(line, '\n');
5395 if (nl)
5396 *nl = '\0';
5397 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5398 bline->id_str, bline->datebuf, committer, line);
5400 a->lineno_cur++;
5401 bline = &a->lines[a->lineno_cur - 1];
5403 done:
5404 free(line);
5405 return err;
5408 static const struct got_error *
5409 cmd_blame(int argc, char *argv[])
5411 const struct got_error *error;
5412 struct got_repository *repo = NULL;
5413 struct got_worktree *worktree = NULL;
5414 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5415 char *link_target = NULL;
5416 struct got_object_id *obj_id = NULL;
5417 struct got_object_id *commit_id = NULL;
5418 struct got_commit_object *commit = NULL;
5419 struct got_blob_object *blob = NULL;
5420 char *commit_id_str = NULL;
5421 struct blame_cb_args bca;
5422 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5423 off_t filesize;
5424 int *pack_fds = NULL;
5425 FILE *f1 = NULL, *f2 = NULL;
5427 fd1 = got_opentempfd();
5428 if (fd1 == -1)
5429 return got_error_from_errno("got_opentempfd");
5431 memset(&bca, 0, sizeof(bca));
5433 #ifndef PROFILE
5434 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5435 NULL) == -1)
5436 err(1, "pledge");
5437 #endif
5439 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5440 switch (ch) {
5441 case 'c':
5442 commit_id_str = optarg;
5443 break;
5444 case 'r':
5445 repo_path = realpath(optarg, NULL);
5446 if (repo_path == NULL)
5447 return got_error_from_errno2("realpath",
5448 optarg);
5449 got_path_strip_trailing_slashes(repo_path);
5450 break;
5451 default:
5452 usage_blame();
5453 /* NOTREACHED */
5457 argc -= optind;
5458 argv += optind;
5460 if (argc == 1)
5461 path = argv[0];
5462 else
5463 usage_blame();
5465 cwd = getcwd(NULL, 0);
5466 if (cwd == NULL) {
5467 error = got_error_from_errno("getcwd");
5468 goto done;
5471 error = got_repo_pack_fds_open(&pack_fds);
5472 if (error != NULL)
5473 goto done;
5475 if (repo_path == NULL) {
5476 error = got_worktree_open(&worktree, cwd);
5477 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5478 goto done;
5479 else
5480 error = NULL;
5481 if (worktree) {
5482 repo_path =
5483 strdup(got_worktree_get_repo_path(worktree));
5484 if (repo_path == NULL) {
5485 error = got_error_from_errno("strdup");
5486 if (error)
5487 goto done;
5489 } else {
5490 repo_path = strdup(cwd);
5491 if (repo_path == NULL) {
5492 error = got_error_from_errno("strdup");
5493 goto done;
5498 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5499 if (error != NULL)
5500 goto done;
5502 if (worktree) {
5503 const char *prefix = got_worktree_get_path_prefix(worktree);
5504 char *p;
5506 error = got_worktree_resolve_path(&p, worktree, path);
5507 if (error)
5508 goto done;
5509 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5510 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5511 p) == -1) {
5512 error = got_error_from_errno("asprintf");
5513 free(p);
5514 goto done;
5516 free(p);
5517 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5518 } else {
5519 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5520 if (error)
5521 goto done;
5522 error = got_repo_map_path(&in_repo_path, repo, path);
5524 if (error)
5525 goto done;
5527 if (commit_id_str == NULL) {
5528 struct got_reference *head_ref;
5529 error = got_ref_open(&head_ref, repo, worktree ?
5530 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5531 if (error != NULL)
5532 goto done;
5533 error = got_ref_resolve(&commit_id, repo, head_ref);
5534 got_ref_close(head_ref);
5535 if (error != NULL)
5536 goto done;
5537 } else {
5538 struct got_reflist_head refs;
5539 TAILQ_INIT(&refs);
5540 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5541 NULL);
5542 if (error)
5543 goto done;
5544 error = got_repo_match_object_id(&commit_id, NULL,
5545 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5546 got_ref_list_free(&refs);
5547 if (error)
5548 goto done;
5551 if (worktree) {
5552 /* Release work tree lock. */
5553 got_worktree_close(worktree);
5554 worktree = NULL;
5557 error = got_object_open_as_commit(&commit, repo, commit_id);
5558 if (error)
5559 goto done;
5561 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5562 commit, repo);
5563 if (error)
5564 goto done;
5566 error = got_object_id_by_path(&obj_id, repo, commit,
5567 link_target ? link_target : in_repo_path);
5568 if (error)
5569 goto done;
5571 error = got_object_get_type(&obj_type, repo, obj_id);
5572 if (error)
5573 goto done;
5575 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5576 error = got_error_path(link_target ? link_target : in_repo_path,
5577 GOT_ERR_OBJ_TYPE);
5578 goto done;
5581 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5582 if (error)
5583 goto done;
5584 bca.f = got_opentemp();
5585 if (bca.f == NULL) {
5586 error = got_error_from_errno("got_opentemp");
5587 goto done;
5589 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5590 &bca.line_offsets, bca.f, blob);
5591 if (error || bca.nlines == 0)
5592 goto done;
5594 /* Don't include \n at EOF in the blame line count. */
5595 if (bca.line_offsets[bca.nlines - 1] == filesize)
5596 bca.nlines--;
5598 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5599 if (bca.lines == NULL) {
5600 error = got_error_from_errno("calloc");
5601 goto done;
5603 bca.lineno_cur = 1;
5604 bca.nlines_prec = 0;
5605 i = bca.nlines;
5606 while (i > 0) {
5607 i /= 10;
5608 bca.nlines_prec++;
5610 bca.repo = repo;
5612 fd2 = got_opentempfd();
5613 if (fd2 == -1) {
5614 error = got_error_from_errno("got_opentempfd");
5615 goto done;
5617 fd3 = got_opentempfd();
5618 if (fd3 == -1) {
5619 error = got_error_from_errno("got_opentempfd");
5620 goto done;
5622 f1 = got_opentemp();
5623 if (f1 == NULL) {
5624 error = got_error_from_errno("got_opentemp");
5625 goto done;
5627 f2 = got_opentemp();
5628 if (f2 == NULL) {
5629 error = got_error_from_errno("got_opentemp");
5630 goto done;
5632 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5633 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5634 check_cancelled, NULL, fd2, fd3, f1, f2);
5635 done:
5636 free(in_repo_path);
5637 free(link_target);
5638 free(repo_path);
5639 free(cwd);
5640 free(commit_id);
5641 free(obj_id);
5642 if (commit)
5643 got_object_commit_close(commit);
5645 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5646 error = got_error_from_errno("close");
5647 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5648 error = got_error_from_errno("close");
5649 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5650 error = got_error_from_errno("close");
5651 if (f1 && fclose(f1) == EOF && error == NULL)
5652 error = got_error_from_errno("fclose");
5653 if (f2 && fclose(f2) == EOF && error == NULL)
5654 error = got_error_from_errno("fclose");
5656 if (blob)
5657 got_object_blob_close(blob);
5658 if (worktree)
5659 got_worktree_close(worktree);
5660 if (repo) {
5661 const struct got_error *close_err = got_repo_close(repo);
5662 if (error == NULL)
5663 error = close_err;
5665 if (pack_fds) {
5666 const struct got_error *pack_err =
5667 got_repo_pack_fds_close(pack_fds);
5668 if (error == NULL)
5669 error = pack_err;
5671 if (bca.lines) {
5672 for (i = 0; i < bca.nlines; i++) {
5673 struct blame_line *bline = &bca.lines[i];
5674 free(bline->id_str);
5675 free(bline->committer);
5677 free(bca.lines);
5679 free(bca.line_offsets);
5680 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5681 error = got_error_from_errno("fclose");
5682 return error;
5685 __dead static void
5686 usage_tree(void)
5688 fprintf(stderr,
5689 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5690 getprogname());
5691 exit(1);
5694 static const struct got_error *
5695 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5696 const char *root_path, struct got_repository *repo)
5698 const struct got_error *err = NULL;
5699 int is_root_path = (strcmp(path, root_path) == 0);
5700 const char *modestr = "";
5701 mode_t mode = got_tree_entry_get_mode(te);
5702 char *link_target = NULL;
5704 path += strlen(root_path);
5705 while (path[0] == '/')
5706 path++;
5708 if (got_object_tree_entry_is_submodule(te))
5709 modestr = "$";
5710 else if (S_ISLNK(mode)) {
5711 int i;
5713 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5714 if (err)
5715 return err;
5716 for (i = 0; i < strlen(link_target); i++) {
5717 if (!isprint((unsigned char)link_target[i]))
5718 link_target[i] = '?';
5721 modestr = "@";
5723 else if (S_ISDIR(mode))
5724 modestr = "/";
5725 else if (mode & S_IXUSR)
5726 modestr = "*";
5728 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5729 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5730 link_target ? " -> ": "", link_target ? link_target : "");
5732 free(link_target);
5733 return NULL;
5736 static const struct got_error *
5737 print_tree(const char *path, struct got_commit_object *commit,
5738 int show_ids, int recurse, const char *root_path,
5739 struct got_repository *repo)
5741 const struct got_error *err = NULL;
5742 struct got_object_id *tree_id = NULL;
5743 struct got_tree_object *tree = NULL;
5744 int nentries, i;
5746 err = got_object_id_by_path(&tree_id, repo, commit, path);
5747 if (err)
5748 goto done;
5750 err = got_object_open_as_tree(&tree, repo, tree_id);
5751 if (err)
5752 goto done;
5753 nentries = got_object_tree_get_nentries(tree);
5754 for (i = 0; i < nentries; i++) {
5755 struct got_tree_entry *te;
5756 char *id = NULL;
5758 if (sigint_received || sigpipe_received)
5759 break;
5761 te = got_object_tree_get_entry(tree, i);
5762 if (show_ids) {
5763 char *id_str;
5764 err = got_object_id_str(&id_str,
5765 got_tree_entry_get_id(te));
5766 if (err)
5767 goto done;
5768 if (asprintf(&id, "%s ", id_str) == -1) {
5769 err = got_error_from_errno("asprintf");
5770 free(id_str);
5771 goto done;
5773 free(id_str);
5775 err = print_entry(te, id, path, root_path, repo);
5776 free(id);
5777 if (err)
5778 goto done;
5780 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5781 char *child_path;
5782 if (asprintf(&child_path, "%s%s%s", path,
5783 path[0] == '/' && path[1] == '\0' ? "" : "/",
5784 got_tree_entry_get_name(te)) == -1) {
5785 err = got_error_from_errno("asprintf");
5786 goto done;
5788 err = print_tree(child_path, commit, show_ids, 1,
5789 root_path, repo);
5790 free(child_path);
5791 if (err)
5792 goto done;
5795 done:
5796 if (tree)
5797 got_object_tree_close(tree);
5798 free(tree_id);
5799 return err;
5802 static const struct got_error *
5803 cmd_tree(int argc, char *argv[])
5805 const struct got_error *error;
5806 struct got_repository *repo = NULL;
5807 struct got_worktree *worktree = NULL;
5808 const char *path, *refname = NULL;
5809 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5810 struct got_object_id *commit_id = NULL;
5811 struct got_commit_object *commit = NULL;
5812 char *commit_id_str = NULL;
5813 int show_ids = 0, recurse = 0;
5814 int ch;
5815 int *pack_fds = NULL;
5817 #ifndef PROFILE
5818 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5819 NULL) == -1)
5820 err(1, "pledge");
5821 #endif
5823 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5824 switch (ch) {
5825 case 'c':
5826 commit_id_str = optarg;
5827 break;
5828 case 'r':
5829 repo_path = realpath(optarg, NULL);
5830 if (repo_path == NULL)
5831 return got_error_from_errno2("realpath",
5832 optarg);
5833 got_path_strip_trailing_slashes(repo_path);
5834 break;
5835 case 'i':
5836 show_ids = 1;
5837 break;
5838 case 'R':
5839 recurse = 1;
5840 break;
5841 default:
5842 usage_tree();
5843 /* NOTREACHED */
5847 argc -= optind;
5848 argv += optind;
5850 if (argc == 1)
5851 path = argv[0];
5852 else if (argc > 1)
5853 usage_tree();
5854 else
5855 path = NULL;
5857 cwd = getcwd(NULL, 0);
5858 if (cwd == NULL) {
5859 error = got_error_from_errno("getcwd");
5860 goto done;
5863 error = got_repo_pack_fds_open(&pack_fds);
5864 if (error != NULL)
5865 goto done;
5867 if (repo_path == NULL) {
5868 error = got_worktree_open(&worktree, cwd);
5869 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5870 goto done;
5871 else
5872 error = NULL;
5873 if (worktree) {
5874 repo_path =
5875 strdup(got_worktree_get_repo_path(worktree));
5876 if (repo_path == NULL)
5877 error = got_error_from_errno("strdup");
5878 if (error)
5879 goto done;
5880 } else {
5881 repo_path = strdup(cwd);
5882 if (repo_path == NULL) {
5883 error = got_error_from_errno("strdup");
5884 goto done;
5889 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5890 if (error != NULL)
5891 goto done;
5893 if (worktree) {
5894 const char *prefix = got_worktree_get_path_prefix(worktree);
5895 char *p;
5897 if (path == NULL)
5898 path = "";
5899 error = got_worktree_resolve_path(&p, worktree, path);
5900 if (error)
5901 goto done;
5902 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5903 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5904 p) == -1) {
5905 error = got_error_from_errno("asprintf");
5906 free(p);
5907 goto done;
5909 free(p);
5910 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5911 if (error)
5912 goto done;
5913 } else {
5914 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5915 if (error)
5916 goto done;
5917 if (path == NULL)
5918 path = "/";
5919 error = got_repo_map_path(&in_repo_path, repo, path);
5920 if (error != NULL)
5921 goto done;
5924 if (commit_id_str == NULL) {
5925 struct got_reference *head_ref;
5926 if (worktree)
5927 refname = got_worktree_get_head_ref_name(worktree);
5928 else
5929 refname = GOT_REF_HEAD;
5930 error = got_ref_open(&head_ref, repo, refname, 0);
5931 if (error != NULL)
5932 goto done;
5933 error = got_ref_resolve(&commit_id, repo, head_ref);
5934 got_ref_close(head_ref);
5935 if (error != NULL)
5936 goto done;
5937 } else {
5938 struct got_reflist_head refs;
5939 TAILQ_INIT(&refs);
5940 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5941 NULL);
5942 if (error)
5943 goto done;
5944 error = got_repo_match_object_id(&commit_id, NULL,
5945 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5946 got_ref_list_free(&refs);
5947 if (error)
5948 goto done;
5951 if (worktree) {
5952 /* Release work tree lock. */
5953 got_worktree_close(worktree);
5954 worktree = NULL;
5957 error = got_object_open_as_commit(&commit, repo, commit_id);
5958 if (error)
5959 goto done;
5961 error = print_tree(in_repo_path, commit, show_ids, recurse,
5962 in_repo_path, repo);
5963 done:
5964 free(in_repo_path);
5965 free(repo_path);
5966 free(cwd);
5967 free(commit_id);
5968 if (commit)
5969 got_object_commit_close(commit);
5970 if (worktree)
5971 got_worktree_close(worktree);
5972 if (repo) {
5973 const struct got_error *close_err = got_repo_close(repo);
5974 if (error == NULL)
5975 error = close_err;
5977 if (pack_fds) {
5978 const struct got_error *pack_err =
5979 got_repo_pack_fds_close(pack_fds);
5980 if (error == NULL)
5981 error = pack_err;
5983 return error;
5986 __dead static void
5987 usage_status(void)
5989 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5990 "[-S status-codes] [path ...]\n", getprogname());
5991 exit(1);
5994 struct got_status_arg {
5995 char *status_codes;
5996 int suppress;
5999 static const struct got_error *
6000 print_status(void *arg, unsigned char status, unsigned char staged_status,
6001 const char *path, struct got_object_id *blob_id,
6002 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6003 int dirfd, const char *de_name)
6005 struct got_status_arg *st = arg;
6007 if (status == staged_status && (status == GOT_STATUS_DELETE))
6008 status = GOT_STATUS_NO_CHANGE;
6009 if (st != NULL && st->status_codes) {
6010 size_t ncodes = strlen(st->status_codes);
6011 int i, j = 0;
6013 for (i = 0; i < ncodes ; i++) {
6014 if (st->suppress) {
6015 if (status == st->status_codes[i] ||
6016 staged_status == st->status_codes[i]) {
6017 j++;
6018 continue;
6020 } else {
6021 if (status == st->status_codes[i] ||
6022 staged_status == st->status_codes[i])
6023 break;
6027 if (st->suppress && j == 0)
6028 goto print;
6030 if (i == ncodes)
6031 return NULL;
6033 print:
6034 printf("%c%c %s\n", status, staged_status, path);
6035 return NULL;
6038 static const struct got_error *
6039 cmd_status(int argc, char *argv[])
6041 const struct got_error *error = NULL;
6042 struct got_repository *repo = NULL;
6043 struct got_worktree *worktree = NULL;
6044 struct got_status_arg st;
6045 char *cwd = NULL;
6046 struct got_pathlist_head paths;
6047 struct got_pathlist_entry *pe;
6048 int ch, i, no_ignores = 0;
6049 int *pack_fds = NULL;
6051 TAILQ_INIT(&paths);
6053 memset(&st, 0, sizeof(st));
6054 st.status_codes = NULL;
6055 st.suppress = 0;
6057 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6058 switch (ch) {
6059 case 'I':
6060 no_ignores = 1;
6061 break;
6062 case 'S':
6063 if (st.status_codes != NULL && st.suppress == 0)
6064 option_conflict('S', 's');
6065 st.suppress = 1;
6066 /* fallthrough */
6067 case 's':
6068 for (i = 0; i < strlen(optarg); i++) {
6069 switch (optarg[i]) {
6070 case GOT_STATUS_MODIFY:
6071 case GOT_STATUS_ADD:
6072 case GOT_STATUS_DELETE:
6073 case GOT_STATUS_CONFLICT:
6074 case GOT_STATUS_MISSING:
6075 case GOT_STATUS_OBSTRUCTED:
6076 case GOT_STATUS_UNVERSIONED:
6077 case GOT_STATUS_MODE_CHANGE:
6078 case GOT_STATUS_NONEXISTENT:
6079 break;
6080 default:
6081 errx(1, "invalid status code '%c'",
6082 optarg[i]);
6085 if (ch == 's' && st.suppress)
6086 option_conflict('s', 'S');
6087 st.status_codes = optarg;
6088 break;
6089 default:
6090 usage_status();
6091 /* NOTREACHED */
6095 argc -= optind;
6096 argv += optind;
6098 #ifndef PROFILE
6099 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6100 NULL) == -1)
6101 err(1, "pledge");
6102 #endif
6103 cwd = getcwd(NULL, 0);
6104 if (cwd == NULL) {
6105 error = got_error_from_errno("getcwd");
6106 goto done;
6109 error = got_repo_pack_fds_open(&pack_fds);
6110 if (error != NULL)
6111 goto done;
6113 error = got_worktree_open(&worktree, cwd);
6114 if (error) {
6115 if (error->code == GOT_ERR_NOT_WORKTREE)
6116 error = wrap_not_worktree_error(error, "status", cwd);
6117 goto done;
6120 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6121 NULL, pack_fds);
6122 if (error != NULL)
6123 goto done;
6125 error = apply_unveil(got_repo_get_path(repo), 1,
6126 got_worktree_get_root_path(worktree));
6127 if (error)
6128 goto done;
6130 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6131 if (error)
6132 goto done;
6134 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6135 print_status, &st, check_cancelled, NULL);
6136 done:
6137 if (pack_fds) {
6138 const struct got_error *pack_err =
6139 got_repo_pack_fds_close(pack_fds);
6140 if (error == NULL)
6141 error = pack_err;
6144 TAILQ_FOREACH(pe, &paths, entry)
6145 free((char *)pe->path);
6146 got_pathlist_free(&paths);
6147 free(cwd);
6148 return error;
6151 __dead static void
6152 usage_ref(void)
6154 fprintf(stderr,
6155 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6156 "[-s reference] [-d] [name]\n",
6157 getprogname());
6158 exit(1);
6161 static const struct got_error *
6162 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6164 static const struct got_error *err = NULL;
6165 struct got_reflist_head refs;
6166 struct got_reflist_entry *re;
6168 TAILQ_INIT(&refs);
6169 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6170 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6171 repo);
6172 if (err)
6173 return err;
6175 TAILQ_FOREACH(re, &refs, entry) {
6176 char *refstr;
6177 refstr = got_ref_to_str(re->ref);
6178 if (refstr == NULL) {
6179 err = got_error_from_errno("got_ref_to_str");
6180 break;
6182 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6183 free(refstr);
6186 got_ref_list_free(&refs);
6187 return err;
6190 static const struct got_error *
6191 delete_ref_by_name(struct got_repository *repo, const char *refname)
6193 const struct got_error *err;
6194 struct got_reference *ref;
6196 err = got_ref_open(&ref, repo, refname, 0);
6197 if (err)
6198 return err;
6200 err = delete_ref(repo, ref);
6201 got_ref_close(ref);
6202 return err;
6205 static const struct got_error *
6206 add_ref(struct got_repository *repo, const char *refname, const char *target)
6208 const struct got_error *err = NULL;
6209 struct got_object_id *id = NULL;
6210 struct got_reference *ref = NULL;
6211 struct got_reflist_head refs;
6214 * Don't let the user create a reference name with a leading '-'.
6215 * While technically a valid reference name, this case is usually
6216 * an unintended typo.
6218 if (refname[0] == '-')
6219 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6221 TAILQ_INIT(&refs);
6222 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6223 if (err)
6224 goto done;
6225 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6226 &refs, repo);
6227 got_ref_list_free(&refs);
6228 if (err)
6229 goto done;
6231 err = got_ref_alloc(&ref, refname, id);
6232 if (err)
6233 goto done;
6235 err = got_ref_write(ref, repo);
6236 done:
6237 if (ref)
6238 got_ref_close(ref);
6239 free(id);
6240 return err;
6243 static const struct got_error *
6244 add_symref(struct got_repository *repo, const char *refname, const char *target)
6246 const struct got_error *err = NULL;
6247 struct got_reference *ref = NULL;
6248 struct got_reference *target_ref = NULL;
6251 * Don't let the user create a reference name with a leading '-'.
6252 * While technically a valid reference name, this case is usually
6253 * an unintended typo.
6255 if (refname[0] == '-')
6256 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6258 err = got_ref_open(&target_ref, repo, target, 0);
6259 if (err)
6260 return err;
6262 err = got_ref_alloc_symref(&ref, refname, target_ref);
6263 if (err)
6264 goto done;
6266 err = got_ref_write(ref, repo);
6267 done:
6268 if (target_ref)
6269 got_ref_close(target_ref);
6270 if (ref)
6271 got_ref_close(ref);
6272 return err;
6275 static const struct got_error *
6276 cmd_ref(int argc, char *argv[])
6278 const struct got_error *error = NULL;
6279 struct got_repository *repo = NULL;
6280 struct got_worktree *worktree = NULL;
6281 char *cwd = NULL, *repo_path = NULL;
6282 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6283 const char *obj_arg = NULL, *symref_target= NULL;
6284 char *refname = NULL;
6285 int *pack_fds = NULL;
6287 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6288 switch (ch) {
6289 case 'c':
6290 obj_arg = optarg;
6291 break;
6292 case 'd':
6293 do_delete = 1;
6294 break;
6295 case 'r':
6296 repo_path = realpath(optarg, NULL);
6297 if (repo_path == NULL)
6298 return got_error_from_errno2("realpath",
6299 optarg);
6300 got_path_strip_trailing_slashes(repo_path);
6301 break;
6302 case 'l':
6303 do_list = 1;
6304 break;
6305 case 's':
6306 symref_target = optarg;
6307 break;
6308 case 't':
6309 sort_by_time = 1;
6310 break;
6311 default:
6312 usage_ref();
6313 /* NOTREACHED */
6317 if (obj_arg && do_list)
6318 option_conflict('c', 'l');
6319 if (obj_arg && do_delete)
6320 option_conflict('c', 'd');
6321 if (obj_arg && symref_target)
6322 option_conflict('c', 's');
6323 if (symref_target && do_delete)
6324 option_conflict('s', 'd');
6325 if (symref_target && do_list)
6326 option_conflict('s', 'l');
6327 if (do_delete && do_list)
6328 option_conflict('d', 'l');
6329 if (sort_by_time && !do_list)
6330 errx(1, "-t option requires -l option");
6332 argc -= optind;
6333 argv += optind;
6335 if (do_list) {
6336 if (argc != 0 && argc != 1)
6337 usage_ref();
6338 if (argc == 1) {
6339 refname = strdup(argv[0]);
6340 if (refname == NULL) {
6341 error = got_error_from_errno("strdup");
6342 goto done;
6345 } else {
6346 if (argc != 1)
6347 usage_ref();
6348 refname = strdup(argv[0]);
6349 if (refname == NULL) {
6350 error = got_error_from_errno("strdup");
6351 goto done;
6355 if (refname)
6356 got_path_strip_trailing_slashes(refname);
6358 #ifndef PROFILE
6359 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6360 "sendfd unveil", NULL) == -1)
6361 err(1, "pledge");
6362 #endif
6363 cwd = getcwd(NULL, 0);
6364 if (cwd == NULL) {
6365 error = got_error_from_errno("getcwd");
6366 goto done;
6369 error = got_repo_pack_fds_open(&pack_fds);
6370 if (error != NULL)
6371 goto done;
6373 if (repo_path == NULL) {
6374 error = got_worktree_open(&worktree, cwd);
6375 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6376 goto done;
6377 else
6378 error = NULL;
6379 if (worktree) {
6380 repo_path =
6381 strdup(got_worktree_get_repo_path(worktree));
6382 if (repo_path == NULL)
6383 error = got_error_from_errno("strdup");
6384 if (error)
6385 goto done;
6386 } else {
6387 repo_path = strdup(cwd);
6388 if (repo_path == NULL) {
6389 error = got_error_from_errno("strdup");
6390 goto done;
6395 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6396 if (error != NULL)
6397 goto done;
6399 #ifndef PROFILE
6400 if (do_list) {
6401 /* Remove "cpath" promise. */
6402 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6403 NULL) == -1)
6404 err(1, "pledge");
6406 #endif
6408 error = apply_unveil(got_repo_get_path(repo), do_list,
6409 worktree ? got_worktree_get_root_path(worktree) : NULL);
6410 if (error)
6411 goto done;
6413 if (do_list)
6414 error = list_refs(repo, refname, sort_by_time);
6415 else if (do_delete)
6416 error = delete_ref_by_name(repo, refname);
6417 else if (symref_target)
6418 error = add_symref(repo, refname, symref_target);
6419 else {
6420 if (obj_arg == NULL)
6421 usage_ref();
6422 error = add_ref(repo, refname, obj_arg);
6424 done:
6425 free(refname);
6426 if (repo) {
6427 const struct got_error *close_err = got_repo_close(repo);
6428 if (error == NULL)
6429 error = close_err;
6431 if (worktree)
6432 got_worktree_close(worktree);
6433 if (pack_fds) {
6434 const struct got_error *pack_err =
6435 got_repo_pack_fds_close(pack_fds);
6436 if (error == NULL)
6437 error = pack_err;
6439 free(cwd);
6440 free(repo_path);
6441 return error;
6444 __dead static void
6445 usage_branch(void)
6447 fprintf(stderr,
6448 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6449 "[-n] [name]\n", getprogname());
6450 exit(1);
6453 static const struct got_error *
6454 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6455 struct got_reference *ref)
6457 const struct got_error *err = NULL;
6458 const char *refname, *marker = " ";
6459 char *refstr;
6461 refname = got_ref_get_name(ref);
6462 if (worktree && strcmp(refname,
6463 got_worktree_get_head_ref_name(worktree)) == 0) {
6464 struct got_object_id *id = NULL;
6466 err = got_ref_resolve(&id, repo, ref);
6467 if (err)
6468 return err;
6469 if (got_object_id_cmp(id,
6470 got_worktree_get_base_commit_id(worktree)) == 0)
6471 marker = "* ";
6472 else
6473 marker = "~ ";
6474 free(id);
6477 if (strncmp(refname, "refs/heads/", 11) == 0)
6478 refname += 11;
6479 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6480 refname += 18;
6481 if (strncmp(refname, "refs/remotes/", 13) == 0)
6482 refname += 13;
6484 refstr = got_ref_to_str(ref);
6485 if (refstr == NULL)
6486 return got_error_from_errno("got_ref_to_str");
6488 printf("%s%s: %s\n", marker, refname, refstr);
6489 free(refstr);
6490 return NULL;
6493 static const struct got_error *
6494 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6496 const char *refname;
6498 if (worktree == NULL)
6499 return got_error(GOT_ERR_NOT_WORKTREE);
6501 refname = got_worktree_get_head_ref_name(worktree);
6503 if (strncmp(refname, "refs/heads/", 11) == 0)
6504 refname += 11;
6505 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6506 refname += 18;
6508 printf("%s\n", refname);
6510 return NULL;
6513 static const struct got_error *
6514 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6515 int sort_by_time)
6517 static const struct got_error *err = NULL;
6518 struct got_reflist_head refs;
6519 struct got_reflist_entry *re;
6520 struct got_reference *temp_ref = NULL;
6521 int rebase_in_progress, histedit_in_progress;
6523 TAILQ_INIT(&refs);
6525 if (worktree) {
6526 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6527 worktree);
6528 if (err)
6529 return err;
6531 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6532 worktree);
6533 if (err)
6534 return err;
6536 if (rebase_in_progress || histedit_in_progress) {
6537 err = got_ref_open(&temp_ref, repo,
6538 got_worktree_get_head_ref_name(worktree), 0);
6539 if (err)
6540 return err;
6541 list_branch(repo, worktree, temp_ref);
6542 got_ref_close(temp_ref);
6546 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6547 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6548 repo);
6549 if (err)
6550 return err;
6552 TAILQ_FOREACH(re, &refs, entry)
6553 list_branch(repo, worktree, re->ref);
6555 got_ref_list_free(&refs);
6557 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6558 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6559 repo);
6560 if (err)
6561 return err;
6563 TAILQ_FOREACH(re, &refs, entry)
6564 list_branch(repo, worktree, re->ref);
6566 got_ref_list_free(&refs);
6568 return NULL;
6571 static const struct got_error *
6572 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6573 const char *branch_name)
6575 const struct got_error *err = NULL;
6576 struct got_reference *ref = NULL;
6577 char *refname, *remote_refname = NULL;
6579 if (strncmp(branch_name, "refs/", 5) == 0)
6580 branch_name += 5;
6581 if (strncmp(branch_name, "heads/", 6) == 0)
6582 branch_name += 6;
6583 else if (strncmp(branch_name, "remotes/", 8) == 0)
6584 branch_name += 8;
6586 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6587 return got_error_from_errno("asprintf");
6589 if (asprintf(&remote_refname, "refs/remotes/%s",
6590 branch_name) == -1) {
6591 err = got_error_from_errno("asprintf");
6592 goto done;
6595 err = got_ref_open(&ref, repo, refname, 0);
6596 if (err) {
6597 const struct got_error *err2;
6598 if (err->code != GOT_ERR_NOT_REF)
6599 goto done;
6601 * Keep 'err' intact such that if neither branch exists
6602 * we report "refs/heads" rather than "refs/remotes" in
6603 * our error message.
6605 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6606 if (err2)
6607 goto done;
6608 err = NULL;
6611 if (worktree &&
6612 strcmp(got_worktree_get_head_ref_name(worktree),
6613 got_ref_get_name(ref)) == 0) {
6614 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6615 "will not delete this work tree's current branch");
6616 goto done;
6619 err = delete_ref(repo, ref);
6620 done:
6621 if (ref)
6622 got_ref_close(ref);
6623 free(refname);
6624 free(remote_refname);
6625 return err;
6628 static const struct got_error *
6629 add_branch(struct got_repository *repo, const char *branch_name,
6630 struct got_object_id *base_commit_id)
6632 const struct got_error *err = NULL;
6633 struct got_reference *ref = NULL;
6634 char *base_refname = NULL, *refname = NULL;
6637 * Don't let the user create a branch name with a leading '-'.
6638 * While technically a valid reference name, this case is usually
6639 * an unintended typo.
6641 if (branch_name[0] == '-')
6642 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6644 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6645 branch_name += 11;
6647 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6648 err = got_error_from_errno("asprintf");
6649 goto done;
6652 err = got_ref_open(&ref, repo, refname, 0);
6653 if (err == NULL) {
6654 err = got_error(GOT_ERR_BRANCH_EXISTS);
6655 goto done;
6656 } else if (err->code != GOT_ERR_NOT_REF)
6657 goto done;
6659 err = got_ref_alloc(&ref, refname, base_commit_id);
6660 if (err)
6661 goto done;
6663 err = got_ref_write(ref, repo);
6664 done:
6665 if (ref)
6666 got_ref_close(ref);
6667 free(base_refname);
6668 free(refname);
6669 return err;
6672 static const struct got_error *
6673 cmd_branch(int argc, char *argv[])
6675 const struct got_error *error = NULL;
6676 struct got_repository *repo = NULL;
6677 struct got_worktree *worktree = NULL;
6678 char *cwd = NULL, *repo_path = NULL;
6679 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6680 const char *delref = NULL, *commit_id_arg = NULL;
6681 struct got_reference *ref = NULL;
6682 struct got_pathlist_head paths;
6683 struct got_pathlist_entry *pe;
6684 struct got_object_id *commit_id = NULL;
6685 char *commit_id_str = NULL;
6686 int *pack_fds = NULL;
6688 TAILQ_INIT(&paths);
6690 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6691 switch (ch) {
6692 case 'c':
6693 commit_id_arg = optarg;
6694 break;
6695 case 'd':
6696 delref = optarg;
6697 break;
6698 case 'r':
6699 repo_path = realpath(optarg, NULL);
6700 if (repo_path == NULL)
6701 return got_error_from_errno2("realpath",
6702 optarg);
6703 got_path_strip_trailing_slashes(repo_path);
6704 break;
6705 case 'l':
6706 do_list = 1;
6707 break;
6708 case 'n':
6709 do_update = 0;
6710 break;
6711 case 't':
6712 sort_by_time = 1;
6713 break;
6714 default:
6715 usage_branch();
6716 /* NOTREACHED */
6720 if (do_list && delref)
6721 option_conflict('l', 'd');
6722 if (sort_by_time && !do_list)
6723 errx(1, "-t option requires -l option");
6725 argc -= optind;
6726 argv += optind;
6728 if (!do_list && !delref && argc == 0)
6729 do_show = 1;
6731 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6732 errx(1, "-c option can only be used when creating a branch");
6734 if (do_list || delref) {
6735 if (argc > 0)
6736 usage_branch();
6737 } else if (!do_show && argc != 1)
6738 usage_branch();
6740 #ifndef PROFILE
6741 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6742 "sendfd unveil", NULL) == -1)
6743 err(1, "pledge");
6744 #endif
6745 cwd = getcwd(NULL, 0);
6746 if (cwd == NULL) {
6747 error = got_error_from_errno("getcwd");
6748 goto done;
6751 error = got_repo_pack_fds_open(&pack_fds);
6752 if (error != NULL)
6753 goto done;
6755 if (repo_path == NULL) {
6756 error = got_worktree_open(&worktree, cwd);
6757 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6758 goto done;
6759 else
6760 error = NULL;
6761 if (worktree) {
6762 repo_path =
6763 strdup(got_worktree_get_repo_path(worktree));
6764 if (repo_path == NULL)
6765 error = got_error_from_errno("strdup");
6766 if (error)
6767 goto done;
6768 } else {
6769 repo_path = strdup(cwd);
6770 if (repo_path == NULL) {
6771 error = got_error_from_errno("strdup");
6772 goto done;
6777 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6778 if (error != NULL)
6779 goto done;
6781 #ifndef PROFILE
6782 if (do_list || do_show) {
6783 /* Remove "cpath" promise. */
6784 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6785 NULL) == -1)
6786 err(1, "pledge");
6788 #endif
6790 error = apply_unveil(got_repo_get_path(repo), do_list,
6791 worktree ? got_worktree_get_root_path(worktree) : NULL);
6792 if (error)
6793 goto done;
6795 if (do_show)
6796 error = show_current_branch(repo, worktree);
6797 else if (do_list)
6798 error = list_branches(repo, worktree, sort_by_time);
6799 else if (delref)
6800 error = delete_branch(repo, worktree, delref);
6801 else {
6802 struct got_reflist_head refs;
6803 TAILQ_INIT(&refs);
6804 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6805 NULL);
6806 if (error)
6807 goto done;
6808 if (commit_id_arg == NULL)
6809 commit_id_arg = worktree ?
6810 got_worktree_get_head_ref_name(worktree) :
6811 GOT_REF_HEAD;
6812 error = got_repo_match_object_id(&commit_id, NULL,
6813 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6814 got_ref_list_free(&refs);
6815 if (error)
6816 goto done;
6817 error = add_branch(repo, argv[0], commit_id);
6818 if (error)
6819 goto done;
6820 if (worktree && do_update) {
6821 struct got_update_progress_arg upa;
6822 char *branch_refname = NULL;
6824 error = got_object_id_str(&commit_id_str, commit_id);
6825 if (error)
6826 goto done;
6827 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6828 worktree);
6829 if (error)
6830 goto done;
6831 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6832 == -1) {
6833 error = got_error_from_errno("asprintf");
6834 goto done;
6836 error = got_ref_open(&ref, repo, branch_refname, 0);
6837 free(branch_refname);
6838 if (error)
6839 goto done;
6840 error = switch_head_ref(ref, commit_id, worktree,
6841 repo);
6842 if (error)
6843 goto done;
6844 error = got_worktree_set_base_commit_id(worktree, repo,
6845 commit_id);
6846 if (error)
6847 goto done;
6848 memset(&upa, 0, sizeof(upa));
6849 error = got_worktree_checkout_files(worktree, &paths,
6850 repo, update_progress, &upa, check_cancelled,
6851 NULL);
6852 if (error)
6853 goto done;
6854 if (upa.did_something) {
6855 printf("Updated to %s: %s\n",
6856 got_worktree_get_head_ref_name(worktree),
6857 commit_id_str);
6859 print_update_progress_stats(&upa);
6862 done:
6863 if (ref)
6864 got_ref_close(ref);
6865 if (repo) {
6866 const struct got_error *close_err = got_repo_close(repo);
6867 if (error == NULL)
6868 error = close_err;
6870 if (worktree)
6871 got_worktree_close(worktree);
6872 if (pack_fds) {
6873 const struct got_error *pack_err =
6874 got_repo_pack_fds_close(pack_fds);
6875 if (error == NULL)
6876 error = pack_err;
6878 free(cwd);
6879 free(repo_path);
6880 free(commit_id);
6881 free(commit_id_str);
6882 TAILQ_FOREACH(pe, &paths, entry)
6883 free((char *)pe->path);
6884 got_pathlist_free(&paths);
6885 return error;
6889 __dead static void
6890 usage_tag(void)
6892 fprintf(stderr,
6893 "usage: %s tag [-c commit] [-r repository] [-l] "
6894 "[-m message] [-s signer-id] [-V] name\n",
6895 getprogname());
6896 exit(1);
6899 #if 0
6900 static const struct got_error *
6901 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6903 const struct got_error *err = NULL;
6904 struct got_reflist_entry *re, *se, *new;
6905 struct got_object_id *re_id, *se_id;
6906 struct got_tag_object *re_tag, *se_tag;
6907 time_t re_time, se_time;
6909 STAILQ_FOREACH(re, tags, entry) {
6910 se = STAILQ_FIRST(sorted);
6911 if (se == NULL) {
6912 err = got_reflist_entry_dup(&new, re);
6913 if (err)
6914 return err;
6915 STAILQ_INSERT_HEAD(sorted, new, entry);
6916 continue;
6917 } else {
6918 err = got_ref_resolve(&re_id, repo, re->ref);
6919 if (err)
6920 break;
6921 err = got_object_open_as_tag(&re_tag, repo, re_id);
6922 free(re_id);
6923 if (err)
6924 break;
6925 re_time = got_object_tag_get_tagger_time(re_tag);
6926 got_object_tag_close(re_tag);
6929 while (se) {
6930 err = got_ref_resolve(&se_id, repo, re->ref);
6931 if (err)
6932 break;
6933 err = got_object_open_as_tag(&se_tag, repo, se_id);
6934 free(se_id);
6935 if (err)
6936 break;
6937 se_time = got_object_tag_get_tagger_time(se_tag);
6938 got_object_tag_close(se_tag);
6940 if (se_time > re_time) {
6941 err = got_reflist_entry_dup(&new, re);
6942 if (err)
6943 return err;
6944 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6945 break;
6947 se = STAILQ_NEXT(se, entry);
6948 continue;
6951 done:
6952 return err;
6954 #endif
6956 static const struct got_error *
6957 get_tag_refname(char **refname, const char *tag_name)
6959 const struct got_error *err;
6961 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6962 *refname = strdup(tag_name);
6963 if (*refname == NULL)
6964 return got_error_from_errno("strdup");
6965 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6966 err = got_error_from_errno("asprintf");
6967 *refname = NULL;
6968 return err;
6971 return NULL;
6974 static const struct got_error *
6975 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6976 const char *allowed_signers, const char *revoked_signers, int verbosity)
6978 static const struct got_error *err = NULL;
6979 struct got_reflist_head refs;
6980 struct got_reflist_entry *re;
6981 char *wanted_refname = NULL;
6982 int bad_sigs = 0;
6984 TAILQ_INIT(&refs);
6986 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6987 if (err)
6988 return err;
6990 if (tag_name) {
6991 struct got_reference *ref;
6992 err = get_tag_refname(&wanted_refname, tag_name);
6993 if (err)
6994 goto done;
6995 /* Wanted tag reference should exist. */
6996 err = got_ref_open(&ref, repo, wanted_refname, 0);
6997 if (err)
6998 goto done;
6999 got_ref_close(ref);
7002 TAILQ_FOREACH(re, &refs, entry) {
7003 const char *refname;
7004 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7005 char datebuf[26];
7006 const char *tagger, *ssh_sig = NULL;
7007 char *sig_msg = NULL;
7008 time_t tagger_time;
7009 struct got_object_id *id;
7010 struct got_tag_object *tag;
7011 struct got_commit_object *commit = NULL;
7013 refname = got_ref_get_name(re->ref);
7014 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7015 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7016 continue;
7017 refname += 10;
7018 refstr = got_ref_to_str(re->ref);
7019 if (refstr == NULL) {
7020 err = got_error_from_errno("got_ref_to_str");
7021 break;
7024 err = got_ref_resolve(&id, repo, re->ref);
7025 if (err)
7026 break;
7027 err = got_object_open_as_tag(&tag, repo, id);
7028 if (err) {
7029 if (err->code != GOT_ERR_OBJ_TYPE) {
7030 free(id);
7031 break;
7033 /* "lightweight" tag */
7034 err = got_object_open_as_commit(&commit, repo, id);
7035 if (err) {
7036 free(id);
7037 break;
7039 tagger = got_object_commit_get_committer(commit);
7040 tagger_time =
7041 got_object_commit_get_committer_time(commit);
7042 err = got_object_id_str(&id_str, id);
7043 free(id);
7044 if (err)
7045 break;
7046 } else {
7047 free(id);
7048 tagger = got_object_tag_get_tagger(tag);
7049 tagger_time = got_object_tag_get_tagger_time(tag);
7050 err = got_object_id_str(&id_str,
7051 got_object_tag_get_object_id(tag));
7052 if (err)
7053 break;
7056 if (verify_tags) {
7057 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7058 got_object_tag_get_message(tag));
7059 if (ssh_sig && allowed_signers == NULL) {
7060 err = got_error_msg(
7061 GOT_ERR_VERIFY_TAG_SIGNATURE,
7062 "SSH signature verification requires "
7063 "setting allowed_signers in "
7064 "got.conf(5)");
7065 break;
7069 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7070 free(refstr);
7071 printf("from: %s\n", tagger);
7072 datestr = get_datestr(&tagger_time, datebuf);
7073 if (datestr)
7074 printf("date: %s UTC\n", datestr);
7075 if (commit)
7076 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7077 else {
7078 switch (got_object_tag_get_object_type(tag)) {
7079 case GOT_OBJ_TYPE_BLOB:
7080 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7081 id_str);
7082 break;
7083 case GOT_OBJ_TYPE_TREE:
7084 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7085 id_str);
7086 break;
7087 case GOT_OBJ_TYPE_COMMIT:
7088 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7089 id_str);
7090 break;
7091 case GOT_OBJ_TYPE_TAG:
7092 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7093 id_str);
7094 break;
7095 default:
7096 break;
7099 free(id_str);
7101 if (ssh_sig) {
7102 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7103 allowed_signers, revoked_signers, verbosity);
7104 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7105 bad_sigs = 1;
7106 else if (err)
7107 break;
7108 printf("signature: %s", sig_msg);
7109 free(sig_msg);
7110 sig_msg = NULL;
7113 if (commit) {
7114 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7115 if (err)
7116 break;
7117 got_object_commit_close(commit);
7118 } else {
7119 tagmsg0 = strdup(got_object_tag_get_message(tag));
7120 got_object_tag_close(tag);
7121 if (tagmsg0 == NULL) {
7122 err = got_error_from_errno("strdup");
7123 break;
7127 tagmsg = tagmsg0;
7128 do {
7129 line = strsep(&tagmsg, "\n");
7130 if (line)
7131 printf(" %s\n", line);
7132 } while (line);
7133 free(tagmsg0);
7135 done:
7136 got_ref_list_free(&refs);
7137 free(wanted_refname);
7139 if (err == NULL && bad_sigs)
7140 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7141 return err;
7144 static const struct got_error *
7145 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7146 const char *tag_name, const char *repo_path)
7148 const struct got_error *err = NULL;
7149 char *template = NULL, *initial_content = NULL;
7150 char *editor = NULL;
7151 int initial_content_len;
7152 int fd = -1;
7154 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7155 err = got_error_from_errno("asprintf");
7156 goto done;
7159 initial_content_len = asprintf(&initial_content,
7160 "\n# tagging commit %s as %s\n",
7161 commit_id_str, tag_name);
7162 if (initial_content_len == -1) {
7163 err = got_error_from_errno("asprintf");
7164 goto done;
7167 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7168 if (err)
7169 goto done;
7171 if (write(fd, initial_content, initial_content_len) == -1) {
7172 err = got_error_from_errno2("write", *tagmsg_path);
7173 goto done;
7176 err = get_editor(&editor);
7177 if (err)
7178 goto done;
7179 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7180 initial_content_len, 1);
7181 done:
7182 free(initial_content);
7183 free(template);
7184 free(editor);
7186 if (fd != -1 && close(fd) == -1 && err == NULL)
7187 err = got_error_from_errno2("close", *tagmsg_path);
7189 if (err) {
7190 free(*tagmsg);
7191 *tagmsg = NULL;
7193 return err;
7196 static const struct got_error *
7197 add_tag(struct got_repository *repo, const char *tagger,
7198 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7199 const char *signer_id, int verbosity)
7201 const struct got_error *err = NULL;
7202 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7203 char *label = NULL, *commit_id_str = NULL;
7204 struct got_reference *ref = NULL;
7205 char *refname = NULL, *tagmsg = NULL;
7206 char *tagmsg_path = NULL, *tag_id_str = NULL;
7207 int preserve_tagmsg = 0;
7208 struct got_reflist_head refs;
7210 TAILQ_INIT(&refs);
7213 * Don't let the user create a tag name with a leading '-'.
7214 * While technically a valid reference name, this case is usually
7215 * an unintended typo.
7217 if (tag_name[0] == '-')
7218 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7220 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7221 if (err)
7222 goto done;
7224 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7225 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7226 if (err)
7227 goto done;
7229 err = got_object_id_str(&commit_id_str, commit_id);
7230 if (err)
7231 goto done;
7233 err = get_tag_refname(&refname, tag_name);
7234 if (err)
7235 goto done;
7236 if (strncmp("refs/tags/", tag_name, 10) == 0)
7237 tag_name += 10;
7239 err = got_ref_open(&ref, repo, refname, 0);
7240 if (err == NULL) {
7241 err = got_error(GOT_ERR_TAG_EXISTS);
7242 goto done;
7243 } else if (err->code != GOT_ERR_NOT_REF)
7244 goto done;
7246 if (tagmsg_arg == NULL) {
7247 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7248 tag_name, got_repo_get_path(repo));
7249 if (err) {
7250 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7251 tagmsg_path != NULL)
7252 preserve_tagmsg = 1;
7253 goto done;
7255 /* Editor is done; we can now apply unveil(2) */
7256 err = got_sigs_apply_unveil();
7257 if (err)
7258 goto done;
7259 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7260 if (err)
7261 goto done;
7264 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7265 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7266 verbosity);
7267 if (err) {
7268 if (tagmsg_path)
7269 preserve_tagmsg = 1;
7270 goto done;
7273 err = got_ref_alloc(&ref, refname, tag_id);
7274 if (err) {
7275 if (tagmsg_path)
7276 preserve_tagmsg = 1;
7277 goto done;
7280 err = got_ref_write(ref, repo);
7281 if (err) {
7282 if (tagmsg_path)
7283 preserve_tagmsg = 1;
7284 goto done;
7287 err = got_object_id_str(&tag_id_str, tag_id);
7288 if (err) {
7289 if (tagmsg_path)
7290 preserve_tagmsg = 1;
7291 goto done;
7293 printf("Created tag %s\n", tag_id_str);
7294 done:
7295 if (preserve_tagmsg) {
7296 fprintf(stderr, "%s: tag message preserved in %s\n",
7297 getprogname(), tagmsg_path);
7298 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7299 err = got_error_from_errno2("unlink", tagmsg_path);
7300 free(tag_id_str);
7301 if (ref)
7302 got_ref_close(ref);
7303 free(commit_id);
7304 free(commit_id_str);
7305 free(refname);
7306 free(tagmsg);
7307 free(tagmsg_path);
7308 got_ref_list_free(&refs);
7309 return err;
7312 static const struct got_error *
7313 cmd_tag(int argc, char *argv[])
7315 const struct got_error *error = NULL;
7316 struct got_repository *repo = NULL;
7317 struct got_worktree *worktree = NULL;
7318 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7319 char *gitconfig_path = NULL, *tagger = NULL;
7320 char *allowed_signers = NULL, *revoked_signers = NULL;
7321 char *signer_id = NULL;
7322 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7323 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7324 int *pack_fds = NULL;
7326 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7327 switch (ch) {
7328 case 'c':
7329 commit_id_arg = optarg;
7330 break;
7331 case 'm':
7332 tagmsg = optarg;
7333 break;
7334 case 'r':
7335 repo_path = realpath(optarg, NULL);
7336 if (repo_path == NULL) {
7337 error = got_error_from_errno2("realpath",
7338 optarg);
7339 goto done;
7341 got_path_strip_trailing_slashes(repo_path);
7342 break;
7343 case 'l':
7344 do_list = 1;
7345 break;
7346 case 's':
7347 signer_id = strdup(optarg);
7348 if (signer_id == NULL) {
7349 error = got_error_from_errno("strdup");
7350 goto done;
7352 break;
7353 case 'V':
7354 verify_tags = 1;
7355 break;
7356 case 'v':
7357 if (verbosity < 0)
7358 verbosity = 0;
7359 else if (verbosity < 3)
7360 verbosity++;
7361 break;
7362 default:
7363 usage_tag();
7364 /* NOTREACHED */
7368 argc -= optind;
7369 argv += optind;
7371 if (do_list || verify_tags) {
7372 if (commit_id_arg != NULL)
7373 errx(1,
7374 "-c option can only be used when creating a tag");
7375 if (tagmsg) {
7376 if (do_list)
7377 option_conflict('l', 'm');
7378 else
7379 option_conflict('V', 'm');
7381 if (signer_id) {
7382 if (do_list)
7383 option_conflict('l', 's');
7384 else
7385 option_conflict('V', 's');
7387 if (argc > 1)
7388 usage_tag();
7389 } else if (argc != 1)
7390 usage_tag();
7392 if (argc == 1)
7393 tag_name = argv[0];
7395 #ifndef PROFILE
7396 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7397 "sendfd unveil", NULL) == -1)
7398 err(1, "pledge");
7399 #endif
7400 cwd = getcwd(NULL, 0);
7401 if (cwd == NULL) {
7402 error = got_error_from_errno("getcwd");
7403 goto done;
7406 error = got_repo_pack_fds_open(&pack_fds);
7407 if (error != NULL)
7408 goto done;
7410 if (repo_path == NULL) {
7411 error = got_worktree_open(&worktree, cwd);
7412 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7413 goto done;
7414 else
7415 error = NULL;
7416 if (worktree) {
7417 repo_path =
7418 strdup(got_worktree_get_repo_path(worktree));
7419 if (repo_path == NULL)
7420 error = got_error_from_errno("strdup");
7421 if (error)
7422 goto done;
7423 } else {
7424 repo_path = strdup(cwd);
7425 if (repo_path == NULL) {
7426 error = got_error_from_errno("strdup");
7427 goto done;
7432 if (do_list || verify_tags) {
7433 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7434 if (error != NULL)
7435 goto done;
7436 error = get_allowed_signers(&allowed_signers, repo, worktree);
7437 if (error)
7438 goto done;
7439 error = get_revoked_signers(&revoked_signers, repo, worktree);
7440 if (error)
7441 goto done;
7442 if (worktree) {
7443 /* Release work tree lock. */
7444 got_worktree_close(worktree);
7445 worktree = NULL;
7449 * Remove "cpath" promise unless needed for signature tmpfile
7450 * creation.
7452 if (verify_tags)
7453 got_sigs_apply_unveil();
7454 else {
7455 #ifndef PROFILE
7456 if (pledge("stdio rpath wpath flock proc exec sendfd "
7457 "unveil", NULL) == -1)
7458 err(1, "pledge");
7459 #endif
7461 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7462 if (error)
7463 goto done;
7464 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7465 revoked_signers, verbosity);
7466 } else {
7467 error = get_gitconfig_path(&gitconfig_path);
7468 if (error)
7469 goto done;
7470 error = got_repo_open(&repo, repo_path, gitconfig_path,
7471 pack_fds);
7472 if (error != NULL)
7473 goto done;
7475 error = get_author(&tagger, repo, worktree);
7476 if (error)
7477 goto done;
7478 if (signer_id == NULL) {
7479 error = get_signer_id(&signer_id, repo, worktree);
7480 if (error)
7481 goto done;
7483 if (worktree) {
7484 /* Release work tree lock. */
7485 got_worktree_close(worktree);
7486 worktree = NULL;
7489 if (tagmsg) {
7490 if (signer_id) {
7491 error = got_sigs_apply_unveil();
7492 if (error)
7493 goto done;
7495 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7496 if (error)
7497 goto done;
7500 if (commit_id_arg == NULL) {
7501 struct got_reference *head_ref;
7502 struct got_object_id *commit_id;
7503 error = got_ref_open(&head_ref, repo,
7504 worktree ? got_worktree_get_head_ref_name(worktree)
7505 : GOT_REF_HEAD, 0);
7506 if (error)
7507 goto done;
7508 error = got_ref_resolve(&commit_id, repo, head_ref);
7509 got_ref_close(head_ref);
7510 if (error)
7511 goto done;
7512 error = got_object_id_str(&commit_id_str, commit_id);
7513 free(commit_id);
7514 if (error)
7515 goto done;
7518 error = add_tag(repo, tagger, tag_name,
7519 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7520 signer_id, verbosity);
7522 done:
7523 if (repo) {
7524 const struct got_error *close_err = got_repo_close(repo);
7525 if (error == NULL)
7526 error = close_err;
7528 if (worktree)
7529 got_worktree_close(worktree);
7530 if (pack_fds) {
7531 const struct got_error *pack_err =
7532 got_repo_pack_fds_close(pack_fds);
7533 if (error == NULL)
7534 error = pack_err;
7536 free(cwd);
7537 free(repo_path);
7538 free(gitconfig_path);
7539 free(commit_id_str);
7540 free(tagger);
7541 free(allowed_signers);
7542 free(revoked_signers);
7543 free(signer_id);
7544 return error;
7547 __dead static void
7548 usage_add(void)
7550 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7551 getprogname());
7552 exit(1);
7555 static const struct got_error *
7556 add_progress(void *arg, unsigned char status, const char *path)
7558 while (path[0] == '/')
7559 path++;
7560 printf("%c %s\n", status, path);
7561 return NULL;
7564 static const struct got_error *
7565 cmd_add(int argc, char *argv[])
7567 const struct got_error *error = NULL;
7568 struct got_repository *repo = NULL;
7569 struct got_worktree *worktree = NULL;
7570 char *cwd = NULL;
7571 struct got_pathlist_head paths;
7572 struct got_pathlist_entry *pe;
7573 int ch, can_recurse = 0, no_ignores = 0;
7574 int *pack_fds = NULL;
7576 TAILQ_INIT(&paths);
7578 while ((ch = getopt(argc, argv, "IR")) != -1) {
7579 switch (ch) {
7580 case 'I':
7581 no_ignores = 1;
7582 break;
7583 case 'R':
7584 can_recurse = 1;
7585 break;
7586 default:
7587 usage_add();
7588 /* NOTREACHED */
7592 argc -= optind;
7593 argv += optind;
7595 #ifndef PROFILE
7596 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7597 NULL) == -1)
7598 err(1, "pledge");
7599 #endif
7600 if (argc < 1)
7601 usage_add();
7603 cwd = getcwd(NULL, 0);
7604 if (cwd == NULL) {
7605 error = got_error_from_errno("getcwd");
7606 goto done;
7609 error = got_repo_pack_fds_open(&pack_fds);
7610 if (error != NULL)
7611 goto done;
7613 error = got_worktree_open(&worktree, cwd);
7614 if (error) {
7615 if (error->code == GOT_ERR_NOT_WORKTREE)
7616 error = wrap_not_worktree_error(error, "add", cwd);
7617 goto done;
7620 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7621 NULL, pack_fds);
7622 if (error != NULL)
7623 goto done;
7625 error = apply_unveil(got_repo_get_path(repo), 1,
7626 got_worktree_get_root_path(worktree));
7627 if (error)
7628 goto done;
7630 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7631 if (error)
7632 goto done;
7634 if (!can_recurse) {
7635 char *ondisk_path;
7636 struct stat sb;
7637 TAILQ_FOREACH(pe, &paths, entry) {
7638 if (asprintf(&ondisk_path, "%s/%s",
7639 got_worktree_get_root_path(worktree),
7640 pe->path) == -1) {
7641 error = got_error_from_errno("asprintf");
7642 goto done;
7644 if (lstat(ondisk_path, &sb) == -1) {
7645 if (errno == ENOENT) {
7646 free(ondisk_path);
7647 continue;
7649 error = got_error_from_errno2("lstat",
7650 ondisk_path);
7651 free(ondisk_path);
7652 goto done;
7654 free(ondisk_path);
7655 if (S_ISDIR(sb.st_mode)) {
7656 error = got_error_msg(GOT_ERR_BAD_PATH,
7657 "adding directories requires -R option");
7658 goto done;
7663 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7664 NULL, repo, no_ignores);
7665 done:
7666 if (repo) {
7667 const struct got_error *close_err = got_repo_close(repo);
7668 if (error == NULL)
7669 error = close_err;
7671 if (worktree)
7672 got_worktree_close(worktree);
7673 if (pack_fds) {
7674 const struct got_error *pack_err =
7675 got_repo_pack_fds_close(pack_fds);
7676 if (error == NULL)
7677 error = pack_err;
7679 TAILQ_FOREACH(pe, &paths, entry)
7680 free((char *)pe->path);
7681 got_pathlist_free(&paths);
7682 free(cwd);
7683 return error;
7686 __dead static void
7687 usage_remove(void)
7689 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7690 "path ...\n", getprogname());
7691 exit(1);
7694 static const struct got_error *
7695 print_remove_status(void *arg, unsigned char status,
7696 unsigned char staged_status, const char *path)
7698 while (path[0] == '/')
7699 path++;
7700 if (status == GOT_STATUS_NONEXISTENT)
7701 return NULL;
7702 if (status == staged_status && (status == GOT_STATUS_DELETE))
7703 status = GOT_STATUS_NO_CHANGE;
7704 printf("%c%c %s\n", status, staged_status, path);
7705 return NULL;
7708 static const struct got_error *
7709 cmd_remove(int argc, char *argv[])
7711 const struct got_error *error = NULL;
7712 struct got_worktree *worktree = NULL;
7713 struct got_repository *repo = NULL;
7714 const char *status_codes = NULL;
7715 char *cwd = NULL;
7716 struct got_pathlist_head paths;
7717 struct got_pathlist_entry *pe;
7718 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7719 int ignore_missing_paths = 0;
7720 int *pack_fds = NULL;
7722 TAILQ_INIT(&paths);
7724 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7725 switch (ch) {
7726 case 'f':
7727 delete_local_mods = 1;
7728 ignore_missing_paths = 1;
7729 break;
7730 case 'k':
7731 keep_on_disk = 1;
7732 break;
7733 case 'R':
7734 can_recurse = 1;
7735 break;
7736 case 's':
7737 for (i = 0; i < strlen(optarg); i++) {
7738 switch (optarg[i]) {
7739 case GOT_STATUS_MODIFY:
7740 delete_local_mods = 1;
7741 break;
7742 case GOT_STATUS_MISSING:
7743 ignore_missing_paths = 1;
7744 break;
7745 default:
7746 errx(1, "invalid status code '%c'",
7747 optarg[i]);
7750 status_codes = optarg;
7751 break;
7752 default:
7753 usage_remove();
7754 /* NOTREACHED */
7758 argc -= optind;
7759 argv += optind;
7761 #ifndef PROFILE
7762 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7763 NULL) == -1)
7764 err(1, "pledge");
7765 #endif
7766 if (argc < 1)
7767 usage_remove();
7769 cwd = getcwd(NULL, 0);
7770 if (cwd == NULL) {
7771 error = got_error_from_errno("getcwd");
7772 goto done;
7775 error = got_repo_pack_fds_open(&pack_fds);
7776 if (error != NULL)
7777 goto done;
7779 error = got_worktree_open(&worktree, cwd);
7780 if (error) {
7781 if (error->code == GOT_ERR_NOT_WORKTREE)
7782 error = wrap_not_worktree_error(error, "remove", cwd);
7783 goto done;
7786 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7787 NULL, pack_fds);
7788 if (error)
7789 goto done;
7791 error = apply_unveil(got_repo_get_path(repo), 1,
7792 got_worktree_get_root_path(worktree));
7793 if (error)
7794 goto done;
7796 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7797 if (error)
7798 goto done;
7800 if (!can_recurse) {
7801 char *ondisk_path;
7802 struct stat sb;
7803 TAILQ_FOREACH(pe, &paths, entry) {
7804 if (asprintf(&ondisk_path, "%s/%s",
7805 got_worktree_get_root_path(worktree),
7806 pe->path) == -1) {
7807 error = got_error_from_errno("asprintf");
7808 goto done;
7810 if (lstat(ondisk_path, &sb) == -1) {
7811 if (errno == ENOENT) {
7812 free(ondisk_path);
7813 continue;
7815 error = got_error_from_errno2("lstat",
7816 ondisk_path);
7817 free(ondisk_path);
7818 goto done;
7820 free(ondisk_path);
7821 if (S_ISDIR(sb.st_mode)) {
7822 error = got_error_msg(GOT_ERR_BAD_PATH,
7823 "removing directories requires -R option");
7824 goto done;
7829 error = got_worktree_schedule_delete(worktree, &paths,
7830 delete_local_mods, status_codes, print_remove_status, NULL,
7831 repo, keep_on_disk, ignore_missing_paths);
7832 done:
7833 if (repo) {
7834 const struct got_error *close_err = got_repo_close(repo);
7835 if (error == NULL)
7836 error = close_err;
7838 if (worktree)
7839 got_worktree_close(worktree);
7840 if (pack_fds) {
7841 const struct got_error *pack_err =
7842 got_repo_pack_fds_close(pack_fds);
7843 if (error == NULL)
7844 error = pack_err;
7846 TAILQ_FOREACH(pe, &paths, entry)
7847 free((char *)pe->path);
7848 got_pathlist_free(&paths);
7849 free(cwd);
7850 return error;
7853 __dead static void
7854 usage_patch(void)
7856 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7857 "[-R] [patchfile]\n", getprogname());
7858 exit(1);
7861 static const struct got_error *
7862 patch_from_stdin(int *patchfd)
7864 const struct got_error *err = NULL;
7865 ssize_t r;
7866 char *path, buf[BUFSIZ];
7867 sig_t sighup, sigint, sigquit;
7869 err = got_opentemp_named_fd(&path, patchfd,
7870 GOT_TMPDIR_STR "/got-patch");
7871 if (err)
7872 return err;
7873 unlink(path);
7874 free(path);
7876 sighup = signal(SIGHUP, SIG_DFL);
7877 sigint = signal(SIGINT, SIG_DFL);
7878 sigquit = signal(SIGQUIT, SIG_DFL);
7880 for (;;) {
7881 r = read(0, buf, sizeof(buf));
7882 if (r == -1) {
7883 err = got_error_from_errno("read");
7884 break;
7886 if (r == 0)
7887 break;
7888 if (write(*patchfd, buf, r) == -1) {
7889 err = got_error_from_errno("write");
7890 break;
7894 signal(SIGHUP, sighup);
7895 signal(SIGINT, sigint);
7896 signal(SIGQUIT, sigquit);
7898 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7899 err = got_error_from_errno("lseek");
7901 if (err != NULL) {
7902 close(*patchfd);
7903 *patchfd = -1;
7906 return err;
7909 static const struct got_error *
7910 patch_progress(void *arg, const char *old, const char *new,
7911 unsigned char status, const struct got_error *error, int old_from,
7912 int old_lines, int new_from, int new_lines, int offset,
7913 int ws_mangled, const struct got_error *hunk_err)
7915 const char *path = new == NULL ? old : new;
7917 while (*path == '/')
7918 path++;
7920 if (status != 0)
7921 printf("%c %s\n", status, path);
7923 if (error != NULL)
7924 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7926 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7927 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7928 old_lines, new_from, new_lines);
7929 if (hunk_err != NULL)
7930 printf("%s\n", hunk_err->msg);
7931 else if (offset != 0)
7932 printf("applied with offset %d\n", offset);
7933 else
7934 printf("hunk contains mangled whitespace\n");
7937 return NULL;
7940 static const struct got_error *
7941 cmd_patch(int argc, char *argv[])
7943 const struct got_error *error = NULL, *close_error = NULL;
7944 struct got_worktree *worktree = NULL;
7945 struct got_repository *repo = NULL;
7946 const char *errstr;
7947 char *cwd = NULL;
7948 int ch, nop = 0, strip = -1, reverse = 0;
7949 int patchfd;
7950 int *pack_fds = NULL;
7952 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7953 switch (ch) {
7954 case 'n':
7955 nop = 1;
7956 break;
7957 case 'p':
7958 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7959 if (errstr != NULL)
7960 errx(1, "pathname strip count is %s: %s",
7961 errstr, optarg);
7962 break;
7963 case 'R':
7964 reverse = 1;
7965 break;
7966 default:
7967 usage_patch();
7968 /* NOTREACHED */
7972 argc -= optind;
7973 argv += optind;
7975 if (argc == 0) {
7976 error = patch_from_stdin(&patchfd);
7977 if (error)
7978 return error;
7979 } else if (argc == 1) {
7980 patchfd = open(argv[0], O_RDONLY);
7981 if (patchfd == -1) {
7982 error = got_error_from_errno2("open", argv[0]);
7983 return error;
7985 } else
7986 usage_patch();
7988 if ((cwd = getcwd(NULL, 0)) == NULL) {
7989 error = got_error_from_errno("getcwd");
7990 goto done;
7993 error = got_repo_pack_fds_open(&pack_fds);
7994 if (error != NULL)
7995 goto done;
7997 error = got_worktree_open(&worktree, cwd);
7998 if (error != NULL)
7999 goto done;
8001 const char *repo_path = got_worktree_get_repo_path(worktree);
8002 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8003 if (error != NULL)
8004 goto done;
8006 error = apply_unveil(got_repo_get_path(repo), 0,
8007 got_worktree_get_root_path(worktree));
8008 if (error != NULL)
8009 goto done;
8011 #ifndef PROFILE
8012 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
8013 NULL) == -1)
8014 err(1, "pledge");
8015 #endif
8017 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8018 &patch_progress, NULL, check_cancelled, NULL);
8020 done:
8021 if (repo) {
8022 close_error = got_repo_close(repo);
8023 if (error == NULL)
8024 error = close_error;
8026 if (worktree != NULL) {
8027 close_error = got_worktree_close(worktree);
8028 if (error == NULL)
8029 error = close_error;
8031 if (pack_fds) {
8032 const struct got_error *pack_err =
8033 got_repo_pack_fds_close(pack_fds);
8034 if (error == NULL)
8035 error = pack_err;
8037 free(cwd);
8038 return error;
8041 __dead static void
8042 usage_revert(void)
8044 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
8045 "path ...\n", getprogname());
8046 exit(1);
8049 static const struct got_error *
8050 revert_progress(void *arg, unsigned char status, const char *path)
8052 if (status == GOT_STATUS_UNVERSIONED)
8053 return NULL;
8055 while (path[0] == '/')
8056 path++;
8057 printf("%c %s\n", status, path);
8058 return NULL;
8061 struct choose_patch_arg {
8062 FILE *patch_script_file;
8063 const char *action;
8066 static const struct got_error *
8067 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8068 int nchanges, const char *action)
8070 const struct got_error *err;
8071 char *line = NULL;
8072 size_t linesize = 0;
8073 ssize_t linelen;
8075 switch (status) {
8076 case GOT_STATUS_ADD:
8077 printf("A %s\n%s this addition? [y/n] ", path, action);
8078 break;
8079 case GOT_STATUS_DELETE:
8080 printf("D %s\n%s this deletion? [y/n] ", path, action);
8081 break;
8082 case GOT_STATUS_MODIFY:
8083 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8084 return got_error_from_errno("fseek");
8085 printf(GOT_COMMIT_SEP_STR);
8086 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8087 printf("%s", line);
8088 if (linelen == -1 && ferror(patch_file)) {
8089 err = got_error_from_errno("getline");
8090 free(line);
8091 return err;
8093 free(line);
8094 printf(GOT_COMMIT_SEP_STR);
8095 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8096 path, n, nchanges, action);
8097 break;
8098 default:
8099 return got_error_path(path, GOT_ERR_FILE_STATUS);
8102 return NULL;
8105 static const struct got_error *
8106 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8107 FILE *patch_file, int n, int nchanges)
8109 const struct got_error *err = NULL;
8110 char *line = NULL;
8111 size_t linesize = 0;
8112 ssize_t linelen;
8113 int resp = ' ';
8114 struct choose_patch_arg *a = arg;
8116 *choice = GOT_PATCH_CHOICE_NONE;
8118 if (a->patch_script_file) {
8119 char *nl;
8120 err = show_change(status, path, patch_file, n, nchanges,
8121 a->action);
8122 if (err)
8123 return err;
8124 linelen = getline(&line, &linesize, a->patch_script_file);
8125 if (linelen == -1) {
8126 if (ferror(a->patch_script_file))
8127 return got_error_from_errno("getline");
8128 return NULL;
8130 nl = strchr(line, '\n');
8131 if (nl)
8132 *nl = '\0';
8133 if (strcmp(line, "y") == 0) {
8134 *choice = GOT_PATCH_CHOICE_YES;
8135 printf("y\n");
8136 } else if (strcmp(line, "n") == 0) {
8137 *choice = GOT_PATCH_CHOICE_NO;
8138 printf("n\n");
8139 } else if (strcmp(line, "q") == 0 &&
8140 status == GOT_STATUS_MODIFY) {
8141 *choice = GOT_PATCH_CHOICE_QUIT;
8142 printf("q\n");
8143 } else
8144 printf("invalid response '%s'\n", line);
8145 free(line);
8146 return NULL;
8149 while (resp != 'y' && resp != 'n' && resp != 'q') {
8150 err = show_change(status, path, patch_file, n, nchanges,
8151 a->action);
8152 if (err)
8153 return err;
8154 resp = getchar();
8155 if (resp == '\n')
8156 resp = getchar();
8157 if (status == GOT_STATUS_MODIFY) {
8158 if (resp != 'y' && resp != 'n' && resp != 'q') {
8159 printf("invalid response '%c'\n", resp);
8160 resp = ' ';
8162 } else if (resp != 'y' && resp != 'n') {
8163 printf("invalid response '%c'\n", resp);
8164 resp = ' ';
8168 if (resp == 'y')
8169 *choice = GOT_PATCH_CHOICE_YES;
8170 else if (resp == 'n')
8171 *choice = GOT_PATCH_CHOICE_NO;
8172 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8173 *choice = GOT_PATCH_CHOICE_QUIT;
8175 return NULL;
8178 static const struct got_error *
8179 cmd_revert(int argc, char *argv[])
8181 const struct got_error *error = NULL;
8182 struct got_worktree *worktree = NULL;
8183 struct got_repository *repo = NULL;
8184 char *cwd = NULL, *path = NULL;
8185 struct got_pathlist_head paths;
8186 struct got_pathlist_entry *pe;
8187 int ch, can_recurse = 0, pflag = 0;
8188 FILE *patch_script_file = NULL;
8189 const char *patch_script_path = NULL;
8190 struct choose_patch_arg cpa;
8191 int *pack_fds = NULL;
8193 TAILQ_INIT(&paths);
8195 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8196 switch (ch) {
8197 case 'p':
8198 pflag = 1;
8199 break;
8200 case 'F':
8201 patch_script_path = optarg;
8202 break;
8203 case 'R':
8204 can_recurse = 1;
8205 break;
8206 default:
8207 usage_revert();
8208 /* NOTREACHED */
8212 argc -= optind;
8213 argv += optind;
8215 #ifndef PROFILE
8216 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8217 "unveil", NULL) == -1)
8218 err(1, "pledge");
8219 #endif
8220 if (argc < 1)
8221 usage_revert();
8222 if (patch_script_path && !pflag)
8223 errx(1, "-F option can only be used together with -p option");
8225 cwd = getcwd(NULL, 0);
8226 if (cwd == NULL) {
8227 error = got_error_from_errno("getcwd");
8228 goto done;
8231 error = got_repo_pack_fds_open(&pack_fds);
8232 if (error != NULL)
8233 goto done;
8235 error = got_worktree_open(&worktree, cwd);
8236 if (error) {
8237 if (error->code == GOT_ERR_NOT_WORKTREE)
8238 error = wrap_not_worktree_error(error, "revert", cwd);
8239 goto done;
8242 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8243 NULL, pack_fds);
8244 if (error != NULL)
8245 goto done;
8247 if (patch_script_path) {
8248 patch_script_file = fopen(patch_script_path, "re");
8249 if (patch_script_file == NULL) {
8250 error = got_error_from_errno2("fopen",
8251 patch_script_path);
8252 goto done;
8255 error = apply_unveil(got_repo_get_path(repo), 1,
8256 got_worktree_get_root_path(worktree));
8257 if (error)
8258 goto done;
8260 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8261 if (error)
8262 goto done;
8264 if (!can_recurse) {
8265 char *ondisk_path;
8266 struct stat sb;
8267 TAILQ_FOREACH(pe, &paths, entry) {
8268 if (asprintf(&ondisk_path, "%s/%s",
8269 got_worktree_get_root_path(worktree),
8270 pe->path) == -1) {
8271 error = got_error_from_errno("asprintf");
8272 goto done;
8274 if (lstat(ondisk_path, &sb) == -1) {
8275 if (errno == ENOENT) {
8276 free(ondisk_path);
8277 continue;
8279 error = got_error_from_errno2("lstat",
8280 ondisk_path);
8281 free(ondisk_path);
8282 goto done;
8284 free(ondisk_path);
8285 if (S_ISDIR(sb.st_mode)) {
8286 error = got_error_msg(GOT_ERR_BAD_PATH,
8287 "reverting directories requires -R option");
8288 goto done;
8293 cpa.patch_script_file = patch_script_file;
8294 cpa.action = "revert";
8295 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8296 pflag ? choose_patch : NULL, &cpa, repo);
8297 done:
8298 if (patch_script_file && fclose(patch_script_file) == EOF &&
8299 error == NULL)
8300 error = got_error_from_errno2("fclose", patch_script_path);
8301 if (repo) {
8302 const struct got_error *close_err = got_repo_close(repo);
8303 if (error == NULL)
8304 error = close_err;
8306 if (worktree)
8307 got_worktree_close(worktree);
8308 if (pack_fds) {
8309 const struct got_error *pack_err =
8310 got_repo_pack_fds_close(pack_fds);
8311 if (error == NULL)
8312 error = pack_err;
8314 free(path);
8315 free(cwd);
8316 return error;
8319 __dead static void
8320 usage_commit(void)
8322 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8323 "[path ...]\n", getprogname());
8324 exit(1);
8327 struct collect_commit_logmsg_arg {
8328 const char *cmdline_log;
8329 const char *prepared_log;
8330 int non_interactive;
8331 const char *editor;
8332 const char *worktree_path;
8333 const char *branch_name;
8334 const char *repo_path;
8335 char *logmsg_path;
8339 static const struct got_error *
8340 read_prepared_logmsg(char **logmsg, const char *path)
8342 const struct got_error *err = NULL;
8343 FILE *f = NULL;
8344 struct stat sb;
8345 size_t r;
8347 *logmsg = NULL;
8348 memset(&sb, 0, sizeof(sb));
8350 f = fopen(path, "re");
8351 if (f == NULL)
8352 return got_error_from_errno2("fopen", path);
8354 if (fstat(fileno(f), &sb) == -1) {
8355 err = got_error_from_errno2("fstat", path);
8356 goto done;
8358 if (sb.st_size == 0) {
8359 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8360 goto done;
8363 *logmsg = malloc(sb.st_size + 1);
8364 if (*logmsg == NULL) {
8365 err = got_error_from_errno("malloc");
8366 goto done;
8369 r = fread(*logmsg, 1, sb.st_size, f);
8370 if (r != sb.st_size) {
8371 if (ferror(f))
8372 err = got_error_from_errno2("fread", path);
8373 else
8374 err = got_error(GOT_ERR_IO);
8375 goto done;
8377 (*logmsg)[sb.st_size] = '\0';
8378 done:
8379 if (fclose(f) == EOF && err == NULL)
8380 err = got_error_from_errno2("fclose", path);
8381 if (err) {
8382 free(*logmsg);
8383 *logmsg = NULL;
8385 return err;
8389 static const struct got_error *
8390 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8391 void *arg)
8393 char *initial_content = NULL;
8394 struct got_pathlist_entry *pe;
8395 const struct got_error *err = NULL;
8396 char *template = NULL;
8397 struct collect_commit_logmsg_arg *a = arg;
8398 int initial_content_len;
8399 int fd = -1;
8400 size_t len;
8402 /* if a message was specified on the command line, just use it */
8403 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8404 len = strlen(a->cmdline_log) + 1;
8405 *logmsg = malloc(len + 1);
8406 if (*logmsg == NULL)
8407 return got_error_from_errno("malloc");
8408 strlcpy(*logmsg, a->cmdline_log, len);
8409 return NULL;
8410 } else if (a->prepared_log != NULL && a->non_interactive)
8411 return read_prepared_logmsg(logmsg, a->prepared_log);
8413 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8414 return got_error_from_errno("asprintf");
8416 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8417 if (err)
8418 goto done;
8420 if (a->prepared_log) {
8421 char *msg;
8422 err = read_prepared_logmsg(&msg, a->prepared_log);
8423 if (err)
8424 goto done;
8425 if (write(fd, msg, strlen(msg)) == -1) {
8426 err = got_error_from_errno2("write", a->logmsg_path);
8427 free(msg);
8428 goto done;
8430 free(msg);
8433 initial_content_len = asprintf(&initial_content,
8434 "\n# changes to be committed on branch %s:\n",
8435 a->branch_name);
8436 if (initial_content_len == -1) {
8437 err = got_error_from_errno("asprintf");
8438 goto done;
8441 if (write(fd, initial_content, initial_content_len) == -1) {
8442 err = got_error_from_errno2("write", a->logmsg_path);
8443 goto done;
8446 TAILQ_FOREACH(pe, commitable_paths, entry) {
8447 struct got_commitable *ct = pe->data;
8448 dprintf(fd, "# %c %s\n",
8449 got_commitable_get_status(ct),
8450 got_commitable_get_path(ct));
8453 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8454 initial_content_len, a->prepared_log ? 0 : 1);
8455 done:
8456 free(initial_content);
8457 free(template);
8459 if (fd != -1 && close(fd) == -1 && err == NULL)
8460 err = got_error_from_errno2("close", a->logmsg_path);
8462 /* Editor is done; we can now apply unveil(2) */
8463 if (err == NULL)
8464 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8465 if (err) {
8466 free(*logmsg);
8467 *logmsg = NULL;
8469 return err;
8472 static const struct got_error *
8473 cmd_commit(int argc, char *argv[])
8475 const struct got_error *error = NULL;
8476 struct got_worktree *worktree = NULL;
8477 struct got_repository *repo = NULL;
8478 char *cwd = NULL, *id_str = NULL;
8479 struct got_object_id *id = NULL;
8480 const char *logmsg = NULL;
8481 char *prepared_logmsg = NULL;
8482 struct collect_commit_logmsg_arg cl_arg;
8483 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8484 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8485 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8486 struct got_pathlist_head paths;
8487 int *pack_fds = NULL;
8489 TAILQ_INIT(&paths);
8490 cl_arg.logmsg_path = NULL;
8492 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8493 switch (ch) {
8494 case 'F':
8495 if (logmsg != NULL)
8496 option_conflict('F', 'm');
8497 prepared_logmsg = realpath(optarg, NULL);
8498 if (prepared_logmsg == NULL)
8499 return got_error_from_errno2("realpath",
8500 optarg);
8501 break;
8502 case 'm':
8503 if (prepared_logmsg)
8504 option_conflict('m', 'F');
8505 logmsg = optarg;
8506 break;
8507 case 'N':
8508 non_interactive = 1;
8509 break;
8510 case 'S':
8511 allow_bad_symlinks = 1;
8512 break;
8513 default:
8514 usage_commit();
8515 /* NOTREACHED */
8519 argc -= optind;
8520 argv += optind;
8522 #ifndef PROFILE
8523 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8524 "unveil", NULL) == -1)
8525 err(1, "pledge");
8526 #endif
8527 cwd = getcwd(NULL, 0);
8528 if (cwd == NULL) {
8529 error = got_error_from_errno("getcwd");
8530 goto done;
8533 error = got_repo_pack_fds_open(&pack_fds);
8534 if (error != NULL)
8535 goto done;
8537 error = got_worktree_open(&worktree, cwd);
8538 if (error) {
8539 if (error->code == GOT_ERR_NOT_WORKTREE)
8540 error = wrap_not_worktree_error(error, "commit", cwd);
8541 goto done;
8544 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8545 if (error)
8546 goto done;
8547 if (rebase_in_progress) {
8548 error = got_error(GOT_ERR_REBASING);
8549 goto done;
8552 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8553 worktree);
8554 if (error)
8555 goto done;
8557 error = get_gitconfig_path(&gitconfig_path);
8558 if (error)
8559 goto done;
8560 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8561 gitconfig_path, pack_fds);
8562 if (error != NULL)
8563 goto done;
8565 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8566 if (error)
8567 goto done;
8568 if (merge_in_progress) {
8569 error = got_error(GOT_ERR_MERGE_BUSY);
8570 goto done;
8573 error = get_author(&author, repo, worktree);
8574 if (error)
8575 return error;
8578 * unveil(2) traverses exec(2); if an editor is used we have
8579 * to apply unveil after the log message has been written.
8581 if (logmsg == NULL || strlen(logmsg) == 0)
8582 error = get_editor(&editor);
8583 else
8584 error = apply_unveil(got_repo_get_path(repo), 0,
8585 got_worktree_get_root_path(worktree));
8586 if (error)
8587 goto done;
8589 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8590 if (error)
8591 goto done;
8593 cl_arg.editor = editor;
8594 cl_arg.cmdline_log = logmsg;
8595 cl_arg.prepared_log = prepared_logmsg;
8596 cl_arg.non_interactive = non_interactive;
8597 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8598 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8599 if (!histedit_in_progress) {
8600 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8601 error = got_error(GOT_ERR_COMMIT_BRANCH);
8602 goto done;
8604 cl_arg.branch_name += 11;
8606 cl_arg.repo_path = got_repo_get_path(repo);
8607 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8608 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8609 print_status, NULL, repo);
8610 if (error) {
8611 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8612 cl_arg.logmsg_path != NULL)
8613 preserve_logmsg = 1;
8614 goto done;
8617 error = got_object_id_str(&id_str, id);
8618 if (error)
8619 goto done;
8620 printf("Created commit %s\n", id_str);
8621 done:
8622 if (preserve_logmsg) {
8623 fprintf(stderr, "%s: log message preserved in %s\n",
8624 getprogname(), cl_arg.logmsg_path);
8625 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8626 error == NULL)
8627 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8628 free(cl_arg.logmsg_path);
8629 if (repo) {
8630 const struct got_error *close_err = got_repo_close(repo);
8631 if (error == NULL)
8632 error = close_err;
8634 if (worktree)
8635 got_worktree_close(worktree);
8636 if (pack_fds) {
8637 const struct got_error *pack_err =
8638 got_repo_pack_fds_close(pack_fds);
8639 if (error == NULL)
8640 error = pack_err;
8642 free(cwd);
8643 free(id_str);
8644 free(gitconfig_path);
8645 free(editor);
8646 free(author);
8647 free(prepared_logmsg);
8648 return error;
8651 __dead static void
8652 usage_send(void)
8654 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8655 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8656 "[remote-repository]\n", getprogname());
8657 exit(1);
8660 static void
8661 print_load_info(int print_colored, int print_found, int print_trees,
8662 int ncolored, int nfound, int ntrees)
8664 if (print_colored) {
8665 printf("%d commit%s colored", ncolored,
8666 ncolored == 1 ? "" : "s");
8668 if (print_found) {
8669 printf("%s%d object%s found",
8670 ncolored > 0 ? "; " : "",
8671 nfound, nfound == 1 ? "" : "s");
8673 if (print_trees) {
8674 printf("; %d tree%s scanned", ntrees,
8675 ntrees == 1 ? "" : "s");
8679 struct got_send_progress_arg {
8680 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8681 int verbosity;
8682 int last_ncolored;
8683 int last_nfound;
8684 int last_ntrees;
8685 int loading_done;
8686 int last_ncommits;
8687 int last_nobj_total;
8688 int last_p_deltify;
8689 int last_p_written;
8690 int last_p_sent;
8691 int printed_something;
8692 int sent_something;
8693 struct got_pathlist_head *delete_branches;
8696 static const struct got_error *
8697 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8698 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8699 int nobj_written, off_t bytes_sent, const char *refname, int success)
8701 struct got_send_progress_arg *a = arg;
8702 char scaled_packsize[FMT_SCALED_STRSIZE];
8703 char scaled_sent[FMT_SCALED_STRSIZE];
8704 int p_deltify = 0, p_written = 0, p_sent = 0;
8705 int print_colored = 0, print_found = 0, print_trees = 0;
8706 int print_searching = 0, print_total = 0;
8707 int print_deltify = 0, print_written = 0, print_sent = 0;
8709 if (a->verbosity < 0)
8710 return NULL;
8712 if (refname) {
8713 const char *status = success ? "accepted" : "rejected";
8715 if (success) {
8716 struct got_pathlist_entry *pe;
8717 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8718 const char *branchname = pe->path;
8719 if (got_path_cmp(branchname, refname,
8720 strlen(branchname), strlen(refname)) == 0) {
8721 status = "deleted";
8722 a->sent_something = 1;
8723 break;
8728 if (a->printed_something)
8729 putchar('\n');
8730 printf("Server has %s %s", status, refname);
8731 a->printed_something = 1;
8732 return NULL;
8735 if (a->last_ncolored != ncolored) {
8736 print_colored = 1;
8737 a->last_ncolored = ncolored;
8740 if (a->last_nfound != nfound) {
8741 print_colored = 1;
8742 print_found = 1;
8743 a->last_nfound = nfound;
8746 if (a->last_ntrees != ntrees) {
8747 print_colored = 1;
8748 print_found = 1;
8749 print_trees = 1;
8750 a->last_ntrees = ntrees;
8753 if ((print_colored || print_found || print_trees) &&
8754 !a->loading_done) {
8755 printf("\r");
8756 print_load_info(print_colored, print_found, print_trees,
8757 ncolored, nfound, ntrees);
8758 a->printed_something = 1;
8759 fflush(stdout);
8760 return NULL;
8761 } else if (!a->loading_done) {
8762 printf("\r");
8763 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8764 printf("\n");
8765 a->loading_done = 1;
8768 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8769 return got_error_from_errno("fmt_scaled");
8770 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8771 return got_error_from_errno("fmt_scaled");
8773 if (a->last_ncommits != ncommits) {
8774 print_searching = 1;
8775 a->last_ncommits = ncommits;
8778 if (a->last_nobj_total != nobj_total) {
8779 print_searching = 1;
8780 print_total = 1;
8781 a->last_nobj_total = nobj_total;
8784 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8785 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8786 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8787 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8788 return got_error(GOT_ERR_NO_SPACE);
8791 if (nobj_deltify > 0 || nobj_written > 0) {
8792 if (nobj_deltify > 0) {
8793 p_deltify = (nobj_deltify * 100) / nobj_total;
8794 if (p_deltify != a->last_p_deltify) {
8795 a->last_p_deltify = p_deltify;
8796 print_searching = 1;
8797 print_total = 1;
8798 print_deltify = 1;
8801 if (nobj_written > 0) {
8802 p_written = (nobj_written * 100) / nobj_total;
8803 if (p_written != a->last_p_written) {
8804 a->last_p_written = p_written;
8805 print_searching = 1;
8806 print_total = 1;
8807 print_deltify = 1;
8808 print_written = 1;
8813 if (bytes_sent > 0) {
8814 p_sent = (bytes_sent * 100) / packfile_size;
8815 if (p_sent != a->last_p_sent) {
8816 a->last_p_sent = p_sent;
8817 print_searching = 1;
8818 print_total = 1;
8819 print_deltify = 1;
8820 print_written = 1;
8821 print_sent = 1;
8823 a->sent_something = 1;
8826 if (print_searching || print_total || print_deltify || print_written ||
8827 print_sent)
8828 printf("\r");
8829 if (print_searching)
8830 printf("packing %d reference%s", ncommits,
8831 ncommits == 1 ? "" : "s");
8832 if (print_total)
8833 printf("; %d object%s", nobj_total,
8834 nobj_total == 1 ? "" : "s");
8835 if (print_deltify)
8836 printf("; deltify: %d%%", p_deltify);
8837 if (print_sent)
8838 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8839 scaled_packsize, p_sent);
8840 else if (print_written)
8841 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8842 scaled_packsize, p_written);
8843 if (print_searching || print_total || print_deltify ||
8844 print_written || print_sent) {
8845 a->printed_something = 1;
8846 fflush(stdout);
8848 return NULL;
8851 static const struct got_error *
8852 cmd_send(int argc, char *argv[])
8854 const struct got_error *error = NULL;
8855 char *cwd = NULL, *repo_path = NULL;
8856 const char *remote_name;
8857 char *proto = NULL, *host = NULL, *port = NULL;
8858 char *repo_name = NULL, *server_path = NULL;
8859 const struct got_remote_repo *remotes, *remote = NULL;
8860 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8861 struct got_repository *repo = NULL;
8862 struct got_worktree *worktree = NULL;
8863 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8864 struct got_pathlist_head branches;
8865 struct got_pathlist_head tags;
8866 struct got_reflist_head all_branches;
8867 struct got_reflist_head all_tags;
8868 struct got_pathlist_head delete_args;
8869 struct got_pathlist_head delete_branches;
8870 struct got_reflist_entry *re;
8871 struct got_pathlist_entry *pe;
8872 int i, ch, sendfd = -1, sendstatus;
8873 pid_t sendpid = -1;
8874 struct got_send_progress_arg spa;
8875 int verbosity = 0, overwrite_refs = 0;
8876 int send_all_branches = 0, send_all_tags = 0;
8877 struct got_reference *ref = NULL;
8878 int *pack_fds = NULL;
8880 TAILQ_INIT(&branches);
8881 TAILQ_INIT(&tags);
8882 TAILQ_INIT(&all_branches);
8883 TAILQ_INIT(&all_tags);
8884 TAILQ_INIT(&delete_args);
8885 TAILQ_INIT(&delete_branches);
8887 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8888 switch (ch) {
8889 case 'a':
8890 send_all_branches = 1;
8891 break;
8892 case 'b':
8893 error = got_pathlist_append(&branches, optarg, NULL);
8894 if (error)
8895 return error;
8896 nbranches++;
8897 break;
8898 case 'd':
8899 error = got_pathlist_append(&delete_args, optarg, NULL);
8900 if (error)
8901 return error;
8902 break;
8903 case 'f':
8904 overwrite_refs = 1;
8905 break;
8906 case 'r':
8907 repo_path = realpath(optarg, NULL);
8908 if (repo_path == NULL)
8909 return got_error_from_errno2("realpath",
8910 optarg);
8911 got_path_strip_trailing_slashes(repo_path);
8912 break;
8913 case 't':
8914 error = got_pathlist_append(&tags, optarg, NULL);
8915 if (error)
8916 return error;
8917 ntags++;
8918 break;
8919 case 'T':
8920 send_all_tags = 1;
8921 break;
8922 case 'v':
8923 if (verbosity < 0)
8924 verbosity = 0;
8925 else if (verbosity < 3)
8926 verbosity++;
8927 break;
8928 case 'q':
8929 verbosity = -1;
8930 break;
8931 default:
8932 usage_send();
8933 /* NOTREACHED */
8936 argc -= optind;
8937 argv += optind;
8939 if (send_all_branches && !TAILQ_EMPTY(&branches))
8940 option_conflict('a', 'b');
8941 if (send_all_tags && !TAILQ_EMPTY(&tags))
8942 option_conflict('T', 't');
8945 if (argc == 0)
8946 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8947 else if (argc == 1)
8948 remote_name = argv[0];
8949 else
8950 usage_send();
8952 cwd = getcwd(NULL, 0);
8953 if (cwd == NULL) {
8954 error = got_error_from_errno("getcwd");
8955 goto done;
8958 error = got_repo_pack_fds_open(&pack_fds);
8959 if (error != NULL)
8960 goto done;
8962 if (repo_path == NULL) {
8963 error = got_worktree_open(&worktree, cwd);
8964 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8965 goto done;
8966 else
8967 error = NULL;
8968 if (worktree) {
8969 repo_path =
8970 strdup(got_worktree_get_repo_path(worktree));
8971 if (repo_path == NULL)
8972 error = got_error_from_errno("strdup");
8973 if (error)
8974 goto done;
8975 } else {
8976 repo_path = strdup(cwd);
8977 if (repo_path == NULL) {
8978 error = got_error_from_errno("strdup");
8979 goto done;
8984 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8985 if (error)
8986 goto done;
8988 if (worktree) {
8989 worktree_conf = got_worktree_get_gotconfig(worktree);
8990 if (worktree_conf) {
8991 got_gotconfig_get_remotes(&nremotes, &remotes,
8992 worktree_conf);
8993 for (i = 0; i < nremotes; i++) {
8994 if (strcmp(remotes[i].name, remote_name) == 0) {
8995 remote = &remotes[i];
8996 break;
9001 if (remote == NULL) {
9002 repo_conf = got_repo_get_gotconfig(repo);
9003 if (repo_conf) {
9004 got_gotconfig_get_remotes(&nremotes, &remotes,
9005 repo_conf);
9006 for (i = 0; i < nremotes; i++) {
9007 if (strcmp(remotes[i].name, remote_name) == 0) {
9008 remote = &remotes[i];
9009 break;
9014 if (remote == NULL) {
9015 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9016 for (i = 0; i < nremotes; i++) {
9017 if (strcmp(remotes[i].name, remote_name) == 0) {
9018 remote = &remotes[i];
9019 break;
9023 if (remote == NULL) {
9024 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9025 goto done;
9028 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9029 &repo_name, remote->send_url);
9030 if (error)
9031 goto done;
9033 if (strcmp(proto, "git") == 0) {
9034 #ifndef PROFILE
9035 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9036 "sendfd dns inet unveil", NULL) == -1)
9037 err(1, "pledge");
9038 #endif
9039 } else if (strcmp(proto, "git+ssh") == 0 ||
9040 strcmp(proto, "ssh") == 0) {
9041 #ifndef PROFILE
9042 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9043 "sendfd unveil", NULL) == -1)
9044 err(1, "pledge");
9045 #endif
9046 } else if (strcmp(proto, "http") == 0 ||
9047 strcmp(proto, "git+http") == 0) {
9048 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9049 goto done;
9050 } else {
9051 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9052 goto done;
9055 error = got_dial_apply_unveil(proto);
9056 if (error)
9057 goto done;
9059 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9060 if (error)
9061 goto done;
9063 if (send_all_branches) {
9064 error = got_ref_list(&all_branches, repo, "refs/heads",
9065 got_ref_cmp_by_name, NULL);
9066 if (error)
9067 goto done;
9068 TAILQ_FOREACH(re, &all_branches, entry) {
9069 const char *branchname = got_ref_get_name(re->ref);
9070 error = got_pathlist_append(&branches,
9071 branchname, NULL);
9072 if (error)
9073 goto done;
9074 nbranches++;
9076 } else if (nbranches == 0) {
9077 for (i = 0; i < remote->nsend_branches; i++) {
9078 got_pathlist_append(&branches,
9079 remote->send_branches[i], NULL);
9083 if (send_all_tags) {
9084 error = got_ref_list(&all_tags, repo, "refs/tags",
9085 got_ref_cmp_by_name, NULL);
9086 if (error)
9087 goto done;
9088 TAILQ_FOREACH(re, &all_tags, entry) {
9089 const char *tagname = got_ref_get_name(re->ref);
9090 error = got_pathlist_append(&tags,
9091 tagname, NULL);
9092 if (error)
9093 goto done;
9094 ntags++;
9099 * To prevent accidents only branches in refs/heads/ can be deleted
9100 * with 'got send -d'.
9101 * Deleting anything else requires local repository access or Git.
9103 TAILQ_FOREACH(pe, &delete_args, entry) {
9104 const char *branchname = pe->path;
9105 char *s;
9106 struct got_pathlist_entry *new;
9107 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9108 s = strdup(branchname);
9109 if (s == NULL) {
9110 error = got_error_from_errno("strdup");
9111 goto done;
9113 } else {
9114 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9115 error = got_error_from_errno("asprintf");
9116 goto done;
9119 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9120 if (error || new == NULL /* duplicate */)
9121 free(s);
9122 if (error)
9123 goto done;
9124 ndelete_branches++;
9127 if (nbranches == 0 && ndelete_branches == 0) {
9128 struct got_reference *head_ref;
9129 if (worktree)
9130 error = got_ref_open(&head_ref, repo,
9131 got_worktree_get_head_ref_name(worktree), 0);
9132 else
9133 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9134 if (error)
9135 goto done;
9136 if (got_ref_is_symbolic(head_ref)) {
9137 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9138 got_ref_close(head_ref);
9139 if (error)
9140 goto done;
9141 } else
9142 ref = head_ref;
9143 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9144 NULL);
9145 if (error)
9146 goto done;
9147 nbranches++;
9150 if (verbosity >= 0)
9151 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9152 port ? ":" : "", port ? port : "");
9154 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9155 server_path, verbosity);
9156 if (error)
9157 goto done;
9159 memset(&spa, 0, sizeof(spa));
9160 spa.last_scaled_packsize[0] = '\0';
9161 spa.last_p_deltify = -1;
9162 spa.last_p_written = -1;
9163 spa.verbosity = verbosity;
9164 spa.delete_branches = &delete_branches;
9165 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9166 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9167 check_cancelled, NULL);
9168 if (spa.printed_something)
9169 putchar('\n');
9170 if (error)
9171 goto done;
9172 if (!spa.sent_something && verbosity >= 0)
9173 printf("Already up-to-date\n");
9174 done:
9175 if (sendpid > 0) {
9176 if (kill(sendpid, SIGTERM) == -1)
9177 error = got_error_from_errno("kill");
9178 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9179 error = got_error_from_errno("waitpid");
9181 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9182 error = got_error_from_errno("close");
9183 if (repo) {
9184 const struct got_error *close_err = got_repo_close(repo);
9185 if (error == NULL)
9186 error = close_err;
9188 if (worktree)
9189 got_worktree_close(worktree);
9190 if (pack_fds) {
9191 const struct got_error *pack_err =
9192 got_repo_pack_fds_close(pack_fds);
9193 if (error == NULL)
9194 error = pack_err;
9196 if (ref)
9197 got_ref_close(ref);
9198 got_pathlist_free(&branches);
9199 got_pathlist_free(&tags);
9200 got_ref_list_free(&all_branches);
9201 got_ref_list_free(&all_tags);
9202 got_pathlist_free(&delete_args);
9203 TAILQ_FOREACH(pe, &delete_branches, entry)
9204 free((char *)pe->path);
9205 got_pathlist_free(&delete_branches);
9206 free(cwd);
9207 free(repo_path);
9208 free(proto);
9209 free(host);
9210 free(port);
9211 free(server_path);
9212 free(repo_name);
9213 return error;
9216 __dead static void
9217 usage_cherrypick(void)
9219 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9220 exit(1);
9223 static const struct got_error *
9224 cmd_cherrypick(int argc, char *argv[])
9226 const struct got_error *error = NULL;
9227 struct got_worktree *worktree = NULL;
9228 struct got_repository *repo = NULL;
9229 char *cwd = NULL, *commit_id_str = NULL;
9230 struct got_object_id *commit_id = NULL;
9231 struct got_commit_object *commit = NULL;
9232 struct got_object_qid *pid;
9233 int ch;
9234 struct got_update_progress_arg upa;
9235 int *pack_fds = NULL;
9237 while ((ch = getopt(argc, argv, "")) != -1) {
9238 switch (ch) {
9239 default:
9240 usage_cherrypick();
9241 /* NOTREACHED */
9245 argc -= optind;
9246 argv += optind;
9248 #ifndef PROFILE
9249 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9250 "unveil", NULL) == -1)
9251 err(1, "pledge");
9252 #endif
9253 if (argc != 1)
9254 usage_cherrypick();
9256 cwd = getcwd(NULL, 0);
9257 if (cwd == NULL) {
9258 error = got_error_from_errno("getcwd");
9259 goto done;
9262 error = got_repo_pack_fds_open(&pack_fds);
9263 if (error != NULL)
9264 goto done;
9266 error = got_worktree_open(&worktree, cwd);
9267 if (error) {
9268 if (error->code == GOT_ERR_NOT_WORKTREE)
9269 error = wrap_not_worktree_error(error, "cherrypick",
9270 cwd);
9271 goto done;
9274 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9275 NULL, pack_fds);
9276 if (error != NULL)
9277 goto done;
9279 error = apply_unveil(got_repo_get_path(repo), 0,
9280 got_worktree_get_root_path(worktree));
9281 if (error)
9282 goto done;
9284 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9285 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9286 if (error)
9287 goto done;
9288 error = got_object_id_str(&commit_id_str, commit_id);
9289 if (error)
9290 goto done;
9292 error = got_object_open_as_commit(&commit, repo, commit_id);
9293 if (error)
9294 goto done;
9295 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9296 memset(&upa, 0, sizeof(upa));
9297 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9298 commit_id, repo, update_progress, &upa, check_cancelled,
9299 NULL);
9300 if (error != NULL)
9301 goto done;
9303 if (upa.did_something)
9304 printf("Merged commit %s\n", commit_id_str);
9305 print_merge_progress_stats(&upa);
9306 done:
9307 if (commit)
9308 got_object_commit_close(commit);
9309 free(commit_id_str);
9310 if (worktree)
9311 got_worktree_close(worktree);
9312 if (repo) {
9313 const struct got_error *close_err = got_repo_close(repo);
9314 if (error == NULL)
9315 error = close_err;
9317 if (pack_fds) {
9318 const struct got_error *pack_err =
9319 got_repo_pack_fds_close(pack_fds);
9320 if (error == NULL)
9321 error = pack_err;
9324 return error;
9327 __dead static void
9328 usage_backout(void)
9330 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9331 exit(1);
9334 static const struct got_error *
9335 cmd_backout(int argc, char *argv[])
9337 const struct got_error *error = NULL;
9338 struct got_worktree *worktree = NULL;
9339 struct got_repository *repo = NULL;
9340 char *cwd = NULL, *commit_id_str = NULL;
9341 struct got_object_id *commit_id = NULL;
9342 struct got_commit_object *commit = NULL;
9343 struct got_object_qid *pid;
9344 int ch;
9345 struct got_update_progress_arg upa;
9346 int *pack_fds = NULL;
9348 while ((ch = getopt(argc, argv, "")) != -1) {
9349 switch (ch) {
9350 default:
9351 usage_backout();
9352 /* NOTREACHED */
9356 argc -= optind;
9357 argv += optind;
9359 #ifndef PROFILE
9360 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9361 "unveil", NULL) == -1)
9362 err(1, "pledge");
9363 #endif
9364 if (argc != 1)
9365 usage_backout();
9367 cwd = getcwd(NULL, 0);
9368 if (cwd == NULL) {
9369 error = got_error_from_errno("getcwd");
9370 goto done;
9373 error = got_repo_pack_fds_open(&pack_fds);
9374 if (error != NULL)
9375 goto done;
9377 error = got_worktree_open(&worktree, cwd);
9378 if (error) {
9379 if (error->code == GOT_ERR_NOT_WORKTREE)
9380 error = wrap_not_worktree_error(error, "backout", cwd);
9381 goto done;
9384 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9385 NULL, pack_fds);
9386 if (error != NULL)
9387 goto done;
9389 error = apply_unveil(got_repo_get_path(repo), 0,
9390 got_worktree_get_root_path(worktree));
9391 if (error)
9392 goto done;
9394 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9395 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9396 if (error)
9397 goto done;
9398 error = got_object_id_str(&commit_id_str, commit_id);
9399 if (error)
9400 goto done;
9402 error = got_object_open_as_commit(&commit, repo, commit_id);
9403 if (error)
9404 goto done;
9405 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9406 if (pid == NULL) {
9407 error = got_error(GOT_ERR_ROOT_COMMIT);
9408 goto done;
9411 memset(&upa, 0, sizeof(upa));
9412 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9413 repo, update_progress, &upa, check_cancelled, NULL);
9414 if (error != NULL)
9415 goto done;
9417 if (upa.did_something)
9418 printf("Backed out commit %s\n", commit_id_str);
9419 print_merge_progress_stats(&upa);
9420 done:
9421 if (commit)
9422 got_object_commit_close(commit);
9423 free(commit_id_str);
9424 if (worktree)
9425 got_worktree_close(worktree);
9426 if (repo) {
9427 const struct got_error *close_err = got_repo_close(repo);
9428 if (error == NULL)
9429 error = close_err;
9431 if (pack_fds) {
9432 const struct got_error *pack_err =
9433 got_repo_pack_fds_close(pack_fds);
9434 if (error == NULL)
9435 error = pack_err;
9437 return error;
9440 __dead static void
9441 usage_rebase(void)
9443 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9444 getprogname());
9445 exit(1);
9448 static void
9449 trim_logmsg(char *logmsg, int limit)
9451 char *nl;
9452 size_t len;
9454 len = strlen(logmsg);
9455 if (len > limit)
9456 len = limit;
9457 logmsg[len] = '\0';
9458 nl = strchr(logmsg, '\n');
9459 if (nl)
9460 *nl = '\0';
9463 static const struct got_error *
9464 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9466 const struct got_error *err;
9467 char *logmsg0 = NULL;
9468 const char *s;
9470 err = got_object_commit_get_logmsg(&logmsg0, commit);
9471 if (err)
9472 return err;
9474 s = logmsg0;
9475 while (isspace((unsigned char)s[0]))
9476 s++;
9478 *logmsg = strdup(s);
9479 if (*logmsg == NULL) {
9480 err = got_error_from_errno("strdup");
9481 goto done;
9484 trim_logmsg(*logmsg, limit);
9485 done:
9486 free(logmsg0);
9487 return err;
9490 static const struct got_error *
9491 show_rebase_merge_conflict(struct got_object_id *id,
9492 struct got_repository *repo)
9494 const struct got_error *err;
9495 struct got_commit_object *commit = NULL;
9496 char *id_str = NULL, *logmsg = NULL;
9498 err = got_object_open_as_commit(&commit, repo, id);
9499 if (err)
9500 return err;
9502 err = got_object_id_str(&id_str, id);
9503 if (err)
9504 goto done;
9506 id_str[12] = '\0';
9508 err = get_short_logmsg(&logmsg, 42, commit);
9509 if (err)
9510 goto done;
9512 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9513 done:
9514 free(id_str);
9515 got_object_commit_close(commit);
9516 free(logmsg);
9517 return err;
9520 static const struct got_error *
9521 show_rebase_progress(struct got_commit_object *commit,
9522 struct got_object_id *old_id, struct got_object_id *new_id)
9524 const struct got_error *err;
9525 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9527 err = got_object_id_str(&old_id_str, old_id);
9528 if (err)
9529 goto done;
9531 if (new_id) {
9532 err = got_object_id_str(&new_id_str, new_id);
9533 if (err)
9534 goto done;
9537 old_id_str[12] = '\0';
9538 if (new_id_str)
9539 new_id_str[12] = '\0';
9541 err = get_short_logmsg(&logmsg, 42, commit);
9542 if (err)
9543 goto done;
9545 printf("%s -> %s: %s\n", old_id_str,
9546 new_id_str ? new_id_str : "no-op change", logmsg);
9547 done:
9548 free(old_id_str);
9549 free(new_id_str);
9550 free(logmsg);
9551 return err;
9554 static const struct got_error *
9555 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9556 struct got_reference *branch, struct got_reference *new_base_branch,
9557 struct got_reference *tmp_branch, struct got_repository *repo,
9558 int create_backup)
9560 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9561 return got_worktree_rebase_complete(worktree, fileindex,
9562 new_base_branch, tmp_branch, branch, repo, create_backup);
9565 static const struct got_error *
9566 rebase_commit(struct got_pathlist_head *merged_paths,
9567 struct got_worktree *worktree, struct got_fileindex *fileindex,
9568 struct got_reference *tmp_branch,
9569 struct got_object_id *commit_id, struct got_repository *repo)
9571 const struct got_error *error;
9572 struct got_commit_object *commit;
9573 struct got_object_id *new_commit_id;
9575 error = got_object_open_as_commit(&commit, repo, commit_id);
9576 if (error)
9577 return error;
9579 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9580 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9581 if (error) {
9582 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9583 goto done;
9584 error = show_rebase_progress(commit, commit_id, NULL);
9585 } else {
9586 error = show_rebase_progress(commit, commit_id, new_commit_id);
9587 free(new_commit_id);
9589 done:
9590 got_object_commit_close(commit);
9591 return error;
9594 struct check_path_prefix_arg {
9595 const char *path_prefix;
9596 size_t len;
9597 int errcode;
9600 static const struct got_error *
9601 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9602 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9603 struct got_object_id *id1, struct got_object_id *id2,
9604 const char *path1, const char *path2,
9605 mode_t mode1, mode_t mode2, struct got_repository *repo)
9607 struct check_path_prefix_arg *a = arg;
9609 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9610 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9611 return got_error(a->errcode);
9613 return NULL;
9616 static const struct got_error *
9617 check_path_prefix(struct got_object_id *parent_id,
9618 struct got_object_id *commit_id, const char *path_prefix,
9619 int errcode, struct got_repository *repo)
9621 const struct got_error *err;
9622 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9623 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9624 struct check_path_prefix_arg cpp_arg;
9626 if (got_path_is_root_dir(path_prefix))
9627 return NULL;
9629 err = got_object_open_as_commit(&commit, repo, commit_id);
9630 if (err)
9631 goto done;
9633 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9634 if (err)
9635 goto done;
9637 err = got_object_open_as_tree(&tree1, repo,
9638 got_object_commit_get_tree_id(parent_commit));
9639 if (err)
9640 goto done;
9642 err = got_object_open_as_tree(&tree2, repo,
9643 got_object_commit_get_tree_id(commit));
9644 if (err)
9645 goto done;
9647 cpp_arg.path_prefix = path_prefix;
9648 while (cpp_arg.path_prefix[0] == '/')
9649 cpp_arg.path_prefix++;
9650 cpp_arg.len = strlen(cpp_arg.path_prefix);
9651 cpp_arg.errcode = errcode;
9652 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9653 check_path_prefix_in_diff, &cpp_arg, 0);
9654 done:
9655 if (tree1)
9656 got_object_tree_close(tree1);
9657 if (tree2)
9658 got_object_tree_close(tree2);
9659 if (commit)
9660 got_object_commit_close(commit);
9661 if (parent_commit)
9662 got_object_commit_close(parent_commit);
9663 return err;
9666 static const struct got_error *
9667 collect_commits(struct got_object_id_queue *commits,
9668 struct got_object_id *initial_commit_id,
9669 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9670 const char *path_prefix, int path_prefix_errcode,
9671 struct got_repository *repo)
9673 const struct got_error *err = NULL;
9674 struct got_commit_graph *graph = NULL;
9675 struct got_object_id *parent_id = NULL;
9676 struct got_object_qid *qid;
9677 struct got_object_id *commit_id = initial_commit_id;
9679 err = got_commit_graph_open(&graph, "/", 1);
9680 if (err)
9681 return err;
9683 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9684 check_cancelled, NULL);
9685 if (err)
9686 goto done;
9687 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9688 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9689 check_cancelled, NULL);
9690 if (err) {
9691 if (err->code == GOT_ERR_ITER_COMPLETED) {
9692 err = got_error_msg(GOT_ERR_ANCESTRY,
9693 "ran out of commits to rebase before "
9694 "youngest common ancestor commit has "
9695 "been reached?!?");
9697 goto done;
9698 } else {
9699 err = check_path_prefix(parent_id, commit_id,
9700 path_prefix, path_prefix_errcode, repo);
9701 if (err)
9702 goto done;
9704 err = got_object_qid_alloc(&qid, commit_id);
9705 if (err)
9706 goto done;
9707 STAILQ_INSERT_HEAD(commits, qid, entry);
9708 commit_id = parent_id;
9711 done:
9712 got_commit_graph_close(graph);
9713 return err;
9716 static const struct got_error *
9717 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9719 const struct got_error *err = NULL;
9720 time_t committer_time;
9721 struct tm tm;
9722 char datebuf[11]; /* YYYY-MM-DD + NUL */
9723 char *author0 = NULL, *author, *smallerthan;
9724 char *logmsg0 = NULL, *logmsg, *newline;
9726 committer_time = got_object_commit_get_committer_time(commit);
9727 if (gmtime_r(&committer_time, &tm) == NULL)
9728 return got_error_from_errno("gmtime_r");
9729 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9730 return got_error(GOT_ERR_NO_SPACE);
9732 author0 = strdup(got_object_commit_get_author(commit));
9733 if (author0 == NULL)
9734 return got_error_from_errno("strdup");
9735 author = author0;
9736 smallerthan = strchr(author, '<');
9737 if (smallerthan && smallerthan[1] != '\0')
9738 author = smallerthan + 1;
9739 author[strcspn(author, "@>")] = '\0';
9741 err = got_object_commit_get_logmsg(&logmsg0, commit);
9742 if (err)
9743 goto done;
9744 logmsg = logmsg0;
9745 while (*logmsg == '\n')
9746 logmsg++;
9747 newline = strchr(logmsg, '\n');
9748 if (newline)
9749 *newline = '\0';
9751 if (asprintf(brief_str, "%s %s %s",
9752 datebuf, author, logmsg) == -1)
9753 err = got_error_from_errno("asprintf");
9754 done:
9755 free(author0);
9756 free(logmsg0);
9757 return err;
9760 static const struct got_error *
9761 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9762 struct got_repository *repo)
9764 const struct got_error *err;
9765 char *id_str;
9767 err = got_object_id_str(&id_str, id);
9768 if (err)
9769 return err;
9771 err = got_ref_delete(ref, repo);
9772 if (err)
9773 goto done;
9775 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9776 done:
9777 free(id_str);
9778 return err;
9781 static const struct got_error *
9782 print_backup_ref(const char *branch_name, const char *new_id_str,
9783 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9784 struct got_reflist_object_id_map *refs_idmap,
9785 struct got_repository *repo)
9787 const struct got_error *err = NULL;
9788 struct got_reflist_head *refs;
9789 char *refs_str = NULL;
9790 struct got_object_id *new_commit_id = NULL;
9791 struct got_commit_object *new_commit = NULL;
9792 char *new_commit_brief_str = NULL;
9793 struct got_object_id *yca_id = NULL;
9794 struct got_commit_object *yca_commit = NULL;
9795 char *yca_id_str = NULL, *yca_brief_str = NULL;
9796 char *custom_refs_str;
9798 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9799 return got_error_from_errno("asprintf");
9801 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9802 0, 0, refs_idmap, custom_refs_str);
9803 if (err)
9804 goto done;
9806 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9807 if (err)
9808 goto done;
9810 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9811 if (refs) {
9812 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9813 if (err)
9814 goto done;
9817 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9818 if (err)
9819 goto done;
9821 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9822 if (err)
9823 goto done;
9825 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9826 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9827 if (err)
9828 goto done;
9830 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9831 refs_str ? " (" : "", refs_str ? refs_str : "",
9832 refs_str ? ")" : "", new_commit_brief_str);
9833 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9834 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9835 free(refs_str);
9836 refs_str = NULL;
9838 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9839 if (err)
9840 goto done;
9842 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9843 if (err)
9844 goto done;
9846 err = got_object_id_str(&yca_id_str, yca_id);
9847 if (err)
9848 goto done;
9850 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9851 if (refs) {
9852 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9853 if (err)
9854 goto done;
9856 printf("history forked at %s%s%s%s\n %s\n",
9857 yca_id_str,
9858 refs_str ? " (" : "", refs_str ? refs_str : "",
9859 refs_str ? ")" : "", yca_brief_str);
9861 done:
9862 free(custom_refs_str);
9863 free(new_commit_id);
9864 free(refs_str);
9865 free(yca_id);
9866 free(yca_id_str);
9867 free(yca_brief_str);
9868 if (new_commit)
9869 got_object_commit_close(new_commit);
9870 if (yca_commit)
9871 got_object_commit_close(yca_commit);
9873 return NULL;
9876 static const struct got_error *
9877 process_backup_refs(const char *backup_ref_prefix,
9878 const char *wanted_branch_name,
9879 int delete, struct got_repository *repo)
9881 const struct got_error *err;
9882 struct got_reflist_head refs, backup_refs;
9883 struct got_reflist_entry *re;
9884 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9885 struct got_object_id *old_commit_id = NULL;
9886 char *branch_name = NULL;
9887 struct got_commit_object *old_commit = NULL;
9888 struct got_reflist_object_id_map *refs_idmap = NULL;
9889 int wanted_branch_found = 0;
9891 TAILQ_INIT(&refs);
9892 TAILQ_INIT(&backup_refs);
9894 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9895 if (err)
9896 return err;
9898 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9899 if (err)
9900 goto done;
9902 if (wanted_branch_name) {
9903 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9904 wanted_branch_name += 11;
9907 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9908 got_ref_cmp_by_commit_timestamp_descending, repo);
9909 if (err)
9910 goto done;
9912 TAILQ_FOREACH(re, &backup_refs, entry) {
9913 const char *refname = got_ref_get_name(re->ref);
9914 char *slash;
9916 err = check_cancelled(NULL);
9917 if (err)
9918 break;
9920 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9921 if (err)
9922 break;
9924 err = got_object_open_as_commit(&old_commit, repo,
9925 old_commit_id);
9926 if (err)
9927 break;
9929 if (strncmp(backup_ref_prefix, refname,
9930 backup_ref_prefix_len) == 0)
9931 refname += backup_ref_prefix_len;
9933 while (refname[0] == '/')
9934 refname++;
9936 branch_name = strdup(refname);
9937 if (branch_name == NULL) {
9938 err = got_error_from_errno("strdup");
9939 break;
9941 slash = strrchr(branch_name, '/');
9942 if (slash) {
9943 *slash = '\0';
9944 refname += strlen(branch_name) + 1;
9947 if (wanted_branch_name == NULL ||
9948 strcmp(wanted_branch_name, branch_name) == 0) {
9949 wanted_branch_found = 1;
9950 if (delete) {
9951 err = delete_backup_ref(re->ref,
9952 old_commit_id, repo);
9953 } else {
9954 err = print_backup_ref(branch_name, refname,
9955 old_commit_id, old_commit, refs_idmap,
9956 repo);
9958 if (err)
9959 break;
9962 free(old_commit_id);
9963 old_commit_id = NULL;
9964 free(branch_name);
9965 branch_name = NULL;
9966 got_object_commit_close(old_commit);
9967 old_commit = NULL;
9970 if (wanted_branch_name && !wanted_branch_found) {
9971 err = got_error_fmt(GOT_ERR_NOT_REF,
9972 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9974 done:
9975 if (refs_idmap)
9976 got_reflist_object_id_map_free(refs_idmap);
9977 got_ref_list_free(&refs);
9978 got_ref_list_free(&backup_refs);
9979 free(old_commit_id);
9980 free(branch_name);
9981 if (old_commit)
9982 got_object_commit_close(old_commit);
9983 return err;
9986 static const struct got_error *
9987 abort_progress(void *arg, unsigned char status, const char *path)
9990 * Unversioned files should not clutter progress output when
9991 * an operation is aborted.
9993 if (status == GOT_STATUS_UNVERSIONED)
9994 return NULL;
9996 return update_progress(arg, status, path);
9999 static const struct got_error *
10000 cmd_rebase(int argc, char *argv[])
10002 const struct got_error *error = NULL;
10003 struct got_worktree *worktree = NULL;
10004 struct got_repository *repo = NULL;
10005 struct got_fileindex *fileindex = NULL;
10006 char *cwd = NULL;
10007 struct got_reference *branch = NULL;
10008 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10009 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10010 struct got_object_id *resume_commit_id = NULL;
10011 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10012 struct got_commit_object *commit = NULL;
10013 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10014 int histedit_in_progress = 0, merge_in_progress = 0;
10015 int create_backup = 1, list_backups = 0, delete_backups = 0;
10016 struct got_object_id_queue commits;
10017 struct got_pathlist_head merged_paths;
10018 const struct got_object_id_queue *parent_ids;
10019 struct got_object_qid *qid, *pid;
10020 struct got_update_progress_arg upa;
10021 int *pack_fds = NULL;
10023 STAILQ_INIT(&commits);
10024 TAILQ_INIT(&merged_paths);
10025 memset(&upa, 0, sizeof(upa));
10027 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10028 switch (ch) {
10029 case 'a':
10030 abort_rebase = 1;
10031 break;
10032 case 'c':
10033 continue_rebase = 1;
10034 break;
10035 case 'l':
10036 list_backups = 1;
10037 break;
10038 case 'X':
10039 delete_backups = 1;
10040 break;
10041 default:
10042 usage_rebase();
10043 /* NOTREACHED */
10047 argc -= optind;
10048 argv += optind;
10050 #ifndef PROFILE
10051 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10052 "unveil", NULL) == -1)
10053 err(1, "pledge");
10054 #endif
10055 if (list_backups) {
10056 if (abort_rebase)
10057 option_conflict('l', 'a');
10058 if (continue_rebase)
10059 option_conflict('l', 'c');
10060 if (delete_backups)
10061 option_conflict('l', 'X');
10062 if (argc != 0 && argc != 1)
10063 usage_rebase();
10064 } else if (delete_backups) {
10065 if (abort_rebase)
10066 option_conflict('X', 'a');
10067 if (continue_rebase)
10068 option_conflict('X', 'c');
10069 if (list_backups)
10070 option_conflict('l', 'X');
10071 if (argc != 0 && argc != 1)
10072 usage_rebase();
10073 } else {
10074 if (abort_rebase && continue_rebase)
10075 usage_rebase();
10076 else if (abort_rebase || continue_rebase) {
10077 if (argc != 0)
10078 usage_rebase();
10079 } else if (argc != 1)
10080 usage_rebase();
10083 cwd = getcwd(NULL, 0);
10084 if (cwd == NULL) {
10085 error = got_error_from_errno("getcwd");
10086 goto done;
10089 error = got_repo_pack_fds_open(&pack_fds);
10090 if (error != NULL)
10091 goto done;
10093 error = got_worktree_open(&worktree, cwd);
10094 if (error) {
10095 if (list_backups || delete_backups) {
10096 if (error->code != GOT_ERR_NOT_WORKTREE)
10097 goto done;
10098 } else {
10099 if (error->code == GOT_ERR_NOT_WORKTREE)
10100 error = wrap_not_worktree_error(error,
10101 "rebase", cwd);
10102 goto done;
10106 error = got_repo_open(&repo,
10107 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
10108 pack_fds);
10109 if (error != NULL)
10110 goto done;
10112 error = apply_unveil(got_repo_get_path(repo), 0,
10113 worktree ? got_worktree_get_root_path(worktree) : NULL);
10114 if (error)
10115 goto done;
10117 if (list_backups || delete_backups) {
10118 error = process_backup_refs(
10119 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10120 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10121 goto done; /* nothing else to do */
10124 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10125 worktree);
10126 if (error)
10127 goto done;
10128 if (histedit_in_progress) {
10129 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10130 goto done;
10133 error = got_worktree_merge_in_progress(&merge_in_progress,
10134 worktree, repo);
10135 if (error)
10136 goto done;
10137 if (merge_in_progress) {
10138 error = got_error(GOT_ERR_MERGE_BUSY);
10139 goto done;
10142 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10143 if (error)
10144 goto done;
10146 if (abort_rebase) {
10147 if (!rebase_in_progress) {
10148 error = got_error(GOT_ERR_NOT_REBASING);
10149 goto done;
10151 error = got_worktree_rebase_continue(&resume_commit_id,
10152 &new_base_branch, &tmp_branch, &branch, &fileindex,
10153 worktree, repo);
10154 if (error)
10155 goto done;
10156 printf("Switching work tree to %s\n",
10157 got_ref_get_symref_target(new_base_branch));
10158 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10159 new_base_branch, abort_progress, &upa);
10160 if (error)
10161 goto done;
10162 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10163 print_merge_progress_stats(&upa);
10164 goto done; /* nothing else to do */
10167 if (continue_rebase) {
10168 if (!rebase_in_progress) {
10169 error = got_error(GOT_ERR_NOT_REBASING);
10170 goto done;
10172 error = got_worktree_rebase_continue(&resume_commit_id,
10173 &new_base_branch, &tmp_branch, &branch, &fileindex,
10174 worktree, repo);
10175 if (error)
10176 goto done;
10178 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10179 resume_commit_id, repo);
10180 if (error)
10181 goto done;
10183 yca_id = got_object_id_dup(resume_commit_id);
10184 if (yca_id == NULL) {
10185 error = got_error_from_errno("got_object_id_dup");
10186 goto done;
10188 } else {
10189 error = got_ref_open(&branch, repo, argv[0], 0);
10190 if (error != NULL)
10191 goto done;
10194 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10195 if (error)
10196 goto done;
10198 if (!continue_rebase) {
10199 struct got_object_id *base_commit_id;
10201 base_commit_id = got_worktree_get_base_commit_id(worktree);
10202 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10203 base_commit_id, branch_head_commit_id, 1, repo,
10204 check_cancelled, NULL);
10205 if (error)
10206 goto done;
10207 if (yca_id == NULL) {
10208 error = got_error_msg(GOT_ERR_ANCESTRY,
10209 "specified branch shares no common ancestry "
10210 "with work tree's branch");
10211 goto done;
10214 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10215 if (error) {
10216 if (error->code != GOT_ERR_ANCESTRY)
10217 goto done;
10218 error = NULL;
10219 } else {
10220 struct got_pathlist_head paths;
10221 printf("%s is already based on %s\n",
10222 got_ref_get_name(branch),
10223 got_worktree_get_head_ref_name(worktree));
10224 error = switch_head_ref(branch, branch_head_commit_id,
10225 worktree, repo);
10226 if (error)
10227 goto done;
10228 error = got_worktree_set_base_commit_id(worktree, repo,
10229 branch_head_commit_id);
10230 if (error)
10231 goto done;
10232 TAILQ_INIT(&paths);
10233 error = got_pathlist_append(&paths, "", NULL);
10234 if (error)
10235 goto done;
10236 error = got_worktree_checkout_files(worktree,
10237 &paths, repo, update_progress, &upa,
10238 check_cancelled, NULL);
10239 got_pathlist_free(&paths);
10240 if (error)
10241 goto done;
10242 if (upa.did_something) {
10243 char *id_str;
10244 error = got_object_id_str(&id_str,
10245 branch_head_commit_id);
10246 if (error)
10247 goto done;
10248 printf("Updated to %s: %s\n",
10249 got_worktree_get_head_ref_name(worktree),
10250 id_str);
10251 free(id_str);
10252 } else
10253 printf("Already up-to-date\n");
10254 print_update_progress_stats(&upa);
10255 goto done;
10259 commit_id = branch_head_commit_id;
10260 error = got_object_open_as_commit(&commit, repo, commit_id);
10261 if (error)
10262 goto done;
10264 parent_ids = got_object_commit_get_parent_ids(commit);
10265 pid = STAILQ_FIRST(parent_ids);
10266 if (pid == NULL) {
10267 error = got_error(GOT_ERR_EMPTY_REBASE);
10268 goto done;
10270 error = collect_commits(&commits, commit_id, &pid->id,
10271 yca_id, got_worktree_get_path_prefix(worktree),
10272 GOT_ERR_REBASE_PATH, repo);
10273 got_object_commit_close(commit);
10274 commit = NULL;
10275 if (error)
10276 goto done;
10278 if (!continue_rebase) {
10279 error = got_worktree_rebase_prepare(&new_base_branch,
10280 &tmp_branch, &fileindex, worktree, branch, repo);
10281 if (error)
10282 goto done;
10285 if (STAILQ_EMPTY(&commits)) {
10286 if (continue_rebase) {
10287 error = rebase_complete(worktree, fileindex,
10288 branch, new_base_branch, tmp_branch, repo,
10289 create_backup);
10290 goto done;
10291 } else {
10292 /* Fast-forward the reference of the branch. */
10293 struct got_object_id *new_head_commit_id;
10294 char *id_str;
10295 error = got_ref_resolve(&new_head_commit_id, repo,
10296 new_base_branch);
10297 if (error)
10298 goto done;
10299 error = got_object_id_str(&id_str, new_head_commit_id);
10300 printf("Forwarding %s to commit %s\n",
10301 got_ref_get_name(branch), id_str);
10302 free(id_str);
10303 error = got_ref_change_ref(branch,
10304 new_head_commit_id);
10305 if (error)
10306 goto done;
10307 /* No backup needed since objects did not change. */
10308 create_backup = 0;
10312 pid = NULL;
10313 STAILQ_FOREACH(qid, &commits, entry) {
10315 commit_id = &qid->id;
10316 parent_id = pid ? &pid->id : yca_id;
10317 pid = qid;
10319 memset(&upa, 0, sizeof(upa));
10320 error = got_worktree_rebase_merge_files(&merged_paths,
10321 worktree, fileindex, parent_id, commit_id, repo,
10322 update_progress, &upa, check_cancelled, NULL);
10323 if (error)
10324 goto done;
10326 print_merge_progress_stats(&upa);
10327 if (upa.conflicts > 0 || upa.missing > 0 ||
10328 upa.not_deleted > 0 || upa.unversioned > 0) {
10329 if (upa.conflicts > 0) {
10330 error = show_rebase_merge_conflict(&qid->id,
10331 repo);
10332 if (error)
10333 goto done;
10335 got_worktree_rebase_pathlist_free(&merged_paths);
10336 break;
10339 error = rebase_commit(&merged_paths, worktree, fileindex,
10340 tmp_branch, commit_id, repo);
10341 got_worktree_rebase_pathlist_free(&merged_paths);
10342 if (error)
10343 goto done;
10346 if (upa.conflicts > 0 || upa.missing > 0 ||
10347 upa.not_deleted > 0 || upa.unversioned > 0) {
10348 error = got_worktree_rebase_postpone(worktree, fileindex);
10349 if (error)
10350 goto done;
10351 if (upa.conflicts > 0 && upa.missing == 0 &&
10352 upa.not_deleted == 0 && upa.unversioned == 0) {
10353 error = got_error_msg(GOT_ERR_CONFLICTS,
10354 "conflicts must be resolved before rebasing "
10355 "can continue");
10356 } else if (upa.conflicts > 0) {
10357 error = got_error_msg(GOT_ERR_CONFLICTS,
10358 "conflicts must be resolved before rebasing "
10359 "can continue; changes destined for some "
10360 "files were not yet merged and should be "
10361 "merged manually if required before the "
10362 "rebase operation is continued");
10363 } else {
10364 error = got_error_msg(GOT_ERR_CONFLICTS,
10365 "changes destined for some files were not "
10366 "yet merged and should be merged manually "
10367 "if required before the rebase operation "
10368 "is continued");
10370 } else
10371 error = rebase_complete(worktree, fileindex, branch,
10372 new_base_branch, tmp_branch, repo, create_backup);
10373 done:
10374 got_object_id_queue_free(&commits);
10375 free(branch_head_commit_id);
10376 free(resume_commit_id);
10377 free(yca_id);
10378 if (commit)
10379 got_object_commit_close(commit);
10380 if (branch)
10381 got_ref_close(branch);
10382 if (new_base_branch)
10383 got_ref_close(new_base_branch);
10384 if (tmp_branch)
10385 got_ref_close(tmp_branch);
10386 if (worktree)
10387 got_worktree_close(worktree);
10388 if (repo) {
10389 const struct got_error *close_err = got_repo_close(repo);
10390 if (error == NULL)
10391 error = close_err;
10393 if (pack_fds) {
10394 const struct got_error *pack_err =
10395 got_repo_pack_fds_close(pack_fds);
10396 if (error == NULL)
10397 error = pack_err;
10399 return error;
10402 __dead static void
10403 usage_histedit(void)
10405 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10406 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10407 getprogname());
10408 exit(1);
10411 #define GOT_HISTEDIT_PICK 'p'
10412 #define GOT_HISTEDIT_EDIT 'e'
10413 #define GOT_HISTEDIT_FOLD 'f'
10414 #define GOT_HISTEDIT_DROP 'd'
10415 #define GOT_HISTEDIT_MESG 'm'
10417 static const struct got_histedit_cmd {
10418 unsigned char code;
10419 const char *name;
10420 const char *desc;
10421 } got_histedit_cmds[] = {
10422 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10423 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10424 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10425 "be used" },
10426 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10427 { GOT_HISTEDIT_MESG, "mesg",
10428 "single-line log message for commit above (open editor if empty)" },
10431 struct got_histedit_list_entry {
10432 TAILQ_ENTRY(got_histedit_list_entry) entry;
10433 struct got_object_id *commit_id;
10434 const struct got_histedit_cmd *cmd;
10435 char *logmsg;
10437 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10439 static const struct got_error *
10440 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10441 FILE *f, struct got_repository *repo)
10443 const struct got_error *err = NULL;
10444 char *logmsg = NULL, *id_str = NULL;
10445 struct got_commit_object *commit = NULL;
10446 int n;
10448 err = got_object_open_as_commit(&commit, repo, commit_id);
10449 if (err)
10450 goto done;
10452 err = get_short_logmsg(&logmsg, 34, commit);
10453 if (err)
10454 goto done;
10456 err = got_object_id_str(&id_str, commit_id);
10457 if (err)
10458 goto done;
10460 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10461 if (n < 0)
10462 err = got_ferror(f, GOT_ERR_IO);
10463 done:
10464 if (commit)
10465 got_object_commit_close(commit);
10466 free(id_str);
10467 free(logmsg);
10468 return err;
10471 static const struct got_error *
10472 histedit_write_commit_list(struct got_object_id_queue *commits,
10473 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10474 struct got_repository *repo)
10476 const struct got_error *err = NULL;
10477 struct got_object_qid *qid;
10478 const char *histedit_cmd = NULL;
10480 if (STAILQ_EMPTY(commits))
10481 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10483 STAILQ_FOREACH(qid, commits, entry) {
10484 histedit_cmd = got_histedit_cmds[0].name;
10485 if (edit_only)
10486 histedit_cmd = "edit";
10487 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10488 histedit_cmd = "fold";
10489 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10490 if (err)
10491 break;
10492 if (edit_logmsg_only) {
10493 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10494 if (n < 0) {
10495 err = got_ferror(f, GOT_ERR_IO);
10496 break;
10501 return err;
10504 static const struct got_error *
10505 write_cmd_list(FILE *f, const char *branch_name,
10506 struct got_object_id_queue *commits)
10508 const struct got_error *err = NULL;
10509 size_t i;
10510 int n;
10511 char *id_str;
10512 struct got_object_qid *qid;
10514 qid = STAILQ_FIRST(commits);
10515 err = got_object_id_str(&id_str, &qid->id);
10516 if (err)
10517 return err;
10519 n = fprintf(f,
10520 "# Editing the history of branch '%s' starting at\n"
10521 "# commit %s\n"
10522 "# Commits will be processed in order from top to "
10523 "bottom of this file.\n", branch_name, id_str);
10524 if (n < 0) {
10525 err = got_ferror(f, GOT_ERR_IO);
10526 goto done;
10529 n = fprintf(f, "# Available histedit commands:\n");
10530 if (n < 0) {
10531 err = got_ferror(f, GOT_ERR_IO);
10532 goto done;
10535 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10536 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10537 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10538 cmd->desc);
10539 if (n < 0) {
10540 err = got_ferror(f, GOT_ERR_IO);
10541 break;
10544 done:
10545 free(id_str);
10546 return err;
10549 static const struct got_error *
10550 histedit_syntax_error(int lineno)
10552 static char msg[42];
10553 int ret;
10555 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10556 lineno);
10557 if (ret == -1 || ret >= sizeof(msg))
10558 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10560 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10563 static const struct got_error *
10564 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10565 char *logmsg, struct got_repository *repo)
10567 const struct got_error *err;
10568 struct got_commit_object *folded_commit = NULL;
10569 char *id_str, *folded_logmsg = NULL;
10571 err = got_object_id_str(&id_str, hle->commit_id);
10572 if (err)
10573 return err;
10575 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10576 if (err)
10577 goto done;
10579 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10580 if (err)
10581 goto done;
10582 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10583 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10584 folded_logmsg) == -1) {
10585 err = got_error_from_errno("asprintf");
10587 done:
10588 if (folded_commit)
10589 got_object_commit_close(folded_commit);
10590 free(id_str);
10591 free(folded_logmsg);
10592 return err;
10595 static struct got_histedit_list_entry *
10596 get_folded_commits(struct got_histedit_list_entry *hle)
10598 struct got_histedit_list_entry *prev, *folded = NULL;
10600 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10601 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10602 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10603 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10604 folded = prev;
10605 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10608 return folded;
10611 static const struct got_error *
10612 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10613 struct got_repository *repo)
10615 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10616 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10617 const struct got_error *err = NULL;
10618 struct got_commit_object *commit = NULL;
10619 int logmsg_len;
10620 int fd;
10621 struct got_histedit_list_entry *folded = NULL;
10623 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10624 if (err)
10625 return err;
10627 folded = get_folded_commits(hle);
10628 if (folded) {
10629 while (folded != hle) {
10630 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10631 folded = TAILQ_NEXT(folded, entry);
10632 continue;
10634 err = append_folded_commit_msg(&new_msg, folded,
10635 logmsg, repo);
10636 if (err)
10637 goto done;
10638 free(logmsg);
10639 logmsg = new_msg;
10640 folded = TAILQ_NEXT(folded, entry);
10644 err = got_object_id_str(&id_str, hle->commit_id);
10645 if (err)
10646 goto done;
10647 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10648 if (err)
10649 goto done;
10650 logmsg_len = asprintf(&new_msg,
10651 "%s\n# original log message of commit %s: %s",
10652 logmsg ? logmsg : "", id_str, orig_logmsg);
10653 if (logmsg_len == -1) {
10654 err = got_error_from_errno("asprintf");
10655 goto done;
10657 free(logmsg);
10658 logmsg = new_msg;
10660 err = got_object_id_str(&id_str, hle->commit_id);
10661 if (err)
10662 goto done;
10664 err = got_opentemp_named_fd(&logmsg_path, &fd,
10665 GOT_TMPDIR_STR "/got-logmsg");
10666 if (err)
10667 goto done;
10669 write(fd, logmsg, logmsg_len);
10670 close(fd);
10672 err = get_editor(&editor);
10673 if (err)
10674 goto done;
10676 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10677 logmsg_len, 0);
10678 if (err) {
10679 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10680 goto done;
10681 err = NULL;
10682 hle->logmsg = strdup(new_msg);
10683 if (hle->logmsg == NULL)
10684 err = got_error_from_errno("strdup");
10686 done:
10687 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10688 err = got_error_from_errno2("unlink", logmsg_path);
10689 free(logmsg_path);
10690 free(logmsg);
10691 free(orig_logmsg);
10692 free(editor);
10693 if (commit)
10694 got_object_commit_close(commit);
10695 return err;
10698 static const struct got_error *
10699 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10700 FILE *f, struct got_repository *repo)
10702 const struct got_error *err = NULL;
10703 char *line = NULL, *p, *end;
10704 size_t i, size;
10705 ssize_t len;
10706 int lineno = 0, lastcmd = -1;
10707 const struct got_histedit_cmd *cmd;
10708 struct got_object_id *commit_id = NULL;
10709 struct got_histedit_list_entry *hle = NULL;
10711 for (;;) {
10712 len = getline(&line, &size, f);
10713 if (len == -1) {
10714 const struct got_error *getline_err;
10715 if (feof(f))
10716 break;
10717 getline_err = got_error_from_errno("getline");
10718 err = got_ferror(f, getline_err->code);
10719 break;
10721 lineno++;
10722 p = line;
10723 while (isspace((unsigned char)p[0]))
10724 p++;
10725 if (p[0] == '#' || p[0] == '\0') {
10726 free(line);
10727 line = NULL;
10728 continue;
10730 cmd = NULL;
10731 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10732 cmd = &got_histedit_cmds[i];
10733 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10734 isspace((unsigned char)p[strlen(cmd->name)])) {
10735 p += strlen(cmd->name);
10736 break;
10738 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10739 p++;
10740 break;
10743 if (i == nitems(got_histedit_cmds)) {
10744 err = histedit_syntax_error(lineno);
10745 break;
10747 while (isspace((unsigned char)p[0]))
10748 p++;
10749 if (cmd->code == GOT_HISTEDIT_MESG) {
10750 if (lastcmd != GOT_HISTEDIT_PICK &&
10751 lastcmd != GOT_HISTEDIT_EDIT) {
10752 err = got_error(GOT_ERR_HISTEDIT_CMD);
10753 break;
10755 if (p[0] == '\0') {
10756 err = histedit_edit_logmsg(hle, repo);
10757 if (err)
10758 break;
10759 } else {
10760 hle->logmsg = strdup(p);
10761 if (hle->logmsg == NULL) {
10762 err = got_error_from_errno("strdup");
10763 break;
10766 free(line);
10767 line = NULL;
10768 lastcmd = cmd->code;
10769 continue;
10770 } else {
10771 end = p;
10772 while (end[0] && !isspace((unsigned char)end[0]))
10773 end++;
10774 *end = '\0';
10776 err = got_object_resolve_id_str(&commit_id, repo, p);
10777 if (err) {
10778 /* override error code */
10779 err = histedit_syntax_error(lineno);
10780 break;
10783 hle = malloc(sizeof(*hle));
10784 if (hle == NULL) {
10785 err = got_error_from_errno("malloc");
10786 break;
10788 hle->cmd = cmd;
10789 hle->commit_id = commit_id;
10790 hle->logmsg = NULL;
10791 commit_id = NULL;
10792 free(line);
10793 line = NULL;
10794 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10795 lastcmd = cmd->code;
10798 free(line);
10799 free(commit_id);
10800 return err;
10803 static const struct got_error *
10804 histedit_check_script(struct got_histedit_list *histedit_cmds,
10805 struct got_object_id_queue *commits, struct got_repository *repo)
10807 const struct got_error *err = NULL;
10808 struct got_object_qid *qid;
10809 struct got_histedit_list_entry *hle;
10810 static char msg[92];
10811 char *id_str;
10813 if (TAILQ_EMPTY(histedit_cmds))
10814 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10815 "histedit script contains no commands");
10816 if (STAILQ_EMPTY(commits))
10817 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10819 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10820 struct got_histedit_list_entry *hle2;
10821 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10822 if (hle == hle2)
10823 continue;
10824 if (got_object_id_cmp(hle->commit_id,
10825 hle2->commit_id) != 0)
10826 continue;
10827 err = got_object_id_str(&id_str, hle->commit_id);
10828 if (err)
10829 return err;
10830 snprintf(msg, sizeof(msg), "commit %s is listed "
10831 "more than once in histedit script", id_str);
10832 free(id_str);
10833 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10837 STAILQ_FOREACH(qid, commits, entry) {
10838 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10839 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10840 break;
10842 if (hle == NULL) {
10843 err = got_object_id_str(&id_str, &qid->id);
10844 if (err)
10845 return err;
10846 snprintf(msg, sizeof(msg),
10847 "commit %s missing from histedit script", id_str);
10848 free(id_str);
10849 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10853 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10854 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10855 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10856 "last commit in histedit script cannot be folded");
10858 return NULL;
10861 static const struct got_error *
10862 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10863 const char *path, struct got_object_id_queue *commits,
10864 struct got_repository *repo)
10866 const struct got_error *err = NULL;
10867 char *editor;
10868 FILE *f = NULL;
10870 err = get_editor(&editor);
10871 if (err)
10872 return err;
10874 if (spawn_editor(editor, path) == -1) {
10875 err = got_error_from_errno("failed spawning editor");
10876 goto done;
10879 f = fopen(path, "re");
10880 if (f == NULL) {
10881 err = got_error_from_errno("fopen");
10882 goto done;
10884 err = histedit_parse_list(histedit_cmds, f, repo);
10885 if (err)
10886 goto done;
10888 err = histedit_check_script(histedit_cmds, commits, repo);
10889 done:
10890 if (f && fclose(f) == EOF && err == NULL)
10891 err = got_error_from_errno("fclose");
10892 free(editor);
10893 return err;
10896 static const struct got_error *
10897 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10898 struct got_object_id_queue *, const char *, const char *,
10899 struct got_repository *);
10901 static const struct got_error *
10902 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10903 struct got_object_id_queue *commits, const char *branch_name,
10904 int edit_logmsg_only, int fold_only, int edit_only,
10905 struct got_repository *repo)
10907 const struct got_error *err;
10908 FILE *f = NULL;
10909 char *path = NULL;
10911 err = got_opentemp_named(&path, &f, "got-histedit");
10912 if (err)
10913 return err;
10915 err = write_cmd_list(f, branch_name, commits);
10916 if (err)
10917 goto done;
10919 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10920 fold_only, edit_only, repo);
10921 if (err)
10922 goto done;
10924 if (edit_logmsg_only || fold_only || edit_only) {
10925 rewind(f);
10926 err = histedit_parse_list(histedit_cmds, f, repo);
10927 } else {
10928 if (fclose(f) == EOF) {
10929 err = got_error_from_errno("fclose");
10930 goto done;
10932 f = NULL;
10933 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10934 if (err) {
10935 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10936 err->code != GOT_ERR_HISTEDIT_CMD)
10937 goto done;
10938 err = histedit_edit_list_retry(histedit_cmds, err,
10939 commits, path, branch_name, repo);
10942 done:
10943 if (f && fclose(f) == EOF && err == NULL)
10944 err = got_error_from_errno("fclose");
10945 if (path && unlink(path) != 0 && err == NULL)
10946 err = got_error_from_errno2("unlink", path);
10947 free(path);
10948 return err;
10951 static const struct got_error *
10952 histedit_save_list(struct got_histedit_list *histedit_cmds,
10953 struct got_worktree *worktree, struct got_repository *repo)
10955 const struct got_error *err = NULL;
10956 char *path = NULL;
10957 FILE *f = NULL;
10958 struct got_histedit_list_entry *hle;
10959 struct got_commit_object *commit = NULL;
10961 err = got_worktree_get_histedit_script_path(&path, worktree);
10962 if (err)
10963 return err;
10965 f = fopen(path, "we");
10966 if (f == NULL) {
10967 err = got_error_from_errno2("fopen", path);
10968 goto done;
10970 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10971 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10972 repo);
10973 if (err)
10974 break;
10976 if (hle->logmsg) {
10977 int n = fprintf(f, "%c %s\n",
10978 GOT_HISTEDIT_MESG, hle->logmsg);
10979 if (n < 0) {
10980 err = got_ferror(f, GOT_ERR_IO);
10981 break;
10985 done:
10986 if (f && fclose(f) == EOF && err == NULL)
10987 err = got_error_from_errno("fclose");
10988 free(path);
10989 if (commit)
10990 got_object_commit_close(commit);
10991 return err;
10994 static void
10995 histedit_free_list(struct got_histedit_list *histedit_cmds)
10997 struct got_histedit_list_entry *hle;
10999 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11000 TAILQ_REMOVE(histedit_cmds, hle, entry);
11001 free(hle);
11005 static const struct got_error *
11006 histedit_load_list(struct got_histedit_list *histedit_cmds,
11007 const char *path, struct got_repository *repo)
11009 const struct got_error *err = NULL;
11010 FILE *f = NULL;
11012 f = fopen(path, "re");
11013 if (f == NULL) {
11014 err = got_error_from_errno2("fopen", path);
11015 goto done;
11018 err = histedit_parse_list(histedit_cmds, f, repo);
11019 done:
11020 if (f && fclose(f) == EOF && err == NULL)
11021 err = got_error_from_errno("fclose");
11022 return err;
11025 static const struct got_error *
11026 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11027 const struct got_error *edit_err, struct got_object_id_queue *commits,
11028 const char *path, const char *branch_name, struct got_repository *repo)
11030 const struct got_error *err = NULL, *prev_err = edit_err;
11031 int resp = ' ';
11033 while (resp != 'c' && resp != 'r' && resp != 'a') {
11034 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11035 "or (a)bort: ", getprogname(), prev_err->msg);
11036 resp = getchar();
11037 if (resp == '\n')
11038 resp = getchar();
11039 if (resp == 'c') {
11040 histedit_free_list(histedit_cmds);
11041 err = histedit_run_editor(histedit_cmds, path, commits,
11042 repo);
11043 if (err) {
11044 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11045 err->code != GOT_ERR_HISTEDIT_CMD)
11046 break;
11047 prev_err = err;
11048 resp = ' ';
11049 continue;
11051 break;
11052 } else if (resp == 'r') {
11053 histedit_free_list(histedit_cmds);
11054 err = histedit_edit_script(histedit_cmds,
11055 commits, branch_name, 0, 0, 0, repo);
11056 if (err) {
11057 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11058 err->code != GOT_ERR_HISTEDIT_CMD)
11059 break;
11060 prev_err = err;
11061 resp = ' ';
11062 continue;
11064 break;
11065 } else if (resp == 'a') {
11066 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11067 break;
11068 } else
11069 printf("invalid response '%c'\n", resp);
11072 return err;
11075 static const struct got_error *
11076 histedit_complete(struct got_worktree *worktree,
11077 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11078 struct got_reference *branch, struct got_repository *repo)
11080 printf("Switching work tree to %s\n",
11081 got_ref_get_symref_target(branch));
11082 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11083 branch, repo);
11086 static const struct got_error *
11087 show_histedit_progress(struct got_commit_object *commit,
11088 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11090 const struct got_error *err;
11091 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11093 err = got_object_id_str(&old_id_str, hle->commit_id);
11094 if (err)
11095 goto done;
11097 if (new_id) {
11098 err = got_object_id_str(&new_id_str, new_id);
11099 if (err)
11100 goto done;
11103 old_id_str[12] = '\0';
11104 if (new_id_str)
11105 new_id_str[12] = '\0';
11107 if (hle->logmsg) {
11108 logmsg = strdup(hle->logmsg);
11109 if (logmsg == NULL) {
11110 err = got_error_from_errno("strdup");
11111 goto done;
11113 trim_logmsg(logmsg, 42);
11114 } else {
11115 err = get_short_logmsg(&logmsg, 42, commit);
11116 if (err)
11117 goto done;
11120 switch (hle->cmd->code) {
11121 case GOT_HISTEDIT_PICK:
11122 case GOT_HISTEDIT_EDIT:
11123 printf("%s -> %s: %s\n", old_id_str,
11124 new_id_str ? new_id_str : "no-op change", logmsg);
11125 break;
11126 case GOT_HISTEDIT_DROP:
11127 case GOT_HISTEDIT_FOLD:
11128 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11129 logmsg);
11130 break;
11131 default:
11132 break;
11134 done:
11135 free(old_id_str);
11136 free(new_id_str);
11137 return err;
11140 static const struct got_error *
11141 histedit_commit(struct got_pathlist_head *merged_paths,
11142 struct got_worktree *worktree, struct got_fileindex *fileindex,
11143 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11144 struct got_repository *repo)
11146 const struct got_error *err;
11147 struct got_commit_object *commit;
11148 struct got_object_id *new_commit_id;
11150 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11151 && hle->logmsg == NULL) {
11152 err = histedit_edit_logmsg(hle, repo);
11153 if (err)
11154 return err;
11157 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11158 if (err)
11159 return err;
11161 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11162 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11163 hle->logmsg, repo);
11164 if (err) {
11165 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11166 goto done;
11167 err = show_histedit_progress(commit, hle, NULL);
11168 } else {
11169 err = show_histedit_progress(commit, hle, new_commit_id);
11170 free(new_commit_id);
11172 done:
11173 got_object_commit_close(commit);
11174 return err;
11177 static const struct got_error *
11178 histedit_skip_commit(struct got_histedit_list_entry *hle,
11179 struct got_worktree *worktree, struct got_repository *repo)
11181 const struct got_error *error;
11182 struct got_commit_object *commit;
11184 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11185 repo);
11186 if (error)
11187 return error;
11189 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11190 if (error)
11191 return error;
11193 error = show_histedit_progress(commit, hle, NULL);
11194 got_object_commit_close(commit);
11195 return error;
11198 static const struct got_error *
11199 check_local_changes(void *arg, unsigned char status,
11200 unsigned char staged_status, const char *path,
11201 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11202 struct got_object_id *commit_id, int dirfd, const char *de_name)
11204 int *have_local_changes = arg;
11206 switch (status) {
11207 case GOT_STATUS_ADD:
11208 case GOT_STATUS_DELETE:
11209 case GOT_STATUS_MODIFY:
11210 case GOT_STATUS_CONFLICT:
11211 *have_local_changes = 1;
11212 return got_error(GOT_ERR_CANCELLED);
11213 default:
11214 break;
11217 switch (staged_status) {
11218 case GOT_STATUS_ADD:
11219 case GOT_STATUS_DELETE:
11220 case GOT_STATUS_MODIFY:
11221 *have_local_changes = 1;
11222 return got_error(GOT_ERR_CANCELLED);
11223 default:
11224 break;
11227 return NULL;
11230 static const struct got_error *
11231 cmd_histedit(int argc, char *argv[])
11233 const struct got_error *error = NULL;
11234 struct got_worktree *worktree = NULL;
11235 struct got_fileindex *fileindex = NULL;
11236 struct got_repository *repo = NULL;
11237 char *cwd = NULL;
11238 struct got_reference *branch = NULL;
11239 struct got_reference *tmp_branch = NULL;
11240 struct got_object_id *resume_commit_id = NULL;
11241 struct got_object_id *base_commit_id = NULL;
11242 struct got_object_id *head_commit_id = NULL;
11243 struct got_commit_object *commit = NULL;
11244 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11245 struct got_update_progress_arg upa;
11246 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11247 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11248 int list_backups = 0, delete_backups = 0;
11249 const char *edit_script_path = NULL;
11250 struct got_object_id_queue commits;
11251 struct got_pathlist_head merged_paths;
11252 const struct got_object_id_queue *parent_ids;
11253 struct got_object_qid *pid;
11254 struct got_histedit_list histedit_cmds;
11255 struct got_histedit_list_entry *hle;
11256 int *pack_fds = NULL;
11258 STAILQ_INIT(&commits);
11259 TAILQ_INIT(&histedit_cmds);
11260 TAILQ_INIT(&merged_paths);
11261 memset(&upa, 0, sizeof(upa));
11263 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11264 switch (ch) {
11265 case 'a':
11266 abort_edit = 1;
11267 break;
11268 case 'c':
11269 continue_edit = 1;
11270 break;
11271 case 'e':
11272 edit_only = 1;
11273 break;
11274 case 'f':
11275 fold_only = 1;
11276 break;
11277 case 'F':
11278 edit_script_path = optarg;
11279 break;
11280 case 'm':
11281 edit_logmsg_only = 1;
11282 break;
11283 case 'l':
11284 list_backups = 1;
11285 break;
11286 case 'X':
11287 delete_backups = 1;
11288 break;
11289 default:
11290 usage_histedit();
11291 /* NOTREACHED */
11295 argc -= optind;
11296 argv += optind;
11298 #ifndef PROFILE
11299 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11300 "unveil", NULL) == -1)
11301 err(1, "pledge");
11302 #endif
11303 if (abort_edit && continue_edit)
11304 option_conflict('a', 'c');
11305 if (edit_script_path && edit_logmsg_only)
11306 option_conflict('F', 'm');
11307 if (abort_edit && edit_logmsg_only)
11308 option_conflict('a', 'm');
11309 if (continue_edit && edit_logmsg_only)
11310 option_conflict('c', 'm');
11311 if (abort_edit && fold_only)
11312 option_conflict('a', 'f');
11313 if (continue_edit && fold_only)
11314 option_conflict('c', 'f');
11315 if (fold_only && edit_logmsg_only)
11316 option_conflict('f', 'm');
11317 if (edit_script_path && fold_only)
11318 option_conflict('F', 'f');
11319 if (abort_edit && edit_only)
11320 option_conflict('a', 'e');
11321 if (continue_edit && edit_only)
11322 option_conflict('c', 'e');
11323 if (edit_only && edit_logmsg_only)
11324 option_conflict('e', 'm');
11325 if (edit_script_path && edit_only)
11326 option_conflict('F', 'e');
11327 if (list_backups) {
11328 if (abort_edit)
11329 option_conflict('l', 'a');
11330 if (continue_edit)
11331 option_conflict('l', 'c');
11332 if (edit_script_path)
11333 option_conflict('l', 'F');
11334 if (edit_logmsg_only)
11335 option_conflict('l', 'm');
11336 if (fold_only)
11337 option_conflict('l', 'f');
11338 if (edit_only)
11339 option_conflict('l', 'e');
11340 if (delete_backups)
11341 option_conflict('l', 'X');
11342 if (argc != 0 && argc != 1)
11343 usage_histedit();
11344 } else if (delete_backups) {
11345 if (abort_edit)
11346 option_conflict('X', 'a');
11347 if (continue_edit)
11348 option_conflict('X', 'c');
11349 if (edit_script_path)
11350 option_conflict('X', 'F');
11351 if (edit_logmsg_only)
11352 option_conflict('X', 'm');
11353 if (fold_only)
11354 option_conflict('X', 'f');
11355 if (edit_only)
11356 option_conflict('X', 'e');
11357 if (list_backups)
11358 option_conflict('X', 'l');
11359 if (argc != 0 && argc != 1)
11360 usage_histedit();
11361 } else if (argc != 0)
11362 usage_histedit();
11365 * This command cannot apply unveil(2) in all cases because the
11366 * user may choose to run an editor to edit the histedit script
11367 * and to edit individual commit log messages.
11368 * unveil(2) traverses exec(2); if an editor is used we have to
11369 * apply unveil after edit script and log messages have been written.
11370 * XXX TODO: Make use of unveil(2) where possible.
11373 cwd = getcwd(NULL, 0);
11374 if (cwd == NULL) {
11375 error = got_error_from_errno("getcwd");
11376 goto done;
11379 error = got_repo_pack_fds_open(&pack_fds);
11380 if (error != NULL)
11381 goto done;
11383 error = got_worktree_open(&worktree, cwd);
11384 if (error) {
11385 if (list_backups || delete_backups) {
11386 if (error->code != GOT_ERR_NOT_WORKTREE)
11387 goto done;
11388 } else {
11389 if (error->code == GOT_ERR_NOT_WORKTREE)
11390 error = wrap_not_worktree_error(error,
11391 "histedit", cwd);
11392 goto done;
11396 if (list_backups || delete_backups) {
11397 error = got_repo_open(&repo,
11398 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11399 NULL, pack_fds);
11400 if (error != NULL)
11401 goto done;
11402 error = apply_unveil(got_repo_get_path(repo), 0,
11403 worktree ? got_worktree_get_root_path(worktree) : NULL);
11404 if (error)
11405 goto done;
11406 error = process_backup_refs(
11407 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11408 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11409 goto done; /* nothing else to do */
11412 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11413 NULL, pack_fds);
11414 if (error != NULL)
11415 goto done;
11417 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11418 if (error)
11419 goto done;
11420 if (rebase_in_progress) {
11421 error = got_error(GOT_ERR_REBASING);
11422 goto done;
11425 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11426 repo);
11427 if (error)
11428 goto done;
11429 if (merge_in_progress) {
11430 error = got_error(GOT_ERR_MERGE_BUSY);
11431 goto done;
11434 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11435 if (error)
11436 goto done;
11438 if (edit_in_progress && edit_logmsg_only) {
11439 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11440 "histedit operation is in progress in this "
11441 "work tree and must be continued or aborted "
11442 "before the -m option can be used");
11443 goto done;
11445 if (edit_in_progress && fold_only) {
11446 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11447 "histedit operation is in progress in this "
11448 "work tree and must be continued or aborted "
11449 "before the -f option can be used");
11450 goto done;
11452 if (edit_in_progress && edit_only) {
11453 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11454 "histedit operation is in progress in this "
11455 "work tree and must be continued or aborted "
11456 "before the -e option can be used");
11457 goto done;
11460 if (edit_in_progress && abort_edit) {
11461 error = got_worktree_histedit_continue(&resume_commit_id,
11462 &tmp_branch, &branch, &base_commit_id, &fileindex,
11463 worktree, repo);
11464 if (error)
11465 goto done;
11466 printf("Switching work tree to %s\n",
11467 got_ref_get_symref_target(branch));
11468 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11469 branch, base_commit_id, abort_progress, &upa);
11470 if (error)
11471 goto done;
11472 printf("Histedit of %s aborted\n",
11473 got_ref_get_symref_target(branch));
11474 print_merge_progress_stats(&upa);
11475 goto done; /* nothing else to do */
11476 } else if (abort_edit) {
11477 error = got_error(GOT_ERR_NOT_HISTEDIT);
11478 goto done;
11481 if (continue_edit) {
11482 char *path;
11484 if (!edit_in_progress) {
11485 error = got_error(GOT_ERR_NOT_HISTEDIT);
11486 goto done;
11489 error = got_worktree_get_histedit_script_path(&path, worktree);
11490 if (error)
11491 goto done;
11493 error = histedit_load_list(&histedit_cmds, path, repo);
11494 free(path);
11495 if (error)
11496 goto done;
11498 error = got_worktree_histedit_continue(&resume_commit_id,
11499 &tmp_branch, &branch, &base_commit_id, &fileindex,
11500 worktree, repo);
11501 if (error)
11502 goto done;
11504 error = got_ref_resolve(&head_commit_id, repo, branch);
11505 if (error)
11506 goto done;
11508 error = got_object_open_as_commit(&commit, repo,
11509 head_commit_id);
11510 if (error)
11511 goto done;
11512 parent_ids = got_object_commit_get_parent_ids(commit);
11513 pid = STAILQ_FIRST(parent_ids);
11514 if (pid == NULL) {
11515 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11516 goto done;
11518 error = collect_commits(&commits, head_commit_id, &pid->id,
11519 base_commit_id, got_worktree_get_path_prefix(worktree),
11520 GOT_ERR_HISTEDIT_PATH, repo);
11521 got_object_commit_close(commit);
11522 commit = NULL;
11523 if (error)
11524 goto done;
11525 } else {
11526 if (edit_in_progress) {
11527 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11528 goto done;
11531 error = got_ref_open(&branch, repo,
11532 got_worktree_get_head_ref_name(worktree), 0);
11533 if (error != NULL)
11534 goto done;
11536 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11537 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11538 "will not edit commit history of a branch outside "
11539 "the \"refs/heads/\" reference namespace");
11540 goto done;
11543 error = got_ref_resolve(&head_commit_id, repo, branch);
11544 got_ref_close(branch);
11545 branch = NULL;
11546 if (error)
11547 goto done;
11549 error = got_object_open_as_commit(&commit, repo,
11550 head_commit_id);
11551 if (error)
11552 goto done;
11553 parent_ids = got_object_commit_get_parent_ids(commit);
11554 pid = STAILQ_FIRST(parent_ids);
11555 if (pid == NULL) {
11556 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11557 goto done;
11559 error = collect_commits(&commits, head_commit_id, &pid->id,
11560 got_worktree_get_base_commit_id(worktree),
11561 got_worktree_get_path_prefix(worktree),
11562 GOT_ERR_HISTEDIT_PATH, repo);
11563 got_object_commit_close(commit);
11564 commit = NULL;
11565 if (error)
11566 goto done;
11568 if (STAILQ_EMPTY(&commits)) {
11569 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11570 goto done;
11573 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11574 &base_commit_id, &fileindex, worktree, repo);
11575 if (error)
11576 goto done;
11578 if (edit_script_path) {
11579 error = histedit_load_list(&histedit_cmds,
11580 edit_script_path, repo);
11581 if (error) {
11582 got_worktree_histedit_abort(worktree, fileindex,
11583 repo, branch, base_commit_id,
11584 abort_progress, &upa);
11585 print_merge_progress_stats(&upa);
11586 goto done;
11588 } else {
11589 const char *branch_name;
11590 branch_name = got_ref_get_symref_target(branch);
11591 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11592 branch_name += 11;
11593 error = histedit_edit_script(&histedit_cmds, &commits,
11594 branch_name, edit_logmsg_only, fold_only,
11595 edit_only, repo);
11596 if (error) {
11597 got_worktree_histedit_abort(worktree, fileindex,
11598 repo, branch, base_commit_id,
11599 abort_progress, &upa);
11600 print_merge_progress_stats(&upa);
11601 goto done;
11606 error = histedit_save_list(&histedit_cmds, worktree,
11607 repo);
11608 if (error) {
11609 got_worktree_histedit_abort(worktree, fileindex,
11610 repo, branch, base_commit_id,
11611 abort_progress, &upa);
11612 print_merge_progress_stats(&upa);
11613 goto done;
11618 error = histedit_check_script(&histedit_cmds, &commits, repo);
11619 if (error)
11620 goto done;
11622 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11623 if (resume_commit_id) {
11624 if (got_object_id_cmp(hle->commit_id,
11625 resume_commit_id) != 0)
11626 continue;
11628 resume_commit_id = NULL;
11629 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11630 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11631 error = histedit_skip_commit(hle, worktree,
11632 repo);
11633 if (error)
11634 goto done;
11635 } else {
11636 struct got_pathlist_head paths;
11637 int have_changes = 0;
11639 TAILQ_INIT(&paths);
11640 error = got_pathlist_append(&paths, "", NULL);
11641 if (error)
11642 goto done;
11643 error = got_worktree_status(worktree, &paths,
11644 repo, 0, check_local_changes, &have_changes,
11645 check_cancelled, NULL);
11646 got_pathlist_free(&paths);
11647 if (error) {
11648 if (error->code != GOT_ERR_CANCELLED)
11649 goto done;
11650 if (sigint_received || sigpipe_received)
11651 goto done;
11653 if (have_changes) {
11654 error = histedit_commit(NULL, worktree,
11655 fileindex, tmp_branch, hle, repo);
11656 if (error)
11657 goto done;
11658 } else {
11659 error = got_object_open_as_commit(
11660 &commit, repo, hle->commit_id);
11661 if (error)
11662 goto done;
11663 error = show_histedit_progress(commit,
11664 hle, NULL);
11665 got_object_commit_close(commit);
11666 commit = NULL;
11667 if (error)
11668 goto done;
11671 continue;
11674 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11675 error = histedit_skip_commit(hle, worktree, repo);
11676 if (error)
11677 goto done;
11678 continue;
11681 error = got_object_open_as_commit(&commit, repo,
11682 hle->commit_id);
11683 if (error)
11684 goto done;
11685 parent_ids = got_object_commit_get_parent_ids(commit);
11686 pid = STAILQ_FIRST(parent_ids);
11688 error = got_worktree_histedit_merge_files(&merged_paths,
11689 worktree, fileindex, &pid->id, hle->commit_id, repo,
11690 update_progress, &upa, check_cancelled, NULL);
11691 if (error)
11692 goto done;
11693 got_object_commit_close(commit);
11694 commit = NULL;
11696 print_merge_progress_stats(&upa);
11697 if (upa.conflicts > 0 || upa.missing > 0 ||
11698 upa.not_deleted > 0 || upa.unversioned > 0) {
11699 if (upa.conflicts > 0) {
11700 error = show_rebase_merge_conflict(
11701 hle->commit_id, repo);
11702 if (error)
11703 goto done;
11705 got_worktree_rebase_pathlist_free(&merged_paths);
11706 break;
11709 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11710 char *id_str;
11711 error = got_object_id_str(&id_str, hle->commit_id);
11712 if (error)
11713 goto done;
11714 printf("Stopping histedit for amending commit %s\n",
11715 id_str);
11716 free(id_str);
11717 got_worktree_rebase_pathlist_free(&merged_paths);
11718 error = got_worktree_histedit_postpone(worktree,
11719 fileindex);
11720 goto done;
11723 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11724 error = histedit_skip_commit(hle, worktree, repo);
11725 if (error)
11726 goto done;
11727 continue;
11730 error = histedit_commit(&merged_paths, worktree, fileindex,
11731 tmp_branch, hle, repo);
11732 got_worktree_rebase_pathlist_free(&merged_paths);
11733 if (error)
11734 goto done;
11737 if (upa.conflicts > 0 || upa.missing > 0 ||
11738 upa.not_deleted > 0 || upa.unversioned > 0) {
11739 error = got_worktree_histedit_postpone(worktree, fileindex);
11740 if (error)
11741 goto done;
11742 if (upa.conflicts > 0 && upa.missing == 0 &&
11743 upa.not_deleted == 0 && upa.unversioned == 0) {
11744 error = got_error_msg(GOT_ERR_CONFLICTS,
11745 "conflicts must be resolved before histedit "
11746 "can continue");
11747 } else if (upa.conflicts > 0) {
11748 error = got_error_msg(GOT_ERR_CONFLICTS,
11749 "conflicts must be resolved before histedit "
11750 "can continue; changes destined for some "
11751 "files were not yet merged and should be "
11752 "merged manually if required before the "
11753 "histedit operation is continued");
11754 } else {
11755 error = got_error_msg(GOT_ERR_CONFLICTS,
11756 "changes destined for some files were not "
11757 "yet merged and should be merged manually "
11758 "if required before the histedit operation "
11759 "is continued");
11761 } else
11762 error = histedit_complete(worktree, fileindex, tmp_branch,
11763 branch, repo);
11764 done:
11765 got_object_id_queue_free(&commits);
11766 histedit_free_list(&histedit_cmds);
11767 free(head_commit_id);
11768 free(base_commit_id);
11769 free(resume_commit_id);
11770 if (commit)
11771 got_object_commit_close(commit);
11772 if (branch)
11773 got_ref_close(branch);
11774 if (tmp_branch)
11775 got_ref_close(tmp_branch);
11776 if (worktree)
11777 got_worktree_close(worktree);
11778 if (repo) {
11779 const struct got_error *close_err = got_repo_close(repo);
11780 if (error == NULL)
11781 error = close_err;
11783 if (pack_fds) {
11784 const struct got_error *pack_err =
11785 got_repo_pack_fds_close(pack_fds);
11786 if (error == NULL)
11787 error = pack_err;
11789 return error;
11792 __dead static void
11793 usage_integrate(void)
11795 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11796 exit(1);
11799 static const struct got_error *
11800 cmd_integrate(int argc, char *argv[])
11802 const struct got_error *error = NULL;
11803 struct got_repository *repo = NULL;
11804 struct got_worktree *worktree = NULL;
11805 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11806 const char *branch_arg = NULL;
11807 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11808 struct got_fileindex *fileindex = NULL;
11809 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11810 int ch;
11811 struct got_update_progress_arg upa;
11812 int *pack_fds = NULL;
11814 while ((ch = getopt(argc, argv, "")) != -1) {
11815 switch (ch) {
11816 default:
11817 usage_integrate();
11818 /* NOTREACHED */
11822 argc -= optind;
11823 argv += optind;
11825 if (argc != 1)
11826 usage_integrate();
11827 branch_arg = argv[0];
11828 #ifndef PROFILE
11829 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11830 "unveil", NULL) == -1)
11831 err(1, "pledge");
11832 #endif
11833 cwd = getcwd(NULL, 0);
11834 if (cwd == NULL) {
11835 error = got_error_from_errno("getcwd");
11836 goto done;
11839 error = got_repo_pack_fds_open(&pack_fds);
11840 if (error != NULL)
11841 goto done;
11843 error = got_worktree_open(&worktree, cwd);
11844 if (error) {
11845 if (error->code == GOT_ERR_NOT_WORKTREE)
11846 error = wrap_not_worktree_error(error, "integrate",
11847 cwd);
11848 goto done;
11851 error = check_rebase_or_histedit_in_progress(worktree);
11852 if (error)
11853 goto done;
11855 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11856 NULL, pack_fds);
11857 if (error != NULL)
11858 goto done;
11860 error = apply_unveil(got_repo_get_path(repo), 0,
11861 got_worktree_get_root_path(worktree));
11862 if (error)
11863 goto done;
11865 error = check_merge_in_progress(worktree, repo);
11866 if (error)
11867 goto done;
11869 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11870 error = got_error_from_errno("asprintf");
11871 goto done;
11874 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11875 &base_branch_ref, worktree, refname, repo);
11876 if (error)
11877 goto done;
11879 refname = strdup(got_ref_get_name(branch_ref));
11880 if (refname == NULL) {
11881 error = got_error_from_errno("strdup");
11882 got_worktree_integrate_abort(worktree, fileindex, repo,
11883 branch_ref, base_branch_ref);
11884 goto done;
11886 base_refname = strdup(got_ref_get_name(base_branch_ref));
11887 if (base_refname == NULL) {
11888 error = got_error_from_errno("strdup");
11889 got_worktree_integrate_abort(worktree, fileindex, repo,
11890 branch_ref, base_branch_ref);
11891 goto done;
11894 error = got_ref_resolve(&commit_id, repo, branch_ref);
11895 if (error)
11896 goto done;
11898 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11899 if (error)
11900 goto done;
11902 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11903 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11904 "specified branch has already been integrated");
11905 got_worktree_integrate_abort(worktree, fileindex, repo,
11906 branch_ref, base_branch_ref);
11907 goto done;
11910 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11911 if (error) {
11912 if (error->code == GOT_ERR_ANCESTRY)
11913 error = got_error(GOT_ERR_REBASE_REQUIRED);
11914 got_worktree_integrate_abort(worktree, fileindex, repo,
11915 branch_ref, base_branch_ref);
11916 goto done;
11919 memset(&upa, 0, sizeof(upa));
11920 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11921 branch_ref, base_branch_ref, update_progress, &upa,
11922 check_cancelled, NULL);
11923 if (error)
11924 goto done;
11926 printf("Integrated %s into %s\n", refname, base_refname);
11927 print_update_progress_stats(&upa);
11928 done:
11929 if (repo) {
11930 const struct got_error *close_err = got_repo_close(repo);
11931 if (error == NULL)
11932 error = close_err;
11934 if (worktree)
11935 got_worktree_close(worktree);
11936 if (pack_fds) {
11937 const struct got_error *pack_err =
11938 got_repo_pack_fds_close(pack_fds);
11939 if (error == NULL)
11940 error = pack_err;
11942 free(cwd);
11943 free(base_commit_id);
11944 free(commit_id);
11945 free(refname);
11946 free(base_refname);
11947 return error;
11950 __dead static void
11951 usage_merge(void)
11953 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11954 getprogname());
11955 exit(1);
11958 static const struct got_error *
11959 cmd_merge(int argc, char *argv[])
11961 const struct got_error *error = NULL;
11962 struct got_worktree *worktree = NULL;
11963 struct got_repository *repo = NULL;
11964 struct got_fileindex *fileindex = NULL;
11965 char *cwd = NULL, *id_str = NULL, *author = NULL;
11966 struct got_reference *branch = NULL, *wt_branch = NULL;
11967 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11968 struct got_object_id *wt_branch_tip = NULL;
11969 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11970 int interrupt_merge = 0;
11971 struct got_update_progress_arg upa;
11972 struct got_object_id *merge_commit_id = NULL;
11973 char *branch_name = NULL;
11974 int *pack_fds = NULL;
11976 memset(&upa, 0, sizeof(upa));
11978 while ((ch = getopt(argc, argv, "acn")) != -1) {
11979 switch (ch) {
11980 case 'a':
11981 abort_merge = 1;
11982 break;
11983 case 'c':
11984 continue_merge = 1;
11985 break;
11986 case 'n':
11987 interrupt_merge = 1;
11988 break;
11989 default:
11990 usage_rebase();
11991 /* NOTREACHED */
11995 argc -= optind;
11996 argv += optind;
11998 #ifndef PROFILE
11999 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12000 "unveil", NULL) == -1)
12001 err(1, "pledge");
12002 #endif
12004 if (abort_merge && continue_merge)
12005 option_conflict('a', 'c');
12006 if (abort_merge || continue_merge) {
12007 if (argc != 0)
12008 usage_merge();
12009 } else if (argc != 1)
12010 usage_merge();
12012 cwd = getcwd(NULL, 0);
12013 if (cwd == NULL) {
12014 error = got_error_from_errno("getcwd");
12015 goto done;
12018 error = got_repo_pack_fds_open(&pack_fds);
12019 if (error != NULL)
12020 goto done;
12022 error = got_worktree_open(&worktree, cwd);
12023 if (error) {
12024 if (error->code == GOT_ERR_NOT_WORKTREE)
12025 error = wrap_not_worktree_error(error,
12026 "merge", cwd);
12027 goto done;
12030 error = got_repo_open(&repo,
12031 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12032 pack_fds);
12033 if (error != NULL)
12034 goto done;
12036 error = apply_unveil(got_repo_get_path(repo), 0,
12037 worktree ? got_worktree_get_root_path(worktree) : NULL);
12038 if (error)
12039 goto done;
12041 error = check_rebase_or_histedit_in_progress(worktree);
12042 if (error)
12043 goto done;
12045 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12046 repo);
12047 if (error)
12048 goto done;
12050 if (abort_merge) {
12051 if (!merge_in_progress) {
12052 error = got_error(GOT_ERR_NOT_MERGING);
12053 goto done;
12055 error = got_worktree_merge_continue(&branch_name,
12056 &branch_tip, &fileindex, worktree, repo);
12057 if (error)
12058 goto done;
12059 error = got_worktree_merge_abort(worktree, fileindex, repo,
12060 abort_progress, &upa);
12061 if (error)
12062 goto done;
12063 printf("Merge of %s aborted\n", branch_name);
12064 goto done; /* nothing else to do */
12067 error = get_author(&author, repo, worktree);
12068 if (error)
12069 goto done;
12071 if (continue_merge) {
12072 if (!merge_in_progress) {
12073 error = got_error(GOT_ERR_NOT_MERGING);
12074 goto done;
12076 error = got_worktree_merge_continue(&branch_name,
12077 &branch_tip, &fileindex, worktree, repo);
12078 if (error)
12079 goto done;
12080 } else {
12081 error = got_ref_open(&branch, repo, argv[0], 0);
12082 if (error != NULL)
12083 goto done;
12084 branch_name = strdup(got_ref_get_name(branch));
12085 if (branch_name == NULL) {
12086 error = got_error_from_errno("strdup");
12087 goto done;
12089 error = got_ref_resolve(&branch_tip, repo, branch);
12090 if (error)
12091 goto done;
12094 error = got_ref_open(&wt_branch, repo,
12095 got_worktree_get_head_ref_name(worktree), 0);
12096 if (error)
12097 goto done;
12098 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12099 if (error)
12100 goto done;
12101 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12102 wt_branch_tip, branch_tip, 0, repo,
12103 check_cancelled, NULL);
12104 if (error && error->code != GOT_ERR_ANCESTRY)
12105 goto done;
12107 if (!continue_merge) {
12108 error = check_path_prefix(wt_branch_tip, branch_tip,
12109 got_worktree_get_path_prefix(worktree),
12110 GOT_ERR_MERGE_PATH, repo);
12111 if (error)
12112 goto done;
12113 if (yca_id) {
12114 error = check_same_branch(wt_branch_tip, branch,
12115 yca_id, repo);
12116 if (error) {
12117 if (error->code != GOT_ERR_ANCESTRY)
12118 goto done;
12119 error = NULL;
12120 } else {
12121 static char msg[512];
12122 snprintf(msg, sizeof(msg),
12123 "cannot create a merge commit because "
12124 "%s is based on %s; %s can be integrated "
12125 "with 'got integrate' instead", branch_name,
12126 got_worktree_get_head_ref_name(worktree),
12127 branch_name);
12128 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12129 goto done;
12132 error = got_worktree_merge_prepare(&fileindex, worktree,
12133 branch, repo);
12134 if (error)
12135 goto done;
12137 error = got_worktree_merge_branch(worktree, fileindex,
12138 yca_id, branch_tip, repo, update_progress, &upa,
12139 check_cancelled, NULL);
12140 if (error)
12141 goto done;
12142 print_merge_progress_stats(&upa);
12143 if (!upa.did_something) {
12144 error = got_worktree_merge_abort(worktree, fileindex,
12145 repo, abort_progress, &upa);
12146 if (error)
12147 goto done;
12148 printf("Already up-to-date\n");
12149 goto done;
12153 if (interrupt_merge) {
12154 error = got_worktree_merge_postpone(worktree, fileindex);
12155 if (error)
12156 goto done;
12157 printf("Merge of %s interrupted on request\n", branch_name);
12158 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12159 upa.not_deleted > 0 || upa.unversioned > 0) {
12160 error = got_worktree_merge_postpone(worktree, fileindex);
12161 if (error)
12162 goto done;
12163 if (upa.conflicts > 0 && upa.missing == 0 &&
12164 upa.not_deleted == 0 && upa.unversioned == 0) {
12165 error = got_error_msg(GOT_ERR_CONFLICTS,
12166 "conflicts must be resolved before merging "
12167 "can continue");
12168 } else if (upa.conflicts > 0) {
12169 error = got_error_msg(GOT_ERR_CONFLICTS,
12170 "conflicts must be resolved before merging "
12171 "can continue; changes destined for some "
12172 "files were not yet merged and "
12173 "should be merged manually if required before the "
12174 "merge operation is continued");
12175 } else {
12176 error = got_error_msg(GOT_ERR_CONFLICTS,
12177 "changes destined for some "
12178 "files were not yet merged and should be "
12179 "merged manually if required before the "
12180 "merge operation is continued");
12182 goto done;
12183 } else {
12184 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12185 fileindex, author, NULL, 1, branch_tip, branch_name,
12186 repo, continue_merge ? print_status : NULL, NULL);
12187 if (error)
12188 goto done;
12189 error = got_worktree_merge_complete(worktree, fileindex, repo);
12190 if (error)
12191 goto done;
12192 error = got_object_id_str(&id_str, merge_commit_id);
12193 if (error)
12194 goto done;
12195 printf("Merged %s into %s: %s\n", branch_name,
12196 got_worktree_get_head_ref_name(worktree),
12197 id_str);
12200 done:
12201 free(id_str);
12202 free(merge_commit_id);
12203 free(author);
12204 free(branch_tip);
12205 free(branch_name);
12206 free(yca_id);
12207 if (branch)
12208 got_ref_close(branch);
12209 if (wt_branch)
12210 got_ref_close(wt_branch);
12211 if (worktree)
12212 got_worktree_close(worktree);
12213 if (repo) {
12214 const struct got_error *close_err = got_repo_close(repo);
12215 if (error == NULL)
12216 error = close_err;
12218 if (pack_fds) {
12219 const struct got_error *pack_err =
12220 got_repo_pack_fds_close(pack_fds);
12221 if (error == NULL)
12222 error = pack_err;
12224 return error;
12227 __dead static void
12228 usage_stage(void)
12230 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12231 "[-S] [file-path ...]\n",
12232 getprogname());
12233 exit(1);
12236 static const struct got_error *
12237 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12238 const char *path, struct got_object_id *blob_id,
12239 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12240 int dirfd, const char *de_name)
12242 const struct got_error *err = NULL;
12243 char *id_str = NULL;
12245 if (staged_status != GOT_STATUS_ADD &&
12246 staged_status != GOT_STATUS_MODIFY &&
12247 staged_status != GOT_STATUS_DELETE)
12248 return NULL;
12250 if (staged_status == GOT_STATUS_ADD ||
12251 staged_status == GOT_STATUS_MODIFY)
12252 err = got_object_id_str(&id_str, staged_blob_id);
12253 else
12254 err = got_object_id_str(&id_str, blob_id);
12255 if (err)
12256 return err;
12258 printf("%s %c %s\n", id_str, staged_status, path);
12259 free(id_str);
12260 return NULL;
12263 static const struct got_error *
12264 cmd_stage(int argc, char *argv[])
12266 const struct got_error *error = NULL;
12267 struct got_repository *repo = NULL;
12268 struct got_worktree *worktree = NULL;
12269 char *cwd = NULL;
12270 struct got_pathlist_head paths;
12271 struct got_pathlist_entry *pe;
12272 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12273 FILE *patch_script_file = NULL;
12274 const char *patch_script_path = NULL;
12275 struct choose_patch_arg cpa;
12276 int *pack_fds = NULL;
12278 TAILQ_INIT(&paths);
12280 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12281 switch (ch) {
12282 case 'l':
12283 list_stage = 1;
12284 break;
12285 case 'p':
12286 pflag = 1;
12287 break;
12288 case 'F':
12289 patch_script_path = optarg;
12290 break;
12291 case 'S':
12292 allow_bad_symlinks = 1;
12293 break;
12294 default:
12295 usage_stage();
12296 /* NOTREACHED */
12300 argc -= optind;
12301 argv += optind;
12303 #ifndef PROFILE
12304 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12305 "unveil", NULL) == -1)
12306 err(1, "pledge");
12307 #endif
12308 if (list_stage && (pflag || patch_script_path))
12309 errx(1, "-l option cannot be used with other options");
12310 if (patch_script_path && !pflag)
12311 errx(1, "-F option can only be used together with -p option");
12313 cwd = getcwd(NULL, 0);
12314 if (cwd == NULL) {
12315 error = got_error_from_errno("getcwd");
12316 goto done;
12319 error = got_repo_pack_fds_open(&pack_fds);
12320 if (error != NULL)
12321 goto done;
12323 error = got_worktree_open(&worktree, cwd);
12324 if (error) {
12325 if (error->code == GOT_ERR_NOT_WORKTREE)
12326 error = wrap_not_worktree_error(error, "stage", cwd);
12327 goto done;
12330 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12331 NULL, pack_fds);
12332 if (error != NULL)
12333 goto done;
12335 if (patch_script_path) {
12336 patch_script_file = fopen(patch_script_path, "re");
12337 if (patch_script_file == NULL) {
12338 error = got_error_from_errno2("fopen",
12339 patch_script_path);
12340 goto done;
12343 error = apply_unveil(got_repo_get_path(repo), 0,
12344 got_worktree_get_root_path(worktree));
12345 if (error)
12346 goto done;
12348 error = check_merge_in_progress(worktree, repo);
12349 if (error)
12350 goto done;
12352 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12353 if (error)
12354 goto done;
12356 if (list_stage)
12357 error = got_worktree_status(worktree, &paths, repo, 0,
12358 print_stage, NULL, check_cancelled, NULL);
12359 else {
12360 cpa.patch_script_file = patch_script_file;
12361 cpa.action = "stage";
12362 error = got_worktree_stage(worktree, &paths,
12363 pflag ? NULL : print_status, NULL,
12364 pflag ? choose_patch : NULL, &cpa,
12365 allow_bad_symlinks, repo);
12367 done:
12368 if (patch_script_file && fclose(patch_script_file) == EOF &&
12369 error == NULL)
12370 error = got_error_from_errno2("fclose", patch_script_path);
12371 if (repo) {
12372 const struct got_error *close_err = got_repo_close(repo);
12373 if (error == NULL)
12374 error = close_err;
12376 if (worktree)
12377 got_worktree_close(worktree);
12378 if (pack_fds) {
12379 const struct got_error *pack_err =
12380 got_repo_pack_fds_close(pack_fds);
12381 if (error == NULL)
12382 error = pack_err;
12384 TAILQ_FOREACH(pe, &paths, entry)
12385 free((char *)pe->path);
12386 got_pathlist_free(&paths);
12387 free(cwd);
12388 return error;
12391 __dead static void
12392 usage_unstage(void)
12394 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12395 "[file-path ...]\n",
12396 getprogname());
12397 exit(1);
12401 static const struct got_error *
12402 cmd_unstage(int argc, char *argv[])
12404 const struct got_error *error = NULL;
12405 struct got_repository *repo = NULL;
12406 struct got_worktree *worktree = NULL;
12407 char *cwd = NULL;
12408 struct got_pathlist_head paths;
12409 struct got_pathlist_entry *pe;
12410 int ch, pflag = 0;
12411 struct got_update_progress_arg upa;
12412 FILE *patch_script_file = NULL;
12413 const char *patch_script_path = NULL;
12414 struct choose_patch_arg cpa;
12415 int *pack_fds = NULL;
12417 TAILQ_INIT(&paths);
12419 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12420 switch (ch) {
12421 case 'p':
12422 pflag = 1;
12423 break;
12424 case 'F':
12425 patch_script_path = optarg;
12426 break;
12427 default:
12428 usage_unstage();
12429 /* NOTREACHED */
12433 argc -= optind;
12434 argv += optind;
12436 #ifndef PROFILE
12437 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12438 "unveil", NULL) == -1)
12439 err(1, "pledge");
12440 #endif
12441 if (patch_script_path && !pflag)
12442 errx(1, "-F option can only be used together with -p option");
12444 cwd = getcwd(NULL, 0);
12445 if (cwd == NULL) {
12446 error = got_error_from_errno("getcwd");
12447 goto done;
12450 error = got_repo_pack_fds_open(&pack_fds);
12451 if (error != NULL)
12452 goto done;
12454 error = got_worktree_open(&worktree, cwd);
12455 if (error) {
12456 if (error->code == GOT_ERR_NOT_WORKTREE)
12457 error = wrap_not_worktree_error(error, "unstage", cwd);
12458 goto done;
12461 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12462 NULL, pack_fds);
12463 if (error != NULL)
12464 goto done;
12466 if (patch_script_path) {
12467 patch_script_file = fopen(patch_script_path, "re");
12468 if (patch_script_file == NULL) {
12469 error = got_error_from_errno2("fopen",
12470 patch_script_path);
12471 goto done;
12475 error = apply_unveil(got_repo_get_path(repo), 0,
12476 got_worktree_get_root_path(worktree));
12477 if (error)
12478 goto done;
12480 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12481 if (error)
12482 goto done;
12484 cpa.patch_script_file = patch_script_file;
12485 cpa.action = "unstage";
12486 memset(&upa, 0, sizeof(upa));
12487 error = got_worktree_unstage(worktree, &paths, update_progress,
12488 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12489 if (!error)
12490 print_merge_progress_stats(&upa);
12491 done:
12492 if (patch_script_file && fclose(patch_script_file) == EOF &&
12493 error == NULL)
12494 error = got_error_from_errno2("fclose", patch_script_path);
12495 if (repo) {
12496 const struct got_error *close_err = got_repo_close(repo);
12497 if (error == NULL)
12498 error = close_err;
12500 if (worktree)
12501 got_worktree_close(worktree);
12502 if (pack_fds) {
12503 const struct got_error *pack_err =
12504 got_repo_pack_fds_close(pack_fds);
12505 if (error == NULL)
12506 error = pack_err;
12508 TAILQ_FOREACH(pe, &paths, entry)
12509 free((char *)pe->path);
12510 got_pathlist_free(&paths);
12511 free(cwd);
12512 return error;
12515 __dead static void
12516 usage_cat(void)
12518 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12519 "arg1 [arg2 ...]\n", getprogname());
12520 exit(1);
12523 static const struct got_error *
12524 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12526 const struct got_error *err;
12527 struct got_blob_object *blob;
12528 int fd = -1;
12530 fd = got_opentempfd();
12531 if (fd == -1)
12532 return got_error_from_errno("got_opentempfd");
12534 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12535 if (err)
12536 goto done;
12538 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12539 done:
12540 if (fd != -1 && close(fd) == -1 && err == NULL)
12541 err = got_error_from_errno("close");
12542 if (blob)
12543 got_object_blob_close(blob);
12544 return err;
12547 static const struct got_error *
12548 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12550 const struct got_error *err;
12551 struct got_tree_object *tree;
12552 int nentries, i;
12554 err = got_object_open_as_tree(&tree, repo, id);
12555 if (err)
12556 return err;
12558 nentries = got_object_tree_get_nentries(tree);
12559 for (i = 0; i < nentries; i++) {
12560 struct got_tree_entry *te;
12561 char *id_str;
12562 if (sigint_received || sigpipe_received)
12563 break;
12564 te = got_object_tree_get_entry(tree, i);
12565 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12566 if (err)
12567 break;
12568 fprintf(outfile, "%s %.7o %s\n", id_str,
12569 got_tree_entry_get_mode(te),
12570 got_tree_entry_get_name(te));
12571 free(id_str);
12574 got_object_tree_close(tree);
12575 return err;
12578 static const struct got_error *
12579 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12581 const struct got_error *err;
12582 struct got_commit_object *commit;
12583 const struct got_object_id_queue *parent_ids;
12584 struct got_object_qid *pid;
12585 char *id_str = NULL;
12586 const char *logmsg = NULL;
12587 char gmtoff[6];
12589 err = got_object_open_as_commit(&commit, repo, id);
12590 if (err)
12591 return err;
12593 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12594 if (err)
12595 goto done;
12597 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12598 parent_ids = got_object_commit_get_parent_ids(commit);
12599 fprintf(outfile, "numparents %d\n",
12600 got_object_commit_get_nparents(commit));
12601 STAILQ_FOREACH(pid, parent_ids, entry) {
12602 char *pid_str;
12603 err = got_object_id_str(&pid_str, &pid->id);
12604 if (err)
12605 goto done;
12606 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12607 free(pid_str);
12609 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12610 got_object_commit_get_author_gmtoff(commit));
12611 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12612 got_object_commit_get_author(commit),
12613 (long long)got_object_commit_get_author_time(commit),
12614 gmtoff);
12616 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12617 got_object_commit_get_committer_gmtoff(commit));
12618 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12619 got_object_commit_get_author(commit),
12620 (long long)got_object_commit_get_committer_time(commit),
12621 gmtoff);
12623 logmsg = got_object_commit_get_logmsg_raw(commit);
12624 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12625 fprintf(outfile, "%s", logmsg);
12626 done:
12627 free(id_str);
12628 got_object_commit_close(commit);
12629 return err;
12632 static const struct got_error *
12633 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12635 const struct got_error *err;
12636 struct got_tag_object *tag;
12637 char *id_str = NULL;
12638 const char *tagmsg = NULL;
12639 char gmtoff[6];
12641 err = got_object_open_as_tag(&tag, repo, id);
12642 if (err)
12643 return err;
12645 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12646 if (err)
12647 goto done;
12649 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12651 switch (got_object_tag_get_object_type(tag)) {
12652 case GOT_OBJ_TYPE_BLOB:
12653 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12654 GOT_OBJ_LABEL_BLOB);
12655 break;
12656 case GOT_OBJ_TYPE_TREE:
12657 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12658 GOT_OBJ_LABEL_TREE);
12659 break;
12660 case GOT_OBJ_TYPE_COMMIT:
12661 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12662 GOT_OBJ_LABEL_COMMIT);
12663 break;
12664 case GOT_OBJ_TYPE_TAG:
12665 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12666 GOT_OBJ_LABEL_TAG);
12667 break;
12668 default:
12669 break;
12672 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12673 got_object_tag_get_name(tag));
12675 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12676 got_object_tag_get_tagger_gmtoff(tag));
12677 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12678 got_object_tag_get_tagger(tag),
12679 (long long)got_object_tag_get_tagger_time(tag),
12680 gmtoff);
12682 tagmsg = got_object_tag_get_message(tag);
12683 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12684 fprintf(outfile, "%s", tagmsg);
12685 done:
12686 free(id_str);
12687 got_object_tag_close(tag);
12688 return err;
12691 static const struct got_error *
12692 cmd_cat(int argc, char *argv[])
12694 const struct got_error *error;
12695 struct got_repository *repo = NULL;
12696 struct got_worktree *worktree = NULL;
12697 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12698 const char *commit_id_str = NULL;
12699 struct got_object_id *id = NULL, *commit_id = NULL;
12700 struct got_commit_object *commit = NULL;
12701 int ch, obj_type, i, force_path = 0;
12702 struct got_reflist_head refs;
12703 int *pack_fds = NULL;
12705 TAILQ_INIT(&refs);
12707 #ifndef PROFILE
12708 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12709 NULL) == -1)
12710 err(1, "pledge");
12711 #endif
12713 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12714 switch (ch) {
12715 case 'c':
12716 commit_id_str = optarg;
12717 break;
12718 case 'r':
12719 repo_path = realpath(optarg, NULL);
12720 if (repo_path == NULL)
12721 return got_error_from_errno2("realpath",
12722 optarg);
12723 got_path_strip_trailing_slashes(repo_path);
12724 break;
12725 case 'P':
12726 force_path = 1;
12727 break;
12728 default:
12729 usage_cat();
12730 /* NOTREACHED */
12734 argc -= optind;
12735 argv += optind;
12737 cwd = getcwd(NULL, 0);
12738 if (cwd == NULL) {
12739 error = got_error_from_errno("getcwd");
12740 goto done;
12743 error = got_repo_pack_fds_open(&pack_fds);
12744 if (error != NULL)
12745 goto done;
12747 if (repo_path == NULL) {
12748 error = got_worktree_open(&worktree, cwd);
12749 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12750 goto done;
12751 if (worktree) {
12752 repo_path = strdup(
12753 got_worktree_get_repo_path(worktree));
12754 if (repo_path == NULL) {
12755 error = got_error_from_errno("strdup");
12756 goto done;
12759 /* Release work tree lock. */
12760 got_worktree_close(worktree);
12761 worktree = NULL;
12765 if (repo_path == NULL) {
12766 repo_path = strdup(cwd);
12767 if (repo_path == NULL)
12768 return got_error_from_errno("strdup");
12771 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12772 free(repo_path);
12773 if (error != NULL)
12774 goto done;
12776 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12777 if (error)
12778 goto done;
12780 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12781 if (error)
12782 goto done;
12784 if (commit_id_str == NULL)
12785 commit_id_str = GOT_REF_HEAD;
12786 error = got_repo_match_object_id(&commit_id, NULL,
12787 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12788 if (error)
12789 goto done;
12791 error = got_object_open_as_commit(&commit, repo, commit_id);
12792 if (error)
12793 goto done;
12795 for (i = 0; i < argc; i++) {
12796 if (force_path) {
12797 error = got_object_id_by_path(&id, repo, commit,
12798 argv[i]);
12799 if (error)
12800 break;
12801 } else {
12802 error = got_repo_match_object_id(&id, &label, argv[i],
12803 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12804 repo);
12805 if (error) {
12806 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12807 error->code != GOT_ERR_NOT_REF)
12808 break;
12809 error = got_object_id_by_path(&id, repo,
12810 commit, argv[i]);
12811 if (error)
12812 break;
12816 error = got_object_get_type(&obj_type, repo, id);
12817 if (error)
12818 break;
12820 switch (obj_type) {
12821 case GOT_OBJ_TYPE_BLOB:
12822 error = cat_blob(id, repo, stdout);
12823 break;
12824 case GOT_OBJ_TYPE_TREE:
12825 error = cat_tree(id, repo, stdout);
12826 break;
12827 case GOT_OBJ_TYPE_COMMIT:
12828 error = cat_commit(id, repo, stdout);
12829 break;
12830 case GOT_OBJ_TYPE_TAG:
12831 error = cat_tag(id, repo, stdout);
12832 break;
12833 default:
12834 error = got_error(GOT_ERR_OBJ_TYPE);
12835 break;
12837 if (error)
12838 break;
12839 free(label);
12840 label = NULL;
12841 free(id);
12842 id = NULL;
12844 done:
12845 free(label);
12846 free(id);
12847 free(commit_id);
12848 if (commit)
12849 got_object_commit_close(commit);
12850 if (worktree)
12851 got_worktree_close(worktree);
12852 if (repo) {
12853 const struct got_error *close_err = got_repo_close(repo);
12854 if (error == NULL)
12855 error = close_err;
12857 if (pack_fds) {
12858 const struct got_error *pack_err =
12859 got_repo_pack_fds_close(pack_fds);
12860 if (error == NULL)
12861 error = pack_err;
12864 got_ref_list_free(&refs);
12865 return error;
12868 __dead static void
12869 usage_info(void)
12871 fprintf(stderr, "usage: %s info [path ...]\n",
12872 getprogname());
12873 exit(1);
12876 static const struct got_error *
12877 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12878 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12879 struct got_object_id *commit_id)
12881 const struct got_error *err = NULL;
12882 char *id_str = NULL;
12883 char datebuf[128];
12884 struct tm mytm, *tm;
12885 struct got_pathlist_head *paths = arg;
12886 struct got_pathlist_entry *pe;
12889 * Clear error indication from any of the path arguments which
12890 * would cause this file index entry to be displayed.
12892 TAILQ_FOREACH(pe, paths, entry) {
12893 if (got_path_cmp(path, pe->path, strlen(path),
12894 pe->path_len) == 0 ||
12895 got_path_is_child(path, pe->path, pe->path_len))
12896 pe->data = NULL; /* no error */
12899 printf(GOT_COMMIT_SEP_STR);
12900 if (S_ISLNK(mode))
12901 printf("symlink: %s\n", path);
12902 else if (S_ISREG(mode)) {
12903 printf("file: %s\n", path);
12904 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12905 } else if (S_ISDIR(mode))
12906 printf("directory: %s\n", path);
12907 else
12908 printf("something: %s\n", path);
12910 tm = localtime_r(&mtime, &mytm);
12911 if (tm == NULL)
12912 return NULL;
12913 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12914 return got_error(GOT_ERR_NO_SPACE);
12915 printf("timestamp: %s\n", datebuf);
12917 if (blob_id) {
12918 err = got_object_id_str(&id_str, blob_id);
12919 if (err)
12920 return err;
12921 printf("based on blob: %s\n", id_str);
12922 free(id_str);
12925 if (staged_blob_id) {
12926 err = got_object_id_str(&id_str, staged_blob_id);
12927 if (err)
12928 return err;
12929 printf("based on staged blob: %s\n", id_str);
12930 free(id_str);
12933 if (commit_id) {
12934 err = got_object_id_str(&id_str, commit_id);
12935 if (err)
12936 return err;
12937 printf("based on commit: %s\n", id_str);
12938 free(id_str);
12941 return NULL;
12944 static const struct got_error *
12945 cmd_info(int argc, char *argv[])
12947 const struct got_error *error = NULL;
12948 struct got_worktree *worktree = NULL;
12949 char *cwd = NULL, *id_str = NULL;
12950 struct got_pathlist_head paths;
12951 struct got_pathlist_entry *pe;
12952 char *uuidstr = NULL;
12953 int ch, show_files = 0;
12954 int *pack_fds = NULL;
12956 TAILQ_INIT(&paths);
12958 while ((ch = getopt(argc, argv, "")) != -1) {
12959 switch (ch) {
12960 default:
12961 usage_info();
12962 /* NOTREACHED */
12966 argc -= optind;
12967 argv += optind;
12969 #ifndef PROFILE
12970 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12971 NULL) == -1)
12972 err(1, "pledge");
12973 #endif
12974 cwd = getcwd(NULL, 0);
12975 if (cwd == NULL) {
12976 error = got_error_from_errno("getcwd");
12977 goto done;
12980 error = got_repo_pack_fds_open(&pack_fds);
12981 if (error != NULL)
12982 goto done;
12984 error = got_worktree_open(&worktree, cwd);
12985 if (error) {
12986 if (error->code == GOT_ERR_NOT_WORKTREE)
12987 error = wrap_not_worktree_error(error, "info", cwd);
12988 goto done;
12991 #ifndef PROFILE
12992 /* Remove "cpath" promise. */
12993 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12994 NULL) == -1)
12995 err(1, "pledge");
12996 #endif
12997 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12998 if (error)
12999 goto done;
13001 if (argc >= 1) {
13002 error = get_worktree_paths_from_argv(&paths, argc, argv,
13003 worktree);
13004 if (error)
13005 goto done;
13006 show_files = 1;
13009 error = got_object_id_str(&id_str,
13010 got_worktree_get_base_commit_id(worktree));
13011 if (error)
13012 goto done;
13014 error = got_worktree_get_uuid(&uuidstr, worktree);
13015 if (error)
13016 goto done;
13018 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13019 printf("work tree base commit: %s\n", id_str);
13020 printf("work tree path prefix: %s\n",
13021 got_worktree_get_path_prefix(worktree));
13022 printf("work tree branch reference: %s\n",
13023 got_worktree_get_head_ref_name(worktree));
13024 printf("work tree UUID: %s\n", uuidstr);
13025 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13027 if (show_files) {
13028 struct got_pathlist_entry *pe;
13029 TAILQ_FOREACH(pe, &paths, entry) {
13030 if (pe->path_len == 0)
13031 continue;
13033 * Assume this path will fail. This will be corrected
13034 * in print_path_info() in case the path does suceeed.
13036 pe->data = (void *)got_error_path(pe->path,
13037 GOT_ERR_BAD_PATH);
13039 error = got_worktree_path_info(worktree, &paths,
13040 print_path_info, &paths, check_cancelled, NULL);
13041 if (error)
13042 goto done;
13043 TAILQ_FOREACH(pe, &paths, entry) {
13044 if (pe->data != NULL) {
13045 error = pe->data; /* bad path */
13046 break;
13050 done:
13051 if (pack_fds) {
13052 const struct got_error *pack_err =
13053 got_repo_pack_fds_close(pack_fds);
13054 if (error == NULL)
13055 error = pack_err;
13057 TAILQ_FOREACH(pe, &paths, entry)
13058 free((char *)pe->path);
13059 got_pathlist_free(&paths);
13060 free(cwd);
13061 free(id_str);
13062 free(uuidstr);
13063 return error;