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 "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.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 [-hV] 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("/usr/bin/vi");
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] [-I pattern] [-m message] "
351 "[-r repository-path] directory\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 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
394 const struct got_error *err = NULL;
395 char *line = NULL;
396 size_t linesize = 0;
398 *logmsg = NULL;
399 *len = 0;
401 if (fseeko(fp, 0L, SEEK_SET) == -1)
402 return got_error_from_errno("fseeko");
404 *logmsg = malloc(filesize + 1);
405 if (*logmsg == NULL)
406 return got_error_from_errno("malloc");
407 (*logmsg)[0] = '\0';
409 while (getline(&line, &linesize, fp) != -1) {
410 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
411 continue; /* remove comments and leading empty lines */
412 *len = strlcat(*logmsg, line, filesize + 1);
413 if (*len >= filesize + 1) {
414 err = got_error(GOT_ERR_NO_SPACE);
415 goto done;
418 if (ferror(fp)) {
419 err = got_ferror(fp, GOT_ERR_IO);
420 goto done;
423 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
424 (*logmsg)[*len - 1] = '\0';
425 (*len)--;
427 done:
428 free(line);
429 if (err) {
430 free(*logmsg);
431 *logmsg = NULL;
432 *len = 0;
434 return err;
437 static const struct got_error *
438 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
439 const char *initial_content, size_t initial_content_len,
440 int require_modification)
442 const struct got_error *err = NULL;
443 struct stat st, st2;
444 FILE *fp = NULL;
445 size_t logmsg_len;
447 *logmsg = NULL;
449 if (stat(logmsg_path, &st) == -1)
450 return got_error_from_errno2("stat", logmsg_path);
452 if (spawn_editor(editor, logmsg_path) == -1)
453 return got_error_from_errno("failed spawning editor");
455 if (require_modification) {
456 struct timespec timeout;
458 timeout.tv_sec = 0;
459 timeout.tv_nsec = 1;
460 nanosleep(&timeout, NULL);
463 if (stat(logmsg_path, &st2) == -1)
464 return got_error_from_errno("stat");
466 if (require_modification && st.st_size == st2.st_size &&
467 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
468 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
469 "no changes made to commit message, aborting");
471 fp = fopen(logmsg_path, "re");
472 if (fp == NULL) {
473 err = got_error_from_errno("fopen");
474 goto done;
477 /* strip comments and leading/trailing newlines */
478 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
479 if (err)
480 goto done;
481 if (logmsg_len == 0) {
482 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
483 "commit message cannot be empty, aborting");
484 goto done;
486 done:
487 if (fp && fclose(fp) == EOF && err == NULL)
488 err = got_error_from_errno("fclose");
489 if (err) {
490 free(*logmsg);
491 *logmsg = NULL;
493 return err;
496 static const struct got_error *
497 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
498 const char *path_dir, const char *branch_name)
500 char *initial_content = NULL;
501 const struct got_error *err = NULL;
502 int initial_content_len;
503 int fd = -1;
505 initial_content_len = asprintf(&initial_content,
506 "\n# %s to be imported to branch %s\n", path_dir,
507 branch_name);
508 if (initial_content_len == -1)
509 return got_error_from_errno("asprintf");
511 err = got_opentemp_named_fd(logmsg_path, &fd,
512 GOT_TMPDIR_STR "/got-importmsg", "");
513 if (err)
514 goto done;
516 if (write(fd, initial_content, initial_content_len) == -1) {
517 err = got_error_from_errno2("write", *logmsg_path);
518 goto done;
520 if (close(fd) == -1) {
521 err = got_error_from_errno2("close", *logmsg_path);
522 goto done;
524 fd = -1;
526 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
527 initial_content_len, 1);
528 done:
529 if (fd != -1 && close(fd) == -1 && err == NULL)
530 err = got_error_from_errno2("close", *logmsg_path);
531 free(initial_content);
532 if (err) {
533 free(*logmsg_path);
534 *logmsg_path = NULL;
536 return err;
539 static const struct got_error *
540 import_progress(void *arg, const char *path)
542 printf("A %s\n", path);
543 return NULL;
546 static const struct got_error *
547 valid_author(const char *author)
549 const char *email = author;
551 /*
552 * Git' expects the author (or committer) to be in the form
553 * "name <email>", which are mostly free form (see the
554 * "committer" description in git-fast-import(1)). We're only
555 * doing this to avoid git's object parser breaking on commits
556 * we create.
557 */
559 while (*author && *author != '\n' && *author != '<' && *author != '>')
560 author++;
561 if (author != email && *author == '<' && *(author - 1) != ' ')
562 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
563 "between author name and email required", email);
564 if (*author++ != '<')
565 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
566 while (*author && *author != '\n' && *author != '<' && *author != '>')
567 author++;
568 if (strcmp(author, ">") != 0)
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 return NULL;
573 static const struct got_error *
574 get_author(char **author, struct got_repository *repo,
575 struct got_worktree *worktree)
577 const struct got_error *err = NULL;
578 const char *got_author = NULL, *name, *email;
579 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
581 *author = NULL;
583 if (worktree)
584 worktree_conf = got_worktree_get_gotconfig(worktree);
585 repo_conf = got_repo_get_gotconfig(repo);
587 /*
588 * Priority of potential author information sources, from most
589 * significant to least significant:
590 * 1) work tree's .got/got.conf file
591 * 2) repository's got.conf file
592 * 3) repository's git config file
593 * 4) environment variables
594 * 5) global git config files (in user's home directory or /etc)
595 */
597 if (worktree_conf)
598 got_author = got_gotconfig_get_author(worktree_conf);
599 if (got_author == NULL)
600 got_author = got_gotconfig_get_author(repo_conf);
601 if (got_author == NULL) {
602 name = got_repo_get_gitconfig_author_name(repo);
603 email = got_repo_get_gitconfig_author_email(repo);
604 if (name && email) {
605 if (asprintf(author, "%s <%s>", name, email) == -1)
606 return got_error_from_errno("asprintf");
607 return NULL;
610 got_author = getenv("GOT_AUTHOR");
611 if (got_author == NULL) {
612 name = got_repo_get_global_gitconfig_author_name(repo);
613 email = got_repo_get_global_gitconfig_author_email(
614 repo);
615 if (name && email) {
616 if (asprintf(author, "%s <%s>", name, email)
617 == -1)
618 return got_error_from_errno("asprintf");
619 return NULL;
621 /* TODO: Look up user in password database? */
622 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
626 *author = strdup(got_author);
627 if (*author == NULL)
628 return got_error_from_errno("strdup");
630 err = valid_author(*author);
631 if (err) {
632 free(*author);
633 *author = NULL;
635 return err;
638 static const struct got_error *
639 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
640 struct got_worktree *worktree)
642 const char *got_allowed_signers = NULL;
643 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
645 *allowed_signers = NULL;
647 if (worktree)
648 worktree_conf = got_worktree_get_gotconfig(worktree);
649 repo_conf = got_repo_get_gotconfig(repo);
651 /*
652 * Priority of potential author information sources, from most
653 * significant to least significant:
654 * 1) work tree's .got/got.conf file
655 * 2) repository's got.conf file
656 */
658 if (worktree_conf)
659 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
660 worktree_conf);
661 if (got_allowed_signers == NULL)
662 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
663 repo_conf);
665 if (got_allowed_signers) {
666 *allowed_signers = strdup(got_allowed_signers);
667 if (*allowed_signers == NULL)
668 return got_error_from_errno("strdup");
670 return NULL;
673 static const struct got_error *
674 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
675 struct got_worktree *worktree)
677 const char *got_revoked_signers = NULL;
678 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
680 *revoked_signers = NULL;
682 if (worktree)
683 worktree_conf = got_worktree_get_gotconfig(worktree);
684 repo_conf = got_repo_get_gotconfig(repo);
686 /*
687 * Priority of potential author information sources, from most
688 * significant to least significant:
689 * 1) work tree's .got/got.conf file
690 * 2) repository's got.conf file
691 */
693 if (worktree_conf)
694 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
695 worktree_conf);
696 if (got_revoked_signers == NULL)
697 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
698 repo_conf);
700 if (got_revoked_signers) {
701 *revoked_signers = strdup(got_revoked_signers);
702 if (*revoked_signers == NULL)
703 return got_error_from_errno("strdup");
705 return NULL;
708 static const char *
709 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
711 const char *got_signer_id = NULL;
712 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
714 if (worktree)
715 worktree_conf = got_worktree_get_gotconfig(worktree);
716 repo_conf = got_repo_get_gotconfig(repo);
718 /*
719 * Priority of potential author information sources, from most
720 * significant to least significant:
721 * 1) work tree's .got/got.conf file
722 * 2) repository's got.conf file
723 */
725 if (worktree_conf)
726 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
727 if (got_signer_id == NULL)
728 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
730 return got_signer_id;
733 static const struct got_error *
734 get_gitconfig_path(char **gitconfig_path)
736 const char *homedir = getenv("HOME");
738 *gitconfig_path = NULL;
739 if (homedir) {
740 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
741 return got_error_from_errno("asprintf");
744 return NULL;
747 static const struct got_error *
748 cmd_import(int argc, char *argv[])
750 const struct got_error *error = NULL;
751 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
752 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
753 const char *branch_name = NULL;
754 char *id_str = NULL, *logmsg_path = NULL;
755 char refname[PATH_MAX] = "refs/heads/";
756 struct got_repository *repo = NULL;
757 struct got_reference *branch_ref = NULL, *head_ref = NULL;
758 struct got_object_id *new_commit_id = NULL;
759 int ch, n = 0;
760 struct got_pathlist_head ignores;
761 struct got_pathlist_entry *pe;
762 int preserve_logmsg = 0;
763 int *pack_fds = NULL;
765 TAILQ_INIT(&ignores);
767 #ifndef PROFILE
768 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
769 "unveil",
770 NULL) == -1)
771 err(1, "pledge");
772 #endif
774 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
775 switch (ch) {
776 case 'b':
777 branch_name = optarg;
778 break;
779 case 'I':
780 if (optarg[0] == '\0')
781 break;
782 error = got_pathlist_insert(&pe, &ignores, optarg,
783 NULL);
784 if (error)
785 goto done;
786 break;
787 case 'm':
788 logmsg = strdup(optarg);
789 if (logmsg == NULL) {
790 error = got_error_from_errno("strdup");
791 goto done;
793 break;
794 case 'r':
795 repo_path = realpath(optarg, NULL);
796 if (repo_path == NULL) {
797 error = got_error_from_errno2("realpath",
798 optarg);
799 goto done;
801 break;
802 default:
803 usage_import();
804 /* NOTREACHED */
808 argc -= optind;
809 argv += optind;
811 if (argc != 1)
812 usage_import();
814 if (repo_path == NULL) {
815 repo_path = getcwd(NULL, 0);
816 if (repo_path == NULL)
817 return got_error_from_errno("getcwd");
819 got_path_strip_trailing_slashes(repo_path);
820 error = get_gitconfig_path(&gitconfig_path);
821 if (error)
822 goto done;
823 error = got_repo_pack_fds_open(&pack_fds);
824 if (error != NULL)
825 goto done;
826 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
827 if (error)
828 goto done;
830 error = get_author(&author, repo, NULL);
831 if (error)
832 return error;
834 /*
835 * Don't let the user create a branch name with a leading '-'.
836 * While technically a valid reference name, this case is usually
837 * an unintended typo.
838 */
839 if (branch_name && branch_name[0] == '-')
840 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
842 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
843 if (error && error->code != GOT_ERR_NOT_REF)
844 goto done;
846 if (branch_name)
847 n = strlcat(refname, branch_name, sizeof(refname));
848 else if (head_ref && got_ref_is_symbolic(head_ref))
849 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
850 sizeof(refname));
851 else
852 n = strlcat(refname, "main", sizeof(refname));
853 if (n >= sizeof(refname)) {
854 error = got_error(GOT_ERR_NO_SPACE);
855 goto done;
858 error = got_ref_open(&branch_ref, repo, refname, 0);
859 if (error) {
860 if (error->code != GOT_ERR_NOT_REF)
861 goto done;
862 } else {
863 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
864 "import target branch already exists");
865 goto done;
868 path_dir = realpath(argv[0], NULL);
869 if (path_dir == NULL) {
870 error = got_error_from_errno2("realpath", argv[0]);
871 goto done;
873 got_path_strip_trailing_slashes(path_dir);
875 /*
876 * unveil(2) traverses exec(2); if an editor is used we have
877 * to apply unveil after the log message has been written.
878 */
879 if (logmsg == NULL || strlen(logmsg) == 0) {
880 error = get_editor(&editor);
881 if (error)
882 goto done;
883 free(logmsg);
884 error = collect_import_msg(&logmsg, &logmsg_path, editor,
885 path_dir, refname);
886 if (error) {
887 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
888 logmsg_path != NULL)
889 preserve_logmsg = 1;
890 goto done;
894 if (unveil(path_dir, "r") != 0) {
895 error = got_error_from_errno2("unveil", path_dir);
896 if (logmsg_path)
897 preserve_logmsg = 1;
898 goto done;
901 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
902 if (error) {
903 if (logmsg_path)
904 preserve_logmsg = 1;
905 goto done;
908 error = got_repo_import(&new_commit_id, path_dir, logmsg,
909 author, &ignores, repo, import_progress, NULL);
910 if (error) {
911 if (logmsg_path)
912 preserve_logmsg = 1;
913 goto done;
916 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
917 if (error) {
918 if (logmsg_path)
919 preserve_logmsg = 1;
920 goto done;
923 error = got_ref_write(branch_ref, repo);
924 if (error) {
925 if (logmsg_path)
926 preserve_logmsg = 1;
927 goto done;
930 error = got_object_id_str(&id_str, new_commit_id);
931 if (error) {
932 if (logmsg_path)
933 preserve_logmsg = 1;
934 goto done;
937 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
938 if (error) {
939 if (error->code != GOT_ERR_NOT_REF) {
940 if (logmsg_path)
941 preserve_logmsg = 1;
942 goto done;
945 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
946 branch_ref);
947 if (error) {
948 if (logmsg_path)
949 preserve_logmsg = 1;
950 goto done;
953 error = got_ref_write(head_ref, repo);
954 if (error) {
955 if (logmsg_path)
956 preserve_logmsg = 1;
957 goto done;
961 printf("Created branch %s with commit %s\n",
962 got_ref_get_name(branch_ref), id_str);
963 done:
964 if (pack_fds) {
965 const struct got_error *pack_err =
966 got_repo_pack_fds_close(pack_fds);
967 if (error == NULL)
968 error = pack_err;
970 if (preserve_logmsg) {
971 fprintf(stderr, "%s: log message preserved in %s\n",
972 getprogname(), logmsg_path);
973 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
974 error = got_error_from_errno2("unlink", logmsg_path);
975 free(logmsg);
976 free(logmsg_path);
977 free(repo_path);
978 free(editor);
979 free(new_commit_id);
980 free(id_str);
981 free(author);
982 free(gitconfig_path);
983 if (branch_ref)
984 got_ref_close(branch_ref);
985 if (head_ref)
986 got_ref_close(head_ref);
987 return error;
990 __dead static void
991 usage_clone(void)
993 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
994 "repository-URL [directory]\n", getprogname());
995 exit(1);
998 struct got_fetch_progress_arg {
999 char last_scaled_size[FMT_SCALED_STRSIZE];
1000 int last_p_indexed;
1001 int last_p_resolved;
1002 int verbosity;
1004 struct got_repository *repo;
1006 int create_configs;
1007 int configs_created;
1008 struct {
1009 struct got_pathlist_head *symrefs;
1010 struct got_pathlist_head *wanted_branches;
1011 struct got_pathlist_head *wanted_refs;
1012 const char *proto;
1013 const char *host;
1014 const char *port;
1015 const char *remote_repo_path;
1016 const char *git_url;
1017 int fetch_all_branches;
1018 int mirror_references;
1019 } config_info;
1022 /* XXX forward declaration */
1023 static const struct got_error *
1024 create_config_files(const char *proto, const char *host, const char *port,
1025 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1026 int mirror_references, struct got_pathlist_head *symrefs,
1027 struct got_pathlist_head *wanted_branches,
1028 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1030 static const struct got_error *
1031 fetch_progress(void *arg, const char *message, off_t packfile_size,
1032 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1034 const struct got_error *err = NULL;
1035 struct got_fetch_progress_arg *a = arg;
1036 char scaled_size[FMT_SCALED_STRSIZE];
1037 int p_indexed, p_resolved;
1038 int print_size = 0, print_indexed = 0, print_resolved = 0;
1041 * In order to allow a failed clone to be resumed with 'got fetch'
1042 * we try to create configuration files as soon as possible.
1043 * Once the server has sent information about its default branch
1044 * we have all required information.
1046 if (a->create_configs && !a->configs_created &&
1047 !TAILQ_EMPTY(a->config_info.symrefs)) {
1048 err = create_config_files(a->config_info.proto,
1049 a->config_info.host, a->config_info.port,
1050 a->config_info.remote_repo_path,
1051 a->config_info.git_url,
1052 a->config_info.fetch_all_branches,
1053 a->config_info.mirror_references,
1054 a->config_info.symrefs,
1055 a->config_info.wanted_branches,
1056 a->config_info.wanted_refs, a->repo);
1057 if (err)
1058 return err;
1059 a->configs_created = 1;
1062 if (a->verbosity < 0)
1063 return NULL;
1065 if (message && message[0] != '\0') {
1066 printf("\rserver: %s", message);
1067 fflush(stdout);
1068 return NULL;
1071 if (packfile_size > 0 || nobj_indexed > 0) {
1072 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1073 (a->last_scaled_size[0] == '\0' ||
1074 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1075 print_size = 1;
1076 if (strlcpy(a->last_scaled_size, scaled_size,
1077 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1078 return got_error(GOT_ERR_NO_SPACE);
1080 if (nobj_indexed > 0) {
1081 p_indexed = (nobj_indexed * 100) / nobj_total;
1082 if (p_indexed != a->last_p_indexed) {
1083 a->last_p_indexed = p_indexed;
1084 print_indexed = 1;
1085 print_size = 1;
1088 if (nobj_resolved > 0) {
1089 p_resolved = (nobj_resolved * 100) /
1090 (nobj_total - nobj_loose);
1091 if (p_resolved != a->last_p_resolved) {
1092 a->last_p_resolved = p_resolved;
1093 print_resolved = 1;
1094 print_indexed = 1;
1095 print_size = 1;
1100 if (print_size || print_indexed || print_resolved)
1101 printf("\r");
1102 if (print_size)
1103 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1104 if (print_indexed)
1105 printf("; indexing %d%%", p_indexed);
1106 if (print_resolved)
1107 printf("; resolving deltas %d%%", p_resolved);
1108 if (print_size || print_indexed || print_resolved)
1109 fflush(stdout);
1111 return NULL;
1114 static const struct got_error *
1115 create_symref(const char *refname, struct got_reference *target_ref,
1116 int verbosity, struct got_repository *repo)
1118 const struct got_error *err;
1119 struct got_reference *head_symref;
1121 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1122 if (err)
1123 return err;
1125 err = got_ref_write(head_symref, repo);
1126 if (err == NULL && verbosity > 0) {
1127 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1128 got_ref_get_name(target_ref));
1130 got_ref_close(head_symref);
1131 return err;
1134 static const struct got_error *
1135 list_remote_refs(struct got_pathlist_head *symrefs,
1136 struct got_pathlist_head *refs)
1138 const struct got_error *err;
1139 struct got_pathlist_entry *pe;
1141 TAILQ_FOREACH(pe, symrefs, entry) {
1142 const char *refname = pe->path;
1143 const char *targetref = pe->data;
1145 printf("%s: %s\n", refname, targetref);
1148 TAILQ_FOREACH(pe, refs, entry) {
1149 const char *refname = pe->path;
1150 struct got_object_id *id = pe->data;
1151 char *id_str;
1153 err = got_object_id_str(&id_str, id);
1154 if (err)
1155 return err;
1156 printf("%s: %s\n", refname, id_str);
1157 free(id_str);
1160 return NULL;
1163 static const struct got_error *
1164 create_ref(const char *refname, struct got_object_id *id,
1165 int verbosity, struct got_repository *repo)
1167 const struct got_error *err = NULL;
1168 struct got_reference *ref;
1169 char *id_str;
1171 err = got_object_id_str(&id_str, id);
1172 if (err)
1173 return err;
1175 err = got_ref_alloc(&ref, refname, id);
1176 if (err)
1177 goto done;
1179 err = got_ref_write(ref, repo);
1180 got_ref_close(ref);
1182 if (err == NULL && verbosity >= 0)
1183 printf("Created reference %s: %s\n", refname, id_str);
1184 done:
1185 free(id_str);
1186 return err;
1189 static int
1190 match_wanted_ref(const char *refname, const char *wanted_ref)
1192 if (strncmp(refname, "refs/", 5) != 0)
1193 return 0;
1194 refname += 5;
1197 * Prevent fetching of references that won't make any
1198 * sense outside of the remote repository's context.
1200 if (strncmp(refname, "got/", 4) == 0)
1201 return 0;
1202 if (strncmp(refname, "remotes/", 8) == 0)
1203 return 0;
1205 if (strncmp(wanted_ref, "refs/", 5) == 0)
1206 wanted_ref += 5;
1208 /* Allow prefix match. */
1209 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1210 return 1;
1212 /* Allow exact match. */
1213 return (strcmp(refname, wanted_ref) == 0);
1216 static int
1217 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1219 struct got_pathlist_entry *pe;
1221 TAILQ_FOREACH(pe, wanted_refs, entry) {
1222 if (match_wanted_ref(refname, pe->path))
1223 return 1;
1226 return 0;
1229 static const struct got_error *
1230 create_wanted_ref(const char *refname, struct got_object_id *id,
1231 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1233 const struct got_error *err;
1234 char *remote_refname;
1236 if (strncmp("refs/", refname, 5) == 0)
1237 refname += 5;
1239 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1240 remote_repo_name, refname) == -1)
1241 return got_error_from_errno("asprintf");
1243 err = create_ref(remote_refname, id, verbosity, repo);
1244 free(remote_refname);
1245 return err;
1248 static const struct got_error *
1249 create_gotconfig(const char *proto, const char *host, const char *port,
1250 const char *remote_repo_path, const char *default_branch,
1251 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1252 struct got_pathlist_head *wanted_refs, int mirror_references,
1253 struct got_repository *repo)
1255 const struct got_error *err = NULL;
1256 char *gotconfig_path = NULL;
1257 char *gotconfig = NULL;
1258 FILE *gotconfig_file = NULL;
1259 const char *branchname = NULL;
1260 char *branches = NULL, *refs = NULL;
1261 ssize_t n;
1263 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1264 struct got_pathlist_entry *pe;
1265 TAILQ_FOREACH(pe, wanted_branches, entry) {
1266 char *s;
1267 branchname = pe->path;
1268 if (strncmp(branchname, "refs/heads/", 11) == 0)
1269 branchname += 11;
1270 if (asprintf(&s, "%s\"%s\" ",
1271 branches ? branches : "", branchname) == -1) {
1272 err = got_error_from_errno("asprintf");
1273 goto done;
1275 free(branches);
1276 branches = s;
1278 } else if (!fetch_all_branches && default_branch) {
1279 branchname = default_branch;
1280 if (strncmp(branchname, "refs/heads/", 11) == 0)
1281 branchname += 11;
1282 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1287 if (!TAILQ_EMPTY(wanted_refs)) {
1288 struct got_pathlist_entry *pe;
1289 TAILQ_FOREACH(pe, wanted_refs, entry) {
1290 char *s;
1291 const char *refname = pe->path;
1292 if (strncmp(refname, "refs/", 5) == 0)
1293 branchname += 5;
1294 if (asprintf(&s, "%s\"%s\" ",
1295 refs ? refs : "", refname) == -1) {
1296 err = got_error_from_errno("asprintf");
1297 goto done;
1299 free(refs);
1300 refs = s;
1304 /* Create got.conf(5). */
1305 gotconfig_path = got_repo_get_path_gotconfig(repo);
1306 if (gotconfig_path == NULL) {
1307 err = got_error_from_errno("got_repo_get_path_gotconfig");
1308 goto done;
1310 gotconfig_file = fopen(gotconfig_path, "ae");
1311 if (gotconfig_file == NULL) {
1312 err = got_error_from_errno2("fopen", gotconfig_path);
1313 goto done;
1315 if (asprintf(&gotconfig,
1316 "remote \"%s\" {\n"
1317 "\tserver %s\n"
1318 "\tprotocol %s\n"
1319 "%s%s%s"
1320 "\trepository \"%s\"\n"
1321 "%s%s%s"
1322 "%s%s%s"
1323 "%s"
1324 "%s"
1325 "}\n",
1326 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1327 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1328 remote_repo_path, branches ? "\tbranch { " : "",
1329 branches ? branches : "", branches ? "}\n" : "",
1330 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1331 mirror_references ? "\tmirror_references yes\n" : "",
1332 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1333 err = got_error_from_errno("asprintf");
1334 goto done;
1336 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1337 if (n != strlen(gotconfig)) {
1338 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1339 goto done;
1342 done:
1343 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1344 err = got_error_from_errno2("fclose", gotconfig_path);
1345 free(gotconfig_path);
1346 free(branches);
1347 return err;
1350 static const struct got_error *
1351 create_gitconfig(const char *git_url, const char *default_branch,
1352 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1353 struct got_pathlist_head *wanted_refs, int mirror_references,
1354 struct got_repository *repo)
1356 const struct got_error *err = NULL;
1357 char *gitconfig_path = NULL;
1358 char *gitconfig = NULL;
1359 FILE *gitconfig_file = NULL;
1360 char *branches = NULL, *refs = NULL;
1361 const char *branchname;
1362 ssize_t n;
1364 /* Create a config file Git can understand. */
1365 gitconfig_path = got_repo_get_path_gitconfig(repo);
1366 if (gitconfig_path == NULL) {
1367 err = got_error_from_errno("got_repo_get_path_gitconfig");
1368 goto done;
1370 gitconfig_file = fopen(gitconfig_path, "ae");
1371 if (gitconfig_file == NULL) {
1372 err = got_error_from_errno2("fopen", gitconfig_path);
1373 goto done;
1375 if (fetch_all_branches) {
1376 if (mirror_references) {
1377 if (asprintf(&branches,
1378 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1379 err = got_error_from_errno("asprintf");
1380 goto done;
1382 } else if (asprintf(&branches,
1383 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1384 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 } else if (!TAILQ_EMPTY(wanted_branches)) {
1389 struct got_pathlist_entry *pe;
1390 TAILQ_FOREACH(pe, wanted_branches, entry) {
1391 char *s;
1392 branchname = pe->path;
1393 if (strncmp(branchname, "refs/heads/", 11) == 0)
1394 branchname += 11;
1395 if (mirror_references) {
1396 if (asprintf(&s,
1397 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1398 branches ? branches : "",
1399 branchname, branchname) == -1) {
1400 err = got_error_from_errno("asprintf");
1401 goto done;
1403 } else if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1405 branches ? branches : "",
1406 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1407 branchname) == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 free(branches);
1412 branches = s;
1414 } else {
1416 * If the server specified a default branch, use just that one.
1417 * Otherwise fall back to fetching all branches on next fetch.
1419 if (default_branch) {
1420 branchname = default_branch;
1421 if (strncmp(branchname, "refs/heads/", 11) == 0)
1422 branchname += 11;
1423 } else
1424 branchname = "*"; /* fall back to all branches */
1425 if (mirror_references) {
1426 if (asprintf(&branches,
1427 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1428 branchname, branchname) == -1) {
1429 err = got_error_from_errno("asprintf");
1430 goto done;
1432 } else if (asprintf(&branches,
1433 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1434 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1435 branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1440 if (!TAILQ_EMPTY(wanted_refs)) {
1441 struct got_pathlist_entry *pe;
1442 TAILQ_FOREACH(pe, wanted_refs, entry) {
1443 char *s;
1444 const char *refname = pe->path;
1445 if (strncmp(refname, "refs/", 5) == 0)
1446 refname += 5;
1447 if (mirror_references) {
1448 if (asprintf(&s,
1449 "%s\tfetch = refs/%s:refs/%s\n",
1450 refs ? refs : "", refname, refname) == -1) {
1451 err = got_error_from_errno("asprintf");
1452 goto done;
1454 } else if (asprintf(&s,
1455 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1456 refs ? refs : "",
1457 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1458 refname) == -1) {
1459 err = got_error_from_errno("asprintf");
1460 goto done;
1462 free(refs);
1463 refs = s;
1467 if (asprintf(&gitconfig,
1468 "[remote \"%s\"]\n"
1469 "\turl = %s\n"
1470 "%s"
1471 "%s"
1472 "\tfetch = refs/tags/*:refs/tags/*\n",
1473 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1474 refs ? refs : "") == -1) {
1475 err = got_error_from_errno("asprintf");
1476 goto done;
1478 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1479 if (n != strlen(gitconfig)) {
1480 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1481 goto done;
1483 done:
1484 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1485 err = got_error_from_errno2("fclose", gitconfig_path);
1486 free(gitconfig_path);
1487 free(branches);
1488 return err;
1491 static const struct got_error *
1492 create_config_files(const char *proto, const char *host, const char *port,
1493 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1494 int mirror_references, struct got_pathlist_head *symrefs,
1495 struct got_pathlist_head *wanted_branches,
1496 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1498 const struct got_error *err = NULL;
1499 const char *default_branch = NULL;
1500 struct got_pathlist_entry *pe;
1503 * If we asked for a set of wanted branches then use the first
1504 * one of those.
1506 if (!TAILQ_EMPTY(wanted_branches)) {
1507 pe = TAILQ_FIRST(wanted_branches);
1508 default_branch = pe->path;
1509 } else {
1510 /* First HEAD ref listed by server is the default branch. */
1511 TAILQ_FOREACH(pe, symrefs, entry) {
1512 const char *refname = pe->path;
1513 const char *target = pe->data;
1515 if (strcmp(refname, GOT_REF_HEAD) != 0)
1516 continue;
1518 default_branch = target;
1519 break;
1523 /* Create got.conf(5). */
1524 err = create_gotconfig(proto, host, port, remote_repo_path,
1525 default_branch, fetch_all_branches, wanted_branches,
1526 wanted_refs, mirror_references, repo);
1527 if (err)
1528 return err;
1530 /* Create a config file Git can understand. */
1531 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1532 wanted_branches, wanted_refs, mirror_references, repo);
1535 static const struct got_error *
1536 cmd_clone(int argc, char *argv[])
1538 const struct got_error *error = NULL;
1539 const char *uri, *dirname;
1540 char *proto, *host, *port, *repo_name, *server_path;
1541 char *default_destdir = NULL, *id_str = NULL;
1542 const char *repo_path;
1543 struct got_repository *repo = NULL;
1544 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1545 struct got_pathlist_entry *pe;
1546 struct got_object_id *pack_hash = NULL;
1547 int ch, fetchfd = -1, fetchstatus;
1548 pid_t fetchpid = -1;
1549 struct got_fetch_progress_arg fpa;
1550 char *git_url = NULL;
1551 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1552 int bflag = 0, list_refs_only = 0;
1553 int *pack_fds = NULL;
1555 TAILQ_INIT(&refs);
1556 TAILQ_INIT(&symrefs);
1557 TAILQ_INIT(&wanted_branches);
1558 TAILQ_INIT(&wanted_refs);
1560 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1561 switch (ch) {
1562 case 'a':
1563 fetch_all_branches = 1;
1564 break;
1565 case 'b':
1566 error = got_pathlist_append(&wanted_branches,
1567 optarg, NULL);
1568 if (error)
1569 return error;
1570 bflag = 1;
1571 break;
1572 case 'l':
1573 list_refs_only = 1;
1574 break;
1575 case 'm':
1576 mirror_references = 1;
1577 break;
1578 case 'q':
1579 verbosity = -1;
1580 break;
1581 case 'R':
1582 error = got_pathlist_append(&wanted_refs,
1583 optarg, NULL);
1584 if (error)
1585 return error;
1586 break;
1587 case 'v':
1588 if (verbosity < 0)
1589 verbosity = 0;
1590 else if (verbosity < 3)
1591 verbosity++;
1592 break;
1593 default:
1594 usage_clone();
1595 break;
1598 argc -= optind;
1599 argv += optind;
1601 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1602 option_conflict('a', 'b');
1603 if (list_refs_only) {
1604 if (!TAILQ_EMPTY(&wanted_branches))
1605 option_conflict('l', 'b');
1606 if (fetch_all_branches)
1607 option_conflict('l', 'a');
1608 if (mirror_references)
1609 option_conflict('l', 'm');
1610 if (!TAILQ_EMPTY(&wanted_refs))
1611 option_conflict('l', 'R');
1614 uri = argv[0];
1616 if (argc == 1)
1617 dirname = NULL;
1618 else if (argc == 2)
1619 dirname = argv[1];
1620 else
1621 usage_clone();
1623 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1624 &repo_name, uri);
1625 if (error)
1626 goto done;
1628 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1629 host, port ? ":" : "", port ? port : "",
1630 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1631 error = got_error_from_errno("asprintf");
1632 goto done;
1635 if (strcmp(proto, "git") == 0) {
1636 #ifndef PROFILE
1637 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1638 "sendfd dns inet unveil", NULL) == -1)
1639 err(1, "pledge");
1640 #endif
1641 } else if (strcmp(proto, "git+ssh") == 0 ||
1642 strcmp(proto, "ssh") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "http") == 0 ||
1649 strcmp(proto, "git+http") == 0) {
1650 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1651 goto done;
1652 } else {
1653 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1654 goto done;
1656 if (dirname == NULL) {
1657 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1658 error = got_error_from_errno("asprintf");
1659 goto done;
1661 repo_path = default_destdir;
1662 } else
1663 repo_path = dirname;
1665 if (!list_refs_only) {
1666 error = got_path_mkdir(repo_path);
1667 if (error &&
1668 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1669 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1670 goto done;
1671 if (!got_path_dir_is_empty(repo_path)) {
1672 error = got_error_path(repo_path,
1673 GOT_ERR_DIR_NOT_EMPTY);
1674 goto done;
1678 error = got_dial_apply_unveil(proto);
1679 if (error)
1680 goto done;
1682 error = apply_unveil(repo_path, 0, NULL);
1683 if (error)
1684 goto done;
1686 if (verbosity >= 0)
1687 printf("Connecting to %s\n", git_url);
1689 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1690 server_path, verbosity);
1691 if (error)
1692 goto done;
1694 if (!list_refs_only) {
1695 error = got_repo_init(repo_path, NULL);
1696 if (error)
1697 goto done;
1698 error = got_repo_pack_fds_open(&pack_fds);
1699 if (error != NULL)
1700 goto done;
1701 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1702 if (error)
1703 goto done;
1706 fpa.last_scaled_size[0] = '\0';
1707 fpa.last_p_indexed = -1;
1708 fpa.last_p_resolved = -1;
1709 fpa.verbosity = verbosity;
1710 fpa.create_configs = 1;
1711 fpa.configs_created = 0;
1712 fpa.repo = repo;
1713 fpa.config_info.symrefs = &symrefs;
1714 fpa.config_info.wanted_branches = &wanted_branches;
1715 fpa.config_info.wanted_refs = &wanted_refs;
1716 fpa.config_info.proto = proto;
1717 fpa.config_info.host = host;
1718 fpa.config_info.port = port;
1719 fpa.config_info.remote_repo_path = server_path;
1720 fpa.config_info.git_url = git_url;
1721 fpa.config_info.fetch_all_branches = fetch_all_branches;
1722 fpa.config_info.mirror_references = mirror_references;
1723 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1724 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1725 fetch_all_branches, &wanted_branches, &wanted_refs,
1726 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1727 fetch_progress, &fpa);
1728 if (error)
1729 goto done;
1731 if (list_refs_only) {
1732 error = list_remote_refs(&symrefs, &refs);
1733 goto done;
1736 if (pack_hash == NULL) {
1737 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1738 "server sent an empty pack file");
1739 goto done;
1741 error = got_object_id_str(&id_str, pack_hash);
1742 if (error)
1743 goto done;
1744 if (verbosity >= 0)
1745 printf("\nFetched %s.pack\n", id_str);
1746 free(id_str);
1748 /* Set up references provided with the pack file. */
1749 TAILQ_FOREACH(pe, &refs, entry) {
1750 const char *refname = pe->path;
1751 struct got_object_id *id = pe->data;
1752 char *remote_refname;
1754 if (is_wanted_ref(&wanted_refs, refname) &&
1755 !mirror_references) {
1756 error = create_wanted_ref(refname, id,
1757 GOT_FETCH_DEFAULT_REMOTE_NAME,
1758 verbosity - 1, repo);
1759 if (error)
1760 goto done;
1761 continue;
1764 error = create_ref(refname, id, verbosity - 1, repo);
1765 if (error)
1766 goto done;
1768 if (mirror_references)
1769 continue;
1771 if (strncmp("refs/heads/", refname, 11) != 0)
1772 continue;
1774 if (asprintf(&remote_refname,
1775 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1776 refname + 11) == -1) {
1777 error = got_error_from_errno("asprintf");
1778 goto done;
1780 error = create_ref(remote_refname, id, verbosity - 1, repo);
1781 free(remote_refname);
1782 if (error)
1783 goto done;
1786 /* Set the HEAD reference if the server provided one. */
1787 TAILQ_FOREACH(pe, &symrefs, entry) {
1788 struct got_reference *target_ref;
1789 const char *refname = pe->path;
1790 const char *target = pe->data;
1791 char *remote_refname = NULL, *remote_target = NULL;
1793 if (strcmp(refname, GOT_REF_HEAD) != 0)
1794 continue;
1796 error = got_ref_open(&target_ref, repo, target, 0);
1797 if (error) {
1798 if (error->code == GOT_ERR_NOT_REF) {
1799 error = NULL;
1800 continue;
1802 goto done;
1805 error = create_symref(refname, target_ref, verbosity, repo);
1806 got_ref_close(target_ref);
1807 if (error)
1808 goto done;
1810 if (mirror_references)
1811 continue;
1813 if (strncmp("refs/heads/", target, 11) != 0)
1814 continue;
1816 if (asprintf(&remote_refname,
1817 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1818 refname) == -1) {
1819 error = got_error_from_errno("asprintf");
1820 goto done;
1822 if (asprintf(&remote_target,
1823 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1824 target + 11) == -1) {
1825 error = got_error_from_errno("asprintf");
1826 free(remote_refname);
1827 goto done;
1829 error = got_ref_open(&target_ref, repo, remote_target, 0);
1830 if (error) {
1831 free(remote_refname);
1832 free(remote_target);
1833 if (error->code == GOT_ERR_NOT_REF) {
1834 error = NULL;
1835 continue;
1837 goto done;
1839 error = create_symref(remote_refname, target_ref,
1840 verbosity - 1, repo);
1841 free(remote_refname);
1842 free(remote_target);
1843 got_ref_close(target_ref);
1844 if (error)
1845 goto done;
1847 if (pe == NULL) {
1849 * We failed to set the HEAD reference. If we asked for
1850 * a set of wanted branches use the first of one of those
1851 * which could be fetched instead.
1853 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1854 const char *target = pe->path;
1855 struct got_reference *target_ref;
1857 error = got_ref_open(&target_ref, repo, target, 0);
1858 if (error) {
1859 if (error->code == GOT_ERR_NOT_REF) {
1860 error = NULL;
1861 continue;
1863 goto done;
1866 error = create_symref(GOT_REF_HEAD, target_ref,
1867 verbosity, repo);
1868 got_ref_close(target_ref);
1869 if (error)
1870 goto done;
1871 break;
1874 if (!fpa.configs_created && pe != NULL) {
1875 error = create_config_files(fpa.config_info.proto,
1876 fpa.config_info.host, fpa.config_info.port,
1877 fpa.config_info.remote_repo_path,
1878 fpa.config_info.git_url,
1879 fpa.config_info.fetch_all_branches,
1880 fpa.config_info.mirror_references,
1881 fpa.config_info.symrefs,
1882 fpa.config_info.wanted_branches,
1883 fpa.config_info.wanted_refs, fpa.repo);
1884 if (error)
1885 goto done;
1889 if (verbosity >= 0)
1890 printf("Created %s repository '%s'\n",
1891 mirror_references ? "mirrored" : "cloned", repo_path);
1892 done:
1893 if (pack_fds) {
1894 const struct got_error *pack_err =
1895 got_repo_pack_fds_close(pack_fds);
1896 if (error == NULL)
1897 error = pack_err;
1899 if (fetchpid > 0) {
1900 if (kill(fetchpid, SIGTERM) == -1)
1901 error = got_error_from_errno("kill");
1902 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1903 error = got_error_from_errno("waitpid");
1905 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1906 error = got_error_from_errno("close");
1907 if (repo) {
1908 const struct got_error *close_err = got_repo_close(repo);
1909 if (error == NULL)
1910 error = close_err;
1912 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1913 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1914 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1915 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1916 free(pack_hash);
1917 free(proto);
1918 free(host);
1919 free(port);
1920 free(server_path);
1921 free(repo_name);
1922 free(default_destdir);
1923 free(git_url);
1924 return error;
1927 static const struct got_error *
1928 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1929 int replace_tags, int verbosity, struct got_repository *repo)
1931 const struct got_error *err = NULL;
1932 char *new_id_str = NULL;
1933 struct got_object_id *old_id = NULL;
1935 err = got_object_id_str(&new_id_str, new_id);
1936 if (err)
1937 goto done;
1939 if (!replace_tags &&
1940 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1941 err = got_ref_resolve(&old_id, repo, ref);
1942 if (err)
1943 goto done;
1944 if (got_object_id_cmp(old_id, new_id) == 0)
1945 goto done;
1946 if (verbosity >= 0) {
1947 printf("Rejecting update of existing tag %s: %s\n",
1948 got_ref_get_name(ref), new_id_str);
1950 goto done;
1953 if (got_ref_is_symbolic(ref)) {
1954 if (verbosity >= 0) {
1955 printf("Replacing reference %s: %s\n",
1956 got_ref_get_name(ref),
1957 got_ref_get_symref_target(ref));
1959 err = got_ref_change_symref_to_ref(ref, new_id);
1960 if (err)
1961 goto done;
1962 err = got_ref_write(ref, repo);
1963 if (err)
1964 goto done;
1965 } else {
1966 err = got_ref_resolve(&old_id, repo, ref);
1967 if (err)
1968 goto done;
1969 if (got_object_id_cmp(old_id, new_id) == 0)
1970 goto done;
1972 err = got_ref_change_ref(ref, new_id);
1973 if (err)
1974 goto done;
1975 err = got_ref_write(ref, repo);
1976 if (err)
1977 goto done;
1980 if (verbosity >= 0)
1981 printf("Updated %s: %s\n", got_ref_get_name(ref),
1982 new_id_str);
1983 done:
1984 free(old_id);
1985 free(new_id_str);
1986 return err;
1989 static const struct got_error *
1990 update_symref(const char *refname, struct got_reference *target_ref,
1991 int verbosity, struct got_repository *repo)
1993 const struct got_error *err = NULL, *unlock_err;
1994 struct got_reference *symref;
1995 int symref_is_locked = 0;
1997 err = got_ref_open(&symref, repo, refname, 1);
1998 if (err) {
1999 if (err->code != GOT_ERR_NOT_REF)
2000 return err;
2001 err = got_ref_alloc_symref(&symref, refname, target_ref);
2002 if (err)
2003 goto done;
2005 err = got_ref_write(symref, repo);
2006 if (err)
2007 goto done;
2009 if (verbosity >= 0)
2010 printf("Created reference %s: %s\n",
2011 got_ref_get_name(symref),
2012 got_ref_get_symref_target(symref));
2013 } else {
2014 symref_is_locked = 1;
2016 if (strcmp(got_ref_get_symref_target(symref),
2017 got_ref_get_name(target_ref)) == 0)
2018 goto done;
2020 err = got_ref_change_symref(symref,
2021 got_ref_get_name(target_ref));
2022 if (err)
2023 goto done;
2025 err = got_ref_write(symref, repo);
2026 if (err)
2027 goto done;
2029 if (verbosity >= 0)
2030 printf("Updated %s: %s\n", got_ref_get_name(symref),
2031 got_ref_get_symref_target(symref));
2034 done:
2035 if (symref_is_locked) {
2036 unlock_err = got_ref_unlock(symref);
2037 if (unlock_err && err == NULL)
2038 err = unlock_err;
2040 got_ref_close(symref);
2041 return err;
2044 __dead static void
2045 usage_fetch(void)
2047 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2048 "[-R reference] [-r repository-path] [remote-repository]\n",
2049 getprogname());
2050 exit(1);
2053 static const struct got_error *
2054 delete_missing_ref(struct got_reference *ref,
2055 int verbosity, struct got_repository *repo)
2057 const struct got_error *err = NULL;
2058 struct got_object_id *id = NULL;
2059 char *id_str = NULL;
2061 if (got_ref_is_symbolic(ref)) {
2062 err = got_ref_delete(ref, repo);
2063 if (err)
2064 return err;
2065 if (verbosity >= 0) {
2066 printf("Deleted %s: %s\n",
2067 got_ref_get_name(ref),
2068 got_ref_get_symref_target(ref));
2070 } else {
2071 err = got_ref_resolve(&id, repo, ref);
2072 if (err)
2073 return err;
2074 err = got_object_id_str(&id_str, id);
2075 if (err)
2076 goto done;
2078 err = got_ref_delete(ref, repo);
2079 if (err)
2080 goto done;
2081 if (verbosity >= 0) {
2082 printf("Deleted %s: %s\n",
2083 got_ref_get_name(ref), id_str);
2086 done:
2087 free(id);
2088 free(id_str);
2089 return err;
2092 static const struct got_error *
2093 delete_missing_refs(struct got_pathlist_head *their_refs,
2094 struct got_pathlist_head *their_symrefs,
2095 const struct got_remote_repo *remote,
2096 int verbosity, struct got_repository *repo)
2098 const struct got_error *err = NULL, *unlock_err;
2099 struct got_reflist_head my_refs;
2100 struct got_reflist_entry *re;
2101 struct got_pathlist_entry *pe;
2102 char *remote_namespace = NULL;
2103 char *local_refname = NULL;
2105 TAILQ_INIT(&my_refs);
2107 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2108 == -1)
2109 return got_error_from_errno("asprintf");
2111 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2112 if (err)
2113 goto done;
2115 TAILQ_FOREACH(re, &my_refs, entry) {
2116 const char *refname = got_ref_get_name(re->ref);
2117 const char *their_refname;
2119 if (remote->mirror_references) {
2120 their_refname = refname;
2121 } else {
2122 if (strncmp(refname, remote_namespace,
2123 strlen(remote_namespace)) == 0) {
2124 if (strcmp(refname + strlen(remote_namespace),
2125 GOT_REF_HEAD) == 0)
2126 continue;
2127 if (asprintf(&local_refname, "refs/heads/%s",
2128 refname + strlen(remote_namespace)) == -1) {
2129 err = got_error_from_errno("asprintf");
2130 goto done;
2132 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2133 continue;
2135 their_refname = local_refname;
2138 TAILQ_FOREACH(pe, their_refs, entry) {
2139 if (strcmp(their_refname, pe->path) == 0)
2140 break;
2142 if (pe != NULL)
2143 continue;
2145 TAILQ_FOREACH(pe, their_symrefs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 err = delete_missing_ref(re->ref, verbosity, repo);
2153 if (err)
2154 break;
2156 if (local_refname) {
2157 struct got_reference *ref;
2158 err = got_ref_open(&ref, repo, local_refname, 1);
2159 if (err) {
2160 if (err->code != GOT_ERR_NOT_REF)
2161 break;
2162 free(local_refname);
2163 local_refname = NULL;
2164 continue;
2166 err = delete_missing_ref(ref, verbosity, repo);
2167 if (err)
2168 break;
2169 unlock_err = got_ref_unlock(ref);
2170 got_ref_close(ref);
2171 if (unlock_err && err == NULL) {
2172 err = unlock_err;
2173 break;
2176 free(local_refname);
2177 local_refname = NULL;
2180 done:
2181 got_ref_list_free(&my_refs);
2182 free(remote_namespace);
2183 free(local_refname);
2184 return err;
2187 static const struct got_error *
2188 update_wanted_ref(const char *refname, struct got_object_id *id,
2189 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2191 const struct got_error *err, *unlock_err;
2192 char *remote_refname;
2193 struct got_reference *ref;
2195 if (strncmp("refs/", refname, 5) == 0)
2196 refname += 5;
2198 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2199 remote_repo_name, refname) == -1)
2200 return got_error_from_errno("asprintf");
2202 err = got_ref_open(&ref, repo, remote_refname, 1);
2203 if (err) {
2204 if (err->code != GOT_ERR_NOT_REF)
2205 goto done;
2206 err = create_ref(remote_refname, id, verbosity, repo);
2207 } else {
2208 err = update_ref(ref, id, 0, verbosity, repo);
2209 unlock_err = got_ref_unlock(ref);
2210 if (unlock_err && err == NULL)
2211 err = unlock_err;
2212 got_ref_close(ref);
2214 done:
2215 free(remote_refname);
2216 return err;
2219 static const struct got_error *
2220 delete_ref(struct got_repository *repo, struct got_reference *ref)
2222 const struct got_error *err = NULL;
2223 struct got_object_id *id = NULL;
2224 char *id_str = NULL;
2225 const char *target;
2227 if (got_ref_is_symbolic(ref)) {
2228 target = got_ref_get_symref_target(ref);
2229 } else {
2230 err = got_ref_resolve(&id, repo, ref);
2231 if (err)
2232 goto done;
2233 err = got_object_id_str(&id_str, id);
2234 if (err)
2235 goto done;
2236 target = id_str;
2239 err = got_ref_delete(ref, repo);
2240 if (err)
2241 goto done;
2243 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2244 done:
2245 free(id);
2246 free(id_str);
2247 return err;
2250 static const struct got_error *
2251 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2253 const struct got_error *err = NULL;
2254 struct got_reflist_head refs;
2255 struct got_reflist_entry *re;
2256 char *prefix;
2258 TAILQ_INIT(&refs);
2260 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2261 err = got_error_from_errno("asprintf");
2262 goto done;
2264 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2265 if (err)
2266 goto done;
2268 TAILQ_FOREACH(re, &refs, entry)
2269 delete_ref(repo, re->ref);
2270 done:
2271 got_ref_list_free(&refs);
2272 return err;
2275 static const struct got_error *
2276 cmd_fetch(int argc, char *argv[])
2278 const struct got_error *error = NULL, *unlock_err;
2279 char *cwd = NULL, *repo_path = NULL;
2280 const char *remote_name;
2281 char *proto = NULL, *host = NULL, *port = NULL;
2282 char *repo_name = NULL, *server_path = NULL;
2283 const struct got_remote_repo *remotes, *remote = NULL;
2284 int nremotes;
2285 char *id_str = NULL;
2286 struct got_repository *repo = NULL;
2287 struct got_worktree *worktree = NULL;
2288 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2289 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2290 struct got_pathlist_entry *pe;
2291 struct got_reflist_head remote_refs;
2292 struct got_reflist_entry *re;
2293 struct got_object_id *pack_hash = NULL;
2294 int i, ch, fetchfd = -1, fetchstatus;
2295 pid_t fetchpid = -1;
2296 struct got_fetch_progress_arg fpa;
2297 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2298 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2299 int *pack_fds = NULL, have_bflag = 0;
2300 const char *remote_head = NULL, *worktree_branch = NULL;
2302 TAILQ_INIT(&refs);
2303 TAILQ_INIT(&symrefs);
2304 TAILQ_INIT(&remote_refs);
2305 TAILQ_INIT(&wanted_branches);
2306 TAILQ_INIT(&wanted_refs);
2308 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2309 switch (ch) {
2310 case 'a':
2311 fetch_all_branches = 1;
2312 break;
2313 case 'b':
2314 error = got_pathlist_append(&wanted_branches,
2315 optarg, NULL);
2316 if (error)
2317 return error;
2318 have_bflag = 1;
2319 break;
2320 case 'd':
2321 delete_refs = 1;
2322 break;
2323 case 'l':
2324 list_refs_only = 1;
2325 break;
2326 case 'q':
2327 verbosity = -1;
2328 break;
2329 case 'R':
2330 error = got_pathlist_append(&wanted_refs,
2331 optarg, NULL);
2332 if (error)
2333 return error;
2334 break;
2335 case 'r':
2336 repo_path = realpath(optarg, NULL);
2337 if (repo_path == NULL)
2338 return got_error_from_errno2("realpath",
2339 optarg);
2340 got_path_strip_trailing_slashes(repo_path);
2341 break;
2342 case 't':
2343 replace_tags = 1;
2344 break;
2345 case 'v':
2346 if (verbosity < 0)
2347 verbosity = 0;
2348 else if (verbosity < 3)
2349 verbosity++;
2350 break;
2351 case 'X':
2352 delete_remote = 1;
2353 break;
2354 default:
2355 usage_fetch();
2356 break;
2359 argc -= optind;
2360 argv += optind;
2362 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('a', 'b');
2364 if (list_refs_only) {
2365 if (!TAILQ_EMPTY(&wanted_branches))
2366 option_conflict('l', 'b');
2367 if (fetch_all_branches)
2368 option_conflict('l', 'a');
2369 if (delete_refs)
2370 option_conflict('l', 'd');
2371 if (delete_remote)
2372 option_conflict('l', 'X');
2374 if (delete_remote) {
2375 if (fetch_all_branches)
2376 option_conflict('X', 'a');
2377 if (!TAILQ_EMPTY(&wanted_branches))
2378 option_conflict('X', 'b');
2379 if (delete_refs)
2380 option_conflict('X', 'd');
2381 if (replace_tags)
2382 option_conflict('X', 't');
2383 if (!TAILQ_EMPTY(&wanted_refs))
2384 option_conflict('X', 'R');
2387 if (argc == 0) {
2388 if (delete_remote)
2389 errx(1, "-X option requires a remote name");
2390 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2391 } else if (argc == 1)
2392 remote_name = argv[0];
2393 else
2394 usage_fetch();
2396 cwd = getcwd(NULL, 0);
2397 if (cwd == NULL) {
2398 error = got_error_from_errno("getcwd");
2399 goto done;
2402 error = got_repo_pack_fds_open(&pack_fds);
2403 if (error != NULL)
2404 goto done;
2406 if (repo_path == NULL) {
2407 error = got_worktree_open(&worktree, cwd);
2408 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2409 goto done;
2410 else
2411 error = NULL;
2412 if (worktree) {
2413 repo_path =
2414 strdup(got_worktree_get_repo_path(worktree));
2415 if (repo_path == NULL)
2416 error = got_error_from_errno("strdup");
2417 if (error)
2418 goto done;
2419 } else {
2420 repo_path = strdup(cwd);
2421 if (repo_path == NULL) {
2422 error = got_error_from_errno("strdup");
2423 goto done;
2428 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2429 if (error)
2430 goto done;
2432 if (delete_remote) {
2433 error = delete_refs_for_remote(repo, remote_name);
2434 goto done; /* nothing else to do */
2437 if (worktree) {
2438 worktree_conf = got_worktree_get_gotconfig(worktree);
2439 if (worktree_conf) {
2440 got_gotconfig_get_remotes(&nremotes, &remotes,
2441 worktree_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 repo_conf = got_repo_get_gotconfig(repo);
2452 if (repo_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 repo_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 remote = &remotes[i];
2458 break;
2463 if (remote == NULL) {
2464 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2465 for (i = 0; i < nremotes; i++) {
2466 if (strcmp(remotes[i].name, remote_name) == 0) {
2467 remote = &remotes[i];
2468 break;
2472 if (remote == NULL) {
2473 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2474 goto done;
2477 if (TAILQ_EMPTY(&wanted_branches)) {
2478 if (!fetch_all_branches)
2479 fetch_all_branches = remote->fetch_all_branches;
2480 for (i = 0; i < remote->nfetch_branches; i++) {
2481 error = got_pathlist_append(&wanted_branches,
2482 remote->fetch_branches[i], NULL);
2483 if (error)
2484 goto done;
2487 if (TAILQ_EMPTY(&wanted_refs)) {
2488 for (i = 0; i < remote->nfetch_refs; i++) {
2489 error = got_pathlist_append(&wanted_refs,
2490 remote->fetch_refs[i], NULL);
2491 if (error)
2492 goto done;
2496 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2497 &repo_name, remote->fetch_url);
2498 if (error)
2499 goto done;
2501 if (strcmp(proto, "git") == 0) {
2502 #ifndef PROFILE
2503 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2504 "sendfd dns inet unveil", NULL) == -1)
2505 err(1, "pledge");
2506 #endif
2507 } else if (strcmp(proto, "git+ssh") == 0 ||
2508 strcmp(proto, "ssh") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "http") == 0 ||
2515 strcmp(proto, "git+http") == 0) {
2516 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2517 goto done;
2518 } else {
2519 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2520 goto done;
2523 error = got_dial_apply_unveil(proto);
2524 if (error)
2525 goto done;
2527 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2528 if (error)
2529 goto done;
2531 if (verbosity >= 0) {
2532 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2533 remote->name, proto, host,
2534 port ? ":" : "", port ? port : "",
2535 *server_path == '/' ? "" : "/", server_path);
2538 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2539 server_path, verbosity);
2540 if (error)
2541 goto done;
2543 if (!have_bflag) {
2545 * If set, get this remote's HEAD ref target so
2546 * if it has changed on the server we can fetch it.
2548 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2549 got_ref_cmp_by_name, repo);
2550 if (error)
2551 goto done;
2553 TAILQ_FOREACH(re, &remote_refs, entry) {
2554 const char *remote_refname, *remote_target;
2555 size_t remote_name_len;
2557 if (!got_ref_is_symbolic(re->ref))
2558 continue;
2560 remote_name_len = strlen(remote->name);
2561 remote_refname = got_ref_get_name(re->ref);
2563 /* we only want refs/remotes/$remote->name/HEAD */
2564 if (strncmp(remote_refname + 13, remote->name,
2565 remote_name_len) != 0)
2566 continue;
2568 if (strcmp(remote_refname + remote_name_len + 14,
2569 GOT_REF_HEAD) != 0)
2570 continue;
2573 * Take the name itself because we already
2574 * only match with refs/heads/ in fetch_pack().
2576 remote_target = got_ref_get_symref_target(re->ref);
2577 remote_head = remote_target + remote_name_len + 14;
2578 break;
2581 if (worktree) {
2582 const char *refname;
2584 refname = got_worktree_get_head_ref_name(worktree);
2585 if (strncmp(refname, "refs/heads/", 11) == 0)
2586 worktree_branch = refname;
2590 fpa.last_scaled_size[0] = '\0';
2591 fpa.last_p_indexed = -1;
2592 fpa.last_p_resolved = -1;
2593 fpa.verbosity = verbosity;
2594 fpa.repo = repo;
2595 fpa.create_configs = 0;
2596 fpa.configs_created = 0;
2597 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2599 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2600 remote->mirror_references, fetch_all_branches, &wanted_branches,
2601 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2602 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2603 if (error)
2604 goto done;
2606 if (list_refs_only) {
2607 error = list_remote_refs(&symrefs, &refs);
2608 goto done;
2611 if (pack_hash == NULL) {
2612 if (verbosity >= 0)
2613 printf("Already up-to-date\n");
2614 } else if (verbosity >= 0) {
2615 error = got_object_id_str(&id_str, pack_hash);
2616 if (error)
2617 goto done;
2618 printf("\nFetched %s.pack\n", id_str);
2619 free(id_str);
2620 id_str = NULL;
2623 /* Update references provided with the pack file. */
2624 TAILQ_FOREACH(pe, &refs, entry) {
2625 const char *refname = pe->path;
2626 struct got_object_id *id = pe->data;
2627 struct got_reference *ref;
2628 char *remote_refname;
2630 if (is_wanted_ref(&wanted_refs, refname) &&
2631 !remote->mirror_references) {
2632 error = update_wanted_ref(refname, id,
2633 remote->name, verbosity, repo);
2634 if (error)
2635 goto done;
2636 continue;
2639 if (remote->mirror_references ||
2640 strncmp("refs/tags/", refname, 10) == 0) {
2641 error = got_ref_open(&ref, repo, refname, 1);
2642 if (error) {
2643 if (error->code != GOT_ERR_NOT_REF)
2644 goto done;
2645 error = create_ref(refname, id, verbosity,
2646 repo);
2647 if (error)
2648 goto done;
2649 } else {
2650 error = update_ref(ref, id, replace_tags,
2651 verbosity, repo);
2652 unlock_err = got_ref_unlock(ref);
2653 if (unlock_err && error == NULL)
2654 error = unlock_err;
2655 got_ref_close(ref);
2656 if (error)
2657 goto done;
2659 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2660 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2661 remote_name, refname + 11) == -1) {
2662 error = got_error_from_errno("asprintf");
2663 goto done;
2666 error = got_ref_open(&ref, repo, remote_refname, 1);
2667 if (error) {
2668 if (error->code != GOT_ERR_NOT_REF)
2669 goto done;
2670 error = create_ref(remote_refname, id,
2671 verbosity, repo);
2672 if (error)
2673 goto done;
2674 } else {
2675 error = update_ref(ref, id, replace_tags,
2676 verbosity, repo);
2677 unlock_err = got_ref_unlock(ref);
2678 if (unlock_err && error == NULL)
2679 error = unlock_err;
2680 got_ref_close(ref);
2681 if (error)
2682 goto done;
2685 /* Also create a local branch if none exists yet. */
2686 error = got_ref_open(&ref, repo, refname, 1);
2687 if (error) {
2688 if (error->code != GOT_ERR_NOT_REF)
2689 goto done;
2690 error = create_ref(refname, id, verbosity,
2691 repo);
2692 if (error)
2693 goto done;
2694 } else {
2695 unlock_err = got_ref_unlock(ref);
2696 if (unlock_err && error == NULL)
2697 error = unlock_err;
2698 got_ref_close(ref);
2702 if (delete_refs) {
2703 error = delete_missing_refs(&refs, &symrefs, remote,
2704 verbosity, repo);
2705 if (error)
2706 goto done;
2709 if (!remote->mirror_references) {
2710 /* Update remote HEAD reference if the server provided one. */
2711 TAILQ_FOREACH(pe, &symrefs, entry) {
2712 struct got_reference *target_ref;
2713 const char *refname = pe->path;
2714 const char *target = pe->data;
2715 char *remote_refname = NULL, *remote_target = NULL;
2717 if (strcmp(refname, GOT_REF_HEAD) != 0)
2718 continue;
2720 if (strncmp("refs/heads/", target, 11) != 0)
2721 continue;
2723 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2724 remote->name, refname) == -1) {
2725 error = got_error_from_errno("asprintf");
2726 goto done;
2728 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2729 remote->name, target + 11) == -1) {
2730 error = got_error_from_errno("asprintf");
2731 free(remote_refname);
2732 goto done;
2735 error = got_ref_open(&target_ref, repo, remote_target,
2736 0);
2737 if (error) {
2738 free(remote_refname);
2739 free(remote_target);
2740 if (error->code == GOT_ERR_NOT_REF) {
2741 error = NULL;
2742 continue;
2744 goto done;
2746 error = update_symref(remote_refname, target_ref,
2747 verbosity, repo);
2748 free(remote_refname);
2749 free(remote_target);
2750 got_ref_close(target_ref);
2751 if (error)
2752 goto done;
2755 done:
2756 if (fetchpid > 0) {
2757 if (kill(fetchpid, SIGTERM) == -1)
2758 error = got_error_from_errno("kill");
2759 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2760 error = got_error_from_errno("waitpid");
2762 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2763 error = got_error_from_errno("close");
2764 if (repo) {
2765 const struct got_error *close_err = got_repo_close(repo);
2766 if (error == NULL)
2767 error = close_err;
2769 if (worktree)
2770 got_worktree_close(worktree);
2771 if (pack_fds) {
2772 const struct got_error *pack_err =
2773 got_repo_pack_fds_close(pack_fds);
2774 if (error == NULL)
2775 error = pack_err;
2777 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2778 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2779 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2780 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2781 got_ref_list_free(&remote_refs);
2782 free(id_str);
2783 free(cwd);
2784 free(repo_path);
2785 free(pack_hash);
2786 free(proto);
2787 free(host);
2788 free(port);
2789 free(server_path);
2790 free(repo_name);
2791 return error;
2795 __dead static void
2796 usage_checkout(void)
2798 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2799 "[-p path-prefix] repository-path [work-tree-path]\n",
2800 getprogname());
2801 exit(1);
2804 static void
2805 show_worktree_base_ref_warning(void)
2807 fprintf(stderr, "%s: warning: could not create a reference "
2808 "to the work tree's base commit; the commit could be "
2809 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2810 "repository writable and running 'got update' will prevent this\n",
2811 getprogname());
2814 struct got_checkout_progress_arg {
2815 const char *worktree_path;
2816 int had_base_commit_ref_error;
2817 int verbosity;
2820 static const struct got_error *
2821 checkout_progress(void *arg, unsigned char status, const char *path)
2823 struct got_checkout_progress_arg *a = arg;
2825 /* Base commit bump happens silently. */
2826 if (status == GOT_STATUS_BUMP_BASE)
2827 return NULL;
2829 if (status == GOT_STATUS_BASE_REF_ERR) {
2830 a->had_base_commit_ref_error = 1;
2831 return NULL;
2834 while (path[0] == '/')
2835 path++;
2837 if (a->verbosity >= 0)
2838 printf("%c %s/%s\n", status, a->worktree_path, path);
2840 return NULL;
2843 static const struct got_error *
2844 check_cancelled(void *arg)
2846 if (sigint_received || sigpipe_received)
2847 return got_error(GOT_ERR_CANCELLED);
2848 return NULL;
2851 static const struct got_error *
2852 check_linear_ancestry(struct got_object_id *commit_id,
2853 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2854 struct got_repository *repo)
2856 const struct got_error *err = NULL;
2857 struct got_object_id *yca_id;
2859 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2860 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2861 if (err)
2862 return err;
2864 if (yca_id == NULL)
2865 return got_error(GOT_ERR_ANCESTRY);
2868 * Require a straight line of history between the target commit
2869 * and the work tree's base commit.
2871 * Non-linear situations such as this require a rebase:
2873 * (commit) D F (base_commit)
2874 * \ /
2875 * C E
2876 * \ /
2877 * B (yca)
2878 * |
2879 * A
2881 * 'got update' only handles linear cases:
2882 * Update forwards in time: A (base/yca) - B - C - D (commit)
2883 * Update backwards in time: D (base) - C - B - A (commit/yca)
2885 if (allow_forwards_in_time_only) {
2886 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2887 return got_error(GOT_ERR_ANCESTRY);
2888 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2889 got_object_id_cmp(base_commit_id, yca_id) != 0)
2890 return got_error(GOT_ERR_ANCESTRY);
2892 free(yca_id);
2893 return NULL;
2896 static const struct got_error *
2897 check_same_branch(struct got_object_id *commit_id,
2898 struct got_reference *head_ref, struct got_object_id *yca_id,
2899 struct got_repository *repo)
2901 const struct got_error *err = NULL;
2902 struct got_commit_graph *graph = NULL;
2903 struct got_object_id *head_commit_id = NULL;
2904 int is_same_branch = 0;
2906 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2907 if (err)
2908 goto done;
2910 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2911 is_same_branch = 1;
2912 goto done;
2914 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2915 is_same_branch = 1;
2916 goto done;
2919 err = got_commit_graph_open(&graph, "/", 1);
2920 if (err)
2921 goto done;
2923 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2924 check_cancelled, NULL);
2925 if (err)
2926 goto done;
2928 for (;;) {
2929 struct got_object_id id;
2931 err = got_commit_graph_iter_next(&id, graph, repo,
2932 check_cancelled, NULL);
2933 if (err) {
2934 if (err->code == GOT_ERR_ITER_COMPLETED)
2935 err = NULL;
2936 break;
2939 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2940 break;
2941 if (got_object_id_cmp(&id, commit_id) == 0) {
2942 is_same_branch = 1;
2943 break;
2946 done:
2947 if (graph)
2948 got_commit_graph_close(graph);
2949 free(head_commit_id);
2950 if (!err && !is_same_branch)
2951 err = got_error(GOT_ERR_ANCESTRY);
2952 return err;
2955 static const struct got_error *
2956 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2958 static char msg[512];
2959 const char *branch_name;
2961 if (got_ref_is_symbolic(ref))
2962 branch_name = got_ref_get_symref_target(ref);
2963 else
2964 branch_name = got_ref_get_name(ref);
2966 if (strncmp("refs/heads/", branch_name, 11) == 0)
2967 branch_name += 11;
2969 snprintf(msg, sizeof(msg),
2970 "target commit is not contained in branch '%s'; "
2971 "the branch to use must be specified with -b; "
2972 "if necessary a new branch can be created for "
2973 "this commit with 'got branch -c %s BRANCH_NAME'",
2974 branch_name, commit_id_str);
2976 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2979 static const struct got_error *
2980 cmd_checkout(int argc, char *argv[])
2982 const struct got_error *error = NULL;
2983 struct got_repository *repo = NULL;
2984 struct got_reference *head_ref = NULL, *ref = NULL;
2985 struct got_worktree *worktree = NULL;
2986 char *repo_path = NULL;
2987 char *worktree_path = NULL;
2988 const char *path_prefix = "";
2989 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2990 char *commit_id_str = NULL;
2991 struct got_object_id *commit_id = NULL;
2992 char *cwd = NULL;
2993 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2994 struct got_pathlist_head paths;
2995 struct got_checkout_progress_arg cpa;
2996 int *pack_fds = NULL;
2998 TAILQ_INIT(&paths);
3000 #ifndef PROFILE
3001 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3002 "unveil", NULL) == -1)
3003 err(1, "pledge");
3004 #endif
3006 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3007 switch (ch) {
3008 case 'b':
3009 branch_name = optarg;
3010 break;
3011 case 'c':
3012 commit_id_str = strdup(optarg);
3013 if (commit_id_str == NULL)
3014 return got_error_from_errno("strdup");
3015 break;
3016 case 'E':
3017 allow_nonempty = 1;
3018 break;
3019 case 'p':
3020 path_prefix = optarg;
3021 break;
3022 case 'q':
3023 verbosity = -1;
3024 break;
3025 default:
3026 usage_checkout();
3027 /* NOTREACHED */
3031 argc -= optind;
3032 argv += optind;
3034 if (argc == 1) {
3035 char *base, *dotgit;
3036 const char *path;
3037 repo_path = realpath(argv[0], NULL);
3038 if (repo_path == NULL)
3039 return got_error_from_errno2("realpath", argv[0]);
3040 cwd = getcwd(NULL, 0);
3041 if (cwd == NULL) {
3042 error = got_error_from_errno("getcwd");
3043 goto done;
3045 if (path_prefix[0])
3046 path = path_prefix;
3047 else
3048 path = repo_path;
3049 error = got_path_basename(&base, path);
3050 if (error)
3051 goto done;
3052 dotgit = strstr(base, ".git");
3053 if (dotgit)
3054 *dotgit = '\0';
3055 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3056 error = got_error_from_errno("asprintf");
3057 free(base);
3058 goto done;
3060 free(base);
3061 } else if (argc == 2) {
3062 repo_path = realpath(argv[0], NULL);
3063 if (repo_path == NULL) {
3064 error = got_error_from_errno2("realpath", argv[0]);
3065 goto done;
3067 worktree_path = realpath(argv[1], NULL);
3068 if (worktree_path == NULL) {
3069 if (errno != ENOENT) {
3070 error = got_error_from_errno2("realpath",
3071 argv[1]);
3072 goto done;
3074 worktree_path = strdup(argv[1]);
3075 if (worktree_path == NULL) {
3076 error = got_error_from_errno("strdup");
3077 goto done;
3080 } else
3081 usage_checkout();
3083 got_path_strip_trailing_slashes(repo_path);
3084 got_path_strip_trailing_slashes(worktree_path);
3086 error = got_repo_pack_fds_open(&pack_fds);
3087 if (error != NULL)
3088 goto done;
3090 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3091 if (error != NULL)
3092 goto done;
3094 /* Pre-create work tree path for unveil(2) */
3095 error = got_path_mkdir(worktree_path);
3096 if (error) {
3097 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3098 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3099 goto done;
3100 if (!allow_nonempty &&
3101 !got_path_dir_is_empty(worktree_path)) {
3102 error = got_error_path(worktree_path,
3103 GOT_ERR_DIR_NOT_EMPTY);
3104 goto done;
3108 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3109 if (error)
3110 goto done;
3112 error = got_ref_open(&head_ref, repo, branch_name, 0);
3113 if (error != NULL)
3114 goto done;
3116 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3117 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3118 goto done;
3120 error = got_worktree_open(&worktree, worktree_path);
3121 if (error != NULL)
3122 goto done;
3124 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3125 path_prefix);
3126 if (error != NULL)
3127 goto done;
3128 if (!same_path_prefix) {
3129 error = got_error(GOT_ERR_PATH_PREFIX);
3130 goto done;
3133 if (commit_id_str) {
3134 struct got_reflist_head refs;
3135 TAILQ_INIT(&refs);
3136 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3137 NULL);
3138 if (error)
3139 goto done;
3140 error = got_repo_match_object_id(&commit_id, NULL,
3141 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3142 got_ref_list_free(&refs);
3143 if (error)
3144 goto done;
3145 error = check_linear_ancestry(commit_id,
3146 got_worktree_get_base_commit_id(worktree), 0, repo);
3147 if (error != NULL) {
3148 if (error->code == GOT_ERR_ANCESTRY) {
3149 error = checkout_ancestry_error(
3150 head_ref, commit_id_str);
3152 goto done;
3154 error = check_same_branch(commit_id, head_ref, NULL, repo);
3155 if (error) {
3156 if (error->code == GOT_ERR_ANCESTRY) {
3157 error = checkout_ancestry_error(
3158 head_ref, commit_id_str);
3160 goto done;
3162 error = got_worktree_set_base_commit_id(worktree, repo,
3163 commit_id);
3164 if (error)
3165 goto done;
3166 /* Expand potentially abbreviated commit ID string. */
3167 free(commit_id_str);
3168 error = got_object_id_str(&commit_id_str, commit_id);
3169 if (error)
3170 goto done;
3171 } else {
3172 commit_id = got_object_id_dup(
3173 got_worktree_get_base_commit_id(worktree));
3174 if (commit_id == NULL) {
3175 error = got_error_from_errno("got_object_id_dup");
3176 goto done;
3178 error = got_object_id_str(&commit_id_str, commit_id);
3179 if (error)
3180 goto done;
3183 error = got_pathlist_append(&paths, "", NULL);
3184 if (error)
3185 goto done;
3186 cpa.worktree_path = worktree_path;
3187 cpa.had_base_commit_ref_error = 0;
3188 cpa.verbosity = verbosity;
3189 error = got_worktree_checkout_files(worktree, &paths, repo,
3190 checkout_progress, &cpa, check_cancelled, NULL);
3191 if (error != NULL)
3192 goto done;
3194 if (got_ref_is_symbolic(head_ref)) {
3195 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3196 if (error)
3197 goto done;
3198 refname = got_ref_get_name(ref);
3199 } else
3200 refname = got_ref_get_name(head_ref);
3201 printf("Checked out %s: %s\n", refname, commit_id_str);
3202 printf("Now shut up and hack\n");
3203 if (cpa.had_base_commit_ref_error)
3204 show_worktree_base_ref_warning();
3205 done:
3206 if (pack_fds) {
3207 const struct got_error *pack_err =
3208 got_repo_pack_fds_close(pack_fds);
3209 if (error == NULL)
3210 error = pack_err;
3212 if (head_ref)
3213 got_ref_close(head_ref);
3214 if (ref)
3215 got_ref_close(ref);
3216 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3217 free(commit_id_str);
3218 free(commit_id);
3219 free(repo_path);
3220 free(worktree_path);
3221 free(cwd);
3222 return error;
3225 struct got_update_progress_arg {
3226 int did_something;
3227 int conflicts;
3228 int obstructed;
3229 int not_updated;
3230 int missing;
3231 int not_deleted;
3232 int unversioned;
3233 int verbosity;
3236 static void
3237 print_update_progress_stats(struct got_update_progress_arg *upa)
3239 if (!upa->did_something)
3240 return;
3242 if (upa->conflicts > 0)
3243 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3244 if (upa->obstructed > 0)
3245 printf("File paths obstructed by a non-regular file: %d\n",
3246 upa->obstructed);
3247 if (upa->not_updated > 0)
3248 printf("Files not updated because of existing merge "
3249 "conflicts: %d\n", upa->not_updated);
3253 * The meaning of some status codes differs between merge-style operations and
3254 * update operations. For example, the ! status code means "file was missing"
3255 * if changes were merged into the work tree, and "missing file was restored"
3256 * if the work tree was updated. This function should be used by any operation
3257 * which merges changes into the work tree without updating the work tree.
3259 static void
3260 print_merge_progress_stats(struct got_update_progress_arg *upa)
3262 if (!upa->did_something)
3263 return;
3265 if (upa->conflicts > 0)
3266 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3267 if (upa->obstructed > 0)
3268 printf("File paths obstructed by a non-regular file: %d\n",
3269 upa->obstructed);
3270 if (upa->missing > 0)
3271 printf("Files which had incoming changes but could not be "
3272 "found in the work tree: %d\n", upa->missing);
3273 if (upa->not_deleted > 0)
3274 printf("Files not deleted due to differences in deleted "
3275 "content: %d\n", upa->not_deleted);
3276 if (upa->unversioned > 0)
3277 printf("Files not merged because an unversioned file was "
3278 "found in the work tree: %d\n", upa->unversioned);
3281 __dead static void
3282 usage_update(void)
3284 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3285 "[path ...]\n", getprogname());
3286 exit(1);
3289 static const struct got_error *
3290 update_progress(void *arg, unsigned char status, const char *path)
3292 struct got_update_progress_arg *upa = arg;
3294 if (status == GOT_STATUS_EXISTS ||
3295 status == GOT_STATUS_BASE_REF_ERR)
3296 return NULL;
3298 upa->did_something = 1;
3300 /* Base commit bump happens silently. */
3301 if (status == GOT_STATUS_BUMP_BASE)
3302 return NULL;
3304 if (status == GOT_STATUS_CONFLICT)
3305 upa->conflicts++;
3306 if (status == GOT_STATUS_OBSTRUCTED)
3307 upa->obstructed++;
3308 if (status == GOT_STATUS_CANNOT_UPDATE)
3309 upa->not_updated++;
3310 if (status == GOT_STATUS_MISSING)
3311 upa->missing++;
3312 if (status == GOT_STATUS_CANNOT_DELETE)
3313 upa->not_deleted++;
3314 if (status == GOT_STATUS_UNVERSIONED)
3315 upa->unversioned++;
3317 while (path[0] == '/')
3318 path++;
3319 if (upa->verbosity >= 0)
3320 printf("%c %s\n", status, path);
3322 return NULL;
3325 static const struct got_error *
3326 switch_head_ref(struct got_reference *head_ref,
3327 struct got_object_id *commit_id, struct got_worktree *worktree,
3328 struct got_repository *repo)
3330 const struct got_error *err = NULL;
3331 char *base_id_str;
3332 int ref_has_moved = 0;
3334 /* Trivial case: switching between two different references. */
3335 if (strcmp(got_ref_get_name(head_ref),
3336 got_worktree_get_head_ref_name(worktree)) != 0) {
3337 printf("Switching work tree from %s to %s\n",
3338 got_worktree_get_head_ref_name(worktree),
3339 got_ref_get_name(head_ref));
3340 return got_worktree_set_head_ref(worktree, head_ref);
3343 err = check_linear_ancestry(commit_id,
3344 got_worktree_get_base_commit_id(worktree), 0, repo);
3345 if (err) {
3346 if (err->code != GOT_ERR_ANCESTRY)
3347 return err;
3348 ref_has_moved = 1;
3350 if (!ref_has_moved)
3351 return NULL;
3353 /* Switching to a rebased branch with the same reference name. */
3354 err = got_object_id_str(&base_id_str,
3355 got_worktree_get_base_commit_id(worktree));
3356 if (err)
3357 return err;
3358 printf("Reference %s now points at a different branch\n",
3359 got_worktree_get_head_ref_name(worktree));
3360 printf("Switching work tree from %s to %s\n", base_id_str,
3361 got_worktree_get_head_ref_name(worktree));
3362 return NULL;
3365 static const struct got_error *
3366 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3368 const struct got_error *err;
3369 int in_progress;
3371 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3372 if (err)
3373 return err;
3374 if (in_progress)
3375 return got_error(GOT_ERR_REBASING);
3377 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3378 if (err)
3379 return err;
3380 if (in_progress)
3381 return got_error(GOT_ERR_HISTEDIT_BUSY);
3383 return NULL;
3386 static const struct got_error *
3387 check_merge_in_progress(struct got_worktree *worktree,
3388 struct got_repository *repo)
3390 const struct got_error *err;
3391 int in_progress;
3393 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3394 if (err)
3395 return err;
3396 if (in_progress)
3397 return got_error(GOT_ERR_MERGE_BUSY);
3399 return NULL;
3402 static const struct got_error *
3403 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3404 char *argv[], struct got_worktree *worktree)
3406 const struct got_error *err = NULL;
3407 char *path;
3408 struct got_pathlist_entry *new;
3409 int i;
3411 if (argc == 0) {
3412 path = strdup("");
3413 if (path == NULL)
3414 return got_error_from_errno("strdup");
3415 return got_pathlist_append(paths, path, NULL);
3418 for (i = 0; i < argc; i++) {
3419 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3420 if (err)
3421 break;
3422 err = got_pathlist_insert(&new, paths, path, NULL);
3423 if (err || new == NULL /* duplicate */) {
3424 free(path);
3425 if (err)
3426 break;
3430 return err;
3433 static const struct got_error *
3434 wrap_not_worktree_error(const struct got_error *orig_err,
3435 const char *cmdname, const char *path)
3437 const struct got_error *err;
3438 struct got_repository *repo;
3439 static char msg[512];
3440 int *pack_fds = NULL;
3442 err = got_repo_pack_fds_open(&pack_fds);
3443 if (err)
3444 return err;
3446 err = got_repo_open(&repo, path, NULL, pack_fds);
3447 if (err)
3448 return orig_err;
3450 snprintf(msg, sizeof(msg),
3451 "'got %s' needs a work tree in addition to a git repository\n"
3452 "Work trees can be checked out from this Git repository with "
3453 "'got checkout'.\n"
3454 "The got(1) manual page contains more information.", cmdname);
3455 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3456 got_repo_close(repo);
3457 if (pack_fds) {
3458 const struct got_error *pack_err =
3459 got_repo_pack_fds_close(pack_fds);
3460 if (err == NULL)
3461 err = pack_err;
3463 return err;
3466 static const struct got_error *
3467 cmd_update(int argc, char *argv[])
3469 const struct got_error *error = NULL;
3470 struct got_repository *repo = NULL;
3471 struct got_worktree *worktree = NULL;
3472 char *worktree_path = NULL;
3473 struct got_object_id *commit_id = NULL;
3474 char *commit_id_str = NULL;
3475 const char *branch_name = NULL;
3476 struct got_reference *head_ref = NULL;
3477 struct got_pathlist_head paths;
3478 struct got_pathlist_entry *pe;
3479 int ch, verbosity = 0;
3480 struct got_update_progress_arg upa;
3481 int *pack_fds = NULL;
3483 TAILQ_INIT(&paths);
3485 #ifndef PROFILE
3486 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3487 "unveil", NULL) == -1)
3488 err(1, "pledge");
3489 #endif
3491 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3492 switch (ch) {
3493 case 'b':
3494 branch_name = optarg;
3495 break;
3496 case 'c':
3497 commit_id_str = strdup(optarg);
3498 if (commit_id_str == NULL)
3499 return got_error_from_errno("strdup");
3500 break;
3501 case 'q':
3502 verbosity = -1;
3503 break;
3504 default:
3505 usage_update();
3506 /* NOTREACHED */
3510 argc -= optind;
3511 argv += optind;
3513 worktree_path = getcwd(NULL, 0);
3514 if (worktree_path == NULL) {
3515 error = got_error_from_errno("getcwd");
3516 goto done;
3519 error = got_repo_pack_fds_open(&pack_fds);
3520 if (error != NULL)
3521 goto done;
3523 error = got_worktree_open(&worktree, worktree_path);
3524 if (error) {
3525 if (error->code == GOT_ERR_NOT_WORKTREE)
3526 error = wrap_not_worktree_error(error, "update",
3527 worktree_path);
3528 goto done;
3531 error = check_rebase_or_histedit_in_progress(worktree);
3532 if (error)
3533 goto done;
3535 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3536 NULL, pack_fds);
3537 if (error != NULL)
3538 goto done;
3540 error = apply_unveil(got_repo_get_path(repo), 0,
3541 got_worktree_get_root_path(worktree));
3542 if (error)
3543 goto done;
3545 error = check_merge_in_progress(worktree, repo);
3546 if (error)
3547 goto done;
3549 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3550 if (error)
3551 goto done;
3553 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3554 got_worktree_get_head_ref_name(worktree), 0);
3555 if (error != NULL)
3556 goto done;
3557 if (commit_id_str == NULL) {
3558 error = got_ref_resolve(&commit_id, repo, head_ref);
3559 if (error != NULL)
3560 goto done;
3561 error = got_object_id_str(&commit_id_str, commit_id);
3562 if (error != NULL)
3563 goto done;
3564 } else {
3565 struct got_reflist_head refs;
3566 TAILQ_INIT(&refs);
3567 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3568 NULL);
3569 if (error)
3570 goto done;
3571 error = got_repo_match_object_id(&commit_id, NULL,
3572 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3573 got_ref_list_free(&refs);
3574 free(commit_id_str);
3575 commit_id_str = NULL;
3576 if (error)
3577 goto done;
3578 error = got_object_id_str(&commit_id_str, commit_id);
3579 if (error)
3580 goto done;
3583 if (branch_name) {
3584 struct got_object_id *head_commit_id;
3585 TAILQ_FOREACH(pe, &paths, entry) {
3586 if (pe->path_len == 0)
3587 continue;
3588 error = got_error_msg(GOT_ERR_BAD_PATH,
3589 "switching between branches requires that "
3590 "the entire work tree gets updated");
3591 goto done;
3593 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3594 if (error)
3595 goto done;
3596 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3597 repo);
3598 free(head_commit_id);
3599 if (error != NULL)
3600 goto done;
3601 error = check_same_branch(commit_id, head_ref, NULL, repo);
3602 if (error)
3603 goto done;
3604 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3605 if (error)
3606 goto done;
3607 } else {
3608 error = check_linear_ancestry(commit_id,
3609 got_worktree_get_base_commit_id(worktree), 0, repo);
3610 if (error != NULL) {
3611 if (error->code == GOT_ERR_ANCESTRY)
3612 error = got_error(GOT_ERR_BRANCH_MOVED);
3613 goto done;
3615 error = check_same_branch(commit_id, head_ref, NULL, repo);
3616 if (error)
3617 goto done;
3620 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3621 commit_id) != 0) {
3622 error = got_worktree_set_base_commit_id(worktree, repo,
3623 commit_id);
3624 if (error)
3625 goto done;
3628 memset(&upa, 0, sizeof(upa));
3629 upa.verbosity = verbosity;
3630 error = got_worktree_checkout_files(worktree, &paths, repo,
3631 update_progress, &upa, check_cancelled, NULL);
3632 if (error != NULL)
3633 goto done;
3635 if (upa.did_something) {
3636 printf("Updated to %s: %s\n",
3637 got_worktree_get_head_ref_name(worktree), commit_id_str);
3638 } else
3639 printf("Already up-to-date\n");
3641 print_update_progress_stats(&upa);
3642 done:
3643 if (pack_fds) {
3644 const struct got_error *pack_err =
3645 got_repo_pack_fds_close(pack_fds);
3646 if (error == NULL)
3647 error = pack_err;
3649 free(worktree_path);
3650 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3651 free(commit_id);
3652 free(commit_id_str);
3653 return error;
3656 static const struct got_error *
3657 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3658 const char *path, int diff_context, int ignore_whitespace,
3659 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3660 struct got_repository *repo, FILE *outfile)
3662 const struct got_error *err = NULL;
3663 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3664 FILE *f1 = NULL, *f2 = NULL;
3665 int fd1 = -1, fd2 = -1;
3667 fd1 = got_opentempfd();
3668 if (fd1 == -1)
3669 return got_error_from_errno("got_opentempfd");
3670 fd2 = got_opentempfd();
3671 if (fd2 == -1) {
3672 err = got_error_from_errno("got_opentempfd");
3673 goto done;
3676 if (blob_id1) {
3677 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3678 fd1);
3679 if (err)
3680 goto done;
3683 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3684 if (err)
3685 goto done;
3687 f1 = got_opentemp();
3688 if (f1 == NULL) {
3689 err = got_error_from_errno("got_opentemp");
3690 goto done;
3692 f2 = got_opentemp();
3693 if (f2 == NULL) {
3694 err = got_error_from_errno("got_opentemp");
3695 goto done;
3698 while (path[0] == '/')
3699 path++;
3700 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3701 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3702 force_text_diff, dsa, outfile);
3703 done:
3704 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3705 err = got_error_from_errno("close");
3706 if (blob1)
3707 got_object_blob_close(blob1);
3708 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3709 err = got_error_from_errno("close");
3710 got_object_blob_close(blob2);
3711 if (f1 && fclose(f1) == EOF && err == NULL)
3712 err = got_error_from_errno("fclose");
3713 if (f2 && fclose(f2) == EOF && err == NULL)
3714 err = got_error_from_errno("fclose");
3715 return err;
3718 static const struct got_error *
3719 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3720 const char *path, int diff_context, int ignore_whitespace,
3721 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3722 struct got_repository *repo, FILE *outfile)
3724 const struct got_error *err = NULL;
3725 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3726 struct got_diff_blob_output_unidiff_arg arg;
3727 FILE *f1 = NULL, *f2 = NULL;
3728 int fd1 = -1, fd2 = -1;
3730 if (tree_id1) {
3731 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3732 if (err)
3733 goto done;
3734 fd1 = got_opentempfd();
3735 if (fd1 == -1) {
3736 err = got_error_from_errno("got_opentempfd");
3737 goto done;
3741 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3742 if (err)
3743 goto done;
3745 f1 = got_opentemp();
3746 if (f1 == NULL) {
3747 err = got_error_from_errno("got_opentemp");
3748 goto done;
3751 f2 = got_opentemp();
3752 if (f2 == NULL) {
3753 err = got_error_from_errno("got_opentemp");
3754 goto done;
3756 fd2 = got_opentempfd();
3757 if (fd2 == -1) {
3758 err = got_error_from_errno("got_opentempfd");
3759 goto done;
3761 arg.diff_context = diff_context;
3762 arg.ignore_whitespace = ignore_whitespace;
3763 arg.force_text_diff = force_text_diff;
3764 arg.diffstat = dsa;
3765 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3766 arg.outfile = outfile;
3767 arg.lines = NULL;
3768 arg.nlines = 0;
3769 while (path[0] == '/')
3770 path++;
3771 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3772 got_diff_blob_output_unidiff, &arg, 1);
3773 done:
3774 if (tree1)
3775 got_object_tree_close(tree1);
3776 if (tree2)
3777 got_object_tree_close(tree2);
3778 if (f1 && fclose(f1) == EOF && err == NULL)
3779 err = got_error_from_errno("fclose");
3780 if (f2 && fclose(f2) == EOF && err == NULL)
3781 err = got_error_from_errno("fclose");
3782 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3783 err = got_error_from_errno("close");
3784 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3785 err = got_error_from_errno("close");
3786 return err;
3789 static const struct got_error *
3790 get_changed_paths(struct got_pathlist_head *paths,
3791 struct got_commit_object *commit, struct got_repository *repo,
3792 struct got_diffstat_cb_arg *dsa)
3794 const struct got_error *err = NULL;
3795 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3796 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3797 struct got_object_qid *qid;
3798 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3799 FILE *f1 = NULL, *f2 = NULL;
3800 int fd1 = -1, fd2 = -1;
3802 if (dsa) {
3803 cb = got_diff_tree_compute_diffstat;
3805 f1 = got_opentemp();
3806 if (f1 == NULL) {
3807 err = got_error_from_errno("got_opentemp");
3808 goto done;
3810 f2 = got_opentemp();
3811 if (f2 == NULL) {
3812 err = got_error_from_errno("got_opentemp");
3813 goto done;
3815 fd1 = got_opentempfd();
3816 if (fd1 == -1) {
3817 err = got_error_from_errno("got_opentempfd");
3818 goto done;
3820 fd2 = got_opentempfd();
3821 if (fd2 == -1) {
3822 err = got_error_from_errno("got_opentempfd");
3823 goto done;
3827 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3828 if (qid != NULL) {
3829 struct got_commit_object *pcommit;
3830 err = got_object_open_as_commit(&pcommit, repo,
3831 &qid->id);
3832 if (err)
3833 return err;
3835 tree_id1 = got_object_id_dup(
3836 got_object_commit_get_tree_id(pcommit));
3837 if (tree_id1 == NULL) {
3838 got_object_commit_close(pcommit);
3839 return got_error_from_errno("got_object_id_dup");
3841 got_object_commit_close(pcommit);
3845 if (tree_id1) {
3846 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3847 if (err)
3848 goto done;
3851 tree_id2 = got_object_commit_get_tree_id(commit);
3852 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3853 if (err)
3854 goto done;
3856 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3857 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3858 done:
3859 if (tree1)
3860 got_object_tree_close(tree1);
3861 if (tree2)
3862 got_object_tree_close(tree2);
3863 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3864 err = got_error_from_errno("close");
3865 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3866 err = got_error_from_errno("close");
3867 if (f1 && fclose(f1) == EOF && err == NULL)
3868 err = got_error_from_errno("fclose");
3869 if (f2 && fclose(f2) == EOF && err == NULL)
3870 err = got_error_from_errno("fclose");
3871 free(tree_id1);
3872 return err;
3875 static const struct got_error *
3876 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3877 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3878 struct got_repository *repo, FILE *outfile)
3880 const struct got_error *err = NULL;
3881 struct got_commit_object *pcommit = NULL;
3882 char *id_str1 = NULL, *id_str2 = NULL;
3883 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3884 struct got_object_qid *qid;
3886 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3887 if (qid != NULL) {
3888 err = got_object_open_as_commit(&pcommit, repo,
3889 &qid->id);
3890 if (err)
3891 return err;
3892 err = got_object_id_str(&id_str1, &qid->id);
3893 if (err)
3894 goto done;
3897 err = got_object_id_str(&id_str2, id);
3898 if (err)
3899 goto done;
3901 if (path && path[0] != '\0') {
3902 int obj_type;
3903 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3904 if (err)
3905 goto done;
3906 if (pcommit) {
3907 err = got_object_id_by_path(&obj_id1, repo,
3908 pcommit, path);
3909 if (err) {
3910 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3911 free(obj_id2);
3912 goto done;
3916 err = got_object_get_type(&obj_type, repo, obj_id2);
3917 if (err) {
3918 free(obj_id2);
3919 goto done;
3921 fprintf(outfile,
3922 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3923 fprintf(outfile, "commit - %s\n",
3924 id_str1 ? id_str1 : "/dev/null");
3925 fprintf(outfile, "commit + %s\n", id_str2);
3926 switch (obj_type) {
3927 case GOT_OBJ_TYPE_BLOB:
3928 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3929 0, 0, dsa, repo, outfile);
3930 break;
3931 case GOT_OBJ_TYPE_TREE:
3932 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3933 0, 0, dsa, repo, outfile);
3934 break;
3935 default:
3936 err = got_error(GOT_ERR_OBJ_TYPE);
3937 break;
3939 free(obj_id1);
3940 free(obj_id2);
3941 } else {
3942 obj_id2 = got_object_commit_get_tree_id(commit);
3943 if (pcommit)
3944 obj_id1 = got_object_commit_get_tree_id(pcommit);
3945 fprintf(outfile,
3946 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3947 fprintf(outfile, "commit - %s\n",
3948 id_str1 ? id_str1 : "/dev/null");
3949 fprintf(outfile, "commit + %s\n", id_str2);
3950 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3951 dsa, repo, outfile);
3953 done:
3954 free(id_str1);
3955 free(id_str2);
3956 if (pcommit)
3957 got_object_commit_close(pcommit);
3958 return err;
3961 static char *
3962 get_datestr(time_t *time, char *datebuf)
3964 struct tm mytm, *tm;
3965 char *p, *s;
3967 tm = gmtime_r(time, &mytm);
3968 if (tm == NULL)
3969 return NULL;
3970 s = asctime_r(tm, datebuf);
3971 if (s == NULL)
3972 return NULL;
3973 p = strchr(s, '\n');
3974 if (p)
3975 *p = '\0';
3976 return s;
3979 static const struct got_error *
3980 match_commit(int *have_match, struct got_object_id *id,
3981 struct got_commit_object *commit, regex_t *regex)
3983 const struct got_error *err = NULL;
3984 regmatch_t regmatch;
3985 char *id_str = NULL, *logmsg = NULL;
3987 *have_match = 0;
3989 err = got_object_id_str(&id_str, id);
3990 if (err)
3991 return err;
3993 err = got_object_commit_get_logmsg(&logmsg, commit);
3994 if (err)
3995 goto done;
3997 if (regexec(regex, got_object_commit_get_author(commit), 1,
3998 &regmatch, 0) == 0 ||
3999 regexec(regex, got_object_commit_get_committer(commit), 1,
4000 &regmatch, 0) == 0 ||
4001 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4002 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4003 *have_match = 1;
4004 done:
4005 free(id_str);
4006 free(logmsg);
4007 return err;
4010 static void
4011 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4012 regex_t *regex)
4014 regmatch_t regmatch;
4015 struct got_pathlist_entry *pe;
4017 *have_match = 0;
4019 TAILQ_FOREACH(pe, changed_paths, entry) {
4020 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4021 *have_match = 1;
4022 break;
4027 static const struct got_error *
4028 match_patch(int *have_match, struct got_commit_object *commit,
4029 struct got_object_id *id, const char *path, int diff_context,
4030 struct got_repository *repo, regex_t *regex, FILE *f)
4032 const struct got_error *err = NULL;
4033 char *line = NULL;
4034 size_t linesize = 0;
4035 regmatch_t regmatch;
4037 *have_match = 0;
4039 err = got_opentemp_truncate(f);
4040 if (err)
4041 return err;
4043 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4044 if (err)
4045 goto done;
4047 if (fseeko(f, 0L, SEEK_SET) == -1) {
4048 err = got_error_from_errno("fseeko");
4049 goto done;
4052 while (getline(&line, &linesize, f) != -1) {
4053 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4054 *have_match = 1;
4055 break;
4058 done:
4059 free(line);
4060 return err;
4063 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4065 static const struct got_error*
4066 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4067 struct got_object_id *id, struct got_repository *repo,
4068 int local_only)
4070 static const struct got_error *err = NULL;
4071 struct got_reflist_entry *re;
4072 char *s;
4073 const char *name;
4075 *refs_str = NULL;
4077 TAILQ_FOREACH(re, refs, entry) {
4078 struct got_tag_object *tag = NULL;
4079 struct got_object_id *ref_id;
4080 int cmp;
4082 name = got_ref_get_name(re->ref);
4083 if (strcmp(name, GOT_REF_HEAD) == 0)
4084 continue;
4085 if (strncmp(name, "refs/", 5) == 0)
4086 name += 5;
4087 if (strncmp(name, "got/", 4) == 0)
4088 continue;
4089 if (strncmp(name, "heads/", 6) == 0)
4090 name += 6;
4091 if (strncmp(name, "remotes/", 8) == 0) {
4092 if (local_only)
4093 continue;
4094 name += 8;
4095 s = strstr(name, "/" GOT_REF_HEAD);
4096 if (s != NULL && s[strlen(s)] == '\0')
4097 continue;
4099 err = got_ref_resolve(&ref_id, repo, re->ref);
4100 if (err)
4101 break;
4102 if (strncmp(name, "tags/", 5) == 0) {
4103 err = got_object_open_as_tag(&tag, repo, ref_id);
4104 if (err) {
4105 if (err->code != GOT_ERR_OBJ_TYPE) {
4106 free(ref_id);
4107 break;
4109 /* Ref points at something other than a tag. */
4110 err = NULL;
4111 tag = NULL;
4114 cmp = got_object_id_cmp(tag ?
4115 got_object_tag_get_object_id(tag) : ref_id, id);
4116 free(ref_id);
4117 if (tag)
4118 got_object_tag_close(tag);
4119 if (cmp != 0)
4120 continue;
4121 s = *refs_str;
4122 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4123 s ? ", " : "", name) == -1) {
4124 err = got_error_from_errno("asprintf");
4125 free(s);
4126 *refs_str = NULL;
4127 break;
4129 free(s);
4132 return err;
4135 static const struct got_error *
4136 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4137 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4139 const struct got_error *err = NULL;
4140 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4141 char *comma, *s, *nl;
4142 struct got_reflist_head *refs;
4143 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4144 struct tm tm;
4145 time_t committer_time;
4147 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4148 if (refs) {
4149 err = build_refs_str(&ref_str, refs, id, repo, 1);
4150 if (err)
4151 return err;
4153 /* Display the first matching ref only. */
4154 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4155 *comma = '\0';
4158 if (ref_str == NULL) {
4159 err = got_object_id_str(&id_str, id);
4160 if (err)
4161 return err;
4164 committer_time = got_object_commit_get_committer_time(commit);
4165 if (gmtime_r(&committer_time, &tm) == NULL) {
4166 err = got_error_from_errno("gmtime_r");
4167 goto done;
4169 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4170 err = got_error(GOT_ERR_NO_SPACE);
4171 goto done;
4174 err = got_object_commit_get_logmsg(&logmsg0, commit);
4175 if (err)
4176 goto done;
4178 s = logmsg0;
4179 while (isspace((unsigned char)s[0]))
4180 s++;
4182 nl = strchr(s, '\n');
4183 if (nl) {
4184 *nl = '\0';
4187 if (ref_str)
4188 printf("%s%-7s %s\n", datebuf, ref_str, s);
4189 else
4190 printf("%s%.7s %s\n", datebuf, id_str, s);
4192 if (fflush(stdout) != 0 && err == NULL)
4193 err = got_error_from_errno("fflush");
4194 done:
4195 free(id_str);
4196 free(ref_str);
4197 free(logmsg0);
4198 return err;
4201 static const struct got_error *
4202 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4204 struct got_pathlist_entry *pe;
4206 if (header != NULL)
4207 printf("%s\n", header);
4209 TAILQ_FOREACH(pe, dsa->paths, entry) {
4210 struct got_diff_changed_path *cp = pe->data;
4211 int pad = dsa->max_path_len - pe->path_len + 1;
4213 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4214 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4216 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4217 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4218 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4220 if (fflush(stdout) != 0)
4221 return got_error_from_errno("fflush");
4223 return NULL;
4226 static const struct got_error *
4227 printfile(FILE *f)
4229 char buf[8192];
4230 size_t r;
4232 if (fseeko(f, 0L, SEEK_SET) == -1)
4233 return got_error_from_errno("fseek");
4235 for (;;) {
4236 r = fread(buf, 1, sizeof(buf), f);
4237 if (r == 0) {
4238 if (ferror(f))
4239 return got_error_from_errno("fread");
4240 if (feof(f))
4241 break;
4243 if (fwrite(buf, 1, r, stdout) != r)
4244 return got_ferror(stdout, GOT_ERR_IO);
4247 return NULL;
4250 static const struct got_error *
4251 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4252 struct got_repository *repo, const char *path,
4253 struct got_pathlist_head *changed_paths,
4254 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4255 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4256 const char *prefix)
4258 const struct got_error *err = NULL;
4259 FILE *f = NULL;
4260 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4261 char datebuf[26];
4262 time_t committer_time;
4263 const char *author, *committer;
4264 char *refs_str = NULL;
4266 err = got_object_id_str(&id_str, id);
4267 if (err)
4268 return err;
4270 if (custom_refs_str == NULL) {
4271 struct got_reflist_head *refs;
4272 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4273 if (refs) {
4274 err = build_refs_str(&refs_str, refs, id, repo, 0);
4275 if (err)
4276 goto done;
4280 printf(GOT_COMMIT_SEP_STR);
4281 if (custom_refs_str)
4282 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4283 custom_refs_str);
4284 else
4285 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4286 refs_str ? " (" : "", refs_str ? refs_str : "",
4287 refs_str ? ")" : "");
4288 free(id_str);
4289 id_str = NULL;
4290 free(refs_str);
4291 refs_str = NULL;
4292 printf("from: %s\n", got_object_commit_get_author(commit));
4293 author = got_object_commit_get_author(commit);
4294 committer = got_object_commit_get_committer(commit);
4295 if (strcmp(author, committer) != 0)
4296 printf("via: %s\n", committer);
4297 committer_time = got_object_commit_get_committer_time(commit);
4298 datestr = get_datestr(&committer_time, datebuf);
4299 if (datestr)
4300 printf("date: %s UTC\n", datestr);
4301 if (got_object_commit_get_nparents(commit) > 1) {
4302 const struct got_object_id_queue *parent_ids;
4303 struct got_object_qid *qid;
4304 int n = 1;
4305 parent_ids = got_object_commit_get_parent_ids(commit);
4306 STAILQ_FOREACH(qid, parent_ids, entry) {
4307 err = got_object_id_str(&id_str, &qid->id);
4308 if (err)
4309 goto done;
4310 printf("parent %d: %s\n", n++, id_str);
4311 free(id_str);
4312 id_str = NULL;
4316 err = got_object_commit_get_logmsg(&logmsg0, commit);
4317 if (err)
4318 goto done;
4320 logmsg = logmsg0;
4321 do {
4322 line = strsep(&logmsg, "\n");
4323 if (line)
4324 printf(" %s\n", line);
4325 } while (line);
4326 free(logmsg0);
4328 if (changed_paths && diffstat == NULL) {
4329 struct got_pathlist_entry *pe;
4331 TAILQ_FOREACH(pe, changed_paths, entry) {
4332 struct got_diff_changed_path *cp = pe->data;
4334 printf(" %c %s\n", cp->status, pe->path);
4336 printf("\n");
4338 if (show_patch) {
4339 if (diffstat) {
4340 f = got_opentemp();
4341 if (f == NULL) {
4342 err = got_error_from_errno("got_opentemp");
4343 goto done;
4347 err = print_patch(commit, id, path, diff_context, diffstat,
4348 repo, diffstat == NULL ? stdout : f);
4349 if (err)
4350 goto done;
4352 if (diffstat) {
4353 err = print_diffstat(diffstat, NULL);
4354 if (err)
4355 goto done;
4356 if (show_patch) {
4357 err = printfile(f);
4358 if (err)
4359 goto done;
4362 if (show_patch)
4363 printf("\n");
4365 if (fflush(stdout) != 0 && err == NULL)
4366 err = got_error_from_errno("fflush");
4367 done:
4368 if (f && fclose(f) == EOF && err == NULL)
4369 err = got_error_from_errno("fclose");
4370 free(id_str);
4371 free(refs_str);
4372 return err;
4375 static const struct got_error *
4376 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4377 struct got_repository *repo, const char *path, int show_changed_paths,
4378 int show_diffstat, int show_patch, const char *search_pattern,
4379 int diff_context, int limit, int log_branches, int reverse_display_order,
4380 struct got_reflist_object_id_map *refs_idmap, int one_line,
4381 FILE *tmpfile)
4383 const struct got_error *err;
4384 struct got_commit_graph *graph;
4385 regex_t regex;
4386 int have_match;
4387 struct got_object_id_queue reversed_commits;
4388 struct got_object_qid *qid;
4389 struct got_commit_object *commit;
4390 struct got_pathlist_head changed_paths;
4392 STAILQ_INIT(&reversed_commits);
4393 TAILQ_INIT(&changed_paths);
4395 if (search_pattern && regcomp(&regex, search_pattern,
4396 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4397 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4399 err = got_commit_graph_open(&graph, path, !log_branches);
4400 if (err)
4401 return err;
4402 err = got_commit_graph_iter_start(graph, root_id, repo,
4403 check_cancelled, NULL);
4404 if (err)
4405 goto done;
4406 for (;;) {
4407 struct got_object_id id;
4408 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4409 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4411 if (sigint_received || sigpipe_received)
4412 break;
4414 err = got_commit_graph_iter_next(&id, graph, repo,
4415 check_cancelled, NULL);
4416 if (err) {
4417 if (err->code == GOT_ERR_ITER_COMPLETED)
4418 err = NULL;
4419 break;
4422 err = got_object_open_as_commit(&commit, repo, &id);
4423 if (err)
4424 break;
4426 if ((show_changed_paths || (show_diffstat && !show_patch))
4427 && !reverse_display_order) {
4428 err = get_changed_paths(&changed_paths, commit, repo,
4429 show_diffstat ? &dsa : NULL);
4430 if (err)
4431 break;
4434 if (search_pattern) {
4435 err = match_commit(&have_match, &id, commit, &regex);
4436 if (err) {
4437 got_object_commit_close(commit);
4438 break;
4440 if (have_match == 0 && show_changed_paths)
4441 match_changed_paths(&have_match,
4442 &changed_paths, &regex);
4443 if (have_match == 0 && show_patch) {
4444 err = match_patch(&have_match, commit, &id,
4445 path, diff_context, repo, &regex, tmpfile);
4446 if (err)
4447 break;
4449 if (have_match == 0) {
4450 got_object_commit_close(commit);
4451 got_pathlist_free(&changed_paths,
4452 GOT_PATHLIST_FREE_ALL);
4453 continue;
4457 if (reverse_display_order) {
4458 err = got_object_qid_alloc(&qid, &id);
4459 if (err)
4460 break;
4461 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4462 got_object_commit_close(commit);
4463 } else {
4464 if (one_line)
4465 err = print_commit_oneline(commit, &id,
4466 repo, refs_idmap);
4467 else
4468 err = print_commit(commit, &id, repo, path,
4469 (show_changed_paths || show_diffstat) ?
4470 &changed_paths : NULL,
4471 show_diffstat ? &dsa : NULL, show_patch,
4472 diff_context, refs_idmap, NULL, NULL);
4473 got_object_commit_close(commit);
4474 if (err)
4475 break;
4477 if ((limit && --limit == 0) ||
4478 (end_id && got_object_id_cmp(&id, end_id) == 0))
4479 break;
4481 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4483 if (reverse_display_order) {
4484 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4485 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4486 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4488 err = got_object_open_as_commit(&commit, repo,
4489 &qid->id);
4490 if (err)
4491 break;
4492 if (show_changed_paths ||
4493 (show_diffstat && !show_patch)) {
4494 err = get_changed_paths(&changed_paths, commit,
4495 repo, show_diffstat ? &dsa : NULL);
4496 if (err)
4497 break;
4499 if (one_line)
4500 err = print_commit_oneline(commit, &qid->id,
4501 repo, refs_idmap);
4502 else
4503 err = print_commit(commit, &qid->id, repo, path,
4504 (show_changed_paths || show_diffstat) ?
4505 &changed_paths : NULL,
4506 show_diffstat ? &dsa : NULL, show_patch,
4507 diff_context, refs_idmap, NULL, NULL);
4508 got_object_commit_close(commit);
4509 if (err)
4510 break;
4511 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4514 done:
4515 while (!STAILQ_EMPTY(&reversed_commits)) {
4516 qid = STAILQ_FIRST(&reversed_commits);
4517 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4518 got_object_qid_free(qid);
4520 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4521 if (search_pattern)
4522 regfree(&regex);
4523 got_commit_graph_close(graph);
4524 return err;
4527 __dead static void
4528 usage_log(void)
4530 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4531 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4532 "[path]\n", getprogname());
4533 exit(1);
4536 static int
4537 get_default_log_limit(void)
4539 const char *got_default_log_limit;
4540 long long n;
4541 const char *errstr;
4543 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4544 if (got_default_log_limit == NULL)
4545 return 0;
4546 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4547 if (errstr != NULL)
4548 return 0;
4549 return n;
4552 static const struct got_error *
4553 cmd_log(int argc, char *argv[])
4555 const struct got_error *error;
4556 struct got_repository *repo = NULL;
4557 struct got_worktree *worktree = NULL;
4558 struct got_object_id *start_id = NULL, *end_id = NULL;
4559 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4560 const char *start_commit = NULL, *end_commit = NULL;
4561 const char *search_pattern = NULL;
4562 int diff_context = -1, ch;
4563 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4564 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4565 const char *errstr;
4566 struct got_reflist_head refs;
4567 struct got_reflist_object_id_map *refs_idmap = NULL;
4568 FILE *tmpfile = NULL;
4569 int *pack_fds = NULL;
4571 TAILQ_INIT(&refs);
4573 #ifndef PROFILE
4574 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4575 NULL)
4576 == -1)
4577 err(1, "pledge");
4578 #endif
4580 limit = get_default_log_limit();
4582 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4583 switch (ch) {
4584 case 'b':
4585 log_branches = 1;
4586 break;
4587 case 'C':
4588 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4589 &errstr);
4590 if (errstr != NULL)
4591 errx(1, "number of context lines is %s: %s",
4592 errstr, optarg);
4593 break;
4594 case 'c':
4595 start_commit = optarg;
4596 break;
4597 case 'd':
4598 show_diffstat = 1;
4599 break;
4600 case 'l':
4601 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4602 if (errstr != NULL)
4603 errx(1, "number of commits is %s: %s",
4604 errstr, optarg);
4605 break;
4606 case 'P':
4607 show_changed_paths = 1;
4608 break;
4609 case 'p':
4610 show_patch = 1;
4611 break;
4612 case 'R':
4613 reverse_display_order = 1;
4614 break;
4615 case 'r':
4616 repo_path = realpath(optarg, NULL);
4617 if (repo_path == NULL)
4618 return got_error_from_errno2("realpath",
4619 optarg);
4620 got_path_strip_trailing_slashes(repo_path);
4621 break;
4622 case 'S':
4623 search_pattern = optarg;
4624 break;
4625 case 's':
4626 one_line = 1;
4627 break;
4628 case 'x':
4629 end_commit = optarg;
4630 break;
4631 default:
4632 usage_log();
4633 /* NOTREACHED */
4637 argc -= optind;
4638 argv += optind;
4640 if (diff_context == -1)
4641 diff_context = 3;
4642 else if (!show_patch)
4643 errx(1, "-C requires -p");
4645 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4646 errx(1, "cannot use -s with -d, -p or -P");
4648 cwd = getcwd(NULL, 0);
4649 if (cwd == NULL) {
4650 error = got_error_from_errno("getcwd");
4651 goto done;
4654 error = got_repo_pack_fds_open(&pack_fds);
4655 if (error != NULL)
4656 goto done;
4658 if (repo_path == NULL) {
4659 error = got_worktree_open(&worktree, cwd);
4660 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4661 goto done;
4662 error = NULL;
4665 if (argc == 1) {
4666 if (worktree) {
4667 error = got_worktree_resolve_path(&path, worktree,
4668 argv[0]);
4669 if (error)
4670 goto done;
4671 } else {
4672 path = strdup(argv[0]);
4673 if (path == NULL) {
4674 error = got_error_from_errno("strdup");
4675 goto done;
4678 } else if (argc != 0)
4679 usage_log();
4681 if (repo_path == NULL) {
4682 repo_path = worktree ?
4683 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4685 if (repo_path == NULL) {
4686 error = got_error_from_errno("strdup");
4687 goto done;
4690 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4691 if (error != NULL)
4692 goto done;
4694 error = apply_unveil(got_repo_get_path(repo), 1,
4695 worktree ? got_worktree_get_root_path(worktree) : NULL);
4696 if (error)
4697 goto done;
4699 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4700 if (error)
4701 goto done;
4703 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4704 if (error)
4705 goto done;
4707 if (start_commit == NULL) {
4708 struct got_reference *head_ref;
4709 struct got_commit_object *commit = NULL;
4710 error = got_ref_open(&head_ref, repo,
4711 worktree ? got_worktree_get_head_ref_name(worktree)
4712 : GOT_REF_HEAD, 0);
4713 if (error != NULL)
4714 goto done;
4715 error = got_ref_resolve(&start_id, repo, head_ref);
4716 got_ref_close(head_ref);
4717 if (error != NULL)
4718 goto done;
4719 error = got_object_open_as_commit(&commit, repo,
4720 start_id);
4721 if (error != NULL)
4722 goto done;
4723 got_object_commit_close(commit);
4724 } else {
4725 error = got_repo_match_object_id(&start_id, NULL,
4726 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4727 if (error != NULL)
4728 goto done;
4730 if (end_commit != NULL) {
4731 error = got_repo_match_object_id(&end_id, NULL,
4732 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4733 if (error != NULL)
4734 goto done;
4737 if (worktree) {
4739 * If a path was specified on the command line it was resolved
4740 * to a path in the work tree above. Prepend the work tree's
4741 * path prefix to obtain the corresponding in-repository path.
4743 if (path) {
4744 const char *prefix;
4745 prefix = got_worktree_get_path_prefix(worktree);
4746 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4747 (path[0] != '\0') ? "/" : "", path) == -1) {
4748 error = got_error_from_errno("asprintf");
4749 goto done;
4752 } else
4753 error = got_repo_map_path(&in_repo_path, repo,
4754 path ? path : "");
4755 if (error != NULL)
4756 goto done;
4757 if (in_repo_path) {
4758 free(path);
4759 path = in_repo_path;
4762 if (worktree) {
4763 /* Release work tree lock. */
4764 got_worktree_close(worktree);
4765 worktree = NULL;
4768 if (search_pattern && show_patch) {
4769 tmpfile = got_opentemp();
4770 if (tmpfile == NULL) {
4771 error = got_error_from_errno("got_opentemp");
4772 goto done;
4776 error = print_commits(start_id, end_id, repo, path ? path : "",
4777 show_changed_paths, show_diffstat, show_patch, search_pattern,
4778 diff_context, limit, log_branches, reverse_display_order,
4779 refs_idmap, one_line, tmpfile);
4780 done:
4781 free(path);
4782 free(repo_path);
4783 free(cwd);
4784 if (worktree)
4785 got_worktree_close(worktree);
4786 if (repo) {
4787 const struct got_error *close_err = got_repo_close(repo);
4788 if (error == NULL)
4789 error = close_err;
4791 if (pack_fds) {
4792 const struct got_error *pack_err =
4793 got_repo_pack_fds_close(pack_fds);
4794 if (error == NULL)
4795 error = pack_err;
4797 if (refs_idmap)
4798 got_reflist_object_id_map_free(refs_idmap);
4799 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4800 error = got_error_from_errno("fclose");
4801 got_ref_list_free(&refs);
4802 return error;
4805 __dead static void
4806 usage_diff(void)
4808 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4809 "[-r repository-path] [object1 object2 | path ...]\n",
4810 getprogname());
4811 exit(1);
4814 struct print_diff_arg {
4815 struct got_repository *repo;
4816 struct got_worktree *worktree;
4817 struct got_diffstat_cb_arg *diffstat;
4818 int diff_context;
4819 const char *id_str;
4820 int header_shown;
4821 int diff_staged;
4822 enum got_diff_algorithm diff_algo;
4823 int ignore_whitespace;
4824 int force_text_diff;
4825 FILE *f1;
4826 FILE *f2;
4827 FILE *outfile;
4831 * Create a file which contains the target path of a symlink so we can feed
4832 * it as content to the diff engine.
4834 static const struct got_error *
4835 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4836 const char *abspath)
4838 const struct got_error *err = NULL;
4839 char target_path[PATH_MAX];
4840 ssize_t target_len, outlen;
4842 *fd = -1;
4844 if (dirfd != -1) {
4845 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4846 if (target_len == -1)
4847 return got_error_from_errno2("readlinkat", abspath);
4848 } else {
4849 target_len = readlink(abspath, target_path, PATH_MAX);
4850 if (target_len == -1)
4851 return got_error_from_errno2("readlink", abspath);
4854 *fd = got_opentempfd();
4855 if (*fd == -1)
4856 return got_error_from_errno("got_opentempfd");
4858 outlen = write(*fd, target_path, target_len);
4859 if (outlen == -1) {
4860 err = got_error_from_errno("got_opentempfd");
4861 goto done;
4864 if (lseek(*fd, 0, SEEK_SET) == -1) {
4865 err = got_error_from_errno2("lseek", abspath);
4866 goto done;
4868 done:
4869 if (err) {
4870 close(*fd);
4871 *fd = -1;
4873 return err;
4876 static const struct got_error *
4877 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4878 const char *path, struct got_object_id *blob_id,
4879 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4880 int dirfd, const char *de_name)
4882 struct print_diff_arg *a = arg;
4883 const struct got_error *err = NULL;
4884 struct got_blob_object *blob1 = NULL;
4885 int fd = -1, fd1 = -1, fd2 = -1;
4886 FILE *f2 = NULL;
4887 char *abspath = NULL, *label1 = NULL;
4888 struct stat sb;
4889 off_t size1 = 0;
4890 int f2_exists = 0;
4892 memset(&sb, 0, sizeof(sb));
4894 if (a->diff_staged) {
4895 if (staged_status != GOT_STATUS_MODIFY &&
4896 staged_status != GOT_STATUS_ADD &&
4897 staged_status != GOT_STATUS_DELETE)
4898 return NULL;
4899 } else {
4900 if (staged_status == GOT_STATUS_DELETE)
4901 return NULL;
4902 if (status == GOT_STATUS_NONEXISTENT)
4903 return got_error_set_errno(ENOENT, path);
4904 if (status != GOT_STATUS_MODIFY &&
4905 status != GOT_STATUS_ADD &&
4906 status != GOT_STATUS_DELETE &&
4907 status != GOT_STATUS_CONFLICT)
4908 return NULL;
4911 err = got_opentemp_truncate(a->f1);
4912 if (err)
4913 return got_error_from_errno("got_opentemp_truncate");
4914 err = got_opentemp_truncate(a->f2);
4915 if (err)
4916 return got_error_from_errno("got_opentemp_truncate");
4918 if (!a->header_shown) {
4919 if (fprintf(a->outfile, "diff %s%s\n",
4920 a->diff_staged ? "-s " : "",
4921 got_worktree_get_root_path(a->worktree)) < 0) {
4922 err = got_error_from_errno("fprintf");
4923 goto done;
4925 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4926 err = got_error_from_errno("fprintf");
4927 goto done;
4929 if (fprintf(a->outfile, "path + %s%s\n",
4930 got_worktree_get_root_path(a->worktree),
4931 a->diff_staged ? " (staged changes)" : "") < 0) {
4932 err = got_error_from_errno("fprintf");
4933 goto done;
4935 a->header_shown = 1;
4938 if (a->diff_staged) {
4939 const char *label1 = NULL, *label2 = NULL;
4940 switch (staged_status) {
4941 case GOT_STATUS_MODIFY:
4942 label1 = path;
4943 label2 = path;
4944 break;
4945 case GOT_STATUS_ADD:
4946 label2 = path;
4947 break;
4948 case GOT_STATUS_DELETE:
4949 label1 = path;
4950 break;
4951 default:
4952 return got_error(GOT_ERR_FILE_STATUS);
4954 fd1 = got_opentempfd();
4955 if (fd1 == -1) {
4956 err = got_error_from_errno("got_opentempfd");
4957 goto done;
4959 fd2 = got_opentempfd();
4960 if (fd2 == -1) {
4961 err = got_error_from_errno("got_opentempfd");
4962 goto done;
4964 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4965 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4966 a->diff_algo, a->diff_context, a->ignore_whitespace,
4967 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4968 goto done;
4971 fd1 = got_opentempfd();
4972 if (fd1 == -1) {
4973 err = got_error_from_errno("got_opentempfd");
4974 goto done;
4977 if (staged_status == GOT_STATUS_ADD ||
4978 staged_status == GOT_STATUS_MODIFY) {
4979 char *id_str;
4980 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4981 8192, fd1);
4982 if (err)
4983 goto done;
4984 err = got_object_id_str(&id_str, staged_blob_id);
4985 if (err)
4986 goto done;
4987 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4988 err = got_error_from_errno("asprintf");
4989 free(id_str);
4990 goto done;
4992 free(id_str);
4993 } else if (status != GOT_STATUS_ADD) {
4994 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4995 fd1);
4996 if (err)
4997 goto done;
5000 if (status != GOT_STATUS_DELETE) {
5001 if (asprintf(&abspath, "%s/%s",
5002 got_worktree_get_root_path(a->worktree), path) == -1) {
5003 err = got_error_from_errno("asprintf");
5004 goto done;
5007 if (dirfd != -1) {
5008 fd = openat(dirfd, de_name,
5009 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5010 if (fd == -1) {
5011 if (!got_err_open_nofollow_on_symlink()) {
5012 err = got_error_from_errno2("openat",
5013 abspath);
5014 goto done;
5016 err = get_symlink_target_file(&fd, dirfd,
5017 de_name, abspath);
5018 if (err)
5019 goto done;
5021 } else {
5022 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5023 if (fd == -1) {
5024 if (!got_err_open_nofollow_on_symlink()) {
5025 err = got_error_from_errno2("open",
5026 abspath);
5027 goto done;
5029 err = get_symlink_target_file(&fd, dirfd,
5030 de_name, abspath);
5031 if (err)
5032 goto done;
5035 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5036 err = got_error_from_errno2("fstatat", abspath);
5037 goto done;
5039 f2 = fdopen(fd, "r");
5040 if (f2 == NULL) {
5041 err = got_error_from_errno2("fdopen", abspath);
5042 goto done;
5044 fd = -1;
5045 f2_exists = 1;
5048 if (blob1) {
5049 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5050 a->f1, blob1);
5051 if (err)
5052 goto done;
5055 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5056 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5057 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5058 done:
5059 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5060 err = got_error_from_errno("close");
5061 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5062 err = got_error_from_errno("close");
5063 if (blob1)
5064 got_object_blob_close(blob1);
5065 if (fd != -1 && close(fd) == -1 && err == NULL)
5066 err = got_error_from_errno("close");
5067 if (f2 && fclose(f2) == EOF && err == NULL)
5068 err = got_error_from_errno("fclose");
5069 free(abspath);
5070 return err;
5073 static const struct got_error *
5074 cmd_diff(int argc, char *argv[])
5076 const struct got_error *error;
5077 struct got_repository *repo = NULL;
5078 struct got_worktree *worktree = NULL;
5079 char *cwd = NULL, *repo_path = NULL;
5080 const char *commit_args[2] = { NULL, NULL };
5081 int ncommit_args = 0;
5082 struct got_object_id *ids[2] = { NULL, NULL };
5083 char *labels[2] = { NULL, NULL };
5084 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5085 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5086 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5087 const char *errstr;
5088 struct got_reflist_head refs;
5089 struct got_pathlist_head diffstat_paths, paths;
5090 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5091 int fd1 = -1, fd2 = -1;
5092 int *pack_fds = NULL;
5093 struct got_diffstat_cb_arg dsa;
5095 memset(&dsa, 0, sizeof(dsa));
5097 TAILQ_INIT(&refs);
5098 TAILQ_INIT(&paths);
5099 TAILQ_INIT(&diffstat_paths);
5101 #ifndef PROFILE
5102 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5103 NULL) == -1)
5104 err(1, "pledge");
5105 #endif
5107 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5108 switch (ch) {
5109 case 'a':
5110 force_text_diff = 1;
5111 break;
5112 case 'C':
5113 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5114 &errstr);
5115 if (errstr != NULL)
5116 errx(1, "number of context lines is %s: %s",
5117 errstr, optarg);
5118 break;
5119 case 'c':
5120 if (ncommit_args >= 2)
5121 errx(1, "too many -c options used");
5122 commit_args[ncommit_args++] = optarg;
5123 break;
5124 case 'd':
5125 show_diffstat = 1;
5126 break;
5127 case 'P':
5128 force_path = 1;
5129 break;
5130 case 'r':
5131 repo_path = realpath(optarg, NULL);
5132 if (repo_path == NULL)
5133 return got_error_from_errno2("realpath",
5134 optarg);
5135 got_path_strip_trailing_slashes(repo_path);
5136 rflag = 1;
5137 break;
5138 case 's':
5139 diff_staged = 1;
5140 break;
5141 case 'w':
5142 ignore_whitespace = 1;
5143 break;
5144 default:
5145 usage_diff();
5146 /* NOTREACHED */
5150 argc -= optind;
5151 argv += optind;
5153 cwd = getcwd(NULL, 0);
5154 if (cwd == NULL) {
5155 error = got_error_from_errno("getcwd");
5156 goto done;
5159 error = got_repo_pack_fds_open(&pack_fds);
5160 if (error != NULL)
5161 goto done;
5163 if (repo_path == NULL) {
5164 error = got_worktree_open(&worktree, cwd);
5165 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5166 goto done;
5167 else
5168 error = NULL;
5169 if (worktree) {
5170 repo_path =
5171 strdup(got_worktree_get_repo_path(worktree));
5172 if (repo_path == NULL) {
5173 error = got_error_from_errno("strdup");
5174 goto done;
5176 } else {
5177 repo_path = strdup(cwd);
5178 if (repo_path == NULL) {
5179 error = got_error_from_errno("strdup");
5180 goto done;
5185 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5186 free(repo_path);
5187 if (error != NULL)
5188 goto done;
5190 if (show_diffstat) {
5191 dsa.paths = &diffstat_paths;
5192 dsa.force_text = force_text_diff;
5193 dsa.ignore_ws = ignore_whitespace;
5194 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5197 if (rflag || worktree == NULL || ncommit_args > 0) {
5198 if (force_path) {
5199 error = got_error_msg(GOT_ERR_NOT_IMPL,
5200 "-P option can only be used when diffing "
5201 "a work tree");
5202 goto done;
5204 if (diff_staged) {
5205 error = got_error_msg(GOT_ERR_NOT_IMPL,
5206 "-s option can only be used when diffing "
5207 "a work tree");
5208 goto done;
5212 error = apply_unveil(got_repo_get_path(repo), 1,
5213 worktree ? got_worktree_get_root_path(worktree) : NULL);
5214 if (error)
5215 goto done;
5217 if ((!force_path && argc == 2) || ncommit_args > 0) {
5218 int obj_type = (ncommit_args > 0 ?
5219 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5220 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5221 NULL);
5222 if (error)
5223 goto done;
5224 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5225 const char *arg;
5226 if (ncommit_args > 0)
5227 arg = commit_args[i];
5228 else
5229 arg = argv[i];
5230 error = got_repo_match_object_id(&ids[i], &labels[i],
5231 arg, obj_type, &refs, repo);
5232 if (error) {
5233 if (error->code != GOT_ERR_NOT_REF &&
5234 error->code != GOT_ERR_NO_OBJ)
5235 goto done;
5236 if (ncommit_args > 0)
5237 goto done;
5238 error = NULL;
5239 break;
5244 f1 = got_opentemp();
5245 if (f1 == NULL) {
5246 error = got_error_from_errno("got_opentemp");
5247 goto done;
5250 f2 = got_opentemp();
5251 if (f2 == NULL) {
5252 error = got_error_from_errno("got_opentemp");
5253 goto done;
5256 outfile = got_opentemp();
5257 if (outfile == NULL) {
5258 error = got_error_from_errno("got_opentemp");
5259 goto done;
5262 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5263 struct print_diff_arg arg;
5264 char *id_str;
5266 if (worktree == NULL) {
5267 if (argc == 2 && ids[0] == NULL) {
5268 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5269 goto done;
5270 } else if (argc == 2 && ids[1] == NULL) {
5271 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5272 goto done;
5273 } else if (argc > 0) {
5274 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5275 "%s", "specified paths cannot be resolved");
5276 goto done;
5277 } else {
5278 error = got_error(GOT_ERR_NOT_WORKTREE);
5279 goto done;
5283 error = get_worktree_paths_from_argv(&paths, argc, argv,
5284 worktree);
5285 if (error)
5286 goto done;
5288 error = got_object_id_str(&id_str,
5289 got_worktree_get_base_commit_id(worktree));
5290 if (error)
5291 goto done;
5292 arg.repo = repo;
5293 arg.worktree = worktree;
5294 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5295 arg.diff_context = diff_context;
5296 arg.id_str = id_str;
5297 arg.header_shown = 0;
5298 arg.diff_staged = diff_staged;
5299 arg.ignore_whitespace = ignore_whitespace;
5300 arg.force_text_diff = force_text_diff;
5301 arg.diffstat = show_diffstat ? &dsa : NULL;
5302 arg.f1 = f1;
5303 arg.f2 = f2;
5304 arg.outfile = outfile;
5306 error = got_worktree_status(worktree, &paths, repo, 0,
5307 print_diff, &arg, check_cancelled, NULL);
5308 free(id_str);
5309 if (error)
5310 goto done;
5312 if (show_diffstat && dsa.nfiles > 0) {
5313 char *header;
5315 if (asprintf(&header, "diffstat %s%s",
5316 diff_staged ? "-s " : "",
5317 got_worktree_get_root_path(worktree)) == -1) {
5318 error = got_error_from_errno("asprintf");
5319 goto done;
5322 error = print_diffstat(&dsa, header);
5323 free(header);
5324 if (error)
5325 goto done;
5328 error = printfile(outfile);
5329 goto done;
5332 if (ncommit_args == 1) {
5333 struct got_commit_object *commit;
5334 error = got_object_open_as_commit(&commit, repo, ids[0]);
5335 if (error)
5336 goto done;
5338 labels[1] = labels[0];
5339 ids[1] = ids[0];
5340 if (got_object_commit_get_nparents(commit) > 0) {
5341 const struct got_object_id_queue *pids;
5342 struct got_object_qid *pid;
5343 pids = got_object_commit_get_parent_ids(commit);
5344 pid = STAILQ_FIRST(pids);
5345 ids[0] = got_object_id_dup(&pid->id);
5346 if (ids[0] == NULL) {
5347 error = got_error_from_errno(
5348 "got_object_id_dup");
5349 got_object_commit_close(commit);
5350 goto done;
5352 error = got_object_id_str(&labels[0], ids[0]);
5353 if (error) {
5354 got_object_commit_close(commit);
5355 goto done;
5357 } else {
5358 ids[0] = NULL;
5359 labels[0] = strdup("/dev/null");
5360 if (labels[0] == NULL) {
5361 error = got_error_from_errno("strdup");
5362 got_object_commit_close(commit);
5363 goto done;
5367 got_object_commit_close(commit);
5370 if (ncommit_args == 0 && argc > 2) {
5371 error = got_error_msg(GOT_ERR_BAD_PATH,
5372 "path arguments cannot be used when diffing two objects");
5373 goto done;
5376 if (ids[0]) {
5377 error = got_object_get_type(&type1, repo, ids[0]);
5378 if (error)
5379 goto done;
5382 error = got_object_get_type(&type2, repo, ids[1]);
5383 if (error)
5384 goto done;
5385 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5386 error = got_error(GOT_ERR_OBJ_TYPE);
5387 goto done;
5389 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5390 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5391 "path arguments cannot be used when diffing blobs");
5392 goto done;
5395 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5396 char *in_repo_path;
5397 struct got_pathlist_entry *new;
5398 if (worktree) {
5399 const char *prefix;
5400 char *p;
5401 error = got_worktree_resolve_path(&p, worktree,
5402 argv[i]);
5403 if (error)
5404 goto done;
5405 prefix = got_worktree_get_path_prefix(worktree);
5406 while (prefix[0] == '/')
5407 prefix++;
5408 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5409 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5410 p) == -1) {
5411 error = got_error_from_errno("asprintf");
5412 free(p);
5413 goto done;
5415 free(p);
5416 } else {
5417 char *mapped_path, *s;
5418 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5419 if (error)
5420 goto done;
5421 s = mapped_path;
5422 while (s[0] == '/')
5423 s++;
5424 in_repo_path = strdup(s);
5425 if (in_repo_path == NULL) {
5426 error = got_error_from_errno("asprintf");
5427 free(mapped_path);
5428 goto done;
5430 free(mapped_path);
5433 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5434 if (error || new == NULL /* duplicate */)
5435 free(in_repo_path);
5436 if (error)
5437 goto done;
5440 if (worktree) {
5441 /* Release work tree lock. */
5442 got_worktree_close(worktree);
5443 worktree = NULL;
5446 fd1 = got_opentempfd();
5447 if (fd1 == -1) {
5448 error = got_error_from_errno("got_opentempfd");
5449 goto done;
5452 fd2 = got_opentempfd();
5453 if (fd2 == -1) {
5454 error = got_error_from_errno("got_opentempfd");
5455 goto done;
5458 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5459 case GOT_OBJ_TYPE_BLOB:
5460 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5461 fd1, fd2, ids[0], ids[1], NULL, NULL,
5462 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5463 ignore_whitespace, force_text_diff,
5464 show_diffstat ? &dsa : NULL, repo, outfile);
5465 break;
5466 case GOT_OBJ_TYPE_TREE:
5467 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5468 ids[0], ids[1], &paths, "", "",
5469 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5470 ignore_whitespace, force_text_diff,
5471 show_diffstat ? &dsa : NULL, repo, outfile);
5472 break;
5473 case GOT_OBJ_TYPE_COMMIT:
5474 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5475 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5476 fd1, fd2, ids[0], ids[1], &paths,
5477 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5478 ignore_whitespace, force_text_diff,
5479 show_diffstat ? &dsa : NULL, repo, outfile);
5480 break;
5481 default:
5482 error = got_error(GOT_ERR_OBJ_TYPE);
5484 if (error)
5485 goto done;
5487 if (show_diffstat && dsa.nfiles > 0) {
5488 char *header = NULL;
5490 if (asprintf(&header, "diffstat %s %s",
5491 labels[0], labels[1]) == -1) {
5492 error = got_error_from_errno("asprintf");
5493 goto done;
5496 error = print_diffstat(&dsa, header);
5497 free(header);
5498 if (error)
5499 goto done;
5502 error = printfile(outfile);
5504 done:
5505 free(labels[0]);
5506 free(labels[1]);
5507 free(ids[0]);
5508 free(ids[1]);
5509 if (worktree)
5510 got_worktree_close(worktree);
5511 if (repo) {
5512 const struct got_error *close_err = got_repo_close(repo);
5513 if (error == NULL)
5514 error = close_err;
5516 if (pack_fds) {
5517 const struct got_error *pack_err =
5518 got_repo_pack_fds_close(pack_fds);
5519 if (error == NULL)
5520 error = pack_err;
5522 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5523 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5524 got_ref_list_free(&refs);
5525 if (outfile && fclose(outfile) == EOF && error == NULL)
5526 error = got_error_from_errno("fclose");
5527 if (f1 && fclose(f1) == EOF && error == NULL)
5528 error = got_error_from_errno("fclose");
5529 if (f2 && fclose(f2) == EOF && error == NULL)
5530 error = got_error_from_errno("fclose");
5531 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5532 error = got_error_from_errno("close");
5533 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5534 error = got_error_from_errno("close");
5535 return error;
5538 __dead static void
5539 usage_blame(void)
5541 fprintf(stderr,
5542 "usage: %s blame [-c commit] [-r repository-path] path\n",
5543 getprogname());
5544 exit(1);
5547 struct blame_line {
5548 int annotated;
5549 char *id_str;
5550 char *committer;
5551 char datebuf[11]; /* YYYY-MM-DD + NUL */
5554 struct blame_cb_args {
5555 struct blame_line *lines;
5556 int nlines;
5557 int nlines_prec;
5558 int lineno_cur;
5559 off_t *line_offsets;
5560 FILE *f;
5561 struct got_repository *repo;
5564 static const struct got_error *
5565 blame_cb(void *arg, int nlines, int lineno,
5566 struct got_commit_object *commit, struct got_object_id *id)
5568 const struct got_error *err = NULL;
5569 struct blame_cb_args *a = arg;
5570 struct blame_line *bline;
5571 char *line = NULL;
5572 size_t linesize = 0;
5573 off_t offset;
5574 struct tm tm;
5575 time_t committer_time;
5577 if (nlines != a->nlines ||
5578 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5579 return got_error(GOT_ERR_RANGE);
5581 if (sigint_received)
5582 return got_error(GOT_ERR_ITER_COMPLETED);
5584 if (lineno == -1)
5585 return NULL; /* no change in this commit */
5587 /* Annotate this line. */
5588 bline = &a->lines[lineno - 1];
5589 if (bline->annotated)
5590 return NULL;
5591 err = got_object_id_str(&bline->id_str, id);
5592 if (err)
5593 return err;
5595 bline->committer = strdup(got_object_commit_get_committer(commit));
5596 if (bline->committer == NULL) {
5597 err = got_error_from_errno("strdup");
5598 goto done;
5601 committer_time = got_object_commit_get_committer_time(commit);
5602 if (gmtime_r(&committer_time, &tm) == NULL)
5603 return got_error_from_errno("gmtime_r");
5604 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5605 &tm) == 0) {
5606 err = got_error(GOT_ERR_NO_SPACE);
5607 goto done;
5609 bline->annotated = 1;
5611 /* Print lines annotated so far. */
5612 bline = &a->lines[a->lineno_cur - 1];
5613 if (!bline->annotated)
5614 goto done;
5616 offset = a->line_offsets[a->lineno_cur - 1];
5617 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5618 err = got_error_from_errno("fseeko");
5619 goto done;
5622 while (a->lineno_cur <= a->nlines && bline->annotated) {
5623 char *smallerthan, *at, *nl, *committer;
5624 size_t len;
5626 if (getline(&line, &linesize, a->f) == -1) {
5627 if (ferror(a->f))
5628 err = got_error_from_errno("getline");
5629 break;
5632 committer = bline->committer;
5633 smallerthan = strchr(committer, '<');
5634 if (smallerthan && smallerthan[1] != '\0')
5635 committer = smallerthan + 1;
5636 at = strchr(committer, '@');
5637 if (at)
5638 *at = '\0';
5639 len = strlen(committer);
5640 if (len >= 9)
5641 committer[8] = '\0';
5643 nl = strchr(line, '\n');
5644 if (nl)
5645 *nl = '\0';
5646 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5647 bline->id_str, bline->datebuf, committer, line);
5649 a->lineno_cur++;
5650 bline = &a->lines[a->lineno_cur - 1];
5652 done:
5653 free(line);
5654 return err;
5657 static const struct got_error *
5658 cmd_blame(int argc, char *argv[])
5660 const struct got_error *error;
5661 struct got_repository *repo = NULL;
5662 struct got_worktree *worktree = NULL;
5663 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5664 char *link_target = NULL;
5665 struct got_object_id *obj_id = NULL;
5666 struct got_object_id *commit_id = NULL;
5667 struct got_commit_object *commit = NULL;
5668 struct got_blob_object *blob = NULL;
5669 char *commit_id_str = NULL;
5670 struct blame_cb_args bca;
5671 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5672 off_t filesize;
5673 int *pack_fds = NULL;
5674 FILE *f1 = NULL, *f2 = NULL;
5676 fd1 = got_opentempfd();
5677 if (fd1 == -1)
5678 return got_error_from_errno("got_opentempfd");
5680 memset(&bca, 0, sizeof(bca));
5682 #ifndef PROFILE
5683 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5684 NULL) == -1)
5685 err(1, "pledge");
5686 #endif
5688 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5689 switch (ch) {
5690 case 'c':
5691 commit_id_str = optarg;
5692 break;
5693 case 'r':
5694 repo_path = realpath(optarg, NULL);
5695 if (repo_path == NULL)
5696 return got_error_from_errno2("realpath",
5697 optarg);
5698 got_path_strip_trailing_slashes(repo_path);
5699 break;
5700 default:
5701 usage_blame();
5702 /* NOTREACHED */
5706 argc -= optind;
5707 argv += optind;
5709 if (argc == 1)
5710 path = argv[0];
5711 else
5712 usage_blame();
5714 cwd = getcwd(NULL, 0);
5715 if (cwd == NULL) {
5716 error = got_error_from_errno("getcwd");
5717 goto done;
5720 error = got_repo_pack_fds_open(&pack_fds);
5721 if (error != NULL)
5722 goto done;
5724 if (repo_path == NULL) {
5725 error = got_worktree_open(&worktree, cwd);
5726 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5727 goto done;
5728 else
5729 error = NULL;
5730 if (worktree) {
5731 repo_path =
5732 strdup(got_worktree_get_repo_path(worktree));
5733 if (repo_path == NULL) {
5734 error = got_error_from_errno("strdup");
5735 if (error)
5736 goto done;
5738 } else {
5739 repo_path = strdup(cwd);
5740 if (repo_path == NULL) {
5741 error = got_error_from_errno("strdup");
5742 goto done;
5747 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5748 if (error != NULL)
5749 goto done;
5751 if (worktree) {
5752 const char *prefix = got_worktree_get_path_prefix(worktree);
5753 char *p;
5755 error = got_worktree_resolve_path(&p, worktree, path);
5756 if (error)
5757 goto done;
5758 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5759 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5760 p) == -1) {
5761 error = got_error_from_errno("asprintf");
5762 free(p);
5763 goto done;
5765 free(p);
5766 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5767 } else {
5768 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5769 if (error)
5770 goto done;
5771 error = got_repo_map_path(&in_repo_path, repo, path);
5773 if (error)
5774 goto done;
5776 if (commit_id_str == NULL) {
5777 struct got_reference *head_ref;
5778 error = got_ref_open(&head_ref, repo, worktree ?
5779 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5780 if (error != NULL)
5781 goto done;
5782 error = got_ref_resolve(&commit_id, repo, head_ref);
5783 got_ref_close(head_ref);
5784 if (error != NULL)
5785 goto done;
5786 } else {
5787 struct got_reflist_head refs;
5788 TAILQ_INIT(&refs);
5789 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5790 NULL);
5791 if (error)
5792 goto done;
5793 error = got_repo_match_object_id(&commit_id, NULL,
5794 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5795 got_ref_list_free(&refs);
5796 if (error)
5797 goto done;
5800 if (worktree) {
5801 /* Release work tree lock. */
5802 got_worktree_close(worktree);
5803 worktree = NULL;
5806 error = got_object_open_as_commit(&commit, repo, commit_id);
5807 if (error)
5808 goto done;
5810 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5811 commit, repo);
5812 if (error)
5813 goto done;
5815 error = got_object_id_by_path(&obj_id, repo, commit,
5816 link_target ? link_target : in_repo_path);
5817 if (error)
5818 goto done;
5820 error = got_object_get_type(&obj_type, repo, obj_id);
5821 if (error)
5822 goto done;
5824 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5825 error = got_error_path(link_target ? link_target : in_repo_path,
5826 GOT_ERR_OBJ_TYPE);
5827 goto done;
5830 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5831 if (error)
5832 goto done;
5833 bca.f = got_opentemp();
5834 if (bca.f == NULL) {
5835 error = got_error_from_errno("got_opentemp");
5836 goto done;
5838 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5839 &bca.line_offsets, bca.f, blob);
5840 if (error || bca.nlines == 0)
5841 goto done;
5843 /* Don't include \n at EOF in the blame line count. */
5844 if (bca.line_offsets[bca.nlines - 1] == filesize)
5845 bca.nlines--;
5847 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5848 if (bca.lines == NULL) {
5849 error = got_error_from_errno("calloc");
5850 goto done;
5852 bca.lineno_cur = 1;
5853 bca.nlines_prec = 0;
5854 i = bca.nlines;
5855 while (i > 0) {
5856 i /= 10;
5857 bca.nlines_prec++;
5859 bca.repo = repo;
5861 fd2 = got_opentempfd();
5862 if (fd2 == -1) {
5863 error = got_error_from_errno("got_opentempfd");
5864 goto done;
5866 fd3 = got_opentempfd();
5867 if (fd3 == -1) {
5868 error = got_error_from_errno("got_opentempfd");
5869 goto done;
5871 f1 = got_opentemp();
5872 if (f1 == NULL) {
5873 error = got_error_from_errno("got_opentemp");
5874 goto done;
5876 f2 = got_opentemp();
5877 if (f2 == NULL) {
5878 error = got_error_from_errno("got_opentemp");
5879 goto done;
5881 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5882 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5883 check_cancelled, NULL, fd2, fd3, f1, f2);
5884 done:
5885 free(in_repo_path);
5886 free(link_target);
5887 free(repo_path);
5888 free(cwd);
5889 free(commit_id);
5890 free(obj_id);
5891 if (commit)
5892 got_object_commit_close(commit);
5894 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5895 error = got_error_from_errno("close");
5896 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5897 error = got_error_from_errno("close");
5898 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5899 error = got_error_from_errno("close");
5900 if (f1 && fclose(f1) == EOF && error == NULL)
5901 error = got_error_from_errno("fclose");
5902 if (f2 && fclose(f2) == EOF && error == NULL)
5903 error = got_error_from_errno("fclose");
5905 if (blob)
5906 got_object_blob_close(blob);
5907 if (worktree)
5908 got_worktree_close(worktree);
5909 if (repo) {
5910 const struct got_error *close_err = got_repo_close(repo);
5911 if (error == NULL)
5912 error = close_err;
5914 if (pack_fds) {
5915 const struct got_error *pack_err =
5916 got_repo_pack_fds_close(pack_fds);
5917 if (error == NULL)
5918 error = pack_err;
5920 if (bca.lines) {
5921 for (i = 0; i < bca.nlines; i++) {
5922 struct blame_line *bline = &bca.lines[i];
5923 free(bline->id_str);
5924 free(bline->committer);
5926 free(bca.lines);
5928 free(bca.line_offsets);
5929 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5930 error = got_error_from_errno("fclose");
5931 return error;
5934 __dead static void
5935 usage_tree(void)
5937 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5938 "[path]\n", getprogname());
5939 exit(1);
5942 static const struct got_error *
5943 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5944 const char *root_path, struct got_repository *repo)
5946 const struct got_error *err = NULL;
5947 int is_root_path = (strcmp(path, root_path) == 0);
5948 const char *modestr = "";
5949 mode_t mode = got_tree_entry_get_mode(te);
5950 char *link_target = NULL;
5952 path += strlen(root_path);
5953 while (path[0] == '/')
5954 path++;
5956 if (got_object_tree_entry_is_submodule(te))
5957 modestr = "$";
5958 else if (S_ISLNK(mode)) {
5959 int i;
5961 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5962 if (err)
5963 return err;
5964 for (i = 0; i < strlen(link_target); i++) {
5965 if (!isprint((unsigned char)link_target[i]))
5966 link_target[i] = '?';
5969 modestr = "@";
5971 else if (S_ISDIR(mode))
5972 modestr = "/";
5973 else if (mode & S_IXUSR)
5974 modestr = "*";
5976 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5977 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5978 link_target ? " -> ": "", link_target ? link_target : "");
5980 free(link_target);
5981 return NULL;
5984 static const struct got_error *
5985 print_tree(const char *path, struct got_commit_object *commit,
5986 int show_ids, int recurse, const char *root_path,
5987 struct got_repository *repo)
5989 const struct got_error *err = NULL;
5990 struct got_object_id *tree_id = NULL;
5991 struct got_tree_object *tree = NULL;
5992 int nentries, i;
5994 err = got_object_id_by_path(&tree_id, repo, commit, path);
5995 if (err)
5996 goto done;
5998 err = got_object_open_as_tree(&tree, repo, tree_id);
5999 if (err)
6000 goto done;
6001 nentries = got_object_tree_get_nentries(tree);
6002 for (i = 0; i < nentries; i++) {
6003 struct got_tree_entry *te;
6004 char *id = NULL;
6006 if (sigint_received || sigpipe_received)
6007 break;
6009 te = got_object_tree_get_entry(tree, i);
6010 if (show_ids) {
6011 char *id_str;
6012 err = got_object_id_str(&id_str,
6013 got_tree_entry_get_id(te));
6014 if (err)
6015 goto done;
6016 if (asprintf(&id, "%s ", id_str) == -1) {
6017 err = got_error_from_errno("asprintf");
6018 free(id_str);
6019 goto done;
6021 free(id_str);
6023 err = print_entry(te, id, path, root_path, repo);
6024 free(id);
6025 if (err)
6026 goto done;
6028 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6029 char *child_path;
6030 if (asprintf(&child_path, "%s%s%s", path,
6031 path[0] == '/' && path[1] == '\0' ? "" : "/",
6032 got_tree_entry_get_name(te)) == -1) {
6033 err = got_error_from_errno("asprintf");
6034 goto done;
6036 err = print_tree(child_path, commit, show_ids, 1,
6037 root_path, repo);
6038 free(child_path);
6039 if (err)
6040 goto done;
6043 done:
6044 if (tree)
6045 got_object_tree_close(tree);
6046 free(tree_id);
6047 return err;
6050 static const struct got_error *
6051 cmd_tree(int argc, char *argv[])
6053 const struct got_error *error;
6054 struct got_repository *repo = NULL;
6055 struct got_worktree *worktree = NULL;
6056 const char *path, *refname = NULL;
6057 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6058 struct got_object_id *commit_id = NULL;
6059 struct got_commit_object *commit = NULL;
6060 char *commit_id_str = NULL;
6061 int show_ids = 0, recurse = 0;
6062 int ch;
6063 int *pack_fds = NULL;
6065 #ifndef PROFILE
6066 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6067 NULL) == -1)
6068 err(1, "pledge");
6069 #endif
6071 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6072 switch (ch) {
6073 case 'c':
6074 commit_id_str = optarg;
6075 break;
6076 case 'i':
6077 show_ids = 1;
6078 break;
6079 case 'R':
6080 recurse = 1;
6081 break;
6082 case 'r':
6083 repo_path = realpath(optarg, NULL);
6084 if (repo_path == NULL)
6085 return got_error_from_errno2("realpath",
6086 optarg);
6087 got_path_strip_trailing_slashes(repo_path);
6088 break;
6089 default:
6090 usage_tree();
6091 /* NOTREACHED */
6095 argc -= optind;
6096 argv += optind;
6098 if (argc == 1)
6099 path = argv[0];
6100 else if (argc > 1)
6101 usage_tree();
6102 else
6103 path = NULL;
6105 cwd = getcwd(NULL, 0);
6106 if (cwd == NULL) {
6107 error = got_error_from_errno("getcwd");
6108 goto done;
6111 error = got_repo_pack_fds_open(&pack_fds);
6112 if (error != NULL)
6113 goto done;
6115 if (repo_path == NULL) {
6116 error = got_worktree_open(&worktree, cwd);
6117 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6118 goto done;
6119 else
6120 error = NULL;
6121 if (worktree) {
6122 repo_path =
6123 strdup(got_worktree_get_repo_path(worktree));
6124 if (repo_path == NULL)
6125 error = got_error_from_errno("strdup");
6126 if (error)
6127 goto done;
6128 } else {
6129 repo_path = strdup(cwd);
6130 if (repo_path == NULL) {
6131 error = got_error_from_errno("strdup");
6132 goto done;
6137 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6138 if (error != NULL)
6139 goto done;
6141 if (worktree) {
6142 const char *prefix = got_worktree_get_path_prefix(worktree);
6143 char *p;
6145 if (path == NULL)
6146 path = "";
6147 error = got_worktree_resolve_path(&p, worktree, path);
6148 if (error)
6149 goto done;
6150 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6151 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6152 p) == -1) {
6153 error = got_error_from_errno("asprintf");
6154 free(p);
6155 goto done;
6157 free(p);
6158 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6159 if (error)
6160 goto done;
6161 } else {
6162 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6163 if (error)
6164 goto done;
6165 if (path == NULL)
6166 path = "/";
6167 error = got_repo_map_path(&in_repo_path, repo, path);
6168 if (error != NULL)
6169 goto done;
6172 if (commit_id_str == NULL) {
6173 struct got_reference *head_ref;
6174 if (worktree)
6175 refname = got_worktree_get_head_ref_name(worktree);
6176 else
6177 refname = GOT_REF_HEAD;
6178 error = got_ref_open(&head_ref, repo, refname, 0);
6179 if (error != NULL)
6180 goto done;
6181 error = got_ref_resolve(&commit_id, repo, head_ref);
6182 got_ref_close(head_ref);
6183 if (error != NULL)
6184 goto done;
6185 } else {
6186 struct got_reflist_head refs;
6187 TAILQ_INIT(&refs);
6188 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6189 NULL);
6190 if (error)
6191 goto done;
6192 error = got_repo_match_object_id(&commit_id, NULL,
6193 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6194 got_ref_list_free(&refs);
6195 if (error)
6196 goto done;
6199 if (worktree) {
6200 /* Release work tree lock. */
6201 got_worktree_close(worktree);
6202 worktree = NULL;
6205 error = got_object_open_as_commit(&commit, repo, commit_id);
6206 if (error)
6207 goto done;
6209 error = print_tree(in_repo_path, commit, show_ids, recurse,
6210 in_repo_path, repo);
6211 done:
6212 free(in_repo_path);
6213 free(repo_path);
6214 free(cwd);
6215 free(commit_id);
6216 if (commit)
6217 got_object_commit_close(commit);
6218 if (worktree)
6219 got_worktree_close(worktree);
6220 if (repo) {
6221 const struct got_error *close_err = got_repo_close(repo);
6222 if (error == NULL)
6223 error = close_err;
6225 if (pack_fds) {
6226 const struct got_error *pack_err =
6227 got_repo_pack_fds_close(pack_fds);
6228 if (error == NULL)
6229 error = pack_err;
6231 return error;
6234 __dead static void
6235 usage_status(void)
6237 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6238 "[-s status-codes] [path ...]\n", getprogname());
6239 exit(1);
6242 struct got_status_arg {
6243 char *status_codes;
6244 int suppress;
6247 static const struct got_error *
6248 print_status(void *arg, unsigned char status, unsigned char staged_status,
6249 const char *path, struct got_object_id *blob_id,
6250 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6251 int dirfd, const char *de_name)
6253 struct got_status_arg *st = arg;
6255 if (status == staged_status && (status == GOT_STATUS_DELETE))
6256 status = GOT_STATUS_NO_CHANGE;
6257 if (st != NULL && st->status_codes) {
6258 size_t ncodes = strlen(st->status_codes);
6259 int i, j = 0;
6261 for (i = 0; i < ncodes ; i++) {
6262 if (st->suppress) {
6263 if (status == st->status_codes[i] ||
6264 staged_status == st->status_codes[i]) {
6265 j++;
6266 continue;
6268 } else {
6269 if (status == st->status_codes[i] ||
6270 staged_status == st->status_codes[i])
6271 break;
6275 if (st->suppress && j == 0)
6276 goto print;
6278 if (i == ncodes)
6279 return NULL;
6281 print:
6282 printf("%c%c %s\n", status, staged_status, path);
6283 return NULL;
6286 static const struct got_error *
6287 cmd_status(int argc, char *argv[])
6289 const struct got_error *error = NULL;
6290 struct got_repository *repo = NULL;
6291 struct got_worktree *worktree = NULL;
6292 struct got_status_arg st;
6293 char *cwd = NULL;
6294 struct got_pathlist_head paths;
6295 int ch, i, no_ignores = 0;
6296 int *pack_fds = NULL;
6298 TAILQ_INIT(&paths);
6300 memset(&st, 0, sizeof(st));
6301 st.status_codes = NULL;
6302 st.suppress = 0;
6304 #ifndef PROFILE
6305 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6306 NULL) == -1)
6307 err(1, "pledge");
6308 #endif
6310 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6311 switch (ch) {
6312 case 'I':
6313 no_ignores = 1;
6314 break;
6315 case 'S':
6316 if (st.status_codes != NULL && st.suppress == 0)
6317 option_conflict('S', 's');
6318 st.suppress = 1;
6319 /* fallthrough */
6320 case 's':
6321 for (i = 0; i < strlen(optarg); i++) {
6322 switch (optarg[i]) {
6323 case GOT_STATUS_MODIFY:
6324 case GOT_STATUS_ADD:
6325 case GOT_STATUS_DELETE:
6326 case GOT_STATUS_CONFLICT:
6327 case GOT_STATUS_MISSING:
6328 case GOT_STATUS_OBSTRUCTED:
6329 case GOT_STATUS_UNVERSIONED:
6330 case GOT_STATUS_MODE_CHANGE:
6331 case GOT_STATUS_NONEXISTENT:
6332 break;
6333 default:
6334 errx(1, "invalid status code '%c'",
6335 optarg[i]);
6338 if (ch == 's' && st.suppress)
6339 option_conflict('s', 'S');
6340 st.status_codes = optarg;
6341 break;
6342 default:
6343 usage_status();
6344 /* NOTREACHED */
6348 argc -= optind;
6349 argv += optind;
6351 cwd = getcwd(NULL, 0);
6352 if (cwd == NULL) {
6353 error = got_error_from_errno("getcwd");
6354 goto done;
6357 error = got_repo_pack_fds_open(&pack_fds);
6358 if (error != NULL)
6359 goto done;
6361 error = got_worktree_open(&worktree, cwd);
6362 if (error) {
6363 if (error->code == GOT_ERR_NOT_WORKTREE)
6364 error = wrap_not_worktree_error(error, "status", cwd);
6365 goto done;
6368 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6369 NULL, pack_fds);
6370 if (error != NULL)
6371 goto done;
6373 error = apply_unveil(got_repo_get_path(repo), 1,
6374 got_worktree_get_root_path(worktree));
6375 if (error)
6376 goto done;
6378 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6379 if (error)
6380 goto done;
6382 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6383 print_status, &st, check_cancelled, NULL);
6384 done:
6385 if (pack_fds) {
6386 const struct got_error *pack_err =
6387 got_repo_pack_fds_close(pack_fds);
6388 if (error == NULL)
6389 error = pack_err;
6392 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6393 free(cwd);
6394 return error;
6397 __dead static void
6398 usage_ref(void)
6400 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6401 "[-s reference] [name]\n", getprogname());
6402 exit(1);
6405 static const struct got_error *
6406 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6408 static const struct got_error *err = NULL;
6409 struct got_reflist_head refs;
6410 struct got_reflist_entry *re;
6412 TAILQ_INIT(&refs);
6413 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6414 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6415 repo);
6416 if (err)
6417 return err;
6419 TAILQ_FOREACH(re, &refs, entry) {
6420 char *refstr;
6421 refstr = got_ref_to_str(re->ref);
6422 if (refstr == NULL) {
6423 err = got_error_from_errno("got_ref_to_str");
6424 break;
6426 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6427 free(refstr);
6430 got_ref_list_free(&refs);
6431 return err;
6434 static const struct got_error *
6435 delete_ref_by_name(struct got_repository *repo, const char *refname)
6437 const struct got_error *err;
6438 struct got_reference *ref;
6440 err = got_ref_open(&ref, repo, refname, 0);
6441 if (err)
6442 return err;
6444 err = delete_ref(repo, ref);
6445 got_ref_close(ref);
6446 return err;
6449 static const struct got_error *
6450 add_ref(struct got_repository *repo, const char *refname, const char *target)
6452 const struct got_error *err = NULL;
6453 struct got_object_id *id = NULL;
6454 struct got_reference *ref = NULL;
6455 struct got_reflist_head refs;
6458 * Don't let the user create a reference name with a leading '-'.
6459 * While technically a valid reference name, this case is usually
6460 * an unintended typo.
6462 if (refname[0] == '-')
6463 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6465 TAILQ_INIT(&refs);
6466 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6467 if (err)
6468 goto done;
6469 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6470 &refs, repo);
6471 got_ref_list_free(&refs);
6472 if (err)
6473 goto done;
6475 err = got_ref_alloc(&ref, refname, id);
6476 if (err)
6477 goto done;
6479 err = got_ref_write(ref, repo);
6480 done:
6481 if (ref)
6482 got_ref_close(ref);
6483 free(id);
6484 return err;
6487 static const struct got_error *
6488 add_symref(struct got_repository *repo, const char *refname, const char *target)
6490 const struct got_error *err = NULL;
6491 struct got_reference *ref = NULL;
6492 struct got_reference *target_ref = NULL;
6495 * Don't let the user create a reference name with a leading '-'.
6496 * While technically a valid reference name, this case is usually
6497 * an unintended typo.
6499 if (refname[0] == '-')
6500 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6502 err = got_ref_open(&target_ref, repo, target, 0);
6503 if (err)
6504 return err;
6506 err = got_ref_alloc_symref(&ref, refname, target_ref);
6507 if (err)
6508 goto done;
6510 err = got_ref_write(ref, repo);
6511 done:
6512 if (target_ref)
6513 got_ref_close(target_ref);
6514 if (ref)
6515 got_ref_close(ref);
6516 return err;
6519 static const struct got_error *
6520 cmd_ref(int argc, char *argv[])
6522 const struct got_error *error = NULL;
6523 struct got_repository *repo = NULL;
6524 struct got_worktree *worktree = NULL;
6525 char *cwd = NULL, *repo_path = NULL;
6526 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6527 const char *obj_arg = NULL, *symref_target= NULL;
6528 char *refname = NULL;
6529 int *pack_fds = NULL;
6531 #ifndef PROFILE
6532 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6533 "sendfd unveil", NULL) == -1)
6534 err(1, "pledge");
6535 #endif
6537 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6538 switch (ch) {
6539 case 'c':
6540 obj_arg = optarg;
6541 break;
6542 case 'd':
6543 do_delete = 1;
6544 break;
6545 case 'l':
6546 do_list = 1;
6547 break;
6548 case 'r':
6549 repo_path = realpath(optarg, NULL);
6550 if (repo_path == NULL)
6551 return got_error_from_errno2("realpath",
6552 optarg);
6553 got_path_strip_trailing_slashes(repo_path);
6554 break;
6555 case 's':
6556 symref_target = optarg;
6557 break;
6558 case 't':
6559 sort_by_time = 1;
6560 break;
6561 default:
6562 usage_ref();
6563 /* NOTREACHED */
6567 if (obj_arg && do_list)
6568 option_conflict('c', 'l');
6569 if (obj_arg && do_delete)
6570 option_conflict('c', 'd');
6571 if (obj_arg && symref_target)
6572 option_conflict('c', 's');
6573 if (symref_target && do_delete)
6574 option_conflict('s', 'd');
6575 if (symref_target && do_list)
6576 option_conflict('s', 'l');
6577 if (do_delete && do_list)
6578 option_conflict('d', 'l');
6579 if (sort_by_time && !do_list)
6580 errx(1, "-t option requires -l option");
6582 argc -= optind;
6583 argv += optind;
6585 if (do_list) {
6586 if (argc != 0 && argc != 1)
6587 usage_ref();
6588 if (argc == 1) {
6589 refname = strdup(argv[0]);
6590 if (refname == NULL) {
6591 error = got_error_from_errno("strdup");
6592 goto done;
6595 } else {
6596 if (argc != 1)
6597 usage_ref();
6598 refname = strdup(argv[0]);
6599 if (refname == NULL) {
6600 error = got_error_from_errno("strdup");
6601 goto done;
6605 if (refname)
6606 got_path_strip_trailing_slashes(refname);
6608 cwd = getcwd(NULL, 0);
6609 if (cwd == NULL) {
6610 error = got_error_from_errno("getcwd");
6611 goto done;
6614 error = got_repo_pack_fds_open(&pack_fds);
6615 if (error != NULL)
6616 goto done;
6618 if (repo_path == NULL) {
6619 error = got_worktree_open(&worktree, cwd);
6620 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6621 goto done;
6622 else
6623 error = NULL;
6624 if (worktree) {
6625 repo_path =
6626 strdup(got_worktree_get_repo_path(worktree));
6627 if (repo_path == NULL)
6628 error = got_error_from_errno("strdup");
6629 if (error)
6630 goto done;
6631 } else {
6632 repo_path = strdup(cwd);
6633 if (repo_path == NULL) {
6634 error = got_error_from_errno("strdup");
6635 goto done;
6640 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6641 if (error != NULL)
6642 goto done;
6644 #ifndef PROFILE
6645 if (do_list) {
6646 /* Remove "cpath" promise. */
6647 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6648 NULL) == -1)
6649 err(1, "pledge");
6651 #endif
6653 error = apply_unveil(got_repo_get_path(repo), do_list,
6654 worktree ? got_worktree_get_root_path(worktree) : NULL);
6655 if (error)
6656 goto done;
6658 if (do_list)
6659 error = list_refs(repo, refname, sort_by_time);
6660 else if (do_delete)
6661 error = delete_ref_by_name(repo, refname);
6662 else if (symref_target)
6663 error = add_symref(repo, refname, symref_target);
6664 else {
6665 if (obj_arg == NULL)
6666 usage_ref();
6667 error = add_ref(repo, refname, obj_arg);
6669 done:
6670 free(refname);
6671 if (repo) {
6672 const struct got_error *close_err = got_repo_close(repo);
6673 if (error == NULL)
6674 error = close_err;
6676 if (worktree)
6677 got_worktree_close(worktree);
6678 if (pack_fds) {
6679 const struct got_error *pack_err =
6680 got_repo_pack_fds_close(pack_fds);
6681 if (error == NULL)
6682 error = pack_err;
6684 free(cwd);
6685 free(repo_path);
6686 return error;
6689 __dead static void
6690 usage_branch(void)
6692 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6693 "[-r repository-path] [name]\n", getprogname());
6694 exit(1);
6697 static const struct got_error *
6698 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6699 struct got_reference *ref)
6701 const struct got_error *err = NULL;
6702 const char *refname, *marker = " ";
6703 char *refstr;
6705 refname = got_ref_get_name(ref);
6706 if (worktree && strcmp(refname,
6707 got_worktree_get_head_ref_name(worktree)) == 0) {
6708 struct got_object_id *id = NULL;
6710 err = got_ref_resolve(&id, repo, ref);
6711 if (err)
6712 return err;
6713 if (got_object_id_cmp(id,
6714 got_worktree_get_base_commit_id(worktree)) == 0)
6715 marker = "* ";
6716 else
6717 marker = "~ ";
6718 free(id);
6721 if (strncmp(refname, "refs/heads/", 11) == 0)
6722 refname += 11;
6723 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6724 refname += 18;
6725 if (strncmp(refname, "refs/remotes/", 13) == 0)
6726 refname += 13;
6728 refstr = got_ref_to_str(ref);
6729 if (refstr == NULL)
6730 return got_error_from_errno("got_ref_to_str");
6732 printf("%s%s: %s\n", marker, refname, refstr);
6733 free(refstr);
6734 return NULL;
6737 static const struct got_error *
6738 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6740 const char *refname;
6742 if (worktree == NULL)
6743 return got_error(GOT_ERR_NOT_WORKTREE);
6745 refname = got_worktree_get_head_ref_name(worktree);
6747 if (strncmp(refname, "refs/heads/", 11) == 0)
6748 refname += 11;
6749 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6750 refname += 18;
6752 printf("%s\n", refname);
6754 return NULL;
6757 static const struct got_error *
6758 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6759 int sort_by_time)
6761 static const struct got_error *err = NULL;
6762 struct got_reflist_head refs;
6763 struct got_reflist_entry *re;
6764 struct got_reference *temp_ref = NULL;
6765 int rebase_in_progress, histedit_in_progress;
6767 TAILQ_INIT(&refs);
6769 if (worktree) {
6770 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6771 worktree);
6772 if (err)
6773 return err;
6775 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6776 worktree);
6777 if (err)
6778 return err;
6780 if (rebase_in_progress || histedit_in_progress) {
6781 err = got_ref_open(&temp_ref, repo,
6782 got_worktree_get_head_ref_name(worktree), 0);
6783 if (err)
6784 return err;
6785 list_branch(repo, worktree, temp_ref);
6786 got_ref_close(temp_ref);
6790 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6791 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6792 repo);
6793 if (err)
6794 return err;
6796 TAILQ_FOREACH(re, &refs, entry)
6797 list_branch(repo, worktree, re->ref);
6799 got_ref_list_free(&refs);
6801 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6802 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6803 repo);
6804 if (err)
6805 return err;
6807 TAILQ_FOREACH(re, &refs, entry)
6808 list_branch(repo, worktree, re->ref);
6810 got_ref_list_free(&refs);
6812 return NULL;
6815 static const struct got_error *
6816 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6817 const char *branch_name)
6819 const struct got_error *err = NULL;
6820 struct got_reference *ref = NULL;
6821 char *refname, *remote_refname = NULL;
6823 if (strncmp(branch_name, "refs/", 5) == 0)
6824 branch_name += 5;
6825 if (strncmp(branch_name, "heads/", 6) == 0)
6826 branch_name += 6;
6827 else if (strncmp(branch_name, "remotes/", 8) == 0)
6828 branch_name += 8;
6830 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6831 return got_error_from_errno("asprintf");
6833 if (asprintf(&remote_refname, "refs/remotes/%s",
6834 branch_name) == -1) {
6835 err = got_error_from_errno("asprintf");
6836 goto done;
6839 err = got_ref_open(&ref, repo, refname, 0);
6840 if (err) {
6841 const struct got_error *err2;
6842 if (err->code != GOT_ERR_NOT_REF)
6843 goto done;
6845 * Keep 'err' intact such that if neither branch exists
6846 * we report "refs/heads" rather than "refs/remotes" in
6847 * our error message.
6849 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6850 if (err2)
6851 goto done;
6852 err = NULL;
6855 if (worktree &&
6856 strcmp(got_worktree_get_head_ref_name(worktree),
6857 got_ref_get_name(ref)) == 0) {
6858 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6859 "will not delete this work tree's current branch");
6860 goto done;
6863 err = delete_ref(repo, ref);
6864 done:
6865 if (ref)
6866 got_ref_close(ref);
6867 free(refname);
6868 free(remote_refname);
6869 return err;
6872 static const struct got_error *
6873 add_branch(struct got_repository *repo, const char *branch_name,
6874 struct got_object_id *base_commit_id)
6876 const struct got_error *err = NULL;
6877 struct got_reference *ref = NULL;
6878 char *refname = NULL;
6881 * Don't let the user create a branch name with a leading '-'.
6882 * While technically a valid reference name, this case is usually
6883 * an unintended typo.
6885 if (branch_name[0] == '-')
6886 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6888 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6889 branch_name += 11;
6891 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6892 err = got_error_from_errno("asprintf");
6893 goto done;
6896 err = got_ref_open(&ref, repo, refname, 0);
6897 if (err == NULL) {
6898 err = got_error(GOT_ERR_BRANCH_EXISTS);
6899 goto done;
6900 } else if (err->code != GOT_ERR_NOT_REF)
6901 goto done;
6903 err = got_ref_alloc(&ref, refname, base_commit_id);
6904 if (err)
6905 goto done;
6907 err = got_ref_write(ref, repo);
6908 done:
6909 if (ref)
6910 got_ref_close(ref);
6911 free(refname);
6912 return err;
6915 static const struct got_error *
6916 cmd_branch(int argc, char *argv[])
6918 const struct got_error *error = NULL;
6919 struct got_repository *repo = NULL;
6920 struct got_worktree *worktree = NULL;
6921 char *cwd = NULL, *repo_path = NULL;
6922 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6923 const char *delref = NULL, *commit_id_arg = NULL;
6924 struct got_reference *ref = NULL;
6925 struct got_pathlist_head paths;
6926 struct got_object_id *commit_id = NULL;
6927 char *commit_id_str = NULL;
6928 int *pack_fds = NULL;
6930 TAILQ_INIT(&paths);
6932 #ifndef PROFILE
6933 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6934 "sendfd unveil", NULL) == -1)
6935 err(1, "pledge");
6936 #endif
6938 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6939 switch (ch) {
6940 case 'c':
6941 commit_id_arg = optarg;
6942 break;
6943 case 'd':
6944 delref = optarg;
6945 break;
6946 case 'l':
6947 do_list = 1;
6948 break;
6949 case 'n':
6950 do_update = 0;
6951 break;
6952 case 'r':
6953 repo_path = realpath(optarg, NULL);
6954 if (repo_path == NULL)
6955 return got_error_from_errno2("realpath",
6956 optarg);
6957 got_path_strip_trailing_slashes(repo_path);
6958 break;
6959 case 't':
6960 sort_by_time = 1;
6961 break;
6962 default:
6963 usage_branch();
6964 /* NOTREACHED */
6968 if (do_list && delref)
6969 option_conflict('l', 'd');
6970 if (sort_by_time && !do_list)
6971 errx(1, "-t option requires -l option");
6973 argc -= optind;
6974 argv += optind;
6976 if (!do_list && !delref && argc == 0)
6977 do_show = 1;
6979 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6980 errx(1, "-c option can only be used when creating a branch");
6982 if (do_list || delref) {
6983 if (argc > 0)
6984 usage_branch();
6985 } else if (!do_show && argc != 1)
6986 usage_branch();
6988 cwd = getcwd(NULL, 0);
6989 if (cwd == NULL) {
6990 error = got_error_from_errno("getcwd");
6991 goto done;
6994 error = got_repo_pack_fds_open(&pack_fds);
6995 if (error != NULL)
6996 goto done;
6998 if (repo_path == NULL) {
6999 error = got_worktree_open(&worktree, cwd);
7000 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7001 goto done;
7002 else
7003 error = NULL;
7004 if (worktree) {
7005 repo_path =
7006 strdup(got_worktree_get_repo_path(worktree));
7007 if (repo_path == NULL)
7008 error = got_error_from_errno("strdup");
7009 if (error)
7010 goto done;
7011 } else {
7012 repo_path = strdup(cwd);
7013 if (repo_path == NULL) {
7014 error = got_error_from_errno("strdup");
7015 goto done;
7020 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7021 if (error != NULL)
7022 goto done;
7024 #ifndef PROFILE
7025 if (do_list || do_show) {
7026 /* Remove "cpath" promise. */
7027 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7028 NULL) == -1)
7029 err(1, "pledge");
7031 #endif
7033 error = apply_unveil(got_repo_get_path(repo), do_list,
7034 worktree ? got_worktree_get_root_path(worktree) : NULL);
7035 if (error)
7036 goto done;
7038 if (do_show)
7039 error = show_current_branch(repo, worktree);
7040 else if (do_list)
7041 error = list_branches(repo, worktree, sort_by_time);
7042 else if (delref)
7043 error = delete_branch(repo, worktree, delref);
7044 else {
7045 struct got_reflist_head refs;
7046 TAILQ_INIT(&refs);
7047 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7048 NULL);
7049 if (error)
7050 goto done;
7051 if (commit_id_arg == NULL)
7052 commit_id_arg = worktree ?
7053 got_worktree_get_head_ref_name(worktree) :
7054 GOT_REF_HEAD;
7055 error = got_repo_match_object_id(&commit_id, NULL,
7056 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7057 got_ref_list_free(&refs);
7058 if (error)
7059 goto done;
7060 error = add_branch(repo, argv[0], commit_id);
7061 if (error)
7062 goto done;
7063 if (worktree && do_update) {
7064 struct got_update_progress_arg upa;
7065 char *branch_refname = NULL;
7067 error = got_object_id_str(&commit_id_str, commit_id);
7068 if (error)
7069 goto done;
7070 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7071 worktree);
7072 if (error)
7073 goto done;
7074 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7075 == -1) {
7076 error = got_error_from_errno("asprintf");
7077 goto done;
7079 error = got_ref_open(&ref, repo, branch_refname, 0);
7080 free(branch_refname);
7081 if (error)
7082 goto done;
7083 error = switch_head_ref(ref, commit_id, worktree,
7084 repo);
7085 if (error)
7086 goto done;
7087 error = got_worktree_set_base_commit_id(worktree, repo,
7088 commit_id);
7089 if (error)
7090 goto done;
7091 memset(&upa, 0, sizeof(upa));
7092 error = got_worktree_checkout_files(worktree, &paths,
7093 repo, update_progress, &upa, check_cancelled,
7094 NULL);
7095 if (error)
7096 goto done;
7097 if (upa.did_something) {
7098 printf("Updated to %s: %s\n",
7099 got_worktree_get_head_ref_name(worktree),
7100 commit_id_str);
7102 print_update_progress_stats(&upa);
7105 done:
7106 if (ref)
7107 got_ref_close(ref);
7108 if (repo) {
7109 const struct got_error *close_err = got_repo_close(repo);
7110 if (error == NULL)
7111 error = close_err;
7113 if (worktree)
7114 got_worktree_close(worktree);
7115 if (pack_fds) {
7116 const struct got_error *pack_err =
7117 got_repo_pack_fds_close(pack_fds);
7118 if (error == NULL)
7119 error = pack_err;
7121 free(cwd);
7122 free(repo_path);
7123 free(commit_id);
7124 free(commit_id_str);
7125 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7126 return error;
7130 __dead static void
7131 usage_tag(void)
7133 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7134 "[-r repository-path] [-s signer-id] name\n", getprogname());
7135 exit(1);
7138 #if 0
7139 static const struct got_error *
7140 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7142 const struct got_error *err = NULL;
7143 struct got_reflist_entry *re, *se, *new;
7144 struct got_object_id *re_id, *se_id;
7145 struct got_tag_object *re_tag, *se_tag;
7146 time_t re_time, se_time;
7148 STAILQ_FOREACH(re, tags, entry) {
7149 se = STAILQ_FIRST(sorted);
7150 if (se == NULL) {
7151 err = got_reflist_entry_dup(&new, re);
7152 if (err)
7153 return err;
7154 STAILQ_INSERT_HEAD(sorted, new, entry);
7155 continue;
7156 } else {
7157 err = got_ref_resolve(&re_id, repo, re->ref);
7158 if (err)
7159 break;
7160 err = got_object_open_as_tag(&re_tag, repo, re_id);
7161 free(re_id);
7162 if (err)
7163 break;
7164 re_time = got_object_tag_get_tagger_time(re_tag);
7165 got_object_tag_close(re_tag);
7168 while (se) {
7169 err = got_ref_resolve(&se_id, repo, re->ref);
7170 if (err)
7171 break;
7172 err = got_object_open_as_tag(&se_tag, repo, se_id);
7173 free(se_id);
7174 if (err)
7175 break;
7176 se_time = got_object_tag_get_tagger_time(se_tag);
7177 got_object_tag_close(se_tag);
7179 if (se_time > re_time) {
7180 err = got_reflist_entry_dup(&new, re);
7181 if (err)
7182 return err;
7183 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7184 break;
7186 se = STAILQ_NEXT(se, entry);
7187 continue;
7190 done:
7191 return err;
7193 #endif
7195 static const struct got_error *
7196 get_tag_refname(char **refname, const char *tag_name)
7198 const struct got_error *err;
7200 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7201 *refname = strdup(tag_name);
7202 if (*refname == NULL)
7203 return got_error_from_errno("strdup");
7204 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7205 err = got_error_from_errno("asprintf");
7206 *refname = NULL;
7207 return err;
7210 return NULL;
7213 static const struct got_error *
7214 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7215 const char *allowed_signers, const char *revoked_signers, int verbosity)
7217 static const struct got_error *err = NULL;
7218 struct got_reflist_head refs;
7219 struct got_reflist_entry *re;
7220 char *wanted_refname = NULL;
7221 int bad_sigs = 0;
7223 TAILQ_INIT(&refs);
7225 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7226 if (err)
7227 return err;
7229 if (tag_name) {
7230 struct got_reference *ref;
7231 err = get_tag_refname(&wanted_refname, tag_name);
7232 if (err)
7233 goto done;
7234 /* Wanted tag reference should exist. */
7235 err = got_ref_open(&ref, repo, wanted_refname, 0);
7236 if (err)
7237 goto done;
7238 got_ref_close(ref);
7241 TAILQ_FOREACH(re, &refs, entry) {
7242 const char *refname;
7243 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7244 char datebuf[26];
7245 const char *tagger, *ssh_sig = NULL;
7246 char *sig_msg = NULL;
7247 time_t tagger_time;
7248 struct got_object_id *id;
7249 struct got_tag_object *tag;
7250 struct got_commit_object *commit = NULL;
7252 refname = got_ref_get_name(re->ref);
7253 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7254 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7255 continue;
7256 refname += 10;
7257 refstr = got_ref_to_str(re->ref);
7258 if (refstr == NULL) {
7259 err = got_error_from_errno("got_ref_to_str");
7260 break;
7263 err = got_ref_resolve(&id, repo, re->ref);
7264 if (err)
7265 break;
7266 err = got_object_open_as_tag(&tag, repo, id);
7267 if (err) {
7268 if (err->code != GOT_ERR_OBJ_TYPE) {
7269 free(id);
7270 break;
7272 /* "lightweight" tag */
7273 err = got_object_open_as_commit(&commit, repo, id);
7274 if (err) {
7275 free(id);
7276 break;
7278 tagger = got_object_commit_get_committer(commit);
7279 tagger_time =
7280 got_object_commit_get_committer_time(commit);
7281 err = got_object_id_str(&id_str, id);
7282 free(id);
7283 if (err)
7284 break;
7285 } else {
7286 free(id);
7287 tagger = got_object_tag_get_tagger(tag);
7288 tagger_time = got_object_tag_get_tagger_time(tag);
7289 err = got_object_id_str(&id_str,
7290 got_object_tag_get_object_id(tag));
7291 if (err)
7292 break;
7295 if (tag && verify_tags) {
7296 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7297 got_object_tag_get_message(tag));
7298 if (ssh_sig && allowed_signers == NULL) {
7299 err = got_error_msg(
7300 GOT_ERR_VERIFY_TAG_SIGNATURE,
7301 "SSH signature verification requires "
7302 "setting allowed_signers in "
7303 "got.conf(5)");
7304 break;
7308 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7309 free(refstr);
7310 printf("from: %s\n", tagger);
7311 datestr = get_datestr(&tagger_time, datebuf);
7312 if (datestr)
7313 printf("date: %s UTC\n", datestr);
7314 if (commit)
7315 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7316 else {
7317 switch (got_object_tag_get_object_type(tag)) {
7318 case GOT_OBJ_TYPE_BLOB:
7319 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7320 id_str);
7321 break;
7322 case GOT_OBJ_TYPE_TREE:
7323 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7324 id_str);
7325 break;
7326 case GOT_OBJ_TYPE_COMMIT:
7327 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7328 id_str);
7329 break;
7330 case GOT_OBJ_TYPE_TAG:
7331 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7332 id_str);
7333 break;
7334 default:
7335 break;
7338 free(id_str);
7340 if (ssh_sig) {
7341 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7342 allowed_signers, revoked_signers, verbosity);
7343 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7344 bad_sigs = 1;
7345 else if (err)
7346 break;
7347 printf("signature: %s", sig_msg);
7348 free(sig_msg);
7349 sig_msg = NULL;
7352 if (commit) {
7353 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7354 if (err)
7355 break;
7356 got_object_commit_close(commit);
7357 } else {
7358 tagmsg0 = strdup(got_object_tag_get_message(tag));
7359 got_object_tag_close(tag);
7360 if (tagmsg0 == NULL) {
7361 err = got_error_from_errno("strdup");
7362 break;
7366 tagmsg = tagmsg0;
7367 do {
7368 line = strsep(&tagmsg, "\n");
7369 if (line)
7370 printf(" %s\n", line);
7371 } while (line);
7372 free(tagmsg0);
7374 done:
7375 got_ref_list_free(&refs);
7376 free(wanted_refname);
7378 if (err == NULL && bad_sigs)
7379 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7380 return err;
7383 static const struct got_error *
7384 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7385 const char *tag_name, const char *repo_path)
7387 const struct got_error *err = NULL;
7388 char *template = NULL, *initial_content = NULL;
7389 char *editor = NULL;
7390 int initial_content_len;
7391 int fd = -1;
7393 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7394 err = got_error_from_errno("asprintf");
7395 goto done;
7398 initial_content_len = asprintf(&initial_content,
7399 "\n# tagging commit %s as %s\n",
7400 commit_id_str, tag_name);
7401 if (initial_content_len == -1) {
7402 err = got_error_from_errno("asprintf");
7403 goto done;
7406 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7407 if (err)
7408 goto done;
7410 if (write(fd, initial_content, initial_content_len) == -1) {
7411 err = got_error_from_errno2("write", *tagmsg_path);
7412 goto done;
7414 if (close(fd) == -1) {
7415 err = got_error_from_errno2("close", *tagmsg_path);
7416 goto done;
7418 fd = -1;
7420 err = get_editor(&editor);
7421 if (err)
7422 goto done;
7423 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7424 initial_content_len, 1);
7425 done:
7426 free(initial_content);
7427 free(template);
7428 free(editor);
7430 if (fd != -1 && close(fd) == -1 && err == NULL)
7431 err = got_error_from_errno2("close", *tagmsg_path);
7433 if (err) {
7434 free(*tagmsg);
7435 *tagmsg = NULL;
7437 return err;
7440 static const struct got_error *
7441 add_tag(struct got_repository *repo, const char *tagger,
7442 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7443 const char *signer_id, int verbosity)
7445 const struct got_error *err = NULL;
7446 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7447 char *label = NULL, *commit_id_str = NULL;
7448 struct got_reference *ref = NULL;
7449 char *refname = NULL, *tagmsg = NULL;
7450 char *tagmsg_path = NULL, *tag_id_str = NULL;
7451 int preserve_tagmsg = 0;
7452 struct got_reflist_head refs;
7454 TAILQ_INIT(&refs);
7457 * Don't let the user create a tag name with a leading '-'.
7458 * While technically a valid reference name, this case is usually
7459 * an unintended typo.
7461 if (tag_name[0] == '-')
7462 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7464 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7465 if (err)
7466 goto done;
7468 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7469 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7470 if (err)
7471 goto done;
7473 err = got_object_id_str(&commit_id_str, commit_id);
7474 if (err)
7475 goto done;
7477 err = get_tag_refname(&refname, tag_name);
7478 if (err)
7479 goto done;
7480 if (strncmp("refs/tags/", tag_name, 10) == 0)
7481 tag_name += 10;
7483 err = got_ref_open(&ref, repo, refname, 0);
7484 if (err == NULL) {
7485 err = got_error(GOT_ERR_TAG_EXISTS);
7486 goto done;
7487 } else if (err->code != GOT_ERR_NOT_REF)
7488 goto done;
7490 if (tagmsg_arg == NULL) {
7491 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7492 tag_name, got_repo_get_path(repo));
7493 if (err) {
7494 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7495 tagmsg_path != NULL)
7496 preserve_tagmsg = 1;
7497 goto done;
7499 /* Editor is done; we can now apply unveil(2) */
7500 err = got_sigs_apply_unveil();
7501 if (err)
7502 goto done;
7503 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7504 if (err)
7505 goto done;
7508 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7509 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7510 verbosity);
7511 if (err) {
7512 if (tagmsg_path)
7513 preserve_tagmsg = 1;
7514 goto done;
7517 err = got_ref_alloc(&ref, refname, tag_id);
7518 if (err) {
7519 if (tagmsg_path)
7520 preserve_tagmsg = 1;
7521 goto done;
7524 err = got_ref_write(ref, repo);
7525 if (err) {
7526 if (tagmsg_path)
7527 preserve_tagmsg = 1;
7528 goto done;
7531 err = got_object_id_str(&tag_id_str, tag_id);
7532 if (err) {
7533 if (tagmsg_path)
7534 preserve_tagmsg = 1;
7535 goto done;
7537 printf("Created tag %s\n", tag_id_str);
7538 done:
7539 if (preserve_tagmsg) {
7540 fprintf(stderr, "%s: tag message preserved in %s\n",
7541 getprogname(), tagmsg_path);
7542 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7543 err = got_error_from_errno2("unlink", tagmsg_path);
7544 free(tag_id_str);
7545 if (ref)
7546 got_ref_close(ref);
7547 free(commit_id);
7548 free(commit_id_str);
7549 free(refname);
7550 free(tagmsg);
7551 free(tagmsg_path);
7552 got_ref_list_free(&refs);
7553 return err;
7556 static const struct got_error *
7557 cmd_tag(int argc, char *argv[])
7559 const struct got_error *error = NULL;
7560 struct got_repository *repo = NULL;
7561 struct got_worktree *worktree = NULL;
7562 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7563 char *gitconfig_path = NULL, *tagger = NULL;
7564 char *allowed_signers = NULL, *revoked_signers = NULL;
7565 const char *signer_id = NULL;
7566 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7567 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7568 int *pack_fds = NULL;
7570 #ifndef PROFILE
7571 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7572 "sendfd unveil", NULL) == -1)
7573 err(1, "pledge");
7574 #endif
7576 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7577 switch (ch) {
7578 case 'c':
7579 commit_id_arg = optarg;
7580 break;
7581 case 'l':
7582 do_list = 1;
7583 break;
7584 case 'm':
7585 tagmsg = optarg;
7586 break;
7587 case 'r':
7588 repo_path = realpath(optarg, NULL);
7589 if (repo_path == NULL) {
7590 error = got_error_from_errno2("realpath",
7591 optarg);
7592 goto done;
7594 got_path_strip_trailing_slashes(repo_path);
7595 break;
7596 case 's':
7597 signer_id = optarg;
7598 break;
7599 case 'V':
7600 verify_tags = 1;
7601 break;
7602 case 'v':
7603 if (verbosity < 0)
7604 verbosity = 0;
7605 else if (verbosity < 3)
7606 verbosity++;
7607 break;
7608 default:
7609 usage_tag();
7610 /* NOTREACHED */
7614 argc -= optind;
7615 argv += optind;
7617 if (do_list || verify_tags) {
7618 if (commit_id_arg != NULL)
7619 errx(1,
7620 "-c option can only be used when creating a tag");
7621 if (tagmsg) {
7622 if (do_list)
7623 option_conflict('l', 'm');
7624 else
7625 option_conflict('V', 'm');
7627 if (signer_id) {
7628 if (do_list)
7629 option_conflict('l', 's');
7630 else
7631 option_conflict('V', 's');
7633 if (argc > 1)
7634 usage_tag();
7635 } else if (argc != 1)
7636 usage_tag();
7638 if (argc == 1)
7639 tag_name = argv[0];
7641 cwd = getcwd(NULL, 0);
7642 if (cwd == NULL) {
7643 error = got_error_from_errno("getcwd");
7644 goto done;
7647 error = got_repo_pack_fds_open(&pack_fds);
7648 if (error != NULL)
7649 goto done;
7651 if (repo_path == NULL) {
7652 error = got_worktree_open(&worktree, cwd);
7653 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7654 goto done;
7655 else
7656 error = NULL;
7657 if (worktree) {
7658 repo_path =
7659 strdup(got_worktree_get_repo_path(worktree));
7660 if (repo_path == NULL)
7661 error = got_error_from_errno("strdup");
7662 if (error)
7663 goto done;
7664 } else {
7665 repo_path = strdup(cwd);
7666 if (repo_path == NULL) {
7667 error = got_error_from_errno("strdup");
7668 goto done;
7673 if (do_list || verify_tags) {
7674 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7675 if (error != NULL)
7676 goto done;
7677 error = get_allowed_signers(&allowed_signers, repo, worktree);
7678 if (error)
7679 goto done;
7680 error = get_revoked_signers(&revoked_signers, repo, worktree);
7681 if (error)
7682 goto done;
7683 if (worktree) {
7684 /* Release work tree lock. */
7685 got_worktree_close(worktree);
7686 worktree = NULL;
7690 * Remove "cpath" promise unless needed for signature tmpfile
7691 * creation.
7693 if (verify_tags)
7694 got_sigs_apply_unveil();
7695 else {
7696 #ifndef PROFILE
7697 if (pledge("stdio rpath wpath flock proc exec sendfd "
7698 "unveil", NULL) == -1)
7699 err(1, "pledge");
7700 #endif
7702 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7703 if (error)
7704 goto done;
7705 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7706 revoked_signers, verbosity);
7707 } else {
7708 error = get_gitconfig_path(&gitconfig_path);
7709 if (error)
7710 goto done;
7711 error = got_repo_open(&repo, repo_path, gitconfig_path,
7712 pack_fds);
7713 if (error != NULL)
7714 goto done;
7716 error = get_author(&tagger, repo, worktree);
7717 if (error)
7718 goto done;
7719 if (signer_id == NULL)
7720 signer_id = get_signer_id(repo, worktree);
7722 if (tagmsg) {
7723 if (signer_id) {
7724 error = got_sigs_apply_unveil();
7725 if (error)
7726 goto done;
7728 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7729 if (error)
7730 goto done;
7733 if (commit_id_arg == NULL) {
7734 struct got_reference *head_ref;
7735 struct got_object_id *commit_id;
7736 error = got_ref_open(&head_ref, repo,
7737 worktree ? got_worktree_get_head_ref_name(worktree)
7738 : GOT_REF_HEAD, 0);
7739 if (error)
7740 goto done;
7741 error = got_ref_resolve(&commit_id, repo, head_ref);
7742 got_ref_close(head_ref);
7743 if (error)
7744 goto done;
7745 error = got_object_id_str(&commit_id_str, commit_id);
7746 free(commit_id);
7747 if (error)
7748 goto done;
7751 if (worktree) {
7752 /* Release work tree lock. */
7753 got_worktree_close(worktree);
7754 worktree = NULL;
7757 error = add_tag(repo, tagger, tag_name,
7758 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7759 signer_id, verbosity);
7761 done:
7762 if (repo) {
7763 const struct got_error *close_err = got_repo_close(repo);
7764 if (error == NULL)
7765 error = close_err;
7767 if (worktree)
7768 got_worktree_close(worktree);
7769 if (pack_fds) {
7770 const struct got_error *pack_err =
7771 got_repo_pack_fds_close(pack_fds);
7772 if (error == NULL)
7773 error = pack_err;
7775 free(cwd);
7776 free(repo_path);
7777 free(gitconfig_path);
7778 free(commit_id_str);
7779 free(tagger);
7780 free(allowed_signers);
7781 free(revoked_signers);
7782 return error;
7785 __dead static void
7786 usage_add(void)
7788 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7789 exit(1);
7792 static const struct got_error *
7793 add_progress(void *arg, unsigned char status, const char *path)
7795 while (path[0] == '/')
7796 path++;
7797 printf("%c %s\n", status, path);
7798 return NULL;
7801 static const struct got_error *
7802 cmd_add(int argc, char *argv[])
7804 const struct got_error *error = NULL;
7805 struct got_repository *repo = NULL;
7806 struct got_worktree *worktree = NULL;
7807 char *cwd = NULL;
7808 struct got_pathlist_head paths;
7809 struct got_pathlist_entry *pe;
7810 int ch, can_recurse = 0, no_ignores = 0;
7811 int *pack_fds = NULL;
7813 TAILQ_INIT(&paths);
7815 #ifndef PROFILE
7816 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7817 NULL) == -1)
7818 err(1, "pledge");
7819 #endif
7821 while ((ch = getopt(argc, argv, "IR")) != -1) {
7822 switch (ch) {
7823 case 'I':
7824 no_ignores = 1;
7825 break;
7826 case 'R':
7827 can_recurse = 1;
7828 break;
7829 default:
7830 usage_add();
7831 /* NOTREACHED */
7835 argc -= optind;
7836 argv += optind;
7838 if (argc < 1)
7839 usage_add();
7841 cwd = getcwd(NULL, 0);
7842 if (cwd == NULL) {
7843 error = got_error_from_errno("getcwd");
7844 goto done;
7847 error = got_repo_pack_fds_open(&pack_fds);
7848 if (error != NULL)
7849 goto done;
7851 error = got_worktree_open(&worktree, cwd);
7852 if (error) {
7853 if (error->code == GOT_ERR_NOT_WORKTREE)
7854 error = wrap_not_worktree_error(error, "add", cwd);
7855 goto done;
7858 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7859 NULL, pack_fds);
7860 if (error != NULL)
7861 goto done;
7863 error = apply_unveil(got_repo_get_path(repo), 1,
7864 got_worktree_get_root_path(worktree));
7865 if (error)
7866 goto done;
7868 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7869 if (error)
7870 goto done;
7872 if (!can_recurse) {
7873 char *ondisk_path;
7874 struct stat sb;
7875 TAILQ_FOREACH(pe, &paths, entry) {
7876 if (asprintf(&ondisk_path, "%s/%s",
7877 got_worktree_get_root_path(worktree),
7878 pe->path) == -1) {
7879 error = got_error_from_errno("asprintf");
7880 goto done;
7882 if (lstat(ondisk_path, &sb) == -1) {
7883 if (errno == ENOENT) {
7884 free(ondisk_path);
7885 continue;
7887 error = got_error_from_errno2("lstat",
7888 ondisk_path);
7889 free(ondisk_path);
7890 goto done;
7892 free(ondisk_path);
7893 if (S_ISDIR(sb.st_mode)) {
7894 error = got_error_msg(GOT_ERR_BAD_PATH,
7895 "adding directories requires -R option");
7896 goto done;
7901 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7902 NULL, repo, no_ignores);
7903 done:
7904 if (repo) {
7905 const struct got_error *close_err = got_repo_close(repo);
7906 if (error == NULL)
7907 error = close_err;
7909 if (worktree)
7910 got_worktree_close(worktree);
7911 if (pack_fds) {
7912 const struct got_error *pack_err =
7913 got_repo_pack_fds_close(pack_fds);
7914 if (error == NULL)
7915 error = pack_err;
7917 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7918 free(cwd);
7919 return error;
7922 __dead static void
7923 usage_remove(void)
7925 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7926 getprogname());
7927 exit(1);
7930 static const struct got_error *
7931 print_remove_status(void *arg, unsigned char status,
7932 unsigned char staged_status, const char *path)
7934 while (path[0] == '/')
7935 path++;
7936 if (status == GOT_STATUS_NONEXISTENT)
7937 return NULL;
7938 if (status == staged_status && (status == GOT_STATUS_DELETE))
7939 status = GOT_STATUS_NO_CHANGE;
7940 printf("%c%c %s\n", status, staged_status, path);
7941 return NULL;
7944 static const struct got_error *
7945 cmd_remove(int argc, char *argv[])
7947 const struct got_error *error = NULL;
7948 struct got_worktree *worktree = NULL;
7949 struct got_repository *repo = NULL;
7950 const char *status_codes = NULL;
7951 char *cwd = NULL;
7952 struct got_pathlist_head paths;
7953 struct got_pathlist_entry *pe;
7954 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7955 int ignore_missing_paths = 0;
7956 int *pack_fds = NULL;
7958 TAILQ_INIT(&paths);
7960 #ifndef PROFILE
7961 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7962 NULL) == -1)
7963 err(1, "pledge");
7964 #endif
7966 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7967 switch (ch) {
7968 case 'f':
7969 delete_local_mods = 1;
7970 ignore_missing_paths = 1;
7971 break;
7972 case 'k':
7973 keep_on_disk = 1;
7974 break;
7975 case 'R':
7976 can_recurse = 1;
7977 break;
7978 case 's':
7979 for (i = 0; i < strlen(optarg); i++) {
7980 switch (optarg[i]) {
7981 case GOT_STATUS_MODIFY:
7982 delete_local_mods = 1;
7983 break;
7984 case GOT_STATUS_MISSING:
7985 ignore_missing_paths = 1;
7986 break;
7987 default:
7988 errx(1, "invalid status code '%c'",
7989 optarg[i]);
7992 status_codes = optarg;
7993 break;
7994 default:
7995 usage_remove();
7996 /* NOTREACHED */
8000 argc -= optind;
8001 argv += optind;
8003 if (argc < 1)
8004 usage_remove();
8006 cwd = getcwd(NULL, 0);
8007 if (cwd == NULL) {
8008 error = got_error_from_errno("getcwd");
8009 goto done;
8012 error = got_repo_pack_fds_open(&pack_fds);
8013 if (error != NULL)
8014 goto done;
8016 error = got_worktree_open(&worktree, cwd);
8017 if (error) {
8018 if (error->code == GOT_ERR_NOT_WORKTREE)
8019 error = wrap_not_worktree_error(error, "remove", cwd);
8020 goto done;
8023 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8024 NULL, pack_fds);
8025 if (error)
8026 goto done;
8028 error = apply_unveil(got_repo_get_path(repo), 1,
8029 got_worktree_get_root_path(worktree));
8030 if (error)
8031 goto done;
8033 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8034 if (error)
8035 goto done;
8037 if (!can_recurse) {
8038 char *ondisk_path;
8039 struct stat sb;
8040 TAILQ_FOREACH(pe, &paths, entry) {
8041 if (asprintf(&ondisk_path, "%s/%s",
8042 got_worktree_get_root_path(worktree),
8043 pe->path) == -1) {
8044 error = got_error_from_errno("asprintf");
8045 goto done;
8047 if (lstat(ondisk_path, &sb) == -1) {
8048 if (errno == ENOENT) {
8049 free(ondisk_path);
8050 continue;
8052 error = got_error_from_errno2("lstat",
8053 ondisk_path);
8054 free(ondisk_path);
8055 goto done;
8057 free(ondisk_path);
8058 if (S_ISDIR(sb.st_mode)) {
8059 error = got_error_msg(GOT_ERR_BAD_PATH,
8060 "removing directories requires -R option");
8061 goto done;
8066 error = got_worktree_schedule_delete(worktree, &paths,
8067 delete_local_mods, status_codes, print_remove_status, NULL,
8068 repo, keep_on_disk, ignore_missing_paths);
8069 done:
8070 if (repo) {
8071 const struct got_error *close_err = got_repo_close(repo);
8072 if (error == NULL)
8073 error = close_err;
8075 if (worktree)
8076 got_worktree_close(worktree);
8077 if (pack_fds) {
8078 const struct got_error *pack_err =
8079 got_repo_pack_fds_close(pack_fds);
8080 if (error == NULL)
8081 error = pack_err;
8083 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8084 free(cwd);
8085 return error;
8088 __dead static void
8089 usage_patch(void)
8091 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8092 "[patchfile]\n", getprogname());
8093 exit(1);
8096 static const struct got_error *
8097 patch_from_stdin(int *patchfd)
8099 const struct got_error *err = NULL;
8100 ssize_t r;
8101 char buf[BUFSIZ];
8102 sig_t sighup, sigint, sigquit;
8104 *patchfd = got_opentempfd();
8105 if (*patchfd == -1)
8106 return got_error_from_errno("got_opentempfd");
8108 sighup = signal(SIGHUP, SIG_DFL);
8109 sigint = signal(SIGINT, SIG_DFL);
8110 sigquit = signal(SIGQUIT, SIG_DFL);
8112 for (;;) {
8113 r = read(0, buf, sizeof(buf));
8114 if (r == -1) {
8115 err = got_error_from_errno("read");
8116 break;
8118 if (r == 0)
8119 break;
8120 if (write(*patchfd, buf, r) == -1) {
8121 err = got_error_from_errno("write");
8122 break;
8126 signal(SIGHUP, sighup);
8127 signal(SIGINT, sigint);
8128 signal(SIGQUIT, sigquit);
8130 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8131 err = got_error_from_errno("lseek");
8133 if (err != NULL) {
8134 close(*patchfd);
8135 *patchfd = -1;
8138 return err;
8141 static const struct got_error *
8142 patch_progress(void *arg, const char *old, const char *new,
8143 unsigned char status, const struct got_error *error, int old_from,
8144 int old_lines, int new_from, int new_lines, int offset,
8145 int ws_mangled, const struct got_error *hunk_err)
8147 const char *path = new == NULL ? old : new;
8149 while (*path == '/')
8150 path++;
8152 if (status != 0)
8153 printf("%c %s\n", status, path);
8155 if (error != NULL)
8156 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8158 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8159 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8160 old_lines, new_from, new_lines);
8161 if (hunk_err != NULL)
8162 printf("%s\n", hunk_err->msg);
8163 else if (offset != 0)
8164 printf("applied with offset %d\n", offset);
8165 else
8166 printf("hunk contains mangled whitespace\n");
8169 return NULL;
8172 static const struct got_error *
8173 cmd_patch(int argc, char *argv[])
8175 const struct got_error *error = NULL, *close_error = NULL;
8176 struct got_worktree *worktree = NULL;
8177 struct got_repository *repo = NULL;
8178 struct got_reflist_head refs;
8179 struct got_object_id *commit_id = NULL;
8180 const char *commit_id_str = NULL;
8181 struct stat sb;
8182 const char *errstr;
8183 char *cwd = NULL;
8184 int ch, nop = 0, strip = -1, reverse = 0;
8185 int patchfd;
8186 int *pack_fds = NULL;
8188 TAILQ_INIT(&refs);
8190 #ifndef PROFILE
8191 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8192 "unveil", NULL) == -1)
8193 err(1, "pledge");
8194 #endif
8196 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8197 switch (ch) {
8198 case 'c':
8199 commit_id_str = optarg;
8200 break;
8201 case 'n':
8202 nop = 1;
8203 break;
8204 case 'p':
8205 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8206 if (errstr != NULL)
8207 errx(1, "pathname strip count is %s: %s",
8208 errstr, optarg);
8209 break;
8210 case 'R':
8211 reverse = 1;
8212 break;
8213 default:
8214 usage_patch();
8215 /* NOTREACHED */
8219 argc -= optind;
8220 argv += optind;
8222 if (argc == 0) {
8223 error = patch_from_stdin(&patchfd);
8224 if (error)
8225 return error;
8226 } else if (argc == 1) {
8227 patchfd = open(argv[0], O_RDONLY);
8228 if (patchfd == -1) {
8229 error = got_error_from_errno2("open", argv[0]);
8230 return error;
8232 if (fstat(patchfd, &sb) == -1) {
8233 error = got_error_from_errno2("fstat", argv[0]);
8234 goto done;
8236 if (!S_ISREG(sb.st_mode)) {
8237 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8238 goto done;
8240 } else
8241 usage_patch();
8243 if ((cwd = getcwd(NULL, 0)) == NULL) {
8244 error = got_error_from_errno("getcwd");
8245 goto done;
8248 error = got_repo_pack_fds_open(&pack_fds);
8249 if (error != NULL)
8250 goto done;
8252 error = got_worktree_open(&worktree, cwd);
8253 if (error != NULL)
8254 goto done;
8256 const char *repo_path = got_worktree_get_repo_path(worktree);
8257 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8258 if (error != NULL)
8259 goto done;
8261 error = apply_unveil(got_repo_get_path(repo), 0,
8262 got_worktree_get_root_path(worktree));
8263 if (error != NULL)
8264 goto done;
8266 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8267 if (error)
8268 goto done;
8270 if (commit_id_str != NULL) {
8271 error = got_repo_match_object_id(&commit_id, NULL,
8272 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8273 if (error)
8274 goto done;
8277 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8278 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8280 done:
8281 got_ref_list_free(&refs);
8282 free(commit_id);
8283 if (repo) {
8284 close_error = got_repo_close(repo);
8285 if (error == NULL)
8286 error = close_error;
8288 if (worktree != NULL) {
8289 close_error = got_worktree_close(worktree);
8290 if (error == NULL)
8291 error = close_error;
8293 if (pack_fds) {
8294 const struct got_error *pack_err =
8295 got_repo_pack_fds_close(pack_fds);
8296 if (error == NULL)
8297 error = pack_err;
8299 free(cwd);
8300 return error;
8303 __dead static void
8304 usage_revert(void)
8306 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8307 getprogname());
8308 exit(1);
8311 static const struct got_error *
8312 revert_progress(void *arg, unsigned char status, const char *path)
8314 if (status == GOT_STATUS_UNVERSIONED)
8315 return NULL;
8317 while (path[0] == '/')
8318 path++;
8319 printf("%c %s\n", status, path);
8320 return NULL;
8323 struct choose_patch_arg {
8324 FILE *patch_script_file;
8325 const char *action;
8328 static const struct got_error *
8329 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8330 int nchanges, const char *action)
8332 const struct got_error *err;
8333 char *line = NULL;
8334 size_t linesize = 0;
8335 ssize_t linelen;
8337 switch (status) {
8338 case GOT_STATUS_ADD:
8339 printf("A %s\n%s this addition? [y/n] ", path, action);
8340 break;
8341 case GOT_STATUS_DELETE:
8342 printf("D %s\n%s this deletion? [y/n] ", path, action);
8343 break;
8344 case GOT_STATUS_MODIFY:
8345 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8346 return got_error_from_errno("fseek");
8347 printf(GOT_COMMIT_SEP_STR);
8348 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8349 printf("%s", line);
8350 if (linelen == -1 && ferror(patch_file)) {
8351 err = got_error_from_errno("getline");
8352 free(line);
8353 return err;
8355 free(line);
8356 printf(GOT_COMMIT_SEP_STR);
8357 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8358 path, n, nchanges, action);
8359 break;
8360 default:
8361 return got_error_path(path, GOT_ERR_FILE_STATUS);
8364 fflush(stdout);
8365 return NULL;
8368 static const struct got_error *
8369 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8370 FILE *patch_file, int n, int nchanges)
8372 const struct got_error *err = NULL;
8373 char *line = NULL;
8374 size_t linesize = 0;
8375 ssize_t linelen;
8376 int resp = ' ';
8377 struct choose_patch_arg *a = arg;
8379 *choice = GOT_PATCH_CHOICE_NONE;
8381 if (a->patch_script_file) {
8382 char *nl;
8383 err = show_change(status, path, patch_file, n, nchanges,
8384 a->action);
8385 if (err)
8386 return err;
8387 linelen = getline(&line, &linesize, a->patch_script_file);
8388 if (linelen == -1) {
8389 if (ferror(a->patch_script_file))
8390 return got_error_from_errno("getline");
8391 return NULL;
8393 nl = strchr(line, '\n');
8394 if (nl)
8395 *nl = '\0';
8396 if (strcmp(line, "y") == 0) {
8397 *choice = GOT_PATCH_CHOICE_YES;
8398 printf("y\n");
8399 } else if (strcmp(line, "n") == 0) {
8400 *choice = GOT_PATCH_CHOICE_NO;
8401 printf("n\n");
8402 } else if (strcmp(line, "q") == 0 &&
8403 status == GOT_STATUS_MODIFY) {
8404 *choice = GOT_PATCH_CHOICE_QUIT;
8405 printf("q\n");
8406 } else
8407 printf("invalid response '%s'\n", line);
8408 free(line);
8409 return NULL;
8412 while (resp != 'y' && resp != 'n' && resp != 'q') {
8413 err = show_change(status, path, patch_file, n, nchanges,
8414 a->action);
8415 if (err)
8416 return err;
8417 resp = getchar();
8418 if (resp == '\n')
8419 resp = getchar();
8420 if (status == GOT_STATUS_MODIFY) {
8421 if (resp != 'y' && resp != 'n' && resp != 'q') {
8422 printf("invalid response '%c'\n", resp);
8423 resp = ' ';
8425 } else if (resp != 'y' && resp != 'n') {
8426 printf("invalid response '%c'\n", resp);
8427 resp = ' ';
8431 if (resp == 'y')
8432 *choice = GOT_PATCH_CHOICE_YES;
8433 else if (resp == 'n')
8434 *choice = GOT_PATCH_CHOICE_NO;
8435 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8436 *choice = GOT_PATCH_CHOICE_QUIT;
8438 return NULL;
8441 struct wt_commitable_path_arg {
8442 struct got_pathlist_head *commit_paths;
8443 int *has_changes;
8447 * Shortcut work tree status callback to determine if the set of paths scanned
8448 * has at least one versioned path that is being modified and, if not NULL, is
8449 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8450 * soon as a path is passed with a status that satisfies this criteria.
8452 static const struct got_error *
8453 worktree_has_commitable_path(void *arg, unsigned char status,
8454 unsigned char staged_status, const char *path,
8455 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8456 struct got_object_id *commit_id, int dirfd, const char *de_name)
8458 struct wt_commitable_path_arg *a = arg;
8460 if (status == staged_status && (status == GOT_STATUS_DELETE))
8461 status = GOT_STATUS_NO_CHANGE;
8463 if (!(status == GOT_STATUS_NO_CHANGE ||
8464 status == GOT_STATUS_UNVERSIONED) ||
8465 staged_status != GOT_STATUS_NO_CHANGE) {
8466 if (a->commit_paths != NULL) {
8467 struct got_pathlist_entry *pe;
8469 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8470 if (strncmp(path, pe->path,
8471 pe->path_len) == 0) {
8472 *a->has_changes = 1;
8473 break;
8476 } else
8477 *a->has_changes = 1;
8479 if (*a->has_changes)
8480 return got_error(GOT_ERR_FILE_MODIFIED);
8483 return NULL;
8487 * Check that the changeset of the commit identified by id is
8488 * comprised of at least one modified path that is being committed.
8490 static const struct got_error *
8491 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8492 struct got_object_id *id, struct got_worktree *worktree,
8493 struct got_repository *repo)
8495 const struct got_error *err;
8496 struct got_pathlist_head paths;
8497 struct got_commit_object *commit = NULL, *pcommit = NULL;
8498 struct got_tree_object *tree = NULL, *ptree = NULL;
8499 struct got_object_qid *pid;
8501 TAILQ_INIT(&paths);
8503 err = got_object_open_as_commit(&commit, repo, id);
8504 if (err)
8505 goto done;
8507 err = got_object_open_as_tree(&tree, repo,
8508 got_object_commit_get_tree_id(commit));
8509 if (err)
8510 goto done;
8512 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8513 if (pid != NULL) {
8514 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8515 if (err)
8516 goto done;
8518 err = got_object_open_as_tree(&ptree, repo,
8519 got_object_commit_get_tree_id(pcommit));
8520 if (err)
8521 goto done;
8524 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8525 got_diff_tree_collect_changed_paths, &paths, 0);
8526 if (err)
8527 goto done;
8529 err = got_worktree_status(worktree, &paths, repo, 0,
8530 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8531 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8533 * At least one changed path in the referenced commit is
8534 * modified in the work tree, that's all we need to know!
8536 err = NULL;
8539 done:
8540 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8541 if (commit)
8542 got_object_commit_close(commit);
8543 if (pcommit)
8544 got_object_commit_close(pcommit);
8545 if (tree)
8546 got_object_tree_close(tree);
8547 if (ptree)
8548 got_object_tree_close(ptree);
8549 return err;
8553 * Remove any "logmsg" reference comprised entirely of paths that have
8554 * been reverted in this work tree. If any path in the logmsg ref changeset
8555 * remains in a changed state in the worktree, do not remove the reference.
8557 static const struct got_error *
8558 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8560 const struct got_error *err;
8561 struct got_reflist_head refs;
8562 struct got_reflist_entry *re;
8563 struct got_commit_object *commit = NULL;
8564 struct got_object_id *commit_id = NULL;
8565 struct wt_commitable_path_arg wcpa;
8566 char *uuidstr = NULL;
8568 TAILQ_INIT(&refs);
8570 err = got_worktree_get_uuid(&uuidstr, worktree);
8571 if (err)
8572 goto done;
8574 err = got_ref_list(&refs, repo, "refs/got/worktree",
8575 got_ref_cmp_by_name, repo);
8576 if (err)
8577 goto done;
8579 TAILQ_FOREACH(re, &refs, entry) {
8580 const char *refname;
8581 int has_changes = 0;
8583 refname = got_ref_get_name(re->ref);
8585 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8586 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8587 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8588 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8589 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8590 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8591 else
8592 continue;
8594 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8595 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8596 else
8597 continue;
8599 err = got_repo_match_object_id(&commit_id, NULL, refname,
8600 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8601 if (err)
8602 goto done;
8604 err = got_object_open_as_commit(&commit, repo, commit_id);
8605 if (err)
8606 goto done;
8608 wcpa.commit_paths = NULL;
8609 wcpa.has_changes = &has_changes;
8611 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8612 worktree, repo);
8613 if (err)
8614 goto done;
8616 if (!has_changes) {
8617 err = got_ref_delete(re->ref, repo);
8618 if (err)
8619 goto done;
8622 got_object_commit_close(commit);
8623 commit = NULL;
8624 free(commit_id);
8625 commit_id = NULL;
8628 done:
8629 free(uuidstr);
8630 free(commit_id);
8631 got_ref_list_free(&refs);
8632 if (commit)
8633 got_object_commit_close(commit);
8634 return err;
8637 static const struct got_error *
8638 cmd_revert(int argc, char *argv[])
8640 const struct got_error *error = NULL;
8641 struct got_worktree *worktree = NULL;
8642 struct got_repository *repo = NULL;
8643 char *cwd = NULL, *path = NULL;
8644 struct got_pathlist_head paths;
8645 struct got_pathlist_entry *pe;
8646 int ch, can_recurse = 0, pflag = 0;
8647 FILE *patch_script_file = NULL;
8648 const char *patch_script_path = NULL;
8649 struct choose_patch_arg cpa;
8650 int *pack_fds = NULL;
8652 TAILQ_INIT(&paths);
8654 #ifndef PROFILE
8655 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8656 "unveil", NULL) == -1)
8657 err(1, "pledge");
8658 #endif
8660 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8661 switch (ch) {
8662 case 'F':
8663 patch_script_path = optarg;
8664 break;
8665 case 'p':
8666 pflag = 1;
8667 break;
8668 case 'R':
8669 can_recurse = 1;
8670 break;
8671 default:
8672 usage_revert();
8673 /* NOTREACHED */
8677 argc -= optind;
8678 argv += optind;
8680 if (argc < 1)
8681 usage_revert();
8682 if (patch_script_path && !pflag)
8683 errx(1, "-F option can only be used together with -p option");
8685 cwd = getcwd(NULL, 0);
8686 if (cwd == NULL) {
8687 error = got_error_from_errno("getcwd");
8688 goto done;
8691 error = got_repo_pack_fds_open(&pack_fds);
8692 if (error != NULL)
8693 goto done;
8695 error = got_worktree_open(&worktree, cwd);
8696 if (error) {
8697 if (error->code == GOT_ERR_NOT_WORKTREE)
8698 error = wrap_not_worktree_error(error, "revert", cwd);
8699 goto done;
8702 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8703 NULL, pack_fds);
8704 if (error != NULL)
8705 goto done;
8707 if (patch_script_path) {
8708 patch_script_file = fopen(patch_script_path, "re");
8709 if (patch_script_file == NULL) {
8710 error = got_error_from_errno2("fopen",
8711 patch_script_path);
8712 goto done;
8717 * XXX "c" perm needed on repo dir to delete merge references.
8719 error = apply_unveil(got_repo_get_path(repo), 0,
8720 got_worktree_get_root_path(worktree));
8721 if (error)
8722 goto done;
8724 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8725 if (error)
8726 goto done;
8728 if (!can_recurse) {
8729 char *ondisk_path;
8730 struct stat sb;
8731 TAILQ_FOREACH(pe, &paths, entry) {
8732 if (asprintf(&ondisk_path, "%s/%s",
8733 got_worktree_get_root_path(worktree),
8734 pe->path) == -1) {
8735 error = got_error_from_errno("asprintf");
8736 goto done;
8738 if (lstat(ondisk_path, &sb) == -1) {
8739 if (errno == ENOENT) {
8740 free(ondisk_path);
8741 continue;
8743 error = got_error_from_errno2("lstat",
8744 ondisk_path);
8745 free(ondisk_path);
8746 goto done;
8748 free(ondisk_path);
8749 if (S_ISDIR(sb.st_mode)) {
8750 error = got_error_msg(GOT_ERR_BAD_PATH,
8751 "reverting directories requires -R option");
8752 goto done;
8757 cpa.patch_script_file = patch_script_file;
8758 cpa.action = "revert";
8759 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8760 pflag ? choose_patch : NULL, &cpa, repo);
8762 error = rm_logmsg_ref(worktree, repo);
8763 done:
8764 if (patch_script_file && fclose(patch_script_file) == EOF &&
8765 error == NULL)
8766 error = got_error_from_errno2("fclose", patch_script_path);
8767 if (repo) {
8768 const struct got_error *close_err = got_repo_close(repo);
8769 if (error == NULL)
8770 error = close_err;
8772 if (worktree)
8773 got_worktree_close(worktree);
8774 if (pack_fds) {
8775 const struct got_error *pack_err =
8776 got_repo_pack_fds_close(pack_fds);
8777 if (error == NULL)
8778 error = pack_err;
8780 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8781 free(path);
8782 free(cwd);
8783 return error;
8786 __dead static void
8787 usage_commit(void)
8789 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8790 "[-m message] [path ...]\n", getprogname());
8791 exit(1);
8794 struct collect_commit_logmsg_arg {
8795 const char *cmdline_log;
8796 const char *prepared_log;
8797 const char *merged_log;
8798 int non_interactive;
8799 const char *editor;
8800 const char *worktree_path;
8801 const char *branch_name;
8802 const char *repo_path;
8803 char *logmsg_path;
8807 static const struct got_error *
8808 read_prepared_logmsg(char **logmsg, const char *path)
8810 const struct got_error *err = NULL;
8811 FILE *f = NULL;
8812 struct stat sb;
8813 size_t r;
8815 *logmsg = NULL;
8816 memset(&sb, 0, sizeof(sb));
8818 f = fopen(path, "re");
8819 if (f == NULL)
8820 return got_error_from_errno2("fopen", path);
8822 if (fstat(fileno(f), &sb) == -1) {
8823 err = got_error_from_errno2("fstat", path);
8824 goto done;
8826 if (sb.st_size == 0) {
8827 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8828 goto done;
8831 *logmsg = malloc(sb.st_size + 1);
8832 if (*logmsg == NULL) {
8833 err = got_error_from_errno("malloc");
8834 goto done;
8837 r = fread(*logmsg, 1, sb.st_size, f);
8838 if (r != sb.st_size) {
8839 if (ferror(f))
8840 err = got_error_from_errno2("fread", path);
8841 else
8842 err = got_error(GOT_ERR_IO);
8843 goto done;
8845 (*logmsg)[sb.st_size] = '\0';
8846 done:
8847 if (fclose(f) == EOF && err == NULL)
8848 err = got_error_from_errno2("fclose", path);
8849 if (err) {
8850 free(*logmsg);
8851 *logmsg = NULL;
8853 return err;
8856 static const struct got_error *
8857 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8858 const char *diff_path, char **logmsg, void *arg)
8860 char *initial_content = NULL;
8861 struct got_pathlist_entry *pe;
8862 const struct got_error *err = NULL;
8863 char *template = NULL;
8864 char *prepared_msg = NULL, *merged_msg = NULL;
8865 struct collect_commit_logmsg_arg *a = arg;
8866 int initial_content_len;
8867 int fd = -1;
8868 size_t len;
8870 /* if a message was specified on the command line, just use it */
8871 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8872 len = strlen(a->cmdline_log) + 1;
8873 *logmsg = malloc(len + 1);
8874 if (*logmsg == NULL)
8875 return got_error_from_errno("malloc");
8876 strlcpy(*logmsg, a->cmdline_log, len);
8877 return NULL;
8878 } else if (a->prepared_log != NULL && a->non_interactive)
8879 return read_prepared_logmsg(logmsg, a->prepared_log);
8881 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8882 return got_error_from_errno("asprintf");
8884 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8885 if (err)
8886 goto done;
8888 if (a->prepared_log) {
8889 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8890 if (err)
8891 goto done;
8892 } else if (a->merged_log) {
8893 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8894 if (err)
8895 goto done;
8898 initial_content_len = asprintf(&initial_content,
8899 "%s%s\n# changes to be committed on branch %s:\n",
8900 prepared_msg ? prepared_msg : "",
8901 merged_msg ? merged_msg : "", a->branch_name);
8902 if (initial_content_len == -1) {
8903 err = got_error_from_errno("asprintf");
8904 goto done;
8907 if (write(fd, initial_content, initial_content_len) == -1) {
8908 err = got_error_from_errno2("write", a->logmsg_path);
8909 goto done;
8912 TAILQ_FOREACH(pe, commitable_paths, entry) {
8913 struct got_commitable *ct = pe->data;
8914 dprintf(fd, "# %c %s\n",
8915 got_commitable_get_status(ct),
8916 got_commitable_get_path(ct));
8919 if (diff_path) {
8920 dprintf(fd, "# detailed changes can be viewed in %s\n",
8921 diff_path);
8924 if (close(fd) == -1) {
8925 err = got_error_from_errno2("close", a->logmsg_path);
8926 goto done;
8928 fd = -1;
8930 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8931 initial_content_len, a->prepared_log ? 0 : 1);
8932 done:
8933 free(initial_content);
8934 free(template);
8935 free(prepared_msg);
8936 free(merged_msg);
8938 if (fd != -1 && close(fd) == -1 && err == NULL)
8939 err = got_error_from_errno2("close", a->logmsg_path);
8941 /* Editor is done; we can now apply unveil(2) */
8942 if (err == NULL)
8943 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8944 if (err) {
8945 free(*logmsg);
8946 *logmsg = NULL;
8948 return err;
8951 static const struct got_error *
8952 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8953 const char *type, int has_content)
8955 const struct got_error *err = NULL;
8956 char *logmsg = NULL;
8958 err = got_object_commit_get_logmsg(&logmsg, commit);
8959 if (err)
8960 return err;
8962 if (fprintf(f, "%s# log message of %s commit %s:%s",
8963 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8964 err = got_ferror(f, GOT_ERR_IO);
8966 free(logmsg);
8967 return err;
8971 * Lookup "logmsg" references of backed-out and cherrypicked commits
8972 * belonging to the current work tree. If found, and the worktree has
8973 * at least one modified file that was changed in the referenced commit,
8974 * add its log message to a new temporary file at *logmsg_path.
8975 * Add all refs found to matched_refs to be scheduled for removal on
8976 * successful commit.
8978 static const struct got_error *
8979 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8980 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8981 struct got_repository *repo)
8983 const struct got_error *err;
8984 struct got_commit_object *commit = NULL;
8985 struct got_object_id *id = NULL;
8986 struct got_reflist_head refs;
8987 struct got_reflist_entry *re, *re_match;
8988 FILE *f = NULL;
8989 char *uuidstr = NULL;
8990 int added_logmsg = 0;
8992 TAILQ_INIT(&refs);
8994 *logmsg_path = NULL;
8996 err = got_worktree_get_uuid(&uuidstr, worktree);
8997 if (err)
8998 goto done;
9000 err = got_ref_list(&refs, repo, "refs/got/worktree",
9001 got_ref_cmp_by_name, repo);
9002 if (err)
9003 goto done;
9005 TAILQ_FOREACH(re, &refs, entry) {
9006 const char *refname, *type;
9007 struct wt_commitable_path_arg wcpa;
9008 int add_logmsg = 0;
9010 refname = got_ref_get_name(re->ref);
9012 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9013 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9014 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9015 type = "cherrypicked";
9016 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9017 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9018 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9019 type = "backed-out";
9020 } else
9021 continue;
9023 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9024 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9025 else
9026 continue;
9028 err = got_repo_match_object_id(&id, NULL, refname,
9029 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9030 if (err)
9031 goto done;
9033 err = got_object_open_as_commit(&commit, repo, id);
9034 if (err)
9035 goto done;
9037 wcpa.commit_paths = paths;
9038 wcpa.has_changes = &add_logmsg;
9040 err = commit_path_changed_in_worktree(&wcpa, id,
9041 worktree, repo);
9042 if (err)
9043 goto done;
9045 if (add_logmsg) {
9046 if (f == NULL) {
9047 err = got_opentemp_named(logmsg_path, &f,
9048 "got-commit-logmsg", "");
9049 if (err)
9050 goto done;
9052 err = cat_logmsg(f, commit, refname, type,
9053 added_logmsg);
9054 if (err)
9055 goto done;
9056 if (!added_logmsg)
9057 ++added_logmsg;
9059 err = got_reflist_entry_dup(&re_match, re);
9060 if (err)
9061 goto done;
9062 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9065 got_object_commit_close(commit);
9066 commit = NULL;
9067 free(id);
9068 id = NULL;
9071 done:
9072 free(id);
9073 free(uuidstr);
9074 got_ref_list_free(&refs);
9075 if (commit)
9076 got_object_commit_close(commit);
9077 if (f && fclose(f) == EOF && err == NULL)
9078 err = got_error_from_errno("fclose");
9079 if (!added_logmsg) {
9080 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9081 err = got_error_from_errno2("unlink", *logmsg_path);
9082 *logmsg_path = NULL;
9084 return err;
9087 static const struct got_error *
9088 cmd_commit(int argc, char *argv[])
9090 const struct got_error *error = NULL;
9091 struct got_worktree *worktree = NULL;
9092 struct got_repository *repo = NULL;
9093 char *cwd = NULL, *id_str = NULL;
9094 struct got_object_id *id = NULL;
9095 const char *logmsg = NULL;
9096 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9097 struct collect_commit_logmsg_arg cl_arg;
9098 const char *author = NULL;
9099 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9100 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9101 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9102 int show_diff = 1, commit_conflicts = 0;
9103 struct got_pathlist_head paths;
9104 struct got_reflist_head refs;
9105 struct got_reflist_entry *re;
9106 int *pack_fds = NULL;
9108 TAILQ_INIT(&refs);
9109 TAILQ_INIT(&paths);
9110 cl_arg.logmsg_path = NULL;
9112 #ifndef PROFILE
9113 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9114 "unveil", NULL) == -1)
9115 err(1, "pledge");
9116 #endif
9118 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9119 switch (ch) {
9120 case 'A':
9121 author = optarg;
9122 error = valid_author(author);
9123 if (error)
9124 return error;
9125 break;
9126 case 'C':
9127 commit_conflicts = 1;
9128 break;
9129 case 'F':
9130 if (logmsg != NULL)
9131 option_conflict('F', 'm');
9132 prepared_logmsg = realpath(optarg, NULL);
9133 if (prepared_logmsg == NULL)
9134 return got_error_from_errno2("realpath",
9135 optarg);
9136 break;
9137 case 'm':
9138 if (prepared_logmsg)
9139 option_conflict('m', 'F');
9140 logmsg = optarg;
9141 break;
9142 case 'N':
9143 non_interactive = 1;
9144 break;
9145 case 'n':
9146 show_diff = 0;
9147 break;
9148 case 'S':
9149 allow_bad_symlinks = 1;
9150 break;
9151 default:
9152 usage_commit();
9153 /* NOTREACHED */
9157 argc -= optind;
9158 argv += optind;
9160 cwd = getcwd(NULL, 0);
9161 if (cwd == NULL) {
9162 error = got_error_from_errno("getcwd");
9163 goto done;
9166 error = got_repo_pack_fds_open(&pack_fds);
9167 if (error != NULL)
9168 goto done;
9170 error = got_worktree_open(&worktree, cwd);
9171 if (error) {
9172 if (error->code == GOT_ERR_NOT_WORKTREE)
9173 error = wrap_not_worktree_error(error, "commit", cwd);
9174 goto done;
9177 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9178 if (error)
9179 goto done;
9180 if (rebase_in_progress) {
9181 error = got_error(GOT_ERR_REBASING);
9182 goto done;
9185 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9186 worktree);
9187 if (error)
9188 goto done;
9190 error = get_gitconfig_path(&gitconfig_path);
9191 if (error)
9192 goto done;
9193 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9194 gitconfig_path, pack_fds);
9195 if (error != NULL)
9196 goto done;
9198 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9199 if (error)
9200 goto done;
9201 if (merge_in_progress) {
9202 error = got_error(GOT_ERR_MERGE_BUSY);
9203 goto done;
9206 error = get_author(&committer, repo, worktree);
9207 if (error)
9208 goto done;
9210 if (author == NULL)
9211 author = committer;
9214 * unveil(2) traverses exec(2); if an editor is used we have
9215 * to apply unveil after the log message has been written.
9217 if (logmsg == NULL || strlen(logmsg) == 0)
9218 error = get_editor(&editor);
9219 else
9220 error = apply_unveil(got_repo_get_path(repo), 0,
9221 got_worktree_get_root_path(worktree));
9222 if (error)
9223 goto done;
9225 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9226 if (error)
9227 goto done;
9229 if (prepared_logmsg == NULL) {
9230 error = lookup_logmsg_ref(&merged_logmsg,
9231 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9232 if (error)
9233 goto done;
9236 cl_arg.editor = editor;
9237 cl_arg.cmdline_log = logmsg;
9238 cl_arg.prepared_log = prepared_logmsg;
9239 cl_arg.merged_log = merged_logmsg;
9240 cl_arg.non_interactive = non_interactive;
9241 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9242 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9243 if (!histedit_in_progress) {
9244 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9245 error = got_error(GOT_ERR_COMMIT_BRANCH);
9246 goto done;
9248 cl_arg.branch_name += 11;
9250 cl_arg.repo_path = got_repo_get_path(repo);
9251 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9252 allow_bad_symlinks, show_diff, commit_conflicts,
9253 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9254 if (error) {
9255 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9256 cl_arg.logmsg_path != NULL)
9257 preserve_logmsg = 1;
9258 goto done;
9261 error = got_object_id_str(&id_str, id);
9262 if (error)
9263 goto done;
9264 printf("Created commit %s\n", id_str);
9266 TAILQ_FOREACH(re, &refs, entry) {
9267 error = got_ref_delete(re->ref, repo);
9268 if (error)
9269 goto done;
9272 done:
9273 if (preserve_logmsg) {
9274 fprintf(stderr, "%s: log message preserved in %s\n",
9275 getprogname(), cl_arg.logmsg_path);
9276 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9277 error == NULL)
9278 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9279 free(cl_arg.logmsg_path);
9280 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9281 error = got_error_from_errno2("unlink", merged_logmsg);
9282 free(merged_logmsg);
9283 if (repo) {
9284 const struct got_error *close_err = got_repo_close(repo);
9285 if (error == NULL)
9286 error = close_err;
9288 if (worktree)
9289 got_worktree_close(worktree);
9290 if (pack_fds) {
9291 const struct got_error *pack_err =
9292 got_repo_pack_fds_close(pack_fds);
9293 if (error == NULL)
9294 error = pack_err;
9296 got_ref_list_free(&refs);
9297 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9298 free(cwd);
9299 free(id_str);
9300 free(gitconfig_path);
9301 free(editor);
9302 free(committer);
9303 free(prepared_logmsg);
9304 return error;
9307 __dead static void
9308 usage_send(void)
9310 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9311 "[-r repository-path] [-t tag] [remote-repository]\n",
9312 getprogname());
9313 exit(1);
9316 static void
9317 print_load_info(int print_colored, int print_found, int print_trees,
9318 int ncolored, int nfound, int ntrees)
9320 if (print_colored) {
9321 printf("%d commit%s colored", ncolored,
9322 ncolored == 1 ? "" : "s");
9324 if (print_found) {
9325 printf("%s%d object%s found",
9326 ncolored > 0 ? "; " : "",
9327 nfound, nfound == 1 ? "" : "s");
9329 if (print_trees) {
9330 printf("; %d tree%s scanned", ntrees,
9331 ntrees == 1 ? "" : "s");
9335 struct got_send_progress_arg {
9336 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9337 int verbosity;
9338 int last_ncolored;
9339 int last_nfound;
9340 int last_ntrees;
9341 int loading_done;
9342 int last_ncommits;
9343 int last_nobj_total;
9344 int last_p_deltify;
9345 int last_p_written;
9346 int last_p_sent;
9347 int printed_something;
9348 int sent_something;
9349 struct got_pathlist_head *delete_branches;
9352 static const struct got_error *
9353 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9354 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9355 int nobj_written, off_t bytes_sent, const char *refname,
9356 const char *errmsg, int success)
9358 struct got_send_progress_arg *a = arg;
9359 char scaled_packsize[FMT_SCALED_STRSIZE];
9360 char scaled_sent[FMT_SCALED_STRSIZE];
9361 int p_deltify = 0, p_written = 0, p_sent = 0;
9362 int print_colored = 0, print_found = 0, print_trees = 0;
9363 int print_searching = 0, print_total = 0;
9364 int print_deltify = 0, print_written = 0, print_sent = 0;
9366 if (a->verbosity < 0)
9367 return NULL;
9369 if (refname) {
9370 const char *status = success ? "accepted" : "rejected";
9372 if (success) {
9373 struct got_pathlist_entry *pe;
9374 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9375 const char *branchname = pe->path;
9376 if (got_path_cmp(branchname, refname,
9377 strlen(branchname), strlen(refname)) == 0) {
9378 status = "deleted";
9379 a->sent_something = 1;
9380 break;
9385 if (a->printed_something)
9386 putchar('\n');
9387 printf("Server has %s %s", status, refname);
9388 if (errmsg)
9389 printf(": %s", errmsg);
9390 a->printed_something = 1;
9391 return NULL;
9394 if (a->last_ncolored != ncolored) {
9395 print_colored = 1;
9396 a->last_ncolored = ncolored;
9399 if (a->last_nfound != nfound) {
9400 print_colored = 1;
9401 print_found = 1;
9402 a->last_nfound = nfound;
9405 if (a->last_ntrees != ntrees) {
9406 print_colored = 1;
9407 print_found = 1;
9408 print_trees = 1;
9409 a->last_ntrees = ntrees;
9412 if ((print_colored || print_found || print_trees) &&
9413 !a->loading_done) {
9414 printf("\r");
9415 print_load_info(print_colored, print_found, print_trees,
9416 ncolored, nfound, ntrees);
9417 a->printed_something = 1;
9418 fflush(stdout);
9419 return NULL;
9420 } else if (!a->loading_done) {
9421 printf("\r");
9422 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9423 printf("\n");
9424 a->loading_done = 1;
9427 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9428 return got_error_from_errno("fmt_scaled");
9429 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9430 return got_error_from_errno("fmt_scaled");
9432 if (a->last_ncommits != ncommits) {
9433 print_searching = 1;
9434 a->last_ncommits = ncommits;
9437 if (a->last_nobj_total != nobj_total) {
9438 print_searching = 1;
9439 print_total = 1;
9440 a->last_nobj_total = nobj_total;
9443 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9444 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9445 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9446 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9447 return got_error(GOT_ERR_NO_SPACE);
9450 if (nobj_deltify > 0 || nobj_written > 0) {
9451 if (nobj_deltify > 0) {
9452 p_deltify = (nobj_deltify * 100) / nobj_total;
9453 if (p_deltify != a->last_p_deltify) {
9454 a->last_p_deltify = p_deltify;
9455 print_searching = 1;
9456 print_total = 1;
9457 print_deltify = 1;
9460 if (nobj_written > 0) {
9461 p_written = (nobj_written * 100) / nobj_total;
9462 if (p_written != a->last_p_written) {
9463 a->last_p_written = p_written;
9464 print_searching = 1;
9465 print_total = 1;
9466 print_deltify = 1;
9467 print_written = 1;
9472 if (bytes_sent > 0) {
9473 p_sent = (bytes_sent * 100) / packfile_size;
9474 if (p_sent != a->last_p_sent) {
9475 a->last_p_sent = p_sent;
9476 print_searching = 1;
9477 print_total = 1;
9478 print_deltify = 1;
9479 print_written = 1;
9480 print_sent = 1;
9482 a->sent_something = 1;
9485 if (print_searching || print_total || print_deltify || print_written ||
9486 print_sent)
9487 printf("\r");
9488 if (print_searching)
9489 printf("packing %d reference%s", ncommits,
9490 ncommits == 1 ? "" : "s");
9491 if (print_total)
9492 printf("; %d object%s", nobj_total,
9493 nobj_total == 1 ? "" : "s");
9494 if (print_deltify)
9495 printf("; deltify: %d%%", p_deltify);
9496 if (print_sent)
9497 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9498 scaled_packsize, p_sent);
9499 else if (print_written)
9500 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9501 scaled_packsize, p_written);
9502 if (print_searching || print_total || print_deltify ||
9503 print_written || print_sent) {
9504 a->printed_something = 1;
9505 fflush(stdout);
9507 return NULL;
9510 static const struct got_error *
9511 cmd_send(int argc, char *argv[])
9513 const struct got_error *error = NULL;
9514 char *cwd = NULL, *repo_path = NULL;
9515 const char *remote_name;
9516 char *proto = NULL, *host = NULL, *port = NULL;
9517 char *repo_name = NULL, *server_path = NULL;
9518 const struct got_remote_repo *remotes, *remote = NULL;
9519 int nremotes, nbranches = 0, ndelete_branches = 0;
9520 struct got_repository *repo = NULL;
9521 struct got_worktree *worktree = NULL;
9522 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9523 struct got_pathlist_head branches;
9524 struct got_pathlist_head tags;
9525 struct got_reflist_head all_branches;
9526 struct got_reflist_head all_tags;
9527 struct got_pathlist_head delete_args;
9528 struct got_pathlist_head delete_branches;
9529 struct got_reflist_entry *re;
9530 struct got_pathlist_entry *pe;
9531 int i, ch, sendfd = -1, sendstatus;
9532 pid_t sendpid = -1;
9533 struct got_send_progress_arg spa;
9534 int verbosity = 0, overwrite_refs = 0;
9535 int send_all_branches = 0, send_all_tags = 0;
9536 struct got_reference *ref = NULL;
9537 int *pack_fds = NULL;
9539 TAILQ_INIT(&branches);
9540 TAILQ_INIT(&tags);
9541 TAILQ_INIT(&all_branches);
9542 TAILQ_INIT(&all_tags);
9543 TAILQ_INIT(&delete_args);
9544 TAILQ_INIT(&delete_branches);
9546 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9547 switch (ch) {
9548 case 'a':
9549 send_all_branches = 1;
9550 break;
9551 case 'b':
9552 error = got_pathlist_append(&branches, optarg, NULL);
9553 if (error)
9554 return error;
9555 nbranches++;
9556 break;
9557 case 'd':
9558 error = got_pathlist_append(&delete_args, optarg, NULL);
9559 if (error)
9560 return error;
9561 break;
9562 case 'f':
9563 overwrite_refs = 1;
9564 break;
9565 case 'q':
9566 verbosity = -1;
9567 break;
9568 case 'r':
9569 repo_path = realpath(optarg, NULL);
9570 if (repo_path == NULL)
9571 return got_error_from_errno2("realpath",
9572 optarg);
9573 got_path_strip_trailing_slashes(repo_path);
9574 break;
9575 case 'T':
9576 send_all_tags = 1;
9577 break;
9578 case 't':
9579 error = got_pathlist_append(&tags, optarg, NULL);
9580 if (error)
9581 return error;
9582 break;
9583 case 'v':
9584 if (verbosity < 0)
9585 verbosity = 0;
9586 else if (verbosity < 3)
9587 verbosity++;
9588 break;
9589 default:
9590 usage_send();
9591 /* NOTREACHED */
9594 argc -= optind;
9595 argv += optind;
9597 if (send_all_branches && !TAILQ_EMPTY(&branches))
9598 option_conflict('a', 'b');
9599 if (send_all_tags && !TAILQ_EMPTY(&tags))
9600 option_conflict('T', 't');
9603 if (argc == 0)
9604 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9605 else if (argc == 1)
9606 remote_name = argv[0];
9607 else
9608 usage_send();
9610 cwd = getcwd(NULL, 0);
9611 if (cwd == NULL) {
9612 error = got_error_from_errno("getcwd");
9613 goto done;
9616 error = got_repo_pack_fds_open(&pack_fds);
9617 if (error != NULL)
9618 goto done;
9620 if (repo_path == NULL) {
9621 error = got_worktree_open(&worktree, cwd);
9622 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9623 goto done;
9624 else
9625 error = NULL;
9626 if (worktree) {
9627 repo_path =
9628 strdup(got_worktree_get_repo_path(worktree));
9629 if (repo_path == NULL)
9630 error = got_error_from_errno("strdup");
9631 if (error)
9632 goto done;
9633 } else {
9634 repo_path = strdup(cwd);
9635 if (repo_path == NULL) {
9636 error = got_error_from_errno("strdup");
9637 goto done;
9642 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9643 if (error)
9644 goto done;
9646 if (worktree) {
9647 worktree_conf = got_worktree_get_gotconfig(worktree);
9648 if (worktree_conf) {
9649 got_gotconfig_get_remotes(&nremotes, &remotes,
9650 worktree_conf);
9651 for (i = 0; i < nremotes; i++) {
9652 if (strcmp(remotes[i].name, remote_name) == 0) {
9653 remote = &remotes[i];
9654 break;
9659 if (remote == NULL) {
9660 repo_conf = got_repo_get_gotconfig(repo);
9661 if (repo_conf) {
9662 got_gotconfig_get_remotes(&nremotes, &remotes,
9663 repo_conf);
9664 for (i = 0; i < nremotes; i++) {
9665 if (strcmp(remotes[i].name, remote_name) == 0) {
9666 remote = &remotes[i];
9667 break;
9672 if (remote == NULL) {
9673 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9674 for (i = 0; i < nremotes; i++) {
9675 if (strcmp(remotes[i].name, remote_name) == 0) {
9676 remote = &remotes[i];
9677 break;
9681 if (remote == NULL) {
9682 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9683 goto done;
9686 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9687 &repo_name, remote->send_url);
9688 if (error)
9689 goto done;
9691 if (strcmp(proto, "git") == 0) {
9692 #ifndef PROFILE
9693 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9694 "sendfd dns inet unveil", NULL) == -1)
9695 err(1, "pledge");
9696 #endif
9697 } else if (strcmp(proto, "git+ssh") == 0 ||
9698 strcmp(proto, "ssh") == 0) {
9699 #ifndef PROFILE
9700 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9701 "sendfd unveil", NULL) == -1)
9702 err(1, "pledge");
9703 #endif
9704 } else if (strcmp(proto, "http") == 0 ||
9705 strcmp(proto, "git+http") == 0) {
9706 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9707 goto done;
9708 } else {
9709 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9710 goto done;
9713 error = got_dial_apply_unveil(proto);
9714 if (error)
9715 goto done;
9717 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9718 if (error)
9719 goto done;
9721 if (send_all_branches) {
9722 error = got_ref_list(&all_branches, repo, "refs/heads",
9723 got_ref_cmp_by_name, NULL);
9724 if (error)
9725 goto done;
9726 TAILQ_FOREACH(re, &all_branches, entry) {
9727 const char *branchname = got_ref_get_name(re->ref);
9728 error = got_pathlist_append(&branches,
9729 branchname, NULL);
9730 if (error)
9731 goto done;
9732 nbranches++;
9734 } else if (nbranches == 0) {
9735 for (i = 0; i < remote->nsend_branches; i++) {
9736 error = got_pathlist_append(&branches,
9737 remote->send_branches[i], NULL);
9738 if (error)
9739 goto done;
9743 if (send_all_tags) {
9744 error = got_ref_list(&all_tags, repo, "refs/tags",
9745 got_ref_cmp_by_name, NULL);
9746 if (error)
9747 goto done;
9748 TAILQ_FOREACH(re, &all_tags, entry) {
9749 const char *tagname = got_ref_get_name(re->ref);
9750 error = got_pathlist_append(&tags,
9751 tagname, NULL);
9752 if (error)
9753 goto done;
9758 * To prevent accidents only branches in refs/heads/ can be deleted
9759 * with 'got send -d'.
9760 * Deleting anything else requires local repository access or Git.
9762 TAILQ_FOREACH(pe, &delete_args, entry) {
9763 const char *branchname = pe->path;
9764 char *s;
9765 struct got_pathlist_entry *new;
9766 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9767 s = strdup(branchname);
9768 if (s == NULL) {
9769 error = got_error_from_errno("strdup");
9770 goto done;
9772 } else {
9773 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9774 error = got_error_from_errno("asprintf");
9775 goto done;
9778 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9779 if (error || new == NULL /* duplicate */)
9780 free(s);
9781 if (error)
9782 goto done;
9783 ndelete_branches++;
9786 if (nbranches == 0 && ndelete_branches == 0) {
9787 struct got_reference *head_ref;
9788 if (worktree)
9789 error = got_ref_open(&head_ref, repo,
9790 got_worktree_get_head_ref_name(worktree), 0);
9791 else
9792 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9793 if (error)
9794 goto done;
9795 if (got_ref_is_symbolic(head_ref)) {
9796 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9797 got_ref_close(head_ref);
9798 if (error)
9799 goto done;
9800 } else
9801 ref = head_ref;
9802 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9803 NULL);
9804 if (error)
9805 goto done;
9806 nbranches++;
9809 if (verbosity >= 0) {
9810 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9811 remote->name, proto, host,
9812 port ? ":" : "", port ? port : "",
9813 *server_path == '/' ? "" : "/", server_path);
9816 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9817 server_path, verbosity);
9818 if (error)
9819 goto done;
9821 memset(&spa, 0, sizeof(spa));
9822 spa.last_scaled_packsize[0] = '\0';
9823 spa.last_p_deltify = -1;
9824 spa.last_p_written = -1;
9825 spa.verbosity = verbosity;
9826 spa.delete_branches = &delete_branches;
9827 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9828 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9829 check_cancelled, NULL);
9830 if (spa.printed_something)
9831 putchar('\n');
9832 if (error)
9833 goto done;
9834 if (!spa.sent_something && verbosity >= 0)
9835 printf("Already up-to-date\n");
9836 done:
9837 if (sendpid > 0) {
9838 if (kill(sendpid, SIGTERM) == -1)
9839 error = got_error_from_errno("kill");
9840 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9841 error = got_error_from_errno("waitpid");
9843 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9844 error = got_error_from_errno("close");
9845 if (repo) {
9846 const struct got_error *close_err = got_repo_close(repo);
9847 if (error == NULL)
9848 error = close_err;
9850 if (worktree)
9851 got_worktree_close(worktree);
9852 if (pack_fds) {
9853 const struct got_error *pack_err =
9854 got_repo_pack_fds_close(pack_fds);
9855 if (error == NULL)
9856 error = pack_err;
9858 if (ref)
9859 got_ref_close(ref);
9860 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9861 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9862 got_ref_list_free(&all_branches);
9863 got_ref_list_free(&all_tags);
9864 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9865 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9866 free(cwd);
9867 free(repo_path);
9868 free(proto);
9869 free(host);
9870 free(port);
9871 free(server_path);
9872 free(repo_name);
9873 return error;
9877 * Print and if delete is set delete all ref_prefix references.
9878 * If wanted_ref is not NULL, only print or delete this reference.
9880 static const struct got_error *
9881 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9882 const char *wanted_ref, int delete, struct got_worktree *worktree,
9883 struct got_repository *repo)
9885 const struct got_error *err;
9886 struct got_pathlist_head paths;
9887 struct got_reflist_head refs;
9888 struct got_reflist_entry *re;
9889 struct got_reflist_object_id_map *refs_idmap = NULL;
9890 struct got_commit_object *commit = NULL;
9891 struct got_object_id *id = NULL;
9892 const char *header_prefix;
9893 char *uuidstr = NULL;
9894 int found = 0;
9896 TAILQ_INIT(&refs);
9897 TAILQ_INIT(&paths);
9899 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9900 if (err)
9901 goto done;
9903 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9904 if (err)
9905 goto done;
9907 if (worktree != NULL) {
9908 err = got_worktree_get_uuid(&uuidstr, worktree);
9909 if (err)
9910 goto done;
9913 if (wanted_ref) {
9914 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9915 wanted_ref += 11;
9918 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9919 header_prefix = "backout";
9920 else
9921 header_prefix = "cherrypick";
9923 TAILQ_FOREACH(re, &refs, entry) {
9924 const char *refname, *wt;
9926 refname = got_ref_get_name(re->ref);
9928 err = check_cancelled(NULL);
9929 if (err)
9930 goto done;
9932 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9933 refname += prefix_len + 1; /* skip '-' delimiter */
9934 else
9935 continue;
9937 wt = refname;
9939 if (worktree == NULL || strncmp(refname, uuidstr,
9940 GOT_WORKTREE_UUID_STRLEN) == 0)
9941 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9942 else
9943 continue;
9945 err = got_repo_match_object_id(&id, NULL, refname,
9946 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9947 if (err)
9948 goto done;
9950 err = got_object_open_as_commit(&commit, repo, id);
9951 if (err)
9952 goto done;
9954 if (wanted_ref)
9955 found = strncmp(wanted_ref, refname,
9956 strlen(wanted_ref)) == 0;
9957 if (wanted_ref && !found) {
9958 struct got_reflist_head *ci_refs;
9960 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9961 id);
9963 if (ci_refs) {
9964 char *refs_str = NULL;
9965 char const *r = NULL;
9967 err = build_refs_str(&refs_str, ci_refs, id,
9968 repo, 1);
9969 if (err)
9970 goto done;
9972 r = refs_str;
9973 while (r) {
9974 if (strncmp(r, wanted_ref,
9975 strlen(wanted_ref)) == 0) {
9976 found = 1;
9977 break;
9979 r = strchr(r, ' ');
9980 if (r)
9981 ++r;
9983 free(refs_str);
9987 if (wanted_ref == NULL || found) {
9988 if (delete) {
9989 err = got_ref_delete(re->ref, repo);
9990 if (err)
9991 goto done;
9992 printf("Deleted: ");
9993 err = print_commit_oneline(commit, id, repo,
9994 refs_idmap);
9995 } else {
9997 * Print paths modified by commit to help
9998 * associate commits with worktree changes.
10000 err = get_changed_paths(&paths, commit,
10001 repo, NULL);
10002 if (err)
10003 goto done;
10005 err = print_commit(commit, id, repo, NULL,
10006 &paths, NULL, 0, 0, refs_idmap, NULL,
10007 header_prefix);
10008 got_pathlist_free(&paths,
10009 GOT_PATHLIST_FREE_ALL);
10011 if (worktree == NULL)
10012 printf("work tree: %.*s\n\n",
10013 GOT_WORKTREE_UUID_STRLEN, wt);
10015 if (err || found)
10016 goto done;
10019 got_object_commit_close(commit);
10020 commit = NULL;
10021 free(id);
10022 id = NULL;
10025 if (wanted_ref != NULL && !found)
10026 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10028 done:
10029 free(id);
10030 free(uuidstr);
10031 got_ref_list_free(&refs);
10032 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10033 if (refs_idmap)
10034 got_reflist_object_id_map_free(refs_idmap);
10035 if (commit)
10036 got_object_commit_close(commit);
10037 return err;
10041 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10042 * identified by id for log messages to prepopulate the editor on commit.
10044 static const struct got_error *
10045 logmsg_ref(struct got_object_id *id, const char *prefix,
10046 struct got_worktree *worktree, struct got_repository *repo)
10048 const struct got_error *err = NULL;
10049 char *idstr, *ref = NULL, *refname = NULL;
10050 int histedit_in_progress;
10051 int rebase_in_progress, merge_in_progress;
10054 * Silenty refuse to create merge reference if any histedit, merge,
10055 * or rebase operation is in progress.
10057 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10058 worktree);
10059 if (err)
10060 return err;
10061 if (histedit_in_progress)
10062 return NULL;
10064 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10065 if (err)
10066 return err;
10067 if (rebase_in_progress)
10068 return NULL;
10070 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10071 repo);
10072 if (err)
10073 return err;
10074 if (merge_in_progress)
10075 return NULL;
10077 err = got_object_id_str(&idstr, id);
10078 if (err)
10079 return err;
10081 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10082 if (err)
10083 goto done;
10085 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10086 err = got_error_from_errno("asprintf");
10087 goto done;
10090 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10091 -1, repo);
10092 done:
10093 free(ref);
10094 free(idstr);
10095 free(refname);
10096 return err;
10099 __dead static void
10100 usage_cherrypick(void)
10102 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10103 getprogname());
10104 exit(1);
10107 static const struct got_error *
10108 cmd_cherrypick(int argc, char *argv[])
10110 const struct got_error *error = NULL;
10111 struct got_worktree *worktree = NULL;
10112 struct got_repository *repo = NULL;
10113 char *cwd = NULL, *commit_id_str = NULL;
10114 struct got_object_id *commit_id = NULL;
10115 struct got_commit_object *commit = NULL;
10116 struct got_object_qid *pid;
10117 int ch, list_refs = 0, remove_refs = 0;
10118 struct got_update_progress_arg upa;
10119 int *pack_fds = NULL;
10121 #ifndef PROFILE
10122 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10123 "unveil", NULL) == -1)
10124 err(1, "pledge");
10125 #endif
10127 while ((ch = getopt(argc, argv, "lX")) != -1) {
10128 switch (ch) {
10129 case 'l':
10130 list_refs = 1;
10131 break;
10132 case 'X':
10133 remove_refs = 1;
10134 break;
10135 default:
10136 usage_cherrypick();
10137 /* NOTREACHED */
10141 argc -= optind;
10142 argv += optind;
10144 if (list_refs || remove_refs) {
10145 if (argc != 0 && argc != 1)
10146 usage_cherrypick();
10147 } else if (argc != 1)
10148 usage_cherrypick();
10149 if (list_refs && remove_refs)
10150 option_conflict('l', 'X');
10152 cwd = getcwd(NULL, 0);
10153 if (cwd == NULL) {
10154 error = got_error_from_errno("getcwd");
10155 goto done;
10158 error = got_repo_pack_fds_open(&pack_fds);
10159 if (error != NULL)
10160 goto done;
10162 error = got_worktree_open(&worktree, cwd);
10163 if (error) {
10164 if (list_refs || remove_refs) {
10165 if (error->code != GOT_ERR_NOT_WORKTREE)
10166 goto done;
10167 } else {
10168 if (error->code == GOT_ERR_NOT_WORKTREE)
10169 error = wrap_not_worktree_error(error,
10170 "cherrypick", cwd);
10171 goto done;
10175 error = got_repo_open(&repo,
10176 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10177 NULL, pack_fds);
10178 if (error != NULL)
10179 goto done;
10181 error = apply_unveil(got_repo_get_path(repo), 0,
10182 worktree ? got_worktree_get_root_path(worktree) : NULL);
10183 if (error)
10184 goto done;
10186 if (list_refs || remove_refs) {
10187 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10188 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10189 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10190 goto done;
10193 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10194 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10195 if (error)
10196 goto done;
10197 error = got_object_id_str(&commit_id_str, commit_id);
10198 if (error)
10199 goto done;
10201 error = got_object_open_as_commit(&commit, repo, commit_id);
10202 if (error)
10203 goto done;
10204 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10205 memset(&upa, 0, sizeof(upa));
10206 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10207 commit_id, repo, update_progress, &upa, check_cancelled,
10208 NULL);
10209 if (error != NULL)
10210 goto done;
10212 if (upa.did_something) {
10213 error = logmsg_ref(commit_id,
10214 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10215 if (error)
10216 goto done;
10217 printf("Merged commit %s\n", commit_id_str);
10219 print_merge_progress_stats(&upa);
10220 done:
10221 free(cwd);
10222 if (commit)
10223 got_object_commit_close(commit);
10224 free(commit_id_str);
10225 if (worktree)
10226 got_worktree_close(worktree);
10227 if (repo) {
10228 const struct got_error *close_err = got_repo_close(repo);
10229 if (error == NULL)
10230 error = close_err;
10232 if (pack_fds) {
10233 const struct got_error *pack_err =
10234 got_repo_pack_fds_close(pack_fds);
10235 if (error == NULL)
10236 error = pack_err;
10239 return error;
10242 __dead static void
10243 usage_backout(void)
10245 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10246 exit(1);
10249 static const struct got_error *
10250 cmd_backout(int argc, char *argv[])
10252 const struct got_error *error = NULL;
10253 struct got_worktree *worktree = NULL;
10254 struct got_repository *repo = NULL;
10255 char *cwd = NULL, *commit_id_str = NULL;
10256 struct got_object_id *commit_id = NULL;
10257 struct got_commit_object *commit = NULL;
10258 struct got_object_qid *pid;
10259 int ch, list_refs = 0, remove_refs = 0;
10260 struct got_update_progress_arg upa;
10261 int *pack_fds = NULL;
10263 #ifndef PROFILE
10264 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10265 "unveil", NULL) == -1)
10266 err(1, "pledge");
10267 #endif
10269 while ((ch = getopt(argc, argv, "lX")) != -1) {
10270 switch (ch) {
10271 case 'l':
10272 list_refs = 1;
10273 break;
10274 case 'X':
10275 remove_refs = 1;
10276 break;
10277 default:
10278 usage_backout();
10279 /* NOTREACHED */
10283 argc -= optind;
10284 argv += optind;
10286 if (list_refs || remove_refs) {
10287 if (argc != 0 && argc != 1)
10288 usage_backout();
10289 } else if (argc != 1)
10290 usage_backout();
10291 if (list_refs && remove_refs)
10292 option_conflict('l', 'X');
10294 cwd = getcwd(NULL, 0);
10295 if (cwd == NULL) {
10296 error = got_error_from_errno("getcwd");
10297 goto done;
10300 error = got_repo_pack_fds_open(&pack_fds);
10301 if (error != NULL)
10302 goto done;
10304 error = got_worktree_open(&worktree, cwd);
10305 if (error) {
10306 if (list_refs || remove_refs) {
10307 if (error->code != GOT_ERR_NOT_WORKTREE)
10308 goto done;
10309 } else {
10310 if (error->code == GOT_ERR_NOT_WORKTREE)
10311 error = wrap_not_worktree_error(error,
10312 "backout", cwd);
10313 goto done;
10317 error = got_repo_open(&repo,
10318 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10319 NULL, pack_fds);
10320 if (error != NULL)
10321 goto done;
10323 error = apply_unveil(got_repo_get_path(repo), 0,
10324 worktree ? got_worktree_get_root_path(worktree) : NULL);
10325 if (error)
10326 goto done;
10328 if (list_refs || remove_refs) {
10329 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10330 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10331 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10332 goto done;
10335 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10336 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10337 if (error)
10338 goto done;
10339 error = got_object_id_str(&commit_id_str, commit_id);
10340 if (error)
10341 goto done;
10343 error = got_object_open_as_commit(&commit, repo, commit_id);
10344 if (error)
10345 goto done;
10346 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10347 if (pid == NULL) {
10348 error = got_error(GOT_ERR_ROOT_COMMIT);
10349 goto done;
10352 memset(&upa, 0, sizeof(upa));
10353 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10354 repo, update_progress, &upa, check_cancelled, NULL);
10355 if (error != NULL)
10356 goto done;
10358 if (upa.did_something) {
10359 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10360 worktree, repo);
10361 if (error)
10362 goto done;
10363 printf("Backed out commit %s\n", commit_id_str);
10365 print_merge_progress_stats(&upa);
10366 done:
10367 free(cwd);
10368 if (commit)
10369 got_object_commit_close(commit);
10370 free(commit_id_str);
10371 if (worktree)
10372 got_worktree_close(worktree);
10373 if (repo) {
10374 const struct got_error *close_err = got_repo_close(repo);
10375 if (error == NULL)
10376 error = close_err;
10378 if (pack_fds) {
10379 const struct got_error *pack_err =
10380 got_repo_pack_fds_close(pack_fds);
10381 if (error == NULL)
10382 error = pack_err;
10384 return error;
10387 __dead static void
10388 usage_rebase(void)
10390 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10391 exit(1);
10394 static void
10395 trim_logmsg(char *logmsg, int limit)
10397 char *nl;
10398 size_t len;
10400 len = strlen(logmsg);
10401 if (len > limit)
10402 len = limit;
10403 logmsg[len] = '\0';
10404 nl = strchr(logmsg, '\n');
10405 if (nl)
10406 *nl = '\0';
10409 static const struct got_error *
10410 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10412 const struct got_error *err;
10413 char *logmsg0 = NULL;
10414 const char *s;
10416 err = got_object_commit_get_logmsg(&logmsg0, commit);
10417 if (err)
10418 return err;
10420 s = logmsg0;
10421 while (isspace((unsigned char)s[0]))
10422 s++;
10424 *logmsg = strdup(s);
10425 if (*logmsg == NULL) {
10426 err = got_error_from_errno("strdup");
10427 goto done;
10430 trim_logmsg(*logmsg, limit);
10431 done:
10432 free(logmsg0);
10433 return err;
10436 static const struct got_error *
10437 show_rebase_merge_conflict(struct got_object_id *id,
10438 struct got_repository *repo)
10440 const struct got_error *err;
10441 struct got_commit_object *commit = NULL;
10442 char *id_str = NULL, *logmsg = NULL;
10444 err = got_object_open_as_commit(&commit, repo, id);
10445 if (err)
10446 return err;
10448 err = got_object_id_str(&id_str, id);
10449 if (err)
10450 goto done;
10452 id_str[12] = '\0';
10454 err = get_short_logmsg(&logmsg, 42, commit);
10455 if (err)
10456 goto done;
10458 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10459 done:
10460 free(id_str);
10461 got_object_commit_close(commit);
10462 free(logmsg);
10463 return err;
10466 static const struct got_error *
10467 show_rebase_progress(struct got_commit_object *commit,
10468 struct got_object_id *old_id, struct got_object_id *new_id)
10470 const struct got_error *err;
10471 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10473 err = got_object_id_str(&old_id_str, old_id);
10474 if (err)
10475 goto done;
10477 if (new_id) {
10478 err = got_object_id_str(&new_id_str, new_id);
10479 if (err)
10480 goto done;
10483 old_id_str[12] = '\0';
10484 if (new_id_str)
10485 new_id_str[12] = '\0';
10487 err = get_short_logmsg(&logmsg, 42, commit);
10488 if (err)
10489 goto done;
10491 printf("%s -> %s: %s\n", old_id_str,
10492 new_id_str ? new_id_str : "no-op change", logmsg);
10493 done:
10494 free(old_id_str);
10495 free(new_id_str);
10496 free(logmsg);
10497 return err;
10500 static const struct got_error *
10501 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10502 struct got_reference *branch, struct got_reference *tmp_branch,
10503 struct got_repository *repo, int create_backup)
10505 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10506 return got_worktree_rebase_complete(worktree, fileindex,
10507 tmp_branch, branch, repo, create_backup);
10510 static const struct got_error *
10511 rebase_commit(struct got_pathlist_head *merged_paths,
10512 struct got_worktree *worktree, struct got_fileindex *fileindex,
10513 struct got_reference *tmp_branch, const char *committer,
10514 struct got_object_id *commit_id, int allow_conflict,
10515 struct got_repository *repo)
10517 const struct got_error *error;
10518 struct got_commit_object *commit;
10519 struct got_object_id *new_commit_id;
10521 error = got_object_open_as_commit(&commit, repo, commit_id);
10522 if (error)
10523 return error;
10525 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10526 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10527 allow_conflict, repo);
10528 if (error) {
10529 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10530 goto done;
10531 error = show_rebase_progress(commit, commit_id, NULL);
10532 } else {
10533 error = show_rebase_progress(commit, commit_id, new_commit_id);
10534 free(new_commit_id);
10536 done:
10537 got_object_commit_close(commit);
10538 return error;
10541 struct check_path_prefix_arg {
10542 const char *path_prefix;
10543 size_t len;
10544 int errcode;
10547 static const struct got_error *
10548 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10549 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10550 struct got_object_id *id1, struct got_object_id *id2,
10551 const char *path1, const char *path2,
10552 mode_t mode1, mode_t mode2, struct got_repository *repo)
10554 struct check_path_prefix_arg *a = arg;
10556 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10557 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10558 return got_error(a->errcode);
10560 return NULL;
10563 static const struct got_error *
10564 check_path_prefix(struct got_object_id *parent_id,
10565 struct got_object_id *commit_id, const char *path_prefix,
10566 int errcode, struct got_repository *repo)
10568 const struct got_error *err;
10569 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10570 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10571 struct check_path_prefix_arg cpp_arg;
10573 if (got_path_is_root_dir(path_prefix))
10574 return NULL;
10576 err = got_object_open_as_commit(&commit, repo, commit_id);
10577 if (err)
10578 goto done;
10580 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10581 if (err)
10582 goto done;
10584 err = got_object_open_as_tree(&tree1, repo,
10585 got_object_commit_get_tree_id(parent_commit));
10586 if (err)
10587 goto done;
10589 err = got_object_open_as_tree(&tree2, repo,
10590 got_object_commit_get_tree_id(commit));
10591 if (err)
10592 goto done;
10594 cpp_arg.path_prefix = path_prefix;
10595 while (cpp_arg.path_prefix[0] == '/')
10596 cpp_arg.path_prefix++;
10597 cpp_arg.len = strlen(cpp_arg.path_prefix);
10598 cpp_arg.errcode = errcode;
10599 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10600 check_path_prefix_in_diff, &cpp_arg, 0);
10601 done:
10602 if (tree1)
10603 got_object_tree_close(tree1);
10604 if (tree2)
10605 got_object_tree_close(tree2);
10606 if (commit)
10607 got_object_commit_close(commit);
10608 if (parent_commit)
10609 got_object_commit_close(parent_commit);
10610 return err;
10613 static const struct got_error *
10614 collect_commits(struct got_object_id_queue *commits,
10615 struct got_object_id *initial_commit_id,
10616 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10617 const char *path_prefix, int path_prefix_errcode,
10618 struct got_repository *repo)
10620 const struct got_error *err = NULL;
10621 struct got_commit_graph *graph = NULL;
10622 struct got_object_id parent_id, commit_id;
10623 struct got_object_qid *qid;
10625 err = got_commit_graph_open(&graph, "/", 1);
10626 if (err)
10627 return err;
10629 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10630 check_cancelled, NULL);
10631 if (err)
10632 goto done;
10634 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10635 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10636 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10637 check_cancelled, NULL);
10638 if (err) {
10639 if (err->code == GOT_ERR_ITER_COMPLETED) {
10640 err = got_error_msg(GOT_ERR_ANCESTRY,
10641 "ran out of commits to rebase before "
10642 "youngest common ancestor commit has "
10643 "been reached?!?");
10645 goto done;
10646 } else {
10647 err = check_path_prefix(&parent_id, &commit_id,
10648 path_prefix, path_prefix_errcode, repo);
10649 if (err)
10650 goto done;
10652 err = got_object_qid_alloc(&qid, &commit_id);
10653 if (err)
10654 goto done;
10655 STAILQ_INSERT_HEAD(commits, qid, entry);
10657 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10660 done:
10661 got_commit_graph_close(graph);
10662 return err;
10665 static const struct got_error *
10666 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10668 const struct got_error *err = NULL;
10669 time_t committer_time;
10670 struct tm tm;
10671 char datebuf[11]; /* YYYY-MM-DD + NUL */
10672 char *author0 = NULL, *author, *smallerthan;
10673 char *logmsg0 = NULL, *logmsg, *newline;
10675 committer_time = got_object_commit_get_committer_time(commit);
10676 if (gmtime_r(&committer_time, &tm) == NULL)
10677 return got_error_from_errno("gmtime_r");
10678 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10679 return got_error(GOT_ERR_NO_SPACE);
10681 author0 = strdup(got_object_commit_get_author(commit));
10682 if (author0 == NULL)
10683 return got_error_from_errno("strdup");
10684 author = author0;
10685 smallerthan = strchr(author, '<');
10686 if (smallerthan && smallerthan[1] != '\0')
10687 author = smallerthan + 1;
10688 author[strcspn(author, "@>")] = '\0';
10690 err = got_object_commit_get_logmsg(&logmsg0, commit);
10691 if (err)
10692 goto done;
10693 logmsg = logmsg0;
10694 while (*logmsg == '\n')
10695 logmsg++;
10696 newline = strchr(logmsg, '\n');
10697 if (newline)
10698 *newline = '\0';
10700 if (asprintf(brief_str, "%s %s %s",
10701 datebuf, author, logmsg) == -1)
10702 err = got_error_from_errno("asprintf");
10703 done:
10704 free(author0);
10705 free(logmsg0);
10706 return err;
10709 static const struct got_error *
10710 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10711 struct got_repository *repo)
10713 const struct got_error *err;
10714 char *id_str;
10716 err = got_object_id_str(&id_str, id);
10717 if (err)
10718 return err;
10720 err = got_ref_delete(ref, repo);
10721 if (err)
10722 goto done;
10724 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10725 done:
10726 free(id_str);
10727 return err;
10730 static const struct got_error *
10731 print_backup_ref(const char *branch_name, const char *new_id_str,
10732 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10733 struct got_reflist_object_id_map *refs_idmap,
10734 struct got_repository *repo)
10736 const struct got_error *err = NULL;
10737 struct got_reflist_head *refs;
10738 char *refs_str = NULL;
10739 struct got_object_id *new_commit_id = NULL;
10740 struct got_commit_object *new_commit = NULL;
10741 char *new_commit_brief_str = NULL;
10742 struct got_object_id *yca_id = NULL;
10743 struct got_commit_object *yca_commit = NULL;
10744 char *yca_id_str = NULL, *yca_brief_str = NULL;
10745 char *custom_refs_str;
10747 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10748 return got_error_from_errno("asprintf");
10750 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10751 0, 0, refs_idmap, custom_refs_str, NULL);
10752 if (err)
10753 goto done;
10755 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10756 if (err)
10757 goto done;
10759 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10760 if (refs) {
10761 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10762 if (err)
10763 goto done;
10766 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10767 if (err)
10768 goto done;
10770 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10771 if (err)
10772 goto done;
10774 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10775 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10776 if (err)
10777 goto done;
10779 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10780 refs_str ? " (" : "", refs_str ? refs_str : "",
10781 refs_str ? ")" : "", new_commit_brief_str);
10782 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10783 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10784 free(refs_str);
10785 refs_str = NULL;
10787 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10788 if (err)
10789 goto done;
10791 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10792 if (err)
10793 goto done;
10795 err = got_object_id_str(&yca_id_str, yca_id);
10796 if (err)
10797 goto done;
10799 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10800 if (refs) {
10801 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10802 if (err)
10803 goto done;
10805 printf("history forked at %s%s%s%s\n %s\n",
10806 yca_id_str,
10807 refs_str ? " (" : "", refs_str ? refs_str : "",
10808 refs_str ? ")" : "", yca_brief_str);
10810 done:
10811 free(custom_refs_str);
10812 free(new_commit_id);
10813 free(refs_str);
10814 free(yca_id);
10815 free(yca_id_str);
10816 free(yca_brief_str);
10817 if (new_commit)
10818 got_object_commit_close(new_commit);
10819 if (yca_commit)
10820 got_object_commit_close(yca_commit);
10822 return err;
10825 static const struct got_error *
10826 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10827 struct got_repository *repo)
10829 const struct got_error *err;
10830 struct got_reflist_head refs;
10831 struct got_reflist_entry *re;
10832 char *uuidstr = NULL;
10833 static char msg[160];
10835 TAILQ_INIT(&refs);
10837 err = got_worktree_get_uuid(&uuidstr, worktree);
10838 if (err)
10839 goto done;
10841 err = got_ref_list(&refs, repo, "refs/got/worktree",
10842 got_ref_cmp_by_name, repo);
10843 if (err)
10844 goto done;
10846 TAILQ_FOREACH(re, &refs, entry) {
10847 const char *cmd, *refname, *type;
10849 refname = got_ref_get_name(re->ref);
10851 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10852 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10853 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10854 cmd = "cherrypick";
10855 type = "cherrypicked";
10856 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10857 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10858 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10859 cmd = "backout";
10860 type = "backed-out";
10861 } else
10862 continue;
10864 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10865 continue;
10867 snprintf(msg, sizeof(msg),
10868 "work tree has references created by %s commits which "
10869 "must be removed with 'got %s -X' before running the %s "
10870 "command", type, cmd, caller);
10871 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10872 goto done;
10875 done:
10876 free(uuidstr);
10877 got_ref_list_free(&refs);
10878 return err;
10881 static const struct got_error *
10882 process_backup_refs(const char *backup_ref_prefix,
10883 const char *wanted_branch_name,
10884 int delete, struct got_repository *repo)
10886 const struct got_error *err;
10887 struct got_reflist_head refs, backup_refs;
10888 struct got_reflist_entry *re;
10889 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10890 struct got_object_id *old_commit_id = NULL;
10891 char *branch_name = NULL;
10892 struct got_commit_object *old_commit = NULL;
10893 struct got_reflist_object_id_map *refs_idmap = NULL;
10894 int wanted_branch_found = 0;
10896 TAILQ_INIT(&refs);
10897 TAILQ_INIT(&backup_refs);
10899 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10900 if (err)
10901 return err;
10903 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10904 if (err)
10905 goto done;
10907 if (wanted_branch_name) {
10908 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10909 wanted_branch_name += 11;
10912 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10913 got_ref_cmp_by_commit_timestamp_descending, repo);
10914 if (err)
10915 goto done;
10917 TAILQ_FOREACH(re, &backup_refs, entry) {
10918 const char *refname = got_ref_get_name(re->ref);
10919 char *slash;
10921 err = check_cancelled(NULL);
10922 if (err)
10923 break;
10925 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10926 if (err)
10927 break;
10929 err = got_object_open_as_commit(&old_commit, repo,
10930 old_commit_id);
10931 if (err)
10932 break;
10934 if (strncmp(backup_ref_prefix, refname,
10935 backup_ref_prefix_len) == 0)
10936 refname += backup_ref_prefix_len;
10938 while (refname[0] == '/')
10939 refname++;
10941 branch_name = strdup(refname);
10942 if (branch_name == NULL) {
10943 err = got_error_from_errno("strdup");
10944 break;
10946 slash = strrchr(branch_name, '/');
10947 if (slash) {
10948 *slash = '\0';
10949 refname += strlen(branch_name) + 1;
10952 if (wanted_branch_name == NULL ||
10953 strcmp(wanted_branch_name, branch_name) == 0) {
10954 wanted_branch_found = 1;
10955 if (delete) {
10956 err = delete_backup_ref(re->ref,
10957 old_commit_id, repo);
10958 } else {
10959 err = print_backup_ref(branch_name, refname,
10960 old_commit_id, old_commit, refs_idmap,
10961 repo);
10963 if (err)
10964 break;
10967 free(old_commit_id);
10968 old_commit_id = NULL;
10969 free(branch_name);
10970 branch_name = NULL;
10971 got_object_commit_close(old_commit);
10972 old_commit = NULL;
10975 if (wanted_branch_name && !wanted_branch_found) {
10976 err = got_error_fmt(GOT_ERR_NOT_REF,
10977 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10979 done:
10980 if (refs_idmap)
10981 got_reflist_object_id_map_free(refs_idmap);
10982 got_ref_list_free(&refs);
10983 got_ref_list_free(&backup_refs);
10984 free(old_commit_id);
10985 free(branch_name);
10986 if (old_commit)
10987 got_object_commit_close(old_commit);
10988 return err;
10991 static const struct got_error *
10992 abort_progress(void *arg, unsigned char status, const char *path)
10995 * Unversioned files should not clutter progress output when
10996 * an operation is aborted.
10998 if (status == GOT_STATUS_UNVERSIONED)
10999 return NULL;
11001 return update_progress(arg, status, path);
11004 static const struct got_error *
11005 cmd_rebase(int argc, char *argv[])
11007 const struct got_error *error = NULL;
11008 struct got_worktree *worktree = NULL;
11009 struct got_repository *repo = NULL;
11010 struct got_fileindex *fileindex = NULL;
11011 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11012 struct got_reference *branch = NULL;
11013 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11014 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11015 struct got_object_id *resume_commit_id = NULL;
11016 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11017 struct got_object_id *head_commit_id = NULL;
11018 struct got_reference *head_ref = NULL;
11019 struct got_commit_object *commit = NULL;
11020 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11021 int histedit_in_progress = 0, merge_in_progress = 0;
11022 int create_backup = 1, list_backups = 0, delete_backups = 0;
11023 int allow_conflict = 0;
11024 struct got_object_id_queue commits;
11025 struct got_pathlist_head merged_paths;
11026 const struct got_object_id_queue *parent_ids;
11027 struct got_object_qid *qid, *pid;
11028 struct got_update_progress_arg upa;
11029 int *pack_fds = NULL;
11031 STAILQ_INIT(&commits);
11032 TAILQ_INIT(&merged_paths);
11033 memset(&upa, 0, sizeof(upa));
11035 #ifndef PROFILE
11036 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11037 "unveil", NULL) == -1)
11038 err(1, "pledge");
11039 #endif
11041 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11042 switch (ch) {
11043 case 'a':
11044 abort_rebase = 1;
11045 break;
11046 case 'C':
11047 allow_conflict = 1;
11048 break;
11049 case 'c':
11050 continue_rebase = 1;
11051 break;
11052 case 'l':
11053 list_backups = 1;
11054 break;
11055 case 'X':
11056 delete_backups = 1;
11057 break;
11058 default:
11059 usage_rebase();
11060 /* NOTREACHED */
11064 argc -= optind;
11065 argv += optind;
11067 if (list_backups) {
11068 if (abort_rebase)
11069 option_conflict('l', 'a');
11070 if (allow_conflict)
11071 option_conflict('l', 'C');
11072 if (continue_rebase)
11073 option_conflict('l', 'c');
11074 if (delete_backups)
11075 option_conflict('l', 'X');
11076 if (argc != 0 && argc != 1)
11077 usage_rebase();
11078 } else if (delete_backups) {
11079 if (abort_rebase)
11080 option_conflict('X', 'a');
11081 if (allow_conflict)
11082 option_conflict('X', 'C');
11083 if (continue_rebase)
11084 option_conflict('X', 'c');
11085 if (list_backups)
11086 option_conflict('l', 'X');
11087 if (argc != 0 && argc != 1)
11088 usage_rebase();
11089 } else if (allow_conflict) {
11090 if (abort_rebase)
11091 option_conflict('C', 'a');
11092 if (!continue_rebase)
11093 errx(1, "-C option requires -c");
11094 } else {
11095 if (abort_rebase && continue_rebase)
11096 usage_rebase();
11097 else if (abort_rebase || continue_rebase) {
11098 if (argc != 0)
11099 usage_rebase();
11100 } else if (argc != 1)
11101 usage_rebase();
11104 cwd = getcwd(NULL, 0);
11105 if (cwd == NULL) {
11106 error = got_error_from_errno("getcwd");
11107 goto done;
11110 error = got_repo_pack_fds_open(&pack_fds);
11111 if (error != NULL)
11112 goto done;
11114 error = got_worktree_open(&worktree, cwd);
11115 if (error) {
11116 if (list_backups || delete_backups) {
11117 if (error->code != GOT_ERR_NOT_WORKTREE)
11118 goto done;
11119 } else {
11120 if (error->code == GOT_ERR_NOT_WORKTREE)
11121 error = wrap_not_worktree_error(error,
11122 "rebase", cwd);
11123 goto done;
11127 error = get_gitconfig_path(&gitconfig_path);
11128 if (error)
11129 goto done;
11130 error = got_repo_open(&repo,
11131 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11132 gitconfig_path, pack_fds);
11133 if (error != NULL)
11134 goto done;
11136 if (worktree != NULL && !list_backups && !delete_backups) {
11137 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11138 if (error)
11139 goto done;
11142 error = get_author(&committer, repo, worktree);
11143 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11144 goto done;
11146 error = apply_unveil(got_repo_get_path(repo), 0,
11147 worktree ? got_worktree_get_root_path(worktree) : NULL);
11148 if (error)
11149 goto done;
11151 if (list_backups || delete_backups) {
11152 error = process_backup_refs(
11153 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11154 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11155 goto done; /* nothing else to do */
11158 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11159 worktree);
11160 if (error)
11161 goto done;
11162 if (histedit_in_progress) {
11163 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11164 goto done;
11167 error = got_worktree_merge_in_progress(&merge_in_progress,
11168 worktree, repo);
11169 if (error)
11170 goto done;
11171 if (merge_in_progress) {
11172 error = got_error(GOT_ERR_MERGE_BUSY);
11173 goto done;
11176 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11177 if (error)
11178 goto done;
11180 if (abort_rebase) {
11181 if (!rebase_in_progress) {
11182 error = got_error(GOT_ERR_NOT_REBASING);
11183 goto done;
11185 error = got_worktree_rebase_continue(&resume_commit_id,
11186 &new_base_branch, &tmp_branch, &branch, &fileindex,
11187 worktree, repo);
11188 if (error)
11189 goto done;
11190 printf("Switching work tree to %s\n",
11191 got_ref_get_symref_target(new_base_branch));
11192 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11193 new_base_branch, abort_progress, &upa);
11194 if (error)
11195 goto done;
11196 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11197 print_merge_progress_stats(&upa);
11198 goto done; /* nothing else to do */
11201 if (continue_rebase) {
11202 if (!rebase_in_progress) {
11203 error = got_error(GOT_ERR_NOT_REBASING);
11204 goto done;
11206 error = got_worktree_rebase_continue(&resume_commit_id,
11207 &new_base_branch, &tmp_branch, &branch, &fileindex,
11208 worktree, repo);
11209 if (error)
11210 goto done;
11212 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11213 committer, resume_commit_id, allow_conflict, repo);
11214 if (error)
11215 goto done;
11217 yca_id = got_object_id_dup(resume_commit_id);
11218 if (yca_id == NULL) {
11219 error = got_error_from_errno("got_object_id_dup");
11220 goto done;
11222 } else {
11223 error = got_ref_open(&branch, repo, argv[0], 0);
11224 if (error != NULL)
11225 goto done;
11226 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11227 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11228 "will not rebase a branch which lives outside "
11229 "the \"refs/heads/\" reference namespace");
11230 goto done;
11234 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11235 if (error)
11236 goto done;
11238 if (!continue_rebase) {
11239 struct got_object_id *base_commit_id;
11241 error = got_ref_open(&head_ref, repo,
11242 got_worktree_get_head_ref_name(worktree), 0);
11243 if (error)
11244 goto done;
11245 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11246 if (error)
11247 goto done;
11248 base_commit_id = got_worktree_get_base_commit_id(worktree);
11249 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11250 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11251 goto done;
11254 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11255 base_commit_id, branch_head_commit_id, 1, repo,
11256 check_cancelled, NULL);
11257 if (error) {
11258 if (error->code == GOT_ERR_ANCESTRY) {
11259 error = got_error_msg(GOT_ERR_ANCESTRY,
11260 "specified branch shares no common "
11261 "ancestry with work tree's branch");
11263 goto done;
11266 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11267 if (error) {
11268 if (error->code != GOT_ERR_ANCESTRY)
11269 goto done;
11270 error = NULL;
11271 } else {
11272 struct got_pathlist_head paths;
11273 printf("%s is already based on %s\n",
11274 got_ref_get_name(branch),
11275 got_worktree_get_head_ref_name(worktree));
11276 error = switch_head_ref(branch, branch_head_commit_id,
11277 worktree, repo);
11278 if (error)
11279 goto done;
11280 error = got_worktree_set_base_commit_id(worktree, repo,
11281 branch_head_commit_id);
11282 if (error)
11283 goto done;
11284 TAILQ_INIT(&paths);
11285 error = got_pathlist_append(&paths, "", NULL);
11286 if (error)
11287 goto done;
11288 error = got_worktree_checkout_files(worktree,
11289 &paths, repo, update_progress, &upa,
11290 check_cancelled, NULL);
11291 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11292 if (error)
11293 goto done;
11294 if (upa.did_something) {
11295 char *id_str;
11296 error = got_object_id_str(&id_str,
11297 branch_head_commit_id);
11298 if (error)
11299 goto done;
11300 printf("Updated to %s: %s\n",
11301 got_worktree_get_head_ref_name(worktree),
11302 id_str);
11303 free(id_str);
11304 } else
11305 printf("Already up-to-date\n");
11306 print_update_progress_stats(&upa);
11307 goto done;
11311 commit_id = branch_head_commit_id;
11312 error = got_object_open_as_commit(&commit, repo, commit_id);
11313 if (error)
11314 goto done;
11316 parent_ids = got_object_commit_get_parent_ids(commit);
11317 pid = STAILQ_FIRST(parent_ids);
11318 if (pid) {
11319 error = collect_commits(&commits, commit_id, &pid->id,
11320 yca_id, got_worktree_get_path_prefix(worktree),
11321 GOT_ERR_REBASE_PATH, repo);
11322 if (error)
11323 goto done;
11326 got_object_commit_close(commit);
11327 commit = NULL;
11329 if (!continue_rebase) {
11330 error = got_worktree_rebase_prepare(&new_base_branch,
11331 &tmp_branch, &fileindex, worktree, branch, repo);
11332 if (error)
11333 goto done;
11336 if (STAILQ_EMPTY(&commits)) {
11337 if (continue_rebase) {
11338 error = rebase_complete(worktree, fileindex,
11339 branch, tmp_branch, repo, create_backup);
11340 goto done;
11341 } else {
11342 /* Fast-forward the reference of the branch. */
11343 struct got_object_id *new_head_commit_id;
11344 char *id_str;
11345 error = got_ref_resolve(&new_head_commit_id, repo,
11346 new_base_branch);
11347 if (error)
11348 goto done;
11349 error = got_object_id_str(&id_str, new_head_commit_id);
11350 if (error)
11351 goto done;
11352 printf("Forwarding %s to commit %s\n",
11353 got_ref_get_name(branch), id_str);
11354 free(id_str);
11355 error = got_ref_change_ref(branch,
11356 new_head_commit_id);
11357 if (error)
11358 goto done;
11359 /* No backup needed since objects did not change. */
11360 create_backup = 0;
11364 pid = NULL;
11365 STAILQ_FOREACH(qid, &commits, entry) {
11367 commit_id = &qid->id;
11368 parent_id = pid ? &pid->id : yca_id;
11369 pid = qid;
11371 memset(&upa, 0, sizeof(upa));
11372 error = got_worktree_rebase_merge_files(&merged_paths,
11373 worktree, fileindex, parent_id, commit_id, repo,
11374 update_progress, &upa, check_cancelled, NULL);
11375 if (error)
11376 goto done;
11378 print_merge_progress_stats(&upa);
11379 if (upa.conflicts > 0 || upa.missing > 0 ||
11380 upa.not_deleted > 0 || upa.unversioned > 0) {
11381 if (upa.conflicts > 0) {
11382 error = show_rebase_merge_conflict(&qid->id,
11383 repo);
11384 if (error)
11385 goto done;
11387 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11388 break;
11391 error = rebase_commit(&merged_paths, worktree, fileindex,
11392 tmp_branch, committer, commit_id, 0, repo);
11393 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11394 if (error)
11395 goto done;
11398 if (upa.conflicts > 0 || upa.missing > 0 ||
11399 upa.not_deleted > 0 || upa.unversioned > 0) {
11400 error = got_worktree_rebase_postpone(worktree, fileindex);
11401 if (error)
11402 goto done;
11403 if (upa.conflicts > 0 && upa.missing == 0 &&
11404 upa.not_deleted == 0 && upa.unversioned == 0) {
11405 error = got_error_msg(GOT_ERR_CONFLICTS,
11406 "conflicts must be resolved before rebasing "
11407 "can continue");
11408 } else if (upa.conflicts > 0) {
11409 error = got_error_msg(GOT_ERR_CONFLICTS,
11410 "conflicts must be resolved before rebasing "
11411 "can continue; changes destined for some "
11412 "files were not yet merged and should be "
11413 "merged manually if required before the "
11414 "rebase operation is continued");
11415 } else {
11416 error = got_error_msg(GOT_ERR_CONFLICTS,
11417 "changes destined for some files were not "
11418 "yet merged and should be merged manually "
11419 "if required before the rebase operation "
11420 "is continued");
11422 } else
11423 error = rebase_complete(worktree, fileindex, branch,
11424 tmp_branch, repo, create_backup);
11425 done:
11426 free(cwd);
11427 free(committer);
11428 free(gitconfig_path);
11429 got_object_id_queue_free(&commits);
11430 free(branch_head_commit_id);
11431 free(resume_commit_id);
11432 free(head_commit_id);
11433 free(yca_id);
11434 if (commit)
11435 got_object_commit_close(commit);
11436 if (branch)
11437 got_ref_close(branch);
11438 if (new_base_branch)
11439 got_ref_close(new_base_branch);
11440 if (tmp_branch)
11441 got_ref_close(tmp_branch);
11442 if (head_ref)
11443 got_ref_close(head_ref);
11444 if (worktree)
11445 got_worktree_close(worktree);
11446 if (repo) {
11447 const struct got_error *close_err = got_repo_close(repo);
11448 if (error == NULL)
11449 error = close_err;
11451 if (pack_fds) {
11452 const struct got_error *pack_err =
11453 got_repo_pack_fds_close(pack_fds);
11454 if (error == NULL)
11455 error = pack_err;
11457 return error;
11460 __dead static void
11461 usage_histedit(void)
11463 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11464 "[branch]\n", getprogname());
11465 exit(1);
11468 #define GOT_HISTEDIT_PICK 'p'
11469 #define GOT_HISTEDIT_EDIT 'e'
11470 #define GOT_HISTEDIT_FOLD 'f'
11471 #define GOT_HISTEDIT_DROP 'd'
11472 #define GOT_HISTEDIT_MESG 'm'
11474 static const struct got_histedit_cmd {
11475 unsigned char code;
11476 const char *name;
11477 const char *desc;
11478 } got_histedit_cmds[] = {
11479 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11480 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11481 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11482 "be used" },
11483 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11484 { GOT_HISTEDIT_MESG, "mesg",
11485 "single-line log message for commit above (open editor if empty)" },
11488 struct got_histedit_list_entry {
11489 TAILQ_ENTRY(got_histedit_list_entry) entry;
11490 struct got_object_id *commit_id;
11491 const struct got_histedit_cmd *cmd;
11492 char *logmsg;
11494 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11496 static const struct got_error *
11497 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11498 FILE *f, struct got_repository *repo)
11500 const struct got_error *err = NULL;
11501 char *logmsg = NULL, *id_str = NULL;
11502 struct got_commit_object *commit = NULL;
11503 int n;
11505 err = got_object_open_as_commit(&commit, repo, commit_id);
11506 if (err)
11507 goto done;
11509 err = get_short_logmsg(&logmsg, 34, commit);
11510 if (err)
11511 goto done;
11513 err = got_object_id_str(&id_str, commit_id);
11514 if (err)
11515 goto done;
11517 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11518 if (n < 0)
11519 err = got_ferror(f, GOT_ERR_IO);
11520 done:
11521 if (commit)
11522 got_object_commit_close(commit);
11523 free(id_str);
11524 free(logmsg);
11525 return err;
11528 static const struct got_error *
11529 histedit_write_commit_list(struct got_object_id_queue *commits,
11530 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11531 int edit_only, struct got_repository *repo)
11533 const struct got_error *err = NULL;
11534 struct got_object_qid *qid;
11535 const char *histedit_cmd = NULL;
11537 if (STAILQ_EMPTY(commits))
11538 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11540 STAILQ_FOREACH(qid, commits, entry) {
11541 histedit_cmd = got_histedit_cmds[0].name;
11542 if (drop_only)
11543 histedit_cmd = "drop";
11544 else if (edit_only)
11545 histedit_cmd = "edit";
11546 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11547 histedit_cmd = "fold";
11548 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11549 if (err)
11550 break;
11551 if (edit_logmsg_only) {
11552 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11553 if (n < 0) {
11554 err = got_ferror(f, GOT_ERR_IO);
11555 break;
11560 return err;
11563 static const struct got_error *
11564 write_cmd_list(FILE *f, const char *branch_name,
11565 struct got_object_id_queue *commits)
11567 const struct got_error *err = NULL;
11568 size_t i;
11569 int n;
11570 char *id_str;
11571 struct got_object_qid *qid;
11573 qid = STAILQ_FIRST(commits);
11574 err = got_object_id_str(&id_str, &qid->id);
11575 if (err)
11576 return err;
11578 n = fprintf(f,
11579 "# Editing the history of branch '%s' starting at\n"
11580 "# commit %s\n"
11581 "# Commits will be processed in order from top to "
11582 "bottom of this file.\n", branch_name, id_str);
11583 if (n < 0) {
11584 err = got_ferror(f, GOT_ERR_IO);
11585 goto done;
11588 n = fprintf(f, "# Available histedit commands:\n");
11589 if (n < 0) {
11590 err = got_ferror(f, GOT_ERR_IO);
11591 goto done;
11594 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11595 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11596 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11597 cmd->desc);
11598 if (n < 0) {
11599 err = got_ferror(f, GOT_ERR_IO);
11600 break;
11603 done:
11604 free(id_str);
11605 return err;
11608 static const struct got_error *
11609 histedit_syntax_error(int lineno)
11611 static char msg[42];
11612 int ret;
11614 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11615 lineno);
11616 if (ret < 0 || (size_t)ret >= sizeof(msg))
11617 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11619 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11622 static const struct got_error *
11623 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11624 char *logmsg, struct got_repository *repo)
11626 const struct got_error *err;
11627 struct got_commit_object *folded_commit = NULL;
11628 char *id_str, *folded_logmsg = NULL;
11630 err = got_object_id_str(&id_str, hle->commit_id);
11631 if (err)
11632 return err;
11634 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11635 if (err)
11636 goto done;
11638 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11639 if (err)
11640 goto done;
11641 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11642 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11643 folded_logmsg) == -1) {
11644 err = got_error_from_errno("asprintf");
11646 done:
11647 if (folded_commit)
11648 got_object_commit_close(folded_commit);
11649 free(id_str);
11650 free(folded_logmsg);
11651 return err;
11654 static struct got_histedit_list_entry *
11655 get_folded_commits(struct got_histedit_list_entry *hle)
11657 struct got_histedit_list_entry *prev, *folded = NULL;
11659 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11660 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11661 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11662 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11663 folded = prev;
11664 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11667 return folded;
11670 static const struct got_error *
11671 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11672 struct got_repository *repo)
11674 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11675 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11676 const struct got_error *err = NULL;
11677 struct got_commit_object *commit = NULL;
11678 int logmsg_len;
11679 int fd = -1;
11680 struct got_histedit_list_entry *folded = NULL;
11682 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11683 if (err)
11684 return err;
11686 folded = get_folded_commits(hle);
11687 if (folded) {
11688 while (folded != hle) {
11689 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11690 folded = TAILQ_NEXT(folded, entry);
11691 continue;
11693 err = append_folded_commit_msg(&new_msg, folded,
11694 logmsg, repo);
11695 if (err)
11696 goto done;
11697 free(logmsg);
11698 logmsg = new_msg;
11699 folded = TAILQ_NEXT(folded, entry);
11703 err = got_object_id_str(&id_str, hle->commit_id);
11704 if (err)
11705 goto done;
11706 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11707 if (err)
11708 goto done;
11709 logmsg_len = asprintf(&new_msg,
11710 "%s\n# original log message of commit %s: %s",
11711 logmsg ? logmsg : "", id_str, orig_logmsg);
11712 if (logmsg_len == -1) {
11713 err = got_error_from_errno("asprintf");
11714 goto done;
11716 free(logmsg);
11717 logmsg = new_msg;
11719 err = got_object_id_str(&id_str, hle->commit_id);
11720 if (err)
11721 goto done;
11723 err = got_opentemp_named_fd(&logmsg_path, &fd,
11724 GOT_TMPDIR_STR "/got-logmsg", "");
11725 if (err)
11726 goto done;
11728 if (write(fd, logmsg, logmsg_len) == -1) {
11729 err = got_error_from_errno2("write", logmsg_path);
11730 goto done;
11732 if (close(fd) == -1) {
11733 err = got_error_from_errno2("close", logmsg_path);
11734 goto done;
11736 fd = -1;
11738 err = get_editor(&editor);
11739 if (err)
11740 goto done;
11742 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11743 logmsg_len, 0);
11744 if (err) {
11745 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11746 goto done;
11747 err = NULL;
11748 hle->logmsg = strdup(new_msg);
11749 if (hle->logmsg == NULL)
11750 err = got_error_from_errno("strdup");
11752 done:
11753 if (fd != -1 && close(fd) == -1 && err == NULL)
11754 err = got_error_from_errno2("close", logmsg_path);
11755 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11756 err = got_error_from_errno2("unlink", logmsg_path);
11757 free(logmsg_path);
11758 free(logmsg);
11759 free(orig_logmsg);
11760 free(editor);
11761 if (commit)
11762 got_object_commit_close(commit);
11763 return err;
11766 static const struct got_error *
11767 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11768 FILE *f, struct got_repository *repo)
11770 const struct got_error *err = NULL;
11771 char *line = NULL, *p, *end;
11772 size_t i, linesize = 0;
11773 ssize_t linelen;
11774 int lineno = 0, lastcmd = -1;
11775 const struct got_histedit_cmd *cmd;
11776 struct got_object_id *commit_id = NULL;
11777 struct got_histedit_list_entry *hle = NULL;
11779 for (;;) {
11780 linelen = getline(&line, &linesize, f);
11781 if (linelen == -1) {
11782 const struct got_error *getline_err;
11783 if (feof(f))
11784 break;
11785 getline_err = got_error_from_errno("getline");
11786 err = got_ferror(f, getline_err->code);
11787 break;
11789 lineno++;
11790 p = line;
11791 while (isspace((unsigned char)p[0]))
11792 p++;
11793 if (p[0] == '#' || p[0] == '\0')
11794 continue;
11795 cmd = NULL;
11796 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11797 cmd = &got_histedit_cmds[i];
11798 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11799 isspace((unsigned char)p[strlen(cmd->name)])) {
11800 p += strlen(cmd->name);
11801 break;
11803 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11804 p++;
11805 break;
11808 if (i == nitems(got_histedit_cmds)) {
11809 err = histedit_syntax_error(lineno);
11810 break;
11812 while (isspace((unsigned char)p[0]))
11813 p++;
11814 if (cmd->code == GOT_HISTEDIT_MESG) {
11815 if (lastcmd != GOT_HISTEDIT_PICK &&
11816 lastcmd != GOT_HISTEDIT_EDIT) {
11817 err = got_error(GOT_ERR_HISTEDIT_CMD);
11818 break;
11820 if (p[0] == '\0') {
11821 err = histedit_edit_logmsg(hle, repo);
11822 if (err)
11823 break;
11824 } else {
11825 hle->logmsg = strdup(p);
11826 if (hle->logmsg == NULL) {
11827 err = got_error_from_errno("strdup");
11828 break;
11831 lastcmd = cmd->code;
11832 continue;
11833 } else {
11834 end = p;
11835 while (end[0] && !isspace((unsigned char)end[0]))
11836 end++;
11837 *end = '\0';
11839 err = got_object_resolve_id_str(&commit_id, repo, p);
11840 if (err) {
11841 /* override error code */
11842 err = histedit_syntax_error(lineno);
11843 break;
11846 hle = malloc(sizeof(*hle));
11847 if (hle == NULL) {
11848 err = got_error_from_errno("malloc");
11849 break;
11851 hle->cmd = cmd;
11852 hle->commit_id = commit_id;
11853 hle->logmsg = NULL;
11854 commit_id = NULL;
11855 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11856 lastcmd = cmd->code;
11859 free(line);
11860 free(commit_id);
11861 return err;
11864 static const struct got_error *
11865 histedit_check_script(struct got_histedit_list *histedit_cmds,
11866 struct got_object_id_queue *commits, struct got_repository *repo)
11868 const struct got_error *err = NULL;
11869 struct got_object_qid *qid;
11870 struct got_histedit_list_entry *hle;
11871 static char msg[92];
11872 char *id_str;
11874 if (TAILQ_EMPTY(histedit_cmds))
11875 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11876 "histedit script contains no commands");
11877 if (STAILQ_EMPTY(commits))
11878 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11880 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11881 struct got_histedit_list_entry *hle2;
11882 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11883 if (hle == hle2)
11884 continue;
11885 if (got_object_id_cmp(hle->commit_id,
11886 hle2->commit_id) != 0)
11887 continue;
11888 err = got_object_id_str(&id_str, hle->commit_id);
11889 if (err)
11890 return err;
11891 snprintf(msg, sizeof(msg), "commit %s is listed "
11892 "more than once in histedit script", id_str);
11893 free(id_str);
11894 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11898 STAILQ_FOREACH(qid, commits, entry) {
11899 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11900 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11901 break;
11903 if (hle == NULL) {
11904 err = got_object_id_str(&id_str, &qid->id);
11905 if (err)
11906 return err;
11907 snprintf(msg, sizeof(msg),
11908 "commit %s missing from histedit script", id_str);
11909 free(id_str);
11910 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11914 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11915 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11916 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11917 "last commit in histedit script cannot be folded");
11919 return NULL;
11922 static const struct got_error *
11923 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11924 const char *path, struct got_object_id_queue *commits,
11925 struct got_repository *repo)
11927 const struct got_error *err = NULL;
11928 char *editor;
11929 FILE *f = NULL;
11931 err = get_editor(&editor);
11932 if (err)
11933 return err;
11935 if (spawn_editor(editor, path) == -1) {
11936 err = got_error_from_errno("failed spawning editor");
11937 goto done;
11940 f = fopen(path, "re");
11941 if (f == NULL) {
11942 err = got_error_from_errno("fopen");
11943 goto done;
11945 err = histedit_parse_list(histedit_cmds, f, repo);
11946 if (err)
11947 goto done;
11949 err = histedit_check_script(histedit_cmds, commits, repo);
11950 done:
11951 if (f && fclose(f) == EOF && err == NULL)
11952 err = got_error_from_errno("fclose");
11953 free(editor);
11954 return err;
11957 static const struct got_error *
11958 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11959 struct got_object_id_queue *, const char *, const char *,
11960 struct got_repository *);
11962 static const struct got_error *
11963 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11964 struct got_object_id_queue *commits, const char *branch_name,
11965 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11966 struct got_repository *repo)
11968 const struct got_error *err;
11969 FILE *f = NULL;
11970 char *path = NULL;
11972 err = got_opentemp_named(&path, &f, "got-histedit", "");
11973 if (err)
11974 return err;
11976 err = write_cmd_list(f, branch_name, commits);
11977 if (err)
11978 goto done;
11980 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11981 fold_only, drop_only, edit_only, repo);
11982 if (err)
11983 goto done;
11985 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11986 rewind(f);
11987 err = histedit_parse_list(histedit_cmds, f, repo);
11988 } else {
11989 if (fclose(f) == EOF) {
11990 err = got_error_from_errno("fclose");
11991 goto done;
11993 f = NULL;
11994 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11995 if (err) {
11996 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11997 err->code != GOT_ERR_HISTEDIT_CMD)
11998 goto done;
11999 err = histedit_edit_list_retry(histedit_cmds, err,
12000 commits, path, branch_name, repo);
12003 done:
12004 if (f && fclose(f) == EOF && err == NULL)
12005 err = got_error_from_errno("fclose");
12006 if (path && unlink(path) != 0 && err == NULL)
12007 err = got_error_from_errno2("unlink", path);
12008 free(path);
12009 return err;
12012 static const struct got_error *
12013 histedit_save_list(struct got_histedit_list *histedit_cmds,
12014 struct got_worktree *worktree, struct got_repository *repo)
12016 const struct got_error *err = NULL;
12017 char *path = NULL;
12018 FILE *f = NULL;
12019 struct got_histedit_list_entry *hle;
12020 struct got_commit_object *commit = NULL;
12022 err = got_worktree_get_histedit_script_path(&path, worktree);
12023 if (err)
12024 return err;
12026 f = fopen(path, "we");
12027 if (f == NULL) {
12028 err = got_error_from_errno2("fopen", path);
12029 goto done;
12031 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12032 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12033 repo);
12034 if (err)
12035 break;
12037 if (hle->logmsg) {
12038 int n = fprintf(f, "%c %s\n",
12039 GOT_HISTEDIT_MESG, hle->logmsg);
12040 if (n < 0) {
12041 err = got_ferror(f, GOT_ERR_IO);
12042 break;
12046 done:
12047 if (f && fclose(f) == EOF && err == NULL)
12048 err = got_error_from_errno("fclose");
12049 free(path);
12050 if (commit)
12051 got_object_commit_close(commit);
12052 return err;
12055 static void
12056 histedit_free_list(struct got_histedit_list *histedit_cmds)
12058 struct got_histedit_list_entry *hle;
12060 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12061 TAILQ_REMOVE(histedit_cmds, hle, entry);
12062 free(hle);
12066 static const struct got_error *
12067 histedit_load_list(struct got_histedit_list *histedit_cmds,
12068 const char *path, struct got_repository *repo)
12070 const struct got_error *err = NULL;
12071 FILE *f = NULL;
12073 f = fopen(path, "re");
12074 if (f == NULL) {
12075 err = got_error_from_errno2("fopen", path);
12076 goto done;
12079 err = histedit_parse_list(histedit_cmds, f, repo);
12080 done:
12081 if (f && fclose(f) == EOF && err == NULL)
12082 err = got_error_from_errno("fclose");
12083 return err;
12086 static const struct got_error *
12087 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12088 const struct got_error *edit_err, struct got_object_id_queue *commits,
12089 const char *path, const char *branch_name, struct got_repository *repo)
12091 const struct got_error *err = NULL, *prev_err = edit_err;
12092 int resp = ' ';
12094 while (resp != 'c' && resp != 'r' && resp != 'a') {
12095 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12096 "or (a)bort: ", getprogname(), prev_err->msg);
12097 resp = getchar();
12098 if (resp == '\n')
12099 resp = getchar();
12100 if (resp == 'c') {
12101 histedit_free_list(histedit_cmds);
12102 err = histedit_run_editor(histedit_cmds, path, commits,
12103 repo);
12104 if (err) {
12105 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12106 err->code != GOT_ERR_HISTEDIT_CMD)
12107 break;
12108 prev_err = err;
12109 resp = ' ';
12110 continue;
12112 break;
12113 } else if (resp == 'r') {
12114 histedit_free_list(histedit_cmds);
12115 err = histedit_edit_script(histedit_cmds,
12116 commits, branch_name, 0, 0, 0, 0, repo);
12117 if (err) {
12118 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12119 err->code != GOT_ERR_HISTEDIT_CMD)
12120 break;
12121 prev_err = err;
12122 resp = ' ';
12123 continue;
12125 break;
12126 } else if (resp == 'a') {
12127 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12128 break;
12129 } else
12130 printf("invalid response '%c'\n", resp);
12133 return err;
12136 static const struct got_error *
12137 histedit_complete(struct got_worktree *worktree,
12138 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12139 struct got_reference *branch, struct got_repository *repo)
12141 printf("Switching work tree to %s\n",
12142 got_ref_get_symref_target(branch));
12143 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12144 branch, repo);
12147 static const struct got_error *
12148 show_histedit_progress(struct got_commit_object *commit,
12149 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12151 const struct got_error *err;
12152 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12154 err = got_object_id_str(&old_id_str, hle->commit_id);
12155 if (err)
12156 goto done;
12158 if (new_id) {
12159 err = got_object_id_str(&new_id_str, new_id);
12160 if (err)
12161 goto done;
12164 old_id_str[12] = '\0';
12165 if (new_id_str)
12166 new_id_str[12] = '\0';
12168 if (hle->logmsg) {
12169 logmsg = strdup(hle->logmsg);
12170 if (logmsg == NULL) {
12171 err = got_error_from_errno("strdup");
12172 goto done;
12174 trim_logmsg(logmsg, 42);
12175 } else {
12176 err = get_short_logmsg(&logmsg, 42, commit);
12177 if (err)
12178 goto done;
12181 switch (hle->cmd->code) {
12182 case GOT_HISTEDIT_PICK:
12183 case GOT_HISTEDIT_EDIT:
12184 printf("%s -> %s: %s\n", old_id_str,
12185 new_id_str ? new_id_str : "no-op change", logmsg);
12186 break;
12187 case GOT_HISTEDIT_DROP:
12188 case GOT_HISTEDIT_FOLD:
12189 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12190 logmsg);
12191 break;
12192 default:
12193 break;
12195 done:
12196 free(old_id_str);
12197 free(new_id_str);
12198 return err;
12201 static const struct got_error *
12202 histedit_commit(struct got_pathlist_head *merged_paths,
12203 struct got_worktree *worktree, struct got_fileindex *fileindex,
12204 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12205 const char *committer, int allow_conflict, struct got_repository *repo)
12207 const struct got_error *err;
12208 struct got_commit_object *commit;
12209 struct got_object_id *new_commit_id;
12211 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12212 && hle->logmsg == NULL) {
12213 err = histedit_edit_logmsg(hle, repo);
12214 if (err)
12215 return err;
12218 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12219 if (err)
12220 return err;
12222 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12223 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12224 hle->logmsg, allow_conflict, repo);
12225 if (err) {
12226 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12227 goto done;
12228 err = show_histedit_progress(commit, hle, NULL);
12229 } else {
12230 err = show_histedit_progress(commit, hle, new_commit_id);
12231 free(new_commit_id);
12233 done:
12234 got_object_commit_close(commit);
12235 return err;
12238 static const struct got_error *
12239 histedit_skip_commit(struct got_histedit_list_entry *hle,
12240 struct got_worktree *worktree, struct got_repository *repo)
12242 const struct got_error *error;
12243 struct got_commit_object *commit;
12245 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12246 repo);
12247 if (error)
12248 return error;
12250 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12251 if (error)
12252 return error;
12254 error = show_histedit_progress(commit, hle, NULL);
12255 got_object_commit_close(commit);
12256 return error;
12259 static const struct got_error *
12260 check_local_changes(void *arg, unsigned char status,
12261 unsigned char staged_status, const char *path,
12262 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12263 struct got_object_id *commit_id, int dirfd, const char *de_name)
12265 int *have_local_changes = arg;
12267 switch (status) {
12268 case GOT_STATUS_ADD:
12269 case GOT_STATUS_DELETE:
12270 case GOT_STATUS_MODIFY:
12271 case GOT_STATUS_CONFLICT:
12272 *have_local_changes = 1;
12273 return got_error(GOT_ERR_CANCELLED);
12274 default:
12275 break;
12278 switch (staged_status) {
12279 case GOT_STATUS_ADD:
12280 case GOT_STATUS_DELETE:
12281 case GOT_STATUS_MODIFY:
12282 *have_local_changes = 1;
12283 return got_error(GOT_ERR_CANCELLED);
12284 default:
12285 break;
12288 return NULL;
12291 static const struct got_error *
12292 cmd_histedit(int argc, char *argv[])
12294 const struct got_error *error = NULL;
12295 struct got_worktree *worktree = NULL;
12296 struct got_fileindex *fileindex = NULL;
12297 struct got_repository *repo = NULL;
12298 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12299 struct got_reference *branch = NULL;
12300 struct got_reference *tmp_branch = NULL;
12301 struct got_object_id *resume_commit_id = NULL;
12302 struct got_object_id *base_commit_id = NULL;
12303 struct got_object_id *head_commit_id = NULL;
12304 struct got_commit_object *commit = NULL;
12305 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12306 struct got_update_progress_arg upa;
12307 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12308 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12309 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12310 const char *edit_script_path = NULL;
12311 struct got_object_id_queue commits;
12312 struct got_pathlist_head merged_paths;
12313 const struct got_object_id_queue *parent_ids;
12314 struct got_object_qid *pid;
12315 struct got_histedit_list histedit_cmds;
12316 struct got_histedit_list_entry *hle;
12317 int *pack_fds = NULL;
12319 STAILQ_INIT(&commits);
12320 TAILQ_INIT(&histedit_cmds);
12321 TAILQ_INIT(&merged_paths);
12322 memset(&upa, 0, sizeof(upa));
12324 #ifndef PROFILE
12325 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12326 "unveil", NULL) == -1)
12327 err(1, "pledge");
12328 #endif
12330 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12331 switch (ch) {
12332 case 'a':
12333 abort_edit = 1;
12334 break;
12335 case 'C':
12336 allow_conflict = 1;
12337 break;
12338 case 'c':
12339 continue_edit = 1;
12340 break;
12341 case 'd':
12342 drop_only = 1;
12343 break;
12344 case 'e':
12345 edit_only = 1;
12346 break;
12347 case 'F':
12348 edit_script_path = optarg;
12349 break;
12350 case 'f':
12351 fold_only = 1;
12352 break;
12353 case 'l':
12354 list_backups = 1;
12355 break;
12356 case 'm':
12357 edit_logmsg_only = 1;
12358 break;
12359 case 'X':
12360 delete_backups = 1;
12361 break;
12362 default:
12363 usage_histedit();
12364 /* NOTREACHED */
12368 argc -= optind;
12369 argv += optind;
12371 if (abort_edit && allow_conflict)
12372 option_conflict('a', 'C');
12373 if (abort_edit && continue_edit)
12374 option_conflict('a', 'c');
12375 if (edit_script_path && allow_conflict)
12376 option_conflict('F', 'C');
12377 if (edit_script_path && edit_logmsg_only)
12378 option_conflict('F', 'm');
12379 if (abort_edit && edit_logmsg_only)
12380 option_conflict('a', 'm');
12381 if (edit_logmsg_only && allow_conflict)
12382 option_conflict('m', 'C');
12383 if (continue_edit && edit_logmsg_only)
12384 option_conflict('c', 'm');
12385 if (abort_edit && fold_only)
12386 option_conflict('a', 'f');
12387 if (fold_only && allow_conflict)
12388 option_conflict('f', 'C');
12389 if (continue_edit && fold_only)
12390 option_conflict('c', 'f');
12391 if (fold_only && edit_logmsg_only)
12392 option_conflict('f', 'm');
12393 if (edit_script_path && fold_only)
12394 option_conflict('F', 'f');
12395 if (abort_edit && edit_only)
12396 option_conflict('a', 'e');
12397 if (continue_edit && edit_only)
12398 option_conflict('c', 'e');
12399 if (edit_only && edit_logmsg_only)
12400 option_conflict('e', 'm');
12401 if (edit_script_path && edit_only)
12402 option_conflict('F', 'e');
12403 if (fold_only && edit_only)
12404 option_conflict('f', 'e');
12405 if (drop_only && abort_edit)
12406 option_conflict('d', 'a');
12407 if (drop_only && allow_conflict)
12408 option_conflict('d', 'C');
12409 if (drop_only && continue_edit)
12410 option_conflict('d', 'c');
12411 if (drop_only && edit_logmsg_only)
12412 option_conflict('d', 'm');
12413 if (drop_only && edit_only)
12414 option_conflict('d', 'e');
12415 if (drop_only && edit_script_path)
12416 option_conflict('d', 'F');
12417 if (drop_only && fold_only)
12418 option_conflict('d', 'f');
12419 if (list_backups) {
12420 if (abort_edit)
12421 option_conflict('l', 'a');
12422 if (allow_conflict)
12423 option_conflict('l', 'C');
12424 if (continue_edit)
12425 option_conflict('l', 'c');
12426 if (edit_script_path)
12427 option_conflict('l', 'F');
12428 if (edit_logmsg_only)
12429 option_conflict('l', 'm');
12430 if (drop_only)
12431 option_conflict('l', 'd');
12432 if (fold_only)
12433 option_conflict('l', 'f');
12434 if (edit_only)
12435 option_conflict('l', 'e');
12436 if (delete_backups)
12437 option_conflict('l', 'X');
12438 if (argc != 0 && argc != 1)
12439 usage_histedit();
12440 } else if (delete_backups) {
12441 if (abort_edit)
12442 option_conflict('X', 'a');
12443 if (allow_conflict)
12444 option_conflict('X', 'C');
12445 if (continue_edit)
12446 option_conflict('X', 'c');
12447 if (drop_only)
12448 option_conflict('X', 'd');
12449 if (edit_script_path)
12450 option_conflict('X', 'F');
12451 if (edit_logmsg_only)
12452 option_conflict('X', 'm');
12453 if (fold_only)
12454 option_conflict('X', 'f');
12455 if (edit_only)
12456 option_conflict('X', 'e');
12457 if (list_backups)
12458 option_conflict('X', 'l');
12459 if (argc != 0 && argc != 1)
12460 usage_histedit();
12461 } else if (allow_conflict && !continue_edit)
12462 errx(1, "-C option requires -c");
12463 else if (argc != 0)
12464 usage_histedit();
12467 * This command cannot apply unveil(2) in all cases because the
12468 * user may choose to run an editor to edit the histedit script
12469 * and to edit individual commit log messages.
12470 * unveil(2) traverses exec(2); if an editor is used we have to
12471 * apply unveil after edit script and log messages have been written.
12472 * XXX TODO: Make use of unveil(2) where possible.
12475 cwd = getcwd(NULL, 0);
12476 if (cwd == NULL) {
12477 error = got_error_from_errno("getcwd");
12478 goto done;
12481 error = got_repo_pack_fds_open(&pack_fds);
12482 if (error != NULL)
12483 goto done;
12485 error = got_worktree_open(&worktree, cwd);
12486 if (error) {
12487 if (list_backups || delete_backups) {
12488 if (error->code != GOT_ERR_NOT_WORKTREE)
12489 goto done;
12490 } else {
12491 if (error->code == GOT_ERR_NOT_WORKTREE)
12492 error = wrap_not_worktree_error(error,
12493 "histedit", cwd);
12494 goto done;
12498 if (list_backups || delete_backups) {
12499 error = got_repo_open(&repo,
12500 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12501 NULL, pack_fds);
12502 if (error != NULL)
12503 goto done;
12504 error = apply_unveil(got_repo_get_path(repo), 0,
12505 worktree ? got_worktree_get_root_path(worktree) : NULL);
12506 if (error)
12507 goto done;
12508 error = process_backup_refs(
12509 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12510 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12511 goto done; /* nothing else to do */
12514 error = get_gitconfig_path(&gitconfig_path);
12515 if (error)
12516 goto done;
12517 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12518 gitconfig_path, pack_fds);
12519 if (error != NULL)
12520 goto done;
12522 if (worktree != NULL && !list_backups && !delete_backups) {
12523 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12524 if (error)
12525 goto done;
12528 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12529 if (error)
12530 goto done;
12531 if (rebase_in_progress) {
12532 error = got_error(GOT_ERR_REBASING);
12533 goto done;
12536 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12537 repo);
12538 if (error)
12539 goto done;
12540 if (merge_in_progress) {
12541 error = got_error(GOT_ERR_MERGE_BUSY);
12542 goto done;
12545 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12546 if (error)
12547 goto done;
12549 if (edit_in_progress && edit_logmsg_only) {
12550 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12551 "histedit operation is in progress in this "
12552 "work tree and must be continued or aborted "
12553 "before the -m option can be used");
12554 goto done;
12556 if (edit_in_progress && drop_only) {
12557 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12558 "histedit operation is in progress in this "
12559 "work tree and must be continued or aborted "
12560 "before the -d option can be used");
12561 goto done;
12563 if (edit_in_progress && fold_only) {
12564 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12565 "histedit operation is in progress in this "
12566 "work tree and must be continued or aborted "
12567 "before the -f option can be used");
12568 goto done;
12570 if (edit_in_progress && edit_only) {
12571 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12572 "histedit operation is in progress in this "
12573 "work tree and must be continued or aborted "
12574 "before the -e option can be used");
12575 goto done;
12578 if (edit_in_progress && abort_edit) {
12579 error = got_worktree_histedit_continue(&resume_commit_id,
12580 &tmp_branch, &branch, &base_commit_id, &fileindex,
12581 worktree, repo);
12582 if (error)
12583 goto done;
12584 printf("Switching work tree to %s\n",
12585 got_ref_get_symref_target(branch));
12586 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12587 branch, base_commit_id, abort_progress, &upa);
12588 if (error)
12589 goto done;
12590 printf("Histedit of %s aborted\n",
12591 got_ref_get_symref_target(branch));
12592 print_merge_progress_stats(&upa);
12593 goto done; /* nothing else to do */
12594 } else if (abort_edit) {
12595 error = got_error(GOT_ERR_NOT_HISTEDIT);
12596 goto done;
12599 error = get_author(&committer, repo, worktree);
12600 if (error)
12601 goto done;
12603 if (continue_edit) {
12604 char *path;
12606 if (!edit_in_progress) {
12607 error = got_error(GOT_ERR_NOT_HISTEDIT);
12608 goto done;
12611 error = got_worktree_get_histedit_script_path(&path, worktree);
12612 if (error)
12613 goto done;
12615 error = histedit_load_list(&histedit_cmds, path, repo);
12616 free(path);
12617 if (error)
12618 goto done;
12620 error = got_worktree_histedit_continue(&resume_commit_id,
12621 &tmp_branch, &branch, &base_commit_id, &fileindex,
12622 worktree, repo);
12623 if (error)
12624 goto done;
12626 error = got_ref_resolve(&head_commit_id, repo, branch);
12627 if (error)
12628 goto done;
12630 error = got_object_open_as_commit(&commit, repo,
12631 head_commit_id);
12632 if (error)
12633 goto done;
12634 parent_ids = got_object_commit_get_parent_ids(commit);
12635 pid = STAILQ_FIRST(parent_ids);
12636 if (pid == NULL) {
12637 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12638 goto done;
12640 error = collect_commits(&commits, head_commit_id, &pid->id,
12641 base_commit_id, got_worktree_get_path_prefix(worktree),
12642 GOT_ERR_HISTEDIT_PATH, repo);
12643 got_object_commit_close(commit);
12644 commit = NULL;
12645 if (error)
12646 goto done;
12647 } else {
12648 if (edit_in_progress) {
12649 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12650 goto done;
12653 error = got_ref_open(&branch, repo,
12654 got_worktree_get_head_ref_name(worktree), 0);
12655 if (error != NULL)
12656 goto done;
12658 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12659 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12660 "will not edit commit history of a branch outside "
12661 "the \"refs/heads/\" reference namespace");
12662 goto done;
12665 error = got_ref_resolve(&head_commit_id, repo, branch);
12666 got_ref_close(branch);
12667 branch = NULL;
12668 if (error)
12669 goto done;
12671 error = got_object_open_as_commit(&commit, repo,
12672 head_commit_id);
12673 if (error)
12674 goto done;
12675 parent_ids = got_object_commit_get_parent_ids(commit);
12676 pid = STAILQ_FIRST(parent_ids);
12677 if (pid == NULL) {
12678 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12679 goto done;
12681 error = collect_commits(&commits, head_commit_id, &pid->id,
12682 got_worktree_get_base_commit_id(worktree),
12683 got_worktree_get_path_prefix(worktree),
12684 GOT_ERR_HISTEDIT_PATH, repo);
12685 got_object_commit_close(commit);
12686 commit = NULL;
12687 if (error)
12688 goto done;
12690 if (STAILQ_EMPTY(&commits)) {
12691 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12692 goto done;
12695 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12696 &base_commit_id, &fileindex, worktree, repo);
12697 if (error)
12698 goto done;
12700 if (edit_script_path) {
12701 error = histedit_load_list(&histedit_cmds,
12702 edit_script_path, repo);
12703 if (error) {
12704 got_worktree_histedit_abort(worktree, fileindex,
12705 repo, branch, base_commit_id,
12706 abort_progress, &upa);
12707 print_merge_progress_stats(&upa);
12708 goto done;
12710 } else {
12711 const char *branch_name;
12712 branch_name = got_ref_get_symref_target(branch);
12713 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12714 branch_name += 11;
12715 error = histedit_edit_script(&histedit_cmds, &commits,
12716 branch_name, edit_logmsg_only, fold_only,
12717 drop_only, edit_only, repo);
12718 if (error) {
12719 got_worktree_histedit_abort(worktree, fileindex,
12720 repo, branch, base_commit_id,
12721 abort_progress, &upa);
12722 print_merge_progress_stats(&upa);
12723 goto done;
12728 error = histedit_save_list(&histedit_cmds, worktree,
12729 repo);
12730 if (error) {
12731 got_worktree_histedit_abort(worktree, fileindex,
12732 repo, branch, base_commit_id,
12733 abort_progress, &upa);
12734 print_merge_progress_stats(&upa);
12735 goto done;
12740 error = histedit_check_script(&histedit_cmds, &commits, repo);
12741 if (error)
12742 goto done;
12744 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12745 if (resume_commit_id) {
12746 if (got_object_id_cmp(hle->commit_id,
12747 resume_commit_id) != 0)
12748 continue;
12750 resume_commit_id = NULL;
12751 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12752 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12753 error = histedit_skip_commit(hle, worktree,
12754 repo);
12755 if (error)
12756 goto done;
12757 } else {
12758 struct got_pathlist_head paths;
12759 int have_changes = 0;
12761 TAILQ_INIT(&paths);
12762 error = got_pathlist_append(&paths, "", NULL);
12763 if (error)
12764 goto done;
12765 error = got_worktree_status(worktree, &paths,
12766 repo, 0, check_local_changes, &have_changes,
12767 check_cancelled, NULL);
12768 got_pathlist_free(&paths,
12769 GOT_PATHLIST_FREE_NONE);
12770 if (error) {
12771 if (error->code != GOT_ERR_CANCELLED)
12772 goto done;
12773 if (sigint_received || sigpipe_received)
12774 goto done;
12776 if (have_changes) {
12777 error = histedit_commit(NULL, worktree,
12778 fileindex, tmp_branch, hle,
12779 committer, allow_conflict, repo);
12780 if (error)
12781 goto done;
12782 } else {
12783 error = got_object_open_as_commit(
12784 &commit, repo, hle->commit_id);
12785 if (error)
12786 goto done;
12787 error = show_histedit_progress(commit,
12788 hle, NULL);
12789 got_object_commit_close(commit);
12790 commit = NULL;
12791 if (error)
12792 goto done;
12795 continue;
12798 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12799 error = histedit_skip_commit(hle, worktree, repo);
12800 if (error)
12801 goto done;
12802 continue;
12805 error = got_object_open_as_commit(&commit, repo,
12806 hle->commit_id);
12807 if (error)
12808 goto done;
12809 parent_ids = got_object_commit_get_parent_ids(commit);
12810 pid = STAILQ_FIRST(parent_ids);
12812 error = got_worktree_histedit_merge_files(&merged_paths,
12813 worktree, fileindex, &pid->id, hle->commit_id, repo,
12814 update_progress, &upa, check_cancelled, NULL);
12815 if (error)
12816 goto done;
12817 got_object_commit_close(commit);
12818 commit = NULL;
12820 print_merge_progress_stats(&upa);
12821 if (upa.conflicts > 0 || upa.missing > 0 ||
12822 upa.not_deleted > 0 || upa.unversioned > 0) {
12823 if (upa.conflicts > 0) {
12824 error = show_rebase_merge_conflict(
12825 hle->commit_id, repo);
12826 if (error)
12827 goto done;
12829 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12830 break;
12833 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12834 char *id_str;
12835 error = got_object_id_str(&id_str, hle->commit_id);
12836 if (error)
12837 goto done;
12838 printf("Stopping histedit for amending commit %s\n",
12839 id_str);
12840 free(id_str);
12841 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12842 error = got_worktree_histedit_postpone(worktree,
12843 fileindex);
12844 goto done;
12847 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12848 error = histedit_skip_commit(hle, worktree, repo);
12849 if (error)
12850 goto done;
12851 continue;
12854 error = histedit_commit(&merged_paths, worktree, fileindex,
12855 tmp_branch, hle, committer, allow_conflict, repo);
12856 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12857 if (error)
12858 goto done;
12861 if (upa.conflicts > 0 || upa.missing > 0 ||
12862 upa.not_deleted > 0 || upa.unversioned > 0) {
12863 error = got_worktree_histedit_postpone(worktree, fileindex);
12864 if (error)
12865 goto done;
12866 if (upa.conflicts > 0 && upa.missing == 0 &&
12867 upa.not_deleted == 0 && upa.unversioned == 0) {
12868 error = got_error_msg(GOT_ERR_CONFLICTS,
12869 "conflicts must be resolved before histedit "
12870 "can continue");
12871 } else if (upa.conflicts > 0) {
12872 error = got_error_msg(GOT_ERR_CONFLICTS,
12873 "conflicts must be resolved before histedit "
12874 "can continue; changes destined for some "
12875 "files were not yet merged and should be "
12876 "merged manually if required before the "
12877 "histedit operation is continued");
12878 } else {
12879 error = got_error_msg(GOT_ERR_CONFLICTS,
12880 "changes destined for some files were not "
12881 "yet merged and should be merged manually "
12882 "if required before the histedit operation "
12883 "is continued");
12885 } else
12886 error = histedit_complete(worktree, fileindex, tmp_branch,
12887 branch, repo);
12888 done:
12889 free(cwd);
12890 free(committer);
12891 free(gitconfig_path);
12892 got_object_id_queue_free(&commits);
12893 histedit_free_list(&histedit_cmds);
12894 free(head_commit_id);
12895 free(base_commit_id);
12896 free(resume_commit_id);
12897 if (commit)
12898 got_object_commit_close(commit);
12899 if (branch)
12900 got_ref_close(branch);
12901 if (tmp_branch)
12902 got_ref_close(tmp_branch);
12903 if (worktree)
12904 got_worktree_close(worktree);
12905 if (repo) {
12906 const struct got_error *close_err = got_repo_close(repo);
12907 if (error == NULL)
12908 error = close_err;
12910 if (pack_fds) {
12911 const struct got_error *pack_err =
12912 got_repo_pack_fds_close(pack_fds);
12913 if (error == NULL)
12914 error = pack_err;
12916 return error;
12919 __dead static void
12920 usage_integrate(void)
12922 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12923 exit(1);
12926 static const struct got_error *
12927 cmd_integrate(int argc, char *argv[])
12929 const struct got_error *error = NULL;
12930 struct got_repository *repo = NULL;
12931 struct got_worktree *worktree = NULL;
12932 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12933 const char *branch_arg = NULL;
12934 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12935 struct got_fileindex *fileindex = NULL;
12936 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12937 int ch;
12938 struct got_update_progress_arg upa;
12939 int *pack_fds = NULL;
12941 #ifndef PROFILE
12942 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12943 "unveil", NULL) == -1)
12944 err(1, "pledge");
12945 #endif
12947 while ((ch = getopt(argc, argv, "")) != -1) {
12948 switch (ch) {
12949 default:
12950 usage_integrate();
12951 /* NOTREACHED */
12955 argc -= optind;
12956 argv += optind;
12958 if (argc != 1)
12959 usage_integrate();
12960 branch_arg = argv[0];
12962 cwd = getcwd(NULL, 0);
12963 if (cwd == NULL) {
12964 error = got_error_from_errno("getcwd");
12965 goto done;
12968 error = got_repo_pack_fds_open(&pack_fds);
12969 if (error != NULL)
12970 goto done;
12972 error = got_worktree_open(&worktree, cwd);
12973 if (error) {
12974 if (error->code == GOT_ERR_NOT_WORKTREE)
12975 error = wrap_not_worktree_error(error, "integrate",
12976 cwd);
12977 goto done;
12980 error = check_rebase_or_histedit_in_progress(worktree);
12981 if (error)
12982 goto done;
12984 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12985 NULL, pack_fds);
12986 if (error != NULL)
12987 goto done;
12989 error = apply_unveil(got_repo_get_path(repo), 0,
12990 got_worktree_get_root_path(worktree));
12991 if (error)
12992 goto done;
12994 error = check_merge_in_progress(worktree, repo);
12995 if (error)
12996 goto done;
12998 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12999 error = got_error_from_errno("asprintf");
13000 goto done;
13003 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13004 &base_branch_ref, worktree, refname, repo);
13005 if (error)
13006 goto done;
13008 refname = strdup(got_ref_get_name(branch_ref));
13009 if (refname == NULL) {
13010 error = got_error_from_errno("strdup");
13011 got_worktree_integrate_abort(worktree, fileindex, repo,
13012 branch_ref, base_branch_ref);
13013 goto done;
13015 base_refname = strdup(got_ref_get_name(base_branch_ref));
13016 if (base_refname == NULL) {
13017 error = got_error_from_errno("strdup");
13018 got_worktree_integrate_abort(worktree, fileindex, repo,
13019 branch_ref, base_branch_ref);
13020 goto done;
13022 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13023 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13024 got_worktree_integrate_abort(worktree, fileindex, repo,
13025 branch_ref, base_branch_ref);
13026 goto done;
13029 error = got_ref_resolve(&commit_id, repo, branch_ref);
13030 if (error)
13031 goto done;
13033 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13034 if (error)
13035 goto done;
13037 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13038 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13039 "specified branch has already been integrated");
13040 got_worktree_integrate_abort(worktree, fileindex, repo,
13041 branch_ref, base_branch_ref);
13042 goto done;
13045 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13046 if (error) {
13047 if (error->code == GOT_ERR_ANCESTRY)
13048 error = got_error(GOT_ERR_REBASE_REQUIRED);
13049 got_worktree_integrate_abort(worktree, fileindex, repo,
13050 branch_ref, base_branch_ref);
13051 goto done;
13054 memset(&upa, 0, sizeof(upa));
13055 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13056 branch_ref, base_branch_ref, update_progress, &upa,
13057 check_cancelled, NULL);
13058 if (error)
13059 goto done;
13061 printf("Integrated %s into %s\n", refname, base_refname);
13062 print_update_progress_stats(&upa);
13063 done:
13064 if (repo) {
13065 const struct got_error *close_err = got_repo_close(repo);
13066 if (error == NULL)
13067 error = close_err;
13069 if (worktree)
13070 got_worktree_close(worktree);
13071 if (pack_fds) {
13072 const struct got_error *pack_err =
13073 got_repo_pack_fds_close(pack_fds);
13074 if (error == NULL)
13075 error = pack_err;
13077 free(cwd);
13078 free(base_commit_id);
13079 free(commit_id);
13080 free(refname);
13081 free(base_refname);
13082 return error;
13085 __dead static void
13086 usage_merge(void)
13088 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13089 exit(1);
13092 static const struct got_error *
13093 cmd_merge(int argc, char *argv[])
13095 const struct got_error *error = NULL;
13096 struct got_worktree *worktree = NULL;
13097 struct got_repository *repo = NULL;
13098 struct got_fileindex *fileindex = NULL;
13099 char *cwd = NULL, *id_str = NULL, *author = NULL;
13100 char *gitconfig_path = NULL;
13101 struct got_reference *branch = NULL, *wt_branch = NULL;
13102 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13103 struct got_object_id *wt_branch_tip = NULL;
13104 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13105 int allow_conflict = 0, interrupt_merge = 0;
13106 struct got_update_progress_arg upa;
13107 struct got_object_id *merge_commit_id = NULL;
13108 char *branch_name = NULL;
13109 int *pack_fds = NULL;
13111 memset(&upa, 0, sizeof(upa));
13113 #ifndef PROFILE
13114 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13115 "unveil", NULL) == -1)
13116 err(1, "pledge");
13117 #endif
13119 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13120 switch (ch) {
13121 case 'a':
13122 abort_merge = 1;
13123 break;
13124 case 'C':
13125 allow_conflict = 1;
13126 case 'c':
13127 continue_merge = 1;
13128 break;
13129 case 'n':
13130 interrupt_merge = 1;
13131 break;
13132 default:
13133 usage_merge();
13134 /* NOTREACHED */
13138 argc -= optind;
13139 argv += optind;
13141 if (allow_conflict) {
13142 if (abort_merge)
13143 option_conflict('a', 'C');
13144 if (!continue_merge)
13145 errx(1, "-C option requires -c");
13147 if (abort_merge && continue_merge)
13148 option_conflict('a', 'c');
13149 if (abort_merge || continue_merge) {
13150 if (argc != 0)
13151 usage_merge();
13152 } else if (argc != 1)
13153 usage_merge();
13155 cwd = getcwd(NULL, 0);
13156 if (cwd == NULL) {
13157 error = got_error_from_errno("getcwd");
13158 goto done;
13161 error = got_repo_pack_fds_open(&pack_fds);
13162 if (error != NULL)
13163 goto done;
13165 error = got_worktree_open(&worktree, cwd);
13166 if (error) {
13167 if (error->code == GOT_ERR_NOT_WORKTREE)
13168 error = wrap_not_worktree_error(error,
13169 "merge", cwd);
13170 goto done;
13173 error = get_gitconfig_path(&gitconfig_path);
13174 if (error)
13175 goto done;
13176 error = got_repo_open(&repo,
13177 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13178 gitconfig_path, pack_fds);
13179 if (error != NULL)
13180 goto done;
13182 if (worktree != NULL) {
13183 error = worktree_has_logmsg_ref("merge", worktree, repo);
13184 if (error)
13185 goto done;
13188 error = apply_unveil(got_repo_get_path(repo), 0,
13189 worktree ? got_worktree_get_root_path(worktree) : NULL);
13190 if (error)
13191 goto done;
13193 error = check_rebase_or_histedit_in_progress(worktree);
13194 if (error)
13195 goto done;
13197 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13198 repo);
13199 if (error)
13200 goto done;
13202 if (abort_merge) {
13203 if (!merge_in_progress) {
13204 error = got_error(GOT_ERR_NOT_MERGING);
13205 goto done;
13207 error = got_worktree_merge_continue(&branch_name,
13208 &branch_tip, &fileindex, worktree, repo);
13209 if (error)
13210 goto done;
13211 error = got_worktree_merge_abort(worktree, fileindex, repo,
13212 abort_progress, &upa);
13213 if (error)
13214 goto done;
13215 printf("Merge of %s aborted\n", branch_name);
13216 goto done; /* nothing else to do */
13219 error = get_author(&author, repo, worktree);
13220 if (error)
13221 goto done;
13223 if (continue_merge) {
13224 if (!merge_in_progress) {
13225 error = got_error(GOT_ERR_NOT_MERGING);
13226 goto done;
13228 error = got_worktree_merge_continue(&branch_name,
13229 &branch_tip, &fileindex, worktree, repo);
13230 if (error)
13231 goto done;
13232 } else {
13233 error = got_ref_open(&branch, repo, argv[0], 0);
13234 if (error != NULL)
13235 goto done;
13236 branch_name = strdup(got_ref_get_name(branch));
13237 if (branch_name == NULL) {
13238 error = got_error_from_errno("strdup");
13239 goto done;
13241 error = got_ref_resolve(&branch_tip, repo, branch);
13242 if (error)
13243 goto done;
13246 error = got_ref_open(&wt_branch, repo,
13247 got_worktree_get_head_ref_name(worktree), 0);
13248 if (error)
13249 goto done;
13250 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13251 if (error)
13252 goto done;
13253 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13254 wt_branch_tip, branch_tip, 0, repo,
13255 check_cancelled, NULL);
13256 if (error && error->code != GOT_ERR_ANCESTRY)
13257 goto done;
13259 if (!continue_merge) {
13260 error = check_path_prefix(wt_branch_tip, branch_tip,
13261 got_worktree_get_path_prefix(worktree),
13262 GOT_ERR_MERGE_PATH, repo);
13263 if (error)
13264 goto done;
13265 if (yca_id) {
13266 error = check_same_branch(wt_branch_tip, branch,
13267 yca_id, repo);
13268 if (error) {
13269 if (error->code != GOT_ERR_ANCESTRY)
13270 goto done;
13271 error = NULL;
13272 } else {
13273 static char msg[512];
13274 snprintf(msg, sizeof(msg),
13275 "cannot create a merge commit because "
13276 "%s is based on %s; %s can be integrated "
13277 "with 'got integrate' instead", branch_name,
13278 got_worktree_get_head_ref_name(worktree),
13279 branch_name);
13280 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13281 goto done;
13284 error = got_worktree_merge_prepare(&fileindex, worktree,
13285 branch, repo);
13286 if (error)
13287 goto done;
13289 error = got_worktree_merge_branch(worktree, fileindex,
13290 yca_id, branch_tip, repo, update_progress, &upa,
13291 check_cancelled, NULL);
13292 if (error)
13293 goto done;
13294 print_merge_progress_stats(&upa);
13295 if (!upa.did_something) {
13296 error = got_worktree_merge_abort(worktree, fileindex,
13297 repo, abort_progress, &upa);
13298 if (error)
13299 goto done;
13300 printf("Already up-to-date\n");
13301 goto done;
13305 if (interrupt_merge) {
13306 error = got_worktree_merge_postpone(worktree, fileindex);
13307 if (error)
13308 goto done;
13309 printf("Merge of %s interrupted on request\n", branch_name);
13310 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13311 upa.not_deleted > 0 || upa.unversioned > 0) {
13312 error = got_worktree_merge_postpone(worktree, fileindex);
13313 if (error)
13314 goto done;
13315 if (upa.conflicts > 0 && upa.missing == 0 &&
13316 upa.not_deleted == 0 && upa.unversioned == 0) {
13317 error = got_error_msg(GOT_ERR_CONFLICTS,
13318 "conflicts must be resolved before merging "
13319 "can continue");
13320 } else if (upa.conflicts > 0) {
13321 error = got_error_msg(GOT_ERR_CONFLICTS,
13322 "conflicts must be resolved before merging "
13323 "can continue; changes destined for some "
13324 "files were not yet merged and "
13325 "should be merged manually if required before the "
13326 "merge operation is continued");
13327 } else {
13328 error = got_error_msg(GOT_ERR_CONFLICTS,
13329 "changes destined for some "
13330 "files were not yet merged and should be "
13331 "merged manually if required before the "
13332 "merge operation is continued");
13334 goto done;
13335 } else {
13336 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13337 fileindex, author, NULL, 1, branch_tip, branch_name,
13338 allow_conflict, repo, continue_merge ? print_status : NULL,
13339 NULL);
13340 if (error)
13341 goto done;
13342 error = got_worktree_merge_complete(worktree, fileindex, repo);
13343 if (error)
13344 goto done;
13345 error = got_object_id_str(&id_str, merge_commit_id);
13346 if (error)
13347 goto done;
13348 printf("Merged %s into %s: %s\n", branch_name,
13349 got_worktree_get_head_ref_name(worktree),
13350 id_str);
13353 done:
13354 free(gitconfig_path);
13355 free(id_str);
13356 free(merge_commit_id);
13357 free(author);
13358 free(branch_tip);
13359 free(branch_name);
13360 free(yca_id);
13361 if (branch)
13362 got_ref_close(branch);
13363 if (wt_branch)
13364 got_ref_close(wt_branch);
13365 if (worktree)
13366 got_worktree_close(worktree);
13367 if (repo) {
13368 const struct got_error *close_err = got_repo_close(repo);
13369 if (error == NULL)
13370 error = close_err;
13372 if (pack_fds) {
13373 const struct got_error *pack_err =
13374 got_repo_pack_fds_close(pack_fds);
13375 if (error == NULL)
13376 error = pack_err;
13378 return error;
13381 __dead static void
13382 usage_stage(void)
13384 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13385 "[path ...]\n", getprogname());
13386 exit(1);
13389 static const struct got_error *
13390 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13391 const char *path, struct got_object_id *blob_id,
13392 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13393 int dirfd, const char *de_name)
13395 const struct got_error *err = NULL;
13396 char *id_str = NULL;
13398 if (staged_status != GOT_STATUS_ADD &&
13399 staged_status != GOT_STATUS_MODIFY &&
13400 staged_status != GOT_STATUS_DELETE)
13401 return NULL;
13403 if (staged_status == GOT_STATUS_ADD ||
13404 staged_status == GOT_STATUS_MODIFY)
13405 err = got_object_id_str(&id_str, staged_blob_id);
13406 else
13407 err = got_object_id_str(&id_str, blob_id);
13408 if (err)
13409 return err;
13411 printf("%s %c %s\n", id_str, staged_status, path);
13412 free(id_str);
13413 return NULL;
13416 static const struct got_error *
13417 cmd_stage(int argc, char *argv[])
13419 const struct got_error *error = NULL;
13420 struct got_repository *repo = NULL;
13421 struct got_worktree *worktree = NULL;
13422 char *cwd = NULL;
13423 struct got_pathlist_head paths;
13424 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13425 FILE *patch_script_file = NULL;
13426 const char *patch_script_path = NULL;
13427 struct choose_patch_arg cpa;
13428 int *pack_fds = NULL;
13430 TAILQ_INIT(&paths);
13432 #ifndef PROFILE
13433 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13434 "unveil", NULL) == -1)
13435 err(1, "pledge");
13436 #endif
13438 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13439 switch (ch) {
13440 case 'F':
13441 patch_script_path = optarg;
13442 break;
13443 case 'l':
13444 list_stage = 1;
13445 break;
13446 case 'p':
13447 pflag = 1;
13448 break;
13449 case 'S':
13450 allow_bad_symlinks = 1;
13451 break;
13452 default:
13453 usage_stage();
13454 /* NOTREACHED */
13458 argc -= optind;
13459 argv += optind;
13461 if (list_stage && (pflag || patch_script_path))
13462 errx(1, "-l option cannot be used with other options");
13463 if (patch_script_path && !pflag)
13464 errx(1, "-F option can only be used together with -p option");
13466 cwd = getcwd(NULL, 0);
13467 if (cwd == NULL) {
13468 error = got_error_from_errno("getcwd");
13469 goto done;
13472 error = got_repo_pack_fds_open(&pack_fds);
13473 if (error != NULL)
13474 goto done;
13476 error = got_worktree_open(&worktree, cwd);
13477 if (error) {
13478 if (error->code == GOT_ERR_NOT_WORKTREE)
13479 error = wrap_not_worktree_error(error, "stage", cwd);
13480 goto done;
13483 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13484 NULL, pack_fds);
13485 if (error != NULL)
13486 goto done;
13488 if (patch_script_path) {
13489 patch_script_file = fopen(patch_script_path, "re");
13490 if (patch_script_file == NULL) {
13491 error = got_error_from_errno2("fopen",
13492 patch_script_path);
13493 goto done;
13496 error = apply_unveil(got_repo_get_path(repo), 0,
13497 got_worktree_get_root_path(worktree));
13498 if (error)
13499 goto done;
13501 error = check_merge_in_progress(worktree, repo);
13502 if (error)
13503 goto done;
13505 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13506 if (error)
13507 goto done;
13509 if (list_stage)
13510 error = got_worktree_status(worktree, &paths, repo, 0,
13511 print_stage, NULL, check_cancelled, NULL);
13512 else {
13513 cpa.patch_script_file = patch_script_file;
13514 cpa.action = "stage";
13515 error = got_worktree_stage(worktree, &paths,
13516 pflag ? NULL : print_status, NULL,
13517 pflag ? choose_patch : NULL, &cpa,
13518 allow_bad_symlinks, repo);
13520 done:
13521 if (patch_script_file && fclose(patch_script_file) == EOF &&
13522 error == NULL)
13523 error = got_error_from_errno2("fclose", patch_script_path);
13524 if (repo) {
13525 const struct got_error *close_err = got_repo_close(repo);
13526 if (error == NULL)
13527 error = close_err;
13529 if (worktree)
13530 got_worktree_close(worktree);
13531 if (pack_fds) {
13532 const struct got_error *pack_err =
13533 got_repo_pack_fds_close(pack_fds);
13534 if (error == NULL)
13535 error = pack_err;
13537 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13538 free(cwd);
13539 return error;
13542 __dead static void
13543 usage_unstage(void)
13545 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13546 "[path ...]\n", getprogname());
13547 exit(1);
13551 static const struct got_error *
13552 cmd_unstage(int argc, char *argv[])
13554 const struct got_error *error = NULL;
13555 struct got_repository *repo = NULL;
13556 struct got_worktree *worktree = NULL;
13557 char *cwd = NULL;
13558 struct got_pathlist_head paths;
13559 int ch, pflag = 0;
13560 struct got_update_progress_arg upa;
13561 FILE *patch_script_file = NULL;
13562 const char *patch_script_path = NULL;
13563 struct choose_patch_arg cpa;
13564 int *pack_fds = NULL;
13566 TAILQ_INIT(&paths);
13568 #ifndef PROFILE
13569 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13570 "unveil", NULL) == -1)
13571 err(1, "pledge");
13572 #endif
13574 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13575 switch (ch) {
13576 case 'F':
13577 patch_script_path = optarg;
13578 break;
13579 case 'p':
13580 pflag = 1;
13581 break;
13582 default:
13583 usage_unstage();
13584 /* NOTREACHED */
13588 argc -= optind;
13589 argv += optind;
13591 if (patch_script_path && !pflag)
13592 errx(1, "-F option can only be used together with -p option");
13594 cwd = getcwd(NULL, 0);
13595 if (cwd == NULL) {
13596 error = got_error_from_errno("getcwd");
13597 goto done;
13600 error = got_repo_pack_fds_open(&pack_fds);
13601 if (error != NULL)
13602 goto done;
13604 error = got_worktree_open(&worktree, cwd);
13605 if (error) {
13606 if (error->code == GOT_ERR_NOT_WORKTREE)
13607 error = wrap_not_worktree_error(error, "unstage", cwd);
13608 goto done;
13611 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13612 NULL, pack_fds);
13613 if (error != NULL)
13614 goto done;
13616 if (patch_script_path) {
13617 patch_script_file = fopen(patch_script_path, "re");
13618 if (patch_script_file == NULL) {
13619 error = got_error_from_errno2("fopen",
13620 patch_script_path);
13621 goto done;
13625 error = apply_unveil(got_repo_get_path(repo), 0,
13626 got_worktree_get_root_path(worktree));
13627 if (error)
13628 goto done;
13630 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13631 if (error)
13632 goto done;
13634 cpa.patch_script_file = patch_script_file;
13635 cpa.action = "unstage";
13636 memset(&upa, 0, sizeof(upa));
13637 error = got_worktree_unstage(worktree, &paths, update_progress,
13638 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13639 if (!error)
13640 print_merge_progress_stats(&upa);
13641 done:
13642 if (patch_script_file && fclose(patch_script_file) == EOF &&
13643 error == NULL)
13644 error = got_error_from_errno2("fclose", patch_script_path);
13645 if (repo) {
13646 const struct got_error *close_err = got_repo_close(repo);
13647 if (error == NULL)
13648 error = close_err;
13650 if (worktree)
13651 got_worktree_close(worktree);
13652 if (pack_fds) {
13653 const struct got_error *pack_err =
13654 got_repo_pack_fds_close(pack_fds);
13655 if (error == NULL)
13656 error = pack_err;
13658 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13659 free(cwd);
13660 return error;
13663 __dead static void
13664 usage_cat(void)
13666 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13667 "arg ...\n", getprogname());
13668 exit(1);
13671 static const struct got_error *
13672 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13674 const struct got_error *err;
13675 struct got_blob_object *blob;
13676 int fd = -1;
13678 fd = got_opentempfd();
13679 if (fd == -1)
13680 return got_error_from_errno("got_opentempfd");
13682 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13683 if (err)
13684 goto done;
13686 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13687 done:
13688 if (fd != -1 && close(fd) == -1 && err == NULL)
13689 err = got_error_from_errno("close");
13690 if (blob)
13691 got_object_blob_close(blob);
13692 return err;
13695 static const struct got_error *
13696 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13698 const struct got_error *err;
13699 struct got_tree_object *tree;
13700 int nentries, i;
13702 err = got_object_open_as_tree(&tree, repo, id);
13703 if (err)
13704 return err;
13706 nentries = got_object_tree_get_nentries(tree);
13707 for (i = 0; i < nentries; i++) {
13708 struct got_tree_entry *te;
13709 char *id_str;
13710 if (sigint_received || sigpipe_received)
13711 break;
13712 te = got_object_tree_get_entry(tree, i);
13713 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13714 if (err)
13715 break;
13716 fprintf(outfile, "%s %.7o %s\n", id_str,
13717 got_tree_entry_get_mode(te),
13718 got_tree_entry_get_name(te));
13719 free(id_str);
13722 got_object_tree_close(tree);
13723 return err;
13726 static const struct got_error *
13727 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13729 const struct got_error *err;
13730 struct got_commit_object *commit;
13731 const struct got_object_id_queue *parent_ids;
13732 struct got_object_qid *pid;
13733 char *id_str = NULL;
13734 const char *logmsg = NULL;
13735 char gmtoff[6];
13737 err = got_object_open_as_commit(&commit, repo, id);
13738 if (err)
13739 return err;
13741 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13742 if (err)
13743 goto done;
13745 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13746 parent_ids = got_object_commit_get_parent_ids(commit);
13747 fprintf(outfile, "numparents %d\n",
13748 got_object_commit_get_nparents(commit));
13749 STAILQ_FOREACH(pid, parent_ids, entry) {
13750 char *pid_str;
13751 err = got_object_id_str(&pid_str, &pid->id);
13752 if (err)
13753 goto done;
13754 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13755 free(pid_str);
13757 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13758 got_object_commit_get_author_gmtoff(commit));
13759 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13760 got_object_commit_get_author(commit),
13761 (long long)got_object_commit_get_author_time(commit),
13762 gmtoff);
13764 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13765 got_object_commit_get_committer_gmtoff(commit));
13766 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13767 got_object_commit_get_committer(commit),
13768 (long long)got_object_commit_get_committer_time(commit),
13769 gmtoff);
13771 logmsg = got_object_commit_get_logmsg_raw(commit);
13772 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13773 fprintf(outfile, "%s", logmsg);
13774 done:
13775 free(id_str);
13776 got_object_commit_close(commit);
13777 return err;
13780 static const struct got_error *
13781 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13783 const struct got_error *err;
13784 struct got_tag_object *tag;
13785 char *id_str = NULL;
13786 const char *tagmsg = NULL;
13787 char gmtoff[6];
13789 err = got_object_open_as_tag(&tag, repo, id);
13790 if (err)
13791 return err;
13793 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13794 if (err)
13795 goto done;
13797 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13799 switch (got_object_tag_get_object_type(tag)) {
13800 case GOT_OBJ_TYPE_BLOB:
13801 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13802 GOT_OBJ_LABEL_BLOB);
13803 break;
13804 case GOT_OBJ_TYPE_TREE:
13805 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13806 GOT_OBJ_LABEL_TREE);
13807 break;
13808 case GOT_OBJ_TYPE_COMMIT:
13809 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13810 GOT_OBJ_LABEL_COMMIT);
13811 break;
13812 case GOT_OBJ_TYPE_TAG:
13813 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13814 GOT_OBJ_LABEL_TAG);
13815 break;
13816 default:
13817 break;
13820 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13821 got_object_tag_get_name(tag));
13823 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13824 got_object_tag_get_tagger_gmtoff(tag));
13825 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13826 got_object_tag_get_tagger(tag),
13827 (long long)got_object_tag_get_tagger_time(tag),
13828 gmtoff);
13830 tagmsg = got_object_tag_get_message(tag);
13831 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13832 fprintf(outfile, "%s", tagmsg);
13833 done:
13834 free(id_str);
13835 got_object_tag_close(tag);
13836 return err;
13839 static const struct got_error *
13840 cmd_cat(int argc, char *argv[])
13842 const struct got_error *error;
13843 struct got_repository *repo = NULL;
13844 struct got_worktree *worktree = NULL;
13845 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13846 const char *commit_id_str = NULL;
13847 struct got_object_id *id = NULL, *commit_id = NULL;
13848 struct got_commit_object *commit = NULL;
13849 int ch, obj_type, i, force_path = 0;
13850 struct got_reflist_head refs;
13851 int *pack_fds = NULL;
13853 TAILQ_INIT(&refs);
13855 #ifndef PROFILE
13856 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13857 NULL) == -1)
13858 err(1, "pledge");
13859 #endif
13861 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13862 switch (ch) {
13863 case 'c':
13864 commit_id_str = optarg;
13865 break;
13866 case 'P':
13867 force_path = 1;
13868 break;
13869 case 'r':
13870 repo_path = realpath(optarg, NULL);
13871 if (repo_path == NULL)
13872 return got_error_from_errno2("realpath",
13873 optarg);
13874 got_path_strip_trailing_slashes(repo_path);
13875 break;
13876 default:
13877 usage_cat();
13878 /* NOTREACHED */
13882 argc -= optind;
13883 argv += optind;
13885 cwd = getcwd(NULL, 0);
13886 if (cwd == NULL) {
13887 error = got_error_from_errno("getcwd");
13888 goto done;
13891 error = got_repo_pack_fds_open(&pack_fds);
13892 if (error != NULL)
13893 goto done;
13895 if (repo_path == NULL) {
13896 error = got_worktree_open(&worktree, cwd);
13897 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13898 goto done;
13899 if (worktree) {
13900 repo_path = strdup(
13901 got_worktree_get_repo_path(worktree));
13902 if (repo_path == NULL) {
13903 error = got_error_from_errno("strdup");
13904 goto done;
13907 /* Release work tree lock. */
13908 got_worktree_close(worktree);
13909 worktree = NULL;
13913 if (repo_path == NULL) {
13914 repo_path = strdup(cwd);
13915 if (repo_path == NULL)
13916 return got_error_from_errno("strdup");
13919 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13920 free(repo_path);
13921 if (error != NULL)
13922 goto done;
13924 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13925 if (error)
13926 goto done;
13928 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13929 if (error)
13930 goto done;
13932 if (commit_id_str == NULL)
13933 commit_id_str = GOT_REF_HEAD;
13934 error = got_repo_match_object_id(&commit_id, NULL,
13935 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13936 if (error)
13937 goto done;
13939 error = got_object_open_as_commit(&commit, repo, commit_id);
13940 if (error)
13941 goto done;
13943 for (i = 0; i < argc; i++) {
13944 if (force_path) {
13945 error = got_object_id_by_path(&id, repo, commit,
13946 argv[i]);
13947 if (error)
13948 break;
13949 } else {
13950 error = got_repo_match_object_id(&id, &label, argv[i],
13951 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13952 repo);
13953 if (error) {
13954 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13955 error->code != GOT_ERR_NOT_REF)
13956 break;
13957 error = got_object_id_by_path(&id, repo,
13958 commit, argv[i]);
13959 if (error)
13960 break;
13964 error = got_object_get_type(&obj_type, repo, id);
13965 if (error)
13966 break;
13968 switch (obj_type) {
13969 case GOT_OBJ_TYPE_BLOB:
13970 error = cat_blob(id, repo, stdout);
13971 break;
13972 case GOT_OBJ_TYPE_TREE:
13973 error = cat_tree(id, repo, stdout);
13974 break;
13975 case GOT_OBJ_TYPE_COMMIT:
13976 error = cat_commit(id, repo, stdout);
13977 break;
13978 case GOT_OBJ_TYPE_TAG:
13979 error = cat_tag(id, repo, stdout);
13980 break;
13981 default:
13982 error = got_error(GOT_ERR_OBJ_TYPE);
13983 break;
13985 if (error)
13986 break;
13987 free(label);
13988 label = NULL;
13989 free(id);
13990 id = NULL;
13992 done:
13993 free(label);
13994 free(id);
13995 free(commit_id);
13996 if (commit)
13997 got_object_commit_close(commit);
13998 if (worktree)
13999 got_worktree_close(worktree);
14000 if (repo) {
14001 const struct got_error *close_err = got_repo_close(repo);
14002 if (error == NULL)
14003 error = close_err;
14005 if (pack_fds) {
14006 const struct got_error *pack_err =
14007 got_repo_pack_fds_close(pack_fds);
14008 if (error == NULL)
14009 error = pack_err;
14012 got_ref_list_free(&refs);
14013 return error;
14016 __dead static void
14017 usage_info(void)
14019 fprintf(stderr, "usage: %s info [path ...]\n",
14020 getprogname());
14021 exit(1);
14024 static const struct got_error *
14025 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14026 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14027 struct got_object_id *commit_id)
14029 const struct got_error *err = NULL;
14030 char *id_str = NULL;
14031 char datebuf[128];
14032 struct tm mytm, *tm;
14033 struct got_pathlist_head *paths = arg;
14034 struct got_pathlist_entry *pe;
14037 * Clear error indication from any of the path arguments which
14038 * would cause this file index entry to be displayed.
14040 TAILQ_FOREACH(pe, paths, entry) {
14041 if (got_path_cmp(path, pe->path, strlen(path),
14042 pe->path_len) == 0 ||
14043 got_path_is_child(path, pe->path, pe->path_len))
14044 pe->data = NULL; /* no error */
14047 printf(GOT_COMMIT_SEP_STR);
14048 if (S_ISLNK(mode))
14049 printf("symlink: %s\n", path);
14050 else if (S_ISREG(mode)) {
14051 printf("file: %s\n", path);
14052 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14053 } else if (S_ISDIR(mode))
14054 printf("directory: %s\n", path);
14055 else
14056 printf("something: %s\n", path);
14058 tm = localtime_r(&mtime, &mytm);
14059 if (tm == NULL)
14060 return NULL;
14061 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14062 return got_error(GOT_ERR_NO_SPACE);
14063 printf("timestamp: %s\n", datebuf);
14065 if (blob_id) {
14066 err = got_object_id_str(&id_str, blob_id);
14067 if (err)
14068 return err;
14069 printf("based on blob: %s\n", id_str);
14070 free(id_str);
14073 if (staged_blob_id) {
14074 err = got_object_id_str(&id_str, staged_blob_id);
14075 if (err)
14076 return err;
14077 printf("based on staged blob: %s\n", id_str);
14078 free(id_str);
14081 if (commit_id) {
14082 err = got_object_id_str(&id_str, commit_id);
14083 if (err)
14084 return err;
14085 printf("based on commit: %s\n", id_str);
14086 free(id_str);
14089 return NULL;
14092 static const struct got_error *
14093 cmd_info(int argc, char *argv[])
14095 const struct got_error *error = NULL;
14096 struct got_worktree *worktree = NULL;
14097 char *cwd = NULL, *id_str = NULL;
14098 struct got_pathlist_head paths;
14099 char *uuidstr = NULL;
14100 int ch, show_files = 0;
14102 TAILQ_INIT(&paths);
14104 #ifndef PROFILE
14105 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14106 NULL) == -1)
14107 err(1, "pledge");
14108 #endif
14110 while ((ch = getopt(argc, argv, "")) != -1) {
14111 switch (ch) {
14112 default:
14113 usage_info();
14114 /* NOTREACHED */
14118 argc -= optind;
14119 argv += optind;
14121 cwd = getcwd(NULL, 0);
14122 if (cwd == NULL) {
14123 error = got_error_from_errno("getcwd");
14124 goto done;
14127 error = got_worktree_open(&worktree, cwd);
14128 if (error) {
14129 if (error->code == GOT_ERR_NOT_WORKTREE)
14130 error = wrap_not_worktree_error(error, "info", cwd);
14131 goto done;
14134 #ifndef PROFILE
14135 /* Remove "wpath cpath proc exec sendfd" promises. */
14136 if (pledge("stdio rpath flock unveil", NULL) == -1)
14137 err(1, "pledge");
14138 #endif
14139 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14140 if (error)
14141 goto done;
14143 if (argc >= 1) {
14144 error = get_worktree_paths_from_argv(&paths, argc, argv,
14145 worktree);
14146 if (error)
14147 goto done;
14148 show_files = 1;
14151 error = got_object_id_str(&id_str,
14152 got_worktree_get_base_commit_id(worktree));
14153 if (error)
14154 goto done;
14156 error = got_worktree_get_uuid(&uuidstr, worktree);
14157 if (error)
14158 goto done;
14160 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14161 printf("work tree base commit: %s\n", id_str);
14162 printf("work tree path prefix: %s\n",
14163 got_worktree_get_path_prefix(worktree));
14164 printf("work tree branch reference: %s\n",
14165 got_worktree_get_head_ref_name(worktree));
14166 printf("work tree UUID: %s\n", uuidstr);
14167 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14169 if (show_files) {
14170 struct got_pathlist_entry *pe;
14171 TAILQ_FOREACH(pe, &paths, entry) {
14172 if (pe->path_len == 0)
14173 continue;
14175 * Assume this path will fail. This will be corrected
14176 * in print_path_info() in case the path does suceeed.
14178 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14180 error = got_worktree_path_info(worktree, &paths,
14181 print_path_info, &paths, check_cancelled, NULL);
14182 if (error)
14183 goto done;
14184 TAILQ_FOREACH(pe, &paths, entry) {
14185 if (pe->data != NULL) {
14186 const struct got_error *perr;
14188 perr = pe->data;
14189 error = got_error_fmt(perr->code, "%s",
14190 pe->path);
14191 break;
14195 done:
14196 if (worktree)
14197 got_worktree_close(worktree);
14198 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14199 free(cwd);
14200 free(id_str);
14201 free(uuidstr);
14202 return error;