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/time.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <libgen.h>
36 #include <time.h>
37 #include <paths.h>
38 #include <regex.h>
39 #include <getopt.h>
41 #include "got_compat.h"
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
61 #include "got_sigs.h"
62 #include "got_date.h"
64 #ifndef nitems
65 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
66 #endif
68 static volatile sig_atomic_t sigint_received;
69 static volatile sig_atomic_t sigpipe_received;
71 static void
72 catch_sigint(int signo)
73 {
74 sigint_received = 1;
75 }
77 static void
78 catch_sigpipe(int signo)
79 {
80 sigpipe_received = 1;
81 }
84 struct got_cmd {
85 const char *cmd_name;
86 const struct got_error *(*cmd_main)(int, char *[]);
87 void (*cmd_usage)(void);
88 const char *cmd_alias;
89 };
91 __dead static void usage(int, int);
92 __dead static void usage_import(void);
93 __dead static void usage_clone(void);
94 __dead static void usage_fetch(void);
95 __dead static void usage_checkout(void);
96 __dead static void usage_update(void);
97 __dead static void usage_log(void);
98 __dead static void usage_diff(void);
99 __dead static void usage_blame(void);
100 __dead static void usage_tree(void);
101 __dead static void usage_status(void);
102 __dead static void usage_ref(void);
103 __dead static void usage_branch(void);
104 __dead static void usage_tag(void);
105 __dead static void usage_add(void);
106 __dead static void usage_remove(void);
107 __dead static void usage_patch(void);
108 __dead static void usage_revert(void);
109 __dead static void usage_commit(void);
110 __dead static void usage_send(void);
111 __dead static void usage_cherrypick(void);
112 __dead static void usage_backout(void);
113 __dead static void usage_rebase(void);
114 __dead static void usage_histedit(void);
115 __dead static void usage_integrate(void);
116 __dead static void usage_merge(void);
117 __dead static void usage_stage(void);
118 __dead static void usage_unstage(void);
119 __dead static void usage_cat(void);
120 __dead static void usage_info(void);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_import(void)
349 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
350 "[-r repository-path] [-I pattern] path\n", getprogname());
351 exit(1);
354 static int
355 spawn_editor(const char *editor, const char *file)
357 pid_t pid;
358 sig_t sighup, sigint, sigquit;
359 int st = -1;
361 sighup = signal(SIGHUP, SIG_IGN);
362 sigint = signal(SIGINT, SIG_IGN);
363 sigquit = signal(SIGQUIT, SIG_IGN);
365 switch (pid = fork()) {
366 case -1:
367 goto doneediting;
368 case 0:
369 execl(editor, editor, file, (char *)NULL);
370 _exit(127);
373 while (waitpid(pid, &st, 0) == -1)
374 if (errno != EINTR)
375 break;
377 doneediting:
378 (void)signal(SIGHUP, sighup);
379 (void)signal(SIGINT, sigint);
380 (void)signal(SIGQUIT, sigquit);
382 if (!WIFEXITED(st)) {
383 errno = EINTR;
384 return -1;
387 return WEXITSTATUS(st);
390 static const struct got_error *
391 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
392 const char *initial_content, size_t initial_content_len,
393 int require_modification)
395 const struct got_error *err = NULL;
396 char *line = NULL;
397 size_t linesize = 0;
398 ssize_t linelen;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while ((linelen = getline(&line, &linesize, fp)) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static int
551 valid_author(const char *author)
553 /*
554 * Really dumb email address check; we're only doing this to
555 * avoid git's object parser breaking on commits we create.
556 */
557 while (*author && *author != '<')
558 author++;
559 if (*author != '<')
560 return 0;
561 while (*author && *author != '@')
562 author++;
563 if (*author != '@')
564 return 0;
565 while (*author && *author != '>')
566 author++;
567 return *author == '>';
570 static const struct got_error *
571 get_author(char **author, struct got_repository *repo,
572 struct got_worktree *worktree)
574 const struct got_error *err = NULL;
575 const char *got_author = NULL, *name, *email;
576 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
578 *author = NULL;
580 if (worktree)
581 worktree_conf = got_worktree_get_gotconfig(worktree);
582 repo_conf = got_repo_get_gotconfig(repo);
584 /*
585 * Priority of potential author information sources, from most
586 * significant to least significant:
587 * 1) work tree's .got/got.conf file
588 * 2) repository's got.conf file
589 * 3) repository's git config file
590 * 4) environment variables
591 * 5) global git config files (in user's home directory or /etc)
592 */
594 if (worktree_conf)
595 got_author = got_gotconfig_get_author(worktree_conf);
596 if (got_author == NULL)
597 got_author = got_gotconfig_get_author(repo_conf);
598 if (got_author == NULL) {
599 name = got_repo_get_gitconfig_author_name(repo);
600 email = got_repo_get_gitconfig_author_email(repo);
601 if (name && email) {
602 if (asprintf(author, "%s <%s>", name, email) == -1)
603 return got_error_from_errno("asprintf");
604 return NULL;
607 got_author = getenv("GOT_AUTHOR");
608 if (got_author == NULL) {
609 name = got_repo_get_global_gitconfig_author_name(repo);
610 email = got_repo_get_global_gitconfig_author_email(
611 repo);
612 if (name && email) {
613 if (asprintf(author, "%s <%s>", name, email)
614 == -1)
615 return got_error_from_errno("asprintf");
616 return NULL;
618 /* TODO: Look up user in password database? */
619 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
623 *author = strdup(got_author);
624 if (*author == NULL)
625 return got_error_from_errno("strdup");
627 if (!valid_author(*author)) {
628 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
629 free(*author);
630 *author = NULL;
632 return err;
635 static const struct got_error *
636 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
637 struct got_worktree *worktree)
639 const char *got_allowed_signers = NULL;
640 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
642 *allowed_signers = NULL;
644 if (worktree)
645 worktree_conf = got_worktree_get_gotconfig(worktree);
646 repo_conf = got_repo_get_gotconfig(repo);
648 /*
649 * Priority of potential author information sources, from most
650 * significant to least significant:
651 * 1) work tree's .got/got.conf file
652 * 2) repository's got.conf file
653 */
655 if (worktree_conf)
656 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
657 worktree_conf);
658 if (got_allowed_signers == NULL)
659 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
660 repo_conf);
662 if (got_allowed_signers) {
663 *allowed_signers = strdup(got_allowed_signers);
664 if (*allowed_signers == NULL)
665 return got_error_from_errno("strdup");
667 return NULL;
670 static const struct got_error *
671 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
672 struct got_worktree *worktree)
674 const char *got_revoked_signers = NULL;
675 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
677 *revoked_signers = NULL;
679 if (worktree)
680 worktree_conf = got_worktree_get_gotconfig(worktree);
681 repo_conf = got_repo_get_gotconfig(repo);
683 /*
684 * Priority of potential author information sources, from most
685 * significant to least significant:
686 * 1) work tree's .got/got.conf file
687 * 2) repository's got.conf file
688 */
690 if (worktree_conf)
691 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
692 worktree_conf);
693 if (got_revoked_signers == NULL)
694 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
695 repo_conf);
697 if (got_revoked_signers) {
698 *revoked_signers = strdup(got_revoked_signers);
699 if (*revoked_signers == NULL)
700 return got_error_from_errno("strdup");
702 return NULL;
705 static const struct got_error *
706 get_signer_id(char **signer_id, struct got_repository *repo,
707 struct got_worktree *worktree)
709 const char *got_signer_id = NULL;
710 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
712 *signer_id = NULL;
714 if (worktree)
715 worktree_conf = got_worktree_get_gotconfig(worktree);
716 repo_conf = got_repo_get_gotconfig(repo);
718 /*
719 * Priority of potential author information sources, from most
720 * significant to least significant:
721 * 1) work tree's .got/got.conf file
722 * 2) repository's got.conf file
723 */
725 if (worktree_conf)
726 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
727 if (got_signer_id == NULL)
728 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
730 if (got_signer_id) {
731 *signer_id = strdup(got_signer_id);
732 if (*signer_id == NULL)
733 return got_error_from_errno("strdup");
735 return NULL;
738 static const struct got_error *
739 get_gitconfig_path(char **gitconfig_path)
741 const char *homedir = getenv("HOME");
743 *gitconfig_path = NULL;
744 if (homedir) {
745 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
746 return got_error_from_errno("asprintf");
749 return NULL;
752 static const struct got_error *
753 cmd_import(int argc, char *argv[])
755 const struct got_error *error = NULL;
756 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
757 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
758 const char *branch_name = "main";
759 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
760 struct got_repository *repo = NULL;
761 struct got_reference *branch_ref = NULL, *head_ref = NULL;
762 struct got_object_id *new_commit_id = NULL;
763 int ch;
764 struct got_pathlist_head ignores;
765 struct got_pathlist_entry *pe;
766 int preserve_logmsg = 0;
767 int *pack_fds = NULL;
769 TAILQ_INIT(&ignores);
771 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
772 switch (ch) {
773 case 'b':
774 branch_name = optarg;
775 break;
776 case 'm':
777 logmsg = strdup(optarg);
778 if (logmsg == NULL) {
779 error = got_error_from_errno("strdup");
780 goto done;
782 break;
783 case 'r':
784 repo_path = realpath(optarg, NULL);
785 if (repo_path == NULL) {
786 error = got_error_from_errno2("realpath",
787 optarg);
788 goto done;
790 break;
791 case 'I':
792 if (optarg[0] == '\0')
793 break;
794 error = got_pathlist_insert(&pe, &ignores, optarg,
795 NULL);
796 if (error)
797 goto done;
798 break;
799 default:
800 usage_import();
801 /* NOTREACHED */
805 argc -= optind;
806 argv += optind;
808 #ifndef PROFILE
809 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
810 "unveil",
811 NULL) == -1)
812 err(1, "pledge");
813 #endif
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
846 error = got_error_from_errno("asprintf");
847 goto done;
850 error = got_ref_open(&branch_ref, repo, refname, 0);
851 if (error) {
852 if (error->code != GOT_ERR_NOT_REF)
853 goto done;
854 } else {
855 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
856 "import target branch already exists");
857 goto done;
860 path_dir = realpath(argv[0], NULL);
861 if (path_dir == NULL) {
862 error = got_error_from_errno2("realpath", argv[0]);
863 goto done;
865 got_path_strip_trailing_slashes(path_dir);
867 /*
868 * unveil(2) traverses exec(2); if an editor is used we have
869 * to apply unveil after the log message has been written.
870 */
871 if (logmsg == NULL || strlen(logmsg) == 0) {
872 error = get_editor(&editor);
873 if (error)
874 goto done;
875 free(logmsg);
876 error = collect_import_msg(&logmsg, &logmsg_path, editor,
877 path_dir, refname);
878 if (error) {
879 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
880 logmsg_path != NULL)
881 preserve_logmsg = 1;
882 goto done;
886 if (unveil(path_dir, "r") != 0) {
887 error = got_error_from_errno2("unveil", path_dir);
888 if (logmsg_path)
889 preserve_logmsg = 1;
890 goto done;
893 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
894 if (error) {
895 if (logmsg_path)
896 preserve_logmsg = 1;
897 goto done;
900 error = got_repo_import(&new_commit_id, path_dir, logmsg,
901 author, &ignores, repo, import_progress, NULL);
902 if (error) {
903 if (logmsg_path)
904 preserve_logmsg = 1;
905 goto done;
908 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
909 if (error) {
910 if (logmsg_path)
911 preserve_logmsg = 1;
912 goto done;
915 error = got_ref_write(branch_ref, repo);
916 if (error) {
917 if (logmsg_path)
918 preserve_logmsg = 1;
919 goto done;
922 error = got_object_id_str(&id_str, new_commit_id);
923 if (error) {
924 if (logmsg_path)
925 preserve_logmsg = 1;
926 goto done;
929 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
930 if (error) {
931 if (error->code != GOT_ERR_NOT_REF) {
932 if (logmsg_path)
933 preserve_logmsg = 1;
934 goto done;
937 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
938 branch_ref);
939 if (error) {
940 if (logmsg_path)
941 preserve_logmsg = 1;
942 goto done;
945 error = got_ref_write(head_ref, repo);
946 if (error) {
947 if (logmsg_path)
948 preserve_logmsg = 1;
949 goto done;
953 printf("Created branch %s with commit %s\n",
954 got_ref_get_name(branch_ref), id_str);
955 done:
956 if (pack_fds) {
957 const struct got_error *pack_err =
958 got_repo_pack_fds_close(pack_fds);
959 if (error == NULL)
960 error = pack_err;
962 if (preserve_logmsg) {
963 fprintf(stderr, "%s: log message preserved in %s\n",
964 getprogname(), logmsg_path);
965 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
966 error = got_error_from_errno2("unlink", logmsg_path);
967 free(logmsg);
968 free(logmsg_path);
969 free(repo_path);
970 free(editor);
971 free(refname);
972 free(new_commit_id);
973 free(id_str);
974 free(author);
975 free(gitconfig_path);
976 if (branch_ref)
977 got_ref_close(branch_ref);
978 if (head_ref)
979 got_ref_close(head_ref);
980 return error;
983 __dead static void
984 usage_clone(void)
986 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
987 "[-R reference] repository-url [directory]\n", getprogname());
988 exit(1);
991 struct got_fetch_progress_arg {
992 char last_scaled_size[FMT_SCALED_STRSIZE];
993 int last_p_indexed;
994 int last_p_resolved;
995 int verbosity;
997 struct got_repository *repo;
999 int create_configs;
1000 int configs_created;
1001 struct {
1002 struct got_pathlist_head *symrefs;
1003 struct got_pathlist_head *wanted_branches;
1004 struct got_pathlist_head *wanted_refs;
1005 const char *proto;
1006 const char *host;
1007 const char *port;
1008 const char *remote_repo_path;
1009 const char *git_url;
1010 int fetch_all_branches;
1011 int mirror_references;
1012 } config_info;
1015 /* XXX forward declaration */
1016 static const struct got_error *
1017 create_config_files(const char *proto, const char *host, const char *port,
1018 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1019 int mirror_references, struct got_pathlist_head *symrefs,
1020 struct got_pathlist_head *wanted_branches,
1021 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1023 static const struct got_error *
1024 fetch_progress(void *arg, const char *message, off_t packfile_size,
1025 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1027 const struct got_error *err = NULL;
1028 struct got_fetch_progress_arg *a = arg;
1029 char scaled_size[FMT_SCALED_STRSIZE];
1030 int p_indexed, p_resolved;
1031 int print_size = 0, print_indexed = 0, print_resolved = 0;
1034 * In order to allow a failed clone to be resumed with 'got fetch'
1035 * we try to create configuration files as soon as possible.
1036 * Once the server has sent information about its default branch
1037 * we have all required information.
1039 if (a->create_configs && !a->configs_created &&
1040 !TAILQ_EMPTY(a->config_info.symrefs)) {
1041 err = create_config_files(a->config_info.proto,
1042 a->config_info.host, a->config_info.port,
1043 a->config_info.remote_repo_path,
1044 a->config_info.git_url,
1045 a->config_info.fetch_all_branches,
1046 a->config_info.mirror_references,
1047 a->config_info.symrefs,
1048 a->config_info.wanted_branches,
1049 a->config_info.wanted_refs, a->repo);
1050 if (err)
1051 return err;
1052 a->configs_created = 1;
1055 if (a->verbosity < 0)
1056 return NULL;
1058 if (message && message[0] != '\0') {
1059 printf("\rserver: %s", message);
1060 fflush(stdout);
1061 return NULL;
1064 if (packfile_size > 0 || nobj_indexed > 0) {
1065 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1066 (a->last_scaled_size[0] == '\0' ||
1067 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1068 print_size = 1;
1069 if (strlcpy(a->last_scaled_size, scaled_size,
1070 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1071 return got_error(GOT_ERR_NO_SPACE);
1073 if (nobj_indexed > 0) {
1074 p_indexed = (nobj_indexed * 100) / nobj_total;
1075 if (p_indexed != a->last_p_indexed) {
1076 a->last_p_indexed = p_indexed;
1077 print_indexed = 1;
1078 print_size = 1;
1081 if (nobj_resolved > 0) {
1082 p_resolved = (nobj_resolved * 100) /
1083 (nobj_total - nobj_loose);
1084 if (p_resolved != a->last_p_resolved) {
1085 a->last_p_resolved = p_resolved;
1086 print_resolved = 1;
1087 print_indexed = 1;
1088 print_size = 1;
1093 if (print_size || print_indexed || print_resolved)
1094 printf("\r");
1095 if (print_size)
1096 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1097 if (print_indexed)
1098 printf("; indexing %d%%", p_indexed);
1099 if (print_resolved)
1100 printf("; resolving deltas %d%%", p_resolved);
1101 if (print_size || print_indexed || print_resolved)
1102 fflush(stdout);
1104 return NULL;
1107 static const struct got_error *
1108 create_symref(const char *refname, struct got_reference *target_ref,
1109 int verbosity, struct got_repository *repo)
1111 const struct got_error *err;
1112 struct got_reference *head_symref;
1114 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1115 if (err)
1116 return err;
1118 err = got_ref_write(head_symref, repo);
1119 if (err == NULL && verbosity > 0) {
1120 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1121 got_ref_get_name(target_ref));
1123 got_ref_close(head_symref);
1124 return err;
1127 static const struct got_error *
1128 list_remote_refs(struct got_pathlist_head *symrefs,
1129 struct got_pathlist_head *refs)
1131 const struct got_error *err;
1132 struct got_pathlist_entry *pe;
1134 TAILQ_FOREACH(pe, symrefs, entry) {
1135 const char *refname = pe->path;
1136 const char *targetref = pe->data;
1138 printf("%s: %s\n", refname, targetref);
1141 TAILQ_FOREACH(pe, refs, entry) {
1142 const char *refname = pe->path;
1143 struct got_object_id *id = pe->data;
1144 char *id_str;
1146 err = got_object_id_str(&id_str, id);
1147 if (err)
1148 return err;
1149 printf("%s: %s\n", refname, id_str);
1150 free(id_str);
1153 return NULL;
1156 static const struct got_error *
1157 create_ref(const char *refname, struct got_object_id *id,
1158 int verbosity, struct got_repository *repo)
1160 const struct got_error *err = NULL;
1161 struct got_reference *ref;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1168 err = got_ref_alloc(&ref, refname, id);
1169 if (err)
1170 goto done;
1172 err = got_ref_write(ref, repo);
1173 got_ref_close(ref);
1175 if (err == NULL && verbosity >= 0)
1176 printf("Created reference %s: %s\n", refname, id_str);
1177 done:
1178 free(id_str);
1179 return err;
1182 static int
1183 match_wanted_ref(const char *refname, const char *wanted_ref)
1185 if (strncmp(refname, "refs/", 5) != 0)
1186 return 0;
1187 refname += 5;
1190 * Prevent fetching of references that won't make any
1191 * sense outside of the remote repository's context.
1193 if (strncmp(refname, "got/", 4) == 0)
1194 return 0;
1195 if (strncmp(refname, "remotes/", 8) == 0)
1196 return 0;
1198 if (strncmp(wanted_ref, "refs/", 5) == 0)
1199 wanted_ref += 5;
1201 /* Allow prefix match. */
1202 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1203 return 1;
1205 /* Allow exact match. */
1206 return (strcmp(refname, wanted_ref) == 0);
1209 static int
1210 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1212 struct got_pathlist_entry *pe;
1214 TAILQ_FOREACH(pe, wanted_refs, entry) {
1215 if (match_wanted_ref(refname, pe->path))
1216 return 1;
1219 return 0;
1222 static const struct got_error *
1223 create_wanted_ref(const char *refname, struct got_object_id *id,
1224 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1226 const struct got_error *err;
1227 char *remote_refname;
1229 if (strncmp("refs/", refname, 5) == 0)
1230 refname += 5;
1232 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1233 remote_repo_name, refname) == -1)
1234 return got_error_from_errno("asprintf");
1236 err = create_ref(remote_refname, id, verbosity, repo);
1237 free(remote_refname);
1238 return err;
1241 static const struct got_error *
1242 create_gotconfig(const char *proto, const char *host, const char *port,
1243 const char *remote_repo_path, const char *default_branch,
1244 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1245 struct got_pathlist_head *wanted_refs, int mirror_references,
1246 struct got_repository *repo)
1248 const struct got_error *err = NULL;
1249 char *gotconfig_path = NULL;
1250 char *gotconfig = NULL;
1251 FILE *gotconfig_file = NULL;
1252 const char *branchname = NULL;
1253 char *branches = NULL, *refs = NULL;
1254 ssize_t n;
1256 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1257 struct got_pathlist_entry *pe;
1258 TAILQ_FOREACH(pe, wanted_branches, entry) {
1259 char *s;
1260 branchname = pe->path;
1261 if (strncmp(branchname, "refs/heads/", 11) == 0)
1262 branchname += 11;
1263 if (asprintf(&s, "%s\"%s\" ",
1264 branches ? branches : "", branchname) == -1) {
1265 err = got_error_from_errno("asprintf");
1266 goto done;
1268 free(branches);
1269 branches = s;
1271 } else if (!fetch_all_branches && default_branch) {
1272 branchname = default_branch;
1273 if (strncmp(branchname, "refs/heads/", 11) == 0)
1274 branchname += 11;
1275 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1276 err = got_error_from_errno("asprintf");
1277 goto done;
1280 if (!TAILQ_EMPTY(wanted_refs)) {
1281 struct got_pathlist_entry *pe;
1282 TAILQ_FOREACH(pe, wanted_refs, entry) {
1283 char *s;
1284 const char *refname = pe->path;
1285 if (strncmp(refname, "refs/", 5) == 0)
1286 branchname += 5;
1287 if (asprintf(&s, "%s\"%s\" ",
1288 refs ? refs : "", refname) == -1) {
1289 err = got_error_from_errno("asprintf");
1290 goto done;
1292 free(refs);
1293 refs = s;
1297 /* Create got.conf(5). */
1298 gotconfig_path = got_repo_get_path_gotconfig(repo);
1299 if (gotconfig_path == NULL) {
1300 err = got_error_from_errno("got_repo_get_path_gotconfig");
1301 goto done;
1303 gotconfig_file = fopen(gotconfig_path, "ae");
1304 if (gotconfig_file == NULL) {
1305 err = got_error_from_errno2("fopen", gotconfig_path);
1306 goto done;
1308 if (asprintf(&gotconfig,
1309 "remote \"%s\" {\n"
1310 "\tserver %s\n"
1311 "\tprotocol %s\n"
1312 "%s%s%s"
1313 "\trepository \"%s\"\n"
1314 "%s%s%s"
1315 "%s%s%s"
1316 "%s"
1317 "%s"
1318 "}\n",
1319 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1320 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1321 remote_repo_path, branches ? "\tbranch { " : "",
1322 branches ? branches : "", branches ? "}\n" : "",
1323 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1324 mirror_references ? "\tmirror_references yes\n" : "",
1325 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1326 err = got_error_from_errno("asprintf");
1327 goto done;
1329 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1330 if (n != strlen(gotconfig)) {
1331 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1332 goto done;
1335 done:
1336 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1337 err = got_error_from_errno2("fclose", gotconfig_path);
1338 free(gotconfig_path);
1339 free(branches);
1340 return err;
1343 static const struct got_error *
1344 create_gitconfig(const char *git_url, const char *default_branch,
1345 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1346 struct got_pathlist_head *wanted_refs, int mirror_references,
1347 struct got_repository *repo)
1349 const struct got_error *err = NULL;
1350 char *gitconfig_path = NULL;
1351 char *gitconfig = NULL;
1352 FILE *gitconfig_file = NULL;
1353 char *branches = NULL, *refs = NULL;
1354 const char *branchname;
1355 ssize_t n;
1357 /* Create a config file Git can understand. */
1358 gitconfig_path = got_repo_get_path_gitconfig(repo);
1359 if (gitconfig_path == NULL) {
1360 err = got_error_from_errno("got_repo_get_path_gitconfig");
1361 goto done;
1363 gitconfig_file = fopen(gitconfig_path, "ae");
1364 if (gitconfig_file == NULL) {
1365 err = got_error_from_errno2("fopen", gitconfig_path);
1366 goto done;
1368 if (fetch_all_branches) {
1369 if (mirror_references) {
1370 if (asprintf(&branches,
1371 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1372 err = got_error_from_errno("asprintf");
1373 goto done;
1375 } else if (asprintf(&branches,
1376 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1377 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1378 err = got_error_from_errno("asprintf");
1379 goto done;
1381 } else if (!TAILQ_EMPTY(wanted_branches)) {
1382 struct got_pathlist_entry *pe;
1383 TAILQ_FOREACH(pe, wanted_branches, entry) {
1384 char *s;
1385 branchname = pe->path;
1386 if (strncmp(branchname, "refs/heads/", 11) == 0)
1387 branchname += 11;
1388 if (mirror_references) {
1389 if (asprintf(&s,
1390 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1391 branches ? branches : "",
1392 branchname, branchname) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 } else if (asprintf(&s,
1397 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1398 branches ? branches : "",
1399 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1400 branchname) == -1) {
1401 err = got_error_from_errno("asprintf");
1402 goto done;
1404 free(branches);
1405 branches = s;
1407 } else {
1409 * If the server specified a default branch, use just that one.
1410 * Otherwise fall back to fetching all branches on next fetch.
1412 if (default_branch) {
1413 branchname = default_branch;
1414 if (strncmp(branchname, "refs/heads/", 11) == 0)
1415 branchname += 11;
1416 } else
1417 branchname = "*"; /* fall back to all branches */
1418 if (mirror_references) {
1419 if (asprintf(&branches,
1420 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1421 branchname, branchname) == -1) {
1422 err = got_error_from_errno("asprintf");
1423 goto done;
1425 } else if (asprintf(&branches,
1426 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1427 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1428 branchname) == -1) {
1429 err = got_error_from_errno("asprintf");
1430 goto done;
1433 if (!TAILQ_EMPTY(wanted_refs)) {
1434 struct got_pathlist_entry *pe;
1435 TAILQ_FOREACH(pe, wanted_refs, entry) {
1436 char *s;
1437 const char *refname = pe->path;
1438 if (strncmp(refname, "refs/", 5) == 0)
1439 refname += 5;
1440 if (mirror_references) {
1441 if (asprintf(&s,
1442 "%s\tfetch = refs/%s:refs/%s\n",
1443 refs ? refs : "", refname, refname) == -1) {
1444 err = got_error_from_errno("asprintf");
1445 goto done;
1447 } else if (asprintf(&s,
1448 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1449 refs ? refs : "",
1450 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1451 refname) == -1) {
1452 err = got_error_from_errno("asprintf");
1453 goto done;
1455 free(refs);
1456 refs = s;
1460 if (asprintf(&gitconfig,
1461 "[remote \"%s\"]\n"
1462 "\turl = %s\n"
1463 "%s"
1464 "%s"
1465 "\tfetch = refs/tags/*:refs/tags/*\n",
1466 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1467 refs ? refs : "") == -1) {
1468 err = got_error_from_errno("asprintf");
1469 goto done;
1471 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1472 if (n != strlen(gitconfig)) {
1473 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1474 goto done;
1476 done:
1477 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1478 err = got_error_from_errno2("fclose", gitconfig_path);
1479 free(gitconfig_path);
1480 free(branches);
1481 return err;
1484 static const struct got_error *
1485 create_config_files(const char *proto, const char *host, const char *port,
1486 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1487 int mirror_references, struct got_pathlist_head *symrefs,
1488 struct got_pathlist_head *wanted_branches,
1489 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1491 const struct got_error *err = NULL;
1492 const char *default_branch = NULL;
1493 struct got_pathlist_entry *pe;
1496 * If we asked for a set of wanted branches then use the first
1497 * one of those.
1499 if (!TAILQ_EMPTY(wanted_branches)) {
1500 pe = TAILQ_FIRST(wanted_branches);
1501 default_branch = pe->path;
1502 } else {
1503 /* First HEAD ref listed by server is the default branch. */
1504 TAILQ_FOREACH(pe, symrefs, entry) {
1505 const char *refname = pe->path;
1506 const char *target = pe->data;
1508 if (strcmp(refname, GOT_REF_HEAD) != 0)
1509 continue;
1511 default_branch = target;
1512 break;
1516 /* Create got.conf(5). */
1517 err = create_gotconfig(proto, host, port, remote_repo_path,
1518 default_branch, fetch_all_branches, wanted_branches,
1519 wanted_refs, mirror_references, repo);
1520 if (err)
1521 return err;
1523 /* Create a config file Git can understand. */
1524 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1525 wanted_branches, wanted_refs, mirror_references, repo);
1528 static const struct got_error *
1529 cmd_clone(int argc, char *argv[])
1531 const struct got_error *error = NULL;
1532 const char *uri, *dirname;
1533 char *proto, *host, *port, *repo_name, *server_path;
1534 char *default_destdir = NULL, *id_str = NULL;
1535 const char *repo_path;
1536 struct got_repository *repo = NULL;
1537 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1538 struct got_pathlist_entry *pe;
1539 struct got_object_id *pack_hash = NULL;
1540 int ch, fetchfd = -1, fetchstatus;
1541 pid_t fetchpid = -1;
1542 struct got_fetch_progress_arg fpa;
1543 char *git_url = NULL;
1544 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1545 int list_refs_only = 0;
1546 int *pack_fds = NULL;
1548 TAILQ_INIT(&refs);
1549 TAILQ_INIT(&symrefs);
1550 TAILQ_INIT(&wanted_branches);
1551 TAILQ_INIT(&wanted_refs);
1553 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1554 switch (ch) {
1555 case 'a':
1556 fetch_all_branches = 1;
1557 break;
1558 case 'b':
1559 error = got_pathlist_append(&wanted_branches,
1560 optarg, NULL);
1561 if (error)
1562 return error;
1563 break;
1564 case 'l':
1565 list_refs_only = 1;
1566 break;
1567 case 'm':
1568 mirror_references = 1;
1569 break;
1570 case 'v':
1571 if (verbosity < 0)
1572 verbosity = 0;
1573 else if (verbosity < 3)
1574 verbosity++;
1575 break;
1576 case 'q':
1577 verbosity = -1;
1578 break;
1579 case 'R':
1580 error = got_pathlist_append(&wanted_refs,
1581 optarg, NULL);
1582 if (error)
1583 return error;
1584 break;
1585 default:
1586 usage_clone();
1587 break;
1590 argc -= optind;
1591 argv += optind;
1593 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1594 option_conflict('a', 'b');
1595 if (list_refs_only) {
1596 if (!TAILQ_EMPTY(&wanted_branches))
1597 option_conflict('l', 'b');
1598 if (fetch_all_branches)
1599 option_conflict('l', 'a');
1600 if (mirror_references)
1601 option_conflict('l', 'm');
1602 if (!TAILQ_EMPTY(&wanted_refs))
1603 option_conflict('l', 'R');
1606 uri = argv[0];
1608 if (argc == 1)
1609 dirname = NULL;
1610 else if (argc == 2)
1611 dirname = argv[1];
1612 else
1613 usage_clone();
1615 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1616 &repo_name, uri);
1617 if (error)
1618 goto done;
1620 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1621 host, port ? ":" : "", port ? port : "",
1622 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1623 error = got_error_from_errno("asprintf");
1624 goto done;
1627 if (strcmp(proto, "git") == 0) {
1628 #ifndef PROFILE
1629 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1630 "sendfd dns inet unveil", NULL) == -1)
1631 err(1, "pledge");
1632 #endif
1633 } else if (strcmp(proto, "git+ssh") == 0 ||
1634 strcmp(proto, "ssh") == 0) {
1635 #ifndef PROFILE
1636 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1637 "sendfd unveil", NULL) == -1)
1638 err(1, "pledge");
1639 #endif
1640 } else if (strcmp(proto, "http") == 0 ||
1641 strcmp(proto, "git+http") == 0) {
1642 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1643 goto done;
1644 } else {
1645 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1646 goto done;
1648 if (dirname == NULL) {
1649 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1650 error = got_error_from_errno("asprintf");
1651 goto done;
1653 repo_path = default_destdir;
1654 } else
1655 repo_path = dirname;
1657 if (!list_refs_only) {
1658 error = got_path_mkdir(repo_path);
1659 if (error &&
1660 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1661 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1662 goto done;
1663 if (!got_path_dir_is_empty(repo_path)) {
1664 error = got_error_path(repo_path,
1665 GOT_ERR_DIR_NOT_EMPTY);
1666 goto done;
1670 error = got_dial_apply_unveil(proto);
1671 if (error)
1672 goto done;
1674 error = apply_unveil(repo_path, 0, NULL);
1675 if (error)
1676 goto done;
1678 if (verbosity >= 0)
1679 printf("Connecting to %s%s%s\n", host,
1680 port ? ":" : "", port ? port : "");
1682 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1683 server_path, verbosity);
1684 if (error)
1685 goto done;
1687 if (!list_refs_only) {
1688 error = got_repo_init(repo_path);
1689 if (error)
1690 goto done;
1691 error = got_repo_pack_fds_open(&pack_fds);
1692 if (error != NULL)
1693 goto done;
1694 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1695 if (error)
1696 goto done;
1699 fpa.last_scaled_size[0] = '\0';
1700 fpa.last_p_indexed = -1;
1701 fpa.last_p_resolved = -1;
1702 fpa.verbosity = verbosity;
1703 fpa.create_configs = 1;
1704 fpa.configs_created = 0;
1705 fpa.repo = repo;
1706 fpa.config_info.symrefs = &symrefs;
1707 fpa.config_info.wanted_branches = &wanted_branches;
1708 fpa.config_info.wanted_refs = &wanted_refs;
1709 fpa.config_info.proto = proto;
1710 fpa.config_info.host = host;
1711 fpa.config_info.port = port;
1712 fpa.config_info.remote_repo_path = server_path;
1713 fpa.config_info.git_url = git_url;
1714 fpa.config_info.fetch_all_branches = fetch_all_branches;
1715 fpa.config_info.mirror_references = mirror_references;
1716 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1717 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1718 fetch_all_branches, &wanted_branches, &wanted_refs,
1719 list_refs_only, verbosity, fetchfd, repo,
1720 fetch_progress, &fpa);
1721 if (error)
1722 goto done;
1724 if (list_refs_only) {
1725 error = list_remote_refs(&symrefs, &refs);
1726 goto done;
1729 if (pack_hash == NULL) {
1730 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1731 "server sent an empty pack file");
1732 goto done;
1734 error = got_object_id_str(&id_str, pack_hash);
1735 if (error)
1736 goto done;
1737 if (verbosity >= 0)
1738 printf("\nFetched %s.pack\n", id_str);
1739 free(id_str);
1741 /* Set up references provided with the pack file. */
1742 TAILQ_FOREACH(pe, &refs, entry) {
1743 const char *refname = pe->path;
1744 struct got_object_id *id = pe->data;
1745 char *remote_refname;
1747 if (is_wanted_ref(&wanted_refs, refname) &&
1748 !mirror_references) {
1749 error = create_wanted_ref(refname, id,
1750 GOT_FETCH_DEFAULT_REMOTE_NAME,
1751 verbosity - 1, repo);
1752 if (error)
1753 goto done;
1754 continue;
1757 error = create_ref(refname, id, verbosity - 1, repo);
1758 if (error)
1759 goto done;
1761 if (mirror_references)
1762 continue;
1764 if (strncmp("refs/heads/", refname, 11) != 0)
1765 continue;
1767 if (asprintf(&remote_refname,
1768 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 refname + 11) == -1) {
1770 error = got_error_from_errno("asprintf");
1771 goto done;
1773 error = create_ref(remote_refname, id, verbosity - 1, repo);
1774 free(remote_refname);
1775 if (error)
1776 goto done;
1779 /* Set the HEAD reference if the server provided one. */
1780 TAILQ_FOREACH(pe, &symrefs, entry) {
1781 struct got_reference *target_ref;
1782 const char *refname = pe->path;
1783 const char *target = pe->data;
1784 char *remote_refname = NULL, *remote_target = NULL;
1786 if (strcmp(refname, GOT_REF_HEAD) != 0)
1787 continue;
1789 error = got_ref_open(&target_ref, repo, target, 0);
1790 if (error) {
1791 if (error->code == GOT_ERR_NOT_REF) {
1792 error = NULL;
1793 continue;
1795 goto done;
1798 error = create_symref(refname, target_ref, verbosity, repo);
1799 got_ref_close(target_ref);
1800 if (error)
1801 goto done;
1803 if (mirror_references)
1804 continue;
1806 if (strncmp("refs/heads/", target, 11) != 0)
1807 continue;
1809 if (asprintf(&remote_refname,
1810 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1811 refname) == -1) {
1812 error = got_error_from_errno("asprintf");
1813 goto done;
1815 if (asprintf(&remote_target,
1816 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1817 target + 11) == -1) {
1818 error = got_error_from_errno("asprintf");
1819 free(remote_refname);
1820 goto done;
1822 error = got_ref_open(&target_ref, repo, remote_target, 0);
1823 if (error) {
1824 free(remote_refname);
1825 free(remote_target);
1826 if (error->code == GOT_ERR_NOT_REF) {
1827 error = NULL;
1828 continue;
1830 goto done;
1832 error = create_symref(remote_refname, target_ref,
1833 verbosity - 1, repo);
1834 free(remote_refname);
1835 free(remote_target);
1836 got_ref_close(target_ref);
1837 if (error)
1838 goto done;
1840 if (pe == NULL) {
1842 * We failed to set the HEAD reference. If we asked for
1843 * a set of wanted branches use the first of one of those
1844 * which could be fetched instead.
1846 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1847 const char *target = pe->path;
1848 struct got_reference *target_ref;
1850 error = got_ref_open(&target_ref, repo, target, 0);
1851 if (error) {
1852 if (error->code == GOT_ERR_NOT_REF) {
1853 error = NULL;
1854 continue;
1856 goto done;
1859 error = create_symref(GOT_REF_HEAD, target_ref,
1860 verbosity, repo);
1861 got_ref_close(target_ref);
1862 if (error)
1863 goto done;
1864 break;
1868 if (verbosity >= 0)
1869 printf("Created %s repository '%s'\n",
1870 mirror_references ? "mirrored" : "cloned", repo_path);
1871 done:
1872 if (pack_fds) {
1873 const struct got_error *pack_err =
1874 got_repo_pack_fds_close(pack_fds);
1875 if (error == NULL)
1876 error = pack_err;
1878 if (fetchpid > 0) {
1879 if (kill(fetchpid, SIGTERM) == -1)
1880 error = got_error_from_errno("kill");
1881 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1882 error = got_error_from_errno("waitpid");
1884 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1885 error = got_error_from_errno("close");
1886 if (repo) {
1887 const struct got_error *close_err = got_repo_close(repo);
1888 if (error == NULL)
1889 error = close_err;
1891 TAILQ_FOREACH(pe, &refs, entry) {
1892 free((void *)pe->path);
1893 free(pe->data);
1895 got_pathlist_free(&refs);
1896 TAILQ_FOREACH(pe, &symrefs, entry) {
1897 free((void *)pe->path);
1898 free(pe->data);
1900 got_pathlist_free(&symrefs);
1901 got_pathlist_free(&wanted_branches);
1902 got_pathlist_free(&wanted_refs);
1903 free(pack_hash);
1904 free(proto);
1905 free(host);
1906 free(port);
1907 free(server_path);
1908 free(repo_name);
1909 free(default_destdir);
1910 free(git_url);
1911 return error;
1914 static const struct got_error *
1915 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1916 int replace_tags, int verbosity, struct got_repository *repo)
1918 const struct got_error *err = NULL;
1919 char *new_id_str = NULL;
1920 struct got_object_id *old_id = NULL;
1922 err = got_object_id_str(&new_id_str, new_id);
1923 if (err)
1924 goto done;
1926 if (!replace_tags &&
1927 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1928 err = got_ref_resolve(&old_id, repo, ref);
1929 if (err)
1930 goto done;
1931 if (got_object_id_cmp(old_id, new_id) == 0)
1932 goto done;
1933 if (verbosity >= 0) {
1934 printf("Rejecting update of existing tag %s: %s\n",
1935 got_ref_get_name(ref), new_id_str);
1937 goto done;
1940 if (got_ref_is_symbolic(ref)) {
1941 if (verbosity >= 0) {
1942 printf("Replacing reference %s: %s\n",
1943 got_ref_get_name(ref),
1944 got_ref_get_symref_target(ref));
1946 err = got_ref_change_symref_to_ref(ref, new_id);
1947 if (err)
1948 goto done;
1949 err = got_ref_write(ref, repo);
1950 if (err)
1951 goto done;
1952 } else {
1953 err = got_ref_resolve(&old_id, repo, ref);
1954 if (err)
1955 goto done;
1956 if (got_object_id_cmp(old_id, new_id) == 0)
1957 goto done;
1959 err = got_ref_change_ref(ref, new_id);
1960 if (err)
1961 goto done;
1962 err = got_ref_write(ref, repo);
1963 if (err)
1964 goto done;
1967 if (verbosity >= 0)
1968 printf("Updated %s: %s\n", got_ref_get_name(ref),
1969 new_id_str);
1970 done:
1971 free(old_id);
1972 free(new_id_str);
1973 return err;
1976 static const struct got_error *
1977 update_symref(const char *refname, struct got_reference *target_ref,
1978 int verbosity, struct got_repository *repo)
1980 const struct got_error *err = NULL, *unlock_err;
1981 struct got_reference *symref;
1982 int symref_is_locked = 0;
1984 err = got_ref_open(&symref, repo, refname, 1);
1985 if (err) {
1986 if (err->code != GOT_ERR_NOT_REF)
1987 return err;
1988 err = got_ref_alloc_symref(&symref, refname, target_ref);
1989 if (err)
1990 goto done;
1992 err = got_ref_write(symref, repo);
1993 if (err)
1994 goto done;
1996 if (verbosity >= 0)
1997 printf("Created reference %s: %s\n",
1998 got_ref_get_name(symref),
1999 got_ref_get_symref_target(symref));
2000 } else {
2001 symref_is_locked = 1;
2003 if (strcmp(got_ref_get_symref_target(symref),
2004 got_ref_get_name(target_ref)) == 0)
2005 goto done;
2007 err = got_ref_change_symref(symref,
2008 got_ref_get_name(target_ref));
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Updated %s: %s\n", got_ref_get_name(symref),
2018 got_ref_get_symref_target(symref));
2021 done:
2022 if (symref_is_locked) {
2023 unlock_err = got_ref_unlock(symref);
2024 if (unlock_err && err == NULL)
2025 err = unlock_err;
2027 got_ref_close(symref);
2028 return err;
2031 __dead static void
2032 usage_fetch(void)
2034 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
2035 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
2036 "[remote-repository-name]\n",
2037 getprogname());
2038 exit(1);
2041 static const struct got_error *
2042 delete_missing_ref(struct got_reference *ref,
2043 int verbosity, struct got_repository *repo)
2045 const struct got_error *err = NULL;
2046 struct got_object_id *id = NULL;
2047 char *id_str = NULL;
2049 if (got_ref_is_symbolic(ref)) {
2050 err = got_ref_delete(ref, repo);
2051 if (err)
2052 return err;
2053 if (verbosity >= 0) {
2054 printf("Deleted %s: %s\n",
2055 got_ref_get_name(ref),
2056 got_ref_get_symref_target(ref));
2058 } else {
2059 err = got_ref_resolve(&id, repo, ref);
2060 if (err)
2061 return err;
2062 err = got_object_id_str(&id_str, id);
2063 if (err)
2064 goto done;
2066 err = got_ref_delete(ref, repo);
2067 if (err)
2068 goto done;
2069 if (verbosity >= 0) {
2070 printf("Deleted %s: %s\n",
2071 got_ref_get_name(ref), id_str);
2074 done:
2075 free(id);
2076 free(id_str);
2077 return NULL;
2080 static const struct got_error *
2081 delete_missing_refs(struct got_pathlist_head *their_refs,
2082 struct got_pathlist_head *their_symrefs,
2083 const struct got_remote_repo *remote,
2084 int verbosity, struct got_repository *repo)
2086 const struct got_error *err = NULL, *unlock_err;
2087 struct got_reflist_head my_refs;
2088 struct got_reflist_entry *re;
2089 struct got_pathlist_entry *pe;
2090 char *remote_namespace = NULL;
2091 char *local_refname = NULL;
2093 TAILQ_INIT(&my_refs);
2095 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2096 == -1)
2097 return got_error_from_errno("asprintf");
2099 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2100 if (err)
2101 goto done;
2103 TAILQ_FOREACH(re, &my_refs, entry) {
2104 const char *refname = got_ref_get_name(re->ref);
2105 const char *their_refname;
2107 if (remote->mirror_references) {
2108 their_refname = refname;
2109 } else {
2110 if (strncmp(refname, remote_namespace,
2111 strlen(remote_namespace)) == 0) {
2112 if (strcmp(refname + strlen(remote_namespace),
2113 GOT_REF_HEAD) == 0)
2114 continue;
2115 if (asprintf(&local_refname, "refs/heads/%s",
2116 refname + strlen(remote_namespace)) == -1) {
2117 err = got_error_from_errno("asprintf");
2118 goto done;
2120 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2121 continue;
2123 their_refname = local_refname;
2126 TAILQ_FOREACH(pe, their_refs, entry) {
2127 if (strcmp(their_refname, pe->path) == 0)
2128 break;
2130 if (pe != NULL)
2131 continue;
2133 TAILQ_FOREACH(pe, their_symrefs, entry) {
2134 if (strcmp(their_refname, pe->path) == 0)
2135 break;
2137 if (pe != NULL)
2138 continue;
2140 err = delete_missing_ref(re->ref, verbosity, repo);
2141 if (err)
2142 break;
2144 if (local_refname) {
2145 struct got_reference *ref;
2146 err = got_ref_open(&ref, repo, local_refname, 1);
2147 if (err) {
2148 if (err->code != GOT_ERR_NOT_REF)
2149 break;
2150 free(local_refname);
2151 local_refname = NULL;
2152 continue;
2154 err = delete_missing_ref(ref, verbosity, repo);
2155 if (err)
2156 break;
2157 unlock_err = got_ref_unlock(ref);
2158 got_ref_close(ref);
2159 if (unlock_err && err == NULL) {
2160 err = unlock_err;
2161 break;
2164 free(local_refname);
2165 local_refname = NULL;
2168 done:
2169 free(remote_namespace);
2170 free(local_refname);
2171 return err;
2174 static const struct got_error *
2175 update_wanted_ref(const char *refname, struct got_object_id *id,
2176 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2178 const struct got_error *err, *unlock_err;
2179 char *remote_refname;
2180 struct got_reference *ref;
2182 if (strncmp("refs/", refname, 5) == 0)
2183 refname += 5;
2185 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2186 remote_repo_name, refname) == -1)
2187 return got_error_from_errno("asprintf");
2189 err = got_ref_open(&ref, repo, remote_refname, 1);
2190 if (err) {
2191 if (err->code != GOT_ERR_NOT_REF)
2192 goto done;
2193 err = create_ref(remote_refname, id, verbosity, repo);
2194 } else {
2195 err = update_ref(ref, id, 0, verbosity, repo);
2196 unlock_err = got_ref_unlock(ref);
2197 if (unlock_err && err == NULL)
2198 err = unlock_err;
2199 got_ref_close(ref);
2201 done:
2202 free(remote_refname);
2203 return err;
2206 static const struct got_error *
2207 delete_ref(struct got_repository *repo, struct got_reference *ref)
2209 const struct got_error *err = NULL;
2210 struct got_object_id *id = NULL;
2211 char *id_str = NULL;
2212 const char *target;
2214 if (got_ref_is_symbolic(ref)) {
2215 target = got_ref_get_symref_target(ref);
2216 } else {
2217 err = got_ref_resolve(&id, repo, ref);
2218 if (err)
2219 goto done;
2220 err = got_object_id_str(&id_str, id);
2221 if (err)
2222 goto done;
2223 target = id_str;
2226 err = got_ref_delete(ref, repo);
2227 if (err)
2228 goto done;
2230 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2231 done:
2232 free(id);
2233 free(id_str);
2234 return err;
2237 static const struct got_error *
2238 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2240 const struct got_error *err = NULL;
2241 struct got_reflist_head refs;
2242 struct got_reflist_entry *re;
2243 char *prefix;
2245 TAILQ_INIT(&refs);
2247 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2248 err = got_error_from_errno("asprintf");
2249 goto done;
2251 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2252 if (err)
2253 goto done;
2255 TAILQ_FOREACH(re, &refs, entry)
2256 delete_ref(repo, re->ref);
2257 done:
2258 got_ref_list_free(&refs);
2259 return err;
2262 static const struct got_error *
2263 cmd_fetch(int argc, char *argv[])
2265 const struct got_error *error = NULL, *unlock_err;
2266 char *cwd = NULL, *repo_path = NULL;
2267 const char *remote_name;
2268 char *proto = NULL, *host = NULL, *port = NULL;
2269 char *repo_name = NULL, *server_path = NULL;
2270 const struct got_remote_repo *remotes, *remote = NULL;
2271 int nremotes;
2272 char *id_str = NULL;
2273 struct got_repository *repo = NULL;
2274 struct got_worktree *worktree = NULL;
2275 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2276 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2277 struct got_pathlist_entry *pe;
2278 struct got_object_id *pack_hash = NULL;
2279 int i, ch, fetchfd = -1, fetchstatus;
2280 pid_t fetchpid = -1;
2281 struct got_fetch_progress_arg fpa;
2282 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2283 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2284 int *pack_fds = NULL;
2286 TAILQ_INIT(&refs);
2287 TAILQ_INIT(&symrefs);
2288 TAILQ_INIT(&wanted_branches);
2289 TAILQ_INIT(&wanted_refs);
2291 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2292 switch (ch) {
2293 case 'a':
2294 fetch_all_branches = 1;
2295 break;
2296 case 'b':
2297 error = got_pathlist_append(&wanted_branches,
2298 optarg, NULL);
2299 if (error)
2300 return error;
2301 break;
2302 case 'd':
2303 delete_refs = 1;
2304 break;
2305 case 'l':
2306 list_refs_only = 1;
2307 break;
2308 case 'r':
2309 repo_path = realpath(optarg, NULL);
2310 if (repo_path == NULL)
2311 return got_error_from_errno2("realpath",
2312 optarg);
2313 got_path_strip_trailing_slashes(repo_path);
2314 break;
2315 case 't':
2316 replace_tags = 1;
2317 break;
2318 case 'v':
2319 if (verbosity < 0)
2320 verbosity = 0;
2321 else if (verbosity < 3)
2322 verbosity++;
2323 break;
2324 case 'q':
2325 verbosity = -1;
2326 break;
2327 case 'R':
2328 error = got_pathlist_append(&wanted_refs,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 break;
2333 case 'X':
2334 delete_remote = 1;
2335 break;
2336 default:
2337 usage_fetch();
2338 break;
2341 argc -= optind;
2342 argv += optind;
2344 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2345 option_conflict('a', 'b');
2346 if (list_refs_only) {
2347 if (!TAILQ_EMPTY(&wanted_branches))
2348 option_conflict('l', 'b');
2349 if (fetch_all_branches)
2350 option_conflict('l', 'a');
2351 if (delete_refs)
2352 option_conflict('l', 'd');
2353 if (delete_remote)
2354 option_conflict('l', 'X');
2356 if (delete_remote) {
2357 if (fetch_all_branches)
2358 option_conflict('X', 'a');
2359 if (!TAILQ_EMPTY(&wanted_branches))
2360 option_conflict('X', 'b');
2361 if (delete_refs)
2362 option_conflict('X', 'd');
2363 if (replace_tags)
2364 option_conflict('X', 't');
2365 if (!TAILQ_EMPTY(&wanted_refs))
2366 option_conflict('X', 'R');
2369 if (argc == 0) {
2370 if (delete_remote)
2371 errx(1, "-X option requires a remote name");
2372 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2373 } else if (argc == 1)
2374 remote_name = argv[0];
2375 else
2376 usage_fetch();
2378 cwd = getcwd(NULL, 0);
2379 if (cwd == NULL) {
2380 error = got_error_from_errno("getcwd");
2381 goto done;
2384 error = got_repo_pack_fds_open(&pack_fds);
2385 if (error != NULL)
2386 goto done;
2388 if (repo_path == NULL) {
2389 error = got_worktree_open(&worktree, cwd);
2390 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2391 goto done;
2392 else
2393 error = NULL;
2394 if (worktree) {
2395 repo_path =
2396 strdup(got_worktree_get_repo_path(worktree));
2397 if (repo_path == NULL)
2398 error = got_error_from_errno("strdup");
2399 if (error)
2400 goto done;
2401 } else {
2402 repo_path = strdup(cwd);
2403 if (repo_path == NULL) {
2404 error = got_error_from_errno("strdup");
2405 goto done;
2410 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2411 if (error)
2412 goto done;
2414 if (delete_remote) {
2415 error = delete_refs_for_remote(repo, remote_name);
2416 goto done; /* nothing else to do */
2419 if (worktree) {
2420 worktree_conf = got_worktree_get_gotconfig(worktree);
2421 if (worktree_conf) {
2422 got_gotconfig_get_remotes(&nremotes, &remotes,
2423 worktree_conf);
2424 for (i = 0; i < nremotes; i++) {
2425 if (strcmp(remotes[i].name, remote_name) == 0) {
2426 remote = &remotes[i];
2427 break;
2432 if (remote == NULL) {
2433 repo_conf = got_repo_get_gotconfig(repo);
2434 if (repo_conf) {
2435 got_gotconfig_get_remotes(&nremotes, &remotes,
2436 repo_conf);
2437 for (i = 0; i < nremotes; i++) {
2438 if (strcmp(remotes[i].name, remote_name) == 0) {
2439 remote = &remotes[i];
2440 break;
2445 if (remote == NULL) {
2446 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2447 for (i = 0; i < nremotes; i++) {
2448 if (strcmp(remotes[i].name, remote_name) == 0) {
2449 remote = &remotes[i];
2450 break;
2454 if (remote == NULL) {
2455 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2456 goto done;
2459 if (TAILQ_EMPTY(&wanted_branches)) {
2460 if (!fetch_all_branches)
2461 fetch_all_branches = remote->fetch_all_branches;
2462 for (i = 0; i < remote->nfetch_branches; i++) {
2463 got_pathlist_append(&wanted_branches,
2464 remote->fetch_branches[i], NULL);
2467 if (TAILQ_EMPTY(&wanted_refs)) {
2468 for (i = 0; i < remote->nfetch_refs; i++) {
2469 got_pathlist_append(&wanted_refs,
2470 remote->fetch_refs[i], NULL);
2474 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2475 &repo_name, remote->fetch_url);
2476 if (error)
2477 goto done;
2479 if (strcmp(proto, "git") == 0) {
2480 #ifndef PROFILE
2481 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2482 "sendfd dns inet unveil", NULL) == -1)
2483 err(1, "pledge");
2484 #endif
2485 } else if (strcmp(proto, "git+ssh") == 0 ||
2486 strcmp(proto, "ssh") == 0) {
2487 #ifndef PROFILE
2488 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2489 "sendfd unveil", NULL) == -1)
2490 err(1, "pledge");
2491 #endif
2492 } else if (strcmp(proto, "http") == 0 ||
2493 strcmp(proto, "git+http") == 0) {
2494 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2495 goto done;
2496 } else {
2497 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2498 goto done;
2501 error = got_dial_apply_unveil(proto);
2502 if (error)
2503 goto done;
2505 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2506 if (error)
2507 goto done;
2509 if (verbosity >= 0)
2510 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2511 port ? ":" : "", port ? port : "");
2513 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2514 server_path, verbosity);
2515 if (error)
2516 goto done;
2518 fpa.last_scaled_size[0] = '\0';
2519 fpa.last_p_indexed = -1;
2520 fpa.last_p_resolved = -1;
2521 fpa.verbosity = verbosity;
2522 fpa.repo = repo;
2523 fpa.create_configs = 0;
2524 fpa.configs_created = 0;
2525 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2526 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2527 remote->mirror_references, fetch_all_branches, &wanted_branches,
2528 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2529 fetch_progress, &fpa);
2530 if (error)
2531 goto done;
2533 if (list_refs_only) {
2534 error = list_remote_refs(&symrefs, &refs);
2535 goto done;
2538 if (pack_hash == NULL) {
2539 if (verbosity >= 0)
2540 printf("Already up-to-date\n");
2541 } else if (verbosity >= 0) {
2542 error = got_object_id_str(&id_str, pack_hash);
2543 if (error)
2544 goto done;
2545 printf("\nFetched %s.pack\n", id_str);
2546 free(id_str);
2547 id_str = NULL;
2550 /* Update references provided with the pack file. */
2551 TAILQ_FOREACH(pe, &refs, entry) {
2552 const char *refname = pe->path;
2553 struct got_object_id *id = pe->data;
2554 struct got_reference *ref;
2555 char *remote_refname;
2557 if (is_wanted_ref(&wanted_refs, refname) &&
2558 !remote->mirror_references) {
2559 error = update_wanted_ref(refname, id,
2560 remote->name, verbosity, repo);
2561 if (error)
2562 goto done;
2563 continue;
2566 if (remote->mirror_references ||
2567 strncmp("refs/tags/", refname, 10) == 0) {
2568 error = got_ref_open(&ref, repo, refname, 1);
2569 if (error) {
2570 if (error->code != GOT_ERR_NOT_REF)
2571 goto done;
2572 error = create_ref(refname, id, verbosity,
2573 repo);
2574 if (error)
2575 goto done;
2576 } else {
2577 error = update_ref(ref, id, replace_tags,
2578 verbosity, repo);
2579 unlock_err = got_ref_unlock(ref);
2580 if (unlock_err && error == NULL)
2581 error = unlock_err;
2582 got_ref_close(ref);
2583 if (error)
2584 goto done;
2586 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2587 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2588 remote_name, refname + 11) == -1) {
2589 error = got_error_from_errno("asprintf");
2590 goto done;
2593 error = got_ref_open(&ref, repo, remote_refname, 1);
2594 if (error) {
2595 if (error->code != GOT_ERR_NOT_REF)
2596 goto done;
2597 error = create_ref(remote_refname, id,
2598 verbosity, repo);
2599 if (error)
2600 goto done;
2601 } else {
2602 error = update_ref(ref, id, replace_tags,
2603 verbosity, repo);
2604 unlock_err = got_ref_unlock(ref);
2605 if (unlock_err && error == NULL)
2606 error = unlock_err;
2607 got_ref_close(ref);
2608 if (error)
2609 goto done;
2612 /* Also create a local branch if none exists yet. */
2613 error = got_ref_open(&ref, repo, refname, 1);
2614 if (error) {
2615 if (error->code != GOT_ERR_NOT_REF)
2616 goto done;
2617 error = create_ref(refname, id, verbosity,
2618 repo);
2619 if (error)
2620 goto done;
2621 } else {
2622 unlock_err = got_ref_unlock(ref);
2623 if (unlock_err && error == NULL)
2624 error = unlock_err;
2625 got_ref_close(ref);
2629 if (delete_refs) {
2630 error = delete_missing_refs(&refs, &symrefs, remote,
2631 verbosity, repo);
2632 if (error)
2633 goto done;
2636 if (!remote->mirror_references) {
2637 /* Update remote HEAD reference if the server provided one. */
2638 TAILQ_FOREACH(pe, &symrefs, entry) {
2639 struct got_reference *target_ref;
2640 const char *refname = pe->path;
2641 const char *target = pe->data;
2642 char *remote_refname = NULL, *remote_target = NULL;
2644 if (strcmp(refname, GOT_REF_HEAD) != 0)
2645 continue;
2647 if (strncmp("refs/heads/", target, 11) != 0)
2648 continue;
2650 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2651 remote->name, refname) == -1) {
2652 error = got_error_from_errno("asprintf");
2653 goto done;
2655 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2656 remote->name, target + 11) == -1) {
2657 error = got_error_from_errno("asprintf");
2658 free(remote_refname);
2659 goto done;
2662 error = got_ref_open(&target_ref, repo, remote_target,
2663 0);
2664 if (error) {
2665 free(remote_refname);
2666 free(remote_target);
2667 if (error->code == GOT_ERR_NOT_REF) {
2668 error = NULL;
2669 continue;
2671 goto done;
2673 error = update_symref(remote_refname, target_ref,
2674 verbosity, repo);
2675 free(remote_refname);
2676 free(remote_target);
2677 got_ref_close(target_ref);
2678 if (error)
2679 goto done;
2682 done:
2683 if (fetchpid > 0) {
2684 if (kill(fetchpid, SIGTERM) == -1)
2685 error = got_error_from_errno("kill");
2686 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2687 error = got_error_from_errno("waitpid");
2689 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2690 error = got_error_from_errno("close");
2691 if (repo) {
2692 const struct got_error *close_err = got_repo_close(repo);
2693 if (error == NULL)
2694 error = close_err;
2696 if (worktree)
2697 got_worktree_close(worktree);
2698 if (pack_fds) {
2699 const struct got_error *pack_err =
2700 got_repo_pack_fds_close(pack_fds);
2701 if (error == NULL)
2702 error = pack_err;
2704 TAILQ_FOREACH(pe, &refs, entry) {
2705 free((void *)pe->path);
2706 free(pe->data);
2708 got_pathlist_free(&refs);
2709 TAILQ_FOREACH(pe, &symrefs, entry) {
2710 free((void *)pe->path);
2711 free(pe->data);
2713 got_pathlist_free(&symrefs);
2714 got_pathlist_free(&wanted_branches);
2715 got_pathlist_free(&wanted_refs);
2716 free(id_str);
2717 free(cwd);
2718 free(repo_path);
2719 free(pack_hash);
2720 free(proto);
2721 free(host);
2722 free(port);
2723 free(server_path);
2724 free(repo_name);
2725 return error;
2729 __dead static void
2730 usage_checkout(void)
2732 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2733 "[-p prefix] [-q] repository-path [worktree-path]\n",
2734 getprogname());
2735 exit(1);
2738 static void
2739 show_worktree_base_ref_warning(void)
2741 fprintf(stderr, "%s: warning: could not create a reference "
2742 "to the work tree's base commit; the commit could be "
2743 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2744 "repository writable and running 'got update' will prevent this\n",
2745 getprogname());
2748 struct got_checkout_progress_arg {
2749 const char *worktree_path;
2750 int had_base_commit_ref_error;
2751 int verbosity;
2754 static const struct got_error *
2755 checkout_progress(void *arg, unsigned char status, const char *path)
2757 struct got_checkout_progress_arg *a = arg;
2759 /* Base commit bump happens silently. */
2760 if (status == GOT_STATUS_BUMP_BASE)
2761 return NULL;
2763 if (status == GOT_STATUS_BASE_REF_ERR) {
2764 a->had_base_commit_ref_error = 1;
2765 return NULL;
2768 while (path[0] == '/')
2769 path++;
2771 if (a->verbosity >= 0)
2772 printf("%c %s/%s\n", status, a->worktree_path, path);
2774 return NULL;
2777 static const struct got_error *
2778 check_cancelled(void *arg)
2780 if (sigint_received || sigpipe_received)
2781 return got_error(GOT_ERR_CANCELLED);
2782 return NULL;
2785 static const struct got_error *
2786 check_linear_ancestry(struct got_object_id *commit_id,
2787 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2788 struct got_repository *repo)
2790 const struct got_error *err = NULL;
2791 struct got_object_id *yca_id;
2793 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2794 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2795 if (err)
2796 return err;
2798 if (yca_id == NULL)
2799 return got_error(GOT_ERR_ANCESTRY);
2802 * Require a straight line of history between the target commit
2803 * and the work tree's base commit.
2805 * Non-linear situations such as this require a rebase:
2807 * (commit) D F (base_commit)
2808 * \ /
2809 * C E
2810 * \ /
2811 * B (yca)
2812 * |
2813 * A
2815 * 'got update' only handles linear cases:
2816 * Update forwards in time: A (base/yca) - B - C - D (commit)
2817 * Update backwards in time: D (base) - C - B - A (commit/yca)
2819 if (allow_forwards_in_time_only) {
2820 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2821 return got_error(GOT_ERR_ANCESTRY);
2822 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2823 got_object_id_cmp(base_commit_id, yca_id) != 0)
2824 return got_error(GOT_ERR_ANCESTRY);
2826 free(yca_id);
2827 return NULL;
2830 static const struct got_error *
2831 check_same_branch(struct got_object_id *commit_id,
2832 struct got_reference *head_ref, struct got_object_id *yca_id,
2833 struct got_repository *repo)
2835 const struct got_error *err = NULL;
2836 struct got_commit_graph *graph = NULL;
2837 struct got_object_id *head_commit_id = NULL;
2838 int is_same_branch = 0;
2840 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2841 if (err)
2842 goto done;
2844 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2845 is_same_branch = 1;
2846 goto done;
2848 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2849 is_same_branch = 1;
2850 goto done;
2853 err = got_commit_graph_open(&graph, "/", 1);
2854 if (err)
2855 goto done;
2857 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2858 check_cancelled, NULL);
2859 if (err)
2860 goto done;
2862 for (;;) {
2863 struct got_object_id *id;
2864 err = got_commit_graph_iter_next(&id, graph, repo,
2865 check_cancelled, NULL);
2866 if (err) {
2867 if (err->code == GOT_ERR_ITER_COMPLETED)
2868 err = NULL;
2869 break;
2872 if (id) {
2873 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2874 break;
2875 if (got_object_id_cmp(id, commit_id) == 0) {
2876 is_same_branch = 1;
2877 break;
2881 done:
2882 if (graph)
2883 got_commit_graph_close(graph);
2884 free(head_commit_id);
2885 if (!err && !is_same_branch)
2886 err = got_error(GOT_ERR_ANCESTRY);
2887 return err;
2890 static const struct got_error *
2891 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2893 static char msg[512];
2894 const char *branch_name;
2896 if (got_ref_is_symbolic(ref))
2897 branch_name = got_ref_get_symref_target(ref);
2898 else
2899 branch_name = got_ref_get_name(ref);
2901 if (strncmp("refs/heads/", branch_name, 11) == 0)
2902 branch_name += 11;
2904 snprintf(msg, sizeof(msg),
2905 "target commit is not contained in branch '%s'; "
2906 "the branch to use must be specified with -b; "
2907 "if necessary a new branch can be created for "
2908 "this commit with 'got branch -c %s BRANCH_NAME'",
2909 branch_name, commit_id_str);
2911 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2914 static const struct got_error *
2915 cmd_checkout(int argc, char *argv[])
2917 const struct got_error *error = NULL;
2918 struct got_repository *repo = NULL;
2919 struct got_reference *head_ref = NULL, *ref = NULL;
2920 struct got_worktree *worktree = NULL;
2921 char *repo_path = NULL;
2922 char *worktree_path = NULL;
2923 const char *path_prefix = "";
2924 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2925 char *commit_id_str = NULL;
2926 struct got_object_id *commit_id = NULL;
2927 char *cwd = NULL;
2928 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2929 struct got_pathlist_head paths;
2930 struct got_checkout_progress_arg cpa;
2931 int *pack_fds = NULL;
2933 TAILQ_INIT(&paths);
2935 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2936 switch (ch) {
2937 case 'b':
2938 branch_name = optarg;
2939 break;
2940 case 'c':
2941 commit_id_str = strdup(optarg);
2942 if (commit_id_str == NULL)
2943 return got_error_from_errno("strdup");
2944 break;
2945 case 'E':
2946 allow_nonempty = 1;
2947 break;
2948 case 'p':
2949 path_prefix = optarg;
2950 break;
2951 case 'q':
2952 verbosity = -1;
2953 break;
2954 default:
2955 usage_checkout();
2956 /* NOTREACHED */
2960 argc -= optind;
2961 argv += optind;
2963 #ifndef PROFILE
2964 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2965 "unveil", NULL) == -1)
2966 err(1, "pledge");
2967 #endif
2968 if (argc == 1) {
2969 char *base, *dotgit;
2970 const char *path;
2971 repo_path = realpath(argv[0], NULL);
2972 if (repo_path == NULL)
2973 return got_error_from_errno2("realpath", argv[0]);
2974 cwd = getcwd(NULL, 0);
2975 if (cwd == NULL) {
2976 error = got_error_from_errno("getcwd");
2977 goto done;
2979 if (path_prefix[0])
2980 path = path_prefix;
2981 else
2982 path = repo_path;
2983 error = got_path_basename(&base, path);
2984 if (error)
2985 goto done;
2986 dotgit = strstr(base, ".git");
2987 if (dotgit)
2988 *dotgit = '\0';
2989 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2990 error = got_error_from_errno("asprintf");
2991 free(base);
2992 goto done;
2994 free(base);
2995 } else if (argc == 2) {
2996 repo_path = realpath(argv[0], NULL);
2997 if (repo_path == NULL) {
2998 error = got_error_from_errno2("realpath", argv[0]);
2999 goto done;
3001 worktree_path = realpath(argv[1], NULL);
3002 if (worktree_path == NULL) {
3003 if (errno != ENOENT) {
3004 error = got_error_from_errno2("realpath",
3005 argv[1]);
3006 goto done;
3008 worktree_path = strdup(argv[1]);
3009 if (worktree_path == NULL) {
3010 error = got_error_from_errno("strdup");
3011 goto done;
3014 } else
3015 usage_checkout();
3017 got_path_strip_trailing_slashes(repo_path);
3018 got_path_strip_trailing_slashes(worktree_path);
3020 error = got_repo_pack_fds_open(&pack_fds);
3021 if (error != NULL)
3022 goto done;
3024 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3025 if (error != NULL)
3026 goto done;
3028 /* Pre-create work tree path for unveil(2) */
3029 error = got_path_mkdir(worktree_path);
3030 if (error) {
3031 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3032 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3033 goto done;
3034 if (!allow_nonempty &&
3035 !got_path_dir_is_empty(worktree_path)) {
3036 error = got_error_path(worktree_path,
3037 GOT_ERR_DIR_NOT_EMPTY);
3038 goto done;
3042 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3043 if (error)
3044 goto done;
3046 error = got_ref_open(&head_ref, repo, branch_name, 0);
3047 if (error != NULL)
3048 goto done;
3050 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3051 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3052 goto done;
3054 error = got_worktree_open(&worktree, worktree_path);
3055 if (error != NULL)
3056 goto done;
3058 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3059 path_prefix);
3060 if (error != NULL)
3061 goto done;
3062 if (!same_path_prefix) {
3063 error = got_error(GOT_ERR_PATH_PREFIX);
3064 goto done;
3067 if (commit_id_str) {
3068 struct got_reflist_head refs;
3069 TAILQ_INIT(&refs);
3070 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3071 NULL);
3072 if (error)
3073 goto done;
3074 error = got_repo_match_object_id(&commit_id, NULL,
3075 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3076 got_ref_list_free(&refs);
3077 if (error)
3078 goto done;
3079 error = check_linear_ancestry(commit_id,
3080 got_worktree_get_base_commit_id(worktree), 0, repo);
3081 if (error != NULL) {
3082 if (error->code == GOT_ERR_ANCESTRY) {
3083 error = checkout_ancestry_error(
3084 head_ref, commit_id_str);
3086 goto done;
3088 error = check_same_branch(commit_id, head_ref, NULL, repo);
3089 if (error) {
3090 if (error->code == GOT_ERR_ANCESTRY) {
3091 error = checkout_ancestry_error(
3092 head_ref, commit_id_str);
3094 goto done;
3096 error = got_worktree_set_base_commit_id(worktree, repo,
3097 commit_id);
3098 if (error)
3099 goto done;
3100 /* Expand potentially abbreviated commit ID string. */
3101 free(commit_id_str);
3102 error = got_object_id_str(&commit_id_str, commit_id);
3103 if (error)
3104 goto done;
3105 } else {
3106 commit_id = got_object_id_dup(
3107 got_worktree_get_base_commit_id(worktree));
3108 if (commit_id == NULL) {
3109 error = got_error_from_errno("got_object_id_dup");
3110 goto done;
3112 error = got_object_id_str(&commit_id_str, commit_id);
3113 if (error)
3114 goto done;
3117 error = got_pathlist_append(&paths, "", NULL);
3118 if (error)
3119 goto done;
3120 cpa.worktree_path = worktree_path;
3121 cpa.had_base_commit_ref_error = 0;
3122 cpa.verbosity = verbosity;
3123 error = got_worktree_checkout_files(worktree, &paths, repo,
3124 checkout_progress, &cpa, check_cancelled, NULL);
3125 if (error != NULL)
3126 goto done;
3128 if (got_ref_is_symbolic(head_ref)) {
3129 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3130 if (error)
3131 goto done;
3132 refname = got_ref_get_name(ref);
3133 } else
3134 refname = got_ref_get_name(head_ref);
3135 printf("Checked out %s: %s\n", refname, commit_id_str);
3136 printf("Now shut up and hack\n");
3137 if (cpa.had_base_commit_ref_error)
3138 show_worktree_base_ref_warning();
3139 done:
3140 if (pack_fds) {
3141 const struct got_error *pack_err =
3142 got_repo_pack_fds_close(pack_fds);
3143 if (error == NULL)
3144 error = pack_err;
3146 if (head_ref)
3147 got_ref_close(head_ref);
3148 if (ref)
3149 got_ref_close(ref);
3150 got_pathlist_free(&paths);
3151 free(commit_id_str);
3152 free(commit_id);
3153 free(repo_path);
3154 free(worktree_path);
3155 free(cwd);
3156 return error;
3159 struct got_update_progress_arg {
3160 int did_something;
3161 int conflicts;
3162 int obstructed;
3163 int not_updated;
3164 int missing;
3165 int not_deleted;
3166 int unversioned;
3167 int verbosity;
3170 static void
3171 print_update_progress_stats(struct got_update_progress_arg *upa)
3173 if (!upa->did_something)
3174 return;
3176 if (upa->conflicts > 0)
3177 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3178 if (upa->obstructed > 0)
3179 printf("File paths obstructed by a non-regular file: %d\n",
3180 upa->obstructed);
3181 if (upa->not_updated > 0)
3182 printf("Files not updated because of existing merge "
3183 "conflicts: %d\n", upa->not_updated);
3187 * The meaning of some status codes differs between merge-style operations and
3188 * update operations. For example, the ! status code means "file was missing"
3189 * if changes were merged into the work tree, and "missing file was restored"
3190 * if the work tree was updated. This function should be used by any operation
3191 * which merges changes into the work tree without updating the work tree.
3193 static void
3194 print_merge_progress_stats(struct got_update_progress_arg *upa)
3196 if (!upa->did_something)
3197 return;
3199 if (upa->conflicts > 0)
3200 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3201 if (upa->obstructed > 0)
3202 printf("File paths obstructed by a non-regular file: %d\n",
3203 upa->obstructed);
3204 if (upa->missing > 0)
3205 printf("Files which had incoming changes but could not be "
3206 "found in the work tree: %d\n", upa->missing);
3207 if (upa->not_deleted > 0)
3208 printf("Files not deleted due to differences in deleted "
3209 "content: %d\n", upa->not_deleted);
3210 if (upa->unversioned > 0)
3211 printf("Files not merged because an unversioned file was "
3212 "found in the work tree: %d\n", upa->unversioned);
3215 __dead static void
3216 usage_update(void)
3218 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3219 "[path ...]\n",
3220 getprogname());
3221 exit(1);
3224 static const struct got_error *
3225 update_progress(void *arg, unsigned char status, const char *path)
3227 struct got_update_progress_arg *upa = arg;
3229 if (status == GOT_STATUS_EXISTS ||
3230 status == GOT_STATUS_BASE_REF_ERR)
3231 return NULL;
3233 upa->did_something = 1;
3235 /* Base commit bump happens silently. */
3236 if (status == GOT_STATUS_BUMP_BASE)
3237 return NULL;
3239 if (status == GOT_STATUS_CONFLICT)
3240 upa->conflicts++;
3241 if (status == GOT_STATUS_OBSTRUCTED)
3242 upa->obstructed++;
3243 if (status == GOT_STATUS_CANNOT_UPDATE)
3244 upa->not_updated++;
3245 if (status == GOT_STATUS_MISSING)
3246 upa->missing++;
3247 if (status == GOT_STATUS_CANNOT_DELETE)
3248 upa->not_deleted++;
3249 if (status == GOT_STATUS_UNVERSIONED)
3250 upa->unversioned++;
3252 while (path[0] == '/')
3253 path++;
3254 if (upa->verbosity >= 0)
3255 printf("%c %s\n", status, path);
3257 return NULL;
3260 static const struct got_error *
3261 switch_head_ref(struct got_reference *head_ref,
3262 struct got_object_id *commit_id, struct got_worktree *worktree,
3263 struct got_repository *repo)
3265 const struct got_error *err = NULL;
3266 char *base_id_str;
3267 int ref_has_moved = 0;
3269 /* Trivial case: switching between two different references. */
3270 if (strcmp(got_ref_get_name(head_ref),
3271 got_worktree_get_head_ref_name(worktree)) != 0) {
3272 printf("Switching work tree from %s to %s\n",
3273 got_worktree_get_head_ref_name(worktree),
3274 got_ref_get_name(head_ref));
3275 return got_worktree_set_head_ref(worktree, head_ref);
3278 err = check_linear_ancestry(commit_id,
3279 got_worktree_get_base_commit_id(worktree), 0, repo);
3280 if (err) {
3281 if (err->code != GOT_ERR_ANCESTRY)
3282 return err;
3283 ref_has_moved = 1;
3285 if (!ref_has_moved)
3286 return NULL;
3288 /* Switching to a rebased branch with the same reference name. */
3289 err = got_object_id_str(&base_id_str,
3290 got_worktree_get_base_commit_id(worktree));
3291 if (err)
3292 return err;
3293 printf("Reference %s now points at a different branch\n",
3294 got_worktree_get_head_ref_name(worktree));
3295 printf("Switching work tree from %s to %s\n", base_id_str,
3296 got_worktree_get_head_ref_name(worktree));
3297 return NULL;
3300 static const struct got_error *
3301 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3303 const struct got_error *err;
3304 int in_progress;
3306 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3307 if (err)
3308 return err;
3309 if (in_progress)
3310 return got_error(GOT_ERR_REBASING);
3312 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3313 if (err)
3314 return err;
3315 if (in_progress)
3316 return got_error(GOT_ERR_HISTEDIT_BUSY);
3318 return NULL;
3321 static const struct got_error *
3322 check_merge_in_progress(struct got_worktree *worktree,
3323 struct got_repository *repo)
3325 const struct got_error *err;
3326 int in_progress;
3328 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3329 if (err)
3330 return err;
3331 if (in_progress)
3332 return got_error(GOT_ERR_MERGE_BUSY);
3334 return NULL;
3337 static const struct got_error *
3338 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3339 char *argv[], struct got_worktree *worktree)
3341 const struct got_error *err = NULL;
3342 char *path;
3343 struct got_pathlist_entry *new;
3344 int i;
3346 if (argc == 0) {
3347 path = strdup("");
3348 if (path == NULL)
3349 return got_error_from_errno("strdup");
3350 return got_pathlist_append(paths, path, NULL);
3353 for (i = 0; i < argc; i++) {
3354 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3355 if (err)
3356 break;
3357 err = got_pathlist_insert(&new, paths, path, NULL);
3358 if (err || new == NULL /* duplicate */) {
3359 free(path);
3360 if (err)
3361 break;
3365 return err;
3368 static const struct got_error *
3369 wrap_not_worktree_error(const struct got_error *orig_err,
3370 const char *cmdname, const char *path)
3372 const struct got_error *err;
3373 struct got_repository *repo;
3374 static char msg[512];
3375 int *pack_fds = NULL;
3377 err = got_repo_pack_fds_open(&pack_fds);
3378 if (err)
3379 return err;
3381 err = got_repo_open(&repo, path, NULL, pack_fds);
3382 if (err)
3383 return orig_err;
3385 snprintf(msg, sizeof(msg),
3386 "'got %s' needs a work tree in addition to a git repository\n"
3387 "Work trees can be checked out from this Git repository with "
3388 "'got checkout'.\n"
3389 "The got(1) manual page contains more information.", cmdname);
3390 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3391 got_repo_close(repo);
3392 if (pack_fds) {
3393 const struct got_error *pack_err =
3394 got_repo_pack_fds_close(pack_fds);
3395 if (err == NULL)
3396 err = pack_err;
3398 return err;
3401 static const struct got_error *
3402 cmd_update(int argc, char *argv[])
3404 const struct got_error *error = NULL;
3405 struct got_repository *repo = NULL;
3406 struct got_worktree *worktree = NULL;
3407 char *worktree_path = NULL;
3408 struct got_object_id *commit_id = NULL;
3409 char *commit_id_str = NULL;
3410 const char *branch_name = NULL;
3411 struct got_reference *head_ref = NULL;
3412 struct got_pathlist_head paths;
3413 struct got_pathlist_entry *pe;
3414 int ch, verbosity = 0;
3415 struct got_update_progress_arg upa;
3416 int *pack_fds = NULL;
3418 TAILQ_INIT(&paths);
3420 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3421 switch (ch) {
3422 case 'b':
3423 branch_name = optarg;
3424 break;
3425 case 'c':
3426 commit_id_str = strdup(optarg);
3427 if (commit_id_str == NULL)
3428 return got_error_from_errno("strdup");
3429 break;
3430 case 'q':
3431 verbosity = -1;
3432 break;
3433 default:
3434 usage_update();
3435 /* NOTREACHED */
3439 argc -= optind;
3440 argv += optind;
3442 #ifndef PROFILE
3443 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3444 "unveil", NULL) == -1)
3445 err(1, "pledge");
3446 #endif
3447 worktree_path = getcwd(NULL, 0);
3448 if (worktree_path == NULL) {
3449 error = got_error_from_errno("getcwd");
3450 goto done;
3453 error = got_repo_pack_fds_open(&pack_fds);
3454 if (error != NULL)
3455 goto done;
3457 error = got_worktree_open(&worktree, worktree_path);
3458 if (error) {
3459 if (error->code == GOT_ERR_NOT_WORKTREE)
3460 error = wrap_not_worktree_error(error, "update",
3461 worktree_path);
3462 goto done;
3465 error = check_rebase_or_histedit_in_progress(worktree);
3466 if (error)
3467 goto done;
3469 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3470 NULL, pack_fds);
3471 if (error != NULL)
3472 goto done;
3474 error = apply_unveil(got_repo_get_path(repo), 0,
3475 got_worktree_get_root_path(worktree));
3476 if (error)
3477 goto done;
3479 error = check_merge_in_progress(worktree, repo);
3480 if (error)
3481 goto done;
3483 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3484 if (error)
3485 goto done;
3487 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3488 got_worktree_get_head_ref_name(worktree), 0);
3489 if (error != NULL)
3490 goto done;
3491 if (commit_id_str == NULL) {
3492 error = got_ref_resolve(&commit_id, repo, head_ref);
3493 if (error != NULL)
3494 goto done;
3495 error = got_object_id_str(&commit_id_str, commit_id);
3496 if (error != NULL)
3497 goto done;
3498 } else {
3499 struct got_reflist_head refs;
3500 TAILQ_INIT(&refs);
3501 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3502 NULL);
3503 if (error)
3504 goto done;
3505 error = got_repo_match_object_id(&commit_id, NULL,
3506 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3507 got_ref_list_free(&refs);
3508 free(commit_id_str);
3509 commit_id_str = NULL;
3510 if (error)
3511 goto done;
3512 error = got_object_id_str(&commit_id_str, commit_id);
3513 if (error)
3514 goto done;
3517 if (branch_name) {
3518 struct got_object_id *head_commit_id;
3519 TAILQ_FOREACH(pe, &paths, entry) {
3520 if (pe->path_len == 0)
3521 continue;
3522 error = got_error_msg(GOT_ERR_BAD_PATH,
3523 "switching between branches requires that "
3524 "the entire work tree gets updated");
3525 goto done;
3527 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3528 if (error)
3529 goto done;
3530 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3531 repo);
3532 free(head_commit_id);
3533 if (error != NULL)
3534 goto done;
3535 error = check_same_branch(commit_id, head_ref, NULL, repo);
3536 if (error)
3537 goto done;
3538 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3539 if (error)
3540 goto done;
3541 } else {
3542 error = check_linear_ancestry(commit_id,
3543 got_worktree_get_base_commit_id(worktree), 0, repo);
3544 if (error != NULL) {
3545 if (error->code == GOT_ERR_ANCESTRY)
3546 error = got_error(GOT_ERR_BRANCH_MOVED);
3547 goto done;
3549 error = check_same_branch(commit_id, head_ref, NULL, repo);
3550 if (error)
3551 goto done;
3554 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3555 commit_id) != 0) {
3556 error = got_worktree_set_base_commit_id(worktree, repo,
3557 commit_id);
3558 if (error)
3559 goto done;
3562 memset(&upa, 0, sizeof(upa));
3563 upa.verbosity = verbosity;
3564 error = got_worktree_checkout_files(worktree, &paths, repo,
3565 update_progress, &upa, check_cancelled, NULL);
3566 if (error != NULL)
3567 goto done;
3569 if (upa.did_something) {
3570 printf("Updated to %s: %s\n",
3571 got_worktree_get_head_ref_name(worktree), commit_id_str);
3572 } else
3573 printf("Already up-to-date\n");
3575 print_update_progress_stats(&upa);
3576 done:
3577 if (pack_fds) {
3578 const struct got_error *pack_err =
3579 got_repo_pack_fds_close(pack_fds);
3580 if (error == NULL)
3581 error = pack_err;
3583 free(worktree_path);
3584 TAILQ_FOREACH(pe, &paths, entry)
3585 free((char *)pe->path);
3586 got_pathlist_free(&paths);
3587 free(commit_id);
3588 free(commit_id_str);
3589 return error;
3592 static const struct got_error *
3593 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3594 const char *path, int diff_context, int ignore_whitespace,
3595 int force_text_diff, struct got_repository *repo, FILE *outfile)
3597 const struct got_error *err = NULL;
3598 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3599 FILE *f1 = NULL, *f2 = NULL;
3600 int fd1 = -1, fd2 = -1;
3602 fd1 = got_opentempfd();
3603 if (fd1 == -1)
3604 return got_error_from_errno("got_opentempfd");
3605 fd2 = got_opentempfd();
3606 if (fd2 == -1) {
3607 err = got_error_from_errno("got_opentempfd");
3608 goto done;
3611 if (blob_id1) {
3612 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3613 fd1);
3614 if (err)
3615 goto done;
3618 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3619 if (err)
3620 goto done;
3622 f1 = got_opentemp();
3623 if (f1 == NULL) {
3624 err = got_error_from_errno("got_opentemp");
3625 goto done;
3627 f2 = got_opentemp();
3628 if (f2 == NULL) {
3629 err = got_error_from_errno("got_opentemp");
3630 goto done;
3633 while (path[0] == '/')
3634 path++;
3635 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3636 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3637 force_text_diff, outfile);
3638 done:
3639 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3640 err = got_error_from_errno("close");
3641 if (blob1)
3642 got_object_blob_close(blob1);
3643 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3644 err = got_error_from_errno("close");
3645 got_object_blob_close(blob2);
3646 if (f1 && fclose(f1) == EOF && err == NULL)
3647 err = got_error_from_errno("fclose");
3648 if (f2 && fclose(f2) == EOF && err == NULL)
3649 err = got_error_from_errno("fclose");
3650 return err;
3653 static const struct got_error *
3654 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3655 const char *path, int diff_context, int ignore_whitespace,
3656 int force_text_diff, struct got_repository *repo, FILE *outfile)
3658 const struct got_error *err = NULL;
3659 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3660 struct got_diff_blob_output_unidiff_arg arg;
3661 FILE *f1 = NULL, *f2 = NULL;
3662 int fd1 = -1, fd2 = -1;
3664 if (tree_id1) {
3665 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3666 if (err)
3667 goto done;
3668 fd1 = got_opentempfd();
3669 if (fd1 == -1) {
3670 err = got_error_from_errno("got_opentempfd");
3671 goto done;
3675 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3676 if (err)
3677 goto done;
3679 f1 = got_opentemp();
3680 if (f1 == NULL) {
3681 err = got_error_from_errno("got_opentemp");
3682 goto done;
3685 f2 = got_opentemp();
3686 if (f2 == NULL) {
3687 err = got_error_from_errno("got_opentemp");
3688 goto done;
3690 fd2 = got_opentempfd();
3691 if (fd2 == -1) {
3692 err = got_error_from_errno("got_opentempfd");
3693 goto done;
3695 arg.diff_context = diff_context;
3696 arg.ignore_whitespace = ignore_whitespace;
3697 arg.force_text_diff = force_text_diff;
3698 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3699 arg.outfile = outfile;
3700 arg.line_offsets = NULL;
3701 arg.nlines = 0;
3702 while (path[0] == '/')
3703 path++;
3704 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3705 got_diff_blob_output_unidiff, &arg, 1);
3706 done:
3707 if (tree1)
3708 got_object_tree_close(tree1);
3709 if (tree2)
3710 got_object_tree_close(tree2);
3711 if (f1 && fclose(f1) == EOF && err == NULL)
3712 err = got_error_from_errno("fclose");
3713 if (f2 && fclose(f2) == EOF && err == NULL)
3714 err = got_error_from_errno("fclose");
3715 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3716 err = got_error_from_errno("close");
3717 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3718 err = got_error_from_errno("close");
3719 return err;
3722 static const struct got_error *
3723 get_changed_paths(struct got_pathlist_head *paths,
3724 struct got_commit_object *commit, struct got_repository *repo)
3726 const struct got_error *err = NULL;
3727 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3728 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3729 struct got_object_qid *qid;
3731 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3732 if (qid != NULL) {
3733 struct got_commit_object *pcommit;
3734 err = got_object_open_as_commit(&pcommit, repo,
3735 &qid->id);
3736 if (err)
3737 return err;
3739 tree_id1 = got_object_id_dup(
3740 got_object_commit_get_tree_id(pcommit));
3741 if (tree_id1 == NULL) {
3742 got_object_commit_close(pcommit);
3743 return got_error_from_errno("got_object_id_dup");
3745 got_object_commit_close(pcommit);
3749 if (tree_id1) {
3750 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3751 if (err)
3752 goto done;
3755 tree_id2 = got_object_commit_get_tree_id(commit);
3756 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3757 if (err)
3758 goto done;
3760 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3761 got_diff_tree_collect_changed_paths, paths, 0);
3762 done:
3763 if (tree1)
3764 got_object_tree_close(tree1);
3765 if (tree2)
3766 got_object_tree_close(tree2);
3767 free(tree_id1);
3768 return err;
3771 static const struct got_error *
3772 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3773 const char *path, int diff_context, struct got_repository *repo,
3774 FILE *outfile)
3776 const struct got_error *err = NULL;
3777 struct got_commit_object *pcommit = NULL;
3778 char *id_str1 = NULL, *id_str2 = NULL;
3779 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3780 struct got_object_qid *qid;
3782 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3783 if (qid != NULL) {
3784 err = got_object_open_as_commit(&pcommit, repo,
3785 &qid->id);
3786 if (err)
3787 return err;
3788 err = got_object_id_str(&id_str1, &qid->id);
3789 if (err)
3790 goto done;
3793 err = got_object_id_str(&id_str2, id);
3794 if (err)
3795 goto done;
3797 if (path && path[0] != '\0') {
3798 int obj_type;
3799 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3800 if (err)
3801 goto done;
3802 if (pcommit) {
3803 err = got_object_id_by_path(&obj_id1, repo,
3804 pcommit, path);
3805 if (err) {
3806 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3807 free(obj_id2);
3808 goto done;
3812 err = got_object_get_type(&obj_type, repo, obj_id2);
3813 if (err) {
3814 free(obj_id2);
3815 goto done;
3817 fprintf(outfile,
3818 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3819 fprintf(outfile, "commit - %s\n",
3820 id_str1 ? id_str1 : "/dev/null");
3821 fprintf(outfile, "commit + %s\n", id_str2);
3822 switch (obj_type) {
3823 case GOT_OBJ_TYPE_BLOB:
3824 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3825 0, 0, repo, outfile);
3826 break;
3827 case GOT_OBJ_TYPE_TREE:
3828 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3829 0, 0, repo, outfile);
3830 break;
3831 default:
3832 err = got_error(GOT_ERR_OBJ_TYPE);
3833 break;
3835 free(obj_id1);
3836 free(obj_id2);
3837 } else {
3838 obj_id2 = got_object_commit_get_tree_id(commit);
3839 if (pcommit)
3840 obj_id1 = got_object_commit_get_tree_id(pcommit);
3841 fprintf(outfile,
3842 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3843 fprintf(outfile, "commit - %s\n",
3844 id_str1 ? id_str1 : "/dev/null");
3845 fprintf(outfile, "commit + %s\n", id_str2);
3846 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3847 repo, outfile);
3849 done:
3850 free(id_str1);
3851 free(id_str2);
3852 if (pcommit)
3853 got_object_commit_close(pcommit);
3854 return err;
3857 static char *
3858 get_datestr(time_t *time, char *datebuf)
3860 struct tm mytm, *tm;
3861 char *p, *s;
3863 tm = gmtime_r(time, &mytm);
3864 if (tm == NULL)
3865 return NULL;
3866 s = asctime_r(tm, datebuf);
3867 if (s == NULL)
3868 return NULL;
3869 p = strchr(s, '\n');
3870 if (p)
3871 *p = '\0';
3872 return s;
3875 static const struct got_error *
3876 match_commit(int *have_match, struct got_object_id *id,
3877 struct got_commit_object *commit, regex_t *regex)
3879 const struct got_error *err = NULL;
3880 regmatch_t regmatch;
3881 char *id_str = NULL, *logmsg = NULL;
3883 *have_match = 0;
3885 err = got_object_id_str(&id_str, id);
3886 if (err)
3887 return err;
3889 err = got_object_commit_get_logmsg(&logmsg, commit);
3890 if (err)
3891 goto done;
3893 if (regexec(regex, got_object_commit_get_author(commit), 1,
3894 &regmatch, 0) == 0 ||
3895 regexec(regex, got_object_commit_get_committer(commit), 1,
3896 &regmatch, 0) == 0 ||
3897 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3898 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3899 *have_match = 1;
3900 done:
3901 free(id_str);
3902 free(logmsg);
3903 return err;
3906 static void
3907 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3908 regex_t *regex)
3910 regmatch_t regmatch;
3911 struct got_pathlist_entry *pe;
3913 *have_match = 0;
3915 TAILQ_FOREACH(pe, changed_paths, entry) {
3916 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3917 *have_match = 1;
3918 break;
3923 static const struct got_error *
3924 match_patch(int *have_match, struct got_commit_object *commit,
3925 struct got_object_id *id, const char *path, int diff_context,
3926 struct got_repository *repo, regex_t *regex, FILE *f)
3928 const struct got_error *err = NULL;
3929 char *line = NULL;
3930 size_t linesize = 0;
3931 ssize_t linelen;
3932 regmatch_t regmatch;
3934 *have_match = 0;
3936 err = got_opentemp_truncate(f);
3937 if (err)
3938 return err;
3940 err = print_patch(commit, id, path, diff_context, repo, f);
3941 if (err)
3942 goto done;
3944 if (fseeko(f, 0L, SEEK_SET) == -1) {
3945 err = got_error_from_errno("fseeko");
3946 goto done;
3949 while ((linelen = getline(&line, &linesize, f)) != -1) {
3950 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3951 *have_match = 1;
3952 break;
3955 done:
3956 free(line);
3957 return err;
3960 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3962 static const struct got_error*
3963 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3964 struct got_object_id *id, struct got_repository *repo,
3965 int local_only)
3967 static const struct got_error *err = NULL;
3968 struct got_reflist_entry *re;
3969 char *s;
3970 const char *name;
3972 *refs_str = NULL;
3974 TAILQ_FOREACH(re, refs, entry) {
3975 struct got_tag_object *tag = NULL;
3976 struct got_object_id *ref_id;
3977 int cmp;
3979 name = got_ref_get_name(re->ref);
3980 if (strcmp(name, GOT_REF_HEAD) == 0)
3981 continue;
3982 if (strncmp(name, "refs/", 5) == 0)
3983 name += 5;
3984 if (strncmp(name, "got/", 4) == 0)
3985 continue;
3986 if (strncmp(name, "heads/", 6) == 0)
3987 name += 6;
3988 if (strncmp(name, "remotes/", 8) == 0) {
3989 if (local_only)
3990 continue;
3991 name += 8;
3992 s = strstr(name, "/" GOT_REF_HEAD);
3993 if (s != NULL && s[strlen(s)] == '\0')
3994 continue;
3996 err = got_ref_resolve(&ref_id, repo, re->ref);
3997 if (err)
3998 break;
3999 if (strncmp(name, "tags/", 5) == 0) {
4000 err = got_object_open_as_tag(&tag, repo, ref_id);
4001 if (err) {
4002 if (err->code != GOT_ERR_OBJ_TYPE) {
4003 free(ref_id);
4004 break;
4006 /* Ref points at something other than a tag. */
4007 err = NULL;
4008 tag = NULL;
4011 cmp = got_object_id_cmp(tag ?
4012 got_object_tag_get_object_id(tag) : ref_id, id);
4013 free(ref_id);
4014 if (tag)
4015 got_object_tag_close(tag);
4016 if (cmp != 0)
4017 continue;
4018 s = *refs_str;
4019 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4020 s ? ", " : "", name) == -1) {
4021 err = got_error_from_errno("asprintf");
4022 free(s);
4023 *refs_str = NULL;
4024 break;
4026 free(s);
4029 return err;
4032 static const struct got_error *
4033 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4034 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4036 const struct got_error *err = NULL;
4037 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4038 char *comma, *s, *nl;
4039 struct got_reflist_head *refs;
4040 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4041 struct tm tm;
4042 time_t committer_time;
4044 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4045 if (refs) {
4046 err = build_refs_str(&ref_str, refs, id, repo, 1);
4047 if (err)
4048 return err;
4050 /* Display the first matching ref only. */
4051 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4052 *comma = '\0';
4055 if (ref_str == NULL) {
4056 err = got_object_id_str(&id_str, id);
4057 if (err)
4058 return err;
4061 committer_time = got_object_commit_get_committer_time(commit);
4062 if (gmtime_r(&committer_time, &tm) == NULL) {
4063 err = got_error_from_errno("gmtime_r");
4064 goto done;
4066 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4067 err = got_error(GOT_ERR_NO_SPACE);
4068 goto done;
4071 err = got_object_commit_get_logmsg(&logmsg0, commit);
4072 if (err)
4073 goto done;
4075 s = logmsg0;
4076 while (isspace((unsigned char)s[0]))
4077 s++;
4079 nl = strchr(s, '\n');
4080 if (nl) {
4081 *nl = '\0';
4084 if (ref_str)
4085 printf("%s%-7s %s\n", datebuf, ref_str, s);
4086 else
4087 printf("%s%.7s %s\n", datebuf, id_str, s);
4089 if (fflush(stdout) != 0 && err == NULL)
4090 err = got_error_from_errno("fflush");
4091 done:
4092 free(id_str);
4093 free(ref_str);
4094 free(logmsg0);
4095 return err;
4098 static const struct got_error *
4099 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4100 struct got_repository *repo, const char *path,
4101 struct got_pathlist_head *changed_paths, int show_patch,
4102 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4103 const char *custom_refs_str)
4105 const struct got_error *err = NULL;
4106 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4107 char datebuf[26];
4108 time_t committer_time;
4109 const char *author, *committer;
4110 char *refs_str = NULL;
4112 err = got_object_id_str(&id_str, id);
4113 if (err)
4114 return err;
4116 if (custom_refs_str == NULL) {
4117 struct got_reflist_head *refs;
4118 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4119 if (refs) {
4120 err = build_refs_str(&refs_str, refs, id, repo, 0);
4121 if (err)
4122 goto done;
4126 printf(GOT_COMMIT_SEP_STR);
4127 if (custom_refs_str)
4128 printf("commit %s (%s)\n", id_str, custom_refs_str);
4129 else
4130 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4131 refs_str ? refs_str : "", refs_str ? ")" : "");
4132 free(id_str);
4133 id_str = NULL;
4134 free(refs_str);
4135 refs_str = NULL;
4136 printf("from: %s\n", got_object_commit_get_author(commit));
4137 committer_time = got_object_commit_get_committer_time(commit);
4138 datestr = get_datestr(&committer_time, datebuf);
4139 if (datestr)
4140 printf("date: %s UTC\n", datestr);
4141 author = got_object_commit_get_author(commit);
4142 committer = got_object_commit_get_committer(commit);
4143 if (strcmp(author, committer) != 0)
4144 printf("via: %s\n", committer);
4145 if (got_object_commit_get_nparents(commit) > 1) {
4146 const struct got_object_id_queue *parent_ids;
4147 struct got_object_qid *qid;
4148 int n = 1;
4149 parent_ids = got_object_commit_get_parent_ids(commit);
4150 STAILQ_FOREACH(qid, parent_ids, entry) {
4151 err = got_object_id_str(&id_str, &qid->id);
4152 if (err)
4153 goto done;
4154 printf("parent %d: %s\n", n++, id_str);
4155 free(id_str);
4156 id_str = NULL;
4160 err = got_object_commit_get_logmsg(&logmsg0, commit);
4161 if (err)
4162 goto done;
4164 logmsg = logmsg0;
4165 do {
4166 line = strsep(&logmsg, "\n");
4167 if (line)
4168 printf(" %s\n", line);
4169 } while (line);
4170 free(logmsg0);
4172 if (changed_paths) {
4173 struct got_pathlist_entry *pe;
4174 TAILQ_FOREACH(pe, changed_paths, entry) {
4175 struct got_diff_changed_path *cp = pe->data;
4176 printf(" %c %s\n", cp->status, pe->path);
4178 printf("\n");
4180 if (show_patch) {
4181 err = print_patch(commit, id, path, diff_context, repo, stdout);
4182 if (err == 0)
4183 printf("\n");
4186 if (fflush(stdout) != 0 && err == NULL)
4187 err = got_error_from_errno("fflush");
4188 done:
4189 free(id_str);
4190 free(refs_str);
4191 return err;
4194 static const struct got_error *
4195 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4196 struct got_repository *repo, const char *path, int show_changed_paths,
4197 int show_patch, const char *search_pattern, int diff_context, int limit,
4198 int log_branches, int reverse_display_order,
4199 struct got_reflist_object_id_map *refs_idmap, int one_line,
4200 FILE *tmpfile)
4202 const struct got_error *err;
4203 struct got_commit_graph *graph;
4204 regex_t regex;
4205 int have_match;
4206 struct got_object_id_queue reversed_commits;
4207 struct got_object_qid *qid;
4208 struct got_commit_object *commit;
4209 struct got_pathlist_head changed_paths;
4210 struct got_pathlist_entry *pe;
4212 STAILQ_INIT(&reversed_commits);
4213 TAILQ_INIT(&changed_paths);
4215 if (search_pattern && regcomp(&regex, search_pattern,
4216 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4217 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4219 err = got_commit_graph_open(&graph, path, !log_branches);
4220 if (err)
4221 return err;
4222 err = got_commit_graph_iter_start(graph, root_id, repo,
4223 check_cancelled, NULL);
4224 if (err)
4225 goto done;
4226 for (;;) {
4227 struct got_object_id *id;
4229 if (sigint_received || sigpipe_received)
4230 break;
4232 err = got_commit_graph_iter_next(&id, graph, repo,
4233 check_cancelled, NULL);
4234 if (err) {
4235 if (err->code == GOT_ERR_ITER_COMPLETED)
4236 err = NULL;
4237 break;
4239 if (id == NULL)
4240 break;
4242 err = got_object_open_as_commit(&commit, repo, id);
4243 if (err)
4244 break;
4246 if (show_changed_paths && !reverse_display_order) {
4247 err = get_changed_paths(&changed_paths, commit, repo);
4248 if (err)
4249 break;
4252 if (search_pattern) {
4253 err = match_commit(&have_match, id, commit, &regex);
4254 if (err) {
4255 got_object_commit_close(commit);
4256 break;
4258 if (have_match == 0 && show_changed_paths)
4259 match_changed_paths(&have_match,
4260 &changed_paths, &regex);
4261 if (have_match == 0 && show_patch) {
4262 err = match_patch(&have_match, commit, id,
4263 path, diff_context, repo, &regex,
4264 tmpfile);
4265 if (err)
4266 break;
4268 if (have_match == 0) {
4269 got_object_commit_close(commit);
4270 TAILQ_FOREACH(pe, &changed_paths, entry) {
4271 free((char *)pe->path);
4272 free(pe->data);
4274 got_pathlist_free(&changed_paths);
4275 continue;
4279 if (reverse_display_order) {
4280 err = got_object_qid_alloc(&qid, id);
4281 if (err)
4282 break;
4283 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4284 got_object_commit_close(commit);
4285 } else {
4286 if (one_line)
4287 err = print_commit_oneline(commit, id,
4288 repo, refs_idmap);
4289 else
4290 err = print_commit(commit, id, repo, path,
4291 show_changed_paths ? &changed_paths : NULL,
4292 show_patch, diff_context, refs_idmap, NULL);
4293 got_object_commit_close(commit);
4294 if (err)
4295 break;
4297 if ((limit && --limit == 0) ||
4298 (end_id && got_object_id_cmp(id, end_id) == 0))
4299 break;
4301 TAILQ_FOREACH(pe, &changed_paths, entry) {
4302 free((char *)pe->path);
4303 free(pe->data);
4305 got_pathlist_free(&changed_paths);
4307 if (reverse_display_order) {
4308 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4309 err = got_object_open_as_commit(&commit, repo,
4310 &qid->id);
4311 if (err)
4312 break;
4313 if (show_changed_paths) {
4314 err = get_changed_paths(&changed_paths,
4315 commit, repo);
4316 if (err)
4317 break;
4319 if (one_line)
4320 err = print_commit_oneline(commit, &qid->id,
4321 repo, refs_idmap);
4322 else
4323 err = print_commit(commit, &qid->id, repo, path,
4324 show_changed_paths ? &changed_paths : NULL,
4325 show_patch, diff_context, refs_idmap, NULL);
4326 got_object_commit_close(commit);
4327 if (err)
4328 break;
4329 TAILQ_FOREACH(pe, &changed_paths, entry) {
4330 free((char *)pe->path);
4331 free(pe->data);
4333 got_pathlist_free(&changed_paths);
4336 done:
4337 while (!STAILQ_EMPTY(&reversed_commits)) {
4338 qid = STAILQ_FIRST(&reversed_commits);
4339 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4340 got_object_qid_free(qid);
4342 TAILQ_FOREACH(pe, &changed_paths, entry) {
4343 free((char *)pe->path);
4344 free(pe->data);
4346 got_pathlist_free(&changed_paths);
4347 if (search_pattern)
4348 regfree(&regex);
4349 got_commit_graph_close(graph);
4350 return err;
4353 __dead static void
4354 usage_log(void)
4356 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4357 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4358 "[-r repository-path] [-R] [path]\n", getprogname());
4359 exit(1);
4362 static int
4363 get_default_log_limit(void)
4365 const char *got_default_log_limit;
4366 long long n;
4367 const char *errstr;
4369 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4370 if (got_default_log_limit == NULL)
4371 return 0;
4372 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4373 if (errstr != NULL)
4374 return 0;
4375 return n;
4378 static const struct got_error *
4379 cmd_log(int argc, char *argv[])
4381 const struct got_error *error;
4382 struct got_repository *repo = NULL;
4383 struct got_worktree *worktree = NULL;
4384 struct got_object_id *start_id = NULL, *end_id = NULL;
4385 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4386 const char *start_commit = NULL, *end_commit = NULL;
4387 const char *search_pattern = NULL;
4388 int diff_context = -1, ch;
4389 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4390 int reverse_display_order = 0, one_line = 0;
4391 const char *errstr;
4392 struct got_reflist_head refs;
4393 struct got_reflist_object_id_map *refs_idmap = NULL;
4394 FILE *tmpfile = NULL;
4395 int *pack_fds = NULL;
4397 TAILQ_INIT(&refs);
4399 #ifndef PROFILE
4400 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4401 NULL)
4402 == -1)
4403 err(1, "pledge");
4404 #endif
4406 limit = get_default_log_limit();
4408 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4409 switch (ch) {
4410 case 'p':
4411 show_patch = 1;
4412 break;
4413 case 'P':
4414 show_changed_paths = 1;
4415 break;
4416 case 'c':
4417 start_commit = optarg;
4418 break;
4419 case 'C':
4420 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4421 &errstr);
4422 if (errstr != NULL)
4423 errx(1, "number of context lines is %s: %s",
4424 errstr, optarg);
4425 break;
4426 case 'l':
4427 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4428 if (errstr != NULL)
4429 errx(1, "number of commits is %s: %s",
4430 errstr, optarg);
4431 break;
4432 case 'b':
4433 log_branches = 1;
4434 break;
4435 case 'r':
4436 repo_path = realpath(optarg, NULL);
4437 if (repo_path == NULL)
4438 return got_error_from_errno2("realpath",
4439 optarg);
4440 got_path_strip_trailing_slashes(repo_path);
4441 break;
4442 case 'R':
4443 reverse_display_order = 1;
4444 break;
4445 case 's':
4446 one_line = 1;
4447 break;
4448 case 'S':
4449 search_pattern = optarg;
4450 break;
4451 case 'x':
4452 end_commit = optarg;
4453 break;
4454 default:
4455 usage_log();
4456 /* NOTREACHED */
4460 argc -= optind;
4461 argv += optind;
4463 if (diff_context == -1)
4464 diff_context = 3;
4465 else if (!show_patch)
4466 errx(1, "-C requires -p");
4468 if (one_line && (show_patch || show_changed_paths))
4469 errx(1, "cannot use -s with -p or -P");
4471 cwd = getcwd(NULL, 0);
4472 if (cwd == NULL) {
4473 error = got_error_from_errno("getcwd");
4474 goto done;
4477 error = got_repo_pack_fds_open(&pack_fds);
4478 if (error != NULL)
4479 goto done;
4481 if (repo_path == NULL) {
4482 error = got_worktree_open(&worktree, cwd);
4483 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4484 goto done;
4485 error = NULL;
4488 if (argc == 1) {
4489 if (worktree) {
4490 error = got_worktree_resolve_path(&path, worktree,
4491 argv[0]);
4492 if (error)
4493 goto done;
4494 } else {
4495 path = strdup(argv[0]);
4496 if (path == NULL) {
4497 error = got_error_from_errno("strdup");
4498 goto done;
4501 } else if (argc != 0)
4502 usage_log();
4504 if (repo_path == NULL) {
4505 repo_path = worktree ?
4506 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4508 if (repo_path == NULL) {
4509 error = got_error_from_errno("strdup");
4510 goto done;
4513 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4514 if (error != NULL)
4515 goto done;
4517 error = apply_unveil(got_repo_get_path(repo), 1,
4518 worktree ? got_worktree_get_root_path(worktree) : NULL);
4519 if (error)
4520 goto done;
4522 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4523 if (error)
4524 goto done;
4526 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4527 if (error)
4528 goto done;
4530 if (start_commit == NULL) {
4531 struct got_reference *head_ref;
4532 struct got_commit_object *commit = NULL;
4533 error = got_ref_open(&head_ref, repo,
4534 worktree ? got_worktree_get_head_ref_name(worktree)
4535 : GOT_REF_HEAD, 0);
4536 if (error != NULL)
4537 goto done;
4538 error = got_ref_resolve(&start_id, repo, head_ref);
4539 got_ref_close(head_ref);
4540 if (error != NULL)
4541 goto done;
4542 error = got_object_open_as_commit(&commit, repo,
4543 start_id);
4544 if (error != NULL)
4545 goto done;
4546 got_object_commit_close(commit);
4547 } else {
4548 error = got_repo_match_object_id(&start_id, NULL,
4549 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4550 if (error != NULL)
4551 goto done;
4553 if (end_commit != NULL) {
4554 error = got_repo_match_object_id(&end_id, NULL,
4555 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4556 if (error != NULL)
4557 goto done;
4560 if (worktree) {
4562 * If a path was specified on the command line it was resolved
4563 * to a path in the work tree above. Prepend the work tree's
4564 * path prefix to obtain the corresponding in-repository path.
4566 if (path) {
4567 const char *prefix;
4568 prefix = got_worktree_get_path_prefix(worktree);
4569 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4570 (path[0] != '\0') ? "/" : "", path) == -1) {
4571 error = got_error_from_errno("asprintf");
4572 goto done;
4575 } else
4576 error = got_repo_map_path(&in_repo_path, repo,
4577 path ? path : "");
4578 if (error != NULL)
4579 goto done;
4580 if (in_repo_path) {
4581 free(path);
4582 path = in_repo_path;
4585 if (worktree) {
4586 /* Release work tree lock. */
4587 got_worktree_close(worktree);
4588 worktree = NULL;
4591 if (search_pattern && show_patch) {
4592 tmpfile = got_opentemp();
4593 if (tmpfile == NULL) {
4594 error = got_error_from_errno("got_opentemp");
4595 goto done;
4599 error = print_commits(start_id, end_id, repo, path ? path : "",
4600 show_changed_paths, show_patch, search_pattern, diff_context,
4601 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4602 tmpfile);
4603 done:
4604 free(path);
4605 free(repo_path);
4606 free(cwd);
4607 if (worktree)
4608 got_worktree_close(worktree);
4609 if (repo) {
4610 const struct got_error *close_err = got_repo_close(repo);
4611 if (error == NULL)
4612 error = close_err;
4614 if (pack_fds) {
4615 const struct got_error *pack_err =
4616 got_repo_pack_fds_close(pack_fds);
4617 if (error == NULL)
4618 error = pack_err;
4620 if (refs_idmap)
4621 got_reflist_object_id_map_free(refs_idmap);
4622 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4623 error = got_error_from_errno("fclose");
4624 got_ref_list_free(&refs);
4625 return error;
4628 __dead static void
4629 usage_diff(void)
4631 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4632 "[-r repository-path] [-s] [-w] [-P] "
4633 "[object1 object2 | path ...]\n", getprogname());
4634 exit(1);
4637 struct print_diff_arg {
4638 struct got_repository *repo;
4639 struct got_worktree *worktree;
4640 int diff_context;
4641 const char *id_str;
4642 int header_shown;
4643 int diff_staged;
4644 enum got_diff_algorithm diff_algo;
4645 int ignore_whitespace;
4646 int force_text_diff;
4647 FILE *f1;
4648 FILE *f2;
4652 * Create a file which contains the target path of a symlink so we can feed
4653 * it as content to the diff engine.
4655 static const struct got_error *
4656 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4657 const char *abspath)
4659 const struct got_error *err = NULL;
4660 char target_path[PATH_MAX];
4661 ssize_t target_len, outlen;
4663 *fd = -1;
4665 if (dirfd != -1) {
4666 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4667 if (target_len == -1)
4668 return got_error_from_errno2("readlinkat", abspath);
4669 } else {
4670 target_len = readlink(abspath, target_path, PATH_MAX);
4671 if (target_len == -1)
4672 return got_error_from_errno2("readlink", abspath);
4675 *fd = got_opentempfd();
4676 if (*fd == -1)
4677 return got_error_from_errno("got_opentempfd");
4679 outlen = write(*fd, target_path, target_len);
4680 if (outlen == -1) {
4681 err = got_error_from_errno("got_opentempfd");
4682 goto done;
4685 if (lseek(*fd, 0, SEEK_SET) == -1) {
4686 err = got_error_from_errno2("lseek", abspath);
4687 goto done;
4689 done:
4690 if (err) {
4691 close(*fd);
4692 *fd = -1;
4694 return err;
4697 static const struct got_error *
4698 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4699 const char *path, struct got_object_id *blob_id,
4700 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4701 int dirfd, const char *de_name)
4703 struct print_diff_arg *a = arg;
4704 const struct got_error *err = NULL;
4705 struct got_blob_object *blob1 = NULL;
4706 int fd = -1, fd1 = -1, fd2 = -1;
4707 FILE *f2 = NULL;
4708 char *abspath = NULL, *label1 = NULL;
4709 struct stat sb;
4710 off_t size1 = 0;
4711 int f2_exists = 1;
4713 if (a->diff_staged) {
4714 if (staged_status != GOT_STATUS_MODIFY &&
4715 staged_status != GOT_STATUS_ADD &&
4716 staged_status != GOT_STATUS_DELETE)
4717 return NULL;
4718 } else {
4719 if (staged_status == GOT_STATUS_DELETE)
4720 return NULL;
4721 if (status == GOT_STATUS_NONEXISTENT)
4722 return got_error_set_errno(ENOENT, path);
4723 if (status != GOT_STATUS_MODIFY &&
4724 status != GOT_STATUS_ADD &&
4725 status != GOT_STATUS_DELETE &&
4726 status != GOT_STATUS_CONFLICT)
4727 return NULL;
4730 err = got_opentemp_truncate(a->f1);
4731 if (err)
4732 return got_error_from_errno("got_opentemp_truncate");
4733 err = got_opentemp_truncate(a->f2);
4734 if (err)
4735 return got_error_from_errno("got_opentemp_truncate");
4737 if (!a->header_shown) {
4738 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4739 got_worktree_get_root_path(a->worktree));
4740 printf("commit - %s\n", a->id_str);
4741 printf("path + %s%s\n",
4742 got_worktree_get_root_path(a->worktree),
4743 a->diff_staged ? " (staged changes)" : "");
4744 a->header_shown = 1;
4747 if (a->diff_staged) {
4748 const char *label1 = NULL, *label2 = NULL;
4749 switch (staged_status) {
4750 case GOT_STATUS_MODIFY:
4751 label1 = path;
4752 label2 = path;
4753 break;
4754 case GOT_STATUS_ADD:
4755 label2 = path;
4756 break;
4757 case GOT_STATUS_DELETE:
4758 label1 = path;
4759 break;
4760 default:
4761 return got_error(GOT_ERR_FILE_STATUS);
4763 fd1 = got_opentempfd();
4764 if (fd1 == -1) {
4765 err = got_error_from_errno("got_opentempfd");
4766 goto done;
4768 fd2 = got_opentempfd();
4769 if (fd2 == -1) {
4770 err = got_error_from_errno("got_opentempfd");
4771 goto done;
4773 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4774 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4775 a->diff_algo, a->diff_context, a->ignore_whitespace,
4776 a->force_text_diff, a->repo, stdout);
4777 goto done;
4780 fd1 = got_opentempfd();
4781 if (fd1 == -1) {
4782 err = got_error_from_errno("got_opentempfd");
4783 goto done;
4786 if (staged_status == GOT_STATUS_ADD ||
4787 staged_status == GOT_STATUS_MODIFY) {
4788 char *id_str;
4789 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4790 8192, fd1);
4791 if (err)
4792 goto done;
4793 err = got_object_id_str(&id_str, staged_blob_id);
4794 if (err)
4795 goto done;
4796 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4797 err = got_error_from_errno("asprintf");
4798 free(id_str);
4799 goto done;
4801 free(id_str);
4802 } else if (status != GOT_STATUS_ADD) {
4803 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4804 fd1);
4805 if (err)
4806 goto done;
4809 if (status != GOT_STATUS_DELETE) {
4810 if (asprintf(&abspath, "%s/%s",
4811 got_worktree_get_root_path(a->worktree), path) == -1) {
4812 err = got_error_from_errno("asprintf");
4813 goto done;
4816 if (dirfd != -1) {
4817 fd = openat(dirfd, de_name,
4818 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4819 if (fd == -1) {
4820 if (!got_err_open_nofollow_on_symlink()) {
4821 err = got_error_from_errno2("openat",
4822 abspath);
4823 goto done;
4825 err = get_symlink_target_file(&fd, dirfd,
4826 de_name, abspath);
4827 if (err)
4828 goto done;
4830 } else {
4831 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4832 if (fd == -1) {
4833 if (!got_err_open_nofollow_on_symlink()) {
4834 err = got_error_from_errno2("open",
4835 abspath);
4836 goto done;
4838 err = get_symlink_target_file(&fd, dirfd,
4839 de_name, abspath);
4840 if (err)
4841 goto done;
4844 if (fstat(fd, &sb) == -1) {
4845 err = got_error_from_errno2("fstat", abspath);
4846 goto done;
4848 f2 = fdopen(fd, "r");
4849 if (f2 == NULL) {
4850 err = got_error_from_errno2("fdopen", abspath);
4851 goto done;
4853 fd = -1;
4854 } else {
4855 sb.st_size = 0;
4856 f2_exists = 0;
4859 if (blob1) {
4860 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4861 a->f1, blob1);
4862 if (err)
4863 goto done;
4866 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4867 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4868 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4869 done:
4870 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4871 err = got_error_from_errno("close");
4872 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4873 err = got_error_from_errno("close");
4874 if (blob1)
4875 got_object_blob_close(blob1);
4876 if (fd != -1 && close(fd) == -1 && err == NULL)
4877 err = got_error_from_errno("close");
4878 if (f2 && fclose(f2) == EOF && err == NULL)
4879 err = got_error_from_errno("fclose");
4880 free(abspath);
4881 return err;
4884 static const struct got_error *
4885 cmd_diff(int argc, char *argv[])
4887 const struct got_error *error;
4888 struct got_repository *repo = NULL;
4889 struct got_worktree *worktree = NULL;
4890 char *cwd = NULL, *repo_path = NULL;
4891 const char *commit_args[2] = { NULL, NULL };
4892 int ncommit_args = 0;
4893 struct got_object_id *ids[2] = { NULL, NULL };
4894 char *labels[2] = { NULL, NULL };
4895 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4896 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4897 int force_text_diff = 0, force_path = 0, rflag = 0;
4898 const char *errstr;
4899 struct got_reflist_head refs;
4900 struct got_pathlist_head paths;
4901 struct got_pathlist_entry *pe;
4902 FILE *f1 = NULL, *f2 = NULL;
4903 int fd1 = -1, fd2 = -1;
4904 int *pack_fds = NULL;
4906 TAILQ_INIT(&refs);
4907 TAILQ_INIT(&paths);
4909 #ifndef PROFILE
4910 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4911 NULL) == -1)
4912 err(1, "pledge");
4913 #endif
4915 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4916 switch (ch) {
4917 case 'a':
4918 force_text_diff = 1;
4919 break;
4920 case 'c':
4921 if (ncommit_args >= 2)
4922 errx(1, "too many -c options used");
4923 commit_args[ncommit_args++] = optarg;
4924 break;
4925 case 'C':
4926 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4927 &errstr);
4928 if (errstr != NULL)
4929 errx(1, "number of context lines is %s: %s",
4930 errstr, optarg);
4931 break;
4932 case 'r':
4933 repo_path = realpath(optarg, NULL);
4934 if (repo_path == NULL)
4935 return got_error_from_errno2("realpath",
4936 optarg);
4937 got_path_strip_trailing_slashes(repo_path);
4938 rflag = 1;
4939 break;
4940 case 's':
4941 diff_staged = 1;
4942 break;
4943 case 'w':
4944 ignore_whitespace = 1;
4945 break;
4946 case 'P':
4947 force_path = 1;
4948 break;
4949 default:
4950 usage_diff();
4951 /* NOTREACHED */
4955 argc -= optind;
4956 argv += optind;
4958 cwd = getcwd(NULL, 0);
4959 if (cwd == NULL) {
4960 error = got_error_from_errno("getcwd");
4961 goto done;
4964 error = got_repo_pack_fds_open(&pack_fds);
4965 if (error != NULL)
4966 goto done;
4968 if (repo_path == NULL) {
4969 error = got_worktree_open(&worktree, cwd);
4970 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4971 goto done;
4972 else
4973 error = NULL;
4974 if (worktree) {
4975 repo_path =
4976 strdup(got_worktree_get_repo_path(worktree));
4977 if (repo_path == NULL) {
4978 error = got_error_from_errno("strdup");
4979 goto done;
4981 } else {
4982 repo_path = strdup(cwd);
4983 if (repo_path == NULL) {
4984 error = got_error_from_errno("strdup");
4985 goto done;
4990 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4991 free(repo_path);
4992 if (error != NULL)
4993 goto done;
4995 if (rflag || worktree == NULL || ncommit_args > 0) {
4996 if (force_path) {
4997 error = got_error_msg(GOT_ERR_NOT_IMPL,
4998 "-P option can only be used when diffing "
4999 "a work tree");
5000 goto done;
5002 if (diff_staged) {
5003 error = got_error_msg(GOT_ERR_NOT_IMPL,
5004 "-s option can only be used when diffing "
5005 "a work tree");
5006 goto done;
5010 error = apply_unveil(got_repo_get_path(repo), 1,
5011 worktree ? got_worktree_get_root_path(worktree) : NULL);
5012 if (error)
5013 goto done;
5015 if ((!force_path && argc == 2) || ncommit_args > 0) {
5016 int obj_type = (ncommit_args > 0 ?
5017 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5018 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5019 NULL);
5020 if (error)
5021 goto done;
5022 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5023 const char *arg;
5024 if (ncommit_args > 0)
5025 arg = commit_args[i];
5026 else
5027 arg = argv[i];
5028 error = got_repo_match_object_id(&ids[i], &labels[i],
5029 arg, obj_type, &refs, repo);
5030 if (error) {
5031 if (error->code != GOT_ERR_NOT_REF &&
5032 error->code != GOT_ERR_NO_OBJ)
5033 goto done;
5034 if (ncommit_args > 0)
5035 goto done;
5036 error = NULL;
5037 break;
5042 f1 = got_opentemp();
5043 if (f1 == NULL) {
5044 error = got_error_from_errno("got_opentemp");
5045 goto done;
5048 f2 = got_opentemp();
5049 if (f2 == NULL) {
5050 error = got_error_from_errno("got_opentemp");
5051 goto done;
5054 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5055 struct print_diff_arg arg;
5056 char *id_str;
5058 if (worktree == NULL) {
5059 if (argc == 2 && ids[0] == NULL) {
5060 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5061 goto done;
5062 } else if (argc == 2 && ids[1] == NULL) {
5063 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5064 goto done;
5065 } else if (argc > 0) {
5066 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5067 "%s", "specified paths cannot be resolved");
5068 goto done;
5069 } else {
5070 error = got_error(GOT_ERR_NOT_WORKTREE);
5071 goto done;
5075 error = get_worktree_paths_from_argv(&paths, argc, argv,
5076 worktree);
5077 if (error)
5078 goto done;
5080 error = got_object_id_str(&id_str,
5081 got_worktree_get_base_commit_id(worktree));
5082 if (error)
5083 goto done;
5084 arg.repo = repo;
5085 arg.worktree = worktree;
5086 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5087 arg.diff_context = diff_context;
5088 arg.id_str = id_str;
5089 arg.header_shown = 0;
5090 arg.diff_staged = diff_staged;
5091 arg.ignore_whitespace = ignore_whitespace;
5092 arg.force_text_diff = force_text_diff;
5093 arg.f1 = f1;
5094 arg.f2 = f2;
5096 error = got_worktree_status(worktree, &paths, repo, 0,
5097 print_diff, &arg, check_cancelled, NULL);
5098 free(id_str);
5099 goto done;
5102 if (ncommit_args == 1) {
5103 struct got_commit_object *commit;
5104 error = got_object_open_as_commit(&commit, repo, ids[0]);
5105 if (error)
5106 goto done;
5108 labels[1] = labels[0];
5109 ids[1] = ids[0];
5110 if (got_object_commit_get_nparents(commit) > 0) {
5111 const struct got_object_id_queue *pids;
5112 struct got_object_qid *pid;
5113 pids = got_object_commit_get_parent_ids(commit);
5114 pid = STAILQ_FIRST(pids);
5115 ids[0] = got_object_id_dup(&pid->id);
5116 if (ids[0] == NULL) {
5117 error = got_error_from_errno(
5118 "got_object_id_dup");
5119 got_object_commit_close(commit);
5120 goto done;
5122 error = got_object_id_str(&labels[0], ids[0]);
5123 if (error) {
5124 got_object_commit_close(commit);
5125 goto done;
5127 } else {
5128 ids[0] = NULL;
5129 labels[0] = strdup("/dev/null");
5130 if (labels[0] == NULL) {
5131 error = got_error_from_errno("strdup");
5132 got_object_commit_close(commit);
5133 goto done;
5137 got_object_commit_close(commit);
5140 if (ncommit_args == 0 && argc > 2) {
5141 error = got_error_msg(GOT_ERR_BAD_PATH,
5142 "path arguments cannot be used when diffing two objects");
5143 goto done;
5146 if (ids[0]) {
5147 error = got_object_get_type(&type1, repo, ids[0]);
5148 if (error)
5149 goto done;
5152 error = got_object_get_type(&type2, repo, ids[1]);
5153 if (error)
5154 goto done;
5155 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5156 error = got_error(GOT_ERR_OBJ_TYPE);
5157 goto done;
5159 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5160 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5161 "path arguments cannot be used when diffing blobs");
5162 goto done;
5165 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5166 char *in_repo_path;
5167 struct got_pathlist_entry *new;
5168 if (worktree) {
5169 const char *prefix;
5170 char *p;
5171 error = got_worktree_resolve_path(&p, worktree,
5172 argv[i]);
5173 if (error)
5174 goto done;
5175 prefix = got_worktree_get_path_prefix(worktree);
5176 while (prefix[0] == '/')
5177 prefix++;
5178 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5179 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5180 p) == -1) {
5181 error = got_error_from_errno("asprintf");
5182 free(p);
5183 goto done;
5185 free(p);
5186 } else {
5187 char *mapped_path, *s;
5188 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5189 if (error)
5190 goto done;
5191 s = mapped_path;
5192 while (s[0] == '/')
5193 s++;
5194 in_repo_path = strdup(s);
5195 if (in_repo_path == NULL) {
5196 error = got_error_from_errno("asprintf");
5197 free(mapped_path);
5198 goto done;
5200 free(mapped_path);
5203 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5204 if (error || new == NULL /* duplicate */)
5205 free(in_repo_path);
5206 if (error)
5207 goto done;
5210 if (worktree) {
5211 /* Release work tree lock. */
5212 got_worktree_close(worktree);
5213 worktree = NULL;
5216 fd1 = got_opentempfd();
5217 if (fd1 == -1) {
5218 error = got_error_from_errno("got_opentempfd");
5219 goto done;
5222 fd2 = got_opentempfd();
5223 if (fd2 == -1) {
5224 error = got_error_from_errno("got_opentempfd");
5225 goto done;
5228 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5229 case GOT_OBJ_TYPE_BLOB:
5230 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5231 fd1, fd2, ids[0], ids[1], NULL, NULL,
5232 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5233 ignore_whitespace, force_text_diff, repo, stdout);
5234 break;
5235 case GOT_OBJ_TYPE_TREE:
5236 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5237 ids[0], ids[1], &paths, "", "",
5238 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5239 ignore_whitespace, force_text_diff, repo, stdout);
5240 break;
5241 case GOT_OBJ_TYPE_COMMIT:
5242 printf("diff %s %s\n", labels[0], labels[1]);
5243 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5244 fd1, fd2, ids[0], ids[1], &paths,
5245 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5246 ignore_whitespace, force_text_diff, repo, stdout);
5247 break;
5248 default:
5249 error = got_error(GOT_ERR_OBJ_TYPE);
5251 done:
5252 free(labels[0]);
5253 free(labels[1]);
5254 free(ids[0]);
5255 free(ids[1]);
5256 if (worktree)
5257 got_worktree_close(worktree);
5258 if (repo) {
5259 const struct got_error *close_err = got_repo_close(repo);
5260 if (error == NULL)
5261 error = close_err;
5263 if (pack_fds) {
5264 const struct got_error *pack_err =
5265 got_repo_pack_fds_close(pack_fds);
5266 if (error == NULL)
5267 error = pack_err;
5269 TAILQ_FOREACH(pe, &paths, entry)
5270 free((char *)pe->path);
5271 got_pathlist_free(&paths);
5272 got_ref_list_free(&refs);
5273 if (f1 && fclose(f1) == EOF && error == NULL)
5274 error = got_error_from_errno("fclose");
5275 if (f2 && fclose(f2) == EOF && error == NULL)
5276 error = got_error_from_errno("fclose");
5277 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5278 error = got_error_from_errno("close");
5279 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5280 error = got_error_from_errno("close");
5281 return error;
5284 __dead static void
5285 usage_blame(void)
5287 fprintf(stderr,
5288 "usage: %s blame [-c commit] [-r repository-path] path\n",
5289 getprogname());
5290 exit(1);
5293 struct blame_line {
5294 int annotated;
5295 char *id_str;
5296 char *committer;
5297 char datebuf[11]; /* YYYY-MM-DD + NUL */
5300 struct blame_cb_args {
5301 struct blame_line *lines;
5302 int nlines;
5303 int nlines_prec;
5304 int lineno_cur;
5305 off_t *line_offsets;
5306 FILE *f;
5307 struct got_repository *repo;
5310 static const struct got_error *
5311 blame_cb(void *arg, int nlines, int lineno,
5312 struct got_commit_object *commit, struct got_object_id *id)
5314 const struct got_error *err = NULL;
5315 struct blame_cb_args *a = arg;
5316 struct blame_line *bline;
5317 char *line = NULL;
5318 size_t linesize = 0;
5319 off_t offset;
5320 struct tm tm;
5321 time_t committer_time;
5323 if (nlines != a->nlines ||
5324 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5325 return got_error(GOT_ERR_RANGE);
5327 if (sigint_received)
5328 return got_error(GOT_ERR_ITER_COMPLETED);
5330 if (lineno == -1)
5331 return NULL; /* no change in this commit */
5333 /* Annotate this line. */
5334 bline = &a->lines[lineno - 1];
5335 if (bline->annotated)
5336 return NULL;
5337 err = got_object_id_str(&bline->id_str, id);
5338 if (err)
5339 return err;
5341 bline->committer = strdup(got_object_commit_get_committer(commit));
5342 if (bline->committer == NULL) {
5343 err = got_error_from_errno("strdup");
5344 goto done;
5347 committer_time = got_object_commit_get_committer_time(commit);
5348 if (gmtime_r(&committer_time, &tm) == NULL)
5349 return got_error_from_errno("gmtime_r");
5350 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5351 &tm) == 0) {
5352 err = got_error(GOT_ERR_NO_SPACE);
5353 goto done;
5355 bline->annotated = 1;
5357 /* Print lines annotated so far. */
5358 bline = &a->lines[a->lineno_cur - 1];
5359 if (!bline->annotated)
5360 goto done;
5362 offset = a->line_offsets[a->lineno_cur - 1];
5363 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5364 err = got_error_from_errno("fseeko");
5365 goto done;
5368 while (bline->annotated) {
5369 char *smallerthan, *at, *nl, *committer;
5370 size_t len;
5372 if (getline(&line, &linesize, a->f) == -1) {
5373 if (ferror(a->f))
5374 err = got_error_from_errno("getline");
5375 break;
5378 committer = bline->committer;
5379 smallerthan = strchr(committer, '<');
5380 if (smallerthan && smallerthan[1] != '\0')
5381 committer = smallerthan + 1;
5382 at = strchr(committer, '@');
5383 if (at)
5384 *at = '\0';
5385 len = strlen(committer);
5386 if (len >= 9)
5387 committer[8] = '\0';
5389 nl = strchr(line, '\n');
5390 if (nl)
5391 *nl = '\0';
5392 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5393 bline->id_str, bline->datebuf, committer, line);
5395 a->lineno_cur++;
5396 bline = &a->lines[a->lineno_cur - 1];
5398 done:
5399 free(line);
5400 return err;
5403 static const struct got_error *
5404 cmd_blame(int argc, char *argv[])
5406 const struct got_error *error;
5407 struct got_repository *repo = NULL;
5408 struct got_worktree *worktree = NULL;
5409 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5410 char *link_target = NULL;
5411 struct got_object_id *obj_id = NULL;
5412 struct got_object_id *commit_id = NULL;
5413 struct got_commit_object *commit = NULL;
5414 struct got_blob_object *blob = NULL;
5415 char *commit_id_str = NULL;
5416 struct blame_cb_args bca;
5417 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5418 off_t filesize;
5419 int *pack_fds = NULL;
5420 FILE *f1 = NULL, *f2 = NULL;
5422 fd1 = got_opentempfd();
5423 if (fd1 == -1)
5424 return got_error_from_errno("got_opentempfd");
5426 memset(&bca, 0, sizeof(bca));
5428 #ifndef PROFILE
5429 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5430 NULL) == -1)
5431 err(1, "pledge");
5432 #endif
5434 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5435 switch (ch) {
5436 case 'c':
5437 commit_id_str = optarg;
5438 break;
5439 case 'r':
5440 repo_path = realpath(optarg, NULL);
5441 if (repo_path == NULL)
5442 return got_error_from_errno2("realpath",
5443 optarg);
5444 got_path_strip_trailing_slashes(repo_path);
5445 break;
5446 default:
5447 usage_blame();
5448 /* NOTREACHED */
5452 argc -= optind;
5453 argv += optind;
5455 if (argc == 1)
5456 path = argv[0];
5457 else
5458 usage_blame();
5460 cwd = getcwd(NULL, 0);
5461 if (cwd == NULL) {
5462 error = got_error_from_errno("getcwd");
5463 goto done;
5466 error = got_repo_pack_fds_open(&pack_fds);
5467 if (error != NULL)
5468 goto done;
5470 if (repo_path == NULL) {
5471 error = got_worktree_open(&worktree, cwd);
5472 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5473 goto done;
5474 else
5475 error = NULL;
5476 if (worktree) {
5477 repo_path =
5478 strdup(got_worktree_get_repo_path(worktree));
5479 if (repo_path == NULL) {
5480 error = got_error_from_errno("strdup");
5481 if (error)
5482 goto done;
5484 } else {
5485 repo_path = strdup(cwd);
5486 if (repo_path == NULL) {
5487 error = got_error_from_errno("strdup");
5488 goto done;
5493 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5494 if (error != NULL)
5495 goto done;
5497 if (worktree) {
5498 const char *prefix = got_worktree_get_path_prefix(worktree);
5499 char *p;
5501 error = got_worktree_resolve_path(&p, worktree, path);
5502 if (error)
5503 goto done;
5504 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5505 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5506 p) == -1) {
5507 error = got_error_from_errno("asprintf");
5508 free(p);
5509 goto done;
5511 free(p);
5512 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5513 } else {
5514 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5515 if (error)
5516 goto done;
5517 error = got_repo_map_path(&in_repo_path, repo, path);
5519 if (error)
5520 goto done;
5522 if (commit_id_str == NULL) {
5523 struct got_reference *head_ref;
5524 error = got_ref_open(&head_ref, repo, worktree ?
5525 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5526 if (error != NULL)
5527 goto done;
5528 error = got_ref_resolve(&commit_id, repo, head_ref);
5529 got_ref_close(head_ref);
5530 if (error != NULL)
5531 goto done;
5532 } else {
5533 struct got_reflist_head refs;
5534 TAILQ_INIT(&refs);
5535 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5536 NULL);
5537 if (error)
5538 goto done;
5539 error = got_repo_match_object_id(&commit_id, NULL,
5540 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5541 got_ref_list_free(&refs);
5542 if (error)
5543 goto done;
5546 if (worktree) {
5547 /* Release work tree lock. */
5548 got_worktree_close(worktree);
5549 worktree = NULL;
5552 error = got_object_open_as_commit(&commit, repo, commit_id);
5553 if (error)
5554 goto done;
5556 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5557 commit, repo);
5558 if (error)
5559 goto done;
5561 error = got_object_id_by_path(&obj_id, repo, commit,
5562 link_target ? link_target : in_repo_path);
5563 if (error)
5564 goto done;
5566 error = got_object_get_type(&obj_type, repo, obj_id);
5567 if (error)
5568 goto done;
5570 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5571 error = got_error_path(link_target ? link_target : in_repo_path,
5572 GOT_ERR_OBJ_TYPE);
5573 goto done;
5576 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5577 if (error)
5578 goto done;
5579 bca.f = got_opentemp();
5580 if (bca.f == NULL) {
5581 error = got_error_from_errno("got_opentemp");
5582 goto done;
5584 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5585 &bca.line_offsets, bca.f, blob);
5586 if (error || bca.nlines == 0)
5587 goto done;
5589 /* Don't include \n at EOF in the blame line count. */
5590 if (bca.line_offsets[bca.nlines - 1] == filesize)
5591 bca.nlines--;
5593 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5594 if (bca.lines == NULL) {
5595 error = got_error_from_errno("calloc");
5596 goto done;
5598 bca.lineno_cur = 1;
5599 bca.nlines_prec = 0;
5600 i = bca.nlines;
5601 while (i > 0) {
5602 i /= 10;
5603 bca.nlines_prec++;
5605 bca.repo = repo;
5607 fd2 = got_opentempfd();
5608 if (fd2 == -1) {
5609 error = got_error_from_errno("got_opentempfd");
5610 goto done;
5612 fd3 = got_opentempfd();
5613 if (fd3 == -1) {
5614 error = got_error_from_errno("got_opentempfd");
5615 goto done;
5617 f1 = got_opentemp();
5618 if (f1 == NULL) {
5619 error = got_error_from_errno("got_opentemp");
5620 goto done;
5622 f2 = got_opentemp();
5623 if (f2 == NULL) {
5624 error = got_error_from_errno("got_opentemp");
5625 goto done;
5627 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5628 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5629 check_cancelled, NULL, fd2, fd3, f1, f2);
5630 done:
5631 free(in_repo_path);
5632 free(link_target);
5633 free(repo_path);
5634 free(cwd);
5635 free(commit_id);
5636 free(obj_id);
5637 if (commit)
5638 got_object_commit_close(commit);
5640 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5641 error = got_error_from_errno("close");
5642 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5643 error = got_error_from_errno("close");
5644 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5645 error = got_error_from_errno("close");
5646 if (f1 && fclose(f1) == EOF && error == NULL)
5647 error = got_error_from_errno("fclose");
5648 if (f2 && fclose(f2) == EOF && error == NULL)
5649 error = got_error_from_errno("fclose");
5651 if (blob)
5652 got_object_blob_close(blob);
5653 if (worktree)
5654 got_worktree_close(worktree);
5655 if (repo) {
5656 const struct got_error *close_err = got_repo_close(repo);
5657 if (error == NULL)
5658 error = close_err;
5660 if (pack_fds) {
5661 const struct got_error *pack_err =
5662 got_repo_pack_fds_close(pack_fds);
5663 if (error == NULL)
5664 error = pack_err;
5666 if (bca.lines) {
5667 for (i = 0; i < bca.nlines; i++) {
5668 struct blame_line *bline = &bca.lines[i];
5669 free(bline->id_str);
5670 free(bline->committer);
5672 free(bca.lines);
5674 free(bca.line_offsets);
5675 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5676 error = got_error_from_errno("fclose");
5677 return error;
5680 __dead static void
5681 usage_tree(void)
5683 fprintf(stderr,
5684 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5685 getprogname());
5686 exit(1);
5689 static const struct got_error *
5690 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5691 const char *root_path, struct got_repository *repo)
5693 const struct got_error *err = NULL;
5694 int is_root_path = (strcmp(path, root_path) == 0);
5695 const char *modestr = "";
5696 mode_t mode = got_tree_entry_get_mode(te);
5697 char *link_target = NULL;
5699 path += strlen(root_path);
5700 while (path[0] == '/')
5701 path++;
5703 if (got_object_tree_entry_is_submodule(te))
5704 modestr = "$";
5705 else if (S_ISLNK(mode)) {
5706 int i;
5708 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5709 if (err)
5710 return err;
5711 for (i = 0; i < strlen(link_target); i++) {
5712 if (!isprint((unsigned char)link_target[i]))
5713 link_target[i] = '?';
5716 modestr = "@";
5718 else if (S_ISDIR(mode))
5719 modestr = "/";
5720 else if (mode & S_IXUSR)
5721 modestr = "*";
5723 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5724 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5725 link_target ? " -> ": "", link_target ? link_target : "");
5727 free(link_target);
5728 return NULL;
5731 static const struct got_error *
5732 print_tree(const char *path, struct got_commit_object *commit,
5733 int show_ids, int recurse, const char *root_path,
5734 struct got_repository *repo)
5736 const struct got_error *err = NULL;
5737 struct got_object_id *tree_id = NULL;
5738 struct got_tree_object *tree = NULL;
5739 int nentries, i;
5741 err = got_object_id_by_path(&tree_id, repo, commit, path);
5742 if (err)
5743 goto done;
5745 err = got_object_open_as_tree(&tree, repo, tree_id);
5746 if (err)
5747 goto done;
5748 nentries = got_object_tree_get_nentries(tree);
5749 for (i = 0; i < nentries; i++) {
5750 struct got_tree_entry *te;
5751 char *id = NULL;
5753 if (sigint_received || sigpipe_received)
5754 break;
5756 te = got_object_tree_get_entry(tree, i);
5757 if (show_ids) {
5758 char *id_str;
5759 err = got_object_id_str(&id_str,
5760 got_tree_entry_get_id(te));
5761 if (err)
5762 goto done;
5763 if (asprintf(&id, "%s ", id_str) == -1) {
5764 err = got_error_from_errno("asprintf");
5765 free(id_str);
5766 goto done;
5768 free(id_str);
5770 err = print_entry(te, id, path, root_path, repo);
5771 free(id);
5772 if (err)
5773 goto done;
5775 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5776 char *child_path;
5777 if (asprintf(&child_path, "%s%s%s", path,
5778 path[0] == '/' && path[1] == '\0' ? "" : "/",
5779 got_tree_entry_get_name(te)) == -1) {
5780 err = got_error_from_errno("asprintf");
5781 goto done;
5783 err = print_tree(child_path, commit, show_ids, 1,
5784 root_path, repo);
5785 free(child_path);
5786 if (err)
5787 goto done;
5790 done:
5791 if (tree)
5792 got_object_tree_close(tree);
5793 free(tree_id);
5794 return err;
5797 static const struct got_error *
5798 cmd_tree(int argc, char *argv[])
5800 const struct got_error *error;
5801 struct got_repository *repo = NULL;
5802 struct got_worktree *worktree = NULL;
5803 const char *path, *refname = NULL;
5804 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5805 struct got_object_id *commit_id = NULL;
5806 struct got_commit_object *commit = NULL;
5807 char *commit_id_str = NULL;
5808 int show_ids = 0, recurse = 0;
5809 int ch;
5810 int *pack_fds = NULL;
5812 #ifndef PROFILE
5813 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5814 NULL) == -1)
5815 err(1, "pledge");
5816 #endif
5818 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5819 switch (ch) {
5820 case 'c':
5821 commit_id_str = optarg;
5822 break;
5823 case 'r':
5824 repo_path = realpath(optarg, NULL);
5825 if (repo_path == NULL)
5826 return got_error_from_errno2("realpath",
5827 optarg);
5828 got_path_strip_trailing_slashes(repo_path);
5829 break;
5830 case 'i':
5831 show_ids = 1;
5832 break;
5833 case 'R':
5834 recurse = 1;
5835 break;
5836 default:
5837 usage_tree();
5838 /* NOTREACHED */
5842 argc -= optind;
5843 argv += optind;
5845 if (argc == 1)
5846 path = argv[0];
5847 else if (argc > 1)
5848 usage_tree();
5849 else
5850 path = NULL;
5852 cwd = getcwd(NULL, 0);
5853 if (cwd == NULL) {
5854 error = got_error_from_errno("getcwd");
5855 goto done;
5858 error = got_repo_pack_fds_open(&pack_fds);
5859 if (error != NULL)
5860 goto done;
5862 if (repo_path == NULL) {
5863 error = got_worktree_open(&worktree, cwd);
5864 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5865 goto done;
5866 else
5867 error = NULL;
5868 if (worktree) {
5869 repo_path =
5870 strdup(got_worktree_get_repo_path(worktree));
5871 if (repo_path == NULL)
5872 error = got_error_from_errno("strdup");
5873 if (error)
5874 goto done;
5875 } else {
5876 repo_path = strdup(cwd);
5877 if (repo_path == NULL) {
5878 error = got_error_from_errno("strdup");
5879 goto done;
5884 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5885 if (error != NULL)
5886 goto done;
5888 if (worktree) {
5889 const char *prefix = got_worktree_get_path_prefix(worktree);
5890 char *p;
5892 if (path == NULL)
5893 path = "";
5894 error = got_worktree_resolve_path(&p, worktree, path);
5895 if (error)
5896 goto done;
5897 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5898 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5899 p) == -1) {
5900 error = got_error_from_errno("asprintf");
5901 free(p);
5902 goto done;
5904 free(p);
5905 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5906 if (error)
5907 goto done;
5908 } else {
5909 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5910 if (error)
5911 goto done;
5912 if (path == NULL)
5913 path = "/";
5914 error = got_repo_map_path(&in_repo_path, repo, path);
5915 if (error != NULL)
5916 goto done;
5919 if (commit_id_str == NULL) {
5920 struct got_reference *head_ref;
5921 if (worktree)
5922 refname = got_worktree_get_head_ref_name(worktree);
5923 else
5924 refname = GOT_REF_HEAD;
5925 error = got_ref_open(&head_ref, repo, refname, 0);
5926 if (error != NULL)
5927 goto done;
5928 error = got_ref_resolve(&commit_id, repo, head_ref);
5929 got_ref_close(head_ref);
5930 if (error != NULL)
5931 goto done;
5932 } else {
5933 struct got_reflist_head refs;
5934 TAILQ_INIT(&refs);
5935 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5936 NULL);
5937 if (error)
5938 goto done;
5939 error = got_repo_match_object_id(&commit_id, NULL,
5940 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5941 got_ref_list_free(&refs);
5942 if (error)
5943 goto done;
5946 if (worktree) {
5947 /* Release work tree lock. */
5948 got_worktree_close(worktree);
5949 worktree = NULL;
5952 error = got_object_open_as_commit(&commit, repo, commit_id);
5953 if (error)
5954 goto done;
5956 error = print_tree(in_repo_path, commit, show_ids, recurse,
5957 in_repo_path, repo);
5958 done:
5959 free(in_repo_path);
5960 free(repo_path);
5961 free(cwd);
5962 free(commit_id);
5963 if (commit)
5964 got_object_commit_close(commit);
5965 if (worktree)
5966 got_worktree_close(worktree);
5967 if (repo) {
5968 const struct got_error *close_err = got_repo_close(repo);
5969 if (error == NULL)
5970 error = close_err;
5972 if (pack_fds) {
5973 const struct got_error *pack_err =
5974 got_repo_pack_fds_close(pack_fds);
5975 if (error == NULL)
5976 error = pack_err;
5978 return error;
5981 __dead static void
5982 usage_status(void)
5984 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5985 "[-S status-codes] [path ...]\n", getprogname());
5986 exit(1);
5989 struct got_status_arg {
5990 char *status_codes;
5991 int suppress;
5994 static const struct got_error *
5995 print_status(void *arg, unsigned char status, unsigned char staged_status,
5996 const char *path, struct got_object_id *blob_id,
5997 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5998 int dirfd, const char *de_name)
6000 struct got_status_arg *st = arg;
6002 if (status == staged_status && (status == GOT_STATUS_DELETE))
6003 status = GOT_STATUS_NO_CHANGE;
6004 if (st != NULL && st->status_codes) {
6005 size_t ncodes = strlen(st->status_codes);
6006 int i, j = 0;
6008 for (i = 0; i < ncodes ; i++) {
6009 if (st->suppress) {
6010 if (status == st->status_codes[i] ||
6011 staged_status == st->status_codes[i]) {
6012 j++;
6013 continue;
6015 } else {
6016 if (status == st->status_codes[i] ||
6017 staged_status == st->status_codes[i])
6018 break;
6022 if (st->suppress && j == 0)
6023 goto print;
6025 if (i == ncodes)
6026 return NULL;
6028 print:
6029 printf("%c%c %s\n", status, staged_status, path);
6030 return NULL;
6033 static const struct got_error *
6034 cmd_status(int argc, char *argv[])
6036 const struct got_error *error = NULL;
6037 struct got_repository *repo = NULL;
6038 struct got_worktree *worktree = NULL;
6039 struct got_status_arg st;
6040 char *cwd = NULL;
6041 struct got_pathlist_head paths;
6042 struct got_pathlist_entry *pe;
6043 int ch, i, no_ignores = 0;
6044 int *pack_fds = NULL;
6046 TAILQ_INIT(&paths);
6048 memset(&st, 0, sizeof(st));
6049 st.status_codes = NULL;
6050 st.suppress = 0;
6052 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6053 switch (ch) {
6054 case 'I':
6055 no_ignores = 1;
6056 break;
6057 case 'S':
6058 if (st.status_codes != NULL && st.suppress == 0)
6059 option_conflict('S', 's');
6060 st.suppress = 1;
6061 /* fallthrough */
6062 case 's':
6063 for (i = 0; i < strlen(optarg); i++) {
6064 switch (optarg[i]) {
6065 case GOT_STATUS_MODIFY:
6066 case GOT_STATUS_ADD:
6067 case GOT_STATUS_DELETE:
6068 case GOT_STATUS_CONFLICT:
6069 case GOT_STATUS_MISSING:
6070 case GOT_STATUS_OBSTRUCTED:
6071 case GOT_STATUS_UNVERSIONED:
6072 case GOT_STATUS_MODE_CHANGE:
6073 case GOT_STATUS_NONEXISTENT:
6074 break;
6075 default:
6076 errx(1, "invalid status code '%c'",
6077 optarg[i]);
6080 if (ch == 's' && st.suppress)
6081 option_conflict('s', 'S');
6082 st.status_codes = optarg;
6083 break;
6084 default:
6085 usage_status();
6086 /* NOTREACHED */
6090 argc -= optind;
6091 argv += optind;
6093 #ifndef PROFILE
6094 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6095 NULL) == -1)
6096 err(1, "pledge");
6097 #endif
6098 cwd = getcwd(NULL, 0);
6099 if (cwd == NULL) {
6100 error = got_error_from_errno("getcwd");
6101 goto done;
6104 error = got_repo_pack_fds_open(&pack_fds);
6105 if (error != NULL)
6106 goto done;
6108 error = got_worktree_open(&worktree, cwd);
6109 if (error) {
6110 if (error->code == GOT_ERR_NOT_WORKTREE)
6111 error = wrap_not_worktree_error(error, "status", cwd);
6112 goto done;
6115 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6116 NULL, pack_fds);
6117 if (error != NULL)
6118 goto done;
6120 error = apply_unveil(got_repo_get_path(repo), 1,
6121 got_worktree_get_root_path(worktree));
6122 if (error)
6123 goto done;
6125 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6126 if (error)
6127 goto done;
6129 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6130 print_status, &st, check_cancelled, NULL);
6131 done:
6132 if (pack_fds) {
6133 const struct got_error *pack_err =
6134 got_repo_pack_fds_close(pack_fds);
6135 if (error == NULL)
6136 error = pack_err;
6139 TAILQ_FOREACH(pe, &paths, entry)
6140 free((char *)pe->path);
6141 got_pathlist_free(&paths);
6142 free(cwd);
6143 return error;
6146 __dead static void
6147 usage_ref(void)
6149 fprintf(stderr,
6150 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6151 "[-s reference] [-d] [name]\n",
6152 getprogname());
6153 exit(1);
6156 static const struct got_error *
6157 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6159 static const struct got_error *err = NULL;
6160 struct got_reflist_head refs;
6161 struct got_reflist_entry *re;
6163 TAILQ_INIT(&refs);
6164 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6165 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6166 repo);
6167 if (err)
6168 return err;
6170 TAILQ_FOREACH(re, &refs, entry) {
6171 char *refstr;
6172 refstr = got_ref_to_str(re->ref);
6173 if (refstr == NULL) {
6174 err = got_error_from_errno("got_ref_to_str");
6175 break;
6177 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6178 free(refstr);
6181 got_ref_list_free(&refs);
6182 return err;
6185 static const struct got_error *
6186 delete_ref_by_name(struct got_repository *repo, const char *refname)
6188 const struct got_error *err;
6189 struct got_reference *ref;
6191 err = got_ref_open(&ref, repo, refname, 0);
6192 if (err)
6193 return err;
6195 err = delete_ref(repo, ref);
6196 got_ref_close(ref);
6197 return err;
6200 static const struct got_error *
6201 add_ref(struct got_repository *repo, const char *refname, const char *target)
6203 const struct got_error *err = NULL;
6204 struct got_object_id *id = NULL;
6205 struct got_reference *ref = NULL;
6206 struct got_reflist_head refs;
6209 * Don't let the user create a reference name with a leading '-'.
6210 * While technically a valid reference name, this case is usually
6211 * an unintended typo.
6213 if (refname[0] == '-')
6214 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6216 TAILQ_INIT(&refs);
6217 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6218 if (err)
6219 goto done;
6220 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6221 &refs, repo);
6222 got_ref_list_free(&refs);
6223 if (err)
6224 goto done;
6226 err = got_ref_alloc(&ref, refname, id);
6227 if (err)
6228 goto done;
6230 err = got_ref_write(ref, repo);
6231 done:
6232 if (ref)
6233 got_ref_close(ref);
6234 free(id);
6235 return err;
6238 static const struct got_error *
6239 add_symref(struct got_repository *repo, const char *refname, const char *target)
6241 const struct got_error *err = NULL;
6242 struct got_reference *ref = NULL;
6243 struct got_reference *target_ref = NULL;
6246 * Don't let the user create a reference name with a leading '-'.
6247 * While technically a valid reference name, this case is usually
6248 * an unintended typo.
6250 if (refname[0] == '-')
6251 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6253 err = got_ref_open(&target_ref, repo, target, 0);
6254 if (err)
6255 return err;
6257 err = got_ref_alloc_symref(&ref, refname, target_ref);
6258 if (err)
6259 goto done;
6261 err = got_ref_write(ref, repo);
6262 done:
6263 if (target_ref)
6264 got_ref_close(target_ref);
6265 if (ref)
6266 got_ref_close(ref);
6267 return err;
6270 static const struct got_error *
6271 cmd_ref(int argc, char *argv[])
6273 const struct got_error *error = NULL;
6274 struct got_repository *repo = NULL;
6275 struct got_worktree *worktree = NULL;
6276 char *cwd = NULL, *repo_path = NULL;
6277 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6278 const char *obj_arg = NULL, *symref_target= NULL;
6279 char *refname = NULL;
6280 int *pack_fds = NULL;
6282 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6283 switch (ch) {
6284 case 'c':
6285 obj_arg = optarg;
6286 break;
6287 case 'd':
6288 do_delete = 1;
6289 break;
6290 case 'r':
6291 repo_path = realpath(optarg, NULL);
6292 if (repo_path == NULL)
6293 return got_error_from_errno2("realpath",
6294 optarg);
6295 got_path_strip_trailing_slashes(repo_path);
6296 break;
6297 case 'l':
6298 do_list = 1;
6299 break;
6300 case 's':
6301 symref_target = optarg;
6302 break;
6303 case 't':
6304 sort_by_time = 1;
6305 break;
6306 default:
6307 usage_ref();
6308 /* NOTREACHED */
6312 if (obj_arg && do_list)
6313 option_conflict('c', 'l');
6314 if (obj_arg && do_delete)
6315 option_conflict('c', 'd');
6316 if (obj_arg && symref_target)
6317 option_conflict('c', 's');
6318 if (symref_target && do_delete)
6319 option_conflict('s', 'd');
6320 if (symref_target && do_list)
6321 option_conflict('s', 'l');
6322 if (do_delete && do_list)
6323 option_conflict('d', 'l');
6324 if (sort_by_time && !do_list)
6325 errx(1, "-t option requires -l option");
6327 argc -= optind;
6328 argv += optind;
6330 if (do_list) {
6331 if (argc != 0 && argc != 1)
6332 usage_ref();
6333 if (argc == 1) {
6334 refname = strdup(argv[0]);
6335 if (refname == NULL) {
6336 error = got_error_from_errno("strdup");
6337 goto done;
6340 } else {
6341 if (argc != 1)
6342 usage_ref();
6343 refname = strdup(argv[0]);
6344 if (refname == NULL) {
6345 error = got_error_from_errno("strdup");
6346 goto done;
6350 if (refname)
6351 got_path_strip_trailing_slashes(refname);
6353 #ifndef PROFILE
6354 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6355 "sendfd unveil", NULL) == -1)
6356 err(1, "pledge");
6357 #endif
6358 cwd = getcwd(NULL, 0);
6359 if (cwd == NULL) {
6360 error = got_error_from_errno("getcwd");
6361 goto done;
6364 error = got_repo_pack_fds_open(&pack_fds);
6365 if (error != NULL)
6366 goto done;
6368 if (repo_path == NULL) {
6369 error = got_worktree_open(&worktree, cwd);
6370 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6371 goto done;
6372 else
6373 error = NULL;
6374 if (worktree) {
6375 repo_path =
6376 strdup(got_worktree_get_repo_path(worktree));
6377 if (repo_path == NULL)
6378 error = got_error_from_errno("strdup");
6379 if (error)
6380 goto done;
6381 } else {
6382 repo_path = strdup(cwd);
6383 if (repo_path == NULL) {
6384 error = got_error_from_errno("strdup");
6385 goto done;
6390 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6391 if (error != NULL)
6392 goto done;
6394 #ifndef PROFILE
6395 if (do_list) {
6396 /* Remove "cpath" promise. */
6397 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6398 NULL) == -1)
6399 err(1, "pledge");
6401 #endif
6403 error = apply_unveil(got_repo_get_path(repo), do_list,
6404 worktree ? got_worktree_get_root_path(worktree) : NULL);
6405 if (error)
6406 goto done;
6408 if (do_list)
6409 error = list_refs(repo, refname, sort_by_time);
6410 else if (do_delete)
6411 error = delete_ref_by_name(repo, refname);
6412 else if (symref_target)
6413 error = add_symref(repo, refname, symref_target);
6414 else {
6415 if (obj_arg == NULL)
6416 usage_ref();
6417 error = add_ref(repo, refname, obj_arg);
6419 done:
6420 free(refname);
6421 if (repo) {
6422 const struct got_error *close_err = got_repo_close(repo);
6423 if (error == NULL)
6424 error = close_err;
6426 if (worktree)
6427 got_worktree_close(worktree);
6428 if (pack_fds) {
6429 const struct got_error *pack_err =
6430 got_repo_pack_fds_close(pack_fds);
6431 if (error == NULL)
6432 error = pack_err;
6434 free(cwd);
6435 free(repo_path);
6436 return error;
6439 __dead static void
6440 usage_branch(void)
6442 fprintf(stderr,
6443 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6444 "[-n] [name]\n", getprogname());
6445 exit(1);
6448 static const struct got_error *
6449 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6450 struct got_reference *ref)
6452 const struct got_error *err = NULL;
6453 const char *refname, *marker = " ";
6454 char *refstr;
6456 refname = got_ref_get_name(ref);
6457 if (worktree && strcmp(refname,
6458 got_worktree_get_head_ref_name(worktree)) == 0) {
6459 struct got_object_id *id = NULL;
6461 err = got_ref_resolve(&id, repo, ref);
6462 if (err)
6463 return err;
6464 if (got_object_id_cmp(id,
6465 got_worktree_get_base_commit_id(worktree)) == 0)
6466 marker = "* ";
6467 else
6468 marker = "~ ";
6469 free(id);
6472 if (strncmp(refname, "refs/heads/", 11) == 0)
6473 refname += 11;
6474 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6475 refname += 18;
6476 if (strncmp(refname, "refs/remotes/", 13) == 0)
6477 refname += 13;
6479 refstr = got_ref_to_str(ref);
6480 if (refstr == NULL)
6481 return got_error_from_errno("got_ref_to_str");
6483 printf("%s%s: %s\n", marker, refname, refstr);
6484 free(refstr);
6485 return NULL;
6488 static const struct got_error *
6489 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6491 const char *refname;
6493 if (worktree == NULL)
6494 return got_error(GOT_ERR_NOT_WORKTREE);
6496 refname = got_worktree_get_head_ref_name(worktree);
6498 if (strncmp(refname, "refs/heads/", 11) == 0)
6499 refname += 11;
6500 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6501 refname += 18;
6503 printf("%s\n", refname);
6505 return NULL;
6508 static const struct got_error *
6509 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6510 int sort_by_time)
6512 static const struct got_error *err = NULL;
6513 struct got_reflist_head refs;
6514 struct got_reflist_entry *re;
6515 struct got_reference *temp_ref = NULL;
6516 int rebase_in_progress, histedit_in_progress;
6518 TAILQ_INIT(&refs);
6520 if (worktree) {
6521 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6522 worktree);
6523 if (err)
6524 return err;
6526 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6527 worktree);
6528 if (err)
6529 return err;
6531 if (rebase_in_progress || histedit_in_progress) {
6532 err = got_ref_open(&temp_ref, repo,
6533 got_worktree_get_head_ref_name(worktree), 0);
6534 if (err)
6535 return err;
6536 list_branch(repo, worktree, temp_ref);
6537 got_ref_close(temp_ref);
6541 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6542 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6543 repo);
6544 if (err)
6545 return err;
6547 TAILQ_FOREACH(re, &refs, entry)
6548 list_branch(repo, worktree, re->ref);
6550 got_ref_list_free(&refs);
6552 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6553 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6554 repo);
6555 if (err)
6556 return err;
6558 TAILQ_FOREACH(re, &refs, entry)
6559 list_branch(repo, worktree, re->ref);
6561 got_ref_list_free(&refs);
6563 return NULL;
6566 static const struct got_error *
6567 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6568 const char *branch_name)
6570 const struct got_error *err = NULL;
6571 struct got_reference *ref = NULL;
6572 char *refname, *remote_refname = NULL;
6574 if (strncmp(branch_name, "refs/", 5) == 0)
6575 branch_name += 5;
6576 if (strncmp(branch_name, "heads/", 6) == 0)
6577 branch_name += 6;
6578 else if (strncmp(branch_name, "remotes/", 8) == 0)
6579 branch_name += 8;
6581 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6582 return got_error_from_errno("asprintf");
6584 if (asprintf(&remote_refname, "refs/remotes/%s",
6585 branch_name) == -1) {
6586 err = got_error_from_errno("asprintf");
6587 goto done;
6590 err = got_ref_open(&ref, repo, refname, 0);
6591 if (err) {
6592 const struct got_error *err2;
6593 if (err->code != GOT_ERR_NOT_REF)
6594 goto done;
6596 * Keep 'err' intact such that if neither branch exists
6597 * we report "refs/heads" rather than "refs/remotes" in
6598 * our error message.
6600 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6601 if (err2)
6602 goto done;
6603 err = NULL;
6606 if (worktree &&
6607 strcmp(got_worktree_get_head_ref_name(worktree),
6608 got_ref_get_name(ref)) == 0) {
6609 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6610 "will not delete this work tree's current branch");
6611 goto done;
6614 err = delete_ref(repo, ref);
6615 done:
6616 if (ref)
6617 got_ref_close(ref);
6618 free(refname);
6619 free(remote_refname);
6620 return err;
6623 static const struct got_error *
6624 add_branch(struct got_repository *repo, const char *branch_name,
6625 struct got_object_id *base_commit_id)
6627 const struct got_error *err = NULL;
6628 struct got_reference *ref = NULL;
6629 char *base_refname = NULL, *refname = NULL;
6632 * Don't let the user create a branch name with a leading '-'.
6633 * While technically a valid reference name, this case is usually
6634 * an unintended typo.
6636 if (branch_name[0] == '-')
6637 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6639 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6640 branch_name += 11;
6642 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6643 err = got_error_from_errno("asprintf");
6644 goto done;
6647 err = got_ref_open(&ref, repo, refname, 0);
6648 if (err == NULL) {
6649 err = got_error(GOT_ERR_BRANCH_EXISTS);
6650 goto done;
6651 } else if (err->code != GOT_ERR_NOT_REF)
6652 goto done;
6654 err = got_ref_alloc(&ref, refname, base_commit_id);
6655 if (err)
6656 goto done;
6658 err = got_ref_write(ref, repo);
6659 done:
6660 if (ref)
6661 got_ref_close(ref);
6662 free(base_refname);
6663 free(refname);
6664 return err;
6667 static const struct got_error *
6668 cmd_branch(int argc, char *argv[])
6670 const struct got_error *error = NULL;
6671 struct got_repository *repo = NULL;
6672 struct got_worktree *worktree = NULL;
6673 char *cwd = NULL, *repo_path = NULL;
6674 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6675 const char *delref = NULL, *commit_id_arg = NULL;
6676 struct got_reference *ref = NULL;
6677 struct got_pathlist_head paths;
6678 struct got_pathlist_entry *pe;
6679 struct got_object_id *commit_id = NULL;
6680 char *commit_id_str = NULL;
6681 int *pack_fds = NULL;
6683 TAILQ_INIT(&paths);
6685 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6686 switch (ch) {
6687 case 'c':
6688 commit_id_arg = optarg;
6689 break;
6690 case 'd':
6691 delref = optarg;
6692 break;
6693 case 'r':
6694 repo_path = realpath(optarg, NULL);
6695 if (repo_path == NULL)
6696 return got_error_from_errno2("realpath",
6697 optarg);
6698 got_path_strip_trailing_slashes(repo_path);
6699 break;
6700 case 'l':
6701 do_list = 1;
6702 break;
6703 case 'n':
6704 do_update = 0;
6705 break;
6706 case 't':
6707 sort_by_time = 1;
6708 break;
6709 default:
6710 usage_branch();
6711 /* NOTREACHED */
6715 if (do_list && delref)
6716 option_conflict('l', 'd');
6717 if (sort_by_time && !do_list)
6718 errx(1, "-t option requires -l option");
6720 argc -= optind;
6721 argv += optind;
6723 if (!do_list && !delref && argc == 0)
6724 do_show = 1;
6726 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6727 errx(1, "-c option can only be used when creating a branch");
6729 if (do_list || delref) {
6730 if (argc > 0)
6731 usage_branch();
6732 } else if (!do_show && argc != 1)
6733 usage_branch();
6735 #ifndef PROFILE
6736 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6737 "sendfd unveil", NULL) == -1)
6738 err(1, "pledge");
6739 #endif
6740 cwd = getcwd(NULL, 0);
6741 if (cwd == NULL) {
6742 error = got_error_from_errno("getcwd");
6743 goto done;
6746 error = got_repo_pack_fds_open(&pack_fds);
6747 if (error != NULL)
6748 goto done;
6750 if (repo_path == NULL) {
6751 error = got_worktree_open(&worktree, cwd);
6752 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6753 goto done;
6754 else
6755 error = NULL;
6756 if (worktree) {
6757 repo_path =
6758 strdup(got_worktree_get_repo_path(worktree));
6759 if (repo_path == NULL)
6760 error = got_error_from_errno("strdup");
6761 if (error)
6762 goto done;
6763 } else {
6764 repo_path = strdup(cwd);
6765 if (repo_path == NULL) {
6766 error = got_error_from_errno("strdup");
6767 goto done;
6772 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6773 if (error != NULL)
6774 goto done;
6776 #ifndef PROFILE
6777 if (do_list || do_show) {
6778 /* Remove "cpath" promise. */
6779 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6780 NULL) == -1)
6781 err(1, "pledge");
6783 #endif
6785 error = apply_unveil(got_repo_get_path(repo), do_list,
6786 worktree ? got_worktree_get_root_path(worktree) : NULL);
6787 if (error)
6788 goto done;
6790 if (do_show)
6791 error = show_current_branch(repo, worktree);
6792 else if (do_list)
6793 error = list_branches(repo, worktree, sort_by_time);
6794 else if (delref)
6795 error = delete_branch(repo, worktree, delref);
6796 else {
6797 struct got_reflist_head refs;
6798 TAILQ_INIT(&refs);
6799 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6800 NULL);
6801 if (error)
6802 goto done;
6803 if (commit_id_arg == NULL)
6804 commit_id_arg = worktree ?
6805 got_worktree_get_head_ref_name(worktree) :
6806 GOT_REF_HEAD;
6807 error = got_repo_match_object_id(&commit_id, NULL,
6808 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6809 got_ref_list_free(&refs);
6810 if (error)
6811 goto done;
6812 error = add_branch(repo, argv[0], commit_id);
6813 if (error)
6814 goto done;
6815 if (worktree && do_update) {
6816 struct got_update_progress_arg upa;
6817 char *branch_refname = NULL;
6819 error = got_object_id_str(&commit_id_str, commit_id);
6820 if (error)
6821 goto done;
6822 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6823 worktree);
6824 if (error)
6825 goto done;
6826 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6827 == -1) {
6828 error = got_error_from_errno("asprintf");
6829 goto done;
6831 error = got_ref_open(&ref, repo, branch_refname, 0);
6832 free(branch_refname);
6833 if (error)
6834 goto done;
6835 error = switch_head_ref(ref, commit_id, worktree,
6836 repo);
6837 if (error)
6838 goto done;
6839 error = got_worktree_set_base_commit_id(worktree, repo,
6840 commit_id);
6841 if (error)
6842 goto done;
6843 memset(&upa, 0, sizeof(upa));
6844 error = got_worktree_checkout_files(worktree, &paths,
6845 repo, update_progress, &upa, check_cancelled,
6846 NULL);
6847 if (error)
6848 goto done;
6849 if (upa.did_something) {
6850 printf("Updated to %s: %s\n",
6851 got_worktree_get_head_ref_name(worktree),
6852 commit_id_str);
6854 print_update_progress_stats(&upa);
6857 done:
6858 if (ref)
6859 got_ref_close(ref);
6860 if (repo) {
6861 const struct got_error *close_err = got_repo_close(repo);
6862 if (error == NULL)
6863 error = close_err;
6865 if (worktree)
6866 got_worktree_close(worktree);
6867 if (pack_fds) {
6868 const struct got_error *pack_err =
6869 got_repo_pack_fds_close(pack_fds);
6870 if (error == NULL)
6871 error = pack_err;
6873 free(cwd);
6874 free(repo_path);
6875 free(commit_id);
6876 free(commit_id_str);
6877 TAILQ_FOREACH(pe, &paths, entry)
6878 free((char *)pe->path);
6879 got_pathlist_free(&paths);
6880 return error;
6884 __dead static void
6885 usage_tag(void)
6887 fprintf(stderr,
6888 "usage: %s tag [-c commit] [-r repository] [-l] "
6889 "[-m message] [-s signer-id] [-V] name\n",
6890 getprogname());
6891 exit(1);
6894 #if 0
6895 static const struct got_error *
6896 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6898 const struct got_error *err = NULL;
6899 struct got_reflist_entry *re, *se, *new;
6900 struct got_object_id *re_id, *se_id;
6901 struct got_tag_object *re_tag, *se_tag;
6902 time_t re_time, se_time;
6904 STAILQ_FOREACH(re, tags, entry) {
6905 se = STAILQ_FIRST(sorted);
6906 if (se == NULL) {
6907 err = got_reflist_entry_dup(&new, re);
6908 if (err)
6909 return err;
6910 STAILQ_INSERT_HEAD(sorted, new, entry);
6911 continue;
6912 } else {
6913 err = got_ref_resolve(&re_id, repo, re->ref);
6914 if (err)
6915 break;
6916 err = got_object_open_as_tag(&re_tag, repo, re_id);
6917 free(re_id);
6918 if (err)
6919 break;
6920 re_time = got_object_tag_get_tagger_time(re_tag);
6921 got_object_tag_close(re_tag);
6924 while (se) {
6925 err = got_ref_resolve(&se_id, repo, re->ref);
6926 if (err)
6927 break;
6928 err = got_object_open_as_tag(&se_tag, repo, se_id);
6929 free(se_id);
6930 if (err)
6931 break;
6932 se_time = got_object_tag_get_tagger_time(se_tag);
6933 got_object_tag_close(se_tag);
6935 if (se_time > re_time) {
6936 err = got_reflist_entry_dup(&new, re);
6937 if (err)
6938 return err;
6939 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6940 break;
6942 se = STAILQ_NEXT(se, entry);
6943 continue;
6946 done:
6947 return err;
6949 #endif
6951 static const struct got_error *
6952 get_tag_refname(char **refname, const char *tag_name)
6954 const struct got_error *err;
6956 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6957 *refname = strdup(tag_name);
6958 if (*refname == NULL)
6959 return got_error_from_errno("strdup");
6960 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6961 err = got_error_from_errno("asprintf");
6962 *refname = NULL;
6963 return err;
6966 return NULL;
6969 static const struct got_error *
6970 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6971 const char *allowed_signers, const char *revoked_signers, int verbosity)
6973 static const struct got_error *err = NULL;
6974 struct got_reflist_head refs;
6975 struct got_reflist_entry *re;
6976 char *wanted_refname = NULL;
6977 int bad_sigs = 0;
6979 TAILQ_INIT(&refs);
6981 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6982 if (err)
6983 return err;
6985 if (tag_name) {
6986 struct got_reference *ref;
6987 err = get_tag_refname(&wanted_refname, tag_name);
6988 if (err)
6989 goto done;
6990 /* Wanted tag reference should exist. */
6991 err = got_ref_open(&ref, repo, wanted_refname, 0);
6992 if (err)
6993 goto done;
6994 got_ref_close(ref);
6997 TAILQ_FOREACH(re, &refs, entry) {
6998 const char *refname;
6999 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7000 char datebuf[26];
7001 const char *tagger, *ssh_sig = NULL;
7002 char *sig_msg = NULL;
7003 time_t tagger_time;
7004 struct got_object_id *id;
7005 struct got_tag_object *tag;
7006 struct got_commit_object *commit = NULL;
7008 refname = got_ref_get_name(re->ref);
7009 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7010 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7011 continue;
7012 refname += 10;
7013 refstr = got_ref_to_str(re->ref);
7014 if (refstr == NULL) {
7015 err = got_error_from_errno("got_ref_to_str");
7016 break;
7019 err = got_ref_resolve(&id, repo, re->ref);
7020 if (err)
7021 break;
7022 err = got_object_open_as_tag(&tag, repo, id);
7023 if (err) {
7024 if (err->code != GOT_ERR_OBJ_TYPE) {
7025 free(id);
7026 break;
7028 /* "lightweight" tag */
7029 err = got_object_open_as_commit(&commit, repo, id);
7030 if (err) {
7031 free(id);
7032 break;
7034 tagger = got_object_commit_get_committer(commit);
7035 tagger_time =
7036 got_object_commit_get_committer_time(commit);
7037 err = got_object_id_str(&id_str, id);
7038 free(id);
7039 if (err)
7040 break;
7041 } else {
7042 free(id);
7043 tagger = got_object_tag_get_tagger(tag);
7044 tagger_time = got_object_tag_get_tagger_time(tag);
7045 err = got_object_id_str(&id_str,
7046 got_object_tag_get_object_id(tag));
7047 if (err)
7048 break;
7051 if (verify_tags) {
7052 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7053 got_object_tag_get_message(tag));
7054 if (ssh_sig && allowed_signers == NULL) {
7055 err = got_error_msg(
7056 GOT_ERR_VERIFY_TAG_SIGNATURE,
7057 "SSH signature verification requires "
7058 "setting allowed_signers in "
7059 "got.conf(5)");
7060 break;
7064 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7065 free(refstr);
7066 printf("from: %s\n", tagger);
7067 datestr = get_datestr(&tagger_time, datebuf);
7068 if (datestr)
7069 printf("date: %s UTC\n", datestr);
7070 if (commit)
7071 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7072 else {
7073 switch (got_object_tag_get_object_type(tag)) {
7074 case GOT_OBJ_TYPE_BLOB:
7075 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7076 id_str);
7077 break;
7078 case GOT_OBJ_TYPE_TREE:
7079 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7080 id_str);
7081 break;
7082 case GOT_OBJ_TYPE_COMMIT:
7083 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7084 id_str);
7085 break;
7086 case GOT_OBJ_TYPE_TAG:
7087 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7088 id_str);
7089 break;
7090 default:
7091 break;
7094 free(id_str);
7096 if (ssh_sig) {
7097 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7098 allowed_signers, revoked_signers, verbosity);
7099 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7100 bad_sigs = 1;
7101 else if (err)
7102 break;
7103 printf("signature: %s", sig_msg);
7104 free(sig_msg);
7105 sig_msg = NULL;
7108 if (commit) {
7109 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7110 if (err)
7111 break;
7112 got_object_commit_close(commit);
7113 } else {
7114 tagmsg0 = strdup(got_object_tag_get_message(tag));
7115 got_object_tag_close(tag);
7116 if (tagmsg0 == NULL) {
7117 err = got_error_from_errno("strdup");
7118 break;
7122 tagmsg = tagmsg0;
7123 do {
7124 line = strsep(&tagmsg, "\n");
7125 if (line)
7126 printf(" %s\n", line);
7127 } while (line);
7128 free(tagmsg0);
7130 done:
7131 got_ref_list_free(&refs);
7132 free(wanted_refname);
7134 if (err == NULL && bad_sigs)
7135 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7136 return err;
7139 static const struct got_error *
7140 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7141 const char *tag_name, const char *repo_path)
7143 const struct got_error *err = NULL;
7144 char *template = NULL, *initial_content = NULL;
7145 char *editor = NULL;
7146 int initial_content_len;
7147 int fd = -1;
7149 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7150 err = got_error_from_errno("asprintf");
7151 goto done;
7154 initial_content_len = asprintf(&initial_content,
7155 "\n# tagging commit %s as %s\n",
7156 commit_id_str, tag_name);
7157 if (initial_content_len == -1) {
7158 err = got_error_from_errno("asprintf");
7159 goto done;
7162 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7163 if (err)
7164 goto done;
7166 if (write(fd, initial_content, initial_content_len) == -1) {
7167 err = got_error_from_errno2("write", *tagmsg_path);
7168 goto done;
7171 err = get_editor(&editor);
7172 if (err)
7173 goto done;
7174 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7175 initial_content_len, 1);
7176 done:
7177 free(initial_content);
7178 free(template);
7179 free(editor);
7181 if (fd != -1 && close(fd) == -1 && err == NULL)
7182 err = got_error_from_errno2("close", *tagmsg_path);
7184 if (err) {
7185 free(*tagmsg);
7186 *tagmsg = NULL;
7188 return err;
7191 static const struct got_error *
7192 add_tag(struct got_repository *repo, const char *tagger,
7193 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7194 const char *signer_id, int verbosity)
7196 const struct got_error *err = NULL;
7197 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7198 char *label = NULL, *commit_id_str = NULL;
7199 struct got_reference *ref = NULL;
7200 char *refname = NULL, *tagmsg = NULL;
7201 char *tagmsg_path = NULL, *tag_id_str = NULL;
7202 int preserve_tagmsg = 0;
7203 struct got_reflist_head refs;
7205 TAILQ_INIT(&refs);
7208 * Don't let the user create a tag name with a leading '-'.
7209 * While technically a valid reference name, this case is usually
7210 * an unintended typo.
7212 if (tag_name[0] == '-')
7213 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7215 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7216 if (err)
7217 goto done;
7219 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7220 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7221 if (err)
7222 goto done;
7224 err = got_object_id_str(&commit_id_str, commit_id);
7225 if (err)
7226 goto done;
7228 err = get_tag_refname(&refname, tag_name);
7229 if (err)
7230 goto done;
7231 if (strncmp("refs/tags/", tag_name, 10) == 0)
7232 tag_name += 10;
7234 err = got_ref_open(&ref, repo, refname, 0);
7235 if (err == NULL) {
7236 err = got_error(GOT_ERR_TAG_EXISTS);
7237 goto done;
7238 } else if (err->code != GOT_ERR_NOT_REF)
7239 goto done;
7241 if (tagmsg_arg == NULL) {
7242 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7243 tag_name, got_repo_get_path(repo));
7244 if (err) {
7245 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7246 tagmsg_path != NULL)
7247 preserve_tagmsg = 1;
7248 goto done;
7250 /* Editor is done; we can now apply unveil(2) */
7251 err = got_sigs_apply_unveil();
7252 if (err)
7253 goto done;
7254 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7255 if (err)
7256 goto done;
7259 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7260 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7261 verbosity);
7262 if (err) {
7263 if (tagmsg_path)
7264 preserve_tagmsg = 1;
7265 goto done;
7268 err = got_ref_alloc(&ref, refname, tag_id);
7269 if (err) {
7270 if (tagmsg_path)
7271 preserve_tagmsg = 1;
7272 goto done;
7275 err = got_ref_write(ref, repo);
7276 if (err) {
7277 if (tagmsg_path)
7278 preserve_tagmsg = 1;
7279 goto done;
7282 err = got_object_id_str(&tag_id_str, tag_id);
7283 if (err) {
7284 if (tagmsg_path)
7285 preserve_tagmsg = 1;
7286 goto done;
7288 printf("Created tag %s\n", tag_id_str);
7289 done:
7290 if (preserve_tagmsg) {
7291 fprintf(stderr, "%s: tag message preserved in %s\n",
7292 getprogname(), tagmsg_path);
7293 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7294 err = got_error_from_errno2("unlink", tagmsg_path);
7295 free(tag_id_str);
7296 if (ref)
7297 got_ref_close(ref);
7298 free(commit_id);
7299 free(commit_id_str);
7300 free(refname);
7301 free(tagmsg);
7302 free(tagmsg_path);
7303 got_ref_list_free(&refs);
7304 return err;
7307 static const struct got_error *
7308 cmd_tag(int argc, char *argv[])
7310 const struct got_error *error = NULL;
7311 struct got_repository *repo = NULL;
7312 struct got_worktree *worktree = NULL;
7313 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7314 char *gitconfig_path = NULL, *tagger = NULL;
7315 char *allowed_signers = NULL, *revoked_signers = NULL;
7316 char *signer_id = NULL;
7317 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7318 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7319 int *pack_fds = NULL;
7321 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7322 switch (ch) {
7323 case 'c':
7324 commit_id_arg = optarg;
7325 break;
7326 case 'm':
7327 tagmsg = optarg;
7328 break;
7329 case 'r':
7330 repo_path = realpath(optarg, NULL);
7331 if (repo_path == NULL) {
7332 error = got_error_from_errno2("realpath",
7333 optarg);
7334 goto done;
7336 got_path_strip_trailing_slashes(repo_path);
7337 break;
7338 case 'l':
7339 do_list = 1;
7340 break;
7341 case 's':
7342 signer_id = strdup(optarg);
7343 if (signer_id == NULL) {
7344 error = got_error_from_errno("strdup");
7345 goto done;
7347 break;
7348 case 'V':
7349 verify_tags = 1;
7350 break;
7351 case 'v':
7352 if (verbosity < 0)
7353 verbosity = 0;
7354 else if (verbosity < 3)
7355 verbosity++;
7356 break;
7357 default:
7358 usage_tag();
7359 /* NOTREACHED */
7363 argc -= optind;
7364 argv += optind;
7366 if (do_list || verify_tags) {
7367 if (commit_id_arg != NULL)
7368 errx(1,
7369 "-c option can only be used when creating a tag");
7370 if (tagmsg)
7371 option_conflict('l', 'm');
7372 if (signer_id)
7373 option_conflict('l', 's');
7374 if (verify_tags)
7375 option_conflict('l', 'V');
7376 if (argc > 1)
7377 usage_tag();
7378 } else if (argc != 1)
7379 usage_tag();
7381 if (verify_tags) {
7382 if (commit_id_arg != NULL)
7383 errx(1,
7384 "-c option can only be used when creating a tag");
7385 if (tagmsg)
7386 option_conflict('V', 'm');
7387 if (signer_id)
7388 option_conflict('V', 's');
7389 if (do_list)
7390 option_conflict('V', 'l');
7393 if (argc == 1)
7394 tag_name = argv[0];
7396 #ifndef PROFILE
7397 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7398 "sendfd unveil", NULL) == -1)
7399 err(1, "pledge");
7400 #endif
7401 cwd = getcwd(NULL, 0);
7402 if (cwd == NULL) {
7403 error = got_error_from_errno("getcwd");
7404 goto done;
7407 error = got_repo_pack_fds_open(&pack_fds);
7408 if (error != NULL)
7409 goto done;
7411 if (repo_path == NULL) {
7412 error = got_worktree_open(&worktree, cwd);
7413 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7414 goto done;
7415 else
7416 error = NULL;
7417 if (worktree) {
7418 repo_path =
7419 strdup(got_worktree_get_repo_path(worktree));
7420 if (repo_path == NULL)
7421 error = got_error_from_errno("strdup");
7422 if (error)
7423 goto done;
7424 } else {
7425 repo_path = strdup(cwd);
7426 if (repo_path == NULL) {
7427 error = got_error_from_errno("strdup");
7428 goto done;
7433 if (do_list || verify_tags) {
7434 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7435 if (error != NULL)
7436 goto done;
7437 error = get_allowed_signers(&allowed_signers, repo, worktree);
7438 if (error)
7439 goto done;
7440 error = get_revoked_signers(&revoked_signers, repo, worktree);
7441 if (error)
7442 goto done;
7443 if (worktree) {
7444 /* Release work tree lock. */
7445 got_worktree_close(worktree);
7446 worktree = NULL;
7450 * Remove "cpath" promise unless needed for signature tmpfile
7451 * creation.
7453 if (verify_tags)
7454 got_sigs_apply_unveil();
7455 else {
7456 #ifndef PROFILE
7457 if (pledge("stdio rpath wpath flock proc exec sendfd "
7458 "unveil", NULL) == -1)
7459 err(1, "pledge");
7460 #endif
7462 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7463 if (error)
7464 goto done;
7465 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7466 revoked_signers, verbosity);
7467 } else {
7468 error = get_gitconfig_path(&gitconfig_path);
7469 if (error)
7470 goto done;
7471 error = got_repo_open(&repo, repo_path, gitconfig_path,
7472 pack_fds);
7473 if (error != NULL)
7474 goto done;
7476 error = get_author(&tagger, repo, worktree);
7477 if (error)
7478 goto done;
7479 if (signer_id == NULL) {
7480 error = get_signer_id(&signer_id, repo, worktree);
7481 if (error)
7482 goto done;
7484 if (worktree) {
7485 /* Release work tree lock. */
7486 got_worktree_close(worktree);
7487 worktree = NULL;
7490 if (tagmsg) {
7491 if (signer_id) {
7492 error = got_sigs_apply_unveil();
7493 if (error)
7494 goto done;
7496 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7497 if (error)
7498 goto done;
7501 if (commit_id_arg == NULL) {
7502 struct got_reference *head_ref;
7503 struct got_object_id *commit_id;
7504 error = got_ref_open(&head_ref, repo,
7505 worktree ? got_worktree_get_head_ref_name(worktree)
7506 : GOT_REF_HEAD, 0);
7507 if (error)
7508 goto done;
7509 error = got_ref_resolve(&commit_id, repo, head_ref);
7510 got_ref_close(head_ref);
7511 if (error)
7512 goto done;
7513 error = got_object_id_str(&commit_id_str, commit_id);
7514 free(commit_id);
7515 if (error)
7516 goto done;
7519 error = add_tag(repo, tagger, tag_name,
7520 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7521 signer_id, verbosity);
7523 done:
7524 if (repo) {
7525 const struct got_error *close_err = got_repo_close(repo);
7526 if (error == NULL)
7527 error = close_err;
7529 if (worktree)
7530 got_worktree_close(worktree);
7531 if (pack_fds) {
7532 const struct got_error *pack_err =
7533 got_repo_pack_fds_close(pack_fds);
7534 if (error == NULL)
7535 error = pack_err;
7537 free(cwd);
7538 free(repo_path);
7539 free(gitconfig_path);
7540 free(commit_id_str);
7541 free(tagger);
7542 free(allowed_signers);
7543 free(revoked_signers);
7544 free(signer_id);
7545 return error;
7548 __dead static void
7549 usage_add(void)
7551 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7552 getprogname());
7553 exit(1);
7556 static const struct got_error *
7557 add_progress(void *arg, unsigned char status, const char *path)
7559 while (path[0] == '/')
7560 path++;
7561 printf("%c %s\n", status, path);
7562 return NULL;
7565 static const struct got_error *
7566 cmd_add(int argc, char *argv[])
7568 const struct got_error *error = NULL;
7569 struct got_repository *repo = NULL;
7570 struct got_worktree *worktree = NULL;
7571 char *cwd = NULL;
7572 struct got_pathlist_head paths;
7573 struct got_pathlist_entry *pe;
7574 int ch, can_recurse = 0, no_ignores = 0;
7575 int *pack_fds = NULL;
7577 TAILQ_INIT(&paths);
7579 while ((ch = getopt(argc, argv, "IR")) != -1) {
7580 switch (ch) {
7581 case 'I':
7582 no_ignores = 1;
7583 break;
7584 case 'R':
7585 can_recurse = 1;
7586 break;
7587 default:
7588 usage_add();
7589 /* NOTREACHED */
7593 argc -= optind;
7594 argv += optind;
7596 #ifndef PROFILE
7597 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7598 NULL) == -1)
7599 err(1, "pledge");
7600 #endif
7601 if (argc < 1)
7602 usage_add();
7604 cwd = getcwd(NULL, 0);
7605 if (cwd == NULL) {
7606 error = got_error_from_errno("getcwd");
7607 goto done;
7610 error = got_repo_pack_fds_open(&pack_fds);
7611 if (error != NULL)
7612 goto done;
7614 error = got_worktree_open(&worktree, cwd);
7615 if (error) {
7616 if (error->code == GOT_ERR_NOT_WORKTREE)
7617 error = wrap_not_worktree_error(error, "add", cwd);
7618 goto done;
7621 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7622 NULL, pack_fds);
7623 if (error != NULL)
7624 goto done;
7626 error = apply_unveil(got_repo_get_path(repo), 1,
7627 got_worktree_get_root_path(worktree));
7628 if (error)
7629 goto done;
7631 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7632 if (error)
7633 goto done;
7635 if (!can_recurse) {
7636 char *ondisk_path;
7637 struct stat sb;
7638 TAILQ_FOREACH(pe, &paths, entry) {
7639 if (asprintf(&ondisk_path, "%s/%s",
7640 got_worktree_get_root_path(worktree),
7641 pe->path) == -1) {
7642 error = got_error_from_errno("asprintf");
7643 goto done;
7645 if (lstat(ondisk_path, &sb) == -1) {
7646 if (errno == ENOENT) {
7647 free(ondisk_path);
7648 continue;
7650 error = got_error_from_errno2("lstat",
7651 ondisk_path);
7652 free(ondisk_path);
7653 goto done;
7655 free(ondisk_path);
7656 if (S_ISDIR(sb.st_mode)) {
7657 error = got_error_msg(GOT_ERR_BAD_PATH,
7658 "adding directories requires -R option");
7659 goto done;
7664 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7665 NULL, repo, no_ignores);
7666 done:
7667 if (repo) {
7668 const struct got_error *close_err = got_repo_close(repo);
7669 if (error == NULL)
7670 error = close_err;
7672 if (worktree)
7673 got_worktree_close(worktree);
7674 if (pack_fds) {
7675 const struct got_error *pack_err =
7676 got_repo_pack_fds_close(pack_fds);
7677 if (error == NULL)
7678 error = pack_err;
7680 TAILQ_FOREACH(pe, &paths, entry)
7681 free((char *)pe->path);
7682 got_pathlist_free(&paths);
7683 free(cwd);
7684 return error;
7687 __dead static void
7688 usage_remove(void)
7690 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7691 "path ...\n", getprogname());
7692 exit(1);
7695 static const struct got_error *
7696 print_remove_status(void *arg, unsigned char status,
7697 unsigned char staged_status, const char *path)
7699 while (path[0] == '/')
7700 path++;
7701 if (status == GOT_STATUS_NONEXISTENT)
7702 return NULL;
7703 if (status == staged_status && (status == GOT_STATUS_DELETE))
7704 status = GOT_STATUS_NO_CHANGE;
7705 printf("%c%c %s\n", status, staged_status, path);
7706 return NULL;
7709 static const struct got_error *
7710 cmd_remove(int argc, char *argv[])
7712 const struct got_error *error = NULL;
7713 struct got_worktree *worktree = NULL;
7714 struct got_repository *repo = NULL;
7715 const char *status_codes = NULL;
7716 char *cwd = NULL;
7717 struct got_pathlist_head paths;
7718 struct got_pathlist_entry *pe;
7719 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7720 int ignore_missing_paths = 0;
7721 int *pack_fds = NULL;
7723 TAILQ_INIT(&paths);
7725 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7726 switch (ch) {
7727 case 'f':
7728 delete_local_mods = 1;
7729 ignore_missing_paths = 1;
7730 break;
7731 case 'k':
7732 keep_on_disk = 1;
7733 break;
7734 case 'R':
7735 can_recurse = 1;
7736 break;
7737 case 's':
7738 for (i = 0; i < strlen(optarg); i++) {
7739 switch (optarg[i]) {
7740 case GOT_STATUS_MODIFY:
7741 delete_local_mods = 1;
7742 break;
7743 case GOT_STATUS_MISSING:
7744 ignore_missing_paths = 1;
7745 break;
7746 default:
7747 errx(1, "invalid status code '%c'",
7748 optarg[i]);
7751 status_codes = optarg;
7752 break;
7753 default:
7754 usage_remove();
7755 /* NOTREACHED */
7759 argc -= optind;
7760 argv += optind;
7762 #ifndef PROFILE
7763 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7764 NULL) == -1)
7765 err(1, "pledge");
7766 #endif
7767 if (argc < 1)
7768 usage_remove();
7770 cwd = getcwd(NULL, 0);
7771 if (cwd == NULL) {
7772 error = got_error_from_errno("getcwd");
7773 goto done;
7776 error = got_repo_pack_fds_open(&pack_fds);
7777 if (error != NULL)
7778 goto done;
7780 error = got_worktree_open(&worktree, cwd);
7781 if (error) {
7782 if (error->code == GOT_ERR_NOT_WORKTREE)
7783 error = wrap_not_worktree_error(error, "remove", cwd);
7784 goto done;
7787 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7788 NULL, pack_fds);
7789 if (error)
7790 goto done;
7792 error = apply_unveil(got_repo_get_path(repo), 1,
7793 got_worktree_get_root_path(worktree));
7794 if (error)
7795 goto done;
7797 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7798 if (error)
7799 goto done;
7801 if (!can_recurse) {
7802 char *ondisk_path;
7803 struct stat sb;
7804 TAILQ_FOREACH(pe, &paths, entry) {
7805 if (asprintf(&ondisk_path, "%s/%s",
7806 got_worktree_get_root_path(worktree),
7807 pe->path) == -1) {
7808 error = got_error_from_errno("asprintf");
7809 goto done;
7811 if (lstat(ondisk_path, &sb) == -1) {
7812 if (errno == ENOENT) {
7813 free(ondisk_path);
7814 continue;
7816 error = got_error_from_errno2("lstat",
7817 ondisk_path);
7818 free(ondisk_path);
7819 goto done;
7821 free(ondisk_path);
7822 if (S_ISDIR(sb.st_mode)) {
7823 error = got_error_msg(GOT_ERR_BAD_PATH,
7824 "removing directories requires -R option");
7825 goto done;
7830 error = got_worktree_schedule_delete(worktree, &paths,
7831 delete_local_mods, status_codes, print_remove_status, NULL,
7832 repo, keep_on_disk, ignore_missing_paths);
7833 done:
7834 if (repo) {
7835 const struct got_error *close_err = got_repo_close(repo);
7836 if (error == NULL)
7837 error = close_err;
7839 if (worktree)
7840 got_worktree_close(worktree);
7841 if (pack_fds) {
7842 const struct got_error *pack_err =
7843 got_repo_pack_fds_close(pack_fds);
7844 if (error == NULL)
7845 error = pack_err;
7847 TAILQ_FOREACH(pe, &paths, entry)
7848 free((char *)pe->path);
7849 got_pathlist_free(&paths);
7850 free(cwd);
7851 return error;
7854 __dead static void
7855 usage_patch(void)
7857 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7858 "[-R] [patchfile]\n", getprogname());
7859 exit(1);
7862 static const struct got_error *
7863 patch_from_stdin(int *patchfd)
7865 const struct got_error *err = NULL;
7866 ssize_t r;
7867 char *path, buf[BUFSIZ];
7868 sig_t sighup, sigint, sigquit;
7870 err = got_opentemp_named_fd(&path, patchfd,
7871 GOT_TMPDIR_STR "/got-patch");
7872 if (err)
7873 return err;
7874 unlink(path);
7875 free(path);
7877 sighup = signal(SIGHUP, SIG_DFL);
7878 sigint = signal(SIGINT, SIG_DFL);
7879 sigquit = signal(SIGQUIT, SIG_DFL);
7881 for (;;) {
7882 r = read(0, buf, sizeof(buf));
7883 if (r == -1) {
7884 err = got_error_from_errno("read");
7885 break;
7887 if (r == 0)
7888 break;
7889 if (write(*patchfd, buf, r) == -1) {
7890 err = got_error_from_errno("write");
7891 break;
7895 signal(SIGHUP, sighup);
7896 signal(SIGINT, sigint);
7897 signal(SIGQUIT, sigquit);
7899 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7900 err = got_error_from_errno("lseek");
7902 if (err != NULL) {
7903 close(*patchfd);
7904 *patchfd = -1;
7907 return err;
7910 static const struct got_error *
7911 patch_progress(void *arg, const char *old, const char *new,
7912 unsigned char status, const struct got_error *error, int old_from,
7913 int old_lines, int new_from, int new_lines, int offset,
7914 int ws_mangled, const struct got_error *hunk_err)
7916 const char *path = new == NULL ? old : new;
7918 while (*path == '/')
7919 path++;
7921 if (status != 0)
7922 printf("%c %s\n", status, path);
7924 if (error != NULL)
7925 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7927 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7928 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7929 old_lines, new_from, new_lines);
7930 if (hunk_err != NULL)
7931 printf("%s\n", hunk_err->msg);
7932 else if (offset != 0)
7933 printf("applied with offset %d\n", offset);
7934 else
7935 printf("hunk contains mangled whitespace\n");
7938 return NULL;
7941 static const struct got_error *
7942 cmd_patch(int argc, char *argv[])
7944 const struct got_error *error = NULL, *close_error = NULL;
7945 struct got_worktree *worktree = NULL;
7946 struct got_repository *repo = NULL;
7947 const char *errstr;
7948 char *cwd = NULL;
7949 int ch, nop = 0, strip = -1, reverse = 0;
7950 int patchfd;
7951 int *pack_fds = NULL;
7953 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7954 switch (ch) {
7955 case 'n':
7956 nop = 1;
7957 break;
7958 case 'p':
7959 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7960 if (errstr != NULL)
7961 errx(1, "pathname strip count is %s: %s",
7962 errstr, optarg);
7963 break;
7964 case 'R':
7965 reverse = 1;
7966 break;
7967 default:
7968 usage_patch();
7969 /* NOTREACHED */
7973 argc -= optind;
7974 argv += optind;
7976 if (argc == 0) {
7977 error = patch_from_stdin(&patchfd);
7978 if (error)
7979 return error;
7980 } else if (argc == 1) {
7981 patchfd = open(argv[0], O_RDONLY);
7982 if (patchfd == -1) {
7983 error = got_error_from_errno2("open", argv[0]);
7984 return error;
7986 } else
7987 usage_patch();
7989 if ((cwd = getcwd(NULL, 0)) == NULL) {
7990 error = got_error_from_errno("getcwd");
7991 goto done;
7994 error = got_repo_pack_fds_open(&pack_fds);
7995 if (error != NULL)
7996 goto done;
7998 error = got_worktree_open(&worktree, cwd);
7999 if (error != NULL)
8000 goto done;
8002 const char *repo_path = got_worktree_get_repo_path(worktree);
8003 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8004 if (error != NULL)
8005 goto done;
8007 error = apply_unveil(got_repo_get_path(repo), 0,
8008 got_worktree_get_root_path(worktree));
8009 if (error != NULL)
8010 goto done;
8012 #ifndef PROFILE
8013 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
8014 NULL) == -1)
8015 err(1, "pledge");
8016 #endif
8018 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8019 &patch_progress, NULL, check_cancelled, NULL);
8021 done:
8022 if (repo) {
8023 close_error = got_repo_close(repo);
8024 if (error == NULL)
8025 error = close_error;
8027 if (worktree != NULL) {
8028 close_error = got_worktree_close(worktree);
8029 if (error == NULL)
8030 error = close_error;
8032 if (pack_fds) {
8033 const struct got_error *pack_err =
8034 got_repo_pack_fds_close(pack_fds);
8035 if (error == NULL)
8036 error = pack_err;
8038 free(cwd);
8039 return error;
8042 __dead static void
8043 usage_revert(void)
8045 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
8046 "path ...\n", getprogname());
8047 exit(1);
8050 static const struct got_error *
8051 revert_progress(void *arg, unsigned char status, const char *path)
8053 if (status == GOT_STATUS_UNVERSIONED)
8054 return NULL;
8056 while (path[0] == '/')
8057 path++;
8058 printf("%c %s\n", status, path);
8059 return NULL;
8062 struct choose_patch_arg {
8063 FILE *patch_script_file;
8064 const char *action;
8067 static const struct got_error *
8068 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8069 int nchanges, const char *action)
8071 const struct got_error *err;
8072 char *line = NULL;
8073 size_t linesize = 0;
8074 ssize_t linelen;
8076 switch (status) {
8077 case GOT_STATUS_ADD:
8078 printf("A %s\n%s this addition? [y/n] ", path, action);
8079 break;
8080 case GOT_STATUS_DELETE:
8081 printf("D %s\n%s this deletion? [y/n] ", path, action);
8082 break;
8083 case GOT_STATUS_MODIFY:
8084 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8085 return got_error_from_errno("fseek");
8086 printf(GOT_COMMIT_SEP_STR);
8087 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8088 printf("%s", line);
8089 if (linelen == -1 && ferror(patch_file)) {
8090 err = got_error_from_errno("getline");
8091 free(line);
8092 return err;
8094 free(line);
8095 printf(GOT_COMMIT_SEP_STR);
8096 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8097 path, n, nchanges, action);
8098 break;
8099 default:
8100 return got_error_path(path, GOT_ERR_FILE_STATUS);
8103 return NULL;
8106 static const struct got_error *
8107 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8108 FILE *patch_file, int n, int nchanges)
8110 const struct got_error *err = NULL;
8111 char *line = NULL;
8112 size_t linesize = 0;
8113 ssize_t linelen;
8114 int resp = ' ';
8115 struct choose_patch_arg *a = arg;
8117 *choice = GOT_PATCH_CHOICE_NONE;
8119 if (a->patch_script_file) {
8120 char *nl;
8121 err = show_change(status, path, patch_file, n, nchanges,
8122 a->action);
8123 if (err)
8124 return err;
8125 linelen = getline(&line, &linesize, a->patch_script_file);
8126 if (linelen == -1) {
8127 if (ferror(a->patch_script_file))
8128 return got_error_from_errno("getline");
8129 return NULL;
8131 nl = strchr(line, '\n');
8132 if (nl)
8133 *nl = '\0';
8134 if (strcmp(line, "y") == 0) {
8135 *choice = GOT_PATCH_CHOICE_YES;
8136 printf("y\n");
8137 } else if (strcmp(line, "n") == 0) {
8138 *choice = GOT_PATCH_CHOICE_NO;
8139 printf("n\n");
8140 } else if (strcmp(line, "q") == 0 &&
8141 status == GOT_STATUS_MODIFY) {
8142 *choice = GOT_PATCH_CHOICE_QUIT;
8143 printf("q\n");
8144 } else
8145 printf("invalid response '%s'\n", line);
8146 free(line);
8147 return NULL;
8150 while (resp != 'y' && resp != 'n' && resp != 'q') {
8151 err = show_change(status, path, patch_file, n, nchanges,
8152 a->action);
8153 if (err)
8154 return err;
8155 resp = getchar();
8156 if (resp == '\n')
8157 resp = getchar();
8158 if (status == GOT_STATUS_MODIFY) {
8159 if (resp != 'y' && resp != 'n' && resp != 'q') {
8160 printf("invalid response '%c'\n", resp);
8161 resp = ' ';
8163 } else if (resp != 'y' && resp != 'n') {
8164 printf("invalid response '%c'\n", resp);
8165 resp = ' ';
8169 if (resp == 'y')
8170 *choice = GOT_PATCH_CHOICE_YES;
8171 else if (resp == 'n')
8172 *choice = GOT_PATCH_CHOICE_NO;
8173 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8174 *choice = GOT_PATCH_CHOICE_QUIT;
8176 return NULL;
8179 static const struct got_error *
8180 cmd_revert(int argc, char *argv[])
8182 const struct got_error *error = NULL;
8183 struct got_worktree *worktree = NULL;
8184 struct got_repository *repo = NULL;
8185 char *cwd = NULL, *path = NULL;
8186 struct got_pathlist_head paths;
8187 struct got_pathlist_entry *pe;
8188 int ch, can_recurse = 0, pflag = 0;
8189 FILE *patch_script_file = NULL;
8190 const char *patch_script_path = NULL;
8191 struct choose_patch_arg cpa;
8192 int *pack_fds = NULL;
8194 TAILQ_INIT(&paths);
8196 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8197 switch (ch) {
8198 case 'p':
8199 pflag = 1;
8200 break;
8201 case 'F':
8202 patch_script_path = optarg;
8203 break;
8204 case 'R':
8205 can_recurse = 1;
8206 break;
8207 default:
8208 usage_revert();
8209 /* NOTREACHED */
8213 argc -= optind;
8214 argv += optind;
8216 #ifndef PROFILE
8217 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8218 "unveil", NULL) == -1)
8219 err(1, "pledge");
8220 #endif
8221 if (argc < 1)
8222 usage_revert();
8223 if (patch_script_path && !pflag)
8224 errx(1, "-F option can only be used together with -p option");
8226 cwd = getcwd(NULL, 0);
8227 if (cwd == NULL) {
8228 error = got_error_from_errno("getcwd");
8229 goto done;
8232 error = got_repo_pack_fds_open(&pack_fds);
8233 if (error != NULL)
8234 goto done;
8236 error = got_worktree_open(&worktree, cwd);
8237 if (error) {
8238 if (error->code == GOT_ERR_NOT_WORKTREE)
8239 error = wrap_not_worktree_error(error, "revert", cwd);
8240 goto done;
8243 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8244 NULL, pack_fds);
8245 if (error != NULL)
8246 goto done;
8248 if (patch_script_path) {
8249 patch_script_file = fopen(patch_script_path, "re");
8250 if (patch_script_file == NULL) {
8251 error = got_error_from_errno2("fopen",
8252 patch_script_path);
8253 goto done;
8256 error = apply_unveil(got_repo_get_path(repo), 1,
8257 got_worktree_get_root_path(worktree));
8258 if (error)
8259 goto done;
8261 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8262 if (error)
8263 goto done;
8265 if (!can_recurse) {
8266 char *ondisk_path;
8267 struct stat sb;
8268 TAILQ_FOREACH(pe, &paths, entry) {
8269 if (asprintf(&ondisk_path, "%s/%s",
8270 got_worktree_get_root_path(worktree),
8271 pe->path) == -1) {
8272 error = got_error_from_errno("asprintf");
8273 goto done;
8275 if (lstat(ondisk_path, &sb) == -1) {
8276 if (errno == ENOENT) {
8277 free(ondisk_path);
8278 continue;
8280 error = got_error_from_errno2("lstat",
8281 ondisk_path);
8282 free(ondisk_path);
8283 goto done;
8285 free(ondisk_path);
8286 if (S_ISDIR(sb.st_mode)) {
8287 error = got_error_msg(GOT_ERR_BAD_PATH,
8288 "reverting directories requires -R option");
8289 goto done;
8294 cpa.patch_script_file = patch_script_file;
8295 cpa.action = "revert";
8296 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8297 pflag ? choose_patch : NULL, &cpa, repo);
8298 done:
8299 if (patch_script_file && fclose(patch_script_file) == EOF &&
8300 error == NULL)
8301 error = got_error_from_errno2("fclose", patch_script_path);
8302 if (repo) {
8303 const struct got_error *close_err = got_repo_close(repo);
8304 if (error == NULL)
8305 error = close_err;
8307 if (worktree)
8308 got_worktree_close(worktree);
8309 if (pack_fds) {
8310 const struct got_error *pack_err =
8311 got_repo_pack_fds_close(pack_fds);
8312 if (error == NULL)
8313 error = pack_err;
8315 free(path);
8316 free(cwd);
8317 return error;
8320 __dead static void
8321 usage_commit(void)
8323 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8324 "[path ...]\n", getprogname());
8325 exit(1);
8328 struct collect_commit_logmsg_arg {
8329 const char *cmdline_log;
8330 const char *prepared_log;
8331 int non_interactive;
8332 const char *editor;
8333 const char *worktree_path;
8334 const char *branch_name;
8335 const char *repo_path;
8336 char *logmsg_path;
8340 static const struct got_error *
8341 read_prepared_logmsg(char **logmsg, const char *path)
8343 const struct got_error *err = NULL;
8344 FILE *f = NULL;
8345 struct stat sb;
8346 size_t r;
8348 *logmsg = NULL;
8349 memset(&sb, 0, sizeof(sb));
8351 f = fopen(path, "re");
8352 if (f == NULL)
8353 return got_error_from_errno2("fopen", path);
8355 if (fstat(fileno(f), &sb) == -1) {
8356 err = got_error_from_errno2("fstat", path);
8357 goto done;
8359 if (sb.st_size == 0) {
8360 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8361 goto done;
8364 *logmsg = malloc(sb.st_size + 1);
8365 if (*logmsg == NULL) {
8366 err = got_error_from_errno("malloc");
8367 goto done;
8370 r = fread(*logmsg, 1, sb.st_size, f);
8371 if (r != sb.st_size) {
8372 if (ferror(f))
8373 err = got_error_from_errno2("fread", path);
8374 else
8375 err = got_error(GOT_ERR_IO);
8376 goto done;
8378 (*logmsg)[sb.st_size] = '\0';
8379 done:
8380 if (fclose(f) == EOF && err == NULL)
8381 err = got_error_from_errno2("fclose", path);
8382 if (err) {
8383 free(*logmsg);
8384 *logmsg = NULL;
8386 return err;
8390 static const struct got_error *
8391 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8392 void *arg)
8394 char *initial_content = NULL;
8395 struct got_pathlist_entry *pe;
8396 const struct got_error *err = NULL;
8397 char *template = NULL;
8398 struct collect_commit_logmsg_arg *a = arg;
8399 int initial_content_len;
8400 int fd = -1;
8401 size_t len;
8403 /* if a message was specified on the command line, just use it */
8404 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8405 len = strlen(a->cmdline_log) + 1;
8406 *logmsg = malloc(len + 1);
8407 if (*logmsg == NULL)
8408 return got_error_from_errno("malloc");
8409 strlcpy(*logmsg, a->cmdline_log, len);
8410 return NULL;
8411 } else if (a->prepared_log != NULL && a->non_interactive)
8412 return read_prepared_logmsg(logmsg, a->prepared_log);
8414 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8415 return got_error_from_errno("asprintf");
8417 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8418 if (err)
8419 goto done;
8421 if (a->prepared_log) {
8422 char *msg;
8423 err = read_prepared_logmsg(&msg, a->prepared_log);
8424 if (err)
8425 goto done;
8426 if (write(fd, msg, strlen(msg)) == -1) {
8427 err = got_error_from_errno2("write", a->logmsg_path);
8428 free(msg);
8429 goto done;
8431 free(msg);
8434 initial_content_len = asprintf(&initial_content,
8435 "\n# changes to be committed on branch %s:\n",
8436 a->branch_name);
8437 if (initial_content_len == -1) {
8438 err = got_error_from_errno("asprintf");
8439 goto done;
8442 if (write(fd, initial_content, initial_content_len) == -1) {
8443 err = got_error_from_errno2("write", a->logmsg_path);
8444 goto done;
8447 TAILQ_FOREACH(pe, commitable_paths, entry) {
8448 struct got_commitable *ct = pe->data;
8449 dprintf(fd, "# %c %s\n",
8450 got_commitable_get_status(ct),
8451 got_commitable_get_path(ct));
8454 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8455 initial_content_len, a->prepared_log ? 0 : 1);
8456 done:
8457 free(initial_content);
8458 free(template);
8460 if (fd != -1 && close(fd) == -1 && err == NULL)
8461 err = got_error_from_errno2("close", a->logmsg_path);
8463 /* Editor is done; we can now apply unveil(2) */
8464 if (err == NULL)
8465 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8466 if (err) {
8467 free(*logmsg);
8468 *logmsg = NULL;
8470 return err;
8473 static const struct got_error *
8474 cmd_commit(int argc, char *argv[])
8476 const struct got_error *error = NULL;
8477 struct got_worktree *worktree = NULL;
8478 struct got_repository *repo = NULL;
8479 char *cwd = NULL, *id_str = NULL;
8480 struct got_object_id *id = NULL;
8481 const char *logmsg = NULL;
8482 char *prepared_logmsg = NULL;
8483 struct collect_commit_logmsg_arg cl_arg;
8484 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8485 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8486 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8487 struct got_pathlist_head paths;
8488 int *pack_fds = NULL;
8490 TAILQ_INIT(&paths);
8491 cl_arg.logmsg_path = NULL;
8493 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8494 switch (ch) {
8495 case 'F':
8496 if (logmsg != NULL)
8497 option_conflict('F', 'm');
8498 prepared_logmsg = realpath(optarg, NULL);
8499 if (prepared_logmsg == NULL)
8500 return got_error_from_errno2("realpath",
8501 optarg);
8502 break;
8503 case 'm':
8504 if (prepared_logmsg)
8505 option_conflict('m', 'F');
8506 logmsg = optarg;
8507 break;
8508 case 'N':
8509 non_interactive = 1;
8510 break;
8511 case 'S':
8512 allow_bad_symlinks = 1;
8513 break;
8514 default:
8515 usage_commit();
8516 /* NOTREACHED */
8520 argc -= optind;
8521 argv += optind;
8523 #ifndef PROFILE
8524 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8525 "unveil", NULL) == -1)
8526 err(1, "pledge");
8527 #endif
8528 cwd = getcwd(NULL, 0);
8529 if (cwd == NULL) {
8530 error = got_error_from_errno("getcwd");
8531 goto done;
8534 error = got_repo_pack_fds_open(&pack_fds);
8535 if (error != NULL)
8536 goto done;
8538 error = got_worktree_open(&worktree, cwd);
8539 if (error) {
8540 if (error->code == GOT_ERR_NOT_WORKTREE)
8541 error = wrap_not_worktree_error(error, "commit", cwd);
8542 goto done;
8545 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8546 if (error)
8547 goto done;
8548 if (rebase_in_progress) {
8549 error = got_error(GOT_ERR_REBASING);
8550 goto done;
8553 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8554 worktree);
8555 if (error)
8556 goto done;
8558 error = get_gitconfig_path(&gitconfig_path);
8559 if (error)
8560 goto done;
8561 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8562 gitconfig_path, pack_fds);
8563 if (error != NULL)
8564 goto done;
8566 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8567 if (error)
8568 goto done;
8569 if (merge_in_progress) {
8570 error = got_error(GOT_ERR_MERGE_BUSY);
8571 goto done;
8574 error = get_author(&author, repo, worktree);
8575 if (error)
8576 return error;
8579 * unveil(2) traverses exec(2); if an editor is used we have
8580 * to apply unveil after the log message has been written.
8582 if (logmsg == NULL || strlen(logmsg) == 0)
8583 error = get_editor(&editor);
8584 else
8585 error = apply_unveil(got_repo_get_path(repo), 0,
8586 got_worktree_get_root_path(worktree));
8587 if (error)
8588 goto done;
8590 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8591 if (error)
8592 goto done;
8594 cl_arg.editor = editor;
8595 cl_arg.cmdline_log = logmsg;
8596 cl_arg.prepared_log = prepared_logmsg;
8597 cl_arg.non_interactive = non_interactive;
8598 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8599 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8600 if (!histedit_in_progress) {
8601 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8602 error = got_error(GOT_ERR_COMMIT_BRANCH);
8603 goto done;
8605 cl_arg.branch_name += 11;
8607 cl_arg.repo_path = got_repo_get_path(repo);
8608 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8609 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8610 print_status, NULL, repo);
8611 if (error) {
8612 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8613 cl_arg.logmsg_path != NULL)
8614 preserve_logmsg = 1;
8615 goto done;
8618 error = got_object_id_str(&id_str, id);
8619 if (error)
8620 goto done;
8621 printf("Created commit %s\n", id_str);
8622 done:
8623 if (preserve_logmsg) {
8624 fprintf(stderr, "%s: log message preserved in %s\n",
8625 getprogname(), cl_arg.logmsg_path);
8626 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8627 error == NULL)
8628 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8629 free(cl_arg.logmsg_path);
8630 if (repo) {
8631 const struct got_error *close_err = got_repo_close(repo);
8632 if (error == NULL)
8633 error = close_err;
8635 if (worktree)
8636 got_worktree_close(worktree);
8637 if (pack_fds) {
8638 const struct got_error *pack_err =
8639 got_repo_pack_fds_close(pack_fds);
8640 if (error == NULL)
8641 error = pack_err;
8643 free(cwd);
8644 free(id_str);
8645 free(gitconfig_path);
8646 free(editor);
8647 free(author);
8648 free(prepared_logmsg);
8649 return error;
8652 __dead static void
8653 usage_send(void)
8655 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8656 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8657 "[remote-repository]\n", getprogname());
8658 exit(1);
8661 static void
8662 print_load_info(int print_colored, int print_found, int print_trees,
8663 int ncolored, int nfound, int ntrees)
8665 if (print_colored) {
8666 printf("%d commit%s colored", ncolored,
8667 ncolored == 1 ? "" : "s");
8669 if (print_found) {
8670 printf("%s%d object%s found",
8671 ncolored > 0 ? "; " : "",
8672 nfound, nfound == 1 ? "" : "s");
8674 if (print_trees) {
8675 printf("; %d tree%s scanned", ntrees,
8676 ntrees == 1 ? "" : "s");
8680 struct got_send_progress_arg {
8681 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8682 int verbosity;
8683 int last_ncolored;
8684 int last_nfound;
8685 int last_ntrees;
8686 int loading_done;
8687 int last_ncommits;
8688 int last_nobj_total;
8689 int last_p_deltify;
8690 int last_p_written;
8691 int last_p_sent;
8692 int printed_something;
8693 int sent_something;
8694 struct got_pathlist_head *delete_branches;
8697 static const struct got_error *
8698 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8699 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8700 int nobj_written, off_t bytes_sent, const char *refname, int success)
8702 struct got_send_progress_arg *a = arg;
8703 char scaled_packsize[FMT_SCALED_STRSIZE];
8704 char scaled_sent[FMT_SCALED_STRSIZE];
8705 int p_deltify = 0, p_written = 0, p_sent = 0;
8706 int print_colored = 0, print_found = 0, print_trees = 0;
8707 int print_searching = 0, print_total = 0;
8708 int print_deltify = 0, print_written = 0, print_sent = 0;
8710 if (a->verbosity < 0)
8711 return NULL;
8713 if (refname) {
8714 const char *status = success ? "accepted" : "rejected";
8716 if (success) {
8717 struct got_pathlist_entry *pe;
8718 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8719 const char *branchname = pe->path;
8720 if (got_path_cmp(branchname, refname,
8721 strlen(branchname), strlen(refname)) == 0) {
8722 status = "deleted";
8723 a->sent_something = 1;
8724 break;
8729 if (a->printed_something)
8730 putchar('\n');
8731 printf("Server has %s %s", status, refname);
8732 a->printed_something = 1;
8733 return NULL;
8736 if (a->last_ncolored != ncolored) {
8737 print_colored = 1;
8738 a->last_ncolored = ncolored;
8741 if (a->last_nfound != nfound) {
8742 print_colored = 1;
8743 print_found = 1;
8744 a->last_nfound = nfound;
8747 if (a->last_ntrees != ntrees) {
8748 print_colored = 1;
8749 print_found = 1;
8750 print_trees = 1;
8751 a->last_ntrees = ntrees;
8754 if ((print_colored || print_found || print_trees) &&
8755 !a->loading_done) {
8756 printf("\r");
8757 print_load_info(print_colored, print_found, print_trees,
8758 ncolored, nfound, ntrees);
8759 a->printed_something = 1;
8760 fflush(stdout);
8761 return NULL;
8762 } else if (!a->loading_done) {
8763 printf("\r");
8764 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8765 printf("\n");
8766 a->loading_done = 1;
8769 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8770 return got_error_from_errno("fmt_scaled");
8771 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8772 return got_error_from_errno("fmt_scaled");
8774 if (a->last_ncommits != ncommits) {
8775 print_searching = 1;
8776 a->last_ncommits = ncommits;
8779 if (a->last_nobj_total != nobj_total) {
8780 print_searching = 1;
8781 print_total = 1;
8782 a->last_nobj_total = nobj_total;
8785 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8786 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8787 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8788 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8789 return got_error(GOT_ERR_NO_SPACE);
8792 if (nobj_deltify > 0 || nobj_written > 0) {
8793 if (nobj_deltify > 0) {
8794 p_deltify = (nobj_deltify * 100) / nobj_total;
8795 if (p_deltify != a->last_p_deltify) {
8796 a->last_p_deltify = p_deltify;
8797 print_searching = 1;
8798 print_total = 1;
8799 print_deltify = 1;
8802 if (nobj_written > 0) {
8803 p_written = (nobj_written * 100) / nobj_total;
8804 if (p_written != a->last_p_written) {
8805 a->last_p_written = p_written;
8806 print_searching = 1;
8807 print_total = 1;
8808 print_deltify = 1;
8809 print_written = 1;
8814 if (bytes_sent > 0) {
8815 p_sent = (bytes_sent * 100) / packfile_size;
8816 if (p_sent != a->last_p_sent) {
8817 a->last_p_sent = p_sent;
8818 print_searching = 1;
8819 print_total = 1;
8820 print_deltify = 1;
8821 print_written = 1;
8822 print_sent = 1;
8824 a->sent_something = 1;
8827 if (print_searching || print_total || print_deltify || print_written ||
8828 print_sent)
8829 printf("\r");
8830 if (print_searching)
8831 printf("packing %d reference%s", ncommits,
8832 ncommits == 1 ? "" : "s");
8833 if (print_total)
8834 printf("; %d object%s", nobj_total,
8835 nobj_total == 1 ? "" : "s");
8836 if (print_deltify)
8837 printf("; deltify: %d%%", p_deltify);
8838 if (print_sent)
8839 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8840 scaled_packsize, p_sent);
8841 else if (print_written)
8842 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8843 scaled_packsize, p_written);
8844 if (print_searching || print_total || print_deltify ||
8845 print_written || print_sent) {
8846 a->printed_something = 1;
8847 fflush(stdout);
8849 return NULL;
8852 static const struct got_error *
8853 cmd_send(int argc, char *argv[])
8855 const struct got_error *error = NULL;
8856 char *cwd = NULL, *repo_path = NULL;
8857 const char *remote_name;
8858 char *proto = NULL, *host = NULL, *port = NULL;
8859 char *repo_name = NULL, *server_path = NULL;
8860 const struct got_remote_repo *remotes, *remote = NULL;
8861 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8862 struct got_repository *repo = NULL;
8863 struct got_worktree *worktree = NULL;
8864 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8865 struct got_pathlist_head branches;
8866 struct got_pathlist_head tags;
8867 struct got_reflist_head all_branches;
8868 struct got_reflist_head all_tags;
8869 struct got_pathlist_head delete_args;
8870 struct got_pathlist_head delete_branches;
8871 struct got_reflist_entry *re;
8872 struct got_pathlist_entry *pe;
8873 int i, ch, sendfd = -1, sendstatus;
8874 pid_t sendpid = -1;
8875 struct got_send_progress_arg spa;
8876 int verbosity = 0, overwrite_refs = 0;
8877 int send_all_branches = 0, send_all_tags = 0;
8878 struct got_reference *ref = NULL;
8879 int *pack_fds = NULL;
8881 TAILQ_INIT(&branches);
8882 TAILQ_INIT(&tags);
8883 TAILQ_INIT(&all_branches);
8884 TAILQ_INIT(&all_tags);
8885 TAILQ_INIT(&delete_args);
8886 TAILQ_INIT(&delete_branches);
8888 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8889 switch (ch) {
8890 case 'a':
8891 send_all_branches = 1;
8892 break;
8893 case 'b':
8894 error = got_pathlist_append(&branches, optarg, NULL);
8895 if (error)
8896 return error;
8897 nbranches++;
8898 break;
8899 case 'd':
8900 error = got_pathlist_append(&delete_args, optarg, NULL);
8901 if (error)
8902 return error;
8903 break;
8904 case 'f':
8905 overwrite_refs = 1;
8906 break;
8907 case 'r':
8908 repo_path = realpath(optarg, NULL);
8909 if (repo_path == NULL)
8910 return got_error_from_errno2("realpath",
8911 optarg);
8912 got_path_strip_trailing_slashes(repo_path);
8913 break;
8914 case 't':
8915 error = got_pathlist_append(&tags, optarg, NULL);
8916 if (error)
8917 return error;
8918 ntags++;
8919 break;
8920 case 'T':
8921 send_all_tags = 1;
8922 break;
8923 case 'v':
8924 if (verbosity < 0)
8925 verbosity = 0;
8926 else if (verbosity < 3)
8927 verbosity++;
8928 break;
8929 case 'q':
8930 verbosity = -1;
8931 break;
8932 default:
8933 usage_send();
8934 /* NOTREACHED */
8937 argc -= optind;
8938 argv += optind;
8940 if (send_all_branches && !TAILQ_EMPTY(&branches))
8941 option_conflict('a', 'b');
8942 if (send_all_tags && !TAILQ_EMPTY(&tags))
8943 option_conflict('T', 't');
8946 if (argc == 0)
8947 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8948 else if (argc == 1)
8949 remote_name = argv[0];
8950 else
8951 usage_send();
8953 cwd = getcwd(NULL, 0);
8954 if (cwd == NULL) {
8955 error = got_error_from_errno("getcwd");
8956 goto done;
8959 error = got_repo_pack_fds_open(&pack_fds);
8960 if (error != NULL)
8961 goto done;
8963 if (repo_path == NULL) {
8964 error = got_worktree_open(&worktree, cwd);
8965 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8966 goto done;
8967 else
8968 error = NULL;
8969 if (worktree) {
8970 repo_path =
8971 strdup(got_worktree_get_repo_path(worktree));
8972 if (repo_path == NULL)
8973 error = got_error_from_errno("strdup");
8974 if (error)
8975 goto done;
8976 } else {
8977 repo_path = strdup(cwd);
8978 if (repo_path == NULL) {
8979 error = got_error_from_errno("strdup");
8980 goto done;
8985 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8986 if (error)
8987 goto done;
8989 if (worktree) {
8990 worktree_conf = got_worktree_get_gotconfig(worktree);
8991 if (worktree_conf) {
8992 got_gotconfig_get_remotes(&nremotes, &remotes,
8993 worktree_conf);
8994 for (i = 0; i < nremotes; i++) {
8995 if (strcmp(remotes[i].name, remote_name) == 0) {
8996 remote = &remotes[i];
8997 break;
9002 if (remote == NULL) {
9003 repo_conf = got_repo_get_gotconfig(repo);
9004 if (repo_conf) {
9005 got_gotconfig_get_remotes(&nremotes, &remotes,
9006 repo_conf);
9007 for (i = 0; i < nremotes; i++) {
9008 if (strcmp(remotes[i].name, remote_name) == 0) {
9009 remote = &remotes[i];
9010 break;
9015 if (remote == NULL) {
9016 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9017 for (i = 0; i < nremotes; i++) {
9018 if (strcmp(remotes[i].name, remote_name) == 0) {
9019 remote = &remotes[i];
9020 break;
9024 if (remote == NULL) {
9025 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9026 goto done;
9029 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9030 &repo_name, remote->send_url);
9031 if (error)
9032 goto done;
9034 if (strcmp(proto, "git") == 0) {
9035 #ifndef PROFILE
9036 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9037 "sendfd dns inet unveil", NULL) == -1)
9038 err(1, "pledge");
9039 #endif
9040 } else if (strcmp(proto, "git+ssh") == 0 ||
9041 strcmp(proto, "ssh") == 0) {
9042 #ifndef PROFILE
9043 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9044 "sendfd unveil", NULL) == -1)
9045 err(1, "pledge");
9046 #endif
9047 } else if (strcmp(proto, "http") == 0 ||
9048 strcmp(proto, "git+http") == 0) {
9049 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9050 goto done;
9051 } else {
9052 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9053 goto done;
9056 error = got_dial_apply_unveil(proto);
9057 if (error)
9058 goto done;
9060 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9061 if (error)
9062 goto done;
9064 if (send_all_branches) {
9065 error = got_ref_list(&all_branches, repo, "refs/heads",
9066 got_ref_cmp_by_name, NULL);
9067 if (error)
9068 goto done;
9069 TAILQ_FOREACH(re, &all_branches, entry) {
9070 const char *branchname = got_ref_get_name(re->ref);
9071 error = got_pathlist_append(&branches,
9072 branchname, NULL);
9073 if (error)
9074 goto done;
9075 nbranches++;
9077 } else if (nbranches == 0) {
9078 for (i = 0; i < remote->nsend_branches; i++) {
9079 got_pathlist_append(&branches,
9080 remote->send_branches[i], NULL);
9084 if (send_all_tags) {
9085 error = got_ref_list(&all_tags, repo, "refs/tags",
9086 got_ref_cmp_by_name, NULL);
9087 if (error)
9088 goto done;
9089 TAILQ_FOREACH(re, &all_tags, entry) {
9090 const char *tagname = got_ref_get_name(re->ref);
9091 error = got_pathlist_append(&tags,
9092 tagname, NULL);
9093 if (error)
9094 goto done;
9095 ntags++;
9100 * To prevent accidents only branches in refs/heads/ can be deleted
9101 * with 'got send -d'.
9102 * Deleting anything else requires local repository access or Git.
9104 TAILQ_FOREACH(pe, &delete_args, entry) {
9105 const char *branchname = pe->path;
9106 char *s;
9107 struct got_pathlist_entry *new;
9108 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9109 s = strdup(branchname);
9110 if (s == NULL) {
9111 error = got_error_from_errno("strdup");
9112 goto done;
9114 } else {
9115 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9116 error = got_error_from_errno("asprintf");
9117 goto done;
9120 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9121 if (error || new == NULL /* duplicate */)
9122 free(s);
9123 if (error)
9124 goto done;
9125 ndelete_branches++;
9128 if (nbranches == 0 && ndelete_branches == 0) {
9129 struct got_reference *head_ref;
9130 if (worktree)
9131 error = got_ref_open(&head_ref, repo,
9132 got_worktree_get_head_ref_name(worktree), 0);
9133 else
9134 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9135 if (error)
9136 goto done;
9137 if (got_ref_is_symbolic(head_ref)) {
9138 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9139 got_ref_close(head_ref);
9140 if (error)
9141 goto done;
9142 } else
9143 ref = head_ref;
9144 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9145 NULL);
9146 if (error)
9147 goto done;
9148 nbranches++;
9151 if (verbosity >= 0)
9152 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9153 port ? ":" : "", port ? port : "");
9155 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9156 server_path, verbosity);
9157 if (error)
9158 goto done;
9160 memset(&spa, 0, sizeof(spa));
9161 spa.last_scaled_packsize[0] = '\0';
9162 spa.last_p_deltify = -1;
9163 spa.last_p_written = -1;
9164 spa.verbosity = verbosity;
9165 spa.delete_branches = &delete_branches;
9166 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9167 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9168 check_cancelled, NULL);
9169 if (spa.printed_something)
9170 putchar('\n');
9171 if (error)
9172 goto done;
9173 if (!spa.sent_something && verbosity >= 0)
9174 printf("Already up-to-date\n");
9175 done:
9176 if (sendpid > 0) {
9177 if (kill(sendpid, SIGTERM) == -1)
9178 error = got_error_from_errno("kill");
9179 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9180 error = got_error_from_errno("waitpid");
9182 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9183 error = got_error_from_errno("close");
9184 if (repo) {
9185 const struct got_error *close_err = got_repo_close(repo);
9186 if (error == NULL)
9187 error = close_err;
9189 if (worktree)
9190 got_worktree_close(worktree);
9191 if (pack_fds) {
9192 const struct got_error *pack_err =
9193 got_repo_pack_fds_close(pack_fds);
9194 if (error == NULL)
9195 error = pack_err;
9197 if (ref)
9198 got_ref_close(ref);
9199 got_pathlist_free(&branches);
9200 got_pathlist_free(&tags);
9201 got_ref_list_free(&all_branches);
9202 got_ref_list_free(&all_tags);
9203 got_pathlist_free(&delete_args);
9204 TAILQ_FOREACH(pe, &delete_branches, entry)
9205 free((char *)pe->path);
9206 got_pathlist_free(&delete_branches);
9207 free(cwd);
9208 free(repo_path);
9209 free(proto);
9210 free(host);
9211 free(port);
9212 free(server_path);
9213 free(repo_name);
9214 return error;
9217 __dead static void
9218 usage_cherrypick(void)
9220 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9221 exit(1);
9224 static const struct got_error *
9225 cmd_cherrypick(int argc, char *argv[])
9227 const struct got_error *error = NULL;
9228 struct got_worktree *worktree = NULL;
9229 struct got_repository *repo = NULL;
9230 char *cwd = NULL, *commit_id_str = NULL;
9231 struct got_object_id *commit_id = NULL;
9232 struct got_commit_object *commit = NULL;
9233 struct got_object_qid *pid;
9234 int ch;
9235 struct got_update_progress_arg upa;
9236 int *pack_fds = NULL;
9238 while ((ch = getopt(argc, argv, "")) != -1) {
9239 switch (ch) {
9240 default:
9241 usage_cherrypick();
9242 /* NOTREACHED */
9246 argc -= optind;
9247 argv += optind;
9249 #ifndef PROFILE
9250 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9251 "unveil", NULL) == -1)
9252 err(1, "pledge");
9253 #endif
9254 if (argc != 1)
9255 usage_cherrypick();
9257 cwd = getcwd(NULL, 0);
9258 if (cwd == NULL) {
9259 error = got_error_from_errno("getcwd");
9260 goto done;
9263 error = got_repo_pack_fds_open(&pack_fds);
9264 if (error != NULL)
9265 goto done;
9267 error = got_worktree_open(&worktree, cwd);
9268 if (error) {
9269 if (error->code == GOT_ERR_NOT_WORKTREE)
9270 error = wrap_not_worktree_error(error, "cherrypick",
9271 cwd);
9272 goto done;
9275 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9276 NULL, pack_fds);
9277 if (error != NULL)
9278 goto done;
9280 error = apply_unveil(got_repo_get_path(repo), 0,
9281 got_worktree_get_root_path(worktree));
9282 if (error)
9283 goto done;
9285 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9286 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9287 if (error)
9288 goto done;
9289 error = got_object_id_str(&commit_id_str, commit_id);
9290 if (error)
9291 goto done;
9293 error = got_object_open_as_commit(&commit, repo, commit_id);
9294 if (error)
9295 goto done;
9296 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9297 memset(&upa, 0, sizeof(upa));
9298 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9299 commit_id, repo, update_progress, &upa, check_cancelled,
9300 NULL);
9301 if (error != NULL)
9302 goto done;
9304 if (upa.did_something)
9305 printf("Merged commit %s\n", commit_id_str);
9306 print_merge_progress_stats(&upa);
9307 done:
9308 if (commit)
9309 got_object_commit_close(commit);
9310 free(commit_id_str);
9311 if (worktree)
9312 got_worktree_close(worktree);
9313 if (repo) {
9314 const struct got_error *close_err = got_repo_close(repo);
9315 if (error == NULL)
9316 error = close_err;
9318 if (pack_fds) {
9319 const struct got_error *pack_err =
9320 got_repo_pack_fds_close(pack_fds);
9321 if (error == NULL)
9322 error = pack_err;
9325 return error;
9328 __dead static void
9329 usage_backout(void)
9331 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9332 exit(1);
9335 static const struct got_error *
9336 cmd_backout(int argc, char *argv[])
9338 const struct got_error *error = NULL;
9339 struct got_worktree *worktree = NULL;
9340 struct got_repository *repo = NULL;
9341 char *cwd = NULL, *commit_id_str = NULL;
9342 struct got_object_id *commit_id = NULL;
9343 struct got_commit_object *commit = NULL;
9344 struct got_object_qid *pid;
9345 int ch;
9346 struct got_update_progress_arg upa;
9347 int *pack_fds = NULL;
9349 while ((ch = getopt(argc, argv, "")) != -1) {
9350 switch (ch) {
9351 default:
9352 usage_backout();
9353 /* NOTREACHED */
9357 argc -= optind;
9358 argv += optind;
9360 #ifndef PROFILE
9361 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9362 "unveil", NULL) == -1)
9363 err(1, "pledge");
9364 #endif
9365 if (argc != 1)
9366 usage_backout();
9368 cwd = getcwd(NULL, 0);
9369 if (cwd == NULL) {
9370 error = got_error_from_errno("getcwd");
9371 goto done;
9374 error = got_repo_pack_fds_open(&pack_fds);
9375 if (error != NULL)
9376 goto done;
9378 error = got_worktree_open(&worktree, cwd);
9379 if (error) {
9380 if (error->code == GOT_ERR_NOT_WORKTREE)
9381 error = wrap_not_worktree_error(error, "backout", cwd);
9382 goto done;
9385 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9386 NULL, pack_fds);
9387 if (error != NULL)
9388 goto done;
9390 error = apply_unveil(got_repo_get_path(repo), 0,
9391 got_worktree_get_root_path(worktree));
9392 if (error)
9393 goto done;
9395 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9396 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9397 if (error)
9398 goto done;
9399 error = got_object_id_str(&commit_id_str, commit_id);
9400 if (error)
9401 goto done;
9403 error = got_object_open_as_commit(&commit, repo, commit_id);
9404 if (error)
9405 goto done;
9406 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9407 if (pid == NULL) {
9408 error = got_error(GOT_ERR_ROOT_COMMIT);
9409 goto done;
9412 memset(&upa, 0, sizeof(upa));
9413 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9414 repo, update_progress, &upa, check_cancelled, NULL);
9415 if (error != NULL)
9416 goto done;
9418 if (upa.did_something)
9419 printf("Backed out commit %s\n", commit_id_str);
9420 print_merge_progress_stats(&upa);
9421 done:
9422 if (commit)
9423 got_object_commit_close(commit);
9424 free(commit_id_str);
9425 if (worktree)
9426 got_worktree_close(worktree);
9427 if (repo) {
9428 const struct got_error *close_err = got_repo_close(repo);
9429 if (error == NULL)
9430 error = close_err;
9432 if (pack_fds) {
9433 const struct got_error *pack_err =
9434 got_repo_pack_fds_close(pack_fds);
9435 if (error == NULL)
9436 error = pack_err;
9438 return error;
9441 __dead static void
9442 usage_rebase(void)
9444 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9445 getprogname());
9446 exit(1);
9449 static void
9450 trim_logmsg(char *logmsg, int limit)
9452 char *nl;
9453 size_t len;
9455 len = strlen(logmsg);
9456 if (len > limit)
9457 len = limit;
9458 logmsg[len] = '\0';
9459 nl = strchr(logmsg, '\n');
9460 if (nl)
9461 *nl = '\0';
9464 static const struct got_error *
9465 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9467 const struct got_error *err;
9468 char *logmsg0 = NULL;
9469 const char *s;
9471 err = got_object_commit_get_logmsg(&logmsg0, commit);
9472 if (err)
9473 return err;
9475 s = logmsg0;
9476 while (isspace((unsigned char)s[0]))
9477 s++;
9479 *logmsg = strdup(s);
9480 if (*logmsg == NULL) {
9481 err = got_error_from_errno("strdup");
9482 goto done;
9485 trim_logmsg(*logmsg, limit);
9486 done:
9487 free(logmsg0);
9488 return err;
9491 static const struct got_error *
9492 show_rebase_merge_conflict(struct got_object_id *id,
9493 struct got_repository *repo)
9495 const struct got_error *err;
9496 struct got_commit_object *commit = NULL;
9497 char *id_str = NULL, *logmsg = NULL;
9499 err = got_object_open_as_commit(&commit, repo, id);
9500 if (err)
9501 return err;
9503 err = got_object_id_str(&id_str, id);
9504 if (err)
9505 goto done;
9507 id_str[12] = '\0';
9509 err = get_short_logmsg(&logmsg, 42, commit);
9510 if (err)
9511 goto done;
9513 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9514 done:
9515 free(id_str);
9516 got_object_commit_close(commit);
9517 free(logmsg);
9518 return err;
9521 static const struct got_error *
9522 show_rebase_progress(struct got_commit_object *commit,
9523 struct got_object_id *old_id, struct got_object_id *new_id)
9525 const struct got_error *err;
9526 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9528 err = got_object_id_str(&old_id_str, old_id);
9529 if (err)
9530 goto done;
9532 if (new_id) {
9533 err = got_object_id_str(&new_id_str, new_id);
9534 if (err)
9535 goto done;
9538 old_id_str[12] = '\0';
9539 if (new_id_str)
9540 new_id_str[12] = '\0';
9542 err = get_short_logmsg(&logmsg, 42, commit);
9543 if (err)
9544 goto done;
9546 printf("%s -> %s: %s\n", old_id_str,
9547 new_id_str ? new_id_str : "no-op change", logmsg);
9548 done:
9549 free(old_id_str);
9550 free(new_id_str);
9551 free(logmsg);
9552 return err;
9555 static const struct got_error *
9556 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9557 struct got_reference *branch, struct got_reference *new_base_branch,
9558 struct got_reference *tmp_branch, struct got_repository *repo,
9559 int create_backup)
9561 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9562 return got_worktree_rebase_complete(worktree, fileindex,
9563 new_base_branch, tmp_branch, branch, repo, create_backup);
9566 static const struct got_error *
9567 rebase_commit(struct got_pathlist_head *merged_paths,
9568 struct got_worktree *worktree, struct got_fileindex *fileindex,
9569 struct got_reference *tmp_branch,
9570 struct got_object_id *commit_id, struct got_repository *repo)
9572 const struct got_error *error;
9573 struct got_commit_object *commit;
9574 struct got_object_id *new_commit_id;
9576 error = got_object_open_as_commit(&commit, repo, commit_id);
9577 if (error)
9578 return error;
9580 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9581 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9582 if (error) {
9583 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9584 goto done;
9585 error = show_rebase_progress(commit, commit_id, NULL);
9586 } else {
9587 error = show_rebase_progress(commit, commit_id, new_commit_id);
9588 free(new_commit_id);
9590 done:
9591 got_object_commit_close(commit);
9592 return error;
9595 struct check_path_prefix_arg {
9596 const char *path_prefix;
9597 size_t len;
9598 int errcode;
9601 static const struct got_error *
9602 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9603 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9604 struct got_object_id *id1, struct got_object_id *id2,
9605 const char *path1, const char *path2,
9606 mode_t mode1, mode_t mode2, struct got_repository *repo)
9608 struct check_path_prefix_arg *a = arg;
9610 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9611 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9612 return got_error(a->errcode);
9614 return NULL;
9617 static const struct got_error *
9618 check_path_prefix(struct got_object_id *parent_id,
9619 struct got_object_id *commit_id, const char *path_prefix,
9620 int errcode, struct got_repository *repo)
9622 const struct got_error *err;
9623 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9624 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9625 struct check_path_prefix_arg cpp_arg;
9627 if (got_path_is_root_dir(path_prefix))
9628 return NULL;
9630 err = got_object_open_as_commit(&commit, repo, commit_id);
9631 if (err)
9632 goto done;
9634 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9635 if (err)
9636 goto done;
9638 err = got_object_open_as_tree(&tree1, repo,
9639 got_object_commit_get_tree_id(parent_commit));
9640 if (err)
9641 goto done;
9643 err = got_object_open_as_tree(&tree2, repo,
9644 got_object_commit_get_tree_id(commit));
9645 if (err)
9646 goto done;
9648 cpp_arg.path_prefix = path_prefix;
9649 while (cpp_arg.path_prefix[0] == '/')
9650 cpp_arg.path_prefix++;
9651 cpp_arg.len = strlen(cpp_arg.path_prefix);
9652 cpp_arg.errcode = errcode;
9653 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9654 check_path_prefix_in_diff, &cpp_arg, 0);
9655 done:
9656 if (tree1)
9657 got_object_tree_close(tree1);
9658 if (tree2)
9659 got_object_tree_close(tree2);
9660 if (commit)
9661 got_object_commit_close(commit);
9662 if (parent_commit)
9663 got_object_commit_close(parent_commit);
9664 return err;
9667 static const struct got_error *
9668 collect_commits(struct got_object_id_queue *commits,
9669 struct got_object_id *initial_commit_id,
9670 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9671 const char *path_prefix, int path_prefix_errcode,
9672 struct got_repository *repo)
9674 const struct got_error *err = NULL;
9675 struct got_commit_graph *graph = NULL;
9676 struct got_object_id *parent_id = NULL;
9677 struct got_object_qid *qid;
9678 struct got_object_id *commit_id = initial_commit_id;
9680 err = got_commit_graph_open(&graph, "/", 1);
9681 if (err)
9682 return err;
9684 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9685 check_cancelled, NULL);
9686 if (err)
9687 goto done;
9688 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9689 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9690 check_cancelled, NULL);
9691 if (err) {
9692 if (err->code == GOT_ERR_ITER_COMPLETED) {
9693 err = got_error_msg(GOT_ERR_ANCESTRY,
9694 "ran out of commits to rebase before "
9695 "youngest common ancestor commit has "
9696 "been reached?!?");
9698 goto done;
9699 } else {
9700 err = check_path_prefix(parent_id, commit_id,
9701 path_prefix, path_prefix_errcode, repo);
9702 if (err)
9703 goto done;
9705 err = got_object_qid_alloc(&qid, commit_id);
9706 if (err)
9707 goto done;
9708 STAILQ_INSERT_HEAD(commits, qid, entry);
9709 commit_id = parent_id;
9712 done:
9713 got_commit_graph_close(graph);
9714 return err;
9717 static const struct got_error *
9718 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9720 const struct got_error *err = NULL;
9721 time_t committer_time;
9722 struct tm tm;
9723 char datebuf[11]; /* YYYY-MM-DD + NUL */
9724 char *author0 = NULL, *author, *smallerthan;
9725 char *logmsg0 = NULL, *logmsg, *newline;
9727 committer_time = got_object_commit_get_committer_time(commit);
9728 if (gmtime_r(&committer_time, &tm) == NULL)
9729 return got_error_from_errno("gmtime_r");
9730 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9731 return got_error(GOT_ERR_NO_SPACE);
9733 author0 = strdup(got_object_commit_get_author(commit));
9734 if (author0 == NULL)
9735 return got_error_from_errno("strdup");
9736 author = author0;
9737 smallerthan = strchr(author, '<');
9738 if (smallerthan && smallerthan[1] != '\0')
9739 author = smallerthan + 1;
9740 author[strcspn(author, "@>")] = '\0';
9742 err = got_object_commit_get_logmsg(&logmsg0, commit);
9743 if (err)
9744 goto done;
9745 logmsg = logmsg0;
9746 while (*logmsg == '\n')
9747 logmsg++;
9748 newline = strchr(logmsg, '\n');
9749 if (newline)
9750 *newline = '\0';
9752 if (asprintf(brief_str, "%s %s %s",
9753 datebuf, author, logmsg) == -1)
9754 err = got_error_from_errno("asprintf");
9755 done:
9756 free(author0);
9757 free(logmsg0);
9758 return err;
9761 static const struct got_error *
9762 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9763 struct got_repository *repo)
9765 const struct got_error *err;
9766 char *id_str;
9768 err = got_object_id_str(&id_str, id);
9769 if (err)
9770 return err;
9772 err = got_ref_delete(ref, repo);
9773 if (err)
9774 goto done;
9776 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9777 done:
9778 free(id_str);
9779 return err;
9782 static const struct got_error *
9783 print_backup_ref(const char *branch_name, const char *new_id_str,
9784 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9785 struct got_reflist_object_id_map *refs_idmap,
9786 struct got_repository *repo)
9788 const struct got_error *err = NULL;
9789 struct got_reflist_head *refs;
9790 char *refs_str = NULL;
9791 struct got_object_id *new_commit_id = NULL;
9792 struct got_commit_object *new_commit = NULL;
9793 char *new_commit_brief_str = NULL;
9794 struct got_object_id *yca_id = NULL;
9795 struct got_commit_object *yca_commit = NULL;
9796 char *yca_id_str = NULL, *yca_brief_str = NULL;
9797 char *custom_refs_str;
9799 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9800 return got_error_from_errno("asprintf");
9802 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9803 0, 0, refs_idmap, custom_refs_str);
9804 if (err)
9805 goto done;
9807 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9808 if (err)
9809 goto done;
9811 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9812 if (refs) {
9813 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9814 if (err)
9815 goto done;
9818 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9819 if (err)
9820 goto done;
9822 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9823 if (err)
9824 goto done;
9826 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9827 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9828 if (err)
9829 goto done;
9831 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9832 refs_str ? " (" : "", refs_str ? refs_str : "",
9833 refs_str ? ")" : "", new_commit_brief_str);
9834 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9835 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9836 free(refs_str);
9837 refs_str = NULL;
9839 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9840 if (err)
9841 goto done;
9843 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9844 if (err)
9845 goto done;
9847 err = got_object_id_str(&yca_id_str, yca_id);
9848 if (err)
9849 goto done;
9851 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9852 if (refs) {
9853 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9854 if (err)
9855 goto done;
9857 printf("history forked at %s%s%s%s\n %s\n",
9858 yca_id_str,
9859 refs_str ? " (" : "", refs_str ? refs_str : "",
9860 refs_str ? ")" : "", yca_brief_str);
9862 done:
9863 free(custom_refs_str);
9864 free(new_commit_id);
9865 free(refs_str);
9866 free(yca_id);
9867 free(yca_id_str);
9868 free(yca_brief_str);
9869 if (new_commit)
9870 got_object_commit_close(new_commit);
9871 if (yca_commit)
9872 got_object_commit_close(yca_commit);
9874 return NULL;
9877 static const struct got_error *
9878 process_backup_refs(const char *backup_ref_prefix,
9879 const char *wanted_branch_name,
9880 int delete, struct got_repository *repo)
9882 const struct got_error *err;
9883 struct got_reflist_head refs, backup_refs;
9884 struct got_reflist_entry *re;
9885 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9886 struct got_object_id *old_commit_id = NULL;
9887 char *branch_name = NULL;
9888 struct got_commit_object *old_commit = NULL;
9889 struct got_reflist_object_id_map *refs_idmap = NULL;
9890 int wanted_branch_found = 0;
9892 TAILQ_INIT(&refs);
9893 TAILQ_INIT(&backup_refs);
9895 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9896 if (err)
9897 return err;
9899 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9900 if (err)
9901 goto done;
9903 if (wanted_branch_name) {
9904 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9905 wanted_branch_name += 11;
9908 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9909 got_ref_cmp_by_commit_timestamp_descending, repo);
9910 if (err)
9911 goto done;
9913 TAILQ_FOREACH(re, &backup_refs, entry) {
9914 const char *refname = got_ref_get_name(re->ref);
9915 char *slash;
9917 err = check_cancelled(NULL);
9918 if (err)
9919 break;
9921 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9922 if (err)
9923 break;
9925 err = got_object_open_as_commit(&old_commit, repo,
9926 old_commit_id);
9927 if (err)
9928 break;
9930 if (strncmp(backup_ref_prefix, refname,
9931 backup_ref_prefix_len) == 0)
9932 refname += backup_ref_prefix_len;
9934 while (refname[0] == '/')
9935 refname++;
9937 branch_name = strdup(refname);
9938 if (branch_name == NULL) {
9939 err = got_error_from_errno("strdup");
9940 break;
9942 slash = strrchr(branch_name, '/');
9943 if (slash) {
9944 *slash = '\0';
9945 refname += strlen(branch_name) + 1;
9948 if (wanted_branch_name == NULL ||
9949 strcmp(wanted_branch_name, branch_name) == 0) {
9950 wanted_branch_found = 1;
9951 if (delete) {
9952 err = delete_backup_ref(re->ref,
9953 old_commit_id, repo);
9954 } else {
9955 err = print_backup_ref(branch_name, refname,
9956 old_commit_id, old_commit, refs_idmap,
9957 repo);
9959 if (err)
9960 break;
9963 free(old_commit_id);
9964 old_commit_id = NULL;
9965 free(branch_name);
9966 branch_name = NULL;
9967 got_object_commit_close(old_commit);
9968 old_commit = NULL;
9971 if (wanted_branch_name && !wanted_branch_found) {
9972 err = got_error_fmt(GOT_ERR_NOT_REF,
9973 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9975 done:
9976 if (refs_idmap)
9977 got_reflist_object_id_map_free(refs_idmap);
9978 got_ref_list_free(&refs);
9979 got_ref_list_free(&backup_refs);
9980 free(old_commit_id);
9981 free(branch_name);
9982 if (old_commit)
9983 got_object_commit_close(old_commit);
9984 return err;
9987 static const struct got_error *
9988 abort_progress(void *arg, unsigned char status, const char *path)
9991 * Unversioned files should not clutter progress output when
9992 * an operation is aborted.
9994 if (status == GOT_STATUS_UNVERSIONED)
9995 return NULL;
9997 return update_progress(arg, status, path);
10000 static const struct got_error *
10001 cmd_rebase(int argc, char *argv[])
10003 const struct got_error *error = NULL;
10004 struct got_worktree *worktree = NULL;
10005 struct got_repository *repo = NULL;
10006 struct got_fileindex *fileindex = NULL;
10007 char *cwd = NULL;
10008 struct got_reference *branch = NULL;
10009 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10010 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10011 struct got_object_id *resume_commit_id = NULL;
10012 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10013 struct got_commit_object *commit = NULL;
10014 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10015 int histedit_in_progress = 0, merge_in_progress = 0;
10016 int create_backup = 1, list_backups = 0, delete_backups = 0;
10017 struct got_object_id_queue commits;
10018 struct got_pathlist_head merged_paths;
10019 const struct got_object_id_queue *parent_ids;
10020 struct got_object_qid *qid, *pid;
10021 struct got_update_progress_arg upa;
10022 int *pack_fds = NULL;
10024 STAILQ_INIT(&commits);
10025 TAILQ_INIT(&merged_paths);
10026 memset(&upa, 0, sizeof(upa));
10028 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10029 switch (ch) {
10030 case 'a':
10031 abort_rebase = 1;
10032 break;
10033 case 'c':
10034 continue_rebase = 1;
10035 break;
10036 case 'l':
10037 list_backups = 1;
10038 break;
10039 case 'X':
10040 delete_backups = 1;
10041 break;
10042 default:
10043 usage_rebase();
10044 /* NOTREACHED */
10048 argc -= optind;
10049 argv += optind;
10051 #ifndef PROFILE
10052 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10053 "unveil", NULL) == -1)
10054 err(1, "pledge");
10055 #endif
10056 if (list_backups) {
10057 if (abort_rebase)
10058 option_conflict('l', 'a');
10059 if (continue_rebase)
10060 option_conflict('l', 'c');
10061 if (delete_backups)
10062 option_conflict('l', 'X');
10063 if (argc != 0 && argc != 1)
10064 usage_rebase();
10065 } else if (delete_backups) {
10066 if (abort_rebase)
10067 option_conflict('X', 'a');
10068 if (continue_rebase)
10069 option_conflict('X', 'c');
10070 if (list_backups)
10071 option_conflict('l', 'X');
10072 if (argc != 0 && argc != 1)
10073 usage_rebase();
10074 } else {
10075 if (abort_rebase && continue_rebase)
10076 usage_rebase();
10077 else if (abort_rebase || continue_rebase) {
10078 if (argc != 0)
10079 usage_rebase();
10080 } else if (argc != 1)
10081 usage_rebase();
10084 cwd = getcwd(NULL, 0);
10085 if (cwd == NULL) {
10086 error = got_error_from_errno("getcwd");
10087 goto done;
10090 error = got_repo_pack_fds_open(&pack_fds);
10091 if (error != NULL)
10092 goto done;
10094 error = got_worktree_open(&worktree, cwd);
10095 if (error) {
10096 if (list_backups || delete_backups) {
10097 if (error->code != GOT_ERR_NOT_WORKTREE)
10098 goto done;
10099 } else {
10100 if (error->code == GOT_ERR_NOT_WORKTREE)
10101 error = wrap_not_worktree_error(error,
10102 "rebase", cwd);
10103 goto done;
10107 error = got_repo_open(&repo,
10108 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
10109 pack_fds);
10110 if (error != NULL)
10111 goto done;
10113 error = apply_unveil(got_repo_get_path(repo), 0,
10114 worktree ? got_worktree_get_root_path(worktree) : NULL);
10115 if (error)
10116 goto done;
10118 if (list_backups || delete_backups) {
10119 error = process_backup_refs(
10120 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10121 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10122 goto done; /* nothing else to do */
10125 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10126 worktree);
10127 if (error)
10128 goto done;
10129 if (histedit_in_progress) {
10130 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10131 goto done;
10134 error = got_worktree_merge_in_progress(&merge_in_progress,
10135 worktree, repo);
10136 if (error)
10137 goto done;
10138 if (merge_in_progress) {
10139 error = got_error(GOT_ERR_MERGE_BUSY);
10140 goto done;
10143 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10144 if (error)
10145 goto done;
10147 if (abort_rebase) {
10148 if (!rebase_in_progress) {
10149 error = got_error(GOT_ERR_NOT_REBASING);
10150 goto done;
10152 error = got_worktree_rebase_continue(&resume_commit_id,
10153 &new_base_branch, &tmp_branch, &branch, &fileindex,
10154 worktree, repo);
10155 if (error)
10156 goto done;
10157 printf("Switching work tree to %s\n",
10158 got_ref_get_symref_target(new_base_branch));
10159 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10160 new_base_branch, abort_progress, &upa);
10161 if (error)
10162 goto done;
10163 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10164 print_merge_progress_stats(&upa);
10165 goto done; /* nothing else to do */
10168 if (continue_rebase) {
10169 if (!rebase_in_progress) {
10170 error = got_error(GOT_ERR_NOT_REBASING);
10171 goto done;
10173 error = got_worktree_rebase_continue(&resume_commit_id,
10174 &new_base_branch, &tmp_branch, &branch, &fileindex,
10175 worktree, repo);
10176 if (error)
10177 goto done;
10179 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10180 resume_commit_id, repo);
10181 if (error)
10182 goto done;
10184 yca_id = got_object_id_dup(resume_commit_id);
10185 if (yca_id == NULL) {
10186 error = got_error_from_errno("got_object_id_dup");
10187 goto done;
10189 } else {
10190 error = got_ref_open(&branch, repo, argv[0], 0);
10191 if (error != NULL)
10192 goto done;
10195 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10196 if (error)
10197 goto done;
10199 if (!continue_rebase) {
10200 struct got_object_id *base_commit_id;
10202 base_commit_id = got_worktree_get_base_commit_id(worktree);
10203 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10204 base_commit_id, branch_head_commit_id, 1, repo,
10205 check_cancelled, NULL);
10206 if (error)
10207 goto done;
10208 if (yca_id == NULL) {
10209 error = got_error_msg(GOT_ERR_ANCESTRY,
10210 "specified branch shares no common ancestry "
10211 "with work tree's branch");
10212 goto done;
10215 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10216 if (error) {
10217 if (error->code != GOT_ERR_ANCESTRY)
10218 goto done;
10219 error = NULL;
10220 } else {
10221 struct got_pathlist_head paths;
10222 printf("%s is already based on %s\n",
10223 got_ref_get_name(branch),
10224 got_worktree_get_head_ref_name(worktree));
10225 error = switch_head_ref(branch, branch_head_commit_id,
10226 worktree, repo);
10227 if (error)
10228 goto done;
10229 error = got_worktree_set_base_commit_id(worktree, repo,
10230 branch_head_commit_id);
10231 if (error)
10232 goto done;
10233 TAILQ_INIT(&paths);
10234 error = got_pathlist_append(&paths, "", NULL);
10235 if (error)
10236 goto done;
10237 error = got_worktree_checkout_files(worktree,
10238 &paths, repo, update_progress, &upa,
10239 check_cancelled, NULL);
10240 got_pathlist_free(&paths);
10241 if (error)
10242 goto done;
10243 if (upa.did_something) {
10244 char *id_str;
10245 error = got_object_id_str(&id_str,
10246 branch_head_commit_id);
10247 if (error)
10248 goto done;
10249 printf("Updated to %s: %s\n",
10250 got_worktree_get_head_ref_name(worktree),
10251 id_str);
10252 free(id_str);
10253 } else
10254 printf("Already up-to-date\n");
10255 print_update_progress_stats(&upa);
10256 goto done;
10260 commit_id = branch_head_commit_id;
10261 error = got_object_open_as_commit(&commit, repo, commit_id);
10262 if (error)
10263 goto done;
10265 parent_ids = got_object_commit_get_parent_ids(commit);
10266 pid = STAILQ_FIRST(parent_ids);
10267 if (pid == NULL) {
10268 error = got_error(GOT_ERR_EMPTY_REBASE);
10269 goto done;
10271 error = collect_commits(&commits, commit_id, &pid->id,
10272 yca_id, got_worktree_get_path_prefix(worktree),
10273 GOT_ERR_REBASE_PATH, repo);
10274 got_object_commit_close(commit);
10275 commit = NULL;
10276 if (error)
10277 goto done;
10279 if (!continue_rebase) {
10280 error = got_worktree_rebase_prepare(&new_base_branch,
10281 &tmp_branch, &fileindex, worktree, branch, repo);
10282 if (error)
10283 goto done;
10286 if (STAILQ_EMPTY(&commits)) {
10287 if (continue_rebase) {
10288 error = rebase_complete(worktree, fileindex,
10289 branch, new_base_branch, tmp_branch, repo,
10290 create_backup);
10291 goto done;
10292 } else {
10293 /* Fast-forward the reference of the branch. */
10294 struct got_object_id *new_head_commit_id;
10295 char *id_str;
10296 error = got_ref_resolve(&new_head_commit_id, repo,
10297 new_base_branch);
10298 if (error)
10299 goto done;
10300 error = got_object_id_str(&id_str, new_head_commit_id);
10301 printf("Forwarding %s to commit %s\n",
10302 got_ref_get_name(branch), id_str);
10303 free(id_str);
10304 error = got_ref_change_ref(branch,
10305 new_head_commit_id);
10306 if (error)
10307 goto done;
10308 /* No backup needed since objects did not change. */
10309 create_backup = 0;
10313 pid = NULL;
10314 STAILQ_FOREACH(qid, &commits, entry) {
10316 commit_id = &qid->id;
10317 parent_id = pid ? &pid->id : yca_id;
10318 pid = qid;
10320 memset(&upa, 0, sizeof(upa));
10321 error = got_worktree_rebase_merge_files(&merged_paths,
10322 worktree, fileindex, parent_id, commit_id, repo,
10323 update_progress, &upa, check_cancelled, NULL);
10324 if (error)
10325 goto done;
10327 print_merge_progress_stats(&upa);
10328 if (upa.conflicts > 0 || upa.missing > 0 ||
10329 upa.not_deleted > 0 || upa.unversioned > 0) {
10330 if (upa.conflicts > 0) {
10331 error = show_rebase_merge_conflict(&qid->id,
10332 repo);
10333 if (error)
10334 goto done;
10336 got_worktree_rebase_pathlist_free(&merged_paths);
10337 break;
10340 error = rebase_commit(&merged_paths, worktree, fileindex,
10341 tmp_branch, commit_id, repo);
10342 got_worktree_rebase_pathlist_free(&merged_paths);
10343 if (error)
10344 goto done;
10347 if (upa.conflicts > 0 || upa.missing > 0 ||
10348 upa.not_deleted > 0 || upa.unversioned > 0) {
10349 error = got_worktree_rebase_postpone(worktree, fileindex);
10350 if (error)
10351 goto done;
10352 if (upa.conflicts > 0 && upa.missing == 0 &&
10353 upa.not_deleted == 0 && upa.unversioned == 0) {
10354 error = got_error_msg(GOT_ERR_CONFLICTS,
10355 "conflicts must be resolved before rebasing "
10356 "can continue");
10357 } else if (upa.conflicts > 0) {
10358 error = got_error_msg(GOT_ERR_CONFLICTS,
10359 "conflicts must be resolved before rebasing "
10360 "can continue; changes destined for some "
10361 "files were not yet merged and should be "
10362 "merged manually if required before the "
10363 "rebase operation is continued");
10364 } else {
10365 error = got_error_msg(GOT_ERR_CONFLICTS,
10366 "changes destined for some files were not "
10367 "yet merged and should be merged manually "
10368 "if required before the rebase operation "
10369 "is continued");
10371 } else
10372 error = rebase_complete(worktree, fileindex, branch,
10373 new_base_branch, tmp_branch, repo, create_backup);
10374 done:
10375 got_object_id_queue_free(&commits);
10376 free(branch_head_commit_id);
10377 free(resume_commit_id);
10378 free(yca_id);
10379 if (commit)
10380 got_object_commit_close(commit);
10381 if (branch)
10382 got_ref_close(branch);
10383 if (new_base_branch)
10384 got_ref_close(new_base_branch);
10385 if (tmp_branch)
10386 got_ref_close(tmp_branch);
10387 if (worktree)
10388 got_worktree_close(worktree);
10389 if (repo) {
10390 const struct got_error *close_err = got_repo_close(repo);
10391 if (error == NULL)
10392 error = close_err;
10394 if (pack_fds) {
10395 const struct got_error *pack_err =
10396 got_repo_pack_fds_close(pack_fds);
10397 if (error == NULL)
10398 error = pack_err;
10400 return error;
10403 __dead static void
10404 usage_histedit(void)
10406 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10407 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10408 getprogname());
10409 exit(1);
10412 #define GOT_HISTEDIT_PICK 'p'
10413 #define GOT_HISTEDIT_EDIT 'e'
10414 #define GOT_HISTEDIT_FOLD 'f'
10415 #define GOT_HISTEDIT_DROP 'd'
10416 #define GOT_HISTEDIT_MESG 'm'
10418 static const struct got_histedit_cmd {
10419 unsigned char code;
10420 const char *name;
10421 const char *desc;
10422 } got_histedit_cmds[] = {
10423 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10424 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10425 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10426 "be used" },
10427 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10428 { GOT_HISTEDIT_MESG, "mesg",
10429 "single-line log message for commit above (open editor if empty)" },
10432 struct got_histedit_list_entry {
10433 TAILQ_ENTRY(got_histedit_list_entry) entry;
10434 struct got_object_id *commit_id;
10435 const struct got_histedit_cmd *cmd;
10436 char *logmsg;
10438 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10440 static const struct got_error *
10441 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10442 FILE *f, struct got_repository *repo)
10444 const struct got_error *err = NULL;
10445 char *logmsg = NULL, *id_str = NULL;
10446 struct got_commit_object *commit = NULL;
10447 int n;
10449 err = got_object_open_as_commit(&commit, repo, commit_id);
10450 if (err)
10451 goto done;
10453 err = get_short_logmsg(&logmsg, 34, commit);
10454 if (err)
10455 goto done;
10457 err = got_object_id_str(&id_str, commit_id);
10458 if (err)
10459 goto done;
10461 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10462 if (n < 0)
10463 err = got_ferror(f, GOT_ERR_IO);
10464 done:
10465 if (commit)
10466 got_object_commit_close(commit);
10467 free(id_str);
10468 free(logmsg);
10469 return err;
10472 static const struct got_error *
10473 histedit_write_commit_list(struct got_object_id_queue *commits,
10474 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10475 struct got_repository *repo)
10477 const struct got_error *err = NULL;
10478 struct got_object_qid *qid;
10479 const char *histedit_cmd = NULL;
10481 if (STAILQ_EMPTY(commits))
10482 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10484 STAILQ_FOREACH(qid, commits, entry) {
10485 histedit_cmd = got_histedit_cmds[0].name;
10486 if (edit_only)
10487 histedit_cmd = "edit";
10488 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10489 histedit_cmd = "fold";
10490 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10491 if (err)
10492 break;
10493 if (edit_logmsg_only) {
10494 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10495 if (n < 0) {
10496 err = got_ferror(f, GOT_ERR_IO);
10497 break;
10502 return err;
10505 static const struct got_error *
10506 write_cmd_list(FILE *f, const char *branch_name,
10507 struct got_object_id_queue *commits)
10509 const struct got_error *err = NULL;
10510 size_t i;
10511 int n;
10512 char *id_str;
10513 struct got_object_qid *qid;
10515 qid = STAILQ_FIRST(commits);
10516 err = got_object_id_str(&id_str, &qid->id);
10517 if (err)
10518 return err;
10520 n = fprintf(f,
10521 "# Editing the history of branch '%s' starting at\n"
10522 "# commit %s\n"
10523 "# Commits will be processed in order from top to "
10524 "bottom of this file.\n", branch_name, id_str);
10525 if (n < 0) {
10526 err = got_ferror(f, GOT_ERR_IO);
10527 goto done;
10530 n = fprintf(f, "# Available histedit commands:\n");
10531 if (n < 0) {
10532 err = got_ferror(f, GOT_ERR_IO);
10533 goto done;
10536 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10537 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10538 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10539 cmd->desc);
10540 if (n < 0) {
10541 err = got_ferror(f, GOT_ERR_IO);
10542 break;
10545 done:
10546 free(id_str);
10547 return err;
10550 static const struct got_error *
10551 histedit_syntax_error(int lineno)
10553 static char msg[42];
10554 int ret;
10556 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10557 lineno);
10558 if (ret == -1 || ret >= sizeof(msg))
10559 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10561 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10564 static const struct got_error *
10565 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10566 char *logmsg, struct got_repository *repo)
10568 const struct got_error *err;
10569 struct got_commit_object *folded_commit = NULL;
10570 char *id_str, *folded_logmsg = NULL;
10572 err = got_object_id_str(&id_str, hle->commit_id);
10573 if (err)
10574 return err;
10576 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10577 if (err)
10578 goto done;
10580 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10581 if (err)
10582 goto done;
10583 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10584 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10585 folded_logmsg) == -1) {
10586 err = got_error_from_errno("asprintf");
10588 done:
10589 if (folded_commit)
10590 got_object_commit_close(folded_commit);
10591 free(id_str);
10592 free(folded_logmsg);
10593 return err;
10596 static struct got_histedit_list_entry *
10597 get_folded_commits(struct got_histedit_list_entry *hle)
10599 struct got_histedit_list_entry *prev, *folded = NULL;
10601 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10602 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10603 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10604 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10605 folded = prev;
10606 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10609 return folded;
10612 static const struct got_error *
10613 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10614 struct got_repository *repo)
10616 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10617 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10618 const struct got_error *err = NULL;
10619 struct got_commit_object *commit = NULL;
10620 int logmsg_len;
10621 int fd;
10622 struct got_histedit_list_entry *folded = NULL;
10624 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10625 if (err)
10626 return err;
10628 folded = get_folded_commits(hle);
10629 if (folded) {
10630 while (folded != hle) {
10631 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10632 folded = TAILQ_NEXT(folded, entry);
10633 continue;
10635 err = append_folded_commit_msg(&new_msg, folded,
10636 logmsg, repo);
10637 if (err)
10638 goto done;
10639 free(logmsg);
10640 logmsg = new_msg;
10641 folded = TAILQ_NEXT(folded, entry);
10645 err = got_object_id_str(&id_str, hle->commit_id);
10646 if (err)
10647 goto done;
10648 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10649 if (err)
10650 goto done;
10651 logmsg_len = asprintf(&new_msg,
10652 "%s\n# original log message of commit %s: %s",
10653 logmsg ? logmsg : "", id_str, orig_logmsg);
10654 if (logmsg_len == -1) {
10655 err = got_error_from_errno("asprintf");
10656 goto done;
10658 free(logmsg);
10659 logmsg = new_msg;
10661 err = got_object_id_str(&id_str, hle->commit_id);
10662 if (err)
10663 goto done;
10665 err = got_opentemp_named_fd(&logmsg_path, &fd,
10666 GOT_TMPDIR_STR "/got-logmsg");
10667 if (err)
10668 goto done;
10670 write(fd, logmsg, logmsg_len);
10671 close(fd);
10673 err = get_editor(&editor);
10674 if (err)
10675 goto done;
10677 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10678 logmsg_len, 0);
10679 if (err) {
10680 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10681 goto done;
10682 err = NULL;
10683 hle->logmsg = strdup(new_msg);
10684 if (hle->logmsg == NULL)
10685 err = got_error_from_errno("strdup");
10687 done:
10688 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10689 err = got_error_from_errno2("unlink", logmsg_path);
10690 free(logmsg_path);
10691 free(logmsg);
10692 free(orig_logmsg);
10693 free(editor);
10694 if (commit)
10695 got_object_commit_close(commit);
10696 return err;
10699 static const struct got_error *
10700 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10701 FILE *f, struct got_repository *repo)
10703 const struct got_error *err = NULL;
10704 char *line = NULL, *p, *end;
10705 size_t i, size;
10706 ssize_t len;
10707 int lineno = 0;
10708 const struct got_histedit_cmd *cmd;
10709 struct got_object_id *commit_id = NULL;
10710 struct got_histedit_list_entry *hle = NULL;
10712 for (;;) {
10713 len = getline(&line, &size, f);
10714 if (len == -1) {
10715 const struct got_error *getline_err;
10716 if (feof(f))
10717 break;
10718 getline_err = got_error_from_errno("getline");
10719 err = got_ferror(f, getline_err->code);
10720 break;
10722 lineno++;
10723 p = line;
10724 while (isspace((unsigned char)p[0]))
10725 p++;
10726 if (p[0] == '#' || p[0] == '\0') {
10727 free(line);
10728 line = NULL;
10729 continue;
10731 cmd = NULL;
10732 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10733 cmd = &got_histedit_cmds[i];
10734 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10735 isspace((unsigned char)p[strlen(cmd->name)])) {
10736 p += strlen(cmd->name);
10737 break;
10739 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10740 p++;
10741 break;
10744 if (i == nitems(got_histedit_cmds)) {
10745 err = histedit_syntax_error(lineno);
10746 break;
10748 while (isspace((unsigned char)p[0]))
10749 p++;
10750 if (cmd->code == GOT_HISTEDIT_MESG) {
10751 if (hle == NULL || hle->logmsg != NULL) {
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 continue;
10769 } else {
10770 end = p;
10771 while (end[0] && !isspace((unsigned char)end[0]))
10772 end++;
10773 *end = '\0';
10775 err = got_object_resolve_id_str(&commit_id, repo, p);
10776 if (err) {
10777 /* override error code */
10778 err = histedit_syntax_error(lineno);
10779 break;
10782 hle = malloc(sizeof(*hle));
10783 if (hle == NULL) {
10784 err = got_error_from_errno("malloc");
10785 break;
10787 hle->cmd = cmd;
10788 hle->commit_id = commit_id;
10789 hle->logmsg = NULL;
10790 commit_id = NULL;
10791 free(line);
10792 line = NULL;
10793 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10796 free(line);
10797 free(commit_id);
10798 return err;
10801 static const struct got_error *
10802 histedit_check_script(struct got_histedit_list *histedit_cmds,
10803 struct got_object_id_queue *commits, struct got_repository *repo)
10805 const struct got_error *err = NULL;
10806 struct got_object_qid *qid;
10807 struct got_histedit_list_entry *hle;
10808 static char msg[92];
10809 char *id_str;
10811 if (TAILQ_EMPTY(histedit_cmds))
10812 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10813 "histedit script contains no commands");
10814 if (STAILQ_EMPTY(commits))
10815 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10817 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10818 struct got_histedit_list_entry *hle2;
10819 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10820 if (hle == hle2)
10821 continue;
10822 if (got_object_id_cmp(hle->commit_id,
10823 hle2->commit_id) != 0)
10824 continue;
10825 err = got_object_id_str(&id_str, hle->commit_id);
10826 if (err)
10827 return err;
10828 snprintf(msg, sizeof(msg), "commit %s is listed "
10829 "more than once in histedit script", id_str);
10830 free(id_str);
10831 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10835 STAILQ_FOREACH(qid, commits, entry) {
10836 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10837 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10838 break;
10840 if (hle == NULL) {
10841 err = got_object_id_str(&id_str, &qid->id);
10842 if (err)
10843 return err;
10844 snprintf(msg, sizeof(msg),
10845 "commit %s missing from histedit script", id_str);
10846 free(id_str);
10847 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10851 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10852 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10853 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10854 "last commit in histedit script cannot be folded");
10856 return NULL;
10859 static const struct got_error *
10860 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10861 const char *path, struct got_object_id_queue *commits,
10862 struct got_repository *repo)
10864 const struct got_error *err = NULL;
10865 char *editor;
10866 FILE *f = NULL;
10868 err = get_editor(&editor);
10869 if (err)
10870 return err;
10872 if (spawn_editor(editor, path) == -1) {
10873 err = got_error_from_errno("failed spawning editor");
10874 goto done;
10877 f = fopen(path, "re");
10878 if (f == NULL) {
10879 err = got_error_from_errno("fopen");
10880 goto done;
10882 err = histedit_parse_list(histedit_cmds, f, repo);
10883 if (err)
10884 goto done;
10886 err = histedit_check_script(histedit_cmds, commits, repo);
10887 done:
10888 if (f && fclose(f) == EOF && err == NULL)
10889 err = got_error_from_errno("fclose");
10890 free(editor);
10891 return err;
10894 static const struct got_error *
10895 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10896 struct got_object_id_queue *, const char *, const char *,
10897 struct got_repository *);
10899 static const struct got_error *
10900 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10901 struct got_object_id_queue *commits, const char *branch_name,
10902 int edit_logmsg_only, int fold_only, int edit_only,
10903 struct got_repository *repo)
10905 const struct got_error *err;
10906 FILE *f = NULL;
10907 char *path = NULL;
10909 err = got_opentemp_named(&path, &f, "got-histedit");
10910 if (err)
10911 return err;
10913 err = write_cmd_list(f, branch_name, commits);
10914 if (err)
10915 goto done;
10917 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10918 fold_only, edit_only, repo);
10919 if (err)
10920 goto done;
10922 if (edit_logmsg_only || fold_only || edit_only) {
10923 rewind(f);
10924 err = histedit_parse_list(histedit_cmds, f, repo);
10925 } else {
10926 if (fclose(f) == EOF) {
10927 err = got_error_from_errno("fclose");
10928 goto done;
10930 f = NULL;
10931 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10932 if (err) {
10933 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10934 err->code != GOT_ERR_HISTEDIT_CMD)
10935 goto done;
10936 err = histedit_edit_list_retry(histedit_cmds, err,
10937 commits, path, branch_name, repo);
10940 done:
10941 if (f && fclose(f) == EOF && err == NULL)
10942 err = got_error_from_errno("fclose");
10943 if (path && unlink(path) != 0 && err == NULL)
10944 err = got_error_from_errno2("unlink", path);
10945 free(path);
10946 return err;
10949 static const struct got_error *
10950 histedit_save_list(struct got_histedit_list *histedit_cmds,
10951 struct got_worktree *worktree, struct got_repository *repo)
10953 const struct got_error *err = NULL;
10954 char *path = NULL;
10955 FILE *f = NULL;
10956 struct got_histedit_list_entry *hle;
10957 struct got_commit_object *commit = NULL;
10959 err = got_worktree_get_histedit_script_path(&path, worktree);
10960 if (err)
10961 return err;
10963 f = fopen(path, "we");
10964 if (f == NULL) {
10965 err = got_error_from_errno2("fopen", path);
10966 goto done;
10968 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10969 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10970 repo);
10971 if (err)
10972 break;
10974 if (hle->logmsg) {
10975 int n = fprintf(f, "%c %s\n",
10976 GOT_HISTEDIT_MESG, hle->logmsg);
10977 if (n < 0) {
10978 err = got_ferror(f, GOT_ERR_IO);
10979 break;
10983 done:
10984 if (f && fclose(f) == EOF && err == NULL)
10985 err = got_error_from_errno("fclose");
10986 free(path);
10987 if (commit)
10988 got_object_commit_close(commit);
10989 return err;
10992 static void
10993 histedit_free_list(struct got_histedit_list *histedit_cmds)
10995 struct got_histedit_list_entry *hle;
10997 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10998 TAILQ_REMOVE(histedit_cmds, hle, entry);
10999 free(hle);
11003 static const struct got_error *
11004 histedit_load_list(struct got_histedit_list *histedit_cmds,
11005 const char *path, struct got_repository *repo)
11007 const struct got_error *err = NULL;
11008 FILE *f = NULL;
11010 f = fopen(path, "re");
11011 if (f == NULL) {
11012 err = got_error_from_errno2("fopen", path);
11013 goto done;
11016 err = histedit_parse_list(histedit_cmds, f, repo);
11017 done:
11018 if (f && fclose(f) == EOF && err == NULL)
11019 err = got_error_from_errno("fclose");
11020 return err;
11023 static const struct got_error *
11024 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11025 const struct got_error *edit_err, struct got_object_id_queue *commits,
11026 const char *path, const char *branch_name, struct got_repository *repo)
11028 const struct got_error *err = NULL, *prev_err = edit_err;
11029 int resp = ' ';
11031 while (resp != 'c' && resp != 'r' && resp != 'a') {
11032 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11033 "or (a)bort: ", getprogname(), prev_err->msg);
11034 resp = getchar();
11035 if (resp == '\n')
11036 resp = getchar();
11037 if (resp == 'c') {
11038 histedit_free_list(histedit_cmds);
11039 err = histedit_run_editor(histedit_cmds, path, commits,
11040 repo);
11041 if (err) {
11042 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11043 err->code != GOT_ERR_HISTEDIT_CMD)
11044 break;
11045 prev_err = err;
11046 resp = ' ';
11047 continue;
11049 break;
11050 } else if (resp == 'r') {
11051 histedit_free_list(histedit_cmds);
11052 err = histedit_edit_script(histedit_cmds,
11053 commits, branch_name, 0, 0, 0, repo);
11054 if (err) {
11055 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11056 err->code != GOT_ERR_HISTEDIT_CMD)
11057 break;
11058 prev_err = err;
11059 resp = ' ';
11060 continue;
11062 break;
11063 } else if (resp == 'a') {
11064 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11065 break;
11066 } else
11067 printf("invalid response '%c'\n", resp);
11070 return err;
11073 static const struct got_error *
11074 histedit_complete(struct got_worktree *worktree,
11075 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11076 struct got_reference *branch, struct got_repository *repo)
11078 printf("Switching work tree to %s\n",
11079 got_ref_get_symref_target(branch));
11080 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11081 branch, repo);
11084 static const struct got_error *
11085 show_histedit_progress(struct got_commit_object *commit,
11086 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11088 const struct got_error *err;
11089 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11091 err = got_object_id_str(&old_id_str, hle->commit_id);
11092 if (err)
11093 goto done;
11095 if (new_id) {
11096 err = got_object_id_str(&new_id_str, new_id);
11097 if (err)
11098 goto done;
11101 old_id_str[12] = '\0';
11102 if (new_id_str)
11103 new_id_str[12] = '\0';
11105 if (hle->logmsg) {
11106 logmsg = strdup(hle->logmsg);
11107 if (logmsg == NULL) {
11108 err = got_error_from_errno("strdup");
11109 goto done;
11111 trim_logmsg(logmsg, 42);
11112 } else {
11113 err = get_short_logmsg(&logmsg, 42, commit);
11114 if (err)
11115 goto done;
11118 switch (hle->cmd->code) {
11119 case GOT_HISTEDIT_PICK:
11120 case GOT_HISTEDIT_EDIT:
11121 printf("%s -> %s: %s\n", old_id_str,
11122 new_id_str ? new_id_str : "no-op change", logmsg);
11123 break;
11124 case GOT_HISTEDIT_DROP:
11125 case GOT_HISTEDIT_FOLD:
11126 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11127 logmsg);
11128 break;
11129 default:
11130 break;
11132 done:
11133 free(old_id_str);
11134 free(new_id_str);
11135 return err;
11138 static const struct got_error *
11139 histedit_commit(struct got_pathlist_head *merged_paths,
11140 struct got_worktree *worktree, struct got_fileindex *fileindex,
11141 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11142 struct got_repository *repo)
11144 const struct got_error *err;
11145 struct got_commit_object *commit;
11146 struct got_object_id *new_commit_id;
11148 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11149 && hle->logmsg == NULL) {
11150 err = histedit_edit_logmsg(hle, repo);
11151 if (err)
11152 return err;
11155 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11156 if (err)
11157 return err;
11159 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11160 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11161 hle->logmsg, repo);
11162 if (err) {
11163 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11164 goto done;
11165 err = show_histedit_progress(commit, hle, NULL);
11166 } else {
11167 err = show_histedit_progress(commit, hle, new_commit_id);
11168 free(new_commit_id);
11170 done:
11171 got_object_commit_close(commit);
11172 return err;
11175 static const struct got_error *
11176 histedit_skip_commit(struct got_histedit_list_entry *hle,
11177 struct got_worktree *worktree, struct got_repository *repo)
11179 const struct got_error *error;
11180 struct got_commit_object *commit;
11182 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11183 repo);
11184 if (error)
11185 return error;
11187 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11188 if (error)
11189 return error;
11191 error = show_histedit_progress(commit, hle, NULL);
11192 got_object_commit_close(commit);
11193 return error;
11196 static const struct got_error *
11197 check_local_changes(void *arg, unsigned char status,
11198 unsigned char staged_status, const char *path,
11199 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11200 struct got_object_id *commit_id, int dirfd, const char *de_name)
11202 int *have_local_changes = arg;
11204 switch (status) {
11205 case GOT_STATUS_ADD:
11206 case GOT_STATUS_DELETE:
11207 case GOT_STATUS_MODIFY:
11208 case GOT_STATUS_CONFLICT:
11209 *have_local_changes = 1;
11210 return got_error(GOT_ERR_CANCELLED);
11211 default:
11212 break;
11215 switch (staged_status) {
11216 case GOT_STATUS_ADD:
11217 case GOT_STATUS_DELETE:
11218 case GOT_STATUS_MODIFY:
11219 *have_local_changes = 1;
11220 return got_error(GOT_ERR_CANCELLED);
11221 default:
11222 break;
11225 return NULL;
11228 static const struct got_error *
11229 cmd_histedit(int argc, char *argv[])
11231 const struct got_error *error = NULL;
11232 struct got_worktree *worktree = NULL;
11233 struct got_fileindex *fileindex = NULL;
11234 struct got_repository *repo = NULL;
11235 char *cwd = NULL;
11236 struct got_reference *branch = NULL;
11237 struct got_reference *tmp_branch = NULL;
11238 struct got_object_id *resume_commit_id = NULL;
11239 struct got_object_id *base_commit_id = NULL;
11240 struct got_object_id *head_commit_id = NULL;
11241 struct got_commit_object *commit = NULL;
11242 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11243 struct got_update_progress_arg upa;
11244 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11245 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11246 int list_backups = 0, delete_backups = 0;
11247 const char *edit_script_path = NULL;
11248 struct got_object_id_queue commits;
11249 struct got_pathlist_head merged_paths;
11250 const struct got_object_id_queue *parent_ids;
11251 struct got_object_qid *pid;
11252 struct got_histedit_list histedit_cmds;
11253 struct got_histedit_list_entry *hle;
11254 int *pack_fds = NULL;
11256 STAILQ_INIT(&commits);
11257 TAILQ_INIT(&histedit_cmds);
11258 TAILQ_INIT(&merged_paths);
11259 memset(&upa, 0, sizeof(upa));
11261 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11262 switch (ch) {
11263 case 'a':
11264 abort_edit = 1;
11265 break;
11266 case 'c':
11267 continue_edit = 1;
11268 break;
11269 case 'e':
11270 edit_only = 1;
11271 break;
11272 case 'f':
11273 fold_only = 1;
11274 break;
11275 case 'F':
11276 edit_script_path = optarg;
11277 break;
11278 case 'm':
11279 edit_logmsg_only = 1;
11280 break;
11281 case 'l':
11282 list_backups = 1;
11283 break;
11284 case 'X':
11285 delete_backups = 1;
11286 break;
11287 default:
11288 usage_histedit();
11289 /* NOTREACHED */
11293 argc -= optind;
11294 argv += optind;
11296 #ifndef PROFILE
11297 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11298 "unveil", NULL) == -1)
11299 err(1, "pledge");
11300 #endif
11301 if (abort_edit && continue_edit)
11302 option_conflict('a', 'c');
11303 if (edit_script_path && edit_logmsg_only)
11304 option_conflict('F', 'm');
11305 if (abort_edit && edit_logmsg_only)
11306 option_conflict('a', 'm');
11307 if (continue_edit && edit_logmsg_only)
11308 option_conflict('c', 'm');
11309 if (abort_edit && fold_only)
11310 option_conflict('a', 'f');
11311 if (continue_edit && fold_only)
11312 option_conflict('c', 'f');
11313 if (fold_only && edit_logmsg_only)
11314 option_conflict('f', 'm');
11315 if (edit_script_path && fold_only)
11316 option_conflict('F', 'f');
11317 if (abort_edit && edit_only)
11318 option_conflict('a', 'e');
11319 if (continue_edit && edit_only)
11320 option_conflict('c', 'e');
11321 if (edit_only && edit_logmsg_only)
11322 option_conflict('e', 'm');
11323 if (edit_script_path && edit_only)
11324 option_conflict('F', 'e');
11325 if (list_backups) {
11326 if (abort_edit)
11327 option_conflict('l', 'a');
11328 if (continue_edit)
11329 option_conflict('l', 'c');
11330 if (edit_script_path)
11331 option_conflict('l', 'F');
11332 if (edit_logmsg_only)
11333 option_conflict('l', 'm');
11334 if (fold_only)
11335 option_conflict('l', 'f');
11336 if (edit_only)
11337 option_conflict('l', 'e');
11338 if (delete_backups)
11339 option_conflict('l', 'X');
11340 if (argc != 0 && argc != 1)
11341 usage_histedit();
11342 } else if (delete_backups) {
11343 if (abort_edit)
11344 option_conflict('X', 'a');
11345 if (continue_edit)
11346 option_conflict('X', 'c');
11347 if (edit_script_path)
11348 option_conflict('X', 'F');
11349 if (edit_logmsg_only)
11350 option_conflict('X', 'm');
11351 if (fold_only)
11352 option_conflict('X', 'f');
11353 if (edit_only)
11354 option_conflict('X', 'e');
11355 if (list_backups)
11356 option_conflict('X', 'l');
11357 if (argc != 0 && argc != 1)
11358 usage_histedit();
11359 } else if (argc != 0)
11360 usage_histedit();
11363 * This command cannot apply unveil(2) in all cases because the
11364 * user may choose to run an editor to edit the histedit script
11365 * and to edit individual commit log messages.
11366 * unveil(2) traverses exec(2); if an editor is used we have to
11367 * apply unveil after edit script and log messages have been written.
11368 * XXX TODO: Make use of unveil(2) where possible.
11371 cwd = getcwd(NULL, 0);
11372 if (cwd == NULL) {
11373 error = got_error_from_errno("getcwd");
11374 goto done;
11377 error = got_repo_pack_fds_open(&pack_fds);
11378 if (error != NULL)
11379 goto done;
11381 error = got_worktree_open(&worktree, cwd);
11382 if (error) {
11383 if (list_backups || delete_backups) {
11384 if (error->code != GOT_ERR_NOT_WORKTREE)
11385 goto done;
11386 } else {
11387 if (error->code == GOT_ERR_NOT_WORKTREE)
11388 error = wrap_not_worktree_error(error,
11389 "histedit", cwd);
11390 goto done;
11394 if (list_backups || delete_backups) {
11395 error = got_repo_open(&repo,
11396 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11397 NULL, pack_fds);
11398 if (error != NULL)
11399 goto done;
11400 error = apply_unveil(got_repo_get_path(repo), 0,
11401 worktree ? got_worktree_get_root_path(worktree) : NULL);
11402 if (error)
11403 goto done;
11404 error = process_backup_refs(
11405 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11406 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11407 goto done; /* nothing else to do */
11410 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11411 NULL, pack_fds);
11412 if (error != NULL)
11413 goto done;
11415 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11416 if (error)
11417 goto done;
11418 if (rebase_in_progress) {
11419 error = got_error(GOT_ERR_REBASING);
11420 goto done;
11423 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11424 repo);
11425 if (error)
11426 goto done;
11427 if (merge_in_progress) {
11428 error = got_error(GOT_ERR_MERGE_BUSY);
11429 goto done;
11432 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11433 if (error)
11434 goto done;
11436 if (edit_in_progress && edit_logmsg_only) {
11437 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11438 "histedit operation is in progress in this "
11439 "work tree and must be continued or aborted "
11440 "before the -m option can be used");
11441 goto done;
11443 if (edit_in_progress && fold_only) {
11444 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11445 "histedit operation is in progress in this "
11446 "work tree and must be continued or aborted "
11447 "before the -f option can be used");
11448 goto done;
11450 if (edit_in_progress && edit_only) {
11451 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11452 "histedit operation is in progress in this "
11453 "work tree and must be continued or aborted "
11454 "before the -e option can be used");
11455 goto done;
11458 if (edit_in_progress && abort_edit) {
11459 error = got_worktree_histedit_continue(&resume_commit_id,
11460 &tmp_branch, &branch, &base_commit_id, &fileindex,
11461 worktree, repo);
11462 if (error)
11463 goto done;
11464 printf("Switching work tree to %s\n",
11465 got_ref_get_symref_target(branch));
11466 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11467 branch, base_commit_id, abort_progress, &upa);
11468 if (error)
11469 goto done;
11470 printf("Histedit of %s aborted\n",
11471 got_ref_get_symref_target(branch));
11472 print_merge_progress_stats(&upa);
11473 goto done; /* nothing else to do */
11474 } else if (abort_edit) {
11475 error = got_error(GOT_ERR_NOT_HISTEDIT);
11476 goto done;
11479 if (continue_edit) {
11480 char *path;
11482 if (!edit_in_progress) {
11483 error = got_error(GOT_ERR_NOT_HISTEDIT);
11484 goto done;
11487 error = got_worktree_get_histedit_script_path(&path, worktree);
11488 if (error)
11489 goto done;
11491 error = histedit_load_list(&histedit_cmds, path, repo);
11492 free(path);
11493 if (error)
11494 goto done;
11496 error = got_worktree_histedit_continue(&resume_commit_id,
11497 &tmp_branch, &branch, &base_commit_id, &fileindex,
11498 worktree, repo);
11499 if (error)
11500 goto done;
11502 error = got_ref_resolve(&head_commit_id, repo, branch);
11503 if (error)
11504 goto done;
11506 error = got_object_open_as_commit(&commit, repo,
11507 head_commit_id);
11508 if (error)
11509 goto done;
11510 parent_ids = got_object_commit_get_parent_ids(commit);
11511 pid = STAILQ_FIRST(parent_ids);
11512 if (pid == NULL) {
11513 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11514 goto done;
11516 error = collect_commits(&commits, head_commit_id, &pid->id,
11517 base_commit_id, got_worktree_get_path_prefix(worktree),
11518 GOT_ERR_HISTEDIT_PATH, repo);
11519 got_object_commit_close(commit);
11520 commit = NULL;
11521 if (error)
11522 goto done;
11523 } else {
11524 if (edit_in_progress) {
11525 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11526 goto done;
11529 error = got_ref_open(&branch, repo,
11530 got_worktree_get_head_ref_name(worktree), 0);
11531 if (error != NULL)
11532 goto done;
11534 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11535 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11536 "will not edit commit history of a branch outside "
11537 "the \"refs/heads/\" reference namespace");
11538 goto done;
11541 error = got_ref_resolve(&head_commit_id, repo, branch);
11542 got_ref_close(branch);
11543 branch = NULL;
11544 if (error)
11545 goto done;
11547 error = got_object_open_as_commit(&commit, repo,
11548 head_commit_id);
11549 if (error)
11550 goto done;
11551 parent_ids = got_object_commit_get_parent_ids(commit);
11552 pid = STAILQ_FIRST(parent_ids);
11553 if (pid == NULL) {
11554 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11555 goto done;
11557 error = collect_commits(&commits, head_commit_id, &pid->id,
11558 got_worktree_get_base_commit_id(worktree),
11559 got_worktree_get_path_prefix(worktree),
11560 GOT_ERR_HISTEDIT_PATH, repo);
11561 got_object_commit_close(commit);
11562 commit = NULL;
11563 if (error)
11564 goto done;
11566 if (STAILQ_EMPTY(&commits)) {
11567 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11568 goto done;
11571 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11572 &base_commit_id, &fileindex, worktree, repo);
11573 if (error)
11574 goto done;
11576 if (edit_script_path) {
11577 error = histedit_load_list(&histedit_cmds,
11578 edit_script_path, repo);
11579 if (error) {
11580 got_worktree_histedit_abort(worktree, fileindex,
11581 repo, branch, base_commit_id,
11582 abort_progress, &upa);
11583 print_merge_progress_stats(&upa);
11584 goto done;
11586 } else {
11587 const char *branch_name;
11588 branch_name = got_ref_get_symref_target(branch);
11589 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11590 branch_name += 11;
11591 error = histedit_edit_script(&histedit_cmds, &commits,
11592 branch_name, edit_logmsg_only, fold_only,
11593 edit_only, repo);
11594 if (error) {
11595 got_worktree_histedit_abort(worktree, fileindex,
11596 repo, branch, base_commit_id,
11597 abort_progress, &upa);
11598 print_merge_progress_stats(&upa);
11599 goto done;
11604 error = histedit_save_list(&histedit_cmds, worktree,
11605 repo);
11606 if (error) {
11607 got_worktree_histedit_abort(worktree, fileindex,
11608 repo, branch, base_commit_id,
11609 abort_progress, &upa);
11610 print_merge_progress_stats(&upa);
11611 goto done;
11616 error = histedit_check_script(&histedit_cmds, &commits, repo);
11617 if (error)
11618 goto done;
11620 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11621 if (resume_commit_id) {
11622 if (got_object_id_cmp(hle->commit_id,
11623 resume_commit_id) != 0)
11624 continue;
11626 resume_commit_id = NULL;
11627 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11628 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11629 error = histedit_skip_commit(hle, worktree,
11630 repo);
11631 if (error)
11632 goto done;
11633 } else {
11634 struct got_pathlist_head paths;
11635 int have_changes = 0;
11637 TAILQ_INIT(&paths);
11638 error = got_pathlist_append(&paths, "", NULL);
11639 if (error)
11640 goto done;
11641 error = got_worktree_status(worktree, &paths,
11642 repo, 0, check_local_changes, &have_changes,
11643 check_cancelled, NULL);
11644 got_pathlist_free(&paths);
11645 if (error) {
11646 if (error->code != GOT_ERR_CANCELLED)
11647 goto done;
11648 if (sigint_received || sigpipe_received)
11649 goto done;
11651 if (have_changes) {
11652 error = histedit_commit(NULL, worktree,
11653 fileindex, tmp_branch, hle, repo);
11654 if (error)
11655 goto done;
11656 } else {
11657 error = got_object_open_as_commit(
11658 &commit, repo, hle->commit_id);
11659 if (error)
11660 goto done;
11661 error = show_histedit_progress(commit,
11662 hle, NULL);
11663 got_object_commit_close(commit);
11664 commit = NULL;
11665 if (error)
11666 goto done;
11669 continue;
11672 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11673 error = histedit_skip_commit(hle, worktree, repo);
11674 if (error)
11675 goto done;
11676 continue;
11679 error = got_object_open_as_commit(&commit, repo,
11680 hle->commit_id);
11681 if (error)
11682 goto done;
11683 parent_ids = got_object_commit_get_parent_ids(commit);
11684 pid = STAILQ_FIRST(parent_ids);
11686 error = got_worktree_histedit_merge_files(&merged_paths,
11687 worktree, fileindex, &pid->id, hle->commit_id, repo,
11688 update_progress, &upa, check_cancelled, NULL);
11689 if (error)
11690 goto done;
11691 got_object_commit_close(commit);
11692 commit = NULL;
11694 print_merge_progress_stats(&upa);
11695 if (upa.conflicts > 0 || upa.missing > 0 ||
11696 upa.not_deleted > 0 || upa.unversioned > 0) {
11697 if (upa.conflicts > 0) {
11698 error = show_rebase_merge_conflict(
11699 hle->commit_id, repo);
11700 if (error)
11701 goto done;
11703 got_worktree_rebase_pathlist_free(&merged_paths);
11704 break;
11707 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11708 char *id_str;
11709 error = got_object_id_str(&id_str, hle->commit_id);
11710 if (error)
11711 goto done;
11712 printf("Stopping histedit for amending commit %s\n",
11713 id_str);
11714 free(id_str);
11715 got_worktree_rebase_pathlist_free(&merged_paths);
11716 error = got_worktree_histedit_postpone(worktree,
11717 fileindex);
11718 goto done;
11721 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11722 error = histedit_skip_commit(hle, worktree, repo);
11723 if (error)
11724 goto done;
11725 continue;
11728 error = histedit_commit(&merged_paths, worktree, fileindex,
11729 tmp_branch, hle, repo);
11730 got_worktree_rebase_pathlist_free(&merged_paths);
11731 if (error)
11732 goto done;
11735 if (upa.conflicts > 0 || upa.missing > 0 ||
11736 upa.not_deleted > 0 || upa.unversioned > 0) {
11737 error = got_worktree_histedit_postpone(worktree, fileindex);
11738 if (error)
11739 goto done;
11740 if (upa.conflicts > 0 && upa.missing == 0 &&
11741 upa.not_deleted == 0 && upa.unversioned == 0) {
11742 error = got_error_msg(GOT_ERR_CONFLICTS,
11743 "conflicts must be resolved before histedit "
11744 "can continue");
11745 } else if (upa.conflicts > 0) {
11746 error = got_error_msg(GOT_ERR_CONFLICTS,
11747 "conflicts must be resolved before histedit "
11748 "can continue; changes destined for some "
11749 "files were not yet merged and should be "
11750 "merged manually if required before the "
11751 "histedit operation is continued");
11752 } else {
11753 error = got_error_msg(GOT_ERR_CONFLICTS,
11754 "changes destined for some files were not "
11755 "yet merged and should be merged manually "
11756 "if required before the histedit operation "
11757 "is continued");
11759 } else
11760 error = histedit_complete(worktree, fileindex, tmp_branch,
11761 branch, repo);
11762 done:
11763 got_object_id_queue_free(&commits);
11764 histedit_free_list(&histedit_cmds);
11765 free(head_commit_id);
11766 free(base_commit_id);
11767 free(resume_commit_id);
11768 if (commit)
11769 got_object_commit_close(commit);
11770 if (branch)
11771 got_ref_close(branch);
11772 if (tmp_branch)
11773 got_ref_close(tmp_branch);
11774 if (worktree)
11775 got_worktree_close(worktree);
11776 if (repo) {
11777 const struct got_error *close_err = got_repo_close(repo);
11778 if (error == NULL)
11779 error = close_err;
11781 if (pack_fds) {
11782 const struct got_error *pack_err =
11783 got_repo_pack_fds_close(pack_fds);
11784 if (error == NULL)
11785 error = pack_err;
11787 return error;
11790 __dead static void
11791 usage_integrate(void)
11793 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11794 exit(1);
11797 static const struct got_error *
11798 cmd_integrate(int argc, char *argv[])
11800 const struct got_error *error = NULL;
11801 struct got_repository *repo = NULL;
11802 struct got_worktree *worktree = NULL;
11803 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11804 const char *branch_arg = NULL;
11805 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11806 struct got_fileindex *fileindex = NULL;
11807 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11808 int ch;
11809 struct got_update_progress_arg upa;
11810 int *pack_fds = NULL;
11812 while ((ch = getopt(argc, argv, "")) != -1) {
11813 switch (ch) {
11814 default:
11815 usage_integrate();
11816 /* NOTREACHED */
11820 argc -= optind;
11821 argv += optind;
11823 if (argc != 1)
11824 usage_integrate();
11825 branch_arg = argv[0];
11826 #ifndef PROFILE
11827 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11828 "unveil", NULL) == -1)
11829 err(1, "pledge");
11830 #endif
11831 cwd = getcwd(NULL, 0);
11832 if (cwd == NULL) {
11833 error = got_error_from_errno("getcwd");
11834 goto done;
11837 error = got_repo_pack_fds_open(&pack_fds);
11838 if (error != NULL)
11839 goto done;
11841 error = got_worktree_open(&worktree, cwd);
11842 if (error) {
11843 if (error->code == GOT_ERR_NOT_WORKTREE)
11844 error = wrap_not_worktree_error(error, "integrate",
11845 cwd);
11846 goto done;
11849 error = check_rebase_or_histedit_in_progress(worktree);
11850 if (error)
11851 goto done;
11853 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11854 NULL, pack_fds);
11855 if (error != NULL)
11856 goto done;
11858 error = apply_unveil(got_repo_get_path(repo), 0,
11859 got_worktree_get_root_path(worktree));
11860 if (error)
11861 goto done;
11863 error = check_merge_in_progress(worktree, repo);
11864 if (error)
11865 goto done;
11867 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11868 error = got_error_from_errno("asprintf");
11869 goto done;
11872 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11873 &base_branch_ref, worktree, refname, repo);
11874 if (error)
11875 goto done;
11877 refname = strdup(got_ref_get_name(branch_ref));
11878 if (refname == NULL) {
11879 error = got_error_from_errno("strdup");
11880 got_worktree_integrate_abort(worktree, fileindex, repo,
11881 branch_ref, base_branch_ref);
11882 goto done;
11884 base_refname = strdup(got_ref_get_name(base_branch_ref));
11885 if (base_refname == NULL) {
11886 error = got_error_from_errno("strdup");
11887 got_worktree_integrate_abort(worktree, fileindex, repo,
11888 branch_ref, base_branch_ref);
11889 goto done;
11892 error = got_ref_resolve(&commit_id, repo, branch_ref);
11893 if (error)
11894 goto done;
11896 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11897 if (error)
11898 goto done;
11900 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11901 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11902 "specified branch has already been integrated");
11903 got_worktree_integrate_abort(worktree, fileindex, repo,
11904 branch_ref, base_branch_ref);
11905 goto done;
11908 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11909 if (error) {
11910 if (error->code == GOT_ERR_ANCESTRY)
11911 error = got_error(GOT_ERR_REBASE_REQUIRED);
11912 got_worktree_integrate_abort(worktree, fileindex, repo,
11913 branch_ref, base_branch_ref);
11914 goto done;
11917 memset(&upa, 0, sizeof(upa));
11918 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11919 branch_ref, base_branch_ref, update_progress, &upa,
11920 check_cancelled, NULL);
11921 if (error)
11922 goto done;
11924 printf("Integrated %s into %s\n", refname, base_refname);
11925 print_update_progress_stats(&upa);
11926 done:
11927 if (repo) {
11928 const struct got_error *close_err = got_repo_close(repo);
11929 if (error == NULL)
11930 error = close_err;
11932 if (worktree)
11933 got_worktree_close(worktree);
11934 if (pack_fds) {
11935 const struct got_error *pack_err =
11936 got_repo_pack_fds_close(pack_fds);
11937 if (error == NULL)
11938 error = pack_err;
11940 free(cwd);
11941 free(base_commit_id);
11942 free(commit_id);
11943 free(refname);
11944 free(base_refname);
11945 return error;
11948 __dead static void
11949 usage_merge(void)
11951 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11952 getprogname());
11953 exit(1);
11956 static const struct got_error *
11957 cmd_merge(int argc, char *argv[])
11959 const struct got_error *error = NULL;
11960 struct got_worktree *worktree = NULL;
11961 struct got_repository *repo = NULL;
11962 struct got_fileindex *fileindex = NULL;
11963 char *cwd = NULL, *id_str = NULL, *author = NULL;
11964 struct got_reference *branch = NULL, *wt_branch = NULL;
11965 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11966 struct got_object_id *wt_branch_tip = NULL;
11967 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11968 int interrupt_merge = 0;
11969 struct got_update_progress_arg upa;
11970 struct got_object_id *merge_commit_id = NULL;
11971 char *branch_name = NULL;
11972 int *pack_fds = NULL;
11974 memset(&upa, 0, sizeof(upa));
11976 while ((ch = getopt(argc, argv, "acn")) != -1) {
11977 switch (ch) {
11978 case 'a':
11979 abort_merge = 1;
11980 break;
11981 case 'c':
11982 continue_merge = 1;
11983 break;
11984 case 'n':
11985 interrupt_merge = 1;
11986 break;
11987 default:
11988 usage_rebase();
11989 /* NOTREACHED */
11993 argc -= optind;
11994 argv += optind;
11996 #ifndef PROFILE
11997 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11998 "unveil", NULL) == -1)
11999 err(1, "pledge");
12000 #endif
12002 if (abort_merge && continue_merge)
12003 option_conflict('a', 'c');
12004 if (abort_merge || continue_merge) {
12005 if (argc != 0)
12006 usage_merge();
12007 } else if (argc != 1)
12008 usage_merge();
12010 cwd = getcwd(NULL, 0);
12011 if (cwd == NULL) {
12012 error = got_error_from_errno("getcwd");
12013 goto done;
12016 error = got_repo_pack_fds_open(&pack_fds);
12017 if (error != NULL)
12018 goto done;
12020 error = got_worktree_open(&worktree, cwd);
12021 if (error) {
12022 if (error->code == GOT_ERR_NOT_WORKTREE)
12023 error = wrap_not_worktree_error(error,
12024 "merge", cwd);
12025 goto done;
12028 error = got_repo_open(&repo,
12029 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12030 pack_fds);
12031 if (error != NULL)
12032 goto done;
12034 error = apply_unveil(got_repo_get_path(repo), 0,
12035 worktree ? got_worktree_get_root_path(worktree) : NULL);
12036 if (error)
12037 goto done;
12039 error = check_rebase_or_histedit_in_progress(worktree);
12040 if (error)
12041 goto done;
12043 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12044 repo);
12045 if (error)
12046 goto done;
12048 if (abort_merge) {
12049 if (!merge_in_progress) {
12050 error = got_error(GOT_ERR_NOT_MERGING);
12051 goto done;
12053 error = got_worktree_merge_continue(&branch_name,
12054 &branch_tip, &fileindex, worktree, repo);
12055 if (error)
12056 goto done;
12057 error = got_worktree_merge_abort(worktree, fileindex, repo,
12058 abort_progress, &upa);
12059 if (error)
12060 goto done;
12061 printf("Merge of %s aborted\n", branch_name);
12062 goto done; /* nothing else to do */
12065 error = get_author(&author, repo, worktree);
12066 if (error)
12067 goto done;
12069 if (continue_merge) {
12070 if (!merge_in_progress) {
12071 error = got_error(GOT_ERR_NOT_MERGING);
12072 goto done;
12074 error = got_worktree_merge_continue(&branch_name,
12075 &branch_tip, &fileindex, worktree, repo);
12076 if (error)
12077 goto done;
12078 } else {
12079 error = got_ref_open(&branch, repo, argv[0], 0);
12080 if (error != NULL)
12081 goto done;
12082 branch_name = strdup(got_ref_get_name(branch));
12083 if (branch_name == NULL) {
12084 error = got_error_from_errno("strdup");
12085 goto done;
12087 error = got_ref_resolve(&branch_tip, repo, branch);
12088 if (error)
12089 goto done;
12092 error = got_ref_open(&wt_branch, repo,
12093 got_worktree_get_head_ref_name(worktree), 0);
12094 if (error)
12095 goto done;
12096 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12097 if (error)
12098 goto done;
12099 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12100 wt_branch_tip, branch_tip, 0, repo,
12101 check_cancelled, NULL);
12102 if (error && error->code != GOT_ERR_ANCESTRY)
12103 goto done;
12105 if (!continue_merge) {
12106 error = check_path_prefix(wt_branch_tip, branch_tip,
12107 got_worktree_get_path_prefix(worktree),
12108 GOT_ERR_MERGE_PATH, repo);
12109 if (error)
12110 goto done;
12111 if (yca_id) {
12112 error = check_same_branch(wt_branch_tip, branch,
12113 yca_id, repo);
12114 if (error) {
12115 if (error->code != GOT_ERR_ANCESTRY)
12116 goto done;
12117 error = NULL;
12118 } else {
12119 static char msg[512];
12120 snprintf(msg, sizeof(msg),
12121 "cannot create a merge commit because "
12122 "%s is based on %s; %s can be integrated "
12123 "with 'got integrate' instead", branch_name,
12124 got_worktree_get_head_ref_name(worktree),
12125 branch_name);
12126 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12127 goto done;
12130 error = got_worktree_merge_prepare(&fileindex, worktree,
12131 branch, repo);
12132 if (error)
12133 goto done;
12135 error = got_worktree_merge_branch(worktree, fileindex,
12136 yca_id, branch_tip, repo, update_progress, &upa,
12137 check_cancelled, NULL);
12138 if (error)
12139 goto done;
12140 print_merge_progress_stats(&upa);
12141 if (!upa.did_something) {
12142 error = got_worktree_merge_abort(worktree, fileindex,
12143 repo, abort_progress, &upa);
12144 if (error)
12145 goto done;
12146 printf("Already up-to-date\n");
12147 goto done;
12151 if (interrupt_merge) {
12152 error = got_worktree_merge_postpone(worktree, fileindex);
12153 if (error)
12154 goto done;
12155 printf("Merge of %s interrupted on request\n", branch_name);
12156 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12157 upa.not_deleted > 0 || upa.unversioned > 0) {
12158 error = got_worktree_merge_postpone(worktree, fileindex);
12159 if (error)
12160 goto done;
12161 if (upa.conflicts > 0 && upa.missing == 0 &&
12162 upa.not_deleted == 0 && upa.unversioned == 0) {
12163 error = got_error_msg(GOT_ERR_CONFLICTS,
12164 "conflicts must be resolved before merging "
12165 "can continue");
12166 } else if (upa.conflicts > 0) {
12167 error = got_error_msg(GOT_ERR_CONFLICTS,
12168 "conflicts must be resolved before merging "
12169 "can continue; changes destined for some "
12170 "files were not yet merged and "
12171 "should be merged manually if required before the "
12172 "merge operation is continued");
12173 } else {
12174 error = got_error_msg(GOT_ERR_CONFLICTS,
12175 "changes destined for some "
12176 "files were not yet merged and should be "
12177 "merged manually if required before the "
12178 "merge operation is continued");
12180 goto done;
12181 } else {
12182 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12183 fileindex, author, NULL, 1, branch_tip, branch_name,
12184 repo, continue_merge ? print_status : NULL, NULL);
12185 if (error)
12186 goto done;
12187 error = got_worktree_merge_complete(worktree, fileindex, repo);
12188 if (error)
12189 goto done;
12190 error = got_object_id_str(&id_str, merge_commit_id);
12191 if (error)
12192 goto done;
12193 printf("Merged %s into %s: %s\n", branch_name,
12194 got_worktree_get_head_ref_name(worktree),
12195 id_str);
12198 done:
12199 free(id_str);
12200 free(merge_commit_id);
12201 free(author);
12202 free(branch_tip);
12203 free(branch_name);
12204 free(yca_id);
12205 if (branch)
12206 got_ref_close(branch);
12207 if (wt_branch)
12208 got_ref_close(wt_branch);
12209 if (worktree)
12210 got_worktree_close(worktree);
12211 if (repo) {
12212 const struct got_error *close_err = got_repo_close(repo);
12213 if (error == NULL)
12214 error = close_err;
12216 if (pack_fds) {
12217 const struct got_error *pack_err =
12218 got_repo_pack_fds_close(pack_fds);
12219 if (error == NULL)
12220 error = pack_err;
12222 return error;
12225 __dead static void
12226 usage_stage(void)
12228 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12229 "[-S] [file-path ...]\n",
12230 getprogname());
12231 exit(1);
12234 static const struct got_error *
12235 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12236 const char *path, struct got_object_id *blob_id,
12237 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12238 int dirfd, const char *de_name)
12240 const struct got_error *err = NULL;
12241 char *id_str = NULL;
12243 if (staged_status != GOT_STATUS_ADD &&
12244 staged_status != GOT_STATUS_MODIFY &&
12245 staged_status != GOT_STATUS_DELETE)
12246 return NULL;
12248 if (staged_status == GOT_STATUS_ADD ||
12249 staged_status == GOT_STATUS_MODIFY)
12250 err = got_object_id_str(&id_str, staged_blob_id);
12251 else
12252 err = got_object_id_str(&id_str, blob_id);
12253 if (err)
12254 return err;
12256 printf("%s %c %s\n", id_str, staged_status, path);
12257 free(id_str);
12258 return NULL;
12261 static const struct got_error *
12262 cmd_stage(int argc, char *argv[])
12264 const struct got_error *error = NULL;
12265 struct got_repository *repo = NULL;
12266 struct got_worktree *worktree = NULL;
12267 char *cwd = NULL;
12268 struct got_pathlist_head paths;
12269 struct got_pathlist_entry *pe;
12270 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12271 FILE *patch_script_file = NULL;
12272 const char *patch_script_path = NULL;
12273 struct choose_patch_arg cpa;
12274 int *pack_fds = NULL;
12276 TAILQ_INIT(&paths);
12278 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12279 switch (ch) {
12280 case 'l':
12281 list_stage = 1;
12282 break;
12283 case 'p':
12284 pflag = 1;
12285 break;
12286 case 'F':
12287 patch_script_path = optarg;
12288 break;
12289 case 'S':
12290 allow_bad_symlinks = 1;
12291 break;
12292 default:
12293 usage_stage();
12294 /* NOTREACHED */
12298 argc -= optind;
12299 argv += optind;
12301 #ifndef PROFILE
12302 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12303 "unveil", NULL) == -1)
12304 err(1, "pledge");
12305 #endif
12306 if (list_stage && (pflag || patch_script_path))
12307 errx(1, "-l option cannot be used with other options");
12308 if (patch_script_path && !pflag)
12309 errx(1, "-F option can only be used together with -p option");
12311 cwd = getcwd(NULL, 0);
12312 if (cwd == NULL) {
12313 error = got_error_from_errno("getcwd");
12314 goto done;
12317 error = got_repo_pack_fds_open(&pack_fds);
12318 if (error != NULL)
12319 goto done;
12321 error = got_worktree_open(&worktree, cwd);
12322 if (error) {
12323 if (error->code == GOT_ERR_NOT_WORKTREE)
12324 error = wrap_not_worktree_error(error, "stage", cwd);
12325 goto done;
12328 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12329 NULL, pack_fds);
12330 if (error != NULL)
12331 goto done;
12333 if (patch_script_path) {
12334 patch_script_file = fopen(patch_script_path, "re");
12335 if (patch_script_file == NULL) {
12336 error = got_error_from_errno2("fopen",
12337 patch_script_path);
12338 goto done;
12341 error = apply_unveil(got_repo_get_path(repo), 0,
12342 got_worktree_get_root_path(worktree));
12343 if (error)
12344 goto done;
12346 error = check_merge_in_progress(worktree, repo);
12347 if (error)
12348 goto done;
12350 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12351 if (error)
12352 goto done;
12354 if (list_stage)
12355 error = got_worktree_status(worktree, &paths, repo, 0,
12356 print_stage, NULL, check_cancelled, NULL);
12357 else {
12358 cpa.patch_script_file = patch_script_file;
12359 cpa.action = "stage";
12360 error = got_worktree_stage(worktree, &paths,
12361 pflag ? NULL : print_status, NULL,
12362 pflag ? choose_patch : NULL, &cpa,
12363 allow_bad_symlinks, repo);
12365 done:
12366 if (patch_script_file && fclose(patch_script_file) == EOF &&
12367 error == NULL)
12368 error = got_error_from_errno2("fclose", patch_script_path);
12369 if (repo) {
12370 const struct got_error *close_err = got_repo_close(repo);
12371 if (error == NULL)
12372 error = close_err;
12374 if (worktree)
12375 got_worktree_close(worktree);
12376 if (pack_fds) {
12377 const struct got_error *pack_err =
12378 got_repo_pack_fds_close(pack_fds);
12379 if (error == NULL)
12380 error = pack_err;
12382 TAILQ_FOREACH(pe, &paths, entry)
12383 free((char *)pe->path);
12384 got_pathlist_free(&paths);
12385 free(cwd);
12386 return error;
12389 __dead static void
12390 usage_unstage(void)
12392 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12393 "[file-path ...]\n",
12394 getprogname());
12395 exit(1);
12399 static const struct got_error *
12400 cmd_unstage(int argc, char *argv[])
12402 const struct got_error *error = NULL;
12403 struct got_repository *repo = NULL;
12404 struct got_worktree *worktree = NULL;
12405 char *cwd = NULL;
12406 struct got_pathlist_head paths;
12407 struct got_pathlist_entry *pe;
12408 int ch, pflag = 0;
12409 struct got_update_progress_arg upa;
12410 FILE *patch_script_file = NULL;
12411 const char *patch_script_path = NULL;
12412 struct choose_patch_arg cpa;
12413 int *pack_fds = NULL;
12415 TAILQ_INIT(&paths);
12417 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12418 switch (ch) {
12419 case 'p':
12420 pflag = 1;
12421 break;
12422 case 'F':
12423 patch_script_path = optarg;
12424 break;
12425 default:
12426 usage_unstage();
12427 /* NOTREACHED */
12431 argc -= optind;
12432 argv += optind;
12434 #ifndef PROFILE
12435 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12436 "unveil", NULL) == -1)
12437 err(1, "pledge");
12438 #endif
12439 if (patch_script_path && !pflag)
12440 errx(1, "-F option can only be used together with -p option");
12442 cwd = getcwd(NULL, 0);
12443 if (cwd == NULL) {
12444 error = got_error_from_errno("getcwd");
12445 goto done;
12448 error = got_repo_pack_fds_open(&pack_fds);
12449 if (error != NULL)
12450 goto done;
12452 error = got_worktree_open(&worktree, cwd);
12453 if (error) {
12454 if (error->code == GOT_ERR_NOT_WORKTREE)
12455 error = wrap_not_worktree_error(error, "unstage", cwd);
12456 goto done;
12459 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12460 NULL, pack_fds);
12461 if (error != NULL)
12462 goto done;
12464 if (patch_script_path) {
12465 patch_script_file = fopen(patch_script_path, "re");
12466 if (patch_script_file == NULL) {
12467 error = got_error_from_errno2("fopen",
12468 patch_script_path);
12469 goto done;
12473 error = apply_unveil(got_repo_get_path(repo), 0,
12474 got_worktree_get_root_path(worktree));
12475 if (error)
12476 goto done;
12478 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12479 if (error)
12480 goto done;
12482 cpa.patch_script_file = patch_script_file;
12483 cpa.action = "unstage";
12484 memset(&upa, 0, sizeof(upa));
12485 error = got_worktree_unstage(worktree, &paths, update_progress,
12486 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12487 if (!error)
12488 print_merge_progress_stats(&upa);
12489 done:
12490 if (patch_script_file && fclose(patch_script_file) == EOF &&
12491 error == NULL)
12492 error = got_error_from_errno2("fclose", patch_script_path);
12493 if (repo) {
12494 const struct got_error *close_err = got_repo_close(repo);
12495 if (error == NULL)
12496 error = close_err;
12498 if (worktree)
12499 got_worktree_close(worktree);
12500 if (pack_fds) {
12501 const struct got_error *pack_err =
12502 got_repo_pack_fds_close(pack_fds);
12503 if (error == NULL)
12504 error = pack_err;
12506 TAILQ_FOREACH(pe, &paths, entry)
12507 free((char *)pe->path);
12508 got_pathlist_free(&paths);
12509 free(cwd);
12510 return error;
12513 __dead static void
12514 usage_cat(void)
12516 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12517 "arg1 [arg2 ...]\n", getprogname());
12518 exit(1);
12521 static const struct got_error *
12522 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12524 const struct got_error *err;
12525 struct got_blob_object *blob;
12526 int fd = -1;
12528 fd = got_opentempfd();
12529 if (fd == -1)
12530 return got_error_from_errno("got_opentempfd");
12532 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12533 if (err)
12534 goto done;
12536 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12537 done:
12538 if (fd != -1 && close(fd) == -1 && err == NULL)
12539 err = got_error_from_errno("close");
12540 if (blob)
12541 got_object_blob_close(blob);
12542 return err;
12545 static const struct got_error *
12546 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12548 const struct got_error *err;
12549 struct got_tree_object *tree;
12550 int nentries, i;
12552 err = got_object_open_as_tree(&tree, repo, id);
12553 if (err)
12554 return err;
12556 nentries = got_object_tree_get_nentries(tree);
12557 for (i = 0; i < nentries; i++) {
12558 struct got_tree_entry *te;
12559 char *id_str;
12560 if (sigint_received || sigpipe_received)
12561 break;
12562 te = got_object_tree_get_entry(tree, i);
12563 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12564 if (err)
12565 break;
12566 fprintf(outfile, "%s %.7o %s\n", id_str,
12567 got_tree_entry_get_mode(te),
12568 got_tree_entry_get_name(te));
12569 free(id_str);
12572 got_object_tree_close(tree);
12573 return err;
12576 static const struct got_error *
12577 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12579 const struct got_error *err;
12580 struct got_commit_object *commit;
12581 const struct got_object_id_queue *parent_ids;
12582 struct got_object_qid *pid;
12583 char *id_str = NULL;
12584 const char *logmsg = NULL;
12585 char gmtoff[6];
12587 err = got_object_open_as_commit(&commit, repo, id);
12588 if (err)
12589 return err;
12591 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12592 if (err)
12593 goto done;
12595 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12596 parent_ids = got_object_commit_get_parent_ids(commit);
12597 fprintf(outfile, "numparents %d\n",
12598 got_object_commit_get_nparents(commit));
12599 STAILQ_FOREACH(pid, parent_ids, entry) {
12600 char *pid_str;
12601 err = got_object_id_str(&pid_str, &pid->id);
12602 if (err)
12603 goto done;
12604 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12605 free(pid_str);
12607 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12608 got_object_commit_get_author_gmtoff(commit));
12609 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12610 got_object_commit_get_author(commit),
12611 (long long)got_object_commit_get_author_time(commit),
12612 gmtoff);
12614 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12615 got_object_commit_get_committer_gmtoff(commit));
12616 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12617 got_object_commit_get_author(commit),
12618 (long long)got_object_commit_get_committer_time(commit),
12619 gmtoff);
12621 logmsg = got_object_commit_get_logmsg_raw(commit);
12622 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12623 fprintf(outfile, "%s", logmsg);
12624 done:
12625 free(id_str);
12626 got_object_commit_close(commit);
12627 return err;
12630 static const struct got_error *
12631 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12633 const struct got_error *err;
12634 struct got_tag_object *tag;
12635 char *id_str = NULL;
12636 const char *tagmsg = NULL;
12637 char gmtoff[6];
12639 err = got_object_open_as_tag(&tag, repo, id);
12640 if (err)
12641 return err;
12643 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12644 if (err)
12645 goto done;
12647 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12649 switch (got_object_tag_get_object_type(tag)) {
12650 case GOT_OBJ_TYPE_BLOB:
12651 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12652 GOT_OBJ_LABEL_BLOB);
12653 break;
12654 case GOT_OBJ_TYPE_TREE:
12655 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12656 GOT_OBJ_LABEL_TREE);
12657 break;
12658 case GOT_OBJ_TYPE_COMMIT:
12659 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12660 GOT_OBJ_LABEL_COMMIT);
12661 break;
12662 case GOT_OBJ_TYPE_TAG:
12663 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12664 GOT_OBJ_LABEL_TAG);
12665 break;
12666 default:
12667 break;
12670 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12671 got_object_tag_get_name(tag));
12673 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12674 got_object_tag_get_tagger_gmtoff(tag));
12675 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12676 got_object_tag_get_tagger(tag),
12677 (long long)got_object_tag_get_tagger_time(tag),
12678 gmtoff);
12680 tagmsg = got_object_tag_get_message(tag);
12681 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12682 fprintf(outfile, "%s", tagmsg);
12683 done:
12684 free(id_str);
12685 got_object_tag_close(tag);
12686 return err;
12689 static const struct got_error *
12690 cmd_cat(int argc, char *argv[])
12692 const struct got_error *error;
12693 struct got_repository *repo = NULL;
12694 struct got_worktree *worktree = NULL;
12695 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12696 const char *commit_id_str = NULL;
12697 struct got_object_id *id = NULL, *commit_id = NULL;
12698 struct got_commit_object *commit = NULL;
12699 int ch, obj_type, i, force_path = 0;
12700 struct got_reflist_head refs;
12701 int *pack_fds = NULL;
12703 TAILQ_INIT(&refs);
12705 #ifndef PROFILE
12706 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12707 NULL) == -1)
12708 err(1, "pledge");
12709 #endif
12711 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12712 switch (ch) {
12713 case 'c':
12714 commit_id_str = optarg;
12715 break;
12716 case 'r':
12717 repo_path = realpath(optarg, NULL);
12718 if (repo_path == NULL)
12719 return got_error_from_errno2("realpath",
12720 optarg);
12721 got_path_strip_trailing_slashes(repo_path);
12722 break;
12723 case 'P':
12724 force_path = 1;
12725 break;
12726 default:
12727 usage_cat();
12728 /* NOTREACHED */
12732 argc -= optind;
12733 argv += optind;
12735 cwd = getcwd(NULL, 0);
12736 if (cwd == NULL) {
12737 error = got_error_from_errno("getcwd");
12738 goto done;
12741 error = got_repo_pack_fds_open(&pack_fds);
12742 if (error != NULL)
12743 goto done;
12745 if (repo_path == NULL) {
12746 error = got_worktree_open(&worktree, cwd);
12747 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12748 goto done;
12749 if (worktree) {
12750 repo_path = strdup(
12751 got_worktree_get_repo_path(worktree));
12752 if (repo_path == NULL) {
12753 error = got_error_from_errno("strdup");
12754 goto done;
12757 /* Release work tree lock. */
12758 got_worktree_close(worktree);
12759 worktree = NULL;
12763 if (repo_path == NULL) {
12764 repo_path = strdup(cwd);
12765 if (repo_path == NULL)
12766 return got_error_from_errno("strdup");
12769 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12770 free(repo_path);
12771 if (error != NULL)
12772 goto done;
12774 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12775 if (error)
12776 goto done;
12778 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12779 if (error)
12780 goto done;
12782 if (commit_id_str == NULL)
12783 commit_id_str = GOT_REF_HEAD;
12784 error = got_repo_match_object_id(&commit_id, NULL,
12785 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12786 if (error)
12787 goto done;
12789 error = got_object_open_as_commit(&commit, repo, commit_id);
12790 if (error)
12791 goto done;
12793 for (i = 0; i < argc; i++) {
12794 if (force_path) {
12795 error = got_object_id_by_path(&id, repo, commit,
12796 argv[i]);
12797 if (error)
12798 break;
12799 } else {
12800 error = got_repo_match_object_id(&id, &label, argv[i],
12801 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12802 repo);
12803 if (error) {
12804 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12805 error->code != GOT_ERR_NOT_REF)
12806 break;
12807 error = got_object_id_by_path(&id, repo,
12808 commit, argv[i]);
12809 if (error)
12810 break;
12814 error = got_object_get_type(&obj_type, repo, id);
12815 if (error)
12816 break;
12818 switch (obj_type) {
12819 case GOT_OBJ_TYPE_BLOB:
12820 error = cat_blob(id, repo, stdout);
12821 break;
12822 case GOT_OBJ_TYPE_TREE:
12823 error = cat_tree(id, repo, stdout);
12824 break;
12825 case GOT_OBJ_TYPE_COMMIT:
12826 error = cat_commit(id, repo, stdout);
12827 break;
12828 case GOT_OBJ_TYPE_TAG:
12829 error = cat_tag(id, repo, stdout);
12830 break;
12831 default:
12832 error = got_error(GOT_ERR_OBJ_TYPE);
12833 break;
12835 if (error)
12836 break;
12837 free(label);
12838 label = NULL;
12839 free(id);
12840 id = NULL;
12842 done:
12843 free(label);
12844 free(id);
12845 free(commit_id);
12846 if (commit)
12847 got_object_commit_close(commit);
12848 if (worktree)
12849 got_worktree_close(worktree);
12850 if (repo) {
12851 const struct got_error *close_err = got_repo_close(repo);
12852 if (error == NULL)
12853 error = close_err;
12855 if (pack_fds) {
12856 const struct got_error *pack_err =
12857 got_repo_pack_fds_close(pack_fds);
12858 if (error == NULL)
12859 error = pack_err;
12862 got_ref_list_free(&refs);
12863 return error;
12866 __dead static void
12867 usage_info(void)
12869 fprintf(stderr, "usage: %s info [path ...]\n",
12870 getprogname());
12871 exit(1);
12874 static const struct got_error *
12875 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12876 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12877 struct got_object_id *commit_id)
12879 const struct got_error *err = NULL;
12880 char *id_str = NULL;
12881 char datebuf[128];
12882 struct tm mytm, *tm;
12883 struct got_pathlist_head *paths = arg;
12884 struct got_pathlist_entry *pe;
12887 * Clear error indication from any of the path arguments which
12888 * would cause this file index entry to be displayed.
12890 TAILQ_FOREACH(pe, paths, entry) {
12891 if (got_path_cmp(path, pe->path, strlen(path),
12892 pe->path_len) == 0 ||
12893 got_path_is_child(path, pe->path, pe->path_len))
12894 pe->data = NULL; /* no error */
12897 printf(GOT_COMMIT_SEP_STR);
12898 if (S_ISLNK(mode))
12899 printf("symlink: %s\n", path);
12900 else if (S_ISREG(mode)) {
12901 printf("file: %s\n", path);
12902 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12903 } else if (S_ISDIR(mode))
12904 printf("directory: %s\n", path);
12905 else
12906 printf("something: %s\n", path);
12908 tm = localtime_r(&mtime, &mytm);
12909 if (tm == NULL)
12910 return NULL;
12911 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12912 return got_error(GOT_ERR_NO_SPACE);
12913 printf("timestamp: %s\n", datebuf);
12915 if (blob_id) {
12916 err = got_object_id_str(&id_str, blob_id);
12917 if (err)
12918 return err;
12919 printf("based on blob: %s\n", id_str);
12920 free(id_str);
12923 if (staged_blob_id) {
12924 err = got_object_id_str(&id_str, staged_blob_id);
12925 if (err)
12926 return err;
12927 printf("based on staged blob: %s\n", id_str);
12928 free(id_str);
12931 if (commit_id) {
12932 err = got_object_id_str(&id_str, commit_id);
12933 if (err)
12934 return err;
12935 printf("based on commit: %s\n", id_str);
12936 free(id_str);
12939 return NULL;
12942 static const struct got_error *
12943 cmd_info(int argc, char *argv[])
12945 const struct got_error *error = NULL;
12946 struct got_worktree *worktree = NULL;
12947 char *cwd = NULL, *id_str = NULL;
12948 struct got_pathlist_head paths;
12949 struct got_pathlist_entry *pe;
12950 char *uuidstr = NULL;
12951 int ch, show_files = 0;
12952 int *pack_fds = NULL;
12954 TAILQ_INIT(&paths);
12956 while ((ch = getopt(argc, argv, "")) != -1) {
12957 switch (ch) {
12958 default:
12959 usage_info();
12960 /* NOTREACHED */
12964 argc -= optind;
12965 argv += optind;
12967 #ifndef PROFILE
12968 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12969 NULL) == -1)
12970 err(1, "pledge");
12971 #endif
12972 cwd = getcwd(NULL, 0);
12973 if (cwd == NULL) {
12974 error = got_error_from_errno("getcwd");
12975 goto done;
12978 error = got_repo_pack_fds_open(&pack_fds);
12979 if (error != NULL)
12980 goto done;
12982 error = got_worktree_open(&worktree, cwd);
12983 if (error) {
12984 if (error->code == GOT_ERR_NOT_WORKTREE)
12985 error = wrap_not_worktree_error(error, "info", cwd);
12986 goto done;
12989 #ifndef PROFILE
12990 /* Remove "cpath" promise. */
12991 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12992 NULL) == -1)
12993 err(1, "pledge");
12994 #endif
12995 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12996 if (error)
12997 goto done;
12999 if (argc >= 1) {
13000 error = get_worktree_paths_from_argv(&paths, argc, argv,
13001 worktree);
13002 if (error)
13003 goto done;
13004 show_files = 1;
13007 error = got_object_id_str(&id_str,
13008 got_worktree_get_base_commit_id(worktree));
13009 if (error)
13010 goto done;
13012 error = got_worktree_get_uuid(&uuidstr, worktree);
13013 if (error)
13014 goto done;
13016 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13017 printf("work tree base commit: %s\n", id_str);
13018 printf("work tree path prefix: %s\n",
13019 got_worktree_get_path_prefix(worktree));
13020 printf("work tree branch reference: %s\n",
13021 got_worktree_get_head_ref_name(worktree));
13022 printf("work tree UUID: %s\n", uuidstr);
13023 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13025 if (show_files) {
13026 struct got_pathlist_entry *pe;
13027 TAILQ_FOREACH(pe, &paths, entry) {
13028 if (pe->path_len == 0)
13029 continue;
13031 * Assume this path will fail. This will be corrected
13032 * in print_path_info() in case the path does suceeed.
13034 pe->data = (void *)got_error_path(pe->path,
13035 GOT_ERR_BAD_PATH);
13037 error = got_worktree_path_info(worktree, &paths,
13038 print_path_info, &paths, check_cancelled, NULL);
13039 if (error)
13040 goto done;
13041 TAILQ_FOREACH(pe, &paths, entry) {
13042 if (pe->data != NULL) {
13043 error = pe->data; /* bad path */
13044 break;
13048 done:
13049 if (pack_fds) {
13050 const struct got_error *pack_err =
13051 got_repo_pack_fds_close(pack_fds);
13052 if (error == NULL)
13053 error = pack_err;
13055 TAILQ_FOREACH(pe, &paths, entry)
13056 free((char *)pe->path);
13057 got_pathlist_free(&paths);
13058 free(cwd);
13059 free(id_str);
13060 free(uuidstr);
13061 return error;