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 if (do_list)
7372 option_conflict('l', 'm');
7373 else
7374 option_conflict('V', 'm');
7376 if (signer_id) {
7377 if (do_list)
7378 option_conflict('l', 's');
7379 else
7380 option_conflict('V', 's');
7382 if (argc > 1)
7383 usage_tag();
7384 } else if (argc != 1)
7385 usage_tag();
7387 if (argc == 1)
7388 tag_name = argv[0];
7390 #ifndef PROFILE
7391 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7392 "sendfd unveil", NULL) == -1)
7393 err(1, "pledge");
7394 #endif
7395 cwd = getcwd(NULL, 0);
7396 if (cwd == NULL) {
7397 error = got_error_from_errno("getcwd");
7398 goto done;
7401 error = got_repo_pack_fds_open(&pack_fds);
7402 if (error != NULL)
7403 goto done;
7405 if (repo_path == NULL) {
7406 error = got_worktree_open(&worktree, cwd);
7407 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7408 goto done;
7409 else
7410 error = NULL;
7411 if (worktree) {
7412 repo_path =
7413 strdup(got_worktree_get_repo_path(worktree));
7414 if (repo_path == NULL)
7415 error = got_error_from_errno("strdup");
7416 if (error)
7417 goto done;
7418 } else {
7419 repo_path = strdup(cwd);
7420 if (repo_path == NULL) {
7421 error = got_error_from_errno("strdup");
7422 goto done;
7427 if (do_list || verify_tags) {
7428 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7429 if (error != NULL)
7430 goto done;
7431 error = get_allowed_signers(&allowed_signers, repo, worktree);
7432 if (error)
7433 goto done;
7434 error = get_revoked_signers(&revoked_signers, repo, worktree);
7435 if (error)
7436 goto done;
7437 if (worktree) {
7438 /* Release work tree lock. */
7439 got_worktree_close(worktree);
7440 worktree = NULL;
7444 * Remove "cpath" promise unless needed for signature tmpfile
7445 * creation.
7447 if (verify_tags)
7448 got_sigs_apply_unveil();
7449 else {
7450 #ifndef PROFILE
7451 if (pledge("stdio rpath wpath flock proc exec sendfd "
7452 "unveil", NULL) == -1)
7453 err(1, "pledge");
7454 #endif
7456 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7457 if (error)
7458 goto done;
7459 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7460 revoked_signers, verbosity);
7461 } else {
7462 error = get_gitconfig_path(&gitconfig_path);
7463 if (error)
7464 goto done;
7465 error = got_repo_open(&repo, repo_path, gitconfig_path,
7466 pack_fds);
7467 if (error != NULL)
7468 goto done;
7470 error = get_author(&tagger, repo, worktree);
7471 if (error)
7472 goto done;
7473 if (signer_id == NULL) {
7474 error = get_signer_id(&signer_id, repo, worktree);
7475 if (error)
7476 goto done;
7478 if (worktree) {
7479 /* Release work tree lock. */
7480 got_worktree_close(worktree);
7481 worktree = NULL;
7484 if (tagmsg) {
7485 if (signer_id) {
7486 error = got_sigs_apply_unveil();
7487 if (error)
7488 goto done;
7490 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7491 if (error)
7492 goto done;
7495 if (commit_id_arg == NULL) {
7496 struct got_reference *head_ref;
7497 struct got_object_id *commit_id;
7498 error = got_ref_open(&head_ref, repo,
7499 worktree ? got_worktree_get_head_ref_name(worktree)
7500 : GOT_REF_HEAD, 0);
7501 if (error)
7502 goto done;
7503 error = got_ref_resolve(&commit_id, repo, head_ref);
7504 got_ref_close(head_ref);
7505 if (error)
7506 goto done;
7507 error = got_object_id_str(&commit_id_str, commit_id);
7508 free(commit_id);
7509 if (error)
7510 goto done;
7513 error = add_tag(repo, tagger, tag_name,
7514 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7515 signer_id, verbosity);
7517 done:
7518 if (repo) {
7519 const struct got_error *close_err = got_repo_close(repo);
7520 if (error == NULL)
7521 error = close_err;
7523 if (worktree)
7524 got_worktree_close(worktree);
7525 if (pack_fds) {
7526 const struct got_error *pack_err =
7527 got_repo_pack_fds_close(pack_fds);
7528 if (error == NULL)
7529 error = pack_err;
7531 free(cwd);
7532 free(repo_path);
7533 free(gitconfig_path);
7534 free(commit_id_str);
7535 free(tagger);
7536 free(allowed_signers);
7537 free(revoked_signers);
7538 free(signer_id);
7539 return error;
7542 __dead static void
7543 usage_add(void)
7545 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7546 getprogname());
7547 exit(1);
7550 static const struct got_error *
7551 add_progress(void *arg, unsigned char status, const char *path)
7553 while (path[0] == '/')
7554 path++;
7555 printf("%c %s\n", status, path);
7556 return NULL;
7559 static const struct got_error *
7560 cmd_add(int argc, char *argv[])
7562 const struct got_error *error = NULL;
7563 struct got_repository *repo = NULL;
7564 struct got_worktree *worktree = NULL;
7565 char *cwd = NULL;
7566 struct got_pathlist_head paths;
7567 struct got_pathlist_entry *pe;
7568 int ch, can_recurse = 0, no_ignores = 0;
7569 int *pack_fds = NULL;
7571 TAILQ_INIT(&paths);
7573 while ((ch = getopt(argc, argv, "IR")) != -1) {
7574 switch (ch) {
7575 case 'I':
7576 no_ignores = 1;
7577 break;
7578 case 'R':
7579 can_recurse = 1;
7580 break;
7581 default:
7582 usage_add();
7583 /* NOTREACHED */
7587 argc -= optind;
7588 argv += optind;
7590 #ifndef PROFILE
7591 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7592 NULL) == -1)
7593 err(1, "pledge");
7594 #endif
7595 if (argc < 1)
7596 usage_add();
7598 cwd = getcwd(NULL, 0);
7599 if (cwd == NULL) {
7600 error = got_error_from_errno("getcwd");
7601 goto done;
7604 error = got_repo_pack_fds_open(&pack_fds);
7605 if (error != NULL)
7606 goto done;
7608 error = got_worktree_open(&worktree, cwd);
7609 if (error) {
7610 if (error->code == GOT_ERR_NOT_WORKTREE)
7611 error = wrap_not_worktree_error(error, "add", cwd);
7612 goto done;
7615 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7616 NULL, pack_fds);
7617 if (error != NULL)
7618 goto done;
7620 error = apply_unveil(got_repo_get_path(repo), 1,
7621 got_worktree_get_root_path(worktree));
7622 if (error)
7623 goto done;
7625 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7626 if (error)
7627 goto done;
7629 if (!can_recurse) {
7630 char *ondisk_path;
7631 struct stat sb;
7632 TAILQ_FOREACH(pe, &paths, entry) {
7633 if (asprintf(&ondisk_path, "%s/%s",
7634 got_worktree_get_root_path(worktree),
7635 pe->path) == -1) {
7636 error = got_error_from_errno("asprintf");
7637 goto done;
7639 if (lstat(ondisk_path, &sb) == -1) {
7640 if (errno == ENOENT) {
7641 free(ondisk_path);
7642 continue;
7644 error = got_error_from_errno2("lstat",
7645 ondisk_path);
7646 free(ondisk_path);
7647 goto done;
7649 free(ondisk_path);
7650 if (S_ISDIR(sb.st_mode)) {
7651 error = got_error_msg(GOT_ERR_BAD_PATH,
7652 "adding directories requires -R option");
7653 goto done;
7658 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7659 NULL, repo, no_ignores);
7660 done:
7661 if (repo) {
7662 const struct got_error *close_err = got_repo_close(repo);
7663 if (error == NULL)
7664 error = close_err;
7666 if (worktree)
7667 got_worktree_close(worktree);
7668 if (pack_fds) {
7669 const struct got_error *pack_err =
7670 got_repo_pack_fds_close(pack_fds);
7671 if (error == NULL)
7672 error = pack_err;
7674 TAILQ_FOREACH(pe, &paths, entry)
7675 free((char *)pe->path);
7676 got_pathlist_free(&paths);
7677 free(cwd);
7678 return error;
7681 __dead static void
7682 usage_remove(void)
7684 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7685 "path ...\n", getprogname());
7686 exit(1);
7689 static const struct got_error *
7690 print_remove_status(void *arg, unsigned char status,
7691 unsigned char staged_status, const char *path)
7693 while (path[0] == '/')
7694 path++;
7695 if (status == GOT_STATUS_NONEXISTENT)
7696 return NULL;
7697 if (status == staged_status && (status == GOT_STATUS_DELETE))
7698 status = GOT_STATUS_NO_CHANGE;
7699 printf("%c%c %s\n", status, staged_status, path);
7700 return NULL;
7703 static const struct got_error *
7704 cmd_remove(int argc, char *argv[])
7706 const struct got_error *error = NULL;
7707 struct got_worktree *worktree = NULL;
7708 struct got_repository *repo = NULL;
7709 const char *status_codes = NULL;
7710 char *cwd = NULL;
7711 struct got_pathlist_head paths;
7712 struct got_pathlist_entry *pe;
7713 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7714 int ignore_missing_paths = 0;
7715 int *pack_fds = NULL;
7717 TAILQ_INIT(&paths);
7719 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7720 switch (ch) {
7721 case 'f':
7722 delete_local_mods = 1;
7723 ignore_missing_paths = 1;
7724 break;
7725 case 'k':
7726 keep_on_disk = 1;
7727 break;
7728 case 'R':
7729 can_recurse = 1;
7730 break;
7731 case 's':
7732 for (i = 0; i < strlen(optarg); i++) {
7733 switch (optarg[i]) {
7734 case GOT_STATUS_MODIFY:
7735 delete_local_mods = 1;
7736 break;
7737 case GOT_STATUS_MISSING:
7738 ignore_missing_paths = 1;
7739 break;
7740 default:
7741 errx(1, "invalid status code '%c'",
7742 optarg[i]);
7745 status_codes = optarg;
7746 break;
7747 default:
7748 usage_remove();
7749 /* NOTREACHED */
7753 argc -= optind;
7754 argv += optind;
7756 #ifndef PROFILE
7757 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7758 NULL) == -1)
7759 err(1, "pledge");
7760 #endif
7761 if (argc < 1)
7762 usage_remove();
7764 cwd = getcwd(NULL, 0);
7765 if (cwd == NULL) {
7766 error = got_error_from_errno("getcwd");
7767 goto done;
7770 error = got_repo_pack_fds_open(&pack_fds);
7771 if (error != NULL)
7772 goto done;
7774 error = got_worktree_open(&worktree, cwd);
7775 if (error) {
7776 if (error->code == GOT_ERR_NOT_WORKTREE)
7777 error = wrap_not_worktree_error(error, "remove", cwd);
7778 goto done;
7781 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7782 NULL, pack_fds);
7783 if (error)
7784 goto done;
7786 error = apply_unveil(got_repo_get_path(repo), 1,
7787 got_worktree_get_root_path(worktree));
7788 if (error)
7789 goto done;
7791 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7792 if (error)
7793 goto done;
7795 if (!can_recurse) {
7796 char *ondisk_path;
7797 struct stat sb;
7798 TAILQ_FOREACH(pe, &paths, entry) {
7799 if (asprintf(&ondisk_path, "%s/%s",
7800 got_worktree_get_root_path(worktree),
7801 pe->path) == -1) {
7802 error = got_error_from_errno("asprintf");
7803 goto done;
7805 if (lstat(ondisk_path, &sb) == -1) {
7806 if (errno == ENOENT) {
7807 free(ondisk_path);
7808 continue;
7810 error = got_error_from_errno2("lstat",
7811 ondisk_path);
7812 free(ondisk_path);
7813 goto done;
7815 free(ondisk_path);
7816 if (S_ISDIR(sb.st_mode)) {
7817 error = got_error_msg(GOT_ERR_BAD_PATH,
7818 "removing directories requires -R option");
7819 goto done;
7824 error = got_worktree_schedule_delete(worktree, &paths,
7825 delete_local_mods, status_codes, print_remove_status, NULL,
7826 repo, keep_on_disk, ignore_missing_paths);
7827 done:
7828 if (repo) {
7829 const struct got_error *close_err = got_repo_close(repo);
7830 if (error == NULL)
7831 error = close_err;
7833 if (worktree)
7834 got_worktree_close(worktree);
7835 if (pack_fds) {
7836 const struct got_error *pack_err =
7837 got_repo_pack_fds_close(pack_fds);
7838 if (error == NULL)
7839 error = pack_err;
7841 TAILQ_FOREACH(pe, &paths, entry)
7842 free((char *)pe->path);
7843 got_pathlist_free(&paths);
7844 free(cwd);
7845 return error;
7848 __dead static void
7849 usage_patch(void)
7851 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7852 "[-R] [patchfile]\n", getprogname());
7853 exit(1);
7856 static const struct got_error *
7857 patch_from_stdin(int *patchfd)
7859 const struct got_error *err = NULL;
7860 ssize_t r;
7861 char *path, buf[BUFSIZ];
7862 sig_t sighup, sigint, sigquit;
7864 err = got_opentemp_named_fd(&path, patchfd,
7865 GOT_TMPDIR_STR "/got-patch");
7866 if (err)
7867 return err;
7868 unlink(path);
7869 free(path);
7871 sighup = signal(SIGHUP, SIG_DFL);
7872 sigint = signal(SIGINT, SIG_DFL);
7873 sigquit = signal(SIGQUIT, SIG_DFL);
7875 for (;;) {
7876 r = read(0, buf, sizeof(buf));
7877 if (r == -1) {
7878 err = got_error_from_errno("read");
7879 break;
7881 if (r == 0)
7882 break;
7883 if (write(*patchfd, buf, r) == -1) {
7884 err = got_error_from_errno("write");
7885 break;
7889 signal(SIGHUP, sighup);
7890 signal(SIGINT, sigint);
7891 signal(SIGQUIT, sigquit);
7893 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7894 err = got_error_from_errno("lseek");
7896 if (err != NULL) {
7897 close(*patchfd);
7898 *patchfd = -1;
7901 return err;
7904 static const struct got_error *
7905 patch_progress(void *arg, const char *old, const char *new,
7906 unsigned char status, const struct got_error *error, int old_from,
7907 int old_lines, int new_from, int new_lines, int offset,
7908 int ws_mangled, const struct got_error *hunk_err)
7910 const char *path = new == NULL ? old : new;
7912 while (*path == '/')
7913 path++;
7915 if (status != 0)
7916 printf("%c %s\n", status, path);
7918 if (error != NULL)
7919 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7921 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7922 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7923 old_lines, new_from, new_lines);
7924 if (hunk_err != NULL)
7925 printf("%s\n", hunk_err->msg);
7926 else if (offset != 0)
7927 printf("applied with offset %d\n", offset);
7928 else
7929 printf("hunk contains mangled whitespace\n");
7932 return NULL;
7935 static const struct got_error *
7936 cmd_patch(int argc, char *argv[])
7938 const struct got_error *error = NULL, *close_error = NULL;
7939 struct got_worktree *worktree = NULL;
7940 struct got_repository *repo = NULL;
7941 const char *errstr;
7942 char *cwd = NULL;
7943 int ch, nop = 0, strip = -1, reverse = 0;
7944 int patchfd;
7945 int *pack_fds = NULL;
7947 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7948 switch (ch) {
7949 case 'n':
7950 nop = 1;
7951 break;
7952 case 'p':
7953 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7954 if (errstr != NULL)
7955 errx(1, "pathname strip count is %s: %s",
7956 errstr, optarg);
7957 break;
7958 case 'R':
7959 reverse = 1;
7960 break;
7961 default:
7962 usage_patch();
7963 /* NOTREACHED */
7967 argc -= optind;
7968 argv += optind;
7970 if (argc == 0) {
7971 error = patch_from_stdin(&patchfd);
7972 if (error)
7973 return error;
7974 } else if (argc == 1) {
7975 patchfd = open(argv[0], O_RDONLY);
7976 if (patchfd == -1) {
7977 error = got_error_from_errno2("open", argv[0]);
7978 return error;
7980 } else
7981 usage_patch();
7983 if ((cwd = getcwd(NULL, 0)) == NULL) {
7984 error = got_error_from_errno("getcwd");
7985 goto done;
7988 error = got_repo_pack_fds_open(&pack_fds);
7989 if (error != NULL)
7990 goto done;
7992 error = got_worktree_open(&worktree, cwd);
7993 if (error != NULL)
7994 goto done;
7996 const char *repo_path = got_worktree_get_repo_path(worktree);
7997 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7998 if (error != NULL)
7999 goto done;
8001 error = apply_unveil(got_repo_get_path(repo), 0,
8002 got_worktree_get_root_path(worktree));
8003 if (error != NULL)
8004 goto done;
8006 #ifndef PROFILE
8007 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
8008 NULL) == -1)
8009 err(1, "pledge");
8010 #endif
8012 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8013 &patch_progress, NULL, check_cancelled, NULL);
8015 done:
8016 if (repo) {
8017 close_error = got_repo_close(repo);
8018 if (error == NULL)
8019 error = close_error;
8021 if (worktree != NULL) {
8022 close_error = got_worktree_close(worktree);
8023 if (error == NULL)
8024 error = close_error;
8026 if (pack_fds) {
8027 const struct got_error *pack_err =
8028 got_repo_pack_fds_close(pack_fds);
8029 if (error == NULL)
8030 error = pack_err;
8032 free(cwd);
8033 return error;
8036 __dead static void
8037 usage_revert(void)
8039 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
8040 "path ...\n", getprogname());
8041 exit(1);
8044 static const struct got_error *
8045 revert_progress(void *arg, unsigned char status, const char *path)
8047 if (status == GOT_STATUS_UNVERSIONED)
8048 return NULL;
8050 while (path[0] == '/')
8051 path++;
8052 printf("%c %s\n", status, path);
8053 return NULL;
8056 struct choose_patch_arg {
8057 FILE *patch_script_file;
8058 const char *action;
8061 static const struct got_error *
8062 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8063 int nchanges, const char *action)
8065 const struct got_error *err;
8066 char *line = NULL;
8067 size_t linesize = 0;
8068 ssize_t linelen;
8070 switch (status) {
8071 case GOT_STATUS_ADD:
8072 printf("A %s\n%s this addition? [y/n] ", path, action);
8073 break;
8074 case GOT_STATUS_DELETE:
8075 printf("D %s\n%s this deletion? [y/n] ", path, action);
8076 break;
8077 case GOT_STATUS_MODIFY:
8078 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8079 return got_error_from_errno("fseek");
8080 printf(GOT_COMMIT_SEP_STR);
8081 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8082 printf("%s", line);
8083 if (linelen == -1 && ferror(patch_file)) {
8084 err = got_error_from_errno("getline");
8085 free(line);
8086 return err;
8088 free(line);
8089 printf(GOT_COMMIT_SEP_STR);
8090 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8091 path, n, nchanges, action);
8092 break;
8093 default:
8094 return got_error_path(path, GOT_ERR_FILE_STATUS);
8097 return NULL;
8100 static const struct got_error *
8101 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8102 FILE *patch_file, int n, int nchanges)
8104 const struct got_error *err = NULL;
8105 char *line = NULL;
8106 size_t linesize = 0;
8107 ssize_t linelen;
8108 int resp = ' ';
8109 struct choose_patch_arg *a = arg;
8111 *choice = GOT_PATCH_CHOICE_NONE;
8113 if (a->patch_script_file) {
8114 char *nl;
8115 err = show_change(status, path, patch_file, n, nchanges,
8116 a->action);
8117 if (err)
8118 return err;
8119 linelen = getline(&line, &linesize, a->patch_script_file);
8120 if (linelen == -1) {
8121 if (ferror(a->patch_script_file))
8122 return got_error_from_errno("getline");
8123 return NULL;
8125 nl = strchr(line, '\n');
8126 if (nl)
8127 *nl = '\0';
8128 if (strcmp(line, "y") == 0) {
8129 *choice = GOT_PATCH_CHOICE_YES;
8130 printf("y\n");
8131 } else if (strcmp(line, "n") == 0) {
8132 *choice = GOT_PATCH_CHOICE_NO;
8133 printf("n\n");
8134 } else if (strcmp(line, "q") == 0 &&
8135 status == GOT_STATUS_MODIFY) {
8136 *choice = GOT_PATCH_CHOICE_QUIT;
8137 printf("q\n");
8138 } else
8139 printf("invalid response '%s'\n", line);
8140 free(line);
8141 return NULL;
8144 while (resp != 'y' && resp != 'n' && resp != 'q') {
8145 err = show_change(status, path, patch_file, n, nchanges,
8146 a->action);
8147 if (err)
8148 return err;
8149 resp = getchar();
8150 if (resp == '\n')
8151 resp = getchar();
8152 if (status == GOT_STATUS_MODIFY) {
8153 if (resp != 'y' && resp != 'n' && resp != 'q') {
8154 printf("invalid response '%c'\n", resp);
8155 resp = ' ';
8157 } else if (resp != 'y' && resp != 'n') {
8158 printf("invalid response '%c'\n", resp);
8159 resp = ' ';
8163 if (resp == 'y')
8164 *choice = GOT_PATCH_CHOICE_YES;
8165 else if (resp == 'n')
8166 *choice = GOT_PATCH_CHOICE_NO;
8167 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8168 *choice = GOT_PATCH_CHOICE_QUIT;
8170 return NULL;
8173 static const struct got_error *
8174 cmd_revert(int argc, char *argv[])
8176 const struct got_error *error = NULL;
8177 struct got_worktree *worktree = NULL;
8178 struct got_repository *repo = NULL;
8179 char *cwd = NULL, *path = NULL;
8180 struct got_pathlist_head paths;
8181 struct got_pathlist_entry *pe;
8182 int ch, can_recurse = 0, pflag = 0;
8183 FILE *patch_script_file = NULL;
8184 const char *patch_script_path = NULL;
8185 struct choose_patch_arg cpa;
8186 int *pack_fds = NULL;
8188 TAILQ_INIT(&paths);
8190 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8191 switch (ch) {
8192 case 'p':
8193 pflag = 1;
8194 break;
8195 case 'F':
8196 patch_script_path = optarg;
8197 break;
8198 case 'R':
8199 can_recurse = 1;
8200 break;
8201 default:
8202 usage_revert();
8203 /* NOTREACHED */
8207 argc -= optind;
8208 argv += optind;
8210 #ifndef PROFILE
8211 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8212 "unveil", NULL) == -1)
8213 err(1, "pledge");
8214 #endif
8215 if (argc < 1)
8216 usage_revert();
8217 if (patch_script_path && !pflag)
8218 errx(1, "-F option can only be used together with -p option");
8220 cwd = getcwd(NULL, 0);
8221 if (cwd == NULL) {
8222 error = got_error_from_errno("getcwd");
8223 goto done;
8226 error = got_repo_pack_fds_open(&pack_fds);
8227 if (error != NULL)
8228 goto done;
8230 error = got_worktree_open(&worktree, cwd);
8231 if (error) {
8232 if (error->code == GOT_ERR_NOT_WORKTREE)
8233 error = wrap_not_worktree_error(error, "revert", cwd);
8234 goto done;
8237 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8238 NULL, pack_fds);
8239 if (error != NULL)
8240 goto done;
8242 if (patch_script_path) {
8243 patch_script_file = fopen(patch_script_path, "re");
8244 if (patch_script_file == NULL) {
8245 error = got_error_from_errno2("fopen",
8246 patch_script_path);
8247 goto done;
8250 error = apply_unveil(got_repo_get_path(repo), 1,
8251 got_worktree_get_root_path(worktree));
8252 if (error)
8253 goto done;
8255 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8256 if (error)
8257 goto done;
8259 if (!can_recurse) {
8260 char *ondisk_path;
8261 struct stat sb;
8262 TAILQ_FOREACH(pe, &paths, entry) {
8263 if (asprintf(&ondisk_path, "%s/%s",
8264 got_worktree_get_root_path(worktree),
8265 pe->path) == -1) {
8266 error = got_error_from_errno("asprintf");
8267 goto done;
8269 if (lstat(ondisk_path, &sb) == -1) {
8270 if (errno == ENOENT) {
8271 free(ondisk_path);
8272 continue;
8274 error = got_error_from_errno2("lstat",
8275 ondisk_path);
8276 free(ondisk_path);
8277 goto done;
8279 free(ondisk_path);
8280 if (S_ISDIR(sb.st_mode)) {
8281 error = got_error_msg(GOT_ERR_BAD_PATH,
8282 "reverting directories requires -R option");
8283 goto done;
8288 cpa.patch_script_file = patch_script_file;
8289 cpa.action = "revert";
8290 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8291 pflag ? choose_patch : NULL, &cpa, repo);
8292 done:
8293 if (patch_script_file && fclose(patch_script_file) == EOF &&
8294 error == NULL)
8295 error = got_error_from_errno2("fclose", patch_script_path);
8296 if (repo) {
8297 const struct got_error *close_err = got_repo_close(repo);
8298 if (error == NULL)
8299 error = close_err;
8301 if (worktree)
8302 got_worktree_close(worktree);
8303 if (pack_fds) {
8304 const struct got_error *pack_err =
8305 got_repo_pack_fds_close(pack_fds);
8306 if (error == NULL)
8307 error = pack_err;
8309 free(path);
8310 free(cwd);
8311 return error;
8314 __dead static void
8315 usage_commit(void)
8317 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8318 "[path ...]\n", getprogname());
8319 exit(1);
8322 struct collect_commit_logmsg_arg {
8323 const char *cmdline_log;
8324 const char *prepared_log;
8325 int non_interactive;
8326 const char *editor;
8327 const char *worktree_path;
8328 const char *branch_name;
8329 const char *repo_path;
8330 char *logmsg_path;
8334 static const struct got_error *
8335 read_prepared_logmsg(char **logmsg, const char *path)
8337 const struct got_error *err = NULL;
8338 FILE *f = NULL;
8339 struct stat sb;
8340 size_t r;
8342 *logmsg = NULL;
8343 memset(&sb, 0, sizeof(sb));
8345 f = fopen(path, "re");
8346 if (f == NULL)
8347 return got_error_from_errno2("fopen", path);
8349 if (fstat(fileno(f), &sb) == -1) {
8350 err = got_error_from_errno2("fstat", path);
8351 goto done;
8353 if (sb.st_size == 0) {
8354 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8355 goto done;
8358 *logmsg = malloc(sb.st_size + 1);
8359 if (*logmsg == NULL) {
8360 err = got_error_from_errno("malloc");
8361 goto done;
8364 r = fread(*logmsg, 1, sb.st_size, f);
8365 if (r != sb.st_size) {
8366 if (ferror(f))
8367 err = got_error_from_errno2("fread", path);
8368 else
8369 err = got_error(GOT_ERR_IO);
8370 goto done;
8372 (*logmsg)[sb.st_size] = '\0';
8373 done:
8374 if (fclose(f) == EOF && err == NULL)
8375 err = got_error_from_errno2("fclose", path);
8376 if (err) {
8377 free(*logmsg);
8378 *logmsg = NULL;
8380 return err;
8384 static const struct got_error *
8385 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8386 void *arg)
8388 char *initial_content = NULL;
8389 struct got_pathlist_entry *pe;
8390 const struct got_error *err = NULL;
8391 char *template = NULL;
8392 struct collect_commit_logmsg_arg *a = arg;
8393 int initial_content_len;
8394 int fd = -1;
8395 size_t len;
8397 /* if a message was specified on the command line, just use it */
8398 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8399 len = strlen(a->cmdline_log) + 1;
8400 *logmsg = malloc(len + 1);
8401 if (*logmsg == NULL)
8402 return got_error_from_errno("malloc");
8403 strlcpy(*logmsg, a->cmdline_log, len);
8404 return NULL;
8405 } else if (a->prepared_log != NULL && a->non_interactive)
8406 return read_prepared_logmsg(logmsg, a->prepared_log);
8408 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8409 return got_error_from_errno("asprintf");
8411 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8412 if (err)
8413 goto done;
8415 if (a->prepared_log) {
8416 char *msg;
8417 err = read_prepared_logmsg(&msg, a->prepared_log);
8418 if (err)
8419 goto done;
8420 if (write(fd, msg, strlen(msg)) == -1) {
8421 err = got_error_from_errno2("write", a->logmsg_path);
8422 free(msg);
8423 goto done;
8425 free(msg);
8428 initial_content_len = asprintf(&initial_content,
8429 "\n# changes to be committed on branch %s:\n",
8430 a->branch_name);
8431 if (initial_content_len == -1) {
8432 err = got_error_from_errno("asprintf");
8433 goto done;
8436 if (write(fd, initial_content, initial_content_len) == -1) {
8437 err = got_error_from_errno2("write", a->logmsg_path);
8438 goto done;
8441 TAILQ_FOREACH(pe, commitable_paths, entry) {
8442 struct got_commitable *ct = pe->data;
8443 dprintf(fd, "# %c %s\n",
8444 got_commitable_get_status(ct),
8445 got_commitable_get_path(ct));
8448 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8449 initial_content_len, a->prepared_log ? 0 : 1);
8450 done:
8451 free(initial_content);
8452 free(template);
8454 if (fd != -1 && close(fd) == -1 && err == NULL)
8455 err = got_error_from_errno2("close", a->logmsg_path);
8457 /* Editor is done; we can now apply unveil(2) */
8458 if (err == NULL)
8459 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8460 if (err) {
8461 free(*logmsg);
8462 *logmsg = NULL;
8464 return err;
8467 static const struct got_error *
8468 cmd_commit(int argc, char *argv[])
8470 const struct got_error *error = NULL;
8471 struct got_worktree *worktree = NULL;
8472 struct got_repository *repo = NULL;
8473 char *cwd = NULL, *id_str = NULL;
8474 struct got_object_id *id = NULL;
8475 const char *logmsg = NULL;
8476 char *prepared_logmsg = NULL;
8477 struct collect_commit_logmsg_arg cl_arg;
8478 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8479 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8480 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8481 struct got_pathlist_head paths;
8482 int *pack_fds = NULL;
8484 TAILQ_INIT(&paths);
8485 cl_arg.logmsg_path = NULL;
8487 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8488 switch (ch) {
8489 case 'F':
8490 if (logmsg != NULL)
8491 option_conflict('F', 'm');
8492 prepared_logmsg = realpath(optarg, NULL);
8493 if (prepared_logmsg == NULL)
8494 return got_error_from_errno2("realpath",
8495 optarg);
8496 break;
8497 case 'm':
8498 if (prepared_logmsg)
8499 option_conflict('m', 'F');
8500 logmsg = optarg;
8501 break;
8502 case 'N':
8503 non_interactive = 1;
8504 break;
8505 case 'S':
8506 allow_bad_symlinks = 1;
8507 break;
8508 default:
8509 usage_commit();
8510 /* NOTREACHED */
8514 argc -= optind;
8515 argv += optind;
8517 #ifndef PROFILE
8518 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8519 "unveil", NULL) == -1)
8520 err(1, "pledge");
8521 #endif
8522 cwd = getcwd(NULL, 0);
8523 if (cwd == NULL) {
8524 error = got_error_from_errno("getcwd");
8525 goto done;
8528 error = got_repo_pack_fds_open(&pack_fds);
8529 if (error != NULL)
8530 goto done;
8532 error = got_worktree_open(&worktree, cwd);
8533 if (error) {
8534 if (error->code == GOT_ERR_NOT_WORKTREE)
8535 error = wrap_not_worktree_error(error, "commit", cwd);
8536 goto done;
8539 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8540 if (error)
8541 goto done;
8542 if (rebase_in_progress) {
8543 error = got_error(GOT_ERR_REBASING);
8544 goto done;
8547 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8548 worktree);
8549 if (error)
8550 goto done;
8552 error = get_gitconfig_path(&gitconfig_path);
8553 if (error)
8554 goto done;
8555 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8556 gitconfig_path, pack_fds);
8557 if (error != NULL)
8558 goto done;
8560 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8561 if (error)
8562 goto done;
8563 if (merge_in_progress) {
8564 error = got_error(GOT_ERR_MERGE_BUSY);
8565 goto done;
8568 error = get_author(&author, repo, worktree);
8569 if (error)
8570 return error;
8573 * unveil(2) traverses exec(2); if an editor is used we have
8574 * to apply unveil after the log message has been written.
8576 if (logmsg == NULL || strlen(logmsg) == 0)
8577 error = get_editor(&editor);
8578 else
8579 error = apply_unveil(got_repo_get_path(repo), 0,
8580 got_worktree_get_root_path(worktree));
8581 if (error)
8582 goto done;
8584 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8585 if (error)
8586 goto done;
8588 cl_arg.editor = editor;
8589 cl_arg.cmdline_log = logmsg;
8590 cl_arg.prepared_log = prepared_logmsg;
8591 cl_arg.non_interactive = non_interactive;
8592 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8593 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8594 if (!histedit_in_progress) {
8595 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8596 error = got_error(GOT_ERR_COMMIT_BRANCH);
8597 goto done;
8599 cl_arg.branch_name += 11;
8601 cl_arg.repo_path = got_repo_get_path(repo);
8602 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8603 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8604 print_status, NULL, repo);
8605 if (error) {
8606 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8607 cl_arg.logmsg_path != NULL)
8608 preserve_logmsg = 1;
8609 goto done;
8612 error = got_object_id_str(&id_str, id);
8613 if (error)
8614 goto done;
8615 printf("Created commit %s\n", id_str);
8616 done:
8617 if (preserve_logmsg) {
8618 fprintf(stderr, "%s: log message preserved in %s\n",
8619 getprogname(), cl_arg.logmsg_path);
8620 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8621 error == NULL)
8622 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8623 free(cl_arg.logmsg_path);
8624 if (repo) {
8625 const struct got_error *close_err = got_repo_close(repo);
8626 if (error == NULL)
8627 error = close_err;
8629 if (worktree)
8630 got_worktree_close(worktree);
8631 if (pack_fds) {
8632 const struct got_error *pack_err =
8633 got_repo_pack_fds_close(pack_fds);
8634 if (error == NULL)
8635 error = pack_err;
8637 free(cwd);
8638 free(id_str);
8639 free(gitconfig_path);
8640 free(editor);
8641 free(author);
8642 free(prepared_logmsg);
8643 return error;
8646 __dead static void
8647 usage_send(void)
8649 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8650 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8651 "[remote-repository]\n", getprogname());
8652 exit(1);
8655 static void
8656 print_load_info(int print_colored, int print_found, int print_trees,
8657 int ncolored, int nfound, int ntrees)
8659 if (print_colored) {
8660 printf("%d commit%s colored", ncolored,
8661 ncolored == 1 ? "" : "s");
8663 if (print_found) {
8664 printf("%s%d object%s found",
8665 ncolored > 0 ? "; " : "",
8666 nfound, nfound == 1 ? "" : "s");
8668 if (print_trees) {
8669 printf("; %d tree%s scanned", ntrees,
8670 ntrees == 1 ? "" : "s");
8674 struct got_send_progress_arg {
8675 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8676 int verbosity;
8677 int last_ncolored;
8678 int last_nfound;
8679 int last_ntrees;
8680 int loading_done;
8681 int last_ncommits;
8682 int last_nobj_total;
8683 int last_p_deltify;
8684 int last_p_written;
8685 int last_p_sent;
8686 int printed_something;
8687 int sent_something;
8688 struct got_pathlist_head *delete_branches;
8691 static const struct got_error *
8692 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8693 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8694 int nobj_written, off_t bytes_sent, const char *refname, int success)
8696 struct got_send_progress_arg *a = arg;
8697 char scaled_packsize[FMT_SCALED_STRSIZE];
8698 char scaled_sent[FMT_SCALED_STRSIZE];
8699 int p_deltify = 0, p_written = 0, p_sent = 0;
8700 int print_colored = 0, print_found = 0, print_trees = 0;
8701 int print_searching = 0, print_total = 0;
8702 int print_deltify = 0, print_written = 0, print_sent = 0;
8704 if (a->verbosity < 0)
8705 return NULL;
8707 if (refname) {
8708 const char *status = success ? "accepted" : "rejected";
8710 if (success) {
8711 struct got_pathlist_entry *pe;
8712 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8713 const char *branchname = pe->path;
8714 if (got_path_cmp(branchname, refname,
8715 strlen(branchname), strlen(refname)) == 0) {
8716 status = "deleted";
8717 a->sent_something = 1;
8718 break;
8723 if (a->printed_something)
8724 putchar('\n');
8725 printf("Server has %s %s", status, refname);
8726 a->printed_something = 1;
8727 return NULL;
8730 if (a->last_ncolored != ncolored) {
8731 print_colored = 1;
8732 a->last_ncolored = ncolored;
8735 if (a->last_nfound != nfound) {
8736 print_colored = 1;
8737 print_found = 1;
8738 a->last_nfound = nfound;
8741 if (a->last_ntrees != ntrees) {
8742 print_colored = 1;
8743 print_found = 1;
8744 print_trees = 1;
8745 a->last_ntrees = ntrees;
8748 if ((print_colored || print_found || print_trees) &&
8749 !a->loading_done) {
8750 printf("\r");
8751 print_load_info(print_colored, print_found, print_trees,
8752 ncolored, nfound, ntrees);
8753 a->printed_something = 1;
8754 fflush(stdout);
8755 return NULL;
8756 } else if (!a->loading_done) {
8757 printf("\r");
8758 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8759 printf("\n");
8760 a->loading_done = 1;
8763 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8764 return got_error_from_errno("fmt_scaled");
8765 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8766 return got_error_from_errno("fmt_scaled");
8768 if (a->last_ncommits != ncommits) {
8769 print_searching = 1;
8770 a->last_ncommits = ncommits;
8773 if (a->last_nobj_total != nobj_total) {
8774 print_searching = 1;
8775 print_total = 1;
8776 a->last_nobj_total = nobj_total;
8779 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8780 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8781 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8782 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8783 return got_error(GOT_ERR_NO_SPACE);
8786 if (nobj_deltify > 0 || nobj_written > 0) {
8787 if (nobj_deltify > 0) {
8788 p_deltify = (nobj_deltify * 100) / nobj_total;
8789 if (p_deltify != a->last_p_deltify) {
8790 a->last_p_deltify = p_deltify;
8791 print_searching = 1;
8792 print_total = 1;
8793 print_deltify = 1;
8796 if (nobj_written > 0) {
8797 p_written = (nobj_written * 100) / nobj_total;
8798 if (p_written != a->last_p_written) {
8799 a->last_p_written = p_written;
8800 print_searching = 1;
8801 print_total = 1;
8802 print_deltify = 1;
8803 print_written = 1;
8808 if (bytes_sent > 0) {
8809 p_sent = (bytes_sent * 100) / packfile_size;
8810 if (p_sent != a->last_p_sent) {
8811 a->last_p_sent = p_sent;
8812 print_searching = 1;
8813 print_total = 1;
8814 print_deltify = 1;
8815 print_written = 1;
8816 print_sent = 1;
8818 a->sent_something = 1;
8821 if (print_searching || print_total || print_deltify || print_written ||
8822 print_sent)
8823 printf("\r");
8824 if (print_searching)
8825 printf("packing %d reference%s", ncommits,
8826 ncommits == 1 ? "" : "s");
8827 if (print_total)
8828 printf("; %d object%s", nobj_total,
8829 nobj_total == 1 ? "" : "s");
8830 if (print_deltify)
8831 printf("; deltify: %d%%", p_deltify);
8832 if (print_sent)
8833 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8834 scaled_packsize, p_sent);
8835 else if (print_written)
8836 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8837 scaled_packsize, p_written);
8838 if (print_searching || print_total || print_deltify ||
8839 print_written || print_sent) {
8840 a->printed_something = 1;
8841 fflush(stdout);
8843 return NULL;
8846 static const struct got_error *
8847 cmd_send(int argc, char *argv[])
8849 const struct got_error *error = NULL;
8850 char *cwd = NULL, *repo_path = NULL;
8851 const char *remote_name;
8852 char *proto = NULL, *host = NULL, *port = NULL;
8853 char *repo_name = NULL, *server_path = NULL;
8854 const struct got_remote_repo *remotes, *remote = NULL;
8855 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8856 struct got_repository *repo = NULL;
8857 struct got_worktree *worktree = NULL;
8858 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8859 struct got_pathlist_head branches;
8860 struct got_pathlist_head tags;
8861 struct got_reflist_head all_branches;
8862 struct got_reflist_head all_tags;
8863 struct got_pathlist_head delete_args;
8864 struct got_pathlist_head delete_branches;
8865 struct got_reflist_entry *re;
8866 struct got_pathlist_entry *pe;
8867 int i, ch, sendfd = -1, sendstatus;
8868 pid_t sendpid = -1;
8869 struct got_send_progress_arg spa;
8870 int verbosity = 0, overwrite_refs = 0;
8871 int send_all_branches = 0, send_all_tags = 0;
8872 struct got_reference *ref = NULL;
8873 int *pack_fds = NULL;
8875 TAILQ_INIT(&branches);
8876 TAILQ_INIT(&tags);
8877 TAILQ_INIT(&all_branches);
8878 TAILQ_INIT(&all_tags);
8879 TAILQ_INIT(&delete_args);
8880 TAILQ_INIT(&delete_branches);
8882 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8883 switch (ch) {
8884 case 'a':
8885 send_all_branches = 1;
8886 break;
8887 case 'b':
8888 error = got_pathlist_append(&branches, optarg, NULL);
8889 if (error)
8890 return error;
8891 nbranches++;
8892 break;
8893 case 'd':
8894 error = got_pathlist_append(&delete_args, optarg, NULL);
8895 if (error)
8896 return error;
8897 break;
8898 case 'f':
8899 overwrite_refs = 1;
8900 break;
8901 case 'r':
8902 repo_path = realpath(optarg, NULL);
8903 if (repo_path == NULL)
8904 return got_error_from_errno2("realpath",
8905 optarg);
8906 got_path_strip_trailing_slashes(repo_path);
8907 break;
8908 case 't':
8909 error = got_pathlist_append(&tags, optarg, NULL);
8910 if (error)
8911 return error;
8912 ntags++;
8913 break;
8914 case 'T':
8915 send_all_tags = 1;
8916 break;
8917 case 'v':
8918 if (verbosity < 0)
8919 verbosity = 0;
8920 else if (verbosity < 3)
8921 verbosity++;
8922 break;
8923 case 'q':
8924 verbosity = -1;
8925 break;
8926 default:
8927 usage_send();
8928 /* NOTREACHED */
8931 argc -= optind;
8932 argv += optind;
8934 if (send_all_branches && !TAILQ_EMPTY(&branches))
8935 option_conflict('a', 'b');
8936 if (send_all_tags && !TAILQ_EMPTY(&tags))
8937 option_conflict('T', 't');
8940 if (argc == 0)
8941 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8942 else if (argc == 1)
8943 remote_name = argv[0];
8944 else
8945 usage_send();
8947 cwd = getcwd(NULL, 0);
8948 if (cwd == NULL) {
8949 error = got_error_from_errno("getcwd");
8950 goto done;
8953 error = got_repo_pack_fds_open(&pack_fds);
8954 if (error != NULL)
8955 goto done;
8957 if (repo_path == NULL) {
8958 error = got_worktree_open(&worktree, cwd);
8959 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8960 goto done;
8961 else
8962 error = NULL;
8963 if (worktree) {
8964 repo_path =
8965 strdup(got_worktree_get_repo_path(worktree));
8966 if (repo_path == NULL)
8967 error = got_error_from_errno("strdup");
8968 if (error)
8969 goto done;
8970 } else {
8971 repo_path = strdup(cwd);
8972 if (repo_path == NULL) {
8973 error = got_error_from_errno("strdup");
8974 goto done;
8979 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8980 if (error)
8981 goto done;
8983 if (worktree) {
8984 worktree_conf = got_worktree_get_gotconfig(worktree);
8985 if (worktree_conf) {
8986 got_gotconfig_get_remotes(&nremotes, &remotes,
8987 worktree_conf);
8988 for (i = 0; i < nremotes; i++) {
8989 if (strcmp(remotes[i].name, remote_name) == 0) {
8990 remote = &remotes[i];
8991 break;
8996 if (remote == NULL) {
8997 repo_conf = got_repo_get_gotconfig(repo);
8998 if (repo_conf) {
8999 got_gotconfig_get_remotes(&nremotes, &remotes,
9000 repo_conf);
9001 for (i = 0; i < nremotes; i++) {
9002 if (strcmp(remotes[i].name, remote_name) == 0) {
9003 remote = &remotes[i];
9004 break;
9009 if (remote == NULL) {
9010 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9011 for (i = 0; i < nremotes; i++) {
9012 if (strcmp(remotes[i].name, remote_name) == 0) {
9013 remote = &remotes[i];
9014 break;
9018 if (remote == NULL) {
9019 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9020 goto done;
9023 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9024 &repo_name, remote->send_url);
9025 if (error)
9026 goto done;
9028 if (strcmp(proto, "git") == 0) {
9029 #ifndef PROFILE
9030 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9031 "sendfd dns inet unveil", NULL) == -1)
9032 err(1, "pledge");
9033 #endif
9034 } else if (strcmp(proto, "git+ssh") == 0 ||
9035 strcmp(proto, "ssh") == 0) {
9036 #ifndef PROFILE
9037 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9038 "sendfd unveil", NULL) == -1)
9039 err(1, "pledge");
9040 #endif
9041 } else if (strcmp(proto, "http") == 0 ||
9042 strcmp(proto, "git+http") == 0) {
9043 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9044 goto done;
9045 } else {
9046 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9047 goto done;
9050 error = got_dial_apply_unveil(proto);
9051 if (error)
9052 goto done;
9054 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9055 if (error)
9056 goto done;
9058 if (send_all_branches) {
9059 error = got_ref_list(&all_branches, repo, "refs/heads",
9060 got_ref_cmp_by_name, NULL);
9061 if (error)
9062 goto done;
9063 TAILQ_FOREACH(re, &all_branches, entry) {
9064 const char *branchname = got_ref_get_name(re->ref);
9065 error = got_pathlist_append(&branches,
9066 branchname, NULL);
9067 if (error)
9068 goto done;
9069 nbranches++;
9071 } else if (nbranches == 0) {
9072 for (i = 0; i < remote->nsend_branches; i++) {
9073 got_pathlist_append(&branches,
9074 remote->send_branches[i], NULL);
9078 if (send_all_tags) {
9079 error = got_ref_list(&all_tags, repo, "refs/tags",
9080 got_ref_cmp_by_name, NULL);
9081 if (error)
9082 goto done;
9083 TAILQ_FOREACH(re, &all_tags, entry) {
9084 const char *tagname = got_ref_get_name(re->ref);
9085 error = got_pathlist_append(&tags,
9086 tagname, NULL);
9087 if (error)
9088 goto done;
9089 ntags++;
9094 * To prevent accidents only branches in refs/heads/ can be deleted
9095 * with 'got send -d'.
9096 * Deleting anything else requires local repository access or Git.
9098 TAILQ_FOREACH(pe, &delete_args, entry) {
9099 const char *branchname = pe->path;
9100 char *s;
9101 struct got_pathlist_entry *new;
9102 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9103 s = strdup(branchname);
9104 if (s == NULL) {
9105 error = got_error_from_errno("strdup");
9106 goto done;
9108 } else {
9109 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9110 error = got_error_from_errno("asprintf");
9111 goto done;
9114 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9115 if (error || new == NULL /* duplicate */)
9116 free(s);
9117 if (error)
9118 goto done;
9119 ndelete_branches++;
9122 if (nbranches == 0 && ndelete_branches == 0) {
9123 struct got_reference *head_ref;
9124 if (worktree)
9125 error = got_ref_open(&head_ref, repo,
9126 got_worktree_get_head_ref_name(worktree), 0);
9127 else
9128 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9129 if (error)
9130 goto done;
9131 if (got_ref_is_symbolic(head_ref)) {
9132 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9133 got_ref_close(head_ref);
9134 if (error)
9135 goto done;
9136 } else
9137 ref = head_ref;
9138 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9139 NULL);
9140 if (error)
9141 goto done;
9142 nbranches++;
9145 if (verbosity >= 0)
9146 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9147 port ? ":" : "", port ? port : "");
9149 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9150 server_path, verbosity);
9151 if (error)
9152 goto done;
9154 memset(&spa, 0, sizeof(spa));
9155 spa.last_scaled_packsize[0] = '\0';
9156 spa.last_p_deltify = -1;
9157 spa.last_p_written = -1;
9158 spa.verbosity = verbosity;
9159 spa.delete_branches = &delete_branches;
9160 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9161 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9162 check_cancelled, NULL);
9163 if (spa.printed_something)
9164 putchar('\n');
9165 if (error)
9166 goto done;
9167 if (!spa.sent_something && verbosity >= 0)
9168 printf("Already up-to-date\n");
9169 done:
9170 if (sendpid > 0) {
9171 if (kill(sendpid, SIGTERM) == -1)
9172 error = got_error_from_errno("kill");
9173 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9174 error = got_error_from_errno("waitpid");
9176 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9177 error = got_error_from_errno("close");
9178 if (repo) {
9179 const struct got_error *close_err = got_repo_close(repo);
9180 if (error == NULL)
9181 error = close_err;
9183 if (worktree)
9184 got_worktree_close(worktree);
9185 if (pack_fds) {
9186 const struct got_error *pack_err =
9187 got_repo_pack_fds_close(pack_fds);
9188 if (error == NULL)
9189 error = pack_err;
9191 if (ref)
9192 got_ref_close(ref);
9193 got_pathlist_free(&branches);
9194 got_pathlist_free(&tags);
9195 got_ref_list_free(&all_branches);
9196 got_ref_list_free(&all_tags);
9197 got_pathlist_free(&delete_args);
9198 TAILQ_FOREACH(pe, &delete_branches, entry)
9199 free((char *)pe->path);
9200 got_pathlist_free(&delete_branches);
9201 free(cwd);
9202 free(repo_path);
9203 free(proto);
9204 free(host);
9205 free(port);
9206 free(server_path);
9207 free(repo_name);
9208 return error;
9211 __dead static void
9212 usage_cherrypick(void)
9214 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9215 exit(1);
9218 static const struct got_error *
9219 cmd_cherrypick(int argc, char *argv[])
9221 const struct got_error *error = NULL;
9222 struct got_worktree *worktree = NULL;
9223 struct got_repository *repo = NULL;
9224 char *cwd = NULL, *commit_id_str = NULL;
9225 struct got_object_id *commit_id = NULL;
9226 struct got_commit_object *commit = NULL;
9227 struct got_object_qid *pid;
9228 int ch;
9229 struct got_update_progress_arg upa;
9230 int *pack_fds = NULL;
9232 while ((ch = getopt(argc, argv, "")) != -1) {
9233 switch (ch) {
9234 default:
9235 usage_cherrypick();
9236 /* NOTREACHED */
9240 argc -= optind;
9241 argv += optind;
9243 #ifndef PROFILE
9244 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9245 "unveil", NULL) == -1)
9246 err(1, "pledge");
9247 #endif
9248 if (argc != 1)
9249 usage_cherrypick();
9251 cwd = getcwd(NULL, 0);
9252 if (cwd == NULL) {
9253 error = got_error_from_errno("getcwd");
9254 goto done;
9257 error = got_repo_pack_fds_open(&pack_fds);
9258 if (error != NULL)
9259 goto done;
9261 error = got_worktree_open(&worktree, cwd);
9262 if (error) {
9263 if (error->code == GOT_ERR_NOT_WORKTREE)
9264 error = wrap_not_worktree_error(error, "cherrypick",
9265 cwd);
9266 goto done;
9269 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9270 NULL, pack_fds);
9271 if (error != NULL)
9272 goto done;
9274 error = apply_unveil(got_repo_get_path(repo), 0,
9275 got_worktree_get_root_path(worktree));
9276 if (error)
9277 goto done;
9279 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9280 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9281 if (error)
9282 goto done;
9283 error = got_object_id_str(&commit_id_str, commit_id);
9284 if (error)
9285 goto done;
9287 error = got_object_open_as_commit(&commit, repo, commit_id);
9288 if (error)
9289 goto done;
9290 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9291 memset(&upa, 0, sizeof(upa));
9292 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9293 commit_id, repo, update_progress, &upa, check_cancelled,
9294 NULL);
9295 if (error != NULL)
9296 goto done;
9298 if (upa.did_something)
9299 printf("Merged commit %s\n", commit_id_str);
9300 print_merge_progress_stats(&upa);
9301 done:
9302 if (commit)
9303 got_object_commit_close(commit);
9304 free(commit_id_str);
9305 if (worktree)
9306 got_worktree_close(worktree);
9307 if (repo) {
9308 const struct got_error *close_err = got_repo_close(repo);
9309 if (error == NULL)
9310 error = close_err;
9312 if (pack_fds) {
9313 const struct got_error *pack_err =
9314 got_repo_pack_fds_close(pack_fds);
9315 if (error == NULL)
9316 error = pack_err;
9319 return error;
9322 __dead static void
9323 usage_backout(void)
9325 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9326 exit(1);
9329 static const struct got_error *
9330 cmd_backout(int argc, char *argv[])
9332 const struct got_error *error = NULL;
9333 struct got_worktree *worktree = NULL;
9334 struct got_repository *repo = NULL;
9335 char *cwd = NULL, *commit_id_str = NULL;
9336 struct got_object_id *commit_id = NULL;
9337 struct got_commit_object *commit = NULL;
9338 struct got_object_qid *pid;
9339 int ch;
9340 struct got_update_progress_arg upa;
9341 int *pack_fds = NULL;
9343 while ((ch = getopt(argc, argv, "")) != -1) {
9344 switch (ch) {
9345 default:
9346 usage_backout();
9347 /* NOTREACHED */
9351 argc -= optind;
9352 argv += optind;
9354 #ifndef PROFILE
9355 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9356 "unveil", NULL) == -1)
9357 err(1, "pledge");
9358 #endif
9359 if (argc != 1)
9360 usage_backout();
9362 cwd = getcwd(NULL, 0);
9363 if (cwd == NULL) {
9364 error = got_error_from_errno("getcwd");
9365 goto done;
9368 error = got_repo_pack_fds_open(&pack_fds);
9369 if (error != NULL)
9370 goto done;
9372 error = got_worktree_open(&worktree, cwd);
9373 if (error) {
9374 if (error->code == GOT_ERR_NOT_WORKTREE)
9375 error = wrap_not_worktree_error(error, "backout", cwd);
9376 goto done;
9379 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9380 NULL, pack_fds);
9381 if (error != NULL)
9382 goto done;
9384 error = apply_unveil(got_repo_get_path(repo), 0,
9385 got_worktree_get_root_path(worktree));
9386 if (error)
9387 goto done;
9389 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9390 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9391 if (error)
9392 goto done;
9393 error = got_object_id_str(&commit_id_str, commit_id);
9394 if (error)
9395 goto done;
9397 error = got_object_open_as_commit(&commit, repo, commit_id);
9398 if (error)
9399 goto done;
9400 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9401 if (pid == NULL) {
9402 error = got_error(GOT_ERR_ROOT_COMMIT);
9403 goto done;
9406 memset(&upa, 0, sizeof(upa));
9407 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9408 repo, update_progress, &upa, check_cancelled, NULL);
9409 if (error != NULL)
9410 goto done;
9412 if (upa.did_something)
9413 printf("Backed out commit %s\n", commit_id_str);
9414 print_merge_progress_stats(&upa);
9415 done:
9416 if (commit)
9417 got_object_commit_close(commit);
9418 free(commit_id_str);
9419 if (worktree)
9420 got_worktree_close(worktree);
9421 if (repo) {
9422 const struct got_error *close_err = got_repo_close(repo);
9423 if (error == NULL)
9424 error = close_err;
9426 if (pack_fds) {
9427 const struct got_error *pack_err =
9428 got_repo_pack_fds_close(pack_fds);
9429 if (error == NULL)
9430 error = pack_err;
9432 return error;
9435 __dead static void
9436 usage_rebase(void)
9438 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9439 getprogname());
9440 exit(1);
9443 static void
9444 trim_logmsg(char *logmsg, int limit)
9446 char *nl;
9447 size_t len;
9449 len = strlen(logmsg);
9450 if (len > limit)
9451 len = limit;
9452 logmsg[len] = '\0';
9453 nl = strchr(logmsg, '\n');
9454 if (nl)
9455 *nl = '\0';
9458 static const struct got_error *
9459 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9461 const struct got_error *err;
9462 char *logmsg0 = NULL;
9463 const char *s;
9465 err = got_object_commit_get_logmsg(&logmsg0, commit);
9466 if (err)
9467 return err;
9469 s = logmsg0;
9470 while (isspace((unsigned char)s[0]))
9471 s++;
9473 *logmsg = strdup(s);
9474 if (*logmsg == NULL) {
9475 err = got_error_from_errno("strdup");
9476 goto done;
9479 trim_logmsg(*logmsg, limit);
9480 done:
9481 free(logmsg0);
9482 return err;
9485 static const struct got_error *
9486 show_rebase_merge_conflict(struct got_object_id *id,
9487 struct got_repository *repo)
9489 const struct got_error *err;
9490 struct got_commit_object *commit = NULL;
9491 char *id_str = NULL, *logmsg = NULL;
9493 err = got_object_open_as_commit(&commit, repo, id);
9494 if (err)
9495 return err;
9497 err = got_object_id_str(&id_str, id);
9498 if (err)
9499 goto done;
9501 id_str[12] = '\0';
9503 err = get_short_logmsg(&logmsg, 42, commit);
9504 if (err)
9505 goto done;
9507 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9508 done:
9509 free(id_str);
9510 got_object_commit_close(commit);
9511 free(logmsg);
9512 return err;
9515 static const struct got_error *
9516 show_rebase_progress(struct got_commit_object *commit,
9517 struct got_object_id *old_id, struct got_object_id *new_id)
9519 const struct got_error *err;
9520 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9522 err = got_object_id_str(&old_id_str, old_id);
9523 if (err)
9524 goto done;
9526 if (new_id) {
9527 err = got_object_id_str(&new_id_str, new_id);
9528 if (err)
9529 goto done;
9532 old_id_str[12] = '\0';
9533 if (new_id_str)
9534 new_id_str[12] = '\0';
9536 err = get_short_logmsg(&logmsg, 42, commit);
9537 if (err)
9538 goto done;
9540 printf("%s -> %s: %s\n", old_id_str,
9541 new_id_str ? new_id_str : "no-op change", logmsg);
9542 done:
9543 free(old_id_str);
9544 free(new_id_str);
9545 free(logmsg);
9546 return err;
9549 static const struct got_error *
9550 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9551 struct got_reference *branch, struct got_reference *new_base_branch,
9552 struct got_reference *tmp_branch, struct got_repository *repo,
9553 int create_backup)
9555 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9556 return got_worktree_rebase_complete(worktree, fileindex,
9557 new_base_branch, tmp_branch, branch, repo, create_backup);
9560 static const struct got_error *
9561 rebase_commit(struct got_pathlist_head *merged_paths,
9562 struct got_worktree *worktree, struct got_fileindex *fileindex,
9563 struct got_reference *tmp_branch,
9564 struct got_object_id *commit_id, struct got_repository *repo)
9566 const struct got_error *error;
9567 struct got_commit_object *commit;
9568 struct got_object_id *new_commit_id;
9570 error = got_object_open_as_commit(&commit, repo, commit_id);
9571 if (error)
9572 return error;
9574 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9575 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9576 if (error) {
9577 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9578 goto done;
9579 error = show_rebase_progress(commit, commit_id, NULL);
9580 } else {
9581 error = show_rebase_progress(commit, commit_id, new_commit_id);
9582 free(new_commit_id);
9584 done:
9585 got_object_commit_close(commit);
9586 return error;
9589 struct check_path_prefix_arg {
9590 const char *path_prefix;
9591 size_t len;
9592 int errcode;
9595 static const struct got_error *
9596 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9597 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9598 struct got_object_id *id1, struct got_object_id *id2,
9599 const char *path1, const char *path2,
9600 mode_t mode1, mode_t mode2, struct got_repository *repo)
9602 struct check_path_prefix_arg *a = arg;
9604 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9605 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9606 return got_error(a->errcode);
9608 return NULL;
9611 static const struct got_error *
9612 check_path_prefix(struct got_object_id *parent_id,
9613 struct got_object_id *commit_id, const char *path_prefix,
9614 int errcode, struct got_repository *repo)
9616 const struct got_error *err;
9617 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9618 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9619 struct check_path_prefix_arg cpp_arg;
9621 if (got_path_is_root_dir(path_prefix))
9622 return NULL;
9624 err = got_object_open_as_commit(&commit, repo, commit_id);
9625 if (err)
9626 goto done;
9628 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9629 if (err)
9630 goto done;
9632 err = got_object_open_as_tree(&tree1, repo,
9633 got_object_commit_get_tree_id(parent_commit));
9634 if (err)
9635 goto done;
9637 err = got_object_open_as_tree(&tree2, repo,
9638 got_object_commit_get_tree_id(commit));
9639 if (err)
9640 goto done;
9642 cpp_arg.path_prefix = path_prefix;
9643 while (cpp_arg.path_prefix[0] == '/')
9644 cpp_arg.path_prefix++;
9645 cpp_arg.len = strlen(cpp_arg.path_prefix);
9646 cpp_arg.errcode = errcode;
9647 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9648 check_path_prefix_in_diff, &cpp_arg, 0);
9649 done:
9650 if (tree1)
9651 got_object_tree_close(tree1);
9652 if (tree2)
9653 got_object_tree_close(tree2);
9654 if (commit)
9655 got_object_commit_close(commit);
9656 if (parent_commit)
9657 got_object_commit_close(parent_commit);
9658 return err;
9661 static const struct got_error *
9662 collect_commits(struct got_object_id_queue *commits,
9663 struct got_object_id *initial_commit_id,
9664 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9665 const char *path_prefix, int path_prefix_errcode,
9666 struct got_repository *repo)
9668 const struct got_error *err = NULL;
9669 struct got_commit_graph *graph = NULL;
9670 struct got_object_id *parent_id = NULL;
9671 struct got_object_qid *qid;
9672 struct got_object_id *commit_id = initial_commit_id;
9674 err = got_commit_graph_open(&graph, "/", 1);
9675 if (err)
9676 return err;
9678 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9679 check_cancelled, NULL);
9680 if (err)
9681 goto done;
9682 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9683 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9684 check_cancelled, NULL);
9685 if (err) {
9686 if (err->code == GOT_ERR_ITER_COMPLETED) {
9687 err = got_error_msg(GOT_ERR_ANCESTRY,
9688 "ran out of commits to rebase before "
9689 "youngest common ancestor commit has "
9690 "been reached?!?");
9692 goto done;
9693 } else {
9694 err = check_path_prefix(parent_id, commit_id,
9695 path_prefix, path_prefix_errcode, repo);
9696 if (err)
9697 goto done;
9699 err = got_object_qid_alloc(&qid, commit_id);
9700 if (err)
9701 goto done;
9702 STAILQ_INSERT_HEAD(commits, qid, entry);
9703 commit_id = parent_id;
9706 done:
9707 got_commit_graph_close(graph);
9708 return err;
9711 static const struct got_error *
9712 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9714 const struct got_error *err = NULL;
9715 time_t committer_time;
9716 struct tm tm;
9717 char datebuf[11]; /* YYYY-MM-DD + NUL */
9718 char *author0 = NULL, *author, *smallerthan;
9719 char *logmsg0 = NULL, *logmsg, *newline;
9721 committer_time = got_object_commit_get_committer_time(commit);
9722 if (gmtime_r(&committer_time, &tm) == NULL)
9723 return got_error_from_errno("gmtime_r");
9724 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9725 return got_error(GOT_ERR_NO_SPACE);
9727 author0 = strdup(got_object_commit_get_author(commit));
9728 if (author0 == NULL)
9729 return got_error_from_errno("strdup");
9730 author = author0;
9731 smallerthan = strchr(author, '<');
9732 if (smallerthan && smallerthan[1] != '\0')
9733 author = smallerthan + 1;
9734 author[strcspn(author, "@>")] = '\0';
9736 err = got_object_commit_get_logmsg(&logmsg0, commit);
9737 if (err)
9738 goto done;
9739 logmsg = logmsg0;
9740 while (*logmsg == '\n')
9741 logmsg++;
9742 newline = strchr(logmsg, '\n');
9743 if (newline)
9744 *newline = '\0';
9746 if (asprintf(brief_str, "%s %s %s",
9747 datebuf, author, logmsg) == -1)
9748 err = got_error_from_errno("asprintf");
9749 done:
9750 free(author0);
9751 free(logmsg0);
9752 return err;
9755 static const struct got_error *
9756 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9757 struct got_repository *repo)
9759 const struct got_error *err;
9760 char *id_str;
9762 err = got_object_id_str(&id_str, id);
9763 if (err)
9764 return err;
9766 err = got_ref_delete(ref, repo);
9767 if (err)
9768 goto done;
9770 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9771 done:
9772 free(id_str);
9773 return err;
9776 static const struct got_error *
9777 print_backup_ref(const char *branch_name, const char *new_id_str,
9778 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9779 struct got_reflist_object_id_map *refs_idmap,
9780 struct got_repository *repo)
9782 const struct got_error *err = NULL;
9783 struct got_reflist_head *refs;
9784 char *refs_str = NULL;
9785 struct got_object_id *new_commit_id = NULL;
9786 struct got_commit_object *new_commit = NULL;
9787 char *new_commit_brief_str = NULL;
9788 struct got_object_id *yca_id = NULL;
9789 struct got_commit_object *yca_commit = NULL;
9790 char *yca_id_str = NULL, *yca_brief_str = NULL;
9791 char *custom_refs_str;
9793 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9794 return got_error_from_errno("asprintf");
9796 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9797 0, 0, refs_idmap, custom_refs_str);
9798 if (err)
9799 goto done;
9801 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9802 if (err)
9803 goto done;
9805 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9806 if (refs) {
9807 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9808 if (err)
9809 goto done;
9812 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9813 if (err)
9814 goto done;
9816 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9817 if (err)
9818 goto done;
9820 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9821 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9822 if (err)
9823 goto done;
9825 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9826 refs_str ? " (" : "", refs_str ? refs_str : "",
9827 refs_str ? ")" : "", new_commit_brief_str);
9828 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9829 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9830 free(refs_str);
9831 refs_str = NULL;
9833 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9834 if (err)
9835 goto done;
9837 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9838 if (err)
9839 goto done;
9841 err = got_object_id_str(&yca_id_str, yca_id);
9842 if (err)
9843 goto done;
9845 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9846 if (refs) {
9847 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9848 if (err)
9849 goto done;
9851 printf("history forked at %s%s%s%s\n %s\n",
9852 yca_id_str,
9853 refs_str ? " (" : "", refs_str ? refs_str : "",
9854 refs_str ? ")" : "", yca_brief_str);
9856 done:
9857 free(custom_refs_str);
9858 free(new_commit_id);
9859 free(refs_str);
9860 free(yca_id);
9861 free(yca_id_str);
9862 free(yca_brief_str);
9863 if (new_commit)
9864 got_object_commit_close(new_commit);
9865 if (yca_commit)
9866 got_object_commit_close(yca_commit);
9868 return NULL;
9871 static const struct got_error *
9872 process_backup_refs(const char *backup_ref_prefix,
9873 const char *wanted_branch_name,
9874 int delete, struct got_repository *repo)
9876 const struct got_error *err;
9877 struct got_reflist_head refs, backup_refs;
9878 struct got_reflist_entry *re;
9879 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9880 struct got_object_id *old_commit_id = NULL;
9881 char *branch_name = NULL;
9882 struct got_commit_object *old_commit = NULL;
9883 struct got_reflist_object_id_map *refs_idmap = NULL;
9884 int wanted_branch_found = 0;
9886 TAILQ_INIT(&refs);
9887 TAILQ_INIT(&backup_refs);
9889 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9890 if (err)
9891 return err;
9893 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9894 if (err)
9895 goto done;
9897 if (wanted_branch_name) {
9898 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9899 wanted_branch_name += 11;
9902 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9903 got_ref_cmp_by_commit_timestamp_descending, repo);
9904 if (err)
9905 goto done;
9907 TAILQ_FOREACH(re, &backup_refs, entry) {
9908 const char *refname = got_ref_get_name(re->ref);
9909 char *slash;
9911 err = check_cancelled(NULL);
9912 if (err)
9913 break;
9915 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9916 if (err)
9917 break;
9919 err = got_object_open_as_commit(&old_commit, repo,
9920 old_commit_id);
9921 if (err)
9922 break;
9924 if (strncmp(backup_ref_prefix, refname,
9925 backup_ref_prefix_len) == 0)
9926 refname += backup_ref_prefix_len;
9928 while (refname[0] == '/')
9929 refname++;
9931 branch_name = strdup(refname);
9932 if (branch_name == NULL) {
9933 err = got_error_from_errno("strdup");
9934 break;
9936 slash = strrchr(branch_name, '/');
9937 if (slash) {
9938 *slash = '\0';
9939 refname += strlen(branch_name) + 1;
9942 if (wanted_branch_name == NULL ||
9943 strcmp(wanted_branch_name, branch_name) == 0) {
9944 wanted_branch_found = 1;
9945 if (delete) {
9946 err = delete_backup_ref(re->ref,
9947 old_commit_id, repo);
9948 } else {
9949 err = print_backup_ref(branch_name, refname,
9950 old_commit_id, old_commit, refs_idmap,
9951 repo);
9953 if (err)
9954 break;
9957 free(old_commit_id);
9958 old_commit_id = NULL;
9959 free(branch_name);
9960 branch_name = NULL;
9961 got_object_commit_close(old_commit);
9962 old_commit = NULL;
9965 if (wanted_branch_name && !wanted_branch_found) {
9966 err = got_error_fmt(GOT_ERR_NOT_REF,
9967 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9969 done:
9970 if (refs_idmap)
9971 got_reflist_object_id_map_free(refs_idmap);
9972 got_ref_list_free(&refs);
9973 got_ref_list_free(&backup_refs);
9974 free(old_commit_id);
9975 free(branch_name);
9976 if (old_commit)
9977 got_object_commit_close(old_commit);
9978 return err;
9981 static const struct got_error *
9982 abort_progress(void *arg, unsigned char status, const char *path)
9985 * Unversioned files should not clutter progress output when
9986 * an operation is aborted.
9988 if (status == GOT_STATUS_UNVERSIONED)
9989 return NULL;
9991 return update_progress(arg, status, path);
9994 static const struct got_error *
9995 cmd_rebase(int argc, char *argv[])
9997 const struct got_error *error = NULL;
9998 struct got_worktree *worktree = NULL;
9999 struct got_repository *repo = NULL;
10000 struct got_fileindex *fileindex = NULL;
10001 char *cwd = NULL;
10002 struct got_reference *branch = NULL;
10003 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10004 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10005 struct got_object_id *resume_commit_id = NULL;
10006 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10007 struct got_commit_object *commit = NULL;
10008 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10009 int histedit_in_progress = 0, merge_in_progress = 0;
10010 int create_backup = 1, list_backups = 0, delete_backups = 0;
10011 struct got_object_id_queue commits;
10012 struct got_pathlist_head merged_paths;
10013 const struct got_object_id_queue *parent_ids;
10014 struct got_object_qid *qid, *pid;
10015 struct got_update_progress_arg upa;
10016 int *pack_fds = NULL;
10018 STAILQ_INIT(&commits);
10019 TAILQ_INIT(&merged_paths);
10020 memset(&upa, 0, sizeof(upa));
10022 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10023 switch (ch) {
10024 case 'a':
10025 abort_rebase = 1;
10026 break;
10027 case 'c':
10028 continue_rebase = 1;
10029 break;
10030 case 'l':
10031 list_backups = 1;
10032 break;
10033 case 'X':
10034 delete_backups = 1;
10035 break;
10036 default:
10037 usage_rebase();
10038 /* NOTREACHED */
10042 argc -= optind;
10043 argv += optind;
10045 #ifndef PROFILE
10046 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10047 "unveil", NULL) == -1)
10048 err(1, "pledge");
10049 #endif
10050 if (list_backups) {
10051 if (abort_rebase)
10052 option_conflict('l', 'a');
10053 if (continue_rebase)
10054 option_conflict('l', 'c');
10055 if (delete_backups)
10056 option_conflict('l', 'X');
10057 if (argc != 0 && argc != 1)
10058 usage_rebase();
10059 } else if (delete_backups) {
10060 if (abort_rebase)
10061 option_conflict('X', 'a');
10062 if (continue_rebase)
10063 option_conflict('X', 'c');
10064 if (list_backups)
10065 option_conflict('l', 'X');
10066 if (argc != 0 && argc != 1)
10067 usage_rebase();
10068 } else {
10069 if (abort_rebase && continue_rebase)
10070 usage_rebase();
10071 else if (abort_rebase || continue_rebase) {
10072 if (argc != 0)
10073 usage_rebase();
10074 } else if (argc != 1)
10075 usage_rebase();
10078 cwd = getcwd(NULL, 0);
10079 if (cwd == NULL) {
10080 error = got_error_from_errno("getcwd");
10081 goto done;
10084 error = got_repo_pack_fds_open(&pack_fds);
10085 if (error != NULL)
10086 goto done;
10088 error = got_worktree_open(&worktree, cwd);
10089 if (error) {
10090 if (list_backups || delete_backups) {
10091 if (error->code != GOT_ERR_NOT_WORKTREE)
10092 goto done;
10093 } else {
10094 if (error->code == GOT_ERR_NOT_WORKTREE)
10095 error = wrap_not_worktree_error(error,
10096 "rebase", cwd);
10097 goto done;
10101 error = got_repo_open(&repo,
10102 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
10103 pack_fds);
10104 if (error != NULL)
10105 goto done;
10107 error = apply_unveil(got_repo_get_path(repo), 0,
10108 worktree ? got_worktree_get_root_path(worktree) : NULL);
10109 if (error)
10110 goto done;
10112 if (list_backups || delete_backups) {
10113 error = process_backup_refs(
10114 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10115 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10116 goto done; /* nothing else to do */
10119 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10120 worktree);
10121 if (error)
10122 goto done;
10123 if (histedit_in_progress) {
10124 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10125 goto done;
10128 error = got_worktree_merge_in_progress(&merge_in_progress,
10129 worktree, repo);
10130 if (error)
10131 goto done;
10132 if (merge_in_progress) {
10133 error = got_error(GOT_ERR_MERGE_BUSY);
10134 goto done;
10137 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10138 if (error)
10139 goto done;
10141 if (abort_rebase) {
10142 if (!rebase_in_progress) {
10143 error = got_error(GOT_ERR_NOT_REBASING);
10144 goto done;
10146 error = got_worktree_rebase_continue(&resume_commit_id,
10147 &new_base_branch, &tmp_branch, &branch, &fileindex,
10148 worktree, repo);
10149 if (error)
10150 goto done;
10151 printf("Switching work tree to %s\n",
10152 got_ref_get_symref_target(new_base_branch));
10153 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10154 new_base_branch, abort_progress, &upa);
10155 if (error)
10156 goto done;
10157 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10158 print_merge_progress_stats(&upa);
10159 goto done; /* nothing else to do */
10162 if (continue_rebase) {
10163 if (!rebase_in_progress) {
10164 error = got_error(GOT_ERR_NOT_REBASING);
10165 goto done;
10167 error = got_worktree_rebase_continue(&resume_commit_id,
10168 &new_base_branch, &tmp_branch, &branch, &fileindex,
10169 worktree, repo);
10170 if (error)
10171 goto done;
10173 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10174 resume_commit_id, repo);
10175 if (error)
10176 goto done;
10178 yca_id = got_object_id_dup(resume_commit_id);
10179 if (yca_id == NULL) {
10180 error = got_error_from_errno("got_object_id_dup");
10181 goto done;
10183 } else {
10184 error = got_ref_open(&branch, repo, argv[0], 0);
10185 if (error != NULL)
10186 goto done;
10189 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10190 if (error)
10191 goto done;
10193 if (!continue_rebase) {
10194 struct got_object_id *base_commit_id;
10196 base_commit_id = got_worktree_get_base_commit_id(worktree);
10197 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10198 base_commit_id, branch_head_commit_id, 1, repo,
10199 check_cancelled, NULL);
10200 if (error)
10201 goto done;
10202 if (yca_id == NULL) {
10203 error = got_error_msg(GOT_ERR_ANCESTRY,
10204 "specified branch shares no common ancestry "
10205 "with work tree's branch");
10206 goto done;
10209 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10210 if (error) {
10211 if (error->code != GOT_ERR_ANCESTRY)
10212 goto done;
10213 error = NULL;
10214 } else {
10215 struct got_pathlist_head paths;
10216 printf("%s is already based on %s\n",
10217 got_ref_get_name(branch),
10218 got_worktree_get_head_ref_name(worktree));
10219 error = switch_head_ref(branch, branch_head_commit_id,
10220 worktree, repo);
10221 if (error)
10222 goto done;
10223 error = got_worktree_set_base_commit_id(worktree, repo,
10224 branch_head_commit_id);
10225 if (error)
10226 goto done;
10227 TAILQ_INIT(&paths);
10228 error = got_pathlist_append(&paths, "", NULL);
10229 if (error)
10230 goto done;
10231 error = got_worktree_checkout_files(worktree,
10232 &paths, repo, update_progress, &upa,
10233 check_cancelled, NULL);
10234 got_pathlist_free(&paths);
10235 if (error)
10236 goto done;
10237 if (upa.did_something) {
10238 char *id_str;
10239 error = got_object_id_str(&id_str,
10240 branch_head_commit_id);
10241 if (error)
10242 goto done;
10243 printf("Updated to %s: %s\n",
10244 got_worktree_get_head_ref_name(worktree),
10245 id_str);
10246 free(id_str);
10247 } else
10248 printf("Already up-to-date\n");
10249 print_update_progress_stats(&upa);
10250 goto done;
10254 commit_id = branch_head_commit_id;
10255 error = got_object_open_as_commit(&commit, repo, commit_id);
10256 if (error)
10257 goto done;
10259 parent_ids = got_object_commit_get_parent_ids(commit);
10260 pid = STAILQ_FIRST(parent_ids);
10261 if (pid == NULL) {
10262 error = got_error(GOT_ERR_EMPTY_REBASE);
10263 goto done;
10265 error = collect_commits(&commits, commit_id, &pid->id,
10266 yca_id, got_worktree_get_path_prefix(worktree),
10267 GOT_ERR_REBASE_PATH, repo);
10268 got_object_commit_close(commit);
10269 commit = NULL;
10270 if (error)
10271 goto done;
10273 if (!continue_rebase) {
10274 error = got_worktree_rebase_prepare(&new_base_branch,
10275 &tmp_branch, &fileindex, worktree, branch, repo);
10276 if (error)
10277 goto done;
10280 if (STAILQ_EMPTY(&commits)) {
10281 if (continue_rebase) {
10282 error = rebase_complete(worktree, fileindex,
10283 branch, new_base_branch, tmp_branch, repo,
10284 create_backup);
10285 goto done;
10286 } else {
10287 /* Fast-forward the reference of the branch. */
10288 struct got_object_id *new_head_commit_id;
10289 char *id_str;
10290 error = got_ref_resolve(&new_head_commit_id, repo,
10291 new_base_branch);
10292 if (error)
10293 goto done;
10294 error = got_object_id_str(&id_str, new_head_commit_id);
10295 printf("Forwarding %s to commit %s\n",
10296 got_ref_get_name(branch), id_str);
10297 free(id_str);
10298 error = got_ref_change_ref(branch,
10299 new_head_commit_id);
10300 if (error)
10301 goto done;
10302 /* No backup needed since objects did not change. */
10303 create_backup = 0;
10307 pid = NULL;
10308 STAILQ_FOREACH(qid, &commits, entry) {
10310 commit_id = &qid->id;
10311 parent_id = pid ? &pid->id : yca_id;
10312 pid = qid;
10314 memset(&upa, 0, sizeof(upa));
10315 error = got_worktree_rebase_merge_files(&merged_paths,
10316 worktree, fileindex, parent_id, commit_id, repo,
10317 update_progress, &upa, check_cancelled, NULL);
10318 if (error)
10319 goto done;
10321 print_merge_progress_stats(&upa);
10322 if (upa.conflicts > 0 || upa.missing > 0 ||
10323 upa.not_deleted > 0 || upa.unversioned > 0) {
10324 if (upa.conflicts > 0) {
10325 error = show_rebase_merge_conflict(&qid->id,
10326 repo);
10327 if (error)
10328 goto done;
10330 got_worktree_rebase_pathlist_free(&merged_paths);
10331 break;
10334 error = rebase_commit(&merged_paths, worktree, fileindex,
10335 tmp_branch, commit_id, repo);
10336 got_worktree_rebase_pathlist_free(&merged_paths);
10337 if (error)
10338 goto done;
10341 if (upa.conflicts > 0 || upa.missing > 0 ||
10342 upa.not_deleted > 0 || upa.unversioned > 0) {
10343 error = got_worktree_rebase_postpone(worktree, fileindex);
10344 if (error)
10345 goto done;
10346 if (upa.conflicts > 0 && upa.missing == 0 &&
10347 upa.not_deleted == 0 && upa.unversioned == 0) {
10348 error = got_error_msg(GOT_ERR_CONFLICTS,
10349 "conflicts must be resolved before rebasing "
10350 "can continue");
10351 } else if (upa.conflicts > 0) {
10352 error = got_error_msg(GOT_ERR_CONFLICTS,
10353 "conflicts must be resolved before rebasing "
10354 "can continue; changes destined for some "
10355 "files were not yet merged and should be "
10356 "merged manually if required before the "
10357 "rebase operation is continued");
10358 } else {
10359 error = got_error_msg(GOT_ERR_CONFLICTS,
10360 "changes destined for some files were not "
10361 "yet merged and should be merged manually "
10362 "if required before the rebase operation "
10363 "is continued");
10365 } else
10366 error = rebase_complete(worktree, fileindex, branch,
10367 new_base_branch, tmp_branch, repo, create_backup);
10368 done:
10369 got_object_id_queue_free(&commits);
10370 free(branch_head_commit_id);
10371 free(resume_commit_id);
10372 free(yca_id);
10373 if (commit)
10374 got_object_commit_close(commit);
10375 if (branch)
10376 got_ref_close(branch);
10377 if (new_base_branch)
10378 got_ref_close(new_base_branch);
10379 if (tmp_branch)
10380 got_ref_close(tmp_branch);
10381 if (worktree)
10382 got_worktree_close(worktree);
10383 if (repo) {
10384 const struct got_error *close_err = got_repo_close(repo);
10385 if (error == NULL)
10386 error = close_err;
10388 if (pack_fds) {
10389 const struct got_error *pack_err =
10390 got_repo_pack_fds_close(pack_fds);
10391 if (error == NULL)
10392 error = pack_err;
10394 return error;
10397 __dead static void
10398 usage_histedit(void)
10400 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10401 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10402 getprogname());
10403 exit(1);
10406 #define GOT_HISTEDIT_PICK 'p'
10407 #define GOT_HISTEDIT_EDIT 'e'
10408 #define GOT_HISTEDIT_FOLD 'f'
10409 #define GOT_HISTEDIT_DROP 'd'
10410 #define GOT_HISTEDIT_MESG 'm'
10412 static const struct got_histedit_cmd {
10413 unsigned char code;
10414 const char *name;
10415 const char *desc;
10416 } got_histedit_cmds[] = {
10417 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10418 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10419 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10420 "be used" },
10421 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10422 { GOT_HISTEDIT_MESG, "mesg",
10423 "single-line log message for commit above (open editor if empty)" },
10426 struct got_histedit_list_entry {
10427 TAILQ_ENTRY(got_histedit_list_entry) entry;
10428 struct got_object_id *commit_id;
10429 const struct got_histedit_cmd *cmd;
10430 char *logmsg;
10432 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10434 static const struct got_error *
10435 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10436 FILE *f, struct got_repository *repo)
10438 const struct got_error *err = NULL;
10439 char *logmsg = NULL, *id_str = NULL;
10440 struct got_commit_object *commit = NULL;
10441 int n;
10443 err = got_object_open_as_commit(&commit, repo, commit_id);
10444 if (err)
10445 goto done;
10447 err = get_short_logmsg(&logmsg, 34, commit);
10448 if (err)
10449 goto done;
10451 err = got_object_id_str(&id_str, commit_id);
10452 if (err)
10453 goto done;
10455 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10456 if (n < 0)
10457 err = got_ferror(f, GOT_ERR_IO);
10458 done:
10459 if (commit)
10460 got_object_commit_close(commit);
10461 free(id_str);
10462 free(logmsg);
10463 return err;
10466 static const struct got_error *
10467 histedit_write_commit_list(struct got_object_id_queue *commits,
10468 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10469 struct got_repository *repo)
10471 const struct got_error *err = NULL;
10472 struct got_object_qid *qid;
10473 const char *histedit_cmd = NULL;
10475 if (STAILQ_EMPTY(commits))
10476 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10478 STAILQ_FOREACH(qid, commits, entry) {
10479 histedit_cmd = got_histedit_cmds[0].name;
10480 if (edit_only)
10481 histedit_cmd = "edit";
10482 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10483 histedit_cmd = "fold";
10484 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10485 if (err)
10486 break;
10487 if (edit_logmsg_only) {
10488 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10489 if (n < 0) {
10490 err = got_ferror(f, GOT_ERR_IO);
10491 break;
10496 return err;
10499 static const struct got_error *
10500 write_cmd_list(FILE *f, const char *branch_name,
10501 struct got_object_id_queue *commits)
10503 const struct got_error *err = NULL;
10504 size_t i;
10505 int n;
10506 char *id_str;
10507 struct got_object_qid *qid;
10509 qid = STAILQ_FIRST(commits);
10510 err = got_object_id_str(&id_str, &qid->id);
10511 if (err)
10512 return err;
10514 n = fprintf(f,
10515 "# Editing the history of branch '%s' starting at\n"
10516 "# commit %s\n"
10517 "# Commits will be processed in order from top to "
10518 "bottom of this file.\n", branch_name, id_str);
10519 if (n < 0) {
10520 err = got_ferror(f, GOT_ERR_IO);
10521 goto done;
10524 n = fprintf(f, "# Available histedit commands:\n");
10525 if (n < 0) {
10526 err = got_ferror(f, GOT_ERR_IO);
10527 goto done;
10530 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10531 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10532 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10533 cmd->desc);
10534 if (n < 0) {
10535 err = got_ferror(f, GOT_ERR_IO);
10536 break;
10539 done:
10540 free(id_str);
10541 return err;
10544 static const struct got_error *
10545 histedit_syntax_error(int lineno)
10547 static char msg[42];
10548 int ret;
10550 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10551 lineno);
10552 if (ret == -1 || ret >= sizeof(msg))
10553 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10555 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10558 static const struct got_error *
10559 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10560 char *logmsg, struct got_repository *repo)
10562 const struct got_error *err;
10563 struct got_commit_object *folded_commit = NULL;
10564 char *id_str, *folded_logmsg = NULL;
10566 err = got_object_id_str(&id_str, hle->commit_id);
10567 if (err)
10568 return err;
10570 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10571 if (err)
10572 goto done;
10574 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10575 if (err)
10576 goto done;
10577 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10578 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10579 folded_logmsg) == -1) {
10580 err = got_error_from_errno("asprintf");
10582 done:
10583 if (folded_commit)
10584 got_object_commit_close(folded_commit);
10585 free(id_str);
10586 free(folded_logmsg);
10587 return err;
10590 static struct got_histedit_list_entry *
10591 get_folded_commits(struct got_histedit_list_entry *hle)
10593 struct got_histedit_list_entry *prev, *folded = NULL;
10595 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10596 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10597 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10598 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10599 folded = prev;
10600 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10603 return folded;
10606 static const struct got_error *
10607 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10608 struct got_repository *repo)
10610 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10611 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10612 const struct got_error *err = NULL;
10613 struct got_commit_object *commit = NULL;
10614 int logmsg_len;
10615 int fd;
10616 struct got_histedit_list_entry *folded = NULL;
10618 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10619 if (err)
10620 return err;
10622 folded = get_folded_commits(hle);
10623 if (folded) {
10624 while (folded != hle) {
10625 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10626 folded = TAILQ_NEXT(folded, entry);
10627 continue;
10629 err = append_folded_commit_msg(&new_msg, folded,
10630 logmsg, repo);
10631 if (err)
10632 goto done;
10633 free(logmsg);
10634 logmsg = new_msg;
10635 folded = TAILQ_NEXT(folded, entry);
10639 err = got_object_id_str(&id_str, hle->commit_id);
10640 if (err)
10641 goto done;
10642 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10643 if (err)
10644 goto done;
10645 logmsg_len = asprintf(&new_msg,
10646 "%s\n# original log message of commit %s: %s",
10647 logmsg ? logmsg : "", id_str, orig_logmsg);
10648 if (logmsg_len == -1) {
10649 err = got_error_from_errno("asprintf");
10650 goto done;
10652 free(logmsg);
10653 logmsg = new_msg;
10655 err = got_object_id_str(&id_str, hle->commit_id);
10656 if (err)
10657 goto done;
10659 err = got_opentemp_named_fd(&logmsg_path, &fd,
10660 GOT_TMPDIR_STR "/got-logmsg");
10661 if (err)
10662 goto done;
10664 write(fd, logmsg, logmsg_len);
10665 close(fd);
10667 err = get_editor(&editor);
10668 if (err)
10669 goto done;
10671 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10672 logmsg_len, 0);
10673 if (err) {
10674 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10675 goto done;
10676 err = NULL;
10677 hle->logmsg = strdup(new_msg);
10678 if (hle->logmsg == NULL)
10679 err = got_error_from_errno("strdup");
10681 done:
10682 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10683 err = got_error_from_errno2("unlink", logmsg_path);
10684 free(logmsg_path);
10685 free(logmsg);
10686 free(orig_logmsg);
10687 free(editor);
10688 if (commit)
10689 got_object_commit_close(commit);
10690 return err;
10693 static const struct got_error *
10694 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10695 FILE *f, struct got_repository *repo)
10697 const struct got_error *err = NULL;
10698 char *line = NULL, *p, *end;
10699 size_t i, size;
10700 ssize_t len;
10701 int lineno = 0, lastcmd = -1;
10702 const struct got_histedit_cmd *cmd;
10703 struct got_object_id *commit_id = NULL;
10704 struct got_histedit_list_entry *hle = NULL;
10706 for (;;) {
10707 len = getline(&line, &size, f);
10708 if (len == -1) {
10709 const struct got_error *getline_err;
10710 if (feof(f))
10711 break;
10712 getline_err = got_error_from_errno("getline");
10713 err = got_ferror(f, getline_err->code);
10714 break;
10716 lineno++;
10717 p = line;
10718 while (isspace((unsigned char)p[0]))
10719 p++;
10720 if (p[0] == '#' || p[0] == '\0') {
10721 free(line);
10722 line = NULL;
10723 continue;
10725 cmd = NULL;
10726 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10727 cmd = &got_histedit_cmds[i];
10728 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10729 isspace((unsigned char)p[strlen(cmd->name)])) {
10730 p += strlen(cmd->name);
10731 break;
10733 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10734 p++;
10735 break;
10738 if (i == nitems(got_histedit_cmds)) {
10739 err = histedit_syntax_error(lineno);
10740 break;
10742 while (isspace((unsigned char)p[0]))
10743 p++;
10744 if (cmd->code == GOT_HISTEDIT_MESG) {
10745 if (lastcmd != GOT_HISTEDIT_PICK &&
10746 lastcmd != GOT_HISTEDIT_EDIT) {
10747 err = got_error(GOT_ERR_HISTEDIT_CMD);
10748 break;
10750 if (p[0] == '\0') {
10751 err = histedit_edit_logmsg(hle, repo);
10752 if (err)
10753 break;
10754 } else {
10755 hle->logmsg = strdup(p);
10756 if (hle->logmsg == NULL) {
10757 err = got_error_from_errno("strdup");
10758 break;
10761 free(line);
10762 line = NULL;
10763 lastcmd = cmd->code;
10764 continue;
10765 } else {
10766 end = p;
10767 while (end[0] && !isspace((unsigned char)end[0]))
10768 end++;
10769 *end = '\0';
10771 err = got_object_resolve_id_str(&commit_id, repo, p);
10772 if (err) {
10773 /* override error code */
10774 err = histedit_syntax_error(lineno);
10775 break;
10778 hle = malloc(sizeof(*hle));
10779 if (hle == NULL) {
10780 err = got_error_from_errno("malloc");
10781 break;
10783 hle->cmd = cmd;
10784 hle->commit_id = commit_id;
10785 hle->logmsg = NULL;
10786 commit_id = NULL;
10787 free(line);
10788 line = NULL;
10789 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10790 lastcmd = cmd->code;
10793 free(line);
10794 free(commit_id);
10795 return err;
10798 static const struct got_error *
10799 histedit_check_script(struct got_histedit_list *histedit_cmds,
10800 struct got_object_id_queue *commits, struct got_repository *repo)
10802 const struct got_error *err = NULL;
10803 struct got_object_qid *qid;
10804 struct got_histedit_list_entry *hle;
10805 static char msg[92];
10806 char *id_str;
10808 if (TAILQ_EMPTY(histedit_cmds))
10809 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10810 "histedit script contains no commands");
10811 if (STAILQ_EMPTY(commits))
10812 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10814 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10815 struct got_histedit_list_entry *hle2;
10816 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10817 if (hle == hle2)
10818 continue;
10819 if (got_object_id_cmp(hle->commit_id,
10820 hle2->commit_id) != 0)
10821 continue;
10822 err = got_object_id_str(&id_str, hle->commit_id);
10823 if (err)
10824 return err;
10825 snprintf(msg, sizeof(msg), "commit %s is listed "
10826 "more than once in histedit script", id_str);
10827 free(id_str);
10828 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10832 STAILQ_FOREACH(qid, commits, entry) {
10833 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10834 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10835 break;
10837 if (hle == NULL) {
10838 err = got_object_id_str(&id_str, &qid->id);
10839 if (err)
10840 return err;
10841 snprintf(msg, sizeof(msg),
10842 "commit %s missing from histedit script", id_str);
10843 free(id_str);
10844 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10848 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10849 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10850 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10851 "last commit in histedit script cannot be folded");
10853 return NULL;
10856 static const struct got_error *
10857 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10858 const char *path, struct got_object_id_queue *commits,
10859 struct got_repository *repo)
10861 const struct got_error *err = NULL;
10862 char *editor;
10863 FILE *f = NULL;
10865 err = get_editor(&editor);
10866 if (err)
10867 return err;
10869 if (spawn_editor(editor, path) == -1) {
10870 err = got_error_from_errno("failed spawning editor");
10871 goto done;
10874 f = fopen(path, "re");
10875 if (f == NULL) {
10876 err = got_error_from_errno("fopen");
10877 goto done;
10879 err = histedit_parse_list(histedit_cmds, f, repo);
10880 if (err)
10881 goto done;
10883 err = histedit_check_script(histedit_cmds, commits, repo);
10884 done:
10885 if (f && fclose(f) == EOF && err == NULL)
10886 err = got_error_from_errno("fclose");
10887 free(editor);
10888 return err;
10891 static const struct got_error *
10892 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10893 struct got_object_id_queue *, const char *, const char *,
10894 struct got_repository *);
10896 static const struct got_error *
10897 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10898 struct got_object_id_queue *commits, const char *branch_name,
10899 int edit_logmsg_only, int fold_only, int edit_only,
10900 struct got_repository *repo)
10902 const struct got_error *err;
10903 FILE *f = NULL;
10904 char *path = NULL;
10906 err = got_opentemp_named(&path, &f, "got-histedit");
10907 if (err)
10908 return err;
10910 err = write_cmd_list(f, branch_name, commits);
10911 if (err)
10912 goto done;
10914 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10915 fold_only, edit_only, repo);
10916 if (err)
10917 goto done;
10919 if (edit_logmsg_only || fold_only || edit_only) {
10920 rewind(f);
10921 err = histedit_parse_list(histedit_cmds, f, repo);
10922 } else {
10923 if (fclose(f) == EOF) {
10924 err = got_error_from_errno("fclose");
10925 goto done;
10927 f = NULL;
10928 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10929 if (err) {
10930 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10931 err->code != GOT_ERR_HISTEDIT_CMD)
10932 goto done;
10933 err = histedit_edit_list_retry(histedit_cmds, err,
10934 commits, path, branch_name, repo);
10937 done:
10938 if (f && fclose(f) == EOF && err == NULL)
10939 err = got_error_from_errno("fclose");
10940 if (path && unlink(path) != 0 && err == NULL)
10941 err = got_error_from_errno2("unlink", path);
10942 free(path);
10943 return err;
10946 static const struct got_error *
10947 histedit_save_list(struct got_histedit_list *histedit_cmds,
10948 struct got_worktree *worktree, struct got_repository *repo)
10950 const struct got_error *err = NULL;
10951 char *path = NULL;
10952 FILE *f = NULL;
10953 struct got_histedit_list_entry *hle;
10954 struct got_commit_object *commit = NULL;
10956 err = got_worktree_get_histedit_script_path(&path, worktree);
10957 if (err)
10958 return err;
10960 f = fopen(path, "we");
10961 if (f == NULL) {
10962 err = got_error_from_errno2("fopen", path);
10963 goto done;
10965 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10966 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10967 repo);
10968 if (err)
10969 break;
10971 if (hle->logmsg) {
10972 int n = fprintf(f, "%c %s\n",
10973 GOT_HISTEDIT_MESG, hle->logmsg);
10974 if (n < 0) {
10975 err = got_ferror(f, GOT_ERR_IO);
10976 break;
10980 done:
10981 if (f && fclose(f) == EOF && err == NULL)
10982 err = got_error_from_errno("fclose");
10983 free(path);
10984 if (commit)
10985 got_object_commit_close(commit);
10986 return err;
10989 static void
10990 histedit_free_list(struct got_histedit_list *histedit_cmds)
10992 struct got_histedit_list_entry *hle;
10994 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10995 TAILQ_REMOVE(histedit_cmds, hle, entry);
10996 free(hle);
11000 static const struct got_error *
11001 histedit_load_list(struct got_histedit_list *histedit_cmds,
11002 const char *path, struct got_repository *repo)
11004 const struct got_error *err = NULL;
11005 FILE *f = NULL;
11007 f = fopen(path, "re");
11008 if (f == NULL) {
11009 err = got_error_from_errno2("fopen", path);
11010 goto done;
11013 err = histedit_parse_list(histedit_cmds, f, repo);
11014 done:
11015 if (f && fclose(f) == EOF && err == NULL)
11016 err = got_error_from_errno("fclose");
11017 return err;
11020 static const struct got_error *
11021 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11022 const struct got_error *edit_err, struct got_object_id_queue *commits,
11023 const char *path, const char *branch_name, struct got_repository *repo)
11025 const struct got_error *err = NULL, *prev_err = edit_err;
11026 int resp = ' ';
11028 while (resp != 'c' && resp != 'r' && resp != 'a') {
11029 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11030 "or (a)bort: ", getprogname(), prev_err->msg);
11031 resp = getchar();
11032 if (resp == '\n')
11033 resp = getchar();
11034 if (resp == 'c') {
11035 histedit_free_list(histedit_cmds);
11036 err = histedit_run_editor(histedit_cmds, path, commits,
11037 repo);
11038 if (err) {
11039 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11040 err->code != GOT_ERR_HISTEDIT_CMD)
11041 break;
11042 prev_err = err;
11043 resp = ' ';
11044 continue;
11046 break;
11047 } else if (resp == 'r') {
11048 histedit_free_list(histedit_cmds);
11049 err = histedit_edit_script(histedit_cmds,
11050 commits, branch_name, 0, 0, 0, repo);
11051 if (err) {
11052 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11053 err->code != GOT_ERR_HISTEDIT_CMD)
11054 break;
11055 prev_err = err;
11056 resp = ' ';
11057 continue;
11059 break;
11060 } else if (resp == 'a') {
11061 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11062 break;
11063 } else
11064 printf("invalid response '%c'\n", resp);
11067 return err;
11070 static const struct got_error *
11071 histedit_complete(struct got_worktree *worktree,
11072 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11073 struct got_reference *branch, struct got_repository *repo)
11075 printf("Switching work tree to %s\n",
11076 got_ref_get_symref_target(branch));
11077 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11078 branch, repo);
11081 static const struct got_error *
11082 show_histedit_progress(struct got_commit_object *commit,
11083 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11085 const struct got_error *err;
11086 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11088 err = got_object_id_str(&old_id_str, hle->commit_id);
11089 if (err)
11090 goto done;
11092 if (new_id) {
11093 err = got_object_id_str(&new_id_str, new_id);
11094 if (err)
11095 goto done;
11098 old_id_str[12] = '\0';
11099 if (new_id_str)
11100 new_id_str[12] = '\0';
11102 if (hle->logmsg) {
11103 logmsg = strdup(hle->logmsg);
11104 if (logmsg == NULL) {
11105 err = got_error_from_errno("strdup");
11106 goto done;
11108 trim_logmsg(logmsg, 42);
11109 } else {
11110 err = get_short_logmsg(&logmsg, 42, commit);
11111 if (err)
11112 goto done;
11115 switch (hle->cmd->code) {
11116 case GOT_HISTEDIT_PICK:
11117 case GOT_HISTEDIT_EDIT:
11118 printf("%s -> %s: %s\n", old_id_str,
11119 new_id_str ? new_id_str : "no-op change", logmsg);
11120 break;
11121 case GOT_HISTEDIT_DROP:
11122 case GOT_HISTEDIT_FOLD:
11123 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11124 logmsg);
11125 break;
11126 default:
11127 break;
11129 done:
11130 free(old_id_str);
11131 free(new_id_str);
11132 return err;
11135 static const struct got_error *
11136 histedit_commit(struct got_pathlist_head *merged_paths,
11137 struct got_worktree *worktree, struct got_fileindex *fileindex,
11138 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11139 struct got_repository *repo)
11141 const struct got_error *err;
11142 struct got_commit_object *commit;
11143 struct got_object_id *new_commit_id;
11145 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11146 && hle->logmsg == NULL) {
11147 err = histedit_edit_logmsg(hle, repo);
11148 if (err)
11149 return err;
11152 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11153 if (err)
11154 return err;
11156 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11157 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11158 hle->logmsg, repo);
11159 if (err) {
11160 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11161 goto done;
11162 err = show_histedit_progress(commit, hle, NULL);
11163 } else {
11164 err = show_histedit_progress(commit, hle, new_commit_id);
11165 free(new_commit_id);
11167 done:
11168 got_object_commit_close(commit);
11169 return err;
11172 static const struct got_error *
11173 histedit_skip_commit(struct got_histedit_list_entry *hle,
11174 struct got_worktree *worktree, struct got_repository *repo)
11176 const struct got_error *error;
11177 struct got_commit_object *commit;
11179 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11180 repo);
11181 if (error)
11182 return error;
11184 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11185 if (error)
11186 return error;
11188 error = show_histedit_progress(commit, hle, NULL);
11189 got_object_commit_close(commit);
11190 return error;
11193 static const struct got_error *
11194 check_local_changes(void *arg, unsigned char status,
11195 unsigned char staged_status, const char *path,
11196 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11197 struct got_object_id *commit_id, int dirfd, const char *de_name)
11199 int *have_local_changes = arg;
11201 switch (status) {
11202 case GOT_STATUS_ADD:
11203 case GOT_STATUS_DELETE:
11204 case GOT_STATUS_MODIFY:
11205 case GOT_STATUS_CONFLICT:
11206 *have_local_changes = 1;
11207 return got_error(GOT_ERR_CANCELLED);
11208 default:
11209 break;
11212 switch (staged_status) {
11213 case GOT_STATUS_ADD:
11214 case GOT_STATUS_DELETE:
11215 case GOT_STATUS_MODIFY:
11216 *have_local_changes = 1;
11217 return got_error(GOT_ERR_CANCELLED);
11218 default:
11219 break;
11222 return NULL;
11225 static const struct got_error *
11226 cmd_histedit(int argc, char *argv[])
11228 const struct got_error *error = NULL;
11229 struct got_worktree *worktree = NULL;
11230 struct got_fileindex *fileindex = NULL;
11231 struct got_repository *repo = NULL;
11232 char *cwd = NULL;
11233 struct got_reference *branch = NULL;
11234 struct got_reference *tmp_branch = NULL;
11235 struct got_object_id *resume_commit_id = NULL;
11236 struct got_object_id *base_commit_id = NULL;
11237 struct got_object_id *head_commit_id = NULL;
11238 struct got_commit_object *commit = NULL;
11239 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11240 struct got_update_progress_arg upa;
11241 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11242 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11243 int list_backups = 0, delete_backups = 0;
11244 const char *edit_script_path = NULL;
11245 struct got_object_id_queue commits;
11246 struct got_pathlist_head merged_paths;
11247 const struct got_object_id_queue *parent_ids;
11248 struct got_object_qid *pid;
11249 struct got_histedit_list histedit_cmds;
11250 struct got_histedit_list_entry *hle;
11251 int *pack_fds = NULL;
11253 STAILQ_INIT(&commits);
11254 TAILQ_INIT(&histedit_cmds);
11255 TAILQ_INIT(&merged_paths);
11256 memset(&upa, 0, sizeof(upa));
11258 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11259 switch (ch) {
11260 case 'a':
11261 abort_edit = 1;
11262 break;
11263 case 'c':
11264 continue_edit = 1;
11265 break;
11266 case 'e':
11267 edit_only = 1;
11268 break;
11269 case 'f':
11270 fold_only = 1;
11271 break;
11272 case 'F':
11273 edit_script_path = optarg;
11274 break;
11275 case 'm':
11276 edit_logmsg_only = 1;
11277 break;
11278 case 'l':
11279 list_backups = 1;
11280 break;
11281 case 'X':
11282 delete_backups = 1;
11283 break;
11284 default:
11285 usage_histedit();
11286 /* NOTREACHED */
11290 argc -= optind;
11291 argv += optind;
11293 #ifndef PROFILE
11294 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11295 "unveil", NULL) == -1)
11296 err(1, "pledge");
11297 #endif
11298 if (abort_edit && continue_edit)
11299 option_conflict('a', 'c');
11300 if (edit_script_path && edit_logmsg_only)
11301 option_conflict('F', 'm');
11302 if (abort_edit && edit_logmsg_only)
11303 option_conflict('a', 'm');
11304 if (continue_edit && edit_logmsg_only)
11305 option_conflict('c', 'm');
11306 if (abort_edit && fold_only)
11307 option_conflict('a', 'f');
11308 if (continue_edit && fold_only)
11309 option_conflict('c', 'f');
11310 if (fold_only && edit_logmsg_only)
11311 option_conflict('f', 'm');
11312 if (edit_script_path && fold_only)
11313 option_conflict('F', 'f');
11314 if (abort_edit && edit_only)
11315 option_conflict('a', 'e');
11316 if (continue_edit && edit_only)
11317 option_conflict('c', 'e');
11318 if (edit_only && edit_logmsg_only)
11319 option_conflict('e', 'm');
11320 if (edit_script_path && edit_only)
11321 option_conflict('F', 'e');
11322 if (list_backups) {
11323 if (abort_edit)
11324 option_conflict('l', 'a');
11325 if (continue_edit)
11326 option_conflict('l', 'c');
11327 if (edit_script_path)
11328 option_conflict('l', 'F');
11329 if (edit_logmsg_only)
11330 option_conflict('l', 'm');
11331 if (fold_only)
11332 option_conflict('l', 'f');
11333 if (edit_only)
11334 option_conflict('l', 'e');
11335 if (delete_backups)
11336 option_conflict('l', 'X');
11337 if (argc != 0 && argc != 1)
11338 usage_histedit();
11339 } else if (delete_backups) {
11340 if (abort_edit)
11341 option_conflict('X', 'a');
11342 if (continue_edit)
11343 option_conflict('X', 'c');
11344 if (edit_script_path)
11345 option_conflict('X', 'F');
11346 if (edit_logmsg_only)
11347 option_conflict('X', 'm');
11348 if (fold_only)
11349 option_conflict('X', 'f');
11350 if (edit_only)
11351 option_conflict('X', 'e');
11352 if (list_backups)
11353 option_conflict('X', 'l');
11354 if (argc != 0 && argc != 1)
11355 usage_histedit();
11356 } else if (argc != 0)
11357 usage_histedit();
11360 * This command cannot apply unveil(2) in all cases because the
11361 * user may choose to run an editor to edit the histedit script
11362 * and to edit individual commit log messages.
11363 * unveil(2) traverses exec(2); if an editor is used we have to
11364 * apply unveil after edit script and log messages have been written.
11365 * XXX TODO: Make use of unveil(2) where possible.
11368 cwd = getcwd(NULL, 0);
11369 if (cwd == NULL) {
11370 error = got_error_from_errno("getcwd");
11371 goto done;
11374 error = got_repo_pack_fds_open(&pack_fds);
11375 if (error != NULL)
11376 goto done;
11378 error = got_worktree_open(&worktree, cwd);
11379 if (error) {
11380 if (list_backups || delete_backups) {
11381 if (error->code != GOT_ERR_NOT_WORKTREE)
11382 goto done;
11383 } else {
11384 if (error->code == GOT_ERR_NOT_WORKTREE)
11385 error = wrap_not_worktree_error(error,
11386 "histedit", cwd);
11387 goto done;
11391 if (list_backups || delete_backups) {
11392 error = got_repo_open(&repo,
11393 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11394 NULL, pack_fds);
11395 if (error != NULL)
11396 goto done;
11397 error = apply_unveil(got_repo_get_path(repo), 0,
11398 worktree ? got_worktree_get_root_path(worktree) : NULL);
11399 if (error)
11400 goto done;
11401 error = process_backup_refs(
11402 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11403 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11404 goto done; /* nothing else to do */
11407 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11408 NULL, pack_fds);
11409 if (error != NULL)
11410 goto done;
11412 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11413 if (error)
11414 goto done;
11415 if (rebase_in_progress) {
11416 error = got_error(GOT_ERR_REBASING);
11417 goto done;
11420 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11421 repo);
11422 if (error)
11423 goto done;
11424 if (merge_in_progress) {
11425 error = got_error(GOT_ERR_MERGE_BUSY);
11426 goto done;
11429 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11430 if (error)
11431 goto done;
11433 if (edit_in_progress && edit_logmsg_only) {
11434 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11435 "histedit operation is in progress in this "
11436 "work tree and must be continued or aborted "
11437 "before the -m option can be used");
11438 goto done;
11440 if (edit_in_progress && fold_only) {
11441 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11442 "histedit operation is in progress in this "
11443 "work tree and must be continued or aborted "
11444 "before the -f option can be used");
11445 goto done;
11447 if (edit_in_progress && edit_only) {
11448 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11449 "histedit operation is in progress in this "
11450 "work tree and must be continued or aborted "
11451 "before the -e option can be used");
11452 goto done;
11455 if (edit_in_progress && abort_edit) {
11456 error = got_worktree_histedit_continue(&resume_commit_id,
11457 &tmp_branch, &branch, &base_commit_id, &fileindex,
11458 worktree, repo);
11459 if (error)
11460 goto done;
11461 printf("Switching work tree to %s\n",
11462 got_ref_get_symref_target(branch));
11463 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11464 branch, base_commit_id, abort_progress, &upa);
11465 if (error)
11466 goto done;
11467 printf("Histedit of %s aborted\n",
11468 got_ref_get_symref_target(branch));
11469 print_merge_progress_stats(&upa);
11470 goto done; /* nothing else to do */
11471 } else if (abort_edit) {
11472 error = got_error(GOT_ERR_NOT_HISTEDIT);
11473 goto done;
11476 if (continue_edit) {
11477 char *path;
11479 if (!edit_in_progress) {
11480 error = got_error(GOT_ERR_NOT_HISTEDIT);
11481 goto done;
11484 error = got_worktree_get_histedit_script_path(&path, worktree);
11485 if (error)
11486 goto done;
11488 error = histedit_load_list(&histedit_cmds, path, repo);
11489 free(path);
11490 if (error)
11491 goto done;
11493 error = got_worktree_histedit_continue(&resume_commit_id,
11494 &tmp_branch, &branch, &base_commit_id, &fileindex,
11495 worktree, repo);
11496 if (error)
11497 goto done;
11499 error = got_ref_resolve(&head_commit_id, repo, branch);
11500 if (error)
11501 goto done;
11503 error = got_object_open_as_commit(&commit, repo,
11504 head_commit_id);
11505 if (error)
11506 goto done;
11507 parent_ids = got_object_commit_get_parent_ids(commit);
11508 pid = STAILQ_FIRST(parent_ids);
11509 if (pid == NULL) {
11510 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11511 goto done;
11513 error = collect_commits(&commits, head_commit_id, &pid->id,
11514 base_commit_id, got_worktree_get_path_prefix(worktree),
11515 GOT_ERR_HISTEDIT_PATH, repo);
11516 got_object_commit_close(commit);
11517 commit = NULL;
11518 if (error)
11519 goto done;
11520 } else {
11521 if (edit_in_progress) {
11522 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11523 goto done;
11526 error = got_ref_open(&branch, repo,
11527 got_worktree_get_head_ref_name(worktree), 0);
11528 if (error != NULL)
11529 goto done;
11531 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11532 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11533 "will not edit commit history of a branch outside "
11534 "the \"refs/heads/\" reference namespace");
11535 goto done;
11538 error = got_ref_resolve(&head_commit_id, repo, branch);
11539 got_ref_close(branch);
11540 branch = NULL;
11541 if (error)
11542 goto done;
11544 error = got_object_open_as_commit(&commit, repo,
11545 head_commit_id);
11546 if (error)
11547 goto done;
11548 parent_ids = got_object_commit_get_parent_ids(commit);
11549 pid = STAILQ_FIRST(parent_ids);
11550 if (pid == NULL) {
11551 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11552 goto done;
11554 error = collect_commits(&commits, head_commit_id, &pid->id,
11555 got_worktree_get_base_commit_id(worktree),
11556 got_worktree_get_path_prefix(worktree),
11557 GOT_ERR_HISTEDIT_PATH, repo);
11558 got_object_commit_close(commit);
11559 commit = NULL;
11560 if (error)
11561 goto done;
11563 if (STAILQ_EMPTY(&commits)) {
11564 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11565 goto done;
11568 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11569 &base_commit_id, &fileindex, worktree, repo);
11570 if (error)
11571 goto done;
11573 if (edit_script_path) {
11574 error = histedit_load_list(&histedit_cmds,
11575 edit_script_path, repo);
11576 if (error) {
11577 got_worktree_histedit_abort(worktree, fileindex,
11578 repo, branch, base_commit_id,
11579 abort_progress, &upa);
11580 print_merge_progress_stats(&upa);
11581 goto done;
11583 } else {
11584 const char *branch_name;
11585 branch_name = got_ref_get_symref_target(branch);
11586 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11587 branch_name += 11;
11588 error = histedit_edit_script(&histedit_cmds, &commits,
11589 branch_name, edit_logmsg_only, fold_only,
11590 edit_only, repo);
11591 if (error) {
11592 got_worktree_histedit_abort(worktree, fileindex,
11593 repo, branch, base_commit_id,
11594 abort_progress, &upa);
11595 print_merge_progress_stats(&upa);
11596 goto done;
11601 error = histedit_save_list(&histedit_cmds, worktree,
11602 repo);
11603 if (error) {
11604 got_worktree_histedit_abort(worktree, fileindex,
11605 repo, branch, base_commit_id,
11606 abort_progress, &upa);
11607 print_merge_progress_stats(&upa);
11608 goto done;
11613 error = histedit_check_script(&histedit_cmds, &commits, repo);
11614 if (error)
11615 goto done;
11617 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11618 if (resume_commit_id) {
11619 if (got_object_id_cmp(hle->commit_id,
11620 resume_commit_id) != 0)
11621 continue;
11623 resume_commit_id = NULL;
11624 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11625 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11626 error = histedit_skip_commit(hle, worktree,
11627 repo);
11628 if (error)
11629 goto done;
11630 } else {
11631 struct got_pathlist_head paths;
11632 int have_changes = 0;
11634 TAILQ_INIT(&paths);
11635 error = got_pathlist_append(&paths, "", NULL);
11636 if (error)
11637 goto done;
11638 error = got_worktree_status(worktree, &paths,
11639 repo, 0, check_local_changes, &have_changes,
11640 check_cancelled, NULL);
11641 got_pathlist_free(&paths);
11642 if (error) {
11643 if (error->code != GOT_ERR_CANCELLED)
11644 goto done;
11645 if (sigint_received || sigpipe_received)
11646 goto done;
11648 if (have_changes) {
11649 error = histedit_commit(NULL, worktree,
11650 fileindex, tmp_branch, hle, repo);
11651 if (error)
11652 goto done;
11653 } else {
11654 error = got_object_open_as_commit(
11655 &commit, repo, hle->commit_id);
11656 if (error)
11657 goto done;
11658 error = show_histedit_progress(commit,
11659 hle, NULL);
11660 got_object_commit_close(commit);
11661 commit = NULL;
11662 if (error)
11663 goto done;
11666 continue;
11669 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11670 error = histedit_skip_commit(hle, worktree, repo);
11671 if (error)
11672 goto done;
11673 continue;
11676 error = got_object_open_as_commit(&commit, repo,
11677 hle->commit_id);
11678 if (error)
11679 goto done;
11680 parent_ids = got_object_commit_get_parent_ids(commit);
11681 pid = STAILQ_FIRST(parent_ids);
11683 error = got_worktree_histedit_merge_files(&merged_paths,
11684 worktree, fileindex, &pid->id, hle->commit_id, repo,
11685 update_progress, &upa, check_cancelled, NULL);
11686 if (error)
11687 goto done;
11688 got_object_commit_close(commit);
11689 commit = NULL;
11691 print_merge_progress_stats(&upa);
11692 if (upa.conflicts > 0 || upa.missing > 0 ||
11693 upa.not_deleted > 0 || upa.unversioned > 0) {
11694 if (upa.conflicts > 0) {
11695 error = show_rebase_merge_conflict(
11696 hle->commit_id, repo);
11697 if (error)
11698 goto done;
11700 got_worktree_rebase_pathlist_free(&merged_paths);
11701 break;
11704 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11705 char *id_str;
11706 error = got_object_id_str(&id_str, hle->commit_id);
11707 if (error)
11708 goto done;
11709 printf("Stopping histedit for amending commit %s\n",
11710 id_str);
11711 free(id_str);
11712 got_worktree_rebase_pathlist_free(&merged_paths);
11713 error = got_worktree_histedit_postpone(worktree,
11714 fileindex);
11715 goto done;
11718 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11719 error = histedit_skip_commit(hle, worktree, repo);
11720 if (error)
11721 goto done;
11722 continue;
11725 error = histedit_commit(&merged_paths, worktree, fileindex,
11726 tmp_branch, hle, repo);
11727 got_worktree_rebase_pathlist_free(&merged_paths);
11728 if (error)
11729 goto done;
11732 if (upa.conflicts > 0 || upa.missing > 0 ||
11733 upa.not_deleted > 0 || upa.unversioned > 0) {
11734 error = got_worktree_histedit_postpone(worktree, fileindex);
11735 if (error)
11736 goto done;
11737 if (upa.conflicts > 0 && upa.missing == 0 &&
11738 upa.not_deleted == 0 && upa.unversioned == 0) {
11739 error = got_error_msg(GOT_ERR_CONFLICTS,
11740 "conflicts must be resolved before histedit "
11741 "can continue");
11742 } else if (upa.conflicts > 0) {
11743 error = got_error_msg(GOT_ERR_CONFLICTS,
11744 "conflicts must be resolved before histedit "
11745 "can continue; changes destined for some "
11746 "files were not yet merged and should be "
11747 "merged manually if required before the "
11748 "histedit operation is continued");
11749 } else {
11750 error = got_error_msg(GOT_ERR_CONFLICTS,
11751 "changes destined for some files were not "
11752 "yet merged and should be merged manually "
11753 "if required before the histedit operation "
11754 "is continued");
11756 } else
11757 error = histedit_complete(worktree, fileindex, tmp_branch,
11758 branch, repo);
11759 done:
11760 got_object_id_queue_free(&commits);
11761 histedit_free_list(&histedit_cmds);
11762 free(head_commit_id);
11763 free(base_commit_id);
11764 free(resume_commit_id);
11765 if (commit)
11766 got_object_commit_close(commit);
11767 if (branch)
11768 got_ref_close(branch);
11769 if (tmp_branch)
11770 got_ref_close(tmp_branch);
11771 if (worktree)
11772 got_worktree_close(worktree);
11773 if (repo) {
11774 const struct got_error *close_err = got_repo_close(repo);
11775 if (error == NULL)
11776 error = close_err;
11778 if (pack_fds) {
11779 const struct got_error *pack_err =
11780 got_repo_pack_fds_close(pack_fds);
11781 if (error == NULL)
11782 error = pack_err;
11784 return error;
11787 __dead static void
11788 usage_integrate(void)
11790 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11791 exit(1);
11794 static const struct got_error *
11795 cmd_integrate(int argc, char *argv[])
11797 const struct got_error *error = NULL;
11798 struct got_repository *repo = NULL;
11799 struct got_worktree *worktree = NULL;
11800 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11801 const char *branch_arg = NULL;
11802 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11803 struct got_fileindex *fileindex = NULL;
11804 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11805 int ch;
11806 struct got_update_progress_arg upa;
11807 int *pack_fds = NULL;
11809 while ((ch = getopt(argc, argv, "")) != -1) {
11810 switch (ch) {
11811 default:
11812 usage_integrate();
11813 /* NOTREACHED */
11817 argc -= optind;
11818 argv += optind;
11820 if (argc != 1)
11821 usage_integrate();
11822 branch_arg = argv[0];
11823 #ifndef PROFILE
11824 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11825 "unveil", NULL) == -1)
11826 err(1, "pledge");
11827 #endif
11828 cwd = getcwd(NULL, 0);
11829 if (cwd == NULL) {
11830 error = got_error_from_errno("getcwd");
11831 goto done;
11834 error = got_repo_pack_fds_open(&pack_fds);
11835 if (error != NULL)
11836 goto done;
11838 error = got_worktree_open(&worktree, cwd);
11839 if (error) {
11840 if (error->code == GOT_ERR_NOT_WORKTREE)
11841 error = wrap_not_worktree_error(error, "integrate",
11842 cwd);
11843 goto done;
11846 error = check_rebase_or_histedit_in_progress(worktree);
11847 if (error)
11848 goto done;
11850 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11851 NULL, pack_fds);
11852 if (error != NULL)
11853 goto done;
11855 error = apply_unveil(got_repo_get_path(repo), 0,
11856 got_worktree_get_root_path(worktree));
11857 if (error)
11858 goto done;
11860 error = check_merge_in_progress(worktree, repo);
11861 if (error)
11862 goto done;
11864 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11865 error = got_error_from_errno("asprintf");
11866 goto done;
11869 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11870 &base_branch_ref, worktree, refname, repo);
11871 if (error)
11872 goto done;
11874 refname = strdup(got_ref_get_name(branch_ref));
11875 if (refname == NULL) {
11876 error = got_error_from_errno("strdup");
11877 got_worktree_integrate_abort(worktree, fileindex, repo,
11878 branch_ref, base_branch_ref);
11879 goto done;
11881 base_refname = strdup(got_ref_get_name(base_branch_ref));
11882 if (base_refname == NULL) {
11883 error = got_error_from_errno("strdup");
11884 got_worktree_integrate_abort(worktree, fileindex, repo,
11885 branch_ref, base_branch_ref);
11886 goto done;
11889 error = got_ref_resolve(&commit_id, repo, branch_ref);
11890 if (error)
11891 goto done;
11893 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11894 if (error)
11895 goto done;
11897 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11898 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11899 "specified branch has already been integrated");
11900 got_worktree_integrate_abort(worktree, fileindex, repo,
11901 branch_ref, base_branch_ref);
11902 goto done;
11905 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11906 if (error) {
11907 if (error->code == GOT_ERR_ANCESTRY)
11908 error = got_error(GOT_ERR_REBASE_REQUIRED);
11909 got_worktree_integrate_abort(worktree, fileindex, repo,
11910 branch_ref, base_branch_ref);
11911 goto done;
11914 memset(&upa, 0, sizeof(upa));
11915 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11916 branch_ref, base_branch_ref, update_progress, &upa,
11917 check_cancelled, NULL);
11918 if (error)
11919 goto done;
11921 printf("Integrated %s into %s\n", refname, base_refname);
11922 print_update_progress_stats(&upa);
11923 done:
11924 if (repo) {
11925 const struct got_error *close_err = got_repo_close(repo);
11926 if (error == NULL)
11927 error = close_err;
11929 if (worktree)
11930 got_worktree_close(worktree);
11931 if (pack_fds) {
11932 const struct got_error *pack_err =
11933 got_repo_pack_fds_close(pack_fds);
11934 if (error == NULL)
11935 error = pack_err;
11937 free(cwd);
11938 free(base_commit_id);
11939 free(commit_id);
11940 free(refname);
11941 free(base_refname);
11942 return error;
11945 __dead static void
11946 usage_merge(void)
11948 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11949 getprogname());
11950 exit(1);
11953 static const struct got_error *
11954 cmd_merge(int argc, char *argv[])
11956 const struct got_error *error = NULL;
11957 struct got_worktree *worktree = NULL;
11958 struct got_repository *repo = NULL;
11959 struct got_fileindex *fileindex = NULL;
11960 char *cwd = NULL, *id_str = NULL, *author = NULL;
11961 struct got_reference *branch = NULL, *wt_branch = NULL;
11962 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11963 struct got_object_id *wt_branch_tip = NULL;
11964 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11965 int interrupt_merge = 0;
11966 struct got_update_progress_arg upa;
11967 struct got_object_id *merge_commit_id = NULL;
11968 char *branch_name = NULL;
11969 int *pack_fds = NULL;
11971 memset(&upa, 0, sizeof(upa));
11973 while ((ch = getopt(argc, argv, "acn")) != -1) {
11974 switch (ch) {
11975 case 'a':
11976 abort_merge = 1;
11977 break;
11978 case 'c':
11979 continue_merge = 1;
11980 break;
11981 case 'n':
11982 interrupt_merge = 1;
11983 break;
11984 default:
11985 usage_rebase();
11986 /* NOTREACHED */
11990 argc -= optind;
11991 argv += optind;
11993 #ifndef PROFILE
11994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11995 "unveil", NULL) == -1)
11996 err(1, "pledge");
11997 #endif
11999 if (abort_merge && continue_merge)
12000 option_conflict('a', 'c');
12001 if (abort_merge || continue_merge) {
12002 if (argc != 0)
12003 usage_merge();
12004 } else if (argc != 1)
12005 usage_merge();
12007 cwd = getcwd(NULL, 0);
12008 if (cwd == NULL) {
12009 error = got_error_from_errno("getcwd");
12010 goto done;
12013 error = got_repo_pack_fds_open(&pack_fds);
12014 if (error != NULL)
12015 goto done;
12017 error = got_worktree_open(&worktree, cwd);
12018 if (error) {
12019 if (error->code == GOT_ERR_NOT_WORKTREE)
12020 error = wrap_not_worktree_error(error,
12021 "merge", cwd);
12022 goto done;
12025 error = got_repo_open(&repo,
12026 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12027 pack_fds);
12028 if (error != NULL)
12029 goto done;
12031 error = apply_unveil(got_repo_get_path(repo), 0,
12032 worktree ? got_worktree_get_root_path(worktree) : NULL);
12033 if (error)
12034 goto done;
12036 error = check_rebase_or_histedit_in_progress(worktree);
12037 if (error)
12038 goto done;
12040 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12041 repo);
12042 if (error)
12043 goto done;
12045 if (abort_merge) {
12046 if (!merge_in_progress) {
12047 error = got_error(GOT_ERR_NOT_MERGING);
12048 goto done;
12050 error = got_worktree_merge_continue(&branch_name,
12051 &branch_tip, &fileindex, worktree, repo);
12052 if (error)
12053 goto done;
12054 error = got_worktree_merge_abort(worktree, fileindex, repo,
12055 abort_progress, &upa);
12056 if (error)
12057 goto done;
12058 printf("Merge of %s aborted\n", branch_name);
12059 goto done; /* nothing else to do */
12062 error = get_author(&author, repo, worktree);
12063 if (error)
12064 goto done;
12066 if (continue_merge) {
12067 if (!merge_in_progress) {
12068 error = got_error(GOT_ERR_NOT_MERGING);
12069 goto done;
12071 error = got_worktree_merge_continue(&branch_name,
12072 &branch_tip, &fileindex, worktree, repo);
12073 if (error)
12074 goto done;
12075 } else {
12076 error = got_ref_open(&branch, repo, argv[0], 0);
12077 if (error != NULL)
12078 goto done;
12079 branch_name = strdup(got_ref_get_name(branch));
12080 if (branch_name == NULL) {
12081 error = got_error_from_errno("strdup");
12082 goto done;
12084 error = got_ref_resolve(&branch_tip, repo, branch);
12085 if (error)
12086 goto done;
12089 error = got_ref_open(&wt_branch, repo,
12090 got_worktree_get_head_ref_name(worktree), 0);
12091 if (error)
12092 goto done;
12093 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12094 if (error)
12095 goto done;
12096 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12097 wt_branch_tip, branch_tip, 0, repo,
12098 check_cancelled, NULL);
12099 if (error && error->code != GOT_ERR_ANCESTRY)
12100 goto done;
12102 if (!continue_merge) {
12103 error = check_path_prefix(wt_branch_tip, branch_tip,
12104 got_worktree_get_path_prefix(worktree),
12105 GOT_ERR_MERGE_PATH, repo);
12106 if (error)
12107 goto done;
12108 if (yca_id) {
12109 error = check_same_branch(wt_branch_tip, branch,
12110 yca_id, repo);
12111 if (error) {
12112 if (error->code != GOT_ERR_ANCESTRY)
12113 goto done;
12114 error = NULL;
12115 } else {
12116 static char msg[512];
12117 snprintf(msg, sizeof(msg),
12118 "cannot create a merge commit because "
12119 "%s is based on %s; %s can be integrated "
12120 "with 'got integrate' instead", branch_name,
12121 got_worktree_get_head_ref_name(worktree),
12122 branch_name);
12123 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12124 goto done;
12127 error = got_worktree_merge_prepare(&fileindex, worktree,
12128 branch, repo);
12129 if (error)
12130 goto done;
12132 error = got_worktree_merge_branch(worktree, fileindex,
12133 yca_id, branch_tip, repo, update_progress, &upa,
12134 check_cancelled, NULL);
12135 if (error)
12136 goto done;
12137 print_merge_progress_stats(&upa);
12138 if (!upa.did_something) {
12139 error = got_worktree_merge_abort(worktree, fileindex,
12140 repo, abort_progress, &upa);
12141 if (error)
12142 goto done;
12143 printf("Already up-to-date\n");
12144 goto done;
12148 if (interrupt_merge) {
12149 error = got_worktree_merge_postpone(worktree, fileindex);
12150 if (error)
12151 goto done;
12152 printf("Merge of %s interrupted on request\n", branch_name);
12153 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12154 upa.not_deleted > 0 || upa.unversioned > 0) {
12155 error = got_worktree_merge_postpone(worktree, fileindex);
12156 if (error)
12157 goto done;
12158 if (upa.conflicts > 0 && upa.missing == 0 &&
12159 upa.not_deleted == 0 && upa.unversioned == 0) {
12160 error = got_error_msg(GOT_ERR_CONFLICTS,
12161 "conflicts must be resolved before merging "
12162 "can continue");
12163 } else if (upa.conflicts > 0) {
12164 error = got_error_msg(GOT_ERR_CONFLICTS,
12165 "conflicts must be resolved before merging "
12166 "can continue; changes destined for some "
12167 "files were not yet merged and "
12168 "should be merged manually if required before the "
12169 "merge operation is continued");
12170 } else {
12171 error = got_error_msg(GOT_ERR_CONFLICTS,
12172 "changes destined for some "
12173 "files were not yet merged and should be "
12174 "merged manually if required before the "
12175 "merge operation is continued");
12177 goto done;
12178 } else {
12179 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12180 fileindex, author, NULL, 1, branch_tip, branch_name,
12181 repo, continue_merge ? print_status : NULL, NULL);
12182 if (error)
12183 goto done;
12184 error = got_worktree_merge_complete(worktree, fileindex, repo);
12185 if (error)
12186 goto done;
12187 error = got_object_id_str(&id_str, merge_commit_id);
12188 if (error)
12189 goto done;
12190 printf("Merged %s into %s: %s\n", branch_name,
12191 got_worktree_get_head_ref_name(worktree),
12192 id_str);
12195 done:
12196 free(id_str);
12197 free(merge_commit_id);
12198 free(author);
12199 free(branch_tip);
12200 free(branch_name);
12201 free(yca_id);
12202 if (branch)
12203 got_ref_close(branch);
12204 if (wt_branch)
12205 got_ref_close(wt_branch);
12206 if (worktree)
12207 got_worktree_close(worktree);
12208 if (repo) {
12209 const struct got_error *close_err = got_repo_close(repo);
12210 if (error == NULL)
12211 error = close_err;
12213 if (pack_fds) {
12214 const struct got_error *pack_err =
12215 got_repo_pack_fds_close(pack_fds);
12216 if (error == NULL)
12217 error = pack_err;
12219 return error;
12222 __dead static void
12223 usage_stage(void)
12225 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12226 "[-S] [file-path ...]\n",
12227 getprogname());
12228 exit(1);
12231 static const struct got_error *
12232 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12233 const char *path, struct got_object_id *blob_id,
12234 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12235 int dirfd, const char *de_name)
12237 const struct got_error *err = NULL;
12238 char *id_str = NULL;
12240 if (staged_status != GOT_STATUS_ADD &&
12241 staged_status != GOT_STATUS_MODIFY &&
12242 staged_status != GOT_STATUS_DELETE)
12243 return NULL;
12245 if (staged_status == GOT_STATUS_ADD ||
12246 staged_status == GOT_STATUS_MODIFY)
12247 err = got_object_id_str(&id_str, staged_blob_id);
12248 else
12249 err = got_object_id_str(&id_str, blob_id);
12250 if (err)
12251 return err;
12253 printf("%s %c %s\n", id_str, staged_status, path);
12254 free(id_str);
12255 return NULL;
12258 static const struct got_error *
12259 cmd_stage(int argc, char *argv[])
12261 const struct got_error *error = NULL;
12262 struct got_repository *repo = NULL;
12263 struct got_worktree *worktree = NULL;
12264 char *cwd = NULL;
12265 struct got_pathlist_head paths;
12266 struct got_pathlist_entry *pe;
12267 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12268 FILE *patch_script_file = NULL;
12269 const char *patch_script_path = NULL;
12270 struct choose_patch_arg cpa;
12271 int *pack_fds = NULL;
12273 TAILQ_INIT(&paths);
12275 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12276 switch (ch) {
12277 case 'l':
12278 list_stage = 1;
12279 break;
12280 case 'p':
12281 pflag = 1;
12282 break;
12283 case 'F':
12284 patch_script_path = optarg;
12285 break;
12286 case 'S':
12287 allow_bad_symlinks = 1;
12288 break;
12289 default:
12290 usage_stage();
12291 /* NOTREACHED */
12295 argc -= optind;
12296 argv += optind;
12298 #ifndef PROFILE
12299 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12300 "unveil", NULL) == -1)
12301 err(1, "pledge");
12302 #endif
12303 if (list_stage && (pflag || patch_script_path))
12304 errx(1, "-l option cannot be used with other options");
12305 if (patch_script_path && !pflag)
12306 errx(1, "-F option can only be used together with -p option");
12308 cwd = getcwd(NULL, 0);
12309 if (cwd == NULL) {
12310 error = got_error_from_errno("getcwd");
12311 goto done;
12314 error = got_repo_pack_fds_open(&pack_fds);
12315 if (error != NULL)
12316 goto done;
12318 error = got_worktree_open(&worktree, cwd);
12319 if (error) {
12320 if (error->code == GOT_ERR_NOT_WORKTREE)
12321 error = wrap_not_worktree_error(error, "stage", cwd);
12322 goto done;
12325 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12326 NULL, pack_fds);
12327 if (error != NULL)
12328 goto done;
12330 if (patch_script_path) {
12331 patch_script_file = fopen(patch_script_path, "re");
12332 if (patch_script_file == NULL) {
12333 error = got_error_from_errno2("fopen",
12334 patch_script_path);
12335 goto done;
12338 error = apply_unveil(got_repo_get_path(repo), 0,
12339 got_worktree_get_root_path(worktree));
12340 if (error)
12341 goto done;
12343 error = check_merge_in_progress(worktree, repo);
12344 if (error)
12345 goto done;
12347 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12348 if (error)
12349 goto done;
12351 if (list_stage)
12352 error = got_worktree_status(worktree, &paths, repo, 0,
12353 print_stage, NULL, check_cancelled, NULL);
12354 else {
12355 cpa.patch_script_file = patch_script_file;
12356 cpa.action = "stage";
12357 error = got_worktree_stage(worktree, &paths,
12358 pflag ? NULL : print_status, NULL,
12359 pflag ? choose_patch : NULL, &cpa,
12360 allow_bad_symlinks, repo);
12362 done:
12363 if (patch_script_file && fclose(patch_script_file) == EOF &&
12364 error == NULL)
12365 error = got_error_from_errno2("fclose", patch_script_path);
12366 if (repo) {
12367 const struct got_error *close_err = got_repo_close(repo);
12368 if (error == NULL)
12369 error = close_err;
12371 if (worktree)
12372 got_worktree_close(worktree);
12373 if (pack_fds) {
12374 const struct got_error *pack_err =
12375 got_repo_pack_fds_close(pack_fds);
12376 if (error == NULL)
12377 error = pack_err;
12379 TAILQ_FOREACH(pe, &paths, entry)
12380 free((char *)pe->path);
12381 got_pathlist_free(&paths);
12382 free(cwd);
12383 return error;
12386 __dead static void
12387 usage_unstage(void)
12389 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12390 "[file-path ...]\n",
12391 getprogname());
12392 exit(1);
12396 static const struct got_error *
12397 cmd_unstage(int argc, char *argv[])
12399 const struct got_error *error = NULL;
12400 struct got_repository *repo = NULL;
12401 struct got_worktree *worktree = NULL;
12402 char *cwd = NULL;
12403 struct got_pathlist_head paths;
12404 struct got_pathlist_entry *pe;
12405 int ch, pflag = 0;
12406 struct got_update_progress_arg upa;
12407 FILE *patch_script_file = NULL;
12408 const char *patch_script_path = NULL;
12409 struct choose_patch_arg cpa;
12410 int *pack_fds = NULL;
12412 TAILQ_INIT(&paths);
12414 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12415 switch (ch) {
12416 case 'p':
12417 pflag = 1;
12418 break;
12419 case 'F':
12420 patch_script_path = optarg;
12421 break;
12422 default:
12423 usage_unstage();
12424 /* NOTREACHED */
12428 argc -= optind;
12429 argv += optind;
12431 #ifndef PROFILE
12432 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12433 "unveil", NULL) == -1)
12434 err(1, "pledge");
12435 #endif
12436 if (patch_script_path && !pflag)
12437 errx(1, "-F option can only be used together with -p option");
12439 cwd = getcwd(NULL, 0);
12440 if (cwd == NULL) {
12441 error = got_error_from_errno("getcwd");
12442 goto done;
12445 error = got_repo_pack_fds_open(&pack_fds);
12446 if (error != NULL)
12447 goto done;
12449 error = got_worktree_open(&worktree, cwd);
12450 if (error) {
12451 if (error->code == GOT_ERR_NOT_WORKTREE)
12452 error = wrap_not_worktree_error(error, "unstage", cwd);
12453 goto done;
12456 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12457 NULL, pack_fds);
12458 if (error != NULL)
12459 goto done;
12461 if (patch_script_path) {
12462 patch_script_file = fopen(patch_script_path, "re");
12463 if (patch_script_file == NULL) {
12464 error = got_error_from_errno2("fopen",
12465 patch_script_path);
12466 goto done;
12470 error = apply_unveil(got_repo_get_path(repo), 0,
12471 got_worktree_get_root_path(worktree));
12472 if (error)
12473 goto done;
12475 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12476 if (error)
12477 goto done;
12479 cpa.patch_script_file = patch_script_file;
12480 cpa.action = "unstage";
12481 memset(&upa, 0, sizeof(upa));
12482 error = got_worktree_unstage(worktree, &paths, update_progress,
12483 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12484 if (!error)
12485 print_merge_progress_stats(&upa);
12486 done:
12487 if (patch_script_file && fclose(patch_script_file) == EOF &&
12488 error == NULL)
12489 error = got_error_from_errno2("fclose", patch_script_path);
12490 if (repo) {
12491 const struct got_error *close_err = got_repo_close(repo);
12492 if (error == NULL)
12493 error = close_err;
12495 if (worktree)
12496 got_worktree_close(worktree);
12497 if (pack_fds) {
12498 const struct got_error *pack_err =
12499 got_repo_pack_fds_close(pack_fds);
12500 if (error == NULL)
12501 error = pack_err;
12503 TAILQ_FOREACH(pe, &paths, entry)
12504 free((char *)pe->path);
12505 got_pathlist_free(&paths);
12506 free(cwd);
12507 return error;
12510 __dead static void
12511 usage_cat(void)
12513 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12514 "arg1 [arg2 ...]\n", getprogname());
12515 exit(1);
12518 static const struct got_error *
12519 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12521 const struct got_error *err;
12522 struct got_blob_object *blob;
12523 int fd = -1;
12525 fd = got_opentempfd();
12526 if (fd == -1)
12527 return got_error_from_errno("got_opentempfd");
12529 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12530 if (err)
12531 goto done;
12533 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12534 done:
12535 if (fd != -1 && close(fd) == -1 && err == NULL)
12536 err = got_error_from_errno("close");
12537 if (blob)
12538 got_object_blob_close(blob);
12539 return err;
12542 static const struct got_error *
12543 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12545 const struct got_error *err;
12546 struct got_tree_object *tree;
12547 int nentries, i;
12549 err = got_object_open_as_tree(&tree, repo, id);
12550 if (err)
12551 return err;
12553 nentries = got_object_tree_get_nentries(tree);
12554 for (i = 0; i < nentries; i++) {
12555 struct got_tree_entry *te;
12556 char *id_str;
12557 if (sigint_received || sigpipe_received)
12558 break;
12559 te = got_object_tree_get_entry(tree, i);
12560 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12561 if (err)
12562 break;
12563 fprintf(outfile, "%s %.7o %s\n", id_str,
12564 got_tree_entry_get_mode(te),
12565 got_tree_entry_get_name(te));
12566 free(id_str);
12569 got_object_tree_close(tree);
12570 return err;
12573 static const struct got_error *
12574 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12576 const struct got_error *err;
12577 struct got_commit_object *commit;
12578 const struct got_object_id_queue *parent_ids;
12579 struct got_object_qid *pid;
12580 char *id_str = NULL;
12581 const char *logmsg = NULL;
12582 char gmtoff[6];
12584 err = got_object_open_as_commit(&commit, repo, id);
12585 if (err)
12586 return err;
12588 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12589 if (err)
12590 goto done;
12592 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12593 parent_ids = got_object_commit_get_parent_ids(commit);
12594 fprintf(outfile, "numparents %d\n",
12595 got_object_commit_get_nparents(commit));
12596 STAILQ_FOREACH(pid, parent_ids, entry) {
12597 char *pid_str;
12598 err = got_object_id_str(&pid_str, &pid->id);
12599 if (err)
12600 goto done;
12601 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12602 free(pid_str);
12604 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12605 got_object_commit_get_author_gmtoff(commit));
12606 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12607 got_object_commit_get_author(commit),
12608 (long long)got_object_commit_get_author_time(commit),
12609 gmtoff);
12611 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12612 got_object_commit_get_committer_gmtoff(commit));
12613 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12614 got_object_commit_get_author(commit),
12615 (long long)got_object_commit_get_committer_time(commit),
12616 gmtoff);
12618 logmsg = got_object_commit_get_logmsg_raw(commit);
12619 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12620 fprintf(outfile, "%s", logmsg);
12621 done:
12622 free(id_str);
12623 got_object_commit_close(commit);
12624 return err;
12627 static const struct got_error *
12628 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12630 const struct got_error *err;
12631 struct got_tag_object *tag;
12632 char *id_str = NULL;
12633 const char *tagmsg = NULL;
12634 char gmtoff[6];
12636 err = got_object_open_as_tag(&tag, repo, id);
12637 if (err)
12638 return err;
12640 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12641 if (err)
12642 goto done;
12644 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12646 switch (got_object_tag_get_object_type(tag)) {
12647 case GOT_OBJ_TYPE_BLOB:
12648 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12649 GOT_OBJ_LABEL_BLOB);
12650 break;
12651 case GOT_OBJ_TYPE_TREE:
12652 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12653 GOT_OBJ_LABEL_TREE);
12654 break;
12655 case GOT_OBJ_TYPE_COMMIT:
12656 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12657 GOT_OBJ_LABEL_COMMIT);
12658 break;
12659 case GOT_OBJ_TYPE_TAG:
12660 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12661 GOT_OBJ_LABEL_TAG);
12662 break;
12663 default:
12664 break;
12667 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12668 got_object_tag_get_name(tag));
12670 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12671 got_object_tag_get_tagger_gmtoff(tag));
12672 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12673 got_object_tag_get_tagger(tag),
12674 (long long)got_object_tag_get_tagger_time(tag),
12675 gmtoff);
12677 tagmsg = got_object_tag_get_message(tag);
12678 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12679 fprintf(outfile, "%s", tagmsg);
12680 done:
12681 free(id_str);
12682 got_object_tag_close(tag);
12683 return err;
12686 static const struct got_error *
12687 cmd_cat(int argc, char *argv[])
12689 const struct got_error *error;
12690 struct got_repository *repo = NULL;
12691 struct got_worktree *worktree = NULL;
12692 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12693 const char *commit_id_str = NULL;
12694 struct got_object_id *id = NULL, *commit_id = NULL;
12695 struct got_commit_object *commit = NULL;
12696 int ch, obj_type, i, force_path = 0;
12697 struct got_reflist_head refs;
12698 int *pack_fds = NULL;
12700 TAILQ_INIT(&refs);
12702 #ifndef PROFILE
12703 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12704 NULL) == -1)
12705 err(1, "pledge");
12706 #endif
12708 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12709 switch (ch) {
12710 case 'c':
12711 commit_id_str = optarg;
12712 break;
12713 case 'r':
12714 repo_path = realpath(optarg, NULL);
12715 if (repo_path == NULL)
12716 return got_error_from_errno2("realpath",
12717 optarg);
12718 got_path_strip_trailing_slashes(repo_path);
12719 break;
12720 case 'P':
12721 force_path = 1;
12722 break;
12723 default:
12724 usage_cat();
12725 /* NOTREACHED */
12729 argc -= optind;
12730 argv += optind;
12732 cwd = getcwd(NULL, 0);
12733 if (cwd == NULL) {
12734 error = got_error_from_errno("getcwd");
12735 goto done;
12738 error = got_repo_pack_fds_open(&pack_fds);
12739 if (error != NULL)
12740 goto done;
12742 if (repo_path == NULL) {
12743 error = got_worktree_open(&worktree, cwd);
12744 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12745 goto done;
12746 if (worktree) {
12747 repo_path = strdup(
12748 got_worktree_get_repo_path(worktree));
12749 if (repo_path == NULL) {
12750 error = got_error_from_errno("strdup");
12751 goto done;
12754 /* Release work tree lock. */
12755 got_worktree_close(worktree);
12756 worktree = NULL;
12760 if (repo_path == NULL) {
12761 repo_path = strdup(cwd);
12762 if (repo_path == NULL)
12763 return got_error_from_errno("strdup");
12766 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12767 free(repo_path);
12768 if (error != NULL)
12769 goto done;
12771 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12772 if (error)
12773 goto done;
12775 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12776 if (error)
12777 goto done;
12779 if (commit_id_str == NULL)
12780 commit_id_str = GOT_REF_HEAD;
12781 error = got_repo_match_object_id(&commit_id, NULL,
12782 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12783 if (error)
12784 goto done;
12786 error = got_object_open_as_commit(&commit, repo, commit_id);
12787 if (error)
12788 goto done;
12790 for (i = 0; i < argc; i++) {
12791 if (force_path) {
12792 error = got_object_id_by_path(&id, repo, commit,
12793 argv[i]);
12794 if (error)
12795 break;
12796 } else {
12797 error = got_repo_match_object_id(&id, &label, argv[i],
12798 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12799 repo);
12800 if (error) {
12801 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12802 error->code != GOT_ERR_NOT_REF)
12803 break;
12804 error = got_object_id_by_path(&id, repo,
12805 commit, argv[i]);
12806 if (error)
12807 break;
12811 error = got_object_get_type(&obj_type, repo, id);
12812 if (error)
12813 break;
12815 switch (obj_type) {
12816 case GOT_OBJ_TYPE_BLOB:
12817 error = cat_blob(id, repo, stdout);
12818 break;
12819 case GOT_OBJ_TYPE_TREE:
12820 error = cat_tree(id, repo, stdout);
12821 break;
12822 case GOT_OBJ_TYPE_COMMIT:
12823 error = cat_commit(id, repo, stdout);
12824 break;
12825 case GOT_OBJ_TYPE_TAG:
12826 error = cat_tag(id, repo, stdout);
12827 break;
12828 default:
12829 error = got_error(GOT_ERR_OBJ_TYPE);
12830 break;
12832 if (error)
12833 break;
12834 free(label);
12835 label = NULL;
12836 free(id);
12837 id = NULL;
12839 done:
12840 free(label);
12841 free(id);
12842 free(commit_id);
12843 if (commit)
12844 got_object_commit_close(commit);
12845 if (worktree)
12846 got_worktree_close(worktree);
12847 if (repo) {
12848 const struct got_error *close_err = got_repo_close(repo);
12849 if (error == NULL)
12850 error = close_err;
12852 if (pack_fds) {
12853 const struct got_error *pack_err =
12854 got_repo_pack_fds_close(pack_fds);
12855 if (error == NULL)
12856 error = pack_err;
12859 got_ref_list_free(&refs);
12860 return error;
12863 __dead static void
12864 usage_info(void)
12866 fprintf(stderr, "usage: %s info [path ...]\n",
12867 getprogname());
12868 exit(1);
12871 static const struct got_error *
12872 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12873 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12874 struct got_object_id *commit_id)
12876 const struct got_error *err = NULL;
12877 char *id_str = NULL;
12878 char datebuf[128];
12879 struct tm mytm, *tm;
12880 struct got_pathlist_head *paths = arg;
12881 struct got_pathlist_entry *pe;
12884 * Clear error indication from any of the path arguments which
12885 * would cause this file index entry to be displayed.
12887 TAILQ_FOREACH(pe, paths, entry) {
12888 if (got_path_cmp(path, pe->path, strlen(path),
12889 pe->path_len) == 0 ||
12890 got_path_is_child(path, pe->path, pe->path_len))
12891 pe->data = NULL; /* no error */
12894 printf(GOT_COMMIT_SEP_STR);
12895 if (S_ISLNK(mode))
12896 printf("symlink: %s\n", path);
12897 else if (S_ISREG(mode)) {
12898 printf("file: %s\n", path);
12899 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12900 } else if (S_ISDIR(mode))
12901 printf("directory: %s\n", path);
12902 else
12903 printf("something: %s\n", path);
12905 tm = localtime_r(&mtime, &mytm);
12906 if (tm == NULL)
12907 return NULL;
12908 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12909 return got_error(GOT_ERR_NO_SPACE);
12910 printf("timestamp: %s\n", datebuf);
12912 if (blob_id) {
12913 err = got_object_id_str(&id_str, blob_id);
12914 if (err)
12915 return err;
12916 printf("based on blob: %s\n", id_str);
12917 free(id_str);
12920 if (staged_blob_id) {
12921 err = got_object_id_str(&id_str, staged_blob_id);
12922 if (err)
12923 return err;
12924 printf("based on staged blob: %s\n", id_str);
12925 free(id_str);
12928 if (commit_id) {
12929 err = got_object_id_str(&id_str, commit_id);
12930 if (err)
12931 return err;
12932 printf("based on commit: %s\n", id_str);
12933 free(id_str);
12936 return NULL;
12939 static const struct got_error *
12940 cmd_info(int argc, char *argv[])
12942 const struct got_error *error = NULL;
12943 struct got_worktree *worktree = NULL;
12944 char *cwd = NULL, *id_str = NULL;
12945 struct got_pathlist_head paths;
12946 struct got_pathlist_entry *pe;
12947 char *uuidstr = NULL;
12948 int ch, show_files = 0;
12949 int *pack_fds = NULL;
12951 TAILQ_INIT(&paths);
12953 while ((ch = getopt(argc, argv, "")) != -1) {
12954 switch (ch) {
12955 default:
12956 usage_info();
12957 /* NOTREACHED */
12961 argc -= optind;
12962 argv += optind;
12964 #ifndef PROFILE
12965 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12966 NULL) == -1)
12967 err(1, "pledge");
12968 #endif
12969 cwd = getcwd(NULL, 0);
12970 if (cwd == NULL) {
12971 error = got_error_from_errno("getcwd");
12972 goto done;
12975 error = got_repo_pack_fds_open(&pack_fds);
12976 if (error != NULL)
12977 goto done;
12979 error = got_worktree_open(&worktree, cwd);
12980 if (error) {
12981 if (error->code == GOT_ERR_NOT_WORKTREE)
12982 error = wrap_not_worktree_error(error, "info", cwd);
12983 goto done;
12986 #ifndef PROFILE
12987 /* Remove "cpath" promise. */
12988 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12989 NULL) == -1)
12990 err(1, "pledge");
12991 #endif
12992 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12993 if (error)
12994 goto done;
12996 if (argc >= 1) {
12997 error = get_worktree_paths_from_argv(&paths, argc, argv,
12998 worktree);
12999 if (error)
13000 goto done;
13001 show_files = 1;
13004 error = got_object_id_str(&id_str,
13005 got_worktree_get_base_commit_id(worktree));
13006 if (error)
13007 goto done;
13009 error = got_worktree_get_uuid(&uuidstr, worktree);
13010 if (error)
13011 goto done;
13013 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13014 printf("work tree base commit: %s\n", id_str);
13015 printf("work tree path prefix: %s\n",
13016 got_worktree_get_path_prefix(worktree));
13017 printf("work tree branch reference: %s\n",
13018 got_worktree_get_head_ref_name(worktree));
13019 printf("work tree UUID: %s\n", uuidstr);
13020 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13022 if (show_files) {
13023 struct got_pathlist_entry *pe;
13024 TAILQ_FOREACH(pe, &paths, entry) {
13025 if (pe->path_len == 0)
13026 continue;
13028 * Assume this path will fail. This will be corrected
13029 * in print_path_info() in case the path does suceeed.
13031 pe->data = (void *)got_error_path(pe->path,
13032 GOT_ERR_BAD_PATH);
13034 error = got_worktree_path_info(worktree, &paths,
13035 print_path_info, &paths, check_cancelled, NULL);
13036 if (error)
13037 goto done;
13038 TAILQ_FOREACH(pe, &paths, entry) {
13039 if (pe->data != NULL) {
13040 error = pe->data; /* bad path */
13041 break;
13045 done:
13046 if (pack_fds) {
13047 const struct got_error *pack_err =
13048 got_repo_pack_fds_close(pack_fds);
13049 if (error == NULL)
13050 error = pack_err;
13052 TAILQ_FOREACH(pe, &paths, entry)
13053 free((char *)pe->path);
13054 got_pathlist_free(&paths);
13055 free(cwd);
13056 free(id_str);
13057 free(uuidstr);
13058 return error;