Blob


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