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;
521 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
522 initial_content_len, 1);
523 done:
524 if (fd != -1 && close(fd) == -1 && err == NULL)
525 err = got_error_from_errno2("close", *logmsg_path);
526 free(initial_content);
527 if (err) {
528 free(*logmsg_path);
529 *logmsg_path = NULL;
531 return err;
534 static const struct got_error *
535 import_progress(void *arg, const char *path)
537 printf("A %s\n", path);
538 return NULL;
541 static const struct got_error *
542 valid_author(const char *author)
544 const char *email = author;
546 /*
547 * Git' expects the author (or committer) to be in the form
548 * "name <email>", which are mostly free form (see the
549 * "committer" description in git-fast-import(1)). We're only
550 * doing this to avoid git's object parser breaking on commits
551 * we create.
552 */
554 while (*author && *author != '\n' && *author != '<' && *author != '>')
555 author++;
556 if (author != email && *author == '<' && *(author - 1) != ' ')
557 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
558 "between author name and email required", email);
559 if (*author++ != '<')
560 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
561 while (*author && *author != '\n' && *author != '<' && *author != '>')
562 author++;
563 if (strcmp(author, ">") != 0)
564 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
565 return NULL;
568 static const struct got_error *
569 get_author(char **author, struct got_repository *repo,
570 struct got_worktree *worktree)
572 const struct got_error *err = NULL;
573 const char *got_author = NULL, *name, *email;
574 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
576 *author = NULL;
578 if (worktree)
579 worktree_conf = got_worktree_get_gotconfig(worktree);
580 repo_conf = got_repo_get_gotconfig(repo);
582 /*
583 * Priority of potential author information sources, from most
584 * significant to least significant:
585 * 1) work tree's .got/got.conf file
586 * 2) repository's got.conf file
587 * 3) repository's git config file
588 * 4) environment variables
589 * 5) global git config files (in user's home directory or /etc)
590 */
592 if (worktree_conf)
593 got_author = got_gotconfig_get_author(worktree_conf);
594 if (got_author == NULL)
595 got_author = got_gotconfig_get_author(repo_conf);
596 if (got_author == NULL) {
597 name = got_repo_get_gitconfig_author_name(repo);
598 email = got_repo_get_gitconfig_author_email(repo);
599 if (name && email) {
600 if (asprintf(author, "%s <%s>", name, email) == -1)
601 return got_error_from_errno("asprintf");
602 return NULL;
605 got_author = getenv("GOT_AUTHOR");
606 if (got_author == NULL) {
607 name = got_repo_get_global_gitconfig_author_name(repo);
608 email = got_repo_get_global_gitconfig_author_email(
609 repo);
610 if (name && email) {
611 if (asprintf(author, "%s <%s>", name, email)
612 == -1)
613 return got_error_from_errno("asprintf");
614 return NULL;
616 /* TODO: Look up user in password database? */
617 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
621 *author = strdup(got_author);
622 if (*author == NULL)
623 return got_error_from_errno("strdup");
625 err = valid_author(*author);
626 if (err) {
627 free(*author);
628 *author = NULL;
630 return err;
633 static const struct got_error *
634 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
635 struct got_worktree *worktree)
637 const char *got_allowed_signers = NULL;
638 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
640 *allowed_signers = NULL;
642 if (worktree)
643 worktree_conf = got_worktree_get_gotconfig(worktree);
644 repo_conf = got_repo_get_gotconfig(repo);
646 /*
647 * Priority of potential author information sources, from most
648 * significant to least significant:
649 * 1) work tree's .got/got.conf file
650 * 2) repository's got.conf file
651 */
653 if (worktree_conf)
654 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
655 worktree_conf);
656 if (got_allowed_signers == NULL)
657 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
658 repo_conf);
660 if (got_allowed_signers) {
661 *allowed_signers = strdup(got_allowed_signers);
662 if (*allowed_signers == NULL)
663 return got_error_from_errno("strdup");
665 return NULL;
668 static const struct got_error *
669 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
670 struct got_worktree *worktree)
672 const char *got_revoked_signers = NULL;
673 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
675 *revoked_signers = NULL;
677 if (worktree)
678 worktree_conf = got_worktree_get_gotconfig(worktree);
679 repo_conf = got_repo_get_gotconfig(repo);
681 /*
682 * Priority of potential author information sources, from most
683 * significant to least significant:
684 * 1) work tree's .got/got.conf file
685 * 2) repository's got.conf file
686 */
688 if (worktree_conf)
689 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
690 worktree_conf);
691 if (got_revoked_signers == NULL)
692 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
693 repo_conf);
695 if (got_revoked_signers) {
696 *revoked_signers = strdup(got_revoked_signers);
697 if (*revoked_signers == NULL)
698 return got_error_from_errno("strdup");
700 return NULL;
703 static const char *
704 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
706 const char *got_signer_id = NULL;
707 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
709 if (worktree)
710 worktree_conf = got_worktree_get_gotconfig(worktree);
711 repo_conf = got_repo_get_gotconfig(repo);
713 /*
714 * Priority of potential author information sources, from most
715 * significant to least significant:
716 * 1) work tree's .got/got.conf file
717 * 2) repository's got.conf file
718 */
720 if (worktree_conf)
721 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
722 if (got_signer_id == NULL)
723 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
725 return got_signer_id;
728 static const struct got_error *
729 get_gitconfig_path(char **gitconfig_path)
731 const char *homedir = getenv("HOME");
733 *gitconfig_path = NULL;
734 if (homedir) {
735 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
736 return got_error_from_errno("asprintf");
739 return NULL;
742 static const struct got_error *
743 cmd_import(int argc, char *argv[])
745 const struct got_error *error = NULL;
746 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
747 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
748 const char *branch_name = NULL;
749 char *id_str = NULL, *logmsg_path = NULL;
750 char refname[PATH_MAX] = "refs/heads/";
751 struct got_repository *repo = NULL;
752 struct got_reference *branch_ref = NULL, *head_ref = NULL;
753 struct got_object_id *new_commit_id = NULL;
754 int ch, n = 0;
755 struct got_pathlist_head ignores;
756 struct got_pathlist_entry *pe;
757 int preserve_logmsg = 0;
758 int *pack_fds = NULL;
760 TAILQ_INIT(&ignores);
762 #ifndef PROFILE
763 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
764 "unveil",
765 NULL) == -1)
766 err(1, "pledge");
767 #endif
769 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
770 switch (ch) {
771 case 'b':
772 branch_name = optarg;
773 break;
774 case 'I':
775 if (optarg[0] == '\0')
776 break;
777 error = got_pathlist_insert(&pe, &ignores, optarg,
778 NULL);
779 if (error)
780 goto done;
781 break;
782 case 'm':
783 logmsg = strdup(optarg);
784 if (logmsg == NULL) {
785 error = got_error_from_errno("strdup");
786 goto done;
788 break;
789 case 'r':
790 repo_path = realpath(optarg, NULL);
791 if (repo_path == NULL) {
792 error = got_error_from_errno2("realpath",
793 optarg);
794 goto done;
796 break;
797 default:
798 usage_import();
799 /* NOTREACHED */
803 argc -= optind;
804 argv += optind;
806 if (argc != 1)
807 usage_import();
809 if (repo_path == NULL) {
810 repo_path = getcwd(NULL, 0);
811 if (repo_path == NULL)
812 return got_error_from_errno("getcwd");
814 got_path_strip_trailing_slashes(repo_path);
815 error = get_gitconfig_path(&gitconfig_path);
816 if (error)
817 goto done;
818 error = got_repo_pack_fds_open(&pack_fds);
819 if (error != NULL)
820 goto done;
821 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
822 if (error)
823 goto done;
825 error = get_author(&author, repo, NULL);
826 if (error)
827 return error;
829 /*
830 * Don't let the user create a branch name with a leading '-'.
831 * While technically a valid reference name, this case is usually
832 * an unintended typo.
833 */
834 if (branch_name && branch_name[0] == '-')
835 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
837 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
838 if (error && error->code != GOT_ERR_NOT_REF)
839 goto done;
841 if (branch_name)
842 n = strlcat(refname, branch_name, sizeof(refname));
843 else if (head_ref && got_ref_is_symbolic(head_ref))
844 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
845 sizeof(refname));
846 else
847 n = strlcat(refname, "main", sizeof(refname));
848 if (n >= sizeof(refname)) {
849 error = got_error(GOT_ERR_NO_SPACE);
850 goto done;
853 error = got_ref_open(&branch_ref, repo, refname, 0);
854 if (error) {
855 if (error->code != GOT_ERR_NOT_REF)
856 goto done;
857 } else {
858 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
859 "import target branch already exists");
860 goto done;
863 path_dir = realpath(argv[0], NULL);
864 if (path_dir == NULL) {
865 error = got_error_from_errno2("realpath", argv[0]);
866 goto done;
868 got_path_strip_trailing_slashes(path_dir);
870 /*
871 * unveil(2) traverses exec(2); if an editor is used we have
872 * to apply unveil after the log message has been written.
873 */
874 if (logmsg == NULL || strlen(logmsg) == 0) {
875 error = get_editor(&editor);
876 if (error)
877 goto done;
878 free(logmsg);
879 error = collect_import_msg(&logmsg, &logmsg_path, editor,
880 path_dir, refname);
881 if (error) {
882 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
883 logmsg_path != NULL)
884 preserve_logmsg = 1;
885 goto done;
889 if (unveil(path_dir, "r") != 0) {
890 error = got_error_from_errno2("unveil", path_dir);
891 if (logmsg_path)
892 preserve_logmsg = 1;
893 goto done;
896 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
897 if (error) {
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = got_repo_import(&new_commit_id, path_dir, logmsg,
904 author, &ignores, repo, import_progress, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_write(branch_ref, repo);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_object_id_str(&id_str, new_commit_id);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
933 if (error) {
934 if (error->code != GOT_ERR_NOT_REF) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
941 branch_ref);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_write(head_ref, repo);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
956 printf("Created branch %s with commit %s\n",
957 got_ref_get_name(branch_ref), id_str);
958 done:
959 if (pack_fds) {
960 const struct got_error *pack_err =
961 got_repo_pack_fds_close(pack_fds);
962 if (error == NULL)
963 error = pack_err;
965 if (preserve_logmsg) {
966 fprintf(stderr, "%s: log message preserved in %s\n",
967 getprogname(), logmsg_path);
968 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
969 error = got_error_from_errno2("unlink", logmsg_path);
970 free(logmsg);
971 free(logmsg_path);
972 free(repo_path);
973 free(editor);
974 free(new_commit_id);
975 free(id_str);
976 free(author);
977 free(gitconfig_path);
978 if (branch_ref)
979 got_ref_close(branch_ref);
980 if (head_ref)
981 got_ref_close(head_ref);
982 return error;
985 __dead static void
986 usage_clone(void)
988 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
989 "repository-URL [directory]\n", getprogname());
990 exit(1);
993 struct got_fetch_progress_arg {
994 char last_scaled_size[FMT_SCALED_STRSIZE];
995 int last_p_indexed;
996 int last_p_resolved;
997 int verbosity;
999 struct got_repository *repo;
1001 int create_configs;
1002 int configs_created;
1003 struct {
1004 struct got_pathlist_head *symrefs;
1005 struct got_pathlist_head *wanted_branches;
1006 struct got_pathlist_head *wanted_refs;
1007 const char *proto;
1008 const char *host;
1009 const char *port;
1010 const char *remote_repo_path;
1011 const char *git_url;
1012 int fetch_all_branches;
1013 int mirror_references;
1014 } config_info;
1017 /* XXX forward declaration */
1018 static const struct got_error *
1019 create_config_files(const char *proto, const char *host, const char *port,
1020 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1021 int mirror_references, struct got_pathlist_head *symrefs,
1022 struct got_pathlist_head *wanted_branches,
1023 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1025 static const struct got_error *
1026 fetch_progress(void *arg, const char *message, off_t packfile_size,
1027 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1029 const struct got_error *err = NULL;
1030 struct got_fetch_progress_arg *a = arg;
1031 char scaled_size[FMT_SCALED_STRSIZE];
1032 int p_indexed, p_resolved;
1033 int print_size = 0, print_indexed = 0, print_resolved = 0;
1036 * In order to allow a failed clone to be resumed with 'got fetch'
1037 * we try to create configuration files as soon as possible.
1038 * Once the server has sent information about its default branch
1039 * we have all required information.
1041 if (a->create_configs && !a->configs_created &&
1042 !TAILQ_EMPTY(a->config_info.symrefs)) {
1043 err = create_config_files(a->config_info.proto,
1044 a->config_info.host, a->config_info.port,
1045 a->config_info.remote_repo_path,
1046 a->config_info.git_url,
1047 a->config_info.fetch_all_branches,
1048 a->config_info.mirror_references,
1049 a->config_info.symrefs,
1050 a->config_info.wanted_branches,
1051 a->config_info.wanted_refs, a->repo);
1052 if (err)
1053 return err;
1054 a->configs_created = 1;
1057 if (a->verbosity < 0)
1058 return NULL;
1060 if (message && message[0] != '\0') {
1061 printf("\rserver: %s", message);
1062 fflush(stdout);
1063 return NULL;
1066 if (packfile_size > 0 || nobj_indexed > 0) {
1067 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1068 (a->last_scaled_size[0] == '\0' ||
1069 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1070 print_size = 1;
1071 if (strlcpy(a->last_scaled_size, scaled_size,
1072 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1073 return got_error(GOT_ERR_NO_SPACE);
1075 if (nobj_indexed > 0) {
1076 p_indexed = (nobj_indexed * 100) / nobj_total;
1077 if (p_indexed != a->last_p_indexed) {
1078 a->last_p_indexed = p_indexed;
1079 print_indexed = 1;
1080 print_size = 1;
1083 if (nobj_resolved > 0) {
1084 p_resolved = (nobj_resolved * 100) /
1085 (nobj_total - nobj_loose);
1086 if (p_resolved != a->last_p_resolved) {
1087 a->last_p_resolved = p_resolved;
1088 print_resolved = 1;
1089 print_indexed = 1;
1090 print_size = 1;
1095 if (print_size || print_indexed || print_resolved)
1096 printf("\r");
1097 if (print_size)
1098 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1099 if (print_indexed)
1100 printf("; indexing %d%%", p_indexed);
1101 if (print_resolved)
1102 printf("; resolving deltas %d%%", p_resolved);
1103 if (print_size || print_indexed || print_resolved)
1104 fflush(stdout);
1106 return NULL;
1109 static const struct got_error *
1110 create_symref(const char *refname, struct got_reference *target_ref,
1111 int verbosity, struct got_repository *repo)
1113 const struct got_error *err;
1114 struct got_reference *head_symref;
1116 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1117 if (err)
1118 return err;
1120 err = got_ref_write(head_symref, repo);
1121 if (err == NULL && verbosity > 0) {
1122 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1123 got_ref_get_name(target_ref));
1125 got_ref_close(head_symref);
1126 return err;
1129 static const struct got_error *
1130 list_remote_refs(struct got_pathlist_head *symrefs,
1131 struct got_pathlist_head *refs)
1133 const struct got_error *err;
1134 struct got_pathlist_entry *pe;
1136 TAILQ_FOREACH(pe, symrefs, entry) {
1137 const char *refname = pe->path;
1138 const char *targetref = pe->data;
1140 printf("%s: %s\n", refname, targetref);
1143 TAILQ_FOREACH(pe, refs, entry) {
1144 const char *refname = pe->path;
1145 struct got_object_id *id = pe->data;
1146 char *id_str;
1148 err = got_object_id_str(&id_str, id);
1149 if (err)
1150 return err;
1151 printf("%s: %s\n", refname, id_str);
1152 free(id_str);
1155 return NULL;
1158 static const struct got_error *
1159 create_ref(const char *refname, struct got_object_id *id,
1160 int verbosity, struct got_repository *repo)
1162 const struct got_error *err = NULL;
1163 struct got_reference *ref;
1164 char *id_str;
1166 err = got_object_id_str(&id_str, id);
1167 if (err)
1168 return err;
1170 err = got_ref_alloc(&ref, refname, id);
1171 if (err)
1172 goto done;
1174 err = got_ref_write(ref, repo);
1175 got_ref_close(ref);
1177 if (err == NULL && verbosity >= 0)
1178 printf("Created reference %s: %s\n", refname, id_str);
1179 done:
1180 free(id_str);
1181 return err;
1184 static int
1185 match_wanted_ref(const char *refname, const char *wanted_ref)
1187 if (strncmp(refname, "refs/", 5) != 0)
1188 return 0;
1189 refname += 5;
1192 * Prevent fetching of references that won't make any
1193 * sense outside of the remote repository's context.
1195 if (strncmp(refname, "got/", 4) == 0)
1196 return 0;
1197 if (strncmp(refname, "remotes/", 8) == 0)
1198 return 0;
1200 if (strncmp(wanted_ref, "refs/", 5) == 0)
1201 wanted_ref += 5;
1203 /* Allow prefix match. */
1204 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1205 return 1;
1207 /* Allow exact match. */
1208 return (strcmp(refname, wanted_ref) == 0);
1211 static int
1212 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1214 struct got_pathlist_entry *pe;
1216 TAILQ_FOREACH(pe, wanted_refs, entry) {
1217 if (match_wanted_ref(refname, pe->path))
1218 return 1;
1221 return 0;
1224 static const struct got_error *
1225 create_wanted_ref(const char *refname, struct got_object_id *id,
1226 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1228 const struct got_error *err;
1229 char *remote_refname;
1231 if (strncmp("refs/", refname, 5) == 0)
1232 refname += 5;
1234 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1235 remote_repo_name, refname) == -1)
1236 return got_error_from_errno("asprintf");
1238 err = create_ref(remote_refname, id, verbosity, repo);
1239 free(remote_refname);
1240 return err;
1243 static const struct got_error *
1244 create_gotconfig(const char *proto, const char *host, const char *port,
1245 const char *remote_repo_path, const char *default_branch,
1246 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1247 struct got_pathlist_head *wanted_refs, int mirror_references,
1248 struct got_repository *repo)
1250 const struct got_error *err = NULL;
1251 char *gotconfig_path = NULL;
1252 char *gotconfig = NULL;
1253 FILE *gotconfig_file = NULL;
1254 const char *branchname = NULL;
1255 char *branches = NULL, *refs = NULL;
1256 ssize_t n;
1258 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1259 struct got_pathlist_entry *pe;
1260 TAILQ_FOREACH(pe, wanted_branches, entry) {
1261 char *s;
1262 branchname = pe->path;
1263 if (strncmp(branchname, "refs/heads/", 11) == 0)
1264 branchname += 11;
1265 if (asprintf(&s, "%s\"%s\" ",
1266 branches ? branches : "", branchname) == -1) {
1267 err = got_error_from_errno("asprintf");
1268 goto done;
1270 free(branches);
1271 branches = s;
1273 } else if (!fetch_all_branches && default_branch) {
1274 branchname = default_branch;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1278 err = got_error_from_errno("asprintf");
1279 goto done;
1282 if (!TAILQ_EMPTY(wanted_refs)) {
1283 struct got_pathlist_entry *pe;
1284 TAILQ_FOREACH(pe, wanted_refs, entry) {
1285 char *s;
1286 const char *refname = pe->path;
1287 if (strncmp(refname, "refs/", 5) == 0)
1288 branchname += 5;
1289 if (asprintf(&s, "%s\"%s\" ",
1290 refs ? refs : "", refname) == -1) {
1291 err = got_error_from_errno("asprintf");
1292 goto done;
1294 free(refs);
1295 refs = s;
1299 /* Create got.conf(5). */
1300 gotconfig_path = got_repo_get_path_gotconfig(repo);
1301 if (gotconfig_path == NULL) {
1302 err = got_error_from_errno("got_repo_get_path_gotconfig");
1303 goto done;
1305 gotconfig_file = fopen(gotconfig_path, "ae");
1306 if (gotconfig_file == NULL) {
1307 err = got_error_from_errno2("fopen", gotconfig_path);
1308 goto done;
1310 if (asprintf(&gotconfig,
1311 "remote \"%s\" {\n"
1312 "\tserver %s\n"
1313 "\tprotocol %s\n"
1314 "%s%s%s"
1315 "\trepository \"%s\"\n"
1316 "%s%s%s"
1317 "%s%s%s"
1318 "%s"
1319 "%s"
1320 "}\n",
1321 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1322 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1323 remote_repo_path, branches ? "\tbranch { " : "",
1324 branches ? branches : "", branches ? "}\n" : "",
1325 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1326 mirror_references ? "\tmirror_references yes\n" : "",
1327 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1328 err = got_error_from_errno("asprintf");
1329 goto done;
1331 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1332 if (n != strlen(gotconfig)) {
1333 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1334 goto done;
1337 done:
1338 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1339 err = got_error_from_errno2("fclose", gotconfig_path);
1340 free(gotconfig_path);
1341 free(branches);
1342 return err;
1345 static const struct got_error *
1346 create_gitconfig(const char *git_url, const char *default_branch,
1347 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1348 struct got_pathlist_head *wanted_refs, int mirror_references,
1349 struct got_repository *repo)
1351 const struct got_error *err = NULL;
1352 char *gitconfig_path = NULL;
1353 char *gitconfig = NULL;
1354 FILE *gitconfig_file = NULL;
1355 char *branches = NULL, *refs = NULL;
1356 const char *branchname;
1357 ssize_t n;
1359 /* Create a config file Git can understand. */
1360 gitconfig_path = got_repo_get_path_gitconfig(repo);
1361 if (gitconfig_path == NULL) {
1362 err = got_error_from_errno("got_repo_get_path_gitconfig");
1363 goto done;
1365 gitconfig_file = fopen(gitconfig_path, "ae");
1366 if (gitconfig_file == NULL) {
1367 err = got_error_from_errno2("fopen", gitconfig_path);
1368 goto done;
1370 if (fetch_all_branches) {
1371 if (mirror_references) {
1372 if (asprintf(&branches,
1373 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1374 err = got_error_from_errno("asprintf");
1375 goto done;
1377 } else if (asprintf(&branches,
1378 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1379 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1380 err = got_error_from_errno("asprintf");
1381 goto done;
1383 } else if (!TAILQ_EMPTY(wanted_branches)) {
1384 struct got_pathlist_entry *pe;
1385 TAILQ_FOREACH(pe, wanted_branches, entry) {
1386 char *s;
1387 branchname = pe->path;
1388 if (strncmp(branchname, "refs/heads/", 11) == 0)
1389 branchname += 11;
1390 if (mirror_references) {
1391 if (asprintf(&s,
1392 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1393 branches ? branches : "",
1394 branchname, branchname) == -1) {
1395 err = got_error_from_errno("asprintf");
1396 goto done;
1398 } else if (asprintf(&s,
1399 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1400 branches ? branches : "",
1401 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1402 branchname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 free(branches);
1407 branches = s;
1409 } else {
1411 * If the server specified a default branch, use just that one.
1412 * Otherwise fall back to fetching all branches on next fetch.
1414 if (default_branch) {
1415 branchname = default_branch;
1416 if (strncmp(branchname, "refs/heads/", 11) == 0)
1417 branchname += 11;
1418 } else
1419 branchname = "*"; /* fall back to all branches */
1420 if (mirror_references) {
1421 if (asprintf(&branches,
1422 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1423 branchname, branchname) == -1) {
1424 err = got_error_from_errno("asprintf");
1425 goto done;
1427 } else if (asprintf(&branches,
1428 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1429 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1430 branchname) == -1) {
1431 err = got_error_from_errno("asprintf");
1432 goto done;
1435 if (!TAILQ_EMPTY(wanted_refs)) {
1436 struct got_pathlist_entry *pe;
1437 TAILQ_FOREACH(pe, wanted_refs, entry) {
1438 char *s;
1439 const char *refname = pe->path;
1440 if (strncmp(refname, "refs/", 5) == 0)
1441 refname += 5;
1442 if (mirror_references) {
1443 if (asprintf(&s,
1444 "%s\tfetch = refs/%s:refs/%s\n",
1445 refs ? refs : "", refname, refname) == -1) {
1446 err = got_error_from_errno("asprintf");
1447 goto done;
1449 } else if (asprintf(&s,
1450 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1451 refs ? refs : "",
1452 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1453 refname) == -1) {
1454 err = got_error_from_errno("asprintf");
1455 goto done;
1457 free(refs);
1458 refs = s;
1462 if (asprintf(&gitconfig,
1463 "[remote \"%s\"]\n"
1464 "\turl = %s\n"
1465 "%s"
1466 "%s"
1467 "\tfetch = refs/tags/*:refs/tags/*\n",
1468 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1469 refs ? refs : "") == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1474 if (n != strlen(gitconfig)) {
1475 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1476 goto done;
1478 done:
1479 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1480 err = got_error_from_errno2("fclose", gitconfig_path);
1481 free(gitconfig_path);
1482 free(branches);
1483 return err;
1486 static const struct got_error *
1487 create_config_files(const char *proto, const char *host, const char *port,
1488 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1489 int mirror_references, struct got_pathlist_head *symrefs,
1490 struct got_pathlist_head *wanted_branches,
1491 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1493 const struct got_error *err = NULL;
1494 const char *default_branch = NULL;
1495 struct got_pathlist_entry *pe;
1498 * If we asked for a set of wanted branches then use the first
1499 * one of those.
1501 if (!TAILQ_EMPTY(wanted_branches)) {
1502 pe = TAILQ_FIRST(wanted_branches);
1503 default_branch = pe->path;
1504 } else {
1505 /* First HEAD ref listed by server is the default branch. */
1506 TAILQ_FOREACH(pe, symrefs, entry) {
1507 const char *refname = pe->path;
1508 const char *target = pe->data;
1510 if (strcmp(refname, GOT_REF_HEAD) != 0)
1511 continue;
1513 default_branch = target;
1514 break;
1518 /* Create got.conf(5). */
1519 err = create_gotconfig(proto, host, port, remote_repo_path,
1520 default_branch, fetch_all_branches, wanted_branches,
1521 wanted_refs, mirror_references, repo);
1522 if (err)
1523 return err;
1525 /* Create a config file Git can understand. */
1526 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1527 wanted_branches, wanted_refs, mirror_references, repo);
1530 static const struct got_error *
1531 cmd_clone(int argc, char *argv[])
1533 const struct got_error *error = NULL;
1534 const char *uri, *dirname;
1535 char *proto, *host, *port, *repo_name, *server_path;
1536 char *default_destdir = NULL, *id_str = NULL;
1537 const char *repo_path;
1538 struct got_repository *repo = NULL;
1539 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1540 struct got_pathlist_entry *pe;
1541 struct got_object_id *pack_hash = NULL;
1542 int ch, fetchfd = -1, fetchstatus;
1543 pid_t fetchpid = -1;
1544 struct got_fetch_progress_arg fpa;
1545 char *git_url = NULL;
1546 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1547 int bflag = 0, list_refs_only = 0;
1548 int *pack_fds = NULL;
1550 TAILQ_INIT(&refs);
1551 TAILQ_INIT(&symrefs);
1552 TAILQ_INIT(&wanted_branches);
1553 TAILQ_INIT(&wanted_refs);
1555 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1556 switch (ch) {
1557 case 'a':
1558 fetch_all_branches = 1;
1559 break;
1560 case 'b':
1561 error = got_pathlist_append(&wanted_branches,
1562 optarg, NULL);
1563 if (error)
1564 return error;
1565 bflag = 1;
1566 break;
1567 case 'l':
1568 list_refs_only = 1;
1569 break;
1570 case 'm':
1571 mirror_references = 1;
1572 break;
1573 case 'q':
1574 verbosity = -1;
1575 break;
1576 case 'R':
1577 error = got_pathlist_append(&wanted_refs,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 break;
1582 case 'v':
1583 if (verbosity < 0)
1584 verbosity = 0;
1585 else if (verbosity < 3)
1586 verbosity++;
1587 break;
1588 default:
1589 usage_clone();
1590 break;
1593 argc -= optind;
1594 argv += optind;
1596 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1597 option_conflict('a', 'b');
1598 if (list_refs_only) {
1599 if (!TAILQ_EMPTY(&wanted_branches))
1600 option_conflict('l', 'b');
1601 if (fetch_all_branches)
1602 option_conflict('l', 'a');
1603 if (mirror_references)
1604 option_conflict('l', 'm');
1605 if (!TAILQ_EMPTY(&wanted_refs))
1606 option_conflict('l', 'R');
1609 uri = argv[0];
1611 if (argc == 1)
1612 dirname = NULL;
1613 else if (argc == 2)
1614 dirname = argv[1];
1615 else
1616 usage_clone();
1618 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1619 &repo_name, uri);
1620 if (error)
1621 goto done;
1623 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1624 host, port ? ":" : "", port ? port : "",
1625 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1626 error = got_error_from_errno("asprintf");
1627 goto done;
1630 if (strcmp(proto, "git") == 0) {
1631 #ifndef PROFILE
1632 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1633 "sendfd dns inet unveil", NULL) == -1)
1634 err(1, "pledge");
1635 #endif
1636 } else if (strcmp(proto, "git+ssh") == 0 ||
1637 strcmp(proto, "ssh") == 0) {
1638 #ifndef PROFILE
1639 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1640 "sendfd unveil", NULL) == -1)
1641 err(1, "pledge");
1642 #endif
1643 } else if (strcmp(proto, "http") == 0 ||
1644 strcmp(proto, "git+http") == 0) {
1645 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1646 goto done;
1647 } else {
1648 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1649 goto done;
1651 if (dirname == NULL) {
1652 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1653 error = got_error_from_errno("asprintf");
1654 goto done;
1656 repo_path = default_destdir;
1657 } else
1658 repo_path = dirname;
1660 if (!list_refs_only) {
1661 error = got_path_mkdir(repo_path);
1662 if (error &&
1663 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1664 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1665 goto done;
1666 if (!got_path_dir_is_empty(repo_path)) {
1667 error = got_error_path(repo_path,
1668 GOT_ERR_DIR_NOT_EMPTY);
1669 goto done;
1673 error = got_dial_apply_unveil(proto);
1674 if (error)
1675 goto done;
1677 error = apply_unveil(repo_path, 0, NULL);
1678 if (error)
1679 goto done;
1681 if (verbosity >= 0)
1682 printf("Connecting to %s\n", git_url);
1684 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1685 server_path, verbosity);
1686 if (error)
1687 goto done;
1689 if (!list_refs_only) {
1690 error = got_repo_init(repo_path, NULL);
1691 if (error)
1692 goto done;
1693 error = got_repo_pack_fds_open(&pack_fds);
1694 if (error != NULL)
1695 goto done;
1696 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1697 if (error)
1698 goto done;
1701 fpa.last_scaled_size[0] = '\0';
1702 fpa.last_p_indexed = -1;
1703 fpa.last_p_resolved = -1;
1704 fpa.verbosity = verbosity;
1705 fpa.create_configs = 1;
1706 fpa.configs_created = 0;
1707 fpa.repo = repo;
1708 fpa.config_info.symrefs = &symrefs;
1709 fpa.config_info.wanted_branches = &wanted_branches;
1710 fpa.config_info.wanted_refs = &wanted_refs;
1711 fpa.config_info.proto = proto;
1712 fpa.config_info.host = host;
1713 fpa.config_info.port = port;
1714 fpa.config_info.remote_repo_path = server_path;
1715 fpa.config_info.git_url = git_url;
1716 fpa.config_info.fetch_all_branches = fetch_all_branches;
1717 fpa.config_info.mirror_references = mirror_references;
1718 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1719 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1720 fetch_all_branches, &wanted_branches, &wanted_refs,
1721 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1722 fetch_progress, &fpa);
1723 if (error)
1724 goto done;
1726 if (list_refs_only) {
1727 error = list_remote_refs(&symrefs, &refs);
1728 goto done;
1731 if (pack_hash == NULL) {
1732 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1733 "server sent an empty pack file");
1734 goto done;
1736 error = got_object_id_str(&id_str, pack_hash);
1737 if (error)
1738 goto done;
1739 if (verbosity >= 0)
1740 printf("\nFetched %s.pack\n", id_str);
1741 free(id_str);
1743 /* Set up references provided with the pack file. */
1744 TAILQ_FOREACH(pe, &refs, entry) {
1745 const char *refname = pe->path;
1746 struct got_object_id *id = pe->data;
1747 char *remote_refname;
1749 if (is_wanted_ref(&wanted_refs, refname) &&
1750 !mirror_references) {
1751 error = create_wanted_ref(refname, id,
1752 GOT_FETCH_DEFAULT_REMOTE_NAME,
1753 verbosity - 1, repo);
1754 if (error)
1755 goto done;
1756 continue;
1759 error = create_ref(refname, id, verbosity - 1, repo);
1760 if (error)
1761 goto done;
1763 if (mirror_references)
1764 continue;
1766 if (strncmp("refs/heads/", refname, 11) != 0)
1767 continue;
1769 if (asprintf(&remote_refname,
1770 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1771 refname + 11) == -1) {
1772 error = got_error_from_errno("asprintf");
1773 goto done;
1775 error = create_ref(remote_refname, id, verbosity - 1, repo);
1776 free(remote_refname);
1777 if (error)
1778 goto done;
1781 /* Set the HEAD reference if the server provided one. */
1782 TAILQ_FOREACH(pe, &symrefs, entry) {
1783 struct got_reference *target_ref;
1784 const char *refname = pe->path;
1785 const char *target = pe->data;
1786 char *remote_refname = NULL, *remote_target = NULL;
1788 if (strcmp(refname, GOT_REF_HEAD) != 0)
1789 continue;
1791 error = got_ref_open(&target_ref, repo, target, 0);
1792 if (error) {
1793 if (error->code == GOT_ERR_NOT_REF) {
1794 error = NULL;
1795 continue;
1797 goto done;
1800 error = create_symref(refname, target_ref, verbosity, repo);
1801 got_ref_close(target_ref);
1802 if (error)
1803 goto done;
1805 if (mirror_references)
1806 continue;
1808 if (strncmp("refs/heads/", target, 11) != 0)
1809 continue;
1811 if (asprintf(&remote_refname,
1812 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1813 refname) == -1) {
1814 error = got_error_from_errno("asprintf");
1815 goto done;
1817 if (asprintf(&remote_target,
1818 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1819 target + 11) == -1) {
1820 error = got_error_from_errno("asprintf");
1821 free(remote_refname);
1822 goto done;
1824 error = got_ref_open(&target_ref, repo, remote_target, 0);
1825 if (error) {
1826 free(remote_refname);
1827 free(remote_target);
1828 if (error->code == GOT_ERR_NOT_REF) {
1829 error = NULL;
1830 continue;
1832 goto done;
1834 error = create_symref(remote_refname, target_ref,
1835 verbosity - 1, repo);
1836 free(remote_refname);
1837 free(remote_target);
1838 got_ref_close(target_ref);
1839 if (error)
1840 goto done;
1842 if (pe == NULL) {
1844 * We failed to set the HEAD reference. If we asked for
1845 * a set of wanted branches use the first of one of those
1846 * which could be fetched instead.
1848 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1849 const char *target = pe->path;
1850 struct got_reference *target_ref;
1852 error = got_ref_open(&target_ref, repo, target, 0);
1853 if (error) {
1854 if (error->code == GOT_ERR_NOT_REF) {
1855 error = NULL;
1856 continue;
1858 goto done;
1861 error = create_symref(GOT_REF_HEAD, target_ref,
1862 verbosity, repo);
1863 got_ref_close(target_ref);
1864 if (error)
1865 goto done;
1866 break;
1869 if (!fpa.configs_created && pe != NULL) {
1870 error = create_config_files(fpa.config_info.proto,
1871 fpa.config_info.host, fpa.config_info.port,
1872 fpa.config_info.remote_repo_path,
1873 fpa.config_info.git_url,
1874 fpa.config_info.fetch_all_branches,
1875 fpa.config_info.mirror_references,
1876 fpa.config_info.symrefs,
1877 fpa.config_info.wanted_branches,
1878 fpa.config_info.wanted_refs, fpa.repo);
1879 if (error)
1880 goto done;
1884 if (verbosity >= 0)
1885 printf("Created %s repository '%s'\n",
1886 mirror_references ? "mirrored" : "cloned", repo_path);
1887 done:
1888 if (pack_fds) {
1889 const struct got_error *pack_err =
1890 got_repo_pack_fds_close(pack_fds);
1891 if (error == NULL)
1892 error = pack_err;
1894 if (fetchpid > 0) {
1895 if (kill(fetchpid, SIGTERM) == -1)
1896 error = got_error_from_errno("kill");
1897 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1898 error = got_error_from_errno("waitpid");
1900 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1901 error = got_error_from_errno("close");
1902 if (repo) {
1903 const struct got_error *close_err = got_repo_close(repo);
1904 if (error == NULL)
1905 error = close_err;
1907 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1908 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1909 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1910 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1911 free(pack_hash);
1912 free(proto);
1913 free(host);
1914 free(port);
1915 free(server_path);
1916 free(repo_name);
1917 free(default_destdir);
1918 free(git_url);
1919 return error;
1922 static const struct got_error *
1923 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1924 int replace_tags, int verbosity, struct got_repository *repo)
1926 const struct got_error *err = NULL;
1927 char *new_id_str = NULL;
1928 struct got_object_id *old_id = NULL;
1930 err = got_object_id_str(&new_id_str, new_id);
1931 if (err)
1932 goto done;
1934 if (!replace_tags &&
1935 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1936 err = got_ref_resolve(&old_id, repo, ref);
1937 if (err)
1938 goto done;
1939 if (got_object_id_cmp(old_id, new_id) == 0)
1940 goto done;
1941 if (verbosity >= 0) {
1942 printf("Rejecting update of existing tag %s: %s\n",
1943 got_ref_get_name(ref), new_id_str);
1945 goto done;
1948 if (got_ref_is_symbolic(ref)) {
1949 if (verbosity >= 0) {
1950 printf("Replacing reference %s: %s\n",
1951 got_ref_get_name(ref),
1952 got_ref_get_symref_target(ref));
1954 err = got_ref_change_symref_to_ref(ref, new_id);
1955 if (err)
1956 goto done;
1957 err = got_ref_write(ref, repo);
1958 if (err)
1959 goto done;
1960 } else {
1961 err = got_ref_resolve(&old_id, repo, ref);
1962 if (err)
1963 goto done;
1964 if (got_object_id_cmp(old_id, new_id) == 0)
1965 goto done;
1967 err = got_ref_change_ref(ref, new_id);
1968 if (err)
1969 goto done;
1970 err = got_ref_write(ref, repo);
1971 if (err)
1972 goto done;
1975 if (verbosity >= 0)
1976 printf("Updated %s: %s\n", got_ref_get_name(ref),
1977 new_id_str);
1978 done:
1979 free(old_id);
1980 free(new_id_str);
1981 return err;
1984 static const struct got_error *
1985 update_symref(const char *refname, struct got_reference *target_ref,
1986 int verbosity, struct got_repository *repo)
1988 const struct got_error *err = NULL, *unlock_err;
1989 struct got_reference *symref;
1990 int symref_is_locked = 0;
1992 err = got_ref_open(&symref, repo, refname, 1);
1993 if (err) {
1994 if (err->code != GOT_ERR_NOT_REF)
1995 return err;
1996 err = got_ref_alloc_symref(&symref, refname, target_ref);
1997 if (err)
1998 goto done;
2000 err = got_ref_write(symref, repo);
2001 if (err)
2002 goto done;
2004 if (verbosity >= 0)
2005 printf("Created reference %s: %s\n",
2006 got_ref_get_name(symref),
2007 got_ref_get_symref_target(symref));
2008 } else {
2009 symref_is_locked = 1;
2011 if (strcmp(got_ref_get_symref_target(symref),
2012 got_ref_get_name(target_ref)) == 0)
2013 goto done;
2015 err = got_ref_change_symref(symref,
2016 got_ref_get_name(target_ref));
2017 if (err)
2018 goto done;
2020 err = got_ref_write(symref, repo);
2021 if (err)
2022 goto done;
2024 if (verbosity >= 0)
2025 printf("Updated %s: %s\n", got_ref_get_name(symref),
2026 got_ref_get_symref_target(symref));
2029 done:
2030 if (symref_is_locked) {
2031 unlock_err = got_ref_unlock(symref);
2032 if (unlock_err && err == NULL)
2033 err = unlock_err;
2035 got_ref_close(symref);
2036 return err;
2039 __dead static void
2040 usage_fetch(void)
2042 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2043 "[-R reference] [-r repository-path] [remote-repository]\n",
2044 getprogname());
2045 exit(1);
2048 static const struct got_error *
2049 delete_missing_ref(struct got_reference *ref,
2050 int verbosity, struct got_repository *repo)
2052 const struct got_error *err = NULL;
2053 struct got_object_id *id = NULL;
2054 char *id_str = NULL;
2056 if (got_ref_is_symbolic(ref)) {
2057 err = got_ref_delete(ref, repo);
2058 if (err)
2059 return err;
2060 if (verbosity >= 0) {
2061 printf("Deleted %s: %s\n",
2062 got_ref_get_name(ref),
2063 got_ref_get_symref_target(ref));
2065 } else {
2066 err = got_ref_resolve(&id, repo, ref);
2067 if (err)
2068 return err;
2069 err = got_object_id_str(&id_str, id);
2070 if (err)
2071 goto done;
2073 err = got_ref_delete(ref, repo);
2074 if (err)
2075 goto done;
2076 if (verbosity >= 0) {
2077 printf("Deleted %s: %s\n",
2078 got_ref_get_name(ref), id_str);
2081 done:
2082 free(id);
2083 free(id_str);
2084 return err;
2087 static const struct got_error *
2088 delete_missing_refs(struct got_pathlist_head *their_refs,
2089 struct got_pathlist_head *their_symrefs,
2090 const struct got_remote_repo *remote,
2091 int verbosity, struct got_repository *repo)
2093 const struct got_error *err = NULL, *unlock_err;
2094 struct got_reflist_head my_refs;
2095 struct got_reflist_entry *re;
2096 struct got_pathlist_entry *pe;
2097 char *remote_namespace = NULL;
2098 char *local_refname = NULL;
2100 TAILQ_INIT(&my_refs);
2102 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2103 == -1)
2104 return got_error_from_errno("asprintf");
2106 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2107 if (err)
2108 goto done;
2110 TAILQ_FOREACH(re, &my_refs, entry) {
2111 const char *refname = got_ref_get_name(re->ref);
2112 const char *their_refname;
2114 if (remote->mirror_references) {
2115 their_refname = refname;
2116 } else {
2117 if (strncmp(refname, remote_namespace,
2118 strlen(remote_namespace)) == 0) {
2119 if (strcmp(refname + strlen(remote_namespace),
2120 GOT_REF_HEAD) == 0)
2121 continue;
2122 if (asprintf(&local_refname, "refs/heads/%s",
2123 refname + strlen(remote_namespace)) == -1) {
2124 err = got_error_from_errno("asprintf");
2125 goto done;
2127 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2128 continue;
2130 their_refname = local_refname;
2133 TAILQ_FOREACH(pe, their_refs, entry) {
2134 if (strcmp(their_refname, pe->path) == 0)
2135 break;
2137 if (pe != NULL)
2138 continue;
2140 TAILQ_FOREACH(pe, their_symrefs, entry) {
2141 if (strcmp(their_refname, pe->path) == 0)
2142 break;
2144 if (pe != NULL)
2145 continue;
2147 err = delete_missing_ref(re->ref, verbosity, repo);
2148 if (err)
2149 break;
2151 if (local_refname) {
2152 struct got_reference *ref;
2153 err = got_ref_open(&ref, repo, local_refname, 1);
2154 if (err) {
2155 if (err->code != GOT_ERR_NOT_REF)
2156 break;
2157 free(local_refname);
2158 local_refname = NULL;
2159 continue;
2161 err = delete_missing_ref(ref, verbosity, repo);
2162 if (err)
2163 break;
2164 unlock_err = got_ref_unlock(ref);
2165 got_ref_close(ref);
2166 if (unlock_err && err == NULL) {
2167 err = unlock_err;
2168 break;
2171 free(local_refname);
2172 local_refname = NULL;
2175 done:
2176 got_ref_list_free(&my_refs);
2177 free(remote_namespace);
2178 free(local_refname);
2179 return err;
2182 static const struct got_error *
2183 update_wanted_ref(const char *refname, struct got_object_id *id,
2184 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2186 const struct got_error *err, *unlock_err;
2187 char *remote_refname;
2188 struct got_reference *ref;
2190 if (strncmp("refs/", refname, 5) == 0)
2191 refname += 5;
2193 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2194 remote_repo_name, refname) == -1)
2195 return got_error_from_errno("asprintf");
2197 err = got_ref_open(&ref, repo, remote_refname, 1);
2198 if (err) {
2199 if (err->code != GOT_ERR_NOT_REF)
2200 goto done;
2201 err = create_ref(remote_refname, id, verbosity, repo);
2202 } else {
2203 err = update_ref(ref, id, 0, verbosity, repo);
2204 unlock_err = got_ref_unlock(ref);
2205 if (unlock_err && err == NULL)
2206 err = unlock_err;
2207 got_ref_close(ref);
2209 done:
2210 free(remote_refname);
2211 return err;
2214 static const struct got_error *
2215 delete_ref(struct got_repository *repo, struct got_reference *ref)
2217 const struct got_error *err = NULL;
2218 struct got_object_id *id = NULL;
2219 char *id_str = NULL;
2220 const char *target;
2222 if (got_ref_is_symbolic(ref)) {
2223 target = got_ref_get_symref_target(ref);
2224 } else {
2225 err = got_ref_resolve(&id, repo, ref);
2226 if (err)
2227 goto done;
2228 err = got_object_id_str(&id_str, id);
2229 if (err)
2230 goto done;
2231 target = id_str;
2234 err = got_ref_delete(ref, repo);
2235 if (err)
2236 goto done;
2238 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2239 done:
2240 free(id);
2241 free(id_str);
2242 return err;
2245 static const struct got_error *
2246 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2248 const struct got_error *err = NULL;
2249 struct got_reflist_head refs;
2250 struct got_reflist_entry *re;
2251 char *prefix;
2253 TAILQ_INIT(&refs);
2255 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2256 err = got_error_from_errno("asprintf");
2257 goto done;
2259 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2260 if (err)
2261 goto done;
2263 TAILQ_FOREACH(re, &refs, entry)
2264 delete_ref(repo, re->ref);
2265 done:
2266 got_ref_list_free(&refs);
2267 return err;
2270 static const struct got_error *
2271 cmd_fetch(int argc, char *argv[])
2273 const struct got_error *error = NULL, *unlock_err;
2274 char *cwd = NULL, *repo_path = NULL;
2275 const char *remote_name;
2276 char *proto = NULL, *host = NULL, *port = NULL;
2277 char *repo_name = NULL, *server_path = NULL;
2278 const struct got_remote_repo *remotes, *remote = NULL;
2279 int nremotes;
2280 char *id_str = NULL;
2281 struct got_repository *repo = NULL;
2282 struct got_worktree *worktree = NULL;
2283 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2284 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2285 struct got_pathlist_entry *pe;
2286 struct got_reflist_head remote_refs;
2287 struct got_reflist_entry *re;
2288 struct got_object_id *pack_hash = NULL;
2289 int i, ch, fetchfd = -1, fetchstatus;
2290 pid_t fetchpid = -1;
2291 struct got_fetch_progress_arg fpa;
2292 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2293 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2294 int *pack_fds = NULL, have_bflag = 0;
2295 const char *remote_head = NULL, *worktree_branch = NULL;
2297 TAILQ_INIT(&refs);
2298 TAILQ_INIT(&symrefs);
2299 TAILQ_INIT(&remote_refs);
2300 TAILQ_INIT(&wanted_branches);
2301 TAILQ_INIT(&wanted_refs);
2303 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2304 switch (ch) {
2305 case 'a':
2306 fetch_all_branches = 1;
2307 break;
2308 case 'b':
2309 error = got_pathlist_append(&wanted_branches,
2310 optarg, NULL);
2311 if (error)
2312 return error;
2313 have_bflag = 1;
2314 break;
2315 case 'd':
2316 delete_refs = 1;
2317 break;
2318 case 'l':
2319 list_refs_only = 1;
2320 break;
2321 case 'q':
2322 verbosity = -1;
2323 break;
2324 case 'R':
2325 error = got_pathlist_append(&wanted_refs,
2326 optarg, NULL);
2327 if (error)
2328 return error;
2329 break;
2330 case 'r':
2331 repo_path = realpath(optarg, NULL);
2332 if (repo_path == NULL)
2333 return got_error_from_errno2("realpath",
2334 optarg);
2335 got_path_strip_trailing_slashes(repo_path);
2336 break;
2337 case 't':
2338 replace_tags = 1;
2339 break;
2340 case 'v':
2341 if (verbosity < 0)
2342 verbosity = 0;
2343 else if (verbosity < 3)
2344 verbosity++;
2345 break;
2346 case 'X':
2347 delete_remote = 1;
2348 break;
2349 default:
2350 usage_fetch();
2351 break;
2354 argc -= optind;
2355 argv += optind;
2357 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2358 option_conflict('a', 'b');
2359 if (list_refs_only) {
2360 if (!TAILQ_EMPTY(&wanted_branches))
2361 option_conflict('l', 'b');
2362 if (fetch_all_branches)
2363 option_conflict('l', 'a');
2364 if (delete_refs)
2365 option_conflict('l', 'd');
2366 if (delete_remote)
2367 option_conflict('l', 'X');
2369 if (delete_remote) {
2370 if (fetch_all_branches)
2371 option_conflict('X', 'a');
2372 if (!TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('X', 'b');
2374 if (delete_refs)
2375 option_conflict('X', 'd');
2376 if (replace_tags)
2377 option_conflict('X', 't');
2378 if (!TAILQ_EMPTY(&wanted_refs))
2379 option_conflict('X', 'R');
2382 if (argc == 0) {
2383 if (delete_remote)
2384 errx(1, "-X option requires a remote name");
2385 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2386 } else if (argc == 1)
2387 remote_name = argv[0];
2388 else
2389 usage_fetch();
2391 cwd = getcwd(NULL, 0);
2392 if (cwd == NULL) {
2393 error = got_error_from_errno("getcwd");
2394 goto done;
2397 error = got_repo_pack_fds_open(&pack_fds);
2398 if (error != NULL)
2399 goto done;
2401 if (repo_path == NULL) {
2402 error = got_worktree_open(&worktree, cwd);
2403 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2404 goto done;
2405 else
2406 error = NULL;
2407 if (worktree) {
2408 repo_path =
2409 strdup(got_worktree_get_repo_path(worktree));
2410 if (repo_path == NULL)
2411 error = got_error_from_errno("strdup");
2412 if (error)
2413 goto done;
2414 } else {
2415 repo_path = strdup(cwd);
2416 if (repo_path == NULL) {
2417 error = got_error_from_errno("strdup");
2418 goto done;
2423 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2424 if (error)
2425 goto done;
2427 if (delete_remote) {
2428 error = delete_refs_for_remote(repo, remote_name);
2429 goto done; /* nothing else to do */
2432 if (worktree) {
2433 worktree_conf = got_worktree_get_gotconfig(worktree);
2434 if (worktree_conf) {
2435 got_gotconfig_get_remotes(&nremotes, &remotes,
2436 worktree_conf);
2437 for (i = 0; i < nremotes; i++) {
2438 if (strcmp(remotes[i].name, remote_name) == 0) {
2439 remote = &remotes[i];
2440 break;
2445 if (remote == NULL) {
2446 repo_conf = got_repo_get_gotconfig(repo);
2447 if (repo_conf) {
2448 got_gotconfig_get_remotes(&nremotes, &remotes,
2449 repo_conf);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 remote = &remotes[i];
2453 break;
2458 if (remote == NULL) {
2459 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2460 for (i = 0; i < nremotes; i++) {
2461 if (strcmp(remotes[i].name, remote_name) == 0) {
2462 remote = &remotes[i];
2463 break;
2467 if (remote == NULL) {
2468 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2469 goto done;
2472 if (TAILQ_EMPTY(&wanted_branches)) {
2473 if (!fetch_all_branches)
2474 fetch_all_branches = remote->fetch_all_branches;
2475 for (i = 0; i < remote->nfetch_branches; i++) {
2476 error = got_pathlist_append(&wanted_branches,
2477 remote->fetch_branches[i], NULL);
2478 if (error)
2479 goto done;
2482 if (TAILQ_EMPTY(&wanted_refs)) {
2483 for (i = 0; i < remote->nfetch_refs; i++) {
2484 error = got_pathlist_append(&wanted_refs,
2485 remote->fetch_refs[i], NULL);
2486 if (error)
2487 goto done;
2491 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2492 &repo_name, remote->fetch_url);
2493 if (error)
2494 goto done;
2496 if (strcmp(proto, "git") == 0) {
2497 #ifndef PROFILE
2498 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2499 "sendfd dns inet unveil", NULL) == -1)
2500 err(1, "pledge");
2501 #endif
2502 } else if (strcmp(proto, "git+ssh") == 0 ||
2503 strcmp(proto, "ssh") == 0) {
2504 #ifndef PROFILE
2505 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2506 "sendfd unveil", NULL) == -1)
2507 err(1, "pledge");
2508 #endif
2509 } else if (strcmp(proto, "http") == 0 ||
2510 strcmp(proto, "git+http") == 0) {
2511 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2512 goto done;
2513 } else {
2514 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2515 goto done;
2518 error = got_dial_apply_unveil(proto);
2519 if (error)
2520 goto done;
2522 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2523 if (error)
2524 goto done;
2526 if (verbosity >= 0) {
2527 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2528 remote->name, proto, host,
2529 port ? ":" : "", port ? port : "",
2530 *server_path == '/' ? "" : "/", server_path);
2533 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2534 server_path, verbosity);
2535 if (error)
2536 goto done;
2538 if (!have_bflag) {
2540 * If set, get this remote's HEAD ref target so
2541 * if it has changed on the server we can fetch it.
2543 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2544 got_ref_cmp_by_name, repo);
2545 if (error)
2546 goto done;
2548 TAILQ_FOREACH(re, &remote_refs, entry) {
2549 const char *remote_refname, *remote_target;
2550 size_t remote_name_len;
2552 if (!got_ref_is_symbolic(re->ref))
2553 continue;
2555 remote_name_len = strlen(remote->name);
2556 remote_refname = got_ref_get_name(re->ref);
2558 /* we only want refs/remotes/$remote->name/HEAD */
2559 if (strncmp(remote_refname + 13, remote->name,
2560 remote_name_len) != 0)
2561 continue;
2563 if (strcmp(remote_refname + remote_name_len + 14,
2564 GOT_REF_HEAD) != 0)
2565 continue;
2568 * Take the name itself because we already
2569 * only match with refs/heads/ in fetch_pack().
2571 remote_target = got_ref_get_symref_target(re->ref);
2572 remote_head = remote_target + remote_name_len + 14;
2573 break;
2576 if (worktree) {
2577 const char *refname;
2579 refname = got_worktree_get_head_ref_name(worktree);
2580 if (strncmp(refname, "refs/heads/", 11) == 0)
2581 worktree_branch = refname;
2585 fpa.last_scaled_size[0] = '\0';
2586 fpa.last_p_indexed = -1;
2587 fpa.last_p_resolved = -1;
2588 fpa.verbosity = verbosity;
2589 fpa.repo = repo;
2590 fpa.create_configs = 0;
2591 fpa.configs_created = 0;
2592 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2594 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2595 remote->mirror_references, fetch_all_branches, &wanted_branches,
2596 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2597 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2598 if (error)
2599 goto done;
2601 if (list_refs_only) {
2602 error = list_remote_refs(&symrefs, &refs);
2603 goto done;
2606 if (pack_hash == NULL) {
2607 if (verbosity >= 0)
2608 printf("Already up-to-date\n");
2609 } else if (verbosity >= 0) {
2610 error = got_object_id_str(&id_str, pack_hash);
2611 if (error)
2612 goto done;
2613 printf("\nFetched %s.pack\n", id_str);
2614 free(id_str);
2615 id_str = NULL;
2618 /* Update references provided with the pack file. */
2619 TAILQ_FOREACH(pe, &refs, entry) {
2620 const char *refname = pe->path;
2621 struct got_object_id *id = pe->data;
2622 struct got_reference *ref;
2623 char *remote_refname;
2625 if (is_wanted_ref(&wanted_refs, refname) &&
2626 !remote->mirror_references) {
2627 error = update_wanted_ref(refname, id,
2628 remote->name, verbosity, repo);
2629 if (error)
2630 goto done;
2631 continue;
2634 if (remote->mirror_references ||
2635 strncmp("refs/tags/", refname, 10) == 0) {
2636 error = got_ref_open(&ref, repo, refname, 1);
2637 if (error) {
2638 if (error->code != GOT_ERR_NOT_REF)
2639 goto done;
2640 error = create_ref(refname, id, verbosity,
2641 repo);
2642 if (error)
2643 goto done;
2644 } else {
2645 error = update_ref(ref, id, replace_tags,
2646 verbosity, repo);
2647 unlock_err = got_ref_unlock(ref);
2648 if (unlock_err && error == NULL)
2649 error = unlock_err;
2650 got_ref_close(ref);
2651 if (error)
2652 goto done;
2654 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2655 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2656 remote_name, refname + 11) == -1) {
2657 error = got_error_from_errno("asprintf");
2658 goto done;
2661 error = got_ref_open(&ref, repo, remote_refname, 1);
2662 if (error) {
2663 if (error->code != GOT_ERR_NOT_REF)
2664 goto done;
2665 error = create_ref(remote_refname, id,
2666 verbosity, repo);
2667 if (error)
2668 goto done;
2669 } else {
2670 error = update_ref(ref, id, replace_tags,
2671 verbosity, repo);
2672 unlock_err = got_ref_unlock(ref);
2673 if (unlock_err && error == NULL)
2674 error = unlock_err;
2675 got_ref_close(ref);
2676 if (error)
2677 goto done;
2680 /* Also create a local branch if none exists yet. */
2681 error = got_ref_open(&ref, repo, refname, 1);
2682 if (error) {
2683 if (error->code != GOT_ERR_NOT_REF)
2684 goto done;
2685 error = create_ref(refname, id, verbosity,
2686 repo);
2687 if (error)
2688 goto done;
2689 } else {
2690 unlock_err = got_ref_unlock(ref);
2691 if (unlock_err && error == NULL)
2692 error = unlock_err;
2693 got_ref_close(ref);
2697 if (delete_refs) {
2698 error = delete_missing_refs(&refs, &symrefs, remote,
2699 verbosity, repo);
2700 if (error)
2701 goto done;
2704 if (!remote->mirror_references) {
2705 /* Update remote HEAD reference if the server provided one. */
2706 TAILQ_FOREACH(pe, &symrefs, entry) {
2707 struct got_reference *target_ref;
2708 const char *refname = pe->path;
2709 const char *target = pe->data;
2710 char *remote_refname = NULL, *remote_target = NULL;
2712 if (strcmp(refname, GOT_REF_HEAD) != 0)
2713 continue;
2715 if (strncmp("refs/heads/", target, 11) != 0)
2716 continue;
2718 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2719 remote->name, refname) == -1) {
2720 error = got_error_from_errno("asprintf");
2721 goto done;
2723 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2724 remote->name, target + 11) == -1) {
2725 error = got_error_from_errno("asprintf");
2726 free(remote_refname);
2727 goto done;
2730 error = got_ref_open(&target_ref, repo, remote_target,
2731 0);
2732 if (error) {
2733 free(remote_refname);
2734 free(remote_target);
2735 if (error->code == GOT_ERR_NOT_REF) {
2736 error = NULL;
2737 continue;
2739 goto done;
2741 error = update_symref(remote_refname, target_ref,
2742 verbosity, repo);
2743 free(remote_refname);
2744 free(remote_target);
2745 got_ref_close(target_ref);
2746 if (error)
2747 goto done;
2750 done:
2751 if (fetchpid > 0) {
2752 if (kill(fetchpid, SIGTERM) == -1)
2753 error = got_error_from_errno("kill");
2754 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2755 error = got_error_from_errno("waitpid");
2757 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2758 error = got_error_from_errno("close");
2759 if (repo) {
2760 const struct got_error *close_err = got_repo_close(repo);
2761 if (error == NULL)
2762 error = close_err;
2764 if (worktree)
2765 got_worktree_close(worktree);
2766 if (pack_fds) {
2767 const struct got_error *pack_err =
2768 got_repo_pack_fds_close(pack_fds);
2769 if (error == NULL)
2770 error = pack_err;
2772 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2773 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2774 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2775 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2776 got_ref_list_free(&remote_refs);
2777 free(id_str);
2778 free(cwd);
2779 free(repo_path);
2780 free(pack_hash);
2781 free(proto);
2782 free(host);
2783 free(port);
2784 free(server_path);
2785 free(repo_name);
2786 return error;
2790 __dead static void
2791 usage_checkout(void)
2793 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2794 "[-p path-prefix] repository-path [work-tree-path]\n",
2795 getprogname());
2796 exit(1);
2799 static void
2800 show_worktree_base_ref_warning(void)
2802 fprintf(stderr, "%s: warning: could not create a reference "
2803 "to the work tree's base commit; the commit could be "
2804 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2805 "repository writable and running 'got update' will prevent this\n",
2806 getprogname());
2809 struct got_checkout_progress_arg {
2810 const char *worktree_path;
2811 int had_base_commit_ref_error;
2812 int verbosity;
2815 static const struct got_error *
2816 checkout_progress(void *arg, unsigned char status, const char *path)
2818 struct got_checkout_progress_arg *a = arg;
2820 /* Base commit bump happens silently. */
2821 if (status == GOT_STATUS_BUMP_BASE)
2822 return NULL;
2824 if (status == GOT_STATUS_BASE_REF_ERR) {
2825 a->had_base_commit_ref_error = 1;
2826 return NULL;
2829 while (path[0] == '/')
2830 path++;
2832 if (a->verbosity >= 0)
2833 printf("%c %s/%s\n", status, a->worktree_path, path);
2835 return NULL;
2838 static const struct got_error *
2839 check_cancelled(void *arg)
2841 if (sigint_received || sigpipe_received)
2842 return got_error(GOT_ERR_CANCELLED);
2843 return NULL;
2846 static const struct got_error *
2847 check_linear_ancestry(struct got_object_id *commit_id,
2848 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2849 struct got_repository *repo)
2851 const struct got_error *err = NULL;
2852 struct got_object_id *yca_id;
2854 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2855 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2856 if (err)
2857 return err;
2859 if (yca_id == NULL)
2860 return got_error(GOT_ERR_ANCESTRY);
2863 * Require a straight line of history between the target commit
2864 * and the work tree's base commit.
2866 * Non-linear situations such as this require a rebase:
2868 * (commit) D F (base_commit)
2869 * \ /
2870 * C E
2871 * \ /
2872 * B (yca)
2873 * |
2874 * A
2876 * 'got update' only handles linear cases:
2877 * Update forwards in time: A (base/yca) - B - C - D (commit)
2878 * Update backwards in time: D (base) - C - B - A (commit/yca)
2880 if (allow_forwards_in_time_only) {
2881 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2882 return got_error(GOT_ERR_ANCESTRY);
2883 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2884 got_object_id_cmp(base_commit_id, yca_id) != 0)
2885 return got_error(GOT_ERR_ANCESTRY);
2887 free(yca_id);
2888 return NULL;
2891 static const struct got_error *
2892 check_same_branch(struct got_object_id *commit_id,
2893 struct got_reference *head_ref, struct got_object_id *yca_id,
2894 struct got_repository *repo)
2896 const struct got_error *err = NULL;
2897 struct got_commit_graph *graph = NULL;
2898 struct got_object_id *head_commit_id = NULL;
2899 int is_same_branch = 0;
2901 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2902 if (err)
2903 goto done;
2905 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2906 is_same_branch = 1;
2907 goto done;
2909 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2910 is_same_branch = 1;
2911 goto done;
2914 err = got_commit_graph_open(&graph, "/", 1);
2915 if (err)
2916 goto done;
2918 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2919 check_cancelled, NULL);
2920 if (err)
2921 goto done;
2923 for (;;) {
2924 struct got_object_id id;
2926 err = got_commit_graph_iter_next(&id, graph, repo,
2927 check_cancelled, NULL);
2928 if (err) {
2929 if (err->code == GOT_ERR_ITER_COMPLETED)
2930 err = NULL;
2931 break;
2934 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2935 break;
2936 if (got_object_id_cmp(&id, commit_id) == 0) {
2937 is_same_branch = 1;
2938 break;
2941 done:
2942 if (graph)
2943 got_commit_graph_close(graph);
2944 free(head_commit_id);
2945 if (!err && !is_same_branch)
2946 err = got_error(GOT_ERR_ANCESTRY);
2947 return err;
2950 static const struct got_error *
2951 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2953 static char msg[512];
2954 const char *branch_name;
2956 if (got_ref_is_symbolic(ref))
2957 branch_name = got_ref_get_symref_target(ref);
2958 else
2959 branch_name = got_ref_get_name(ref);
2961 if (strncmp("refs/heads/", branch_name, 11) == 0)
2962 branch_name += 11;
2964 snprintf(msg, sizeof(msg),
2965 "target commit is not contained in branch '%s'; "
2966 "the branch to use must be specified with -b; "
2967 "if necessary a new branch can be created for "
2968 "this commit with 'got branch -c %s BRANCH_NAME'",
2969 branch_name, commit_id_str);
2971 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2974 static const struct got_error *
2975 cmd_checkout(int argc, char *argv[])
2977 const struct got_error *error = NULL;
2978 struct got_repository *repo = NULL;
2979 struct got_reference *head_ref = NULL, *ref = NULL;
2980 struct got_worktree *worktree = NULL;
2981 char *repo_path = NULL;
2982 char *worktree_path = NULL;
2983 const char *path_prefix = "";
2984 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2985 char *commit_id_str = NULL;
2986 struct got_object_id *commit_id = NULL;
2987 char *cwd = NULL;
2988 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2989 struct got_pathlist_head paths;
2990 struct got_checkout_progress_arg cpa;
2991 int *pack_fds = NULL;
2993 TAILQ_INIT(&paths);
2995 #ifndef PROFILE
2996 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2997 "unveil", NULL) == -1)
2998 err(1, "pledge");
2999 #endif
3001 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3002 switch (ch) {
3003 case 'b':
3004 branch_name = optarg;
3005 break;
3006 case 'c':
3007 commit_id_str = strdup(optarg);
3008 if (commit_id_str == NULL)
3009 return got_error_from_errno("strdup");
3010 break;
3011 case 'E':
3012 allow_nonempty = 1;
3013 break;
3014 case 'p':
3015 path_prefix = optarg;
3016 break;
3017 case 'q':
3018 verbosity = -1;
3019 break;
3020 default:
3021 usage_checkout();
3022 /* NOTREACHED */
3026 argc -= optind;
3027 argv += optind;
3029 if (argc == 1) {
3030 char *base, *dotgit;
3031 const char *path;
3032 repo_path = realpath(argv[0], NULL);
3033 if (repo_path == NULL)
3034 return got_error_from_errno2("realpath", argv[0]);
3035 cwd = getcwd(NULL, 0);
3036 if (cwd == NULL) {
3037 error = got_error_from_errno("getcwd");
3038 goto done;
3040 if (path_prefix[0])
3041 path = path_prefix;
3042 else
3043 path = repo_path;
3044 error = got_path_basename(&base, path);
3045 if (error)
3046 goto done;
3047 dotgit = strstr(base, ".git");
3048 if (dotgit)
3049 *dotgit = '\0';
3050 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3051 error = got_error_from_errno("asprintf");
3052 free(base);
3053 goto done;
3055 free(base);
3056 } else if (argc == 2) {
3057 repo_path = realpath(argv[0], NULL);
3058 if (repo_path == NULL) {
3059 error = got_error_from_errno2("realpath", argv[0]);
3060 goto done;
3062 worktree_path = realpath(argv[1], NULL);
3063 if (worktree_path == NULL) {
3064 if (errno != ENOENT) {
3065 error = got_error_from_errno2("realpath",
3066 argv[1]);
3067 goto done;
3069 worktree_path = strdup(argv[1]);
3070 if (worktree_path == NULL) {
3071 error = got_error_from_errno("strdup");
3072 goto done;
3075 } else
3076 usage_checkout();
3078 got_path_strip_trailing_slashes(repo_path);
3079 got_path_strip_trailing_slashes(worktree_path);
3081 error = got_repo_pack_fds_open(&pack_fds);
3082 if (error != NULL)
3083 goto done;
3085 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3086 if (error != NULL)
3087 goto done;
3089 /* Pre-create work tree path for unveil(2) */
3090 error = got_path_mkdir(worktree_path);
3091 if (error) {
3092 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3093 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3094 goto done;
3095 if (!allow_nonempty &&
3096 !got_path_dir_is_empty(worktree_path)) {
3097 error = got_error_path(worktree_path,
3098 GOT_ERR_DIR_NOT_EMPTY);
3099 goto done;
3103 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3104 if (error)
3105 goto done;
3107 error = got_ref_open(&head_ref, repo, branch_name, 0);
3108 if (error != NULL)
3109 goto done;
3111 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3112 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3113 goto done;
3115 error = got_worktree_open(&worktree, worktree_path);
3116 if (error != NULL)
3117 goto done;
3119 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3120 path_prefix);
3121 if (error != NULL)
3122 goto done;
3123 if (!same_path_prefix) {
3124 error = got_error(GOT_ERR_PATH_PREFIX);
3125 goto done;
3128 if (commit_id_str) {
3129 struct got_reflist_head refs;
3130 TAILQ_INIT(&refs);
3131 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3132 NULL);
3133 if (error)
3134 goto done;
3135 error = got_repo_match_object_id(&commit_id, NULL,
3136 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3137 got_ref_list_free(&refs);
3138 if (error)
3139 goto done;
3140 error = check_linear_ancestry(commit_id,
3141 got_worktree_get_base_commit_id(worktree), 0, repo);
3142 if (error != NULL) {
3143 if (error->code == GOT_ERR_ANCESTRY) {
3144 error = checkout_ancestry_error(
3145 head_ref, commit_id_str);
3147 goto done;
3149 error = check_same_branch(commit_id, head_ref, NULL, repo);
3150 if (error) {
3151 if (error->code == GOT_ERR_ANCESTRY) {
3152 error = checkout_ancestry_error(
3153 head_ref, commit_id_str);
3155 goto done;
3157 error = got_worktree_set_base_commit_id(worktree, repo,
3158 commit_id);
3159 if (error)
3160 goto done;
3161 /* Expand potentially abbreviated commit ID string. */
3162 free(commit_id_str);
3163 error = got_object_id_str(&commit_id_str, commit_id);
3164 if (error)
3165 goto done;
3166 } else {
3167 commit_id = got_object_id_dup(
3168 got_worktree_get_base_commit_id(worktree));
3169 if (commit_id == NULL) {
3170 error = got_error_from_errno("got_object_id_dup");
3171 goto done;
3173 error = got_object_id_str(&commit_id_str, commit_id);
3174 if (error)
3175 goto done;
3178 error = got_pathlist_append(&paths, "", NULL);
3179 if (error)
3180 goto done;
3181 cpa.worktree_path = worktree_path;
3182 cpa.had_base_commit_ref_error = 0;
3183 cpa.verbosity = verbosity;
3184 error = got_worktree_checkout_files(worktree, &paths, repo,
3185 checkout_progress, &cpa, check_cancelled, NULL);
3186 if (error != NULL)
3187 goto done;
3189 if (got_ref_is_symbolic(head_ref)) {
3190 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3191 if (error)
3192 goto done;
3193 refname = got_ref_get_name(ref);
3194 } else
3195 refname = got_ref_get_name(head_ref);
3196 printf("Checked out %s: %s\n", refname, commit_id_str);
3197 printf("Now shut up and hack\n");
3198 if (cpa.had_base_commit_ref_error)
3199 show_worktree_base_ref_warning();
3200 done:
3201 if (pack_fds) {
3202 const struct got_error *pack_err =
3203 got_repo_pack_fds_close(pack_fds);
3204 if (error == NULL)
3205 error = pack_err;
3207 if (head_ref)
3208 got_ref_close(head_ref);
3209 if (ref)
3210 got_ref_close(ref);
3211 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3212 free(commit_id_str);
3213 free(commit_id);
3214 free(repo_path);
3215 free(worktree_path);
3216 free(cwd);
3217 return error;
3220 struct got_update_progress_arg {
3221 int did_something;
3222 int conflicts;
3223 int obstructed;
3224 int not_updated;
3225 int missing;
3226 int not_deleted;
3227 int unversioned;
3228 int verbosity;
3231 static void
3232 print_update_progress_stats(struct got_update_progress_arg *upa)
3234 if (!upa->did_something)
3235 return;
3237 if (upa->conflicts > 0)
3238 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3239 if (upa->obstructed > 0)
3240 printf("File paths obstructed by a non-regular file: %d\n",
3241 upa->obstructed);
3242 if (upa->not_updated > 0)
3243 printf("Files not updated because of existing merge "
3244 "conflicts: %d\n", upa->not_updated);
3248 * The meaning of some status codes differs between merge-style operations and
3249 * update operations. For example, the ! status code means "file was missing"
3250 * if changes were merged into the work tree, and "missing file was restored"
3251 * if the work tree was updated. This function should be used by any operation
3252 * which merges changes into the work tree without updating the work tree.
3254 static void
3255 print_merge_progress_stats(struct got_update_progress_arg *upa)
3257 if (!upa->did_something)
3258 return;
3260 if (upa->conflicts > 0)
3261 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3262 if (upa->obstructed > 0)
3263 printf("File paths obstructed by a non-regular file: %d\n",
3264 upa->obstructed);
3265 if (upa->missing > 0)
3266 printf("Files which had incoming changes but could not be "
3267 "found in the work tree: %d\n", upa->missing);
3268 if (upa->not_deleted > 0)
3269 printf("Files not deleted due to differences in deleted "
3270 "content: %d\n", upa->not_deleted);
3271 if (upa->unversioned > 0)
3272 printf("Files not merged because an unversioned file was "
3273 "found in the work tree: %d\n", upa->unversioned);
3276 __dead static void
3277 usage_update(void)
3279 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3280 "[path ...]\n", getprogname());
3281 exit(1);
3284 static const struct got_error *
3285 update_progress(void *arg, unsigned char status, const char *path)
3287 struct got_update_progress_arg *upa = arg;
3289 if (status == GOT_STATUS_EXISTS ||
3290 status == GOT_STATUS_BASE_REF_ERR)
3291 return NULL;
3293 upa->did_something = 1;
3295 /* Base commit bump happens silently. */
3296 if (status == GOT_STATUS_BUMP_BASE)
3297 return NULL;
3299 if (status == GOT_STATUS_CONFLICT)
3300 upa->conflicts++;
3301 if (status == GOT_STATUS_OBSTRUCTED)
3302 upa->obstructed++;
3303 if (status == GOT_STATUS_CANNOT_UPDATE)
3304 upa->not_updated++;
3305 if (status == GOT_STATUS_MISSING)
3306 upa->missing++;
3307 if (status == GOT_STATUS_CANNOT_DELETE)
3308 upa->not_deleted++;
3309 if (status == GOT_STATUS_UNVERSIONED)
3310 upa->unversioned++;
3312 while (path[0] == '/')
3313 path++;
3314 if (upa->verbosity >= 0)
3315 printf("%c %s\n", status, path);
3317 return NULL;
3320 static const struct got_error *
3321 switch_head_ref(struct got_reference *head_ref,
3322 struct got_object_id *commit_id, struct got_worktree *worktree,
3323 struct got_repository *repo)
3325 const struct got_error *err = NULL;
3326 char *base_id_str;
3327 int ref_has_moved = 0;
3329 /* Trivial case: switching between two different references. */
3330 if (strcmp(got_ref_get_name(head_ref),
3331 got_worktree_get_head_ref_name(worktree)) != 0) {
3332 printf("Switching work tree from %s to %s\n",
3333 got_worktree_get_head_ref_name(worktree),
3334 got_ref_get_name(head_ref));
3335 return got_worktree_set_head_ref(worktree, head_ref);
3338 err = check_linear_ancestry(commit_id,
3339 got_worktree_get_base_commit_id(worktree), 0, repo);
3340 if (err) {
3341 if (err->code != GOT_ERR_ANCESTRY)
3342 return err;
3343 ref_has_moved = 1;
3345 if (!ref_has_moved)
3346 return NULL;
3348 /* Switching to a rebased branch with the same reference name. */
3349 err = got_object_id_str(&base_id_str,
3350 got_worktree_get_base_commit_id(worktree));
3351 if (err)
3352 return err;
3353 printf("Reference %s now points at a different branch\n",
3354 got_worktree_get_head_ref_name(worktree));
3355 printf("Switching work tree from %s to %s\n", base_id_str,
3356 got_worktree_get_head_ref_name(worktree));
3357 return NULL;
3360 static const struct got_error *
3361 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3363 const struct got_error *err;
3364 int in_progress;
3366 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3367 if (err)
3368 return err;
3369 if (in_progress)
3370 return got_error(GOT_ERR_REBASING);
3372 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3373 if (err)
3374 return err;
3375 if (in_progress)
3376 return got_error(GOT_ERR_HISTEDIT_BUSY);
3378 return NULL;
3381 static const struct got_error *
3382 check_merge_in_progress(struct got_worktree *worktree,
3383 struct got_repository *repo)
3385 const struct got_error *err;
3386 int in_progress;
3388 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3389 if (err)
3390 return err;
3391 if (in_progress)
3392 return got_error(GOT_ERR_MERGE_BUSY);
3394 return NULL;
3397 static const struct got_error *
3398 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3399 char *argv[], struct got_worktree *worktree)
3401 const struct got_error *err = NULL;
3402 char *path;
3403 struct got_pathlist_entry *new;
3404 int i;
3406 if (argc == 0) {
3407 path = strdup("");
3408 if (path == NULL)
3409 return got_error_from_errno("strdup");
3410 return got_pathlist_append(paths, path, NULL);
3413 for (i = 0; i < argc; i++) {
3414 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3415 if (err)
3416 break;
3417 err = got_pathlist_insert(&new, paths, path, NULL);
3418 if (err || new == NULL /* duplicate */) {
3419 free(path);
3420 if (err)
3421 break;
3425 return err;
3428 static const struct got_error *
3429 wrap_not_worktree_error(const struct got_error *orig_err,
3430 const char *cmdname, const char *path)
3432 const struct got_error *err;
3433 struct got_repository *repo;
3434 static char msg[512];
3435 int *pack_fds = NULL;
3437 err = got_repo_pack_fds_open(&pack_fds);
3438 if (err)
3439 return err;
3441 err = got_repo_open(&repo, path, NULL, pack_fds);
3442 if (err)
3443 return orig_err;
3445 snprintf(msg, sizeof(msg),
3446 "'got %s' needs a work tree in addition to a git repository\n"
3447 "Work trees can be checked out from this Git repository with "
3448 "'got checkout'.\n"
3449 "The got(1) manual page contains more information.", cmdname);
3450 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3451 got_repo_close(repo);
3452 if (pack_fds) {
3453 const struct got_error *pack_err =
3454 got_repo_pack_fds_close(pack_fds);
3455 if (err == NULL)
3456 err = pack_err;
3458 return err;
3461 static const struct got_error *
3462 cmd_update(int argc, char *argv[])
3464 const struct got_error *error = NULL;
3465 struct got_repository *repo = NULL;
3466 struct got_worktree *worktree = NULL;
3467 char *worktree_path = NULL;
3468 struct got_object_id *commit_id = NULL;
3469 char *commit_id_str = NULL;
3470 const char *branch_name = NULL;
3471 struct got_reference *head_ref = NULL;
3472 struct got_pathlist_head paths;
3473 struct got_pathlist_entry *pe;
3474 int ch, verbosity = 0;
3475 struct got_update_progress_arg upa;
3476 int *pack_fds = NULL;
3478 TAILQ_INIT(&paths);
3480 #ifndef PROFILE
3481 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3482 "unveil", NULL) == -1)
3483 err(1, "pledge");
3484 #endif
3486 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3487 switch (ch) {
3488 case 'b':
3489 branch_name = optarg;
3490 break;
3491 case 'c':
3492 commit_id_str = strdup(optarg);
3493 if (commit_id_str == NULL)
3494 return got_error_from_errno("strdup");
3495 break;
3496 case 'q':
3497 verbosity = -1;
3498 break;
3499 default:
3500 usage_update();
3501 /* NOTREACHED */
3505 argc -= optind;
3506 argv += optind;
3508 worktree_path = getcwd(NULL, 0);
3509 if (worktree_path == NULL) {
3510 error = got_error_from_errno("getcwd");
3511 goto done;
3514 error = got_repo_pack_fds_open(&pack_fds);
3515 if (error != NULL)
3516 goto done;
3518 error = got_worktree_open(&worktree, worktree_path);
3519 if (error) {
3520 if (error->code == GOT_ERR_NOT_WORKTREE)
3521 error = wrap_not_worktree_error(error, "update",
3522 worktree_path);
3523 goto done;
3526 error = check_rebase_or_histedit_in_progress(worktree);
3527 if (error)
3528 goto done;
3530 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3531 NULL, pack_fds);
3532 if (error != NULL)
3533 goto done;
3535 error = apply_unveil(got_repo_get_path(repo), 0,
3536 got_worktree_get_root_path(worktree));
3537 if (error)
3538 goto done;
3540 error = check_merge_in_progress(worktree, repo);
3541 if (error)
3542 goto done;
3544 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3545 if (error)
3546 goto done;
3548 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3549 got_worktree_get_head_ref_name(worktree), 0);
3550 if (error != NULL)
3551 goto done;
3552 if (commit_id_str == NULL) {
3553 error = got_ref_resolve(&commit_id, repo, head_ref);
3554 if (error != NULL)
3555 goto done;
3556 error = got_object_id_str(&commit_id_str, commit_id);
3557 if (error != NULL)
3558 goto done;
3559 } else {
3560 struct got_reflist_head refs;
3561 TAILQ_INIT(&refs);
3562 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3563 NULL);
3564 if (error)
3565 goto done;
3566 error = got_repo_match_object_id(&commit_id, NULL,
3567 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3568 got_ref_list_free(&refs);
3569 free(commit_id_str);
3570 commit_id_str = NULL;
3571 if (error)
3572 goto done;
3573 error = got_object_id_str(&commit_id_str, commit_id);
3574 if (error)
3575 goto done;
3578 if (branch_name) {
3579 struct got_object_id *head_commit_id;
3580 TAILQ_FOREACH(pe, &paths, entry) {
3581 if (pe->path_len == 0)
3582 continue;
3583 error = got_error_msg(GOT_ERR_BAD_PATH,
3584 "switching between branches requires that "
3585 "the entire work tree gets updated");
3586 goto done;
3588 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3589 if (error)
3590 goto done;
3591 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3592 repo);
3593 free(head_commit_id);
3594 if (error != NULL)
3595 goto done;
3596 error = check_same_branch(commit_id, head_ref, NULL, repo);
3597 if (error)
3598 goto done;
3599 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3600 if (error)
3601 goto done;
3602 } else {
3603 error = check_linear_ancestry(commit_id,
3604 got_worktree_get_base_commit_id(worktree), 0, repo);
3605 if (error != NULL) {
3606 if (error->code == GOT_ERR_ANCESTRY)
3607 error = got_error(GOT_ERR_BRANCH_MOVED);
3608 goto done;
3610 error = check_same_branch(commit_id, head_ref, NULL, repo);
3611 if (error)
3612 goto done;
3615 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3616 commit_id) != 0) {
3617 error = got_worktree_set_base_commit_id(worktree, repo,
3618 commit_id);
3619 if (error)
3620 goto done;
3623 memset(&upa, 0, sizeof(upa));
3624 upa.verbosity = verbosity;
3625 error = got_worktree_checkout_files(worktree, &paths, repo,
3626 update_progress, &upa, check_cancelled, NULL);
3627 if (error != NULL)
3628 goto done;
3630 if (upa.did_something) {
3631 printf("Updated to %s: %s\n",
3632 got_worktree_get_head_ref_name(worktree), commit_id_str);
3633 } else
3634 printf("Already up-to-date\n");
3636 print_update_progress_stats(&upa);
3637 done:
3638 if (pack_fds) {
3639 const struct got_error *pack_err =
3640 got_repo_pack_fds_close(pack_fds);
3641 if (error == NULL)
3642 error = pack_err;
3644 free(worktree_path);
3645 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3646 free(commit_id);
3647 free(commit_id_str);
3648 return error;
3651 static const struct got_error *
3652 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3653 const char *path, int diff_context, int ignore_whitespace,
3654 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3655 struct got_repository *repo, FILE *outfile)
3657 const struct got_error *err = NULL;
3658 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3659 FILE *f1 = NULL, *f2 = NULL;
3660 int fd1 = -1, fd2 = -1;
3662 fd1 = got_opentempfd();
3663 if (fd1 == -1)
3664 return got_error_from_errno("got_opentempfd");
3665 fd2 = got_opentempfd();
3666 if (fd2 == -1) {
3667 err = got_error_from_errno("got_opentempfd");
3668 goto done;
3671 if (blob_id1) {
3672 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3673 fd1);
3674 if (err)
3675 goto done;
3678 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3679 if (err)
3680 goto done;
3682 f1 = got_opentemp();
3683 if (f1 == NULL) {
3684 err = got_error_from_errno("got_opentemp");
3685 goto done;
3687 f2 = got_opentemp();
3688 if (f2 == NULL) {
3689 err = got_error_from_errno("got_opentemp");
3690 goto done;
3693 while (path[0] == '/')
3694 path++;
3695 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3696 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3697 force_text_diff, dsa, outfile);
3698 done:
3699 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3700 err = got_error_from_errno("close");
3701 if (blob1)
3702 got_object_blob_close(blob1);
3703 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3704 err = got_error_from_errno("close");
3705 got_object_blob_close(blob2);
3706 if (f1 && fclose(f1) == EOF && err == NULL)
3707 err = got_error_from_errno("fclose");
3708 if (f2 && fclose(f2) == EOF && err == NULL)
3709 err = got_error_from_errno("fclose");
3710 return err;
3713 static const struct got_error *
3714 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3715 const char *path, int diff_context, int ignore_whitespace,
3716 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3717 struct got_repository *repo, FILE *outfile)
3719 const struct got_error *err = NULL;
3720 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3721 struct got_diff_blob_output_unidiff_arg arg;
3722 FILE *f1 = NULL, *f2 = NULL;
3723 int fd1 = -1, fd2 = -1;
3725 if (tree_id1) {
3726 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3727 if (err)
3728 goto done;
3729 fd1 = got_opentempfd();
3730 if (fd1 == -1) {
3731 err = got_error_from_errno("got_opentempfd");
3732 goto done;
3736 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3737 if (err)
3738 goto done;
3740 f1 = got_opentemp();
3741 if (f1 == NULL) {
3742 err = got_error_from_errno("got_opentemp");
3743 goto done;
3746 f2 = got_opentemp();
3747 if (f2 == NULL) {
3748 err = got_error_from_errno("got_opentemp");
3749 goto done;
3751 fd2 = got_opentempfd();
3752 if (fd2 == -1) {
3753 err = got_error_from_errno("got_opentempfd");
3754 goto done;
3756 arg.diff_context = diff_context;
3757 arg.ignore_whitespace = ignore_whitespace;
3758 arg.force_text_diff = force_text_diff;
3759 arg.diffstat = dsa;
3760 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3761 arg.outfile = outfile;
3762 arg.lines = NULL;
3763 arg.nlines = 0;
3764 while (path[0] == '/')
3765 path++;
3766 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3767 got_diff_blob_output_unidiff, &arg, 1);
3768 done:
3769 if (tree1)
3770 got_object_tree_close(tree1);
3771 if (tree2)
3772 got_object_tree_close(tree2);
3773 if (f1 && fclose(f1) == EOF && err == NULL)
3774 err = got_error_from_errno("fclose");
3775 if (f2 && fclose(f2) == EOF && err == NULL)
3776 err = got_error_from_errno("fclose");
3777 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3778 err = got_error_from_errno("close");
3779 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3780 err = got_error_from_errno("close");
3781 return err;
3784 static const struct got_error *
3785 get_changed_paths(struct got_pathlist_head *paths,
3786 struct got_commit_object *commit, struct got_repository *repo,
3787 struct got_diffstat_cb_arg *dsa)
3789 const struct got_error *err = NULL;
3790 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3791 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3792 struct got_object_qid *qid;
3793 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3794 FILE *f1 = NULL, *f2 = NULL;
3795 int fd1 = -1, fd2 = -1;
3797 if (dsa) {
3798 cb = got_diff_tree_compute_diffstat;
3800 f1 = got_opentemp();
3801 if (f1 == NULL) {
3802 err = got_error_from_errno("got_opentemp");
3803 goto done;
3805 f2 = got_opentemp();
3806 if (f2 == NULL) {
3807 err = got_error_from_errno("got_opentemp");
3808 goto done;
3810 fd1 = got_opentempfd();
3811 if (fd1 == -1) {
3812 err = got_error_from_errno("got_opentempfd");
3813 goto done;
3815 fd2 = got_opentempfd();
3816 if (fd2 == -1) {
3817 err = got_error_from_errno("got_opentempfd");
3818 goto done;
3822 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3823 if (qid != NULL) {
3824 struct got_commit_object *pcommit;
3825 err = got_object_open_as_commit(&pcommit, repo,
3826 &qid->id);
3827 if (err)
3828 return err;
3830 tree_id1 = got_object_id_dup(
3831 got_object_commit_get_tree_id(pcommit));
3832 if (tree_id1 == NULL) {
3833 got_object_commit_close(pcommit);
3834 return got_error_from_errno("got_object_id_dup");
3836 got_object_commit_close(pcommit);
3840 if (tree_id1) {
3841 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3842 if (err)
3843 goto done;
3846 tree_id2 = got_object_commit_get_tree_id(commit);
3847 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3848 if (err)
3849 goto done;
3851 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3852 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3853 done:
3854 if (tree1)
3855 got_object_tree_close(tree1);
3856 if (tree2)
3857 got_object_tree_close(tree2);
3858 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3859 err = got_error_from_errno("close");
3860 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3861 err = got_error_from_errno("close");
3862 if (f1 && fclose(f1) == EOF && err == NULL)
3863 err = got_error_from_errno("fclose");
3864 if (f2 && fclose(f2) == EOF && err == NULL)
3865 err = got_error_from_errno("fclose");
3866 free(tree_id1);
3867 return err;
3870 static const struct got_error *
3871 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3872 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3873 struct got_repository *repo, FILE *outfile)
3875 const struct got_error *err = NULL;
3876 struct got_commit_object *pcommit = NULL;
3877 char *id_str1 = NULL, *id_str2 = NULL;
3878 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3879 struct got_object_qid *qid;
3881 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3882 if (qid != NULL) {
3883 err = got_object_open_as_commit(&pcommit, repo,
3884 &qid->id);
3885 if (err)
3886 return err;
3887 err = got_object_id_str(&id_str1, &qid->id);
3888 if (err)
3889 goto done;
3892 err = got_object_id_str(&id_str2, id);
3893 if (err)
3894 goto done;
3896 if (path && path[0] != '\0') {
3897 int obj_type;
3898 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3899 if (err)
3900 goto done;
3901 if (pcommit) {
3902 err = got_object_id_by_path(&obj_id1, repo,
3903 pcommit, path);
3904 if (err) {
3905 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3906 free(obj_id2);
3907 goto done;
3911 err = got_object_get_type(&obj_type, repo, obj_id2);
3912 if (err) {
3913 free(obj_id2);
3914 goto done;
3916 fprintf(outfile,
3917 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3918 fprintf(outfile, "commit - %s\n",
3919 id_str1 ? id_str1 : "/dev/null");
3920 fprintf(outfile, "commit + %s\n", id_str2);
3921 switch (obj_type) {
3922 case GOT_OBJ_TYPE_BLOB:
3923 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3924 0, 0, dsa, repo, outfile);
3925 break;
3926 case GOT_OBJ_TYPE_TREE:
3927 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3928 0, 0, dsa, repo, outfile);
3929 break;
3930 default:
3931 err = got_error(GOT_ERR_OBJ_TYPE);
3932 break;
3934 free(obj_id1);
3935 free(obj_id2);
3936 } else {
3937 obj_id2 = got_object_commit_get_tree_id(commit);
3938 if (pcommit)
3939 obj_id1 = got_object_commit_get_tree_id(pcommit);
3940 fprintf(outfile,
3941 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3942 fprintf(outfile, "commit - %s\n",
3943 id_str1 ? id_str1 : "/dev/null");
3944 fprintf(outfile, "commit + %s\n", id_str2);
3945 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3946 dsa, repo, outfile);
3948 done:
3949 free(id_str1);
3950 free(id_str2);
3951 if (pcommit)
3952 got_object_commit_close(pcommit);
3953 return err;
3956 static char *
3957 get_datestr(time_t *time, char *datebuf)
3959 struct tm mytm, *tm;
3960 char *p, *s;
3962 tm = gmtime_r(time, &mytm);
3963 if (tm == NULL)
3964 return NULL;
3965 s = asctime_r(tm, datebuf);
3966 if (s == NULL)
3967 return NULL;
3968 p = strchr(s, '\n');
3969 if (p)
3970 *p = '\0';
3971 return s;
3974 static const struct got_error *
3975 match_commit(int *have_match, struct got_object_id *id,
3976 struct got_commit_object *commit, regex_t *regex)
3978 const struct got_error *err = NULL;
3979 regmatch_t regmatch;
3980 char *id_str = NULL, *logmsg = NULL;
3982 *have_match = 0;
3984 err = got_object_id_str(&id_str, id);
3985 if (err)
3986 return err;
3988 err = got_object_commit_get_logmsg(&logmsg, commit);
3989 if (err)
3990 goto done;
3992 if (regexec(regex, got_object_commit_get_author(commit), 1,
3993 &regmatch, 0) == 0 ||
3994 regexec(regex, got_object_commit_get_committer(commit), 1,
3995 &regmatch, 0) == 0 ||
3996 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3997 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3998 *have_match = 1;
3999 done:
4000 free(id_str);
4001 free(logmsg);
4002 return err;
4005 static void
4006 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4007 regex_t *regex)
4009 regmatch_t regmatch;
4010 struct got_pathlist_entry *pe;
4012 *have_match = 0;
4014 TAILQ_FOREACH(pe, changed_paths, entry) {
4015 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4016 *have_match = 1;
4017 break;
4022 static const struct got_error *
4023 match_patch(int *have_match, struct got_commit_object *commit,
4024 struct got_object_id *id, const char *path, int diff_context,
4025 struct got_repository *repo, regex_t *regex, FILE *f)
4027 const struct got_error *err = NULL;
4028 char *line = NULL;
4029 size_t linesize = 0;
4030 regmatch_t regmatch;
4032 *have_match = 0;
4034 err = got_opentemp_truncate(f);
4035 if (err)
4036 return err;
4038 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4039 if (err)
4040 goto done;
4042 if (fseeko(f, 0L, SEEK_SET) == -1) {
4043 err = got_error_from_errno("fseeko");
4044 goto done;
4047 while (getline(&line, &linesize, f) != -1) {
4048 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4049 *have_match = 1;
4050 break;
4053 done:
4054 free(line);
4055 return err;
4058 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4060 static const struct got_error*
4061 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4062 struct got_object_id *id, struct got_repository *repo,
4063 int local_only)
4065 static const struct got_error *err = NULL;
4066 struct got_reflist_entry *re;
4067 char *s;
4068 const char *name;
4070 *refs_str = NULL;
4072 TAILQ_FOREACH(re, refs, entry) {
4073 struct got_tag_object *tag = NULL;
4074 struct got_object_id *ref_id;
4075 int cmp;
4077 name = got_ref_get_name(re->ref);
4078 if (strcmp(name, GOT_REF_HEAD) == 0)
4079 continue;
4080 if (strncmp(name, "refs/", 5) == 0)
4081 name += 5;
4082 if (strncmp(name, "got/", 4) == 0)
4083 continue;
4084 if (strncmp(name, "heads/", 6) == 0)
4085 name += 6;
4086 if (strncmp(name, "remotes/", 8) == 0) {
4087 if (local_only)
4088 continue;
4089 name += 8;
4090 s = strstr(name, "/" GOT_REF_HEAD);
4091 if (s != NULL && s[strlen(s)] == '\0')
4092 continue;
4094 err = got_ref_resolve(&ref_id, repo, re->ref);
4095 if (err)
4096 break;
4097 if (strncmp(name, "tags/", 5) == 0) {
4098 err = got_object_open_as_tag(&tag, repo, ref_id);
4099 if (err) {
4100 if (err->code != GOT_ERR_OBJ_TYPE) {
4101 free(ref_id);
4102 break;
4104 /* Ref points at something other than a tag. */
4105 err = NULL;
4106 tag = NULL;
4109 cmp = got_object_id_cmp(tag ?
4110 got_object_tag_get_object_id(tag) : ref_id, id);
4111 free(ref_id);
4112 if (tag)
4113 got_object_tag_close(tag);
4114 if (cmp != 0)
4115 continue;
4116 s = *refs_str;
4117 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4118 s ? ", " : "", name) == -1) {
4119 err = got_error_from_errno("asprintf");
4120 free(s);
4121 *refs_str = NULL;
4122 break;
4124 free(s);
4127 return err;
4130 static const struct got_error *
4131 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4132 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4134 const struct got_error *err = NULL;
4135 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4136 char *comma, *s, *nl;
4137 struct got_reflist_head *refs;
4138 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4139 struct tm tm;
4140 time_t committer_time;
4142 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4143 if (refs) {
4144 err = build_refs_str(&ref_str, refs, id, repo, 1);
4145 if (err)
4146 return err;
4148 /* Display the first matching ref only. */
4149 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4150 *comma = '\0';
4153 if (ref_str == NULL) {
4154 err = got_object_id_str(&id_str, id);
4155 if (err)
4156 return err;
4159 committer_time = got_object_commit_get_committer_time(commit);
4160 if (gmtime_r(&committer_time, &tm) == NULL) {
4161 err = got_error_from_errno("gmtime_r");
4162 goto done;
4164 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4165 err = got_error(GOT_ERR_NO_SPACE);
4166 goto done;
4169 err = got_object_commit_get_logmsg(&logmsg0, commit);
4170 if (err)
4171 goto done;
4173 s = logmsg0;
4174 while (isspace((unsigned char)s[0]))
4175 s++;
4177 nl = strchr(s, '\n');
4178 if (nl) {
4179 *nl = '\0';
4182 if (ref_str)
4183 printf("%s%-7s %s\n", datebuf, ref_str, s);
4184 else
4185 printf("%s%.7s %s\n", datebuf, id_str, s);
4187 if (fflush(stdout) != 0 && err == NULL)
4188 err = got_error_from_errno("fflush");
4189 done:
4190 free(id_str);
4191 free(ref_str);
4192 free(logmsg0);
4193 return err;
4196 static const struct got_error *
4197 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4199 struct got_pathlist_entry *pe;
4201 if (header != NULL)
4202 printf("%s\n", header);
4204 TAILQ_FOREACH(pe, dsa->paths, entry) {
4205 struct got_diff_changed_path *cp = pe->data;
4206 int pad = dsa->max_path_len - pe->path_len + 1;
4208 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4209 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4211 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4212 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4213 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4215 if (fflush(stdout) != 0)
4216 return got_error_from_errno("fflush");
4218 return NULL;
4221 static const struct got_error *
4222 printfile(FILE *f)
4224 char buf[8192];
4225 size_t r;
4227 if (fseeko(f, 0L, SEEK_SET) == -1)
4228 return got_error_from_errno("fseek");
4230 for (;;) {
4231 r = fread(buf, 1, sizeof(buf), f);
4232 if (r == 0) {
4233 if (ferror(f))
4234 return got_error_from_errno("fread");
4235 if (feof(f))
4236 break;
4238 if (fwrite(buf, 1, r, stdout) != r)
4239 return got_ferror(stdout, GOT_ERR_IO);
4242 return NULL;
4245 static const struct got_error *
4246 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4247 struct got_repository *repo, const char *path,
4248 struct got_pathlist_head *changed_paths,
4249 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4250 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4251 const char *prefix)
4253 const struct got_error *err = NULL;
4254 FILE *f = NULL;
4255 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4256 char datebuf[26];
4257 time_t committer_time;
4258 const char *author, *committer;
4259 char *refs_str = NULL;
4261 err = got_object_id_str(&id_str, id);
4262 if (err)
4263 return err;
4265 if (custom_refs_str == NULL) {
4266 struct got_reflist_head *refs;
4267 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4268 if (refs) {
4269 err = build_refs_str(&refs_str, refs, id, repo, 0);
4270 if (err)
4271 goto done;
4275 printf(GOT_COMMIT_SEP_STR);
4276 if (custom_refs_str)
4277 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4278 custom_refs_str);
4279 else
4280 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4281 refs_str ? " (" : "", refs_str ? refs_str : "",
4282 refs_str ? ")" : "");
4283 free(id_str);
4284 id_str = NULL;
4285 free(refs_str);
4286 refs_str = NULL;
4287 printf("from: %s\n", got_object_commit_get_author(commit));
4288 author = got_object_commit_get_author(commit);
4289 committer = got_object_commit_get_committer(commit);
4290 if (strcmp(author, committer) != 0)
4291 printf("via: %s\n", committer);
4292 committer_time = got_object_commit_get_committer_time(commit);
4293 datestr = get_datestr(&committer_time, datebuf);
4294 if (datestr)
4295 printf("date: %s UTC\n", datestr);
4296 if (got_object_commit_get_nparents(commit) > 1) {
4297 const struct got_object_id_queue *parent_ids;
4298 struct got_object_qid *qid;
4299 int n = 1;
4300 parent_ids = got_object_commit_get_parent_ids(commit);
4301 STAILQ_FOREACH(qid, parent_ids, entry) {
4302 err = got_object_id_str(&id_str, &qid->id);
4303 if (err)
4304 goto done;
4305 printf("parent %d: %s\n", n++, id_str);
4306 free(id_str);
4307 id_str = NULL;
4311 err = got_object_commit_get_logmsg(&logmsg0, commit);
4312 if (err)
4313 goto done;
4315 logmsg = logmsg0;
4316 do {
4317 line = strsep(&logmsg, "\n");
4318 if (line)
4319 printf(" %s\n", line);
4320 } while (line);
4321 free(logmsg0);
4323 if (changed_paths && diffstat == NULL) {
4324 struct got_pathlist_entry *pe;
4326 TAILQ_FOREACH(pe, changed_paths, entry) {
4327 struct got_diff_changed_path *cp = pe->data;
4329 printf(" %c %s\n", cp->status, pe->path);
4331 printf("\n");
4333 if (show_patch) {
4334 if (diffstat) {
4335 f = got_opentemp();
4336 if (f == NULL) {
4337 err = got_error_from_errno("got_opentemp");
4338 goto done;
4342 err = print_patch(commit, id, path, diff_context, diffstat,
4343 repo, diffstat == NULL ? stdout : f);
4344 if (err)
4345 goto done;
4347 if (diffstat) {
4348 err = print_diffstat(diffstat, NULL);
4349 if (err)
4350 goto done;
4351 if (show_patch) {
4352 err = printfile(f);
4353 if (err)
4354 goto done;
4357 if (show_patch)
4358 printf("\n");
4360 if (fflush(stdout) != 0 && err == NULL)
4361 err = got_error_from_errno("fflush");
4362 done:
4363 if (f && fclose(f) == EOF && err == NULL)
4364 err = got_error_from_errno("fclose");
4365 free(id_str);
4366 free(refs_str);
4367 return err;
4370 static const struct got_error *
4371 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4372 struct got_repository *repo, const char *path, int show_changed_paths,
4373 int show_diffstat, int show_patch, const char *search_pattern,
4374 int diff_context, int limit, int log_branches, int reverse_display_order,
4375 struct got_reflist_object_id_map *refs_idmap, int one_line,
4376 FILE *tmpfile)
4378 const struct got_error *err;
4379 struct got_commit_graph *graph;
4380 regex_t regex;
4381 int have_match;
4382 struct got_object_id_queue reversed_commits;
4383 struct got_object_qid *qid;
4384 struct got_commit_object *commit;
4385 struct got_pathlist_head changed_paths;
4387 STAILQ_INIT(&reversed_commits);
4388 TAILQ_INIT(&changed_paths);
4390 if (search_pattern && regcomp(&regex, search_pattern,
4391 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4392 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4394 err = got_commit_graph_open(&graph, path, !log_branches);
4395 if (err)
4396 return err;
4397 err = got_commit_graph_iter_start(graph, root_id, repo,
4398 check_cancelled, NULL);
4399 if (err)
4400 goto done;
4401 for (;;) {
4402 struct got_object_id id;
4403 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4404 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4406 if (sigint_received || sigpipe_received)
4407 break;
4409 err = got_commit_graph_iter_next(&id, graph, repo,
4410 check_cancelled, NULL);
4411 if (err) {
4412 if (err->code == GOT_ERR_ITER_COMPLETED)
4413 err = NULL;
4414 break;
4417 err = got_object_open_as_commit(&commit, repo, &id);
4418 if (err)
4419 break;
4421 if ((show_changed_paths || (show_diffstat && !show_patch))
4422 && !reverse_display_order) {
4423 err = get_changed_paths(&changed_paths, commit, repo,
4424 show_diffstat ? &dsa : NULL);
4425 if (err)
4426 break;
4429 if (search_pattern) {
4430 err = match_commit(&have_match, &id, commit, &regex);
4431 if (err) {
4432 got_object_commit_close(commit);
4433 break;
4435 if (have_match == 0 && show_changed_paths)
4436 match_changed_paths(&have_match,
4437 &changed_paths, &regex);
4438 if (have_match == 0 && show_patch) {
4439 err = match_patch(&have_match, commit, &id,
4440 path, diff_context, repo, &regex, tmpfile);
4441 if (err)
4442 break;
4444 if (have_match == 0) {
4445 got_object_commit_close(commit);
4446 got_pathlist_free(&changed_paths,
4447 GOT_PATHLIST_FREE_ALL);
4448 continue;
4452 if (reverse_display_order) {
4453 err = got_object_qid_alloc(&qid, &id);
4454 if (err)
4455 break;
4456 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4457 got_object_commit_close(commit);
4458 } else {
4459 if (one_line)
4460 err = print_commit_oneline(commit, &id,
4461 repo, refs_idmap);
4462 else
4463 err = print_commit(commit, &id, repo, path,
4464 (show_changed_paths || show_diffstat) ?
4465 &changed_paths : NULL,
4466 show_diffstat ? &dsa : NULL, show_patch,
4467 diff_context, refs_idmap, NULL, NULL);
4468 got_object_commit_close(commit);
4469 if (err)
4470 break;
4472 if ((limit && --limit == 0) ||
4473 (end_id && got_object_id_cmp(&id, end_id) == 0))
4474 break;
4476 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4478 if (reverse_display_order) {
4479 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4480 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4481 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4483 err = got_object_open_as_commit(&commit, repo,
4484 &qid->id);
4485 if (err)
4486 break;
4487 if (show_changed_paths ||
4488 (show_diffstat && !show_patch)) {
4489 err = get_changed_paths(&changed_paths, commit,
4490 repo, show_diffstat ? &dsa : NULL);
4491 if (err)
4492 break;
4494 if (one_line)
4495 err = print_commit_oneline(commit, &qid->id,
4496 repo, refs_idmap);
4497 else
4498 err = print_commit(commit, &qid->id, repo, path,
4499 (show_changed_paths || show_diffstat) ?
4500 &changed_paths : NULL,
4501 show_diffstat ? &dsa : NULL, show_patch,
4502 diff_context, refs_idmap, NULL, NULL);
4503 got_object_commit_close(commit);
4504 if (err)
4505 break;
4506 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4509 done:
4510 while (!STAILQ_EMPTY(&reversed_commits)) {
4511 qid = STAILQ_FIRST(&reversed_commits);
4512 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4513 got_object_qid_free(qid);
4515 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4516 if (search_pattern)
4517 regfree(&regex);
4518 got_commit_graph_close(graph);
4519 return err;
4522 __dead static void
4523 usage_log(void)
4525 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4526 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4527 "[path]\n", getprogname());
4528 exit(1);
4531 static int
4532 get_default_log_limit(void)
4534 const char *got_default_log_limit;
4535 long long n;
4536 const char *errstr;
4538 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4539 if (got_default_log_limit == NULL)
4540 return 0;
4541 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4542 if (errstr != NULL)
4543 return 0;
4544 return n;
4547 static const struct got_error *
4548 cmd_log(int argc, char *argv[])
4550 const struct got_error *error;
4551 struct got_repository *repo = NULL;
4552 struct got_worktree *worktree = NULL;
4553 struct got_object_id *start_id = NULL, *end_id = NULL;
4554 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4555 const char *start_commit = NULL, *end_commit = NULL;
4556 const char *search_pattern = NULL;
4557 int diff_context = -1, ch;
4558 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4559 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4560 const char *errstr;
4561 struct got_reflist_head refs;
4562 struct got_reflist_object_id_map *refs_idmap = NULL;
4563 FILE *tmpfile = NULL;
4564 int *pack_fds = NULL;
4566 TAILQ_INIT(&refs);
4568 #ifndef PROFILE
4569 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4570 NULL)
4571 == -1)
4572 err(1, "pledge");
4573 #endif
4575 limit = get_default_log_limit();
4577 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4578 switch (ch) {
4579 case 'b':
4580 log_branches = 1;
4581 break;
4582 case 'C':
4583 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4584 &errstr);
4585 if (errstr != NULL)
4586 errx(1, "number of context lines is %s: %s",
4587 errstr, optarg);
4588 break;
4589 case 'c':
4590 start_commit = optarg;
4591 break;
4592 case 'd':
4593 show_diffstat = 1;
4594 break;
4595 case 'l':
4596 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4597 if (errstr != NULL)
4598 errx(1, "number of commits is %s: %s",
4599 errstr, optarg);
4600 break;
4601 case 'P':
4602 show_changed_paths = 1;
4603 break;
4604 case 'p':
4605 show_patch = 1;
4606 break;
4607 case 'R':
4608 reverse_display_order = 1;
4609 break;
4610 case 'r':
4611 repo_path = realpath(optarg, NULL);
4612 if (repo_path == NULL)
4613 return got_error_from_errno2("realpath",
4614 optarg);
4615 got_path_strip_trailing_slashes(repo_path);
4616 break;
4617 case 'S':
4618 search_pattern = optarg;
4619 break;
4620 case 's':
4621 one_line = 1;
4622 break;
4623 case 'x':
4624 end_commit = optarg;
4625 break;
4626 default:
4627 usage_log();
4628 /* NOTREACHED */
4632 argc -= optind;
4633 argv += optind;
4635 if (diff_context == -1)
4636 diff_context = 3;
4637 else if (!show_patch)
4638 errx(1, "-C requires -p");
4640 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4641 errx(1, "cannot use -s with -d, -p or -P");
4643 cwd = getcwd(NULL, 0);
4644 if (cwd == NULL) {
4645 error = got_error_from_errno("getcwd");
4646 goto done;
4649 error = got_repo_pack_fds_open(&pack_fds);
4650 if (error != NULL)
4651 goto done;
4653 if (repo_path == NULL) {
4654 error = got_worktree_open(&worktree, cwd);
4655 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4656 goto done;
4657 error = NULL;
4660 if (argc == 1) {
4661 if (worktree) {
4662 error = got_worktree_resolve_path(&path, worktree,
4663 argv[0]);
4664 if (error)
4665 goto done;
4666 } else {
4667 path = strdup(argv[0]);
4668 if (path == NULL) {
4669 error = got_error_from_errno("strdup");
4670 goto done;
4673 } else if (argc != 0)
4674 usage_log();
4676 if (repo_path == NULL) {
4677 repo_path = worktree ?
4678 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4680 if (repo_path == NULL) {
4681 error = got_error_from_errno("strdup");
4682 goto done;
4685 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4686 if (error != NULL)
4687 goto done;
4689 error = apply_unveil(got_repo_get_path(repo), 1,
4690 worktree ? got_worktree_get_root_path(worktree) : NULL);
4691 if (error)
4692 goto done;
4694 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4695 if (error)
4696 goto done;
4698 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4699 if (error)
4700 goto done;
4702 if (start_commit == NULL) {
4703 struct got_reference *head_ref;
4704 struct got_commit_object *commit = NULL;
4705 error = got_ref_open(&head_ref, repo,
4706 worktree ? got_worktree_get_head_ref_name(worktree)
4707 : GOT_REF_HEAD, 0);
4708 if (error != NULL)
4709 goto done;
4710 error = got_ref_resolve(&start_id, repo, head_ref);
4711 got_ref_close(head_ref);
4712 if (error != NULL)
4713 goto done;
4714 error = got_object_open_as_commit(&commit, repo,
4715 start_id);
4716 if (error != NULL)
4717 goto done;
4718 got_object_commit_close(commit);
4719 } else {
4720 error = got_repo_match_object_id(&start_id, NULL,
4721 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4722 if (error != NULL)
4723 goto done;
4725 if (end_commit != NULL) {
4726 error = got_repo_match_object_id(&end_id, NULL,
4727 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4728 if (error != NULL)
4729 goto done;
4732 if (worktree) {
4734 * If a path was specified on the command line it was resolved
4735 * to a path in the work tree above. Prepend the work tree's
4736 * path prefix to obtain the corresponding in-repository path.
4738 if (path) {
4739 const char *prefix;
4740 prefix = got_worktree_get_path_prefix(worktree);
4741 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4742 (path[0] != '\0') ? "/" : "", path) == -1) {
4743 error = got_error_from_errno("asprintf");
4744 goto done;
4747 } else
4748 error = got_repo_map_path(&in_repo_path, repo,
4749 path ? path : "");
4750 if (error != NULL)
4751 goto done;
4752 if (in_repo_path) {
4753 free(path);
4754 path = in_repo_path;
4757 if (worktree) {
4758 /* Release work tree lock. */
4759 got_worktree_close(worktree);
4760 worktree = NULL;
4763 if (search_pattern && show_patch) {
4764 tmpfile = got_opentemp();
4765 if (tmpfile == NULL) {
4766 error = got_error_from_errno("got_opentemp");
4767 goto done;
4771 error = print_commits(start_id, end_id, repo, path ? path : "",
4772 show_changed_paths, show_diffstat, show_patch, search_pattern,
4773 diff_context, limit, log_branches, reverse_display_order,
4774 refs_idmap, one_line, tmpfile);
4775 done:
4776 free(path);
4777 free(repo_path);
4778 free(cwd);
4779 if (worktree)
4780 got_worktree_close(worktree);
4781 if (repo) {
4782 const struct got_error *close_err = got_repo_close(repo);
4783 if (error == NULL)
4784 error = close_err;
4786 if (pack_fds) {
4787 const struct got_error *pack_err =
4788 got_repo_pack_fds_close(pack_fds);
4789 if (error == NULL)
4790 error = pack_err;
4792 if (refs_idmap)
4793 got_reflist_object_id_map_free(refs_idmap);
4794 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4795 error = got_error_from_errno("fclose");
4796 got_ref_list_free(&refs);
4797 return error;
4800 __dead static void
4801 usage_diff(void)
4803 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4804 "[-r repository-path] [object1 object2 | path ...]\n",
4805 getprogname());
4806 exit(1);
4809 struct print_diff_arg {
4810 struct got_repository *repo;
4811 struct got_worktree *worktree;
4812 struct got_diffstat_cb_arg *diffstat;
4813 int diff_context;
4814 const char *id_str;
4815 int header_shown;
4816 int diff_staged;
4817 enum got_diff_algorithm diff_algo;
4818 int ignore_whitespace;
4819 int force_text_diff;
4820 FILE *f1;
4821 FILE *f2;
4822 FILE *outfile;
4826 * Create a file which contains the target path of a symlink so we can feed
4827 * it as content to the diff engine.
4829 static const struct got_error *
4830 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4831 const char *abspath)
4833 const struct got_error *err = NULL;
4834 char target_path[PATH_MAX];
4835 ssize_t target_len, outlen;
4837 *fd = -1;
4839 if (dirfd != -1) {
4840 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4841 if (target_len == -1)
4842 return got_error_from_errno2("readlinkat", abspath);
4843 } else {
4844 target_len = readlink(abspath, target_path, PATH_MAX);
4845 if (target_len == -1)
4846 return got_error_from_errno2("readlink", abspath);
4849 *fd = got_opentempfd();
4850 if (*fd == -1)
4851 return got_error_from_errno("got_opentempfd");
4853 outlen = write(*fd, target_path, target_len);
4854 if (outlen == -1) {
4855 err = got_error_from_errno("got_opentempfd");
4856 goto done;
4859 if (lseek(*fd, 0, SEEK_SET) == -1) {
4860 err = got_error_from_errno2("lseek", abspath);
4861 goto done;
4863 done:
4864 if (err) {
4865 close(*fd);
4866 *fd = -1;
4868 return err;
4871 static const struct got_error *
4872 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4873 const char *path, struct got_object_id *blob_id,
4874 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4875 int dirfd, const char *de_name)
4877 struct print_diff_arg *a = arg;
4878 const struct got_error *err = NULL;
4879 struct got_blob_object *blob1 = NULL;
4880 int fd = -1, fd1 = -1, fd2 = -1;
4881 FILE *f2 = NULL;
4882 char *abspath = NULL, *label1 = NULL;
4883 struct stat sb;
4884 off_t size1 = 0;
4885 int f2_exists = 0;
4887 memset(&sb, 0, sizeof(sb));
4889 if (a->diff_staged) {
4890 if (staged_status != GOT_STATUS_MODIFY &&
4891 staged_status != GOT_STATUS_ADD &&
4892 staged_status != GOT_STATUS_DELETE)
4893 return NULL;
4894 } else {
4895 if (staged_status == GOT_STATUS_DELETE)
4896 return NULL;
4897 if (status == GOT_STATUS_NONEXISTENT)
4898 return got_error_set_errno(ENOENT, path);
4899 if (status != GOT_STATUS_MODIFY &&
4900 status != GOT_STATUS_ADD &&
4901 status != GOT_STATUS_DELETE &&
4902 status != GOT_STATUS_CONFLICT)
4903 return NULL;
4906 err = got_opentemp_truncate(a->f1);
4907 if (err)
4908 return got_error_from_errno("got_opentemp_truncate");
4909 err = got_opentemp_truncate(a->f2);
4910 if (err)
4911 return got_error_from_errno("got_opentemp_truncate");
4913 if (!a->header_shown) {
4914 if (fprintf(a->outfile, "diff %s%s\n",
4915 a->diff_staged ? "-s " : "",
4916 got_worktree_get_root_path(a->worktree)) < 0) {
4917 err = got_error_from_errno("fprintf");
4918 goto done;
4920 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4921 err = got_error_from_errno("fprintf");
4922 goto done;
4924 if (fprintf(a->outfile, "path + %s%s\n",
4925 got_worktree_get_root_path(a->worktree),
4926 a->diff_staged ? " (staged changes)" : "") < 0) {
4927 err = got_error_from_errno("fprintf");
4928 goto done;
4930 a->header_shown = 1;
4933 if (a->diff_staged) {
4934 const char *label1 = NULL, *label2 = NULL;
4935 switch (staged_status) {
4936 case GOT_STATUS_MODIFY:
4937 label1 = path;
4938 label2 = path;
4939 break;
4940 case GOT_STATUS_ADD:
4941 label2 = path;
4942 break;
4943 case GOT_STATUS_DELETE:
4944 label1 = path;
4945 break;
4946 default:
4947 return got_error(GOT_ERR_FILE_STATUS);
4949 fd1 = got_opentempfd();
4950 if (fd1 == -1) {
4951 err = got_error_from_errno("got_opentempfd");
4952 goto done;
4954 fd2 = got_opentempfd();
4955 if (fd2 == -1) {
4956 err = got_error_from_errno("got_opentempfd");
4957 goto done;
4959 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4960 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4961 a->diff_algo, a->diff_context, a->ignore_whitespace,
4962 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4963 goto done;
4966 fd1 = got_opentempfd();
4967 if (fd1 == -1) {
4968 err = got_error_from_errno("got_opentempfd");
4969 goto done;
4972 if (staged_status == GOT_STATUS_ADD ||
4973 staged_status == GOT_STATUS_MODIFY) {
4974 char *id_str;
4975 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4976 8192, fd1);
4977 if (err)
4978 goto done;
4979 err = got_object_id_str(&id_str, staged_blob_id);
4980 if (err)
4981 goto done;
4982 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4983 err = got_error_from_errno("asprintf");
4984 free(id_str);
4985 goto done;
4987 free(id_str);
4988 } else if (status != GOT_STATUS_ADD) {
4989 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4990 fd1);
4991 if (err)
4992 goto done;
4995 if (status != GOT_STATUS_DELETE) {
4996 if (asprintf(&abspath, "%s/%s",
4997 got_worktree_get_root_path(a->worktree), path) == -1) {
4998 err = got_error_from_errno("asprintf");
4999 goto done;
5002 if (dirfd != -1) {
5003 fd = openat(dirfd, de_name,
5004 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5005 if (fd == -1) {
5006 if (!got_err_open_nofollow_on_symlink()) {
5007 err = got_error_from_errno2("openat",
5008 abspath);
5009 goto done;
5011 err = get_symlink_target_file(&fd, dirfd,
5012 de_name, abspath);
5013 if (err)
5014 goto done;
5016 } else {
5017 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5018 if (fd == -1) {
5019 if (!got_err_open_nofollow_on_symlink()) {
5020 err = got_error_from_errno2("open",
5021 abspath);
5022 goto done;
5024 err = get_symlink_target_file(&fd, dirfd,
5025 de_name, abspath);
5026 if (err)
5027 goto done;
5030 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5031 err = got_error_from_errno2("fstatat", abspath);
5032 goto done;
5034 f2 = fdopen(fd, "r");
5035 if (f2 == NULL) {
5036 err = got_error_from_errno2("fdopen", abspath);
5037 goto done;
5039 fd = -1;
5040 f2_exists = 1;
5043 if (blob1) {
5044 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5045 a->f1, blob1);
5046 if (err)
5047 goto done;
5050 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5051 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5052 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5053 done:
5054 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5055 err = got_error_from_errno("close");
5056 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5057 err = got_error_from_errno("close");
5058 if (blob1)
5059 got_object_blob_close(blob1);
5060 if (fd != -1 && close(fd) == -1 && err == NULL)
5061 err = got_error_from_errno("close");
5062 if (f2 && fclose(f2) == EOF && err == NULL)
5063 err = got_error_from_errno("fclose");
5064 free(abspath);
5065 return err;
5068 static const struct got_error *
5069 cmd_diff(int argc, char *argv[])
5071 const struct got_error *error;
5072 struct got_repository *repo = NULL;
5073 struct got_worktree *worktree = NULL;
5074 char *cwd = NULL, *repo_path = NULL;
5075 const char *commit_args[2] = { NULL, NULL };
5076 int ncommit_args = 0;
5077 struct got_object_id *ids[2] = { NULL, NULL };
5078 char *labels[2] = { NULL, NULL };
5079 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5080 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5081 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5082 const char *errstr;
5083 struct got_reflist_head refs;
5084 struct got_pathlist_head diffstat_paths, paths;
5085 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5086 int fd1 = -1, fd2 = -1;
5087 int *pack_fds = NULL;
5088 struct got_diffstat_cb_arg dsa;
5090 memset(&dsa, 0, sizeof(dsa));
5092 TAILQ_INIT(&refs);
5093 TAILQ_INIT(&paths);
5094 TAILQ_INIT(&diffstat_paths);
5096 #ifndef PROFILE
5097 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5098 NULL) == -1)
5099 err(1, "pledge");
5100 #endif
5102 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5103 switch (ch) {
5104 case 'a':
5105 force_text_diff = 1;
5106 break;
5107 case 'C':
5108 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5109 &errstr);
5110 if (errstr != NULL)
5111 errx(1, "number of context lines is %s: %s",
5112 errstr, optarg);
5113 break;
5114 case 'c':
5115 if (ncommit_args >= 2)
5116 errx(1, "too many -c options used");
5117 commit_args[ncommit_args++] = optarg;
5118 break;
5119 case 'd':
5120 show_diffstat = 1;
5121 break;
5122 case 'P':
5123 force_path = 1;
5124 break;
5125 case 'r':
5126 repo_path = realpath(optarg, NULL);
5127 if (repo_path == NULL)
5128 return got_error_from_errno2("realpath",
5129 optarg);
5130 got_path_strip_trailing_slashes(repo_path);
5131 rflag = 1;
5132 break;
5133 case 's':
5134 diff_staged = 1;
5135 break;
5136 case 'w':
5137 ignore_whitespace = 1;
5138 break;
5139 default:
5140 usage_diff();
5141 /* NOTREACHED */
5145 argc -= optind;
5146 argv += optind;
5148 cwd = getcwd(NULL, 0);
5149 if (cwd == NULL) {
5150 error = got_error_from_errno("getcwd");
5151 goto done;
5154 error = got_repo_pack_fds_open(&pack_fds);
5155 if (error != NULL)
5156 goto done;
5158 if (repo_path == NULL) {
5159 error = got_worktree_open(&worktree, cwd);
5160 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5161 goto done;
5162 else
5163 error = NULL;
5164 if (worktree) {
5165 repo_path =
5166 strdup(got_worktree_get_repo_path(worktree));
5167 if (repo_path == NULL) {
5168 error = got_error_from_errno("strdup");
5169 goto done;
5171 } else {
5172 repo_path = strdup(cwd);
5173 if (repo_path == NULL) {
5174 error = got_error_from_errno("strdup");
5175 goto done;
5180 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5181 free(repo_path);
5182 if (error != NULL)
5183 goto done;
5185 if (show_diffstat) {
5186 dsa.paths = &diffstat_paths;
5187 dsa.force_text = force_text_diff;
5188 dsa.ignore_ws = ignore_whitespace;
5189 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5192 if (rflag || worktree == NULL || ncommit_args > 0) {
5193 if (force_path) {
5194 error = got_error_msg(GOT_ERR_NOT_IMPL,
5195 "-P option can only be used when diffing "
5196 "a work tree");
5197 goto done;
5199 if (diff_staged) {
5200 error = got_error_msg(GOT_ERR_NOT_IMPL,
5201 "-s option can only be used when diffing "
5202 "a work tree");
5203 goto done;
5207 error = apply_unveil(got_repo_get_path(repo), 1,
5208 worktree ? got_worktree_get_root_path(worktree) : NULL);
5209 if (error)
5210 goto done;
5212 if ((!force_path && argc == 2) || ncommit_args > 0) {
5213 int obj_type = (ncommit_args > 0 ?
5214 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5215 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5216 NULL);
5217 if (error)
5218 goto done;
5219 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5220 const char *arg;
5221 if (ncommit_args > 0)
5222 arg = commit_args[i];
5223 else
5224 arg = argv[i];
5225 error = got_repo_match_object_id(&ids[i], &labels[i],
5226 arg, obj_type, &refs, repo);
5227 if (error) {
5228 if (error->code != GOT_ERR_NOT_REF &&
5229 error->code != GOT_ERR_NO_OBJ)
5230 goto done;
5231 if (ncommit_args > 0)
5232 goto done;
5233 error = NULL;
5234 break;
5239 f1 = got_opentemp();
5240 if (f1 == NULL) {
5241 error = got_error_from_errno("got_opentemp");
5242 goto done;
5245 f2 = got_opentemp();
5246 if (f2 == NULL) {
5247 error = got_error_from_errno("got_opentemp");
5248 goto done;
5251 outfile = got_opentemp();
5252 if (outfile == NULL) {
5253 error = got_error_from_errno("got_opentemp");
5254 goto done;
5257 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5258 struct print_diff_arg arg;
5259 char *id_str;
5261 if (worktree == NULL) {
5262 if (argc == 2 && ids[0] == NULL) {
5263 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5264 goto done;
5265 } else if (argc == 2 && ids[1] == NULL) {
5266 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5267 goto done;
5268 } else if (argc > 0) {
5269 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5270 "%s", "specified paths cannot be resolved");
5271 goto done;
5272 } else {
5273 error = got_error(GOT_ERR_NOT_WORKTREE);
5274 goto done;
5278 error = get_worktree_paths_from_argv(&paths, argc, argv,
5279 worktree);
5280 if (error)
5281 goto done;
5283 error = got_object_id_str(&id_str,
5284 got_worktree_get_base_commit_id(worktree));
5285 if (error)
5286 goto done;
5287 arg.repo = repo;
5288 arg.worktree = worktree;
5289 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5290 arg.diff_context = diff_context;
5291 arg.id_str = id_str;
5292 arg.header_shown = 0;
5293 arg.diff_staged = diff_staged;
5294 arg.ignore_whitespace = ignore_whitespace;
5295 arg.force_text_diff = force_text_diff;
5296 arg.diffstat = show_diffstat ? &dsa : NULL;
5297 arg.f1 = f1;
5298 arg.f2 = f2;
5299 arg.outfile = outfile;
5301 error = got_worktree_status(worktree, &paths, repo, 0,
5302 print_diff, &arg, check_cancelled, NULL);
5303 free(id_str);
5304 if (error)
5305 goto done;
5307 if (show_diffstat && dsa.nfiles > 0) {
5308 char *header;
5310 if (asprintf(&header, "diffstat %s%s",
5311 diff_staged ? "-s " : "",
5312 got_worktree_get_root_path(worktree)) == -1) {
5313 error = got_error_from_errno("asprintf");
5314 goto done;
5317 error = print_diffstat(&dsa, header);
5318 free(header);
5319 if (error)
5320 goto done;
5323 error = printfile(outfile);
5324 goto done;
5327 if (ncommit_args == 1) {
5328 struct got_commit_object *commit;
5329 error = got_object_open_as_commit(&commit, repo, ids[0]);
5330 if (error)
5331 goto done;
5333 labels[1] = labels[0];
5334 ids[1] = ids[0];
5335 if (got_object_commit_get_nparents(commit) > 0) {
5336 const struct got_object_id_queue *pids;
5337 struct got_object_qid *pid;
5338 pids = got_object_commit_get_parent_ids(commit);
5339 pid = STAILQ_FIRST(pids);
5340 ids[0] = got_object_id_dup(&pid->id);
5341 if (ids[0] == NULL) {
5342 error = got_error_from_errno(
5343 "got_object_id_dup");
5344 got_object_commit_close(commit);
5345 goto done;
5347 error = got_object_id_str(&labels[0], ids[0]);
5348 if (error) {
5349 got_object_commit_close(commit);
5350 goto done;
5352 } else {
5353 ids[0] = NULL;
5354 labels[0] = strdup("/dev/null");
5355 if (labels[0] == NULL) {
5356 error = got_error_from_errno("strdup");
5357 got_object_commit_close(commit);
5358 goto done;
5362 got_object_commit_close(commit);
5365 if (ncommit_args == 0 && argc > 2) {
5366 error = got_error_msg(GOT_ERR_BAD_PATH,
5367 "path arguments cannot be used when diffing two objects");
5368 goto done;
5371 if (ids[0]) {
5372 error = got_object_get_type(&type1, repo, ids[0]);
5373 if (error)
5374 goto done;
5377 error = got_object_get_type(&type2, repo, ids[1]);
5378 if (error)
5379 goto done;
5380 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5381 error = got_error(GOT_ERR_OBJ_TYPE);
5382 goto done;
5384 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5385 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5386 "path arguments cannot be used when diffing blobs");
5387 goto done;
5390 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5391 char *in_repo_path;
5392 struct got_pathlist_entry *new;
5393 if (worktree) {
5394 const char *prefix;
5395 char *p;
5396 error = got_worktree_resolve_path(&p, worktree,
5397 argv[i]);
5398 if (error)
5399 goto done;
5400 prefix = got_worktree_get_path_prefix(worktree);
5401 while (prefix[0] == '/')
5402 prefix++;
5403 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5404 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5405 p) == -1) {
5406 error = got_error_from_errno("asprintf");
5407 free(p);
5408 goto done;
5410 free(p);
5411 } else {
5412 char *mapped_path, *s;
5413 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5414 if (error)
5415 goto done;
5416 s = mapped_path;
5417 while (s[0] == '/')
5418 s++;
5419 in_repo_path = strdup(s);
5420 if (in_repo_path == NULL) {
5421 error = got_error_from_errno("asprintf");
5422 free(mapped_path);
5423 goto done;
5425 free(mapped_path);
5428 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5429 if (error || new == NULL /* duplicate */)
5430 free(in_repo_path);
5431 if (error)
5432 goto done;
5435 if (worktree) {
5436 /* Release work tree lock. */
5437 got_worktree_close(worktree);
5438 worktree = NULL;
5441 fd1 = got_opentempfd();
5442 if (fd1 == -1) {
5443 error = got_error_from_errno("got_opentempfd");
5444 goto done;
5447 fd2 = got_opentempfd();
5448 if (fd2 == -1) {
5449 error = got_error_from_errno("got_opentempfd");
5450 goto done;
5453 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5454 case GOT_OBJ_TYPE_BLOB:
5455 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5456 fd1, fd2, ids[0], ids[1], NULL, NULL,
5457 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5458 ignore_whitespace, force_text_diff,
5459 show_diffstat ? &dsa : NULL, repo, outfile);
5460 break;
5461 case GOT_OBJ_TYPE_TREE:
5462 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5463 ids[0], ids[1], &paths, "", "",
5464 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5465 ignore_whitespace, force_text_diff,
5466 show_diffstat ? &dsa : NULL, repo, outfile);
5467 break;
5468 case GOT_OBJ_TYPE_COMMIT:
5469 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5470 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5471 fd1, fd2, ids[0], ids[1], &paths,
5472 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5473 ignore_whitespace, force_text_diff,
5474 show_diffstat ? &dsa : NULL, repo, outfile);
5475 break;
5476 default:
5477 error = got_error(GOT_ERR_OBJ_TYPE);
5479 if (error)
5480 goto done;
5482 if (show_diffstat && dsa.nfiles > 0) {
5483 char *header = NULL;
5485 if (asprintf(&header, "diffstat %s %s",
5486 labels[0], labels[1]) == -1) {
5487 error = got_error_from_errno("asprintf");
5488 goto done;
5491 error = print_diffstat(&dsa, header);
5492 free(header);
5493 if (error)
5494 goto done;
5497 error = printfile(outfile);
5499 done:
5500 free(labels[0]);
5501 free(labels[1]);
5502 free(ids[0]);
5503 free(ids[1]);
5504 if (worktree)
5505 got_worktree_close(worktree);
5506 if (repo) {
5507 const struct got_error *close_err = got_repo_close(repo);
5508 if (error == NULL)
5509 error = close_err;
5511 if (pack_fds) {
5512 const struct got_error *pack_err =
5513 got_repo_pack_fds_close(pack_fds);
5514 if (error == NULL)
5515 error = pack_err;
5517 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5518 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5519 got_ref_list_free(&refs);
5520 if (outfile && fclose(outfile) == EOF && error == NULL)
5521 error = got_error_from_errno("fclose");
5522 if (f1 && fclose(f1) == EOF && error == NULL)
5523 error = got_error_from_errno("fclose");
5524 if (f2 && fclose(f2) == EOF && error == NULL)
5525 error = got_error_from_errno("fclose");
5526 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5527 error = got_error_from_errno("close");
5528 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5529 error = got_error_from_errno("close");
5530 return error;
5533 __dead static void
5534 usage_blame(void)
5536 fprintf(stderr,
5537 "usage: %s blame [-c commit] [-r repository-path] path\n",
5538 getprogname());
5539 exit(1);
5542 struct blame_line {
5543 int annotated;
5544 char *id_str;
5545 char *committer;
5546 char datebuf[11]; /* YYYY-MM-DD + NUL */
5549 struct blame_cb_args {
5550 struct blame_line *lines;
5551 int nlines;
5552 int nlines_prec;
5553 int lineno_cur;
5554 off_t *line_offsets;
5555 FILE *f;
5556 struct got_repository *repo;
5559 static const struct got_error *
5560 blame_cb(void *arg, int nlines, int lineno,
5561 struct got_commit_object *commit, struct got_object_id *id)
5563 const struct got_error *err = NULL;
5564 struct blame_cb_args *a = arg;
5565 struct blame_line *bline;
5566 char *line = NULL;
5567 size_t linesize = 0;
5568 off_t offset;
5569 struct tm tm;
5570 time_t committer_time;
5572 if (nlines != a->nlines ||
5573 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5574 return got_error(GOT_ERR_RANGE);
5576 if (sigint_received)
5577 return got_error(GOT_ERR_ITER_COMPLETED);
5579 if (lineno == -1)
5580 return NULL; /* no change in this commit */
5582 /* Annotate this line. */
5583 bline = &a->lines[lineno - 1];
5584 if (bline->annotated)
5585 return NULL;
5586 err = got_object_id_str(&bline->id_str, id);
5587 if (err)
5588 return err;
5590 bline->committer = strdup(got_object_commit_get_committer(commit));
5591 if (bline->committer == NULL) {
5592 err = got_error_from_errno("strdup");
5593 goto done;
5596 committer_time = got_object_commit_get_committer_time(commit);
5597 if (gmtime_r(&committer_time, &tm) == NULL)
5598 return got_error_from_errno("gmtime_r");
5599 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5600 &tm) == 0) {
5601 err = got_error(GOT_ERR_NO_SPACE);
5602 goto done;
5604 bline->annotated = 1;
5606 /* Print lines annotated so far. */
5607 bline = &a->lines[a->lineno_cur - 1];
5608 if (!bline->annotated)
5609 goto done;
5611 offset = a->line_offsets[a->lineno_cur - 1];
5612 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5613 err = got_error_from_errno("fseeko");
5614 goto done;
5617 while (a->lineno_cur <= a->nlines && bline->annotated) {
5618 char *smallerthan, *at, *nl, *committer;
5619 size_t len;
5621 if (getline(&line, &linesize, a->f) == -1) {
5622 if (ferror(a->f))
5623 err = got_error_from_errno("getline");
5624 break;
5627 committer = bline->committer;
5628 smallerthan = strchr(committer, '<');
5629 if (smallerthan && smallerthan[1] != '\0')
5630 committer = smallerthan + 1;
5631 at = strchr(committer, '@');
5632 if (at)
5633 *at = '\0';
5634 len = strlen(committer);
5635 if (len >= 9)
5636 committer[8] = '\0';
5638 nl = strchr(line, '\n');
5639 if (nl)
5640 *nl = '\0';
5641 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5642 bline->id_str, bline->datebuf, committer, line);
5644 a->lineno_cur++;
5645 bline = &a->lines[a->lineno_cur - 1];
5647 done:
5648 free(line);
5649 return err;
5652 static const struct got_error *
5653 cmd_blame(int argc, char *argv[])
5655 const struct got_error *error;
5656 struct got_repository *repo = NULL;
5657 struct got_worktree *worktree = NULL;
5658 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5659 char *link_target = NULL;
5660 struct got_object_id *obj_id = NULL;
5661 struct got_object_id *commit_id = NULL;
5662 struct got_commit_object *commit = NULL;
5663 struct got_blob_object *blob = NULL;
5664 char *commit_id_str = NULL;
5665 struct blame_cb_args bca;
5666 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5667 off_t filesize;
5668 int *pack_fds = NULL;
5669 FILE *f1 = NULL, *f2 = NULL;
5671 fd1 = got_opentempfd();
5672 if (fd1 == -1)
5673 return got_error_from_errno("got_opentempfd");
5675 memset(&bca, 0, sizeof(bca));
5677 #ifndef PROFILE
5678 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5679 NULL) == -1)
5680 err(1, "pledge");
5681 #endif
5683 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5684 switch (ch) {
5685 case 'c':
5686 commit_id_str = optarg;
5687 break;
5688 case 'r':
5689 repo_path = realpath(optarg, NULL);
5690 if (repo_path == NULL)
5691 return got_error_from_errno2("realpath",
5692 optarg);
5693 got_path_strip_trailing_slashes(repo_path);
5694 break;
5695 default:
5696 usage_blame();
5697 /* NOTREACHED */
5701 argc -= optind;
5702 argv += optind;
5704 if (argc == 1)
5705 path = argv[0];
5706 else
5707 usage_blame();
5709 cwd = getcwd(NULL, 0);
5710 if (cwd == NULL) {
5711 error = got_error_from_errno("getcwd");
5712 goto done;
5715 error = got_repo_pack_fds_open(&pack_fds);
5716 if (error != NULL)
5717 goto done;
5719 if (repo_path == NULL) {
5720 error = got_worktree_open(&worktree, cwd);
5721 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5722 goto done;
5723 else
5724 error = NULL;
5725 if (worktree) {
5726 repo_path =
5727 strdup(got_worktree_get_repo_path(worktree));
5728 if (repo_path == NULL) {
5729 error = got_error_from_errno("strdup");
5730 if (error)
5731 goto done;
5733 } else {
5734 repo_path = strdup(cwd);
5735 if (repo_path == NULL) {
5736 error = got_error_from_errno("strdup");
5737 goto done;
5742 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5743 if (error != NULL)
5744 goto done;
5746 if (worktree) {
5747 const char *prefix = got_worktree_get_path_prefix(worktree);
5748 char *p;
5750 error = got_worktree_resolve_path(&p, worktree, path);
5751 if (error)
5752 goto done;
5753 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5754 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5755 p) == -1) {
5756 error = got_error_from_errno("asprintf");
5757 free(p);
5758 goto done;
5760 free(p);
5761 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5762 } else {
5763 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5764 if (error)
5765 goto done;
5766 error = got_repo_map_path(&in_repo_path, repo, path);
5768 if (error)
5769 goto done;
5771 if (commit_id_str == NULL) {
5772 struct got_reference *head_ref;
5773 error = got_ref_open(&head_ref, repo, worktree ?
5774 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5775 if (error != NULL)
5776 goto done;
5777 error = got_ref_resolve(&commit_id, repo, head_ref);
5778 got_ref_close(head_ref);
5779 if (error != NULL)
5780 goto done;
5781 } else {
5782 struct got_reflist_head refs;
5783 TAILQ_INIT(&refs);
5784 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5785 NULL);
5786 if (error)
5787 goto done;
5788 error = got_repo_match_object_id(&commit_id, NULL,
5789 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5790 got_ref_list_free(&refs);
5791 if (error)
5792 goto done;
5795 if (worktree) {
5796 /* Release work tree lock. */
5797 got_worktree_close(worktree);
5798 worktree = NULL;
5801 error = got_object_open_as_commit(&commit, repo, commit_id);
5802 if (error)
5803 goto done;
5805 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5806 commit, repo);
5807 if (error)
5808 goto done;
5810 error = got_object_id_by_path(&obj_id, repo, commit,
5811 link_target ? link_target : in_repo_path);
5812 if (error)
5813 goto done;
5815 error = got_object_get_type(&obj_type, repo, obj_id);
5816 if (error)
5817 goto done;
5819 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5820 error = got_error_path(link_target ? link_target : in_repo_path,
5821 GOT_ERR_OBJ_TYPE);
5822 goto done;
5825 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5826 if (error)
5827 goto done;
5828 bca.f = got_opentemp();
5829 if (bca.f == NULL) {
5830 error = got_error_from_errno("got_opentemp");
5831 goto done;
5833 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5834 &bca.line_offsets, bca.f, blob);
5835 if (error || bca.nlines == 0)
5836 goto done;
5838 /* Don't include \n at EOF in the blame line count. */
5839 if (bca.line_offsets[bca.nlines - 1] == filesize)
5840 bca.nlines--;
5842 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5843 if (bca.lines == NULL) {
5844 error = got_error_from_errno("calloc");
5845 goto done;
5847 bca.lineno_cur = 1;
5848 bca.nlines_prec = 0;
5849 i = bca.nlines;
5850 while (i > 0) {
5851 i /= 10;
5852 bca.nlines_prec++;
5854 bca.repo = repo;
5856 fd2 = got_opentempfd();
5857 if (fd2 == -1) {
5858 error = got_error_from_errno("got_opentempfd");
5859 goto done;
5861 fd3 = got_opentempfd();
5862 if (fd3 == -1) {
5863 error = got_error_from_errno("got_opentempfd");
5864 goto done;
5866 f1 = got_opentemp();
5867 if (f1 == NULL) {
5868 error = got_error_from_errno("got_opentemp");
5869 goto done;
5871 f2 = got_opentemp();
5872 if (f2 == NULL) {
5873 error = got_error_from_errno("got_opentemp");
5874 goto done;
5876 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5877 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5878 check_cancelled, NULL, fd2, fd3, f1, f2);
5879 done:
5880 free(in_repo_path);
5881 free(link_target);
5882 free(repo_path);
5883 free(cwd);
5884 free(commit_id);
5885 free(obj_id);
5886 if (commit)
5887 got_object_commit_close(commit);
5889 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5890 error = got_error_from_errno("close");
5891 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5892 error = got_error_from_errno("close");
5893 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5894 error = got_error_from_errno("close");
5895 if (f1 && fclose(f1) == EOF && error == NULL)
5896 error = got_error_from_errno("fclose");
5897 if (f2 && fclose(f2) == EOF && error == NULL)
5898 error = got_error_from_errno("fclose");
5900 if (blob)
5901 got_object_blob_close(blob);
5902 if (worktree)
5903 got_worktree_close(worktree);
5904 if (repo) {
5905 const struct got_error *close_err = got_repo_close(repo);
5906 if (error == NULL)
5907 error = close_err;
5909 if (pack_fds) {
5910 const struct got_error *pack_err =
5911 got_repo_pack_fds_close(pack_fds);
5912 if (error == NULL)
5913 error = pack_err;
5915 if (bca.lines) {
5916 for (i = 0; i < bca.nlines; i++) {
5917 struct blame_line *bline = &bca.lines[i];
5918 free(bline->id_str);
5919 free(bline->committer);
5921 free(bca.lines);
5923 free(bca.line_offsets);
5924 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5925 error = got_error_from_errno("fclose");
5926 return error;
5929 __dead static void
5930 usage_tree(void)
5932 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5933 "[path]\n", getprogname());
5934 exit(1);
5937 static const struct got_error *
5938 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5939 const char *root_path, struct got_repository *repo)
5941 const struct got_error *err = NULL;
5942 int is_root_path = (strcmp(path, root_path) == 0);
5943 const char *modestr = "";
5944 mode_t mode = got_tree_entry_get_mode(te);
5945 char *link_target = NULL;
5947 path += strlen(root_path);
5948 while (path[0] == '/')
5949 path++;
5951 if (got_object_tree_entry_is_submodule(te))
5952 modestr = "$";
5953 else if (S_ISLNK(mode)) {
5954 int i;
5956 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5957 if (err)
5958 return err;
5959 for (i = 0; i < strlen(link_target); i++) {
5960 if (!isprint((unsigned char)link_target[i]))
5961 link_target[i] = '?';
5964 modestr = "@";
5966 else if (S_ISDIR(mode))
5967 modestr = "/";
5968 else if (mode & S_IXUSR)
5969 modestr = "*";
5971 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5972 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5973 link_target ? " -> ": "", link_target ? link_target : "");
5975 free(link_target);
5976 return NULL;
5979 static const struct got_error *
5980 print_tree(const char *path, struct got_commit_object *commit,
5981 int show_ids, int recurse, const char *root_path,
5982 struct got_repository *repo)
5984 const struct got_error *err = NULL;
5985 struct got_object_id *tree_id = NULL;
5986 struct got_tree_object *tree = NULL;
5987 int nentries, i;
5989 err = got_object_id_by_path(&tree_id, repo, commit, path);
5990 if (err)
5991 goto done;
5993 err = got_object_open_as_tree(&tree, repo, tree_id);
5994 if (err)
5995 goto done;
5996 nentries = got_object_tree_get_nentries(tree);
5997 for (i = 0; i < nentries; i++) {
5998 struct got_tree_entry *te;
5999 char *id = NULL;
6001 if (sigint_received || sigpipe_received)
6002 break;
6004 te = got_object_tree_get_entry(tree, i);
6005 if (show_ids) {
6006 char *id_str;
6007 err = got_object_id_str(&id_str,
6008 got_tree_entry_get_id(te));
6009 if (err)
6010 goto done;
6011 if (asprintf(&id, "%s ", id_str) == -1) {
6012 err = got_error_from_errno("asprintf");
6013 free(id_str);
6014 goto done;
6016 free(id_str);
6018 err = print_entry(te, id, path, root_path, repo);
6019 free(id);
6020 if (err)
6021 goto done;
6023 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6024 char *child_path;
6025 if (asprintf(&child_path, "%s%s%s", path,
6026 path[0] == '/' && path[1] == '\0' ? "" : "/",
6027 got_tree_entry_get_name(te)) == -1) {
6028 err = got_error_from_errno("asprintf");
6029 goto done;
6031 err = print_tree(child_path, commit, show_ids, 1,
6032 root_path, repo);
6033 free(child_path);
6034 if (err)
6035 goto done;
6038 done:
6039 if (tree)
6040 got_object_tree_close(tree);
6041 free(tree_id);
6042 return err;
6045 static const struct got_error *
6046 cmd_tree(int argc, char *argv[])
6048 const struct got_error *error;
6049 struct got_repository *repo = NULL;
6050 struct got_worktree *worktree = NULL;
6051 const char *path, *refname = NULL;
6052 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6053 struct got_object_id *commit_id = NULL;
6054 struct got_commit_object *commit = NULL;
6055 char *commit_id_str = NULL;
6056 int show_ids = 0, recurse = 0;
6057 int ch;
6058 int *pack_fds = NULL;
6060 #ifndef PROFILE
6061 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6062 NULL) == -1)
6063 err(1, "pledge");
6064 #endif
6066 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6067 switch (ch) {
6068 case 'c':
6069 commit_id_str = optarg;
6070 break;
6071 case 'i':
6072 show_ids = 1;
6073 break;
6074 case 'R':
6075 recurse = 1;
6076 break;
6077 case 'r':
6078 repo_path = realpath(optarg, NULL);
6079 if (repo_path == NULL)
6080 return got_error_from_errno2("realpath",
6081 optarg);
6082 got_path_strip_trailing_slashes(repo_path);
6083 break;
6084 default:
6085 usage_tree();
6086 /* NOTREACHED */
6090 argc -= optind;
6091 argv += optind;
6093 if (argc == 1)
6094 path = argv[0];
6095 else if (argc > 1)
6096 usage_tree();
6097 else
6098 path = NULL;
6100 cwd = getcwd(NULL, 0);
6101 if (cwd == NULL) {
6102 error = got_error_from_errno("getcwd");
6103 goto done;
6106 error = got_repo_pack_fds_open(&pack_fds);
6107 if (error != NULL)
6108 goto done;
6110 if (repo_path == NULL) {
6111 error = got_worktree_open(&worktree, cwd);
6112 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6113 goto done;
6114 else
6115 error = NULL;
6116 if (worktree) {
6117 repo_path =
6118 strdup(got_worktree_get_repo_path(worktree));
6119 if (repo_path == NULL)
6120 error = got_error_from_errno("strdup");
6121 if (error)
6122 goto done;
6123 } else {
6124 repo_path = strdup(cwd);
6125 if (repo_path == NULL) {
6126 error = got_error_from_errno("strdup");
6127 goto done;
6132 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6133 if (error != NULL)
6134 goto done;
6136 if (worktree) {
6137 const char *prefix = got_worktree_get_path_prefix(worktree);
6138 char *p;
6140 if (path == NULL)
6141 path = "";
6142 error = got_worktree_resolve_path(&p, worktree, path);
6143 if (error)
6144 goto done;
6145 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6146 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6147 p) == -1) {
6148 error = got_error_from_errno("asprintf");
6149 free(p);
6150 goto done;
6152 free(p);
6153 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6154 if (error)
6155 goto done;
6156 } else {
6157 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6158 if (error)
6159 goto done;
6160 if (path == NULL)
6161 path = "/";
6162 error = got_repo_map_path(&in_repo_path, repo, path);
6163 if (error != NULL)
6164 goto done;
6167 if (commit_id_str == NULL) {
6168 struct got_reference *head_ref;
6169 if (worktree)
6170 refname = got_worktree_get_head_ref_name(worktree);
6171 else
6172 refname = GOT_REF_HEAD;
6173 error = got_ref_open(&head_ref, repo, refname, 0);
6174 if (error != NULL)
6175 goto done;
6176 error = got_ref_resolve(&commit_id, repo, head_ref);
6177 got_ref_close(head_ref);
6178 if (error != NULL)
6179 goto done;
6180 } else {
6181 struct got_reflist_head refs;
6182 TAILQ_INIT(&refs);
6183 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6184 NULL);
6185 if (error)
6186 goto done;
6187 error = got_repo_match_object_id(&commit_id, NULL,
6188 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6189 got_ref_list_free(&refs);
6190 if (error)
6191 goto done;
6194 if (worktree) {
6195 /* Release work tree lock. */
6196 got_worktree_close(worktree);
6197 worktree = NULL;
6200 error = got_object_open_as_commit(&commit, repo, commit_id);
6201 if (error)
6202 goto done;
6204 error = print_tree(in_repo_path, commit, show_ids, recurse,
6205 in_repo_path, repo);
6206 done:
6207 free(in_repo_path);
6208 free(repo_path);
6209 free(cwd);
6210 free(commit_id);
6211 if (commit)
6212 got_object_commit_close(commit);
6213 if (worktree)
6214 got_worktree_close(worktree);
6215 if (repo) {
6216 const struct got_error *close_err = got_repo_close(repo);
6217 if (error == NULL)
6218 error = close_err;
6220 if (pack_fds) {
6221 const struct got_error *pack_err =
6222 got_repo_pack_fds_close(pack_fds);
6223 if (error == NULL)
6224 error = pack_err;
6226 return error;
6229 __dead static void
6230 usage_status(void)
6232 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6233 "[-s status-codes] [path ...]\n", getprogname());
6234 exit(1);
6237 struct got_status_arg {
6238 char *status_codes;
6239 int suppress;
6242 static const struct got_error *
6243 print_status(void *arg, unsigned char status, unsigned char staged_status,
6244 const char *path, struct got_object_id *blob_id,
6245 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6246 int dirfd, const char *de_name)
6248 struct got_status_arg *st = arg;
6250 if (status == staged_status && (status == GOT_STATUS_DELETE))
6251 status = GOT_STATUS_NO_CHANGE;
6252 if (st != NULL && st->status_codes) {
6253 size_t ncodes = strlen(st->status_codes);
6254 int i, j = 0;
6256 for (i = 0; i < ncodes ; i++) {
6257 if (st->suppress) {
6258 if (status == st->status_codes[i] ||
6259 staged_status == st->status_codes[i]) {
6260 j++;
6261 continue;
6263 } else {
6264 if (status == st->status_codes[i] ||
6265 staged_status == st->status_codes[i])
6266 break;
6270 if (st->suppress && j == 0)
6271 goto print;
6273 if (i == ncodes)
6274 return NULL;
6276 print:
6277 printf("%c%c %s\n", status, staged_status, path);
6278 return NULL;
6281 static const struct got_error *
6282 cmd_status(int argc, char *argv[])
6284 const struct got_error *error = NULL;
6285 struct got_repository *repo = NULL;
6286 struct got_worktree *worktree = NULL;
6287 struct got_status_arg st;
6288 char *cwd = NULL;
6289 struct got_pathlist_head paths;
6290 int ch, i, no_ignores = 0;
6291 int *pack_fds = NULL;
6293 TAILQ_INIT(&paths);
6295 memset(&st, 0, sizeof(st));
6296 st.status_codes = NULL;
6297 st.suppress = 0;
6299 #ifndef PROFILE
6300 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6301 NULL) == -1)
6302 err(1, "pledge");
6303 #endif
6305 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6306 switch (ch) {
6307 case 'I':
6308 no_ignores = 1;
6309 break;
6310 case 'S':
6311 if (st.status_codes != NULL && st.suppress == 0)
6312 option_conflict('S', 's');
6313 st.suppress = 1;
6314 /* fallthrough */
6315 case 's':
6316 for (i = 0; i < strlen(optarg); i++) {
6317 switch (optarg[i]) {
6318 case GOT_STATUS_MODIFY:
6319 case GOT_STATUS_ADD:
6320 case GOT_STATUS_DELETE:
6321 case GOT_STATUS_CONFLICT:
6322 case GOT_STATUS_MISSING:
6323 case GOT_STATUS_OBSTRUCTED:
6324 case GOT_STATUS_UNVERSIONED:
6325 case GOT_STATUS_MODE_CHANGE:
6326 case GOT_STATUS_NONEXISTENT:
6327 break;
6328 default:
6329 errx(1, "invalid status code '%c'",
6330 optarg[i]);
6333 if (ch == 's' && st.suppress)
6334 option_conflict('s', 'S');
6335 st.status_codes = optarg;
6336 break;
6337 default:
6338 usage_status();
6339 /* NOTREACHED */
6343 argc -= optind;
6344 argv += optind;
6346 cwd = getcwd(NULL, 0);
6347 if (cwd == NULL) {
6348 error = got_error_from_errno("getcwd");
6349 goto done;
6352 error = got_repo_pack_fds_open(&pack_fds);
6353 if (error != NULL)
6354 goto done;
6356 error = got_worktree_open(&worktree, cwd);
6357 if (error) {
6358 if (error->code == GOT_ERR_NOT_WORKTREE)
6359 error = wrap_not_worktree_error(error, "status", cwd);
6360 goto done;
6363 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6364 NULL, pack_fds);
6365 if (error != NULL)
6366 goto done;
6368 error = apply_unveil(got_repo_get_path(repo), 1,
6369 got_worktree_get_root_path(worktree));
6370 if (error)
6371 goto done;
6373 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6374 if (error)
6375 goto done;
6377 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6378 print_status, &st, check_cancelled, NULL);
6379 done:
6380 if (pack_fds) {
6381 const struct got_error *pack_err =
6382 got_repo_pack_fds_close(pack_fds);
6383 if (error == NULL)
6384 error = pack_err;
6387 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6388 free(cwd);
6389 return error;
6392 __dead static void
6393 usage_ref(void)
6395 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6396 "[-s reference] [name]\n", getprogname());
6397 exit(1);
6400 static const struct got_error *
6401 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6403 static const struct got_error *err = NULL;
6404 struct got_reflist_head refs;
6405 struct got_reflist_entry *re;
6407 TAILQ_INIT(&refs);
6408 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6409 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6410 repo);
6411 if (err)
6412 return err;
6414 TAILQ_FOREACH(re, &refs, entry) {
6415 char *refstr;
6416 refstr = got_ref_to_str(re->ref);
6417 if (refstr == NULL) {
6418 err = got_error_from_errno("got_ref_to_str");
6419 break;
6421 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6422 free(refstr);
6425 got_ref_list_free(&refs);
6426 return err;
6429 static const struct got_error *
6430 delete_ref_by_name(struct got_repository *repo, const char *refname)
6432 const struct got_error *err;
6433 struct got_reference *ref;
6435 err = got_ref_open(&ref, repo, refname, 0);
6436 if (err)
6437 return err;
6439 err = delete_ref(repo, ref);
6440 got_ref_close(ref);
6441 return err;
6444 static const struct got_error *
6445 add_ref(struct got_repository *repo, const char *refname, const char *target)
6447 const struct got_error *err = NULL;
6448 struct got_object_id *id = NULL;
6449 struct got_reference *ref = NULL;
6450 struct got_reflist_head refs;
6453 * Don't let the user create a reference name with a leading '-'.
6454 * While technically a valid reference name, this case is usually
6455 * an unintended typo.
6457 if (refname[0] == '-')
6458 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6460 TAILQ_INIT(&refs);
6461 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6462 if (err)
6463 goto done;
6464 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6465 &refs, repo);
6466 got_ref_list_free(&refs);
6467 if (err)
6468 goto done;
6470 err = got_ref_alloc(&ref, refname, id);
6471 if (err)
6472 goto done;
6474 err = got_ref_write(ref, repo);
6475 done:
6476 if (ref)
6477 got_ref_close(ref);
6478 free(id);
6479 return err;
6482 static const struct got_error *
6483 add_symref(struct got_repository *repo, const char *refname, const char *target)
6485 const struct got_error *err = NULL;
6486 struct got_reference *ref = NULL;
6487 struct got_reference *target_ref = NULL;
6490 * Don't let the user create a reference name with a leading '-'.
6491 * While technically a valid reference name, this case is usually
6492 * an unintended typo.
6494 if (refname[0] == '-')
6495 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6497 err = got_ref_open(&target_ref, repo, target, 0);
6498 if (err)
6499 return err;
6501 err = got_ref_alloc_symref(&ref, refname, target_ref);
6502 if (err)
6503 goto done;
6505 err = got_ref_write(ref, repo);
6506 done:
6507 if (target_ref)
6508 got_ref_close(target_ref);
6509 if (ref)
6510 got_ref_close(ref);
6511 return err;
6514 static const struct got_error *
6515 cmd_ref(int argc, char *argv[])
6517 const struct got_error *error = NULL;
6518 struct got_repository *repo = NULL;
6519 struct got_worktree *worktree = NULL;
6520 char *cwd = NULL, *repo_path = NULL;
6521 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6522 const char *obj_arg = NULL, *symref_target= NULL;
6523 char *refname = NULL;
6524 int *pack_fds = NULL;
6526 #ifndef PROFILE
6527 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6528 "sendfd unveil", NULL) == -1)
6529 err(1, "pledge");
6530 #endif
6532 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6533 switch (ch) {
6534 case 'c':
6535 obj_arg = optarg;
6536 break;
6537 case 'd':
6538 do_delete = 1;
6539 break;
6540 case 'l':
6541 do_list = 1;
6542 break;
6543 case 'r':
6544 repo_path = realpath(optarg, NULL);
6545 if (repo_path == NULL)
6546 return got_error_from_errno2("realpath",
6547 optarg);
6548 got_path_strip_trailing_slashes(repo_path);
6549 break;
6550 case 's':
6551 symref_target = optarg;
6552 break;
6553 case 't':
6554 sort_by_time = 1;
6555 break;
6556 default:
6557 usage_ref();
6558 /* NOTREACHED */
6562 if (obj_arg && do_list)
6563 option_conflict('c', 'l');
6564 if (obj_arg && do_delete)
6565 option_conflict('c', 'd');
6566 if (obj_arg && symref_target)
6567 option_conflict('c', 's');
6568 if (symref_target && do_delete)
6569 option_conflict('s', 'd');
6570 if (symref_target && do_list)
6571 option_conflict('s', 'l');
6572 if (do_delete && do_list)
6573 option_conflict('d', 'l');
6574 if (sort_by_time && !do_list)
6575 errx(1, "-t option requires -l option");
6577 argc -= optind;
6578 argv += optind;
6580 if (do_list) {
6581 if (argc != 0 && argc != 1)
6582 usage_ref();
6583 if (argc == 1) {
6584 refname = strdup(argv[0]);
6585 if (refname == NULL) {
6586 error = got_error_from_errno("strdup");
6587 goto done;
6590 } else {
6591 if (argc != 1)
6592 usage_ref();
6593 refname = strdup(argv[0]);
6594 if (refname == NULL) {
6595 error = got_error_from_errno("strdup");
6596 goto done;
6600 if (refname)
6601 got_path_strip_trailing_slashes(refname);
6603 cwd = getcwd(NULL, 0);
6604 if (cwd == NULL) {
6605 error = got_error_from_errno("getcwd");
6606 goto done;
6609 error = got_repo_pack_fds_open(&pack_fds);
6610 if (error != NULL)
6611 goto done;
6613 if (repo_path == NULL) {
6614 error = got_worktree_open(&worktree, cwd);
6615 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6616 goto done;
6617 else
6618 error = NULL;
6619 if (worktree) {
6620 repo_path =
6621 strdup(got_worktree_get_repo_path(worktree));
6622 if (repo_path == NULL)
6623 error = got_error_from_errno("strdup");
6624 if (error)
6625 goto done;
6626 } else {
6627 repo_path = strdup(cwd);
6628 if (repo_path == NULL) {
6629 error = got_error_from_errno("strdup");
6630 goto done;
6635 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6636 if (error != NULL)
6637 goto done;
6639 #ifndef PROFILE
6640 if (do_list) {
6641 /* Remove "cpath" promise. */
6642 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6643 NULL) == -1)
6644 err(1, "pledge");
6646 #endif
6648 error = apply_unveil(got_repo_get_path(repo), do_list,
6649 worktree ? got_worktree_get_root_path(worktree) : NULL);
6650 if (error)
6651 goto done;
6653 if (do_list)
6654 error = list_refs(repo, refname, sort_by_time);
6655 else if (do_delete)
6656 error = delete_ref_by_name(repo, refname);
6657 else if (symref_target)
6658 error = add_symref(repo, refname, symref_target);
6659 else {
6660 if (obj_arg == NULL)
6661 usage_ref();
6662 error = add_ref(repo, refname, obj_arg);
6664 done:
6665 free(refname);
6666 if (repo) {
6667 const struct got_error *close_err = got_repo_close(repo);
6668 if (error == NULL)
6669 error = close_err;
6671 if (worktree)
6672 got_worktree_close(worktree);
6673 if (pack_fds) {
6674 const struct got_error *pack_err =
6675 got_repo_pack_fds_close(pack_fds);
6676 if (error == NULL)
6677 error = pack_err;
6679 free(cwd);
6680 free(repo_path);
6681 return error;
6684 __dead static void
6685 usage_branch(void)
6687 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6688 "[-r repository-path] [name]\n", getprogname());
6689 exit(1);
6692 static const struct got_error *
6693 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6694 struct got_reference *ref)
6696 const struct got_error *err = NULL;
6697 const char *refname, *marker = " ";
6698 char *refstr;
6700 refname = got_ref_get_name(ref);
6701 if (worktree && strcmp(refname,
6702 got_worktree_get_head_ref_name(worktree)) == 0) {
6703 struct got_object_id *id = NULL;
6705 err = got_ref_resolve(&id, repo, ref);
6706 if (err)
6707 return err;
6708 if (got_object_id_cmp(id,
6709 got_worktree_get_base_commit_id(worktree)) == 0)
6710 marker = "* ";
6711 else
6712 marker = "~ ";
6713 free(id);
6716 if (strncmp(refname, "refs/heads/", 11) == 0)
6717 refname += 11;
6718 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6719 refname += 18;
6720 if (strncmp(refname, "refs/remotes/", 13) == 0)
6721 refname += 13;
6723 refstr = got_ref_to_str(ref);
6724 if (refstr == NULL)
6725 return got_error_from_errno("got_ref_to_str");
6727 printf("%s%s: %s\n", marker, refname, refstr);
6728 free(refstr);
6729 return NULL;
6732 static const struct got_error *
6733 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6735 const char *refname;
6737 if (worktree == NULL)
6738 return got_error(GOT_ERR_NOT_WORKTREE);
6740 refname = got_worktree_get_head_ref_name(worktree);
6742 if (strncmp(refname, "refs/heads/", 11) == 0)
6743 refname += 11;
6744 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6745 refname += 18;
6747 printf("%s\n", refname);
6749 return NULL;
6752 static const struct got_error *
6753 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6754 int sort_by_time)
6756 static const struct got_error *err = NULL;
6757 struct got_reflist_head refs;
6758 struct got_reflist_entry *re;
6759 struct got_reference *temp_ref = NULL;
6760 int rebase_in_progress, histedit_in_progress;
6762 TAILQ_INIT(&refs);
6764 if (worktree) {
6765 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6766 worktree);
6767 if (err)
6768 return err;
6770 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6771 worktree);
6772 if (err)
6773 return err;
6775 if (rebase_in_progress || histedit_in_progress) {
6776 err = got_ref_open(&temp_ref, repo,
6777 got_worktree_get_head_ref_name(worktree), 0);
6778 if (err)
6779 return err;
6780 list_branch(repo, worktree, temp_ref);
6781 got_ref_close(temp_ref);
6785 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6786 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6787 repo);
6788 if (err)
6789 return err;
6791 TAILQ_FOREACH(re, &refs, entry)
6792 list_branch(repo, worktree, re->ref);
6794 got_ref_list_free(&refs);
6796 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6797 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6798 repo);
6799 if (err)
6800 return err;
6802 TAILQ_FOREACH(re, &refs, entry)
6803 list_branch(repo, worktree, re->ref);
6805 got_ref_list_free(&refs);
6807 return NULL;
6810 static const struct got_error *
6811 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6812 const char *branch_name)
6814 const struct got_error *err = NULL;
6815 struct got_reference *ref = NULL;
6816 char *refname, *remote_refname = NULL;
6818 if (strncmp(branch_name, "refs/", 5) == 0)
6819 branch_name += 5;
6820 if (strncmp(branch_name, "heads/", 6) == 0)
6821 branch_name += 6;
6822 else if (strncmp(branch_name, "remotes/", 8) == 0)
6823 branch_name += 8;
6825 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6826 return got_error_from_errno("asprintf");
6828 if (asprintf(&remote_refname, "refs/remotes/%s",
6829 branch_name) == -1) {
6830 err = got_error_from_errno("asprintf");
6831 goto done;
6834 err = got_ref_open(&ref, repo, refname, 0);
6835 if (err) {
6836 const struct got_error *err2;
6837 if (err->code != GOT_ERR_NOT_REF)
6838 goto done;
6840 * Keep 'err' intact such that if neither branch exists
6841 * we report "refs/heads" rather than "refs/remotes" in
6842 * our error message.
6844 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6845 if (err2)
6846 goto done;
6847 err = NULL;
6850 if (worktree &&
6851 strcmp(got_worktree_get_head_ref_name(worktree),
6852 got_ref_get_name(ref)) == 0) {
6853 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6854 "will not delete this work tree's current branch");
6855 goto done;
6858 err = delete_ref(repo, ref);
6859 done:
6860 if (ref)
6861 got_ref_close(ref);
6862 free(refname);
6863 free(remote_refname);
6864 return err;
6867 static const struct got_error *
6868 add_branch(struct got_repository *repo, const char *branch_name,
6869 struct got_object_id *base_commit_id)
6871 const struct got_error *err = NULL;
6872 struct got_reference *ref = NULL;
6873 char *refname = NULL;
6876 * Don't let the user create a branch name with a leading '-'.
6877 * While technically a valid reference name, this case is usually
6878 * an unintended typo.
6880 if (branch_name[0] == '-')
6881 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6883 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6884 branch_name += 11;
6886 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6887 err = got_error_from_errno("asprintf");
6888 goto done;
6891 err = got_ref_open(&ref, repo, refname, 0);
6892 if (err == NULL) {
6893 err = got_error(GOT_ERR_BRANCH_EXISTS);
6894 goto done;
6895 } else if (err->code != GOT_ERR_NOT_REF)
6896 goto done;
6898 err = got_ref_alloc(&ref, refname, base_commit_id);
6899 if (err)
6900 goto done;
6902 err = got_ref_write(ref, repo);
6903 done:
6904 if (ref)
6905 got_ref_close(ref);
6906 free(refname);
6907 return err;
6910 static const struct got_error *
6911 cmd_branch(int argc, char *argv[])
6913 const struct got_error *error = NULL;
6914 struct got_repository *repo = NULL;
6915 struct got_worktree *worktree = NULL;
6916 char *cwd = NULL, *repo_path = NULL;
6917 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6918 const char *delref = NULL, *commit_id_arg = NULL;
6919 struct got_reference *ref = NULL;
6920 struct got_pathlist_head paths;
6921 struct got_object_id *commit_id = NULL;
6922 char *commit_id_str = NULL;
6923 int *pack_fds = NULL;
6925 TAILQ_INIT(&paths);
6927 #ifndef PROFILE
6928 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6929 "sendfd unveil", NULL) == -1)
6930 err(1, "pledge");
6931 #endif
6933 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6934 switch (ch) {
6935 case 'c':
6936 commit_id_arg = optarg;
6937 break;
6938 case 'd':
6939 delref = optarg;
6940 break;
6941 case 'l':
6942 do_list = 1;
6943 break;
6944 case 'n':
6945 do_update = 0;
6946 break;
6947 case 'r':
6948 repo_path = realpath(optarg, NULL);
6949 if (repo_path == NULL)
6950 return got_error_from_errno2("realpath",
6951 optarg);
6952 got_path_strip_trailing_slashes(repo_path);
6953 break;
6954 case 't':
6955 sort_by_time = 1;
6956 break;
6957 default:
6958 usage_branch();
6959 /* NOTREACHED */
6963 if (do_list && delref)
6964 option_conflict('l', 'd');
6965 if (sort_by_time && !do_list)
6966 errx(1, "-t option requires -l option");
6968 argc -= optind;
6969 argv += optind;
6971 if (!do_list && !delref && argc == 0)
6972 do_show = 1;
6974 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6975 errx(1, "-c option can only be used when creating a branch");
6977 if (do_list || delref) {
6978 if (argc > 0)
6979 usage_branch();
6980 } else if (!do_show && argc != 1)
6981 usage_branch();
6983 cwd = getcwd(NULL, 0);
6984 if (cwd == NULL) {
6985 error = got_error_from_errno("getcwd");
6986 goto done;
6989 error = got_repo_pack_fds_open(&pack_fds);
6990 if (error != NULL)
6991 goto done;
6993 if (repo_path == NULL) {
6994 error = got_worktree_open(&worktree, cwd);
6995 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6996 goto done;
6997 else
6998 error = NULL;
6999 if (worktree) {
7000 repo_path =
7001 strdup(got_worktree_get_repo_path(worktree));
7002 if (repo_path == NULL)
7003 error = got_error_from_errno("strdup");
7004 if (error)
7005 goto done;
7006 } else {
7007 repo_path = strdup(cwd);
7008 if (repo_path == NULL) {
7009 error = got_error_from_errno("strdup");
7010 goto done;
7015 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7016 if (error != NULL)
7017 goto done;
7019 #ifndef PROFILE
7020 if (do_list || do_show) {
7021 /* Remove "cpath" promise. */
7022 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7023 NULL) == -1)
7024 err(1, "pledge");
7026 #endif
7028 error = apply_unveil(got_repo_get_path(repo), do_list,
7029 worktree ? got_worktree_get_root_path(worktree) : NULL);
7030 if (error)
7031 goto done;
7033 if (do_show)
7034 error = show_current_branch(repo, worktree);
7035 else if (do_list)
7036 error = list_branches(repo, worktree, sort_by_time);
7037 else if (delref)
7038 error = delete_branch(repo, worktree, delref);
7039 else {
7040 struct got_reflist_head refs;
7041 TAILQ_INIT(&refs);
7042 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7043 NULL);
7044 if (error)
7045 goto done;
7046 if (commit_id_arg == NULL)
7047 commit_id_arg = worktree ?
7048 got_worktree_get_head_ref_name(worktree) :
7049 GOT_REF_HEAD;
7050 error = got_repo_match_object_id(&commit_id, NULL,
7051 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7052 got_ref_list_free(&refs);
7053 if (error)
7054 goto done;
7055 error = add_branch(repo, argv[0], commit_id);
7056 if (error)
7057 goto done;
7058 if (worktree && do_update) {
7059 struct got_update_progress_arg upa;
7060 char *branch_refname = NULL;
7062 error = got_object_id_str(&commit_id_str, commit_id);
7063 if (error)
7064 goto done;
7065 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7066 worktree);
7067 if (error)
7068 goto done;
7069 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7070 == -1) {
7071 error = got_error_from_errno("asprintf");
7072 goto done;
7074 error = got_ref_open(&ref, repo, branch_refname, 0);
7075 free(branch_refname);
7076 if (error)
7077 goto done;
7078 error = switch_head_ref(ref, commit_id, worktree,
7079 repo);
7080 if (error)
7081 goto done;
7082 error = got_worktree_set_base_commit_id(worktree, repo,
7083 commit_id);
7084 if (error)
7085 goto done;
7086 memset(&upa, 0, sizeof(upa));
7087 error = got_worktree_checkout_files(worktree, &paths,
7088 repo, update_progress, &upa, check_cancelled,
7089 NULL);
7090 if (error)
7091 goto done;
7092 if (upa.did_something) {
7093 printf("Updated to %s: %s\n",
7094 got_worktree_get_head_ref_name(worktree),
7095 commit_id_str);
7097 print_update_progress_stats(&upa);
7100 done:
7101 if (ref)
7102 got_ref_close(ref);
7103 if (repo) {
7104 const struct got_error *close_err = got_repo_close(repo);
7105 if (error == NULL)
7106 error = close_err;
7108 if (worktree)
7109 got_worktree_close(worktree);
7110 if (pack_fds) {
7111 const struct got_error *pack_err =
7112 got_repo_pack_fds_close(pack_fds);
7113 if (error == NULL)
7114 error = pack_err;
7116 free(cwd);
7117 free(repo_path);
7118 free(commit_id);
7119 free(commit_id_str);
7120 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7121 return error;
7125 __dead static void
7126 usage_tag(void)
7128 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7129 "[-r repository-path] [-s signer-id] name\n", getprogname());
7130 exit(1);
7133 #if 0
7134 static const struct got_error *
7135 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7137 const struct got_error *err = NULL;
7138 struct got_reflist_entry *re, *se, *new;
7139 struct got_object_id *re_id, *se_id;
7140 struct got_tag_object *re_tag, *se_tag;
7141 time_t re_time, se_time;
7143 STAILQ_FOREACH(re, tags, entry) {
7144 se = STAILQ_FIRST(sorted);
7145 if (se == NULL) {
7146 err = got_reflist_entry_dup(&new, re);
7147 if (err)
7148 return err;
7149 STAILQ_INSERT_HEAD(sorted, new, entry);
7150 continue;
7151 } else {
7152 err = got_ref_resolve(&re_id, repo, re->ref);
7153 if (err)
7154 break;
7155 err = got_object_open_as_tag(&re_tag, repo, re_id);
7156 free(re_id);
7157 if (err)
7158 break;
7159 re_time = got_object_tag_get_tagger_time(re_tag);
7160 got_object_tag_close(re_tag);
7163 while (se) {
7164 err = got_ref_resolve(&se_id, repo, re->ref);
7165 if (err)
7166 break;
7167 err = got_object_open_as_tag(&se_tag, repo, se_id);
7168 free(se_id);
7169 if (err)
7170 break;
7171 se_time = got_object_tag_get_tagger_time(se_tag);
7172 got_object_tag_close(se_tag);
7174 if (se_time > re_time) {
7175 err = got_reflist_entry_dup(&new, re);
7176 if (err)
7177 return err;
7178 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7179 break;
7181 se = STAILQ_NEXT(se, entry);
7182 continue;
7185 done:
7186 return err;
7188 #endif
7190 static const struct got_error *
7191 get_tag_refname(char **refname, const char *tag_name)
7193 const struct got_error *err;
7195 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7196 *refname = strdup(tag_name);
7197 if (*refname == NULL)
7198 return got_error_from_errno("strdup");
7199 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7200 err = got_error_from_errno("asprintf");
7201 *refname = NULL;
7202 return err;
7205 return NULL;
7208 static const struct got_error *
7209 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7210 const char *allowed_signers, const char *revoked_signers, int verbosity)
7212 static const struct got_error *err = NULL;
7213 struct got_reflist_head refs;
7214 struct got_reflist_entry *re;
7215 char *wanted_refname = NULL;
7216 int bad_sigs = 0;
7218 TAILQ_INIT(&refs);
7220 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7221 if (err)
7222 return err;
7224 if (tag_name) {
7225 struct got_reference *ref;
7226 err = get_tag_refname(&wanted_refname, tag_name);
7227 if (err)
7228 goto done;
7229 /* Wanted tag reference should exist. */
7230 err = got_ref_open(&ref, repo, wanted_refname, 0);
7231 if (err)
7232 goto done;
7233 got_ref_close(ref);
7236 TAILQ_FOREACH(re, &refs, entry) {
7237 const char *refname;
7238 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7239 char datebuf[26];
7240 const char *tagger, *ssh_sig = NULL;
7241 char *sig_msg = NULL;
7242 time_t tagger_time;
7243 struct got_object_id *id;
7244 struct got_tag_object *tag;
7245 struct got_commit_object *commit = NULL;
7247 refname = got_ref_get_name(re->ref);
7248 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7249 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7250 continue;
7251 refname += 10;
7252 refstr = got_ref_to_str(re->ref);
7253 if (refstr == NULL) {
7254 err = got_error_from_errno("got_ref_to_str");
7255 break;
7258 err = got_ref_resolve(&id, repo, re->ref);
7259 if (err)
7260 break;
7261 err = got_object_open_as_tag(&tag, repo, id);
7262 if (err) {
7263 if (err->code != GOT_ERR_OBJ_TYPE) {
7264 free(id);
7265 break;
7267 /* "lightweight" tag */
7268 err = got_object_open_as_commit(&commit, repo, id);
7269 if (err) {
7270 free(id);
7271 break;
7273 tagger = got_object_commit_get_committer(commit);
7274 tagger_time =
7275 got_object_commit_get_committer_time(commit);
7276 err = got_object_id_str(&id_str, id);
7277 free(id);
7278 if (err)
7279 break;
7280 } else {
7281 free(id);
7282 tagger = got_object_tag_get_tagger(tag);
7283 tagger_time = got_object_tag_get_tagger_time(tag);
7284 err = got_object_id_str(&id_str,
7285 got_object_tag_get_object_id(tag));
7286 if (err)
7287 break;
7290 if (tag && verify_tags) {
7291 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7292 got_object_tag_get_message(tag));
7293 if (ssh_sig && allowed_signers == NULL) {
7294 err = got_error_msg(
7295 GOT_ERR_VERIFY_TAG_SIGNATURE,
7296 "SSH signature verification requires "
7297 "setting allowed_signers in "
7298 "got.conf(5)");
7299 break;
7303 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7304 free(refstr);
7305 printf("from: %s\n", tagger);
7306 datestr = get_datestr(&tagger_time, datebuf);
7307 if (datestr)
7308 printf("date: %s UTC\n", datestr);
7309 if (commit)
7310 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7311 else {
7312 switch (got_object_tag_get_object_type(tag)) {
7313 case GOT_OBJ_TYPE_BLOB:
7314 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7315 id_str);
7316 break;
7317 case GOT_OBJ_TYPE_TREE:
7318 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7319 id_str);
7320 break;
7321 case GOT_OBJ_TYPE_COMMIT:
7322 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7323 id_str);
7324 break;
7325 case GOT_OBJ_TYPE_TAG:
7326 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7327 id_str);
7328 break;
7329 default:
7330 break;
7333 free(id_str);
7335 if (ssh_sig) {
7336 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7337 allowed_signers, revoked_signers, verbosity);
7338 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7339 bad_sigs = 1;
7340 else if (err)
7341 break;
7342 printf("signature: %s", sig_msg);
7343 free(sig_msg);
7344 sig_msg = NULL;
7347 if (commit) {
7348 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7349 if (err)
7350 break;
7351 got_object_commit_close(commit);
7352 } else {
7353 tagmsg0 = strdup(got_object_tag_get_message(tag));
7354 got_object_tag_close(tag);
7355 if (tagmsg0 == NULL) {
7356 err = got_error_from_errno("strdup");
7357 break;
7361 tagmsg = tagmsg0;
7362 do {
7363 line = strsep(&tagmsg, "\n");
7364 if (line)
7365 printf(" %s\n", line);
7366 } while (line);
7367 free(tagmsg0);
7369 done:
7370 got_ref_list_free(&refs);
7371 free(wanted_refname);
7373 if (err == NULL && bad_sigs)
7374 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7375 return err;
7378 static const struct got_error *
7379 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7380 const char *tag_name, const char *repo_path)
7382 const struct got_error *err = NULL;
7383 char *template = NULL, *initial_content = NULL;
7384 char *editor = NULL;
7385 int initial_content_len;
7386 int fd = -1;
7388 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7389 err = got_error_from_errno("asprintf");
7390 goto done;
7393 initial_content_len = asprintf(&initial_content,
7394 "\n# tagging commit %s as %s\n",
7395 commit_id_str, tag_name);
7396 if (initial_content_len == -1) {
7397 err = got_error_from_errno("asprintf");
7398 goto done;
7401 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7402 if (err)
7403 goto done;
7405 if (write(fd, initial_content, initial_content_len) == -1) {
7406 err = got_error_from_errno2("write", *tagmsg_path);
7407 goto done;
7410 err = get_editor(&editor);
7411 if (err)
7412 goto done;
7413 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7414 initial_content_len, 1);
7415 done:
7416 free(initial_content);
7417 free(template);
7418 free(editor);
7420 if (fd != -1 && close(fd) == -1 && err == NULL)
7421 err = got_error_from_errno2("close", *tagmsg_path);
7423 if (err) {
7424 free(*tagmsg);
7425 *tagmsg = NULL;
7427 return err;
7430 static const struct got_error *
7431 add_tag(struct got_repository *repo, const char *tagger,
7432 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7433 const char *signer_id, int verbosity)
7435 const struct got_error *err = NULL;
7436 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7437 char *label = NULL, *commit_id_str = NULL;
7438 struct got_reference *ref = NULL;
7439 char *refname = NULL, *tagmsg = NULL;
7440 char *tagmsg_path = NULL, *tag_id_str = NULL;
7441 int preserve_tagmsg = 0;
7442 struct got_reflist_head refs;
7444 TAILQ_INIT(&refs);
7447 * Don't let the user create a tag name with a leading '-'.
7448 * While technically a valid reference name, this case is usually
7449 * an unintended typo.
7451 if (tag_name[0] == '-')
7452 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7454 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7455 if (err)
7456 goto done;
7458 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7459 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7460 if (err)
7461 goto done;
7463 err = got_object_id_str(&commit_id_str, commit_id);
7464 if (err)
7465 goto done;
7467 err = get_tag_refname(&refname, tag_name);
7468 if (err)
7469 goto done;
7470 if (strncmp("refs/tags/", tag_name, 10) == 0)
7471 tag_name += 10;
7473 err = got_ref_open(&ref, repo, refname, 0);
7474 if (err == NULL) {
7475 err = got_error(GOT_ERR_TAG_EXISTS);
7476 goto done;
7477 } else if (err->code != GOT_ERR_NOT_REF)
7478 goto done;
7480 if (tagmsg_arg == NULL) {
7481 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7482 tag_name, got_repo_get_path(repo));
7483 if (err) {
7484 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7485 tagmsg_path != NULL)
7486 preserve_tagmsg = 1;
7487 goto done;
7489 /* Editor is done; we can now apply unveil(2) */
7490 err = got_sigs_apply_unveil();
7491 if (err)
7492 goto done;
7493 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7494 if (err)
7495 goto done;
7498 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7499 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7500 verbosity);
7501 if (err) {
7502 if (tagmsg_path)
7503 preserve_tagmsg = 1;
7504 goto done;
7507 err = got_ref_alloc(&ref, refname, tag_id);
7508 if (err) {
7509 if (tagmsg_path)
7510 preserve_tagmsg = 1;
7511 goto done;
7514 err = got_ref_write(ref, repo);
7515 if (err) {
7516 if (tagmsg_path)
7517 preserve_tagmsg = 1;
7518 goto done;
7521 err = got_object_id_str(&tag_id_str, tag_id);
7522 if (err) {
7523 if (tagmsg_path)
7524 preserve_tagmsg = 1;
7525 goto done;
7527 printf("Created tag %s\n", tag_id_str);
7528 done:
7529 if (preserve_tagmsg) {
7530 fprintf(stderr, "%s: tag message preserved in %s\n",
7531 getprogname(), tagmsg_path);
7532 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7533 err = got_error_from_errno2("unlink", tagmsg_path);
7534 free(tag_id_str);
7535 if (ref)
7536 got_ref_close(ref);
7537 free(commit_id);
7538 free(commit_id_str);
7539 free(refname);
7540 free(tagmsg);
7541 free(tagmsg_path);
7542 got_ref_list_free(&refs);
7543 return err;
7546 static const struct got_error *
7547 cmd_tag(int argc, char *argv[])
7549 const struct got_error *error = NULL;
7550 struct got_repository *repo = NULL;
7551 struct got_worktree *worktree = NULL;
7552 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7553 char *gitconfig_path = NULL, *tagger = NULL;
7554 char *allowed_signers = NULL, *revoked_signers = NULL;
7555 const char *signer_id = NULL;
7556 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7557 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7558 int *pack_fds = NULL;
7560 #ifndef PROFILE
7561 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7562 "sendfd unveil", NULL) == -1)
7563 err(1, "pledge");
7564 #endif
7566 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7567 switch (ch) {
7568 case 'c':
7569 commit_id_arg = optarg;
7570 break;
7571 case 'l':
7572 do_list = 1;
7573 break;
7574 case 'm':
7575 tagmsg = optarg;
7576 break;
7577 case 'r':
7578 repo_path = realpath(optarg, NULL);
7579 if (repo_path == NULL) {
7580 error = got_error_from_errno2("realpath",
7581 optarg);
7582 goto done;
7584 got_path_strip_trailing_slashes(repo_path);
7585 break;
7586 case 's':
7587 signer_id = optarg;
7588 break;
7589 case 'V':
7590 verify_tags = 1;
7591 break;
7592 case 'v':
7593 if (verbosity < 0)
7594 verbosity = 0;
7595 else if (verbosity < 3)
7596 verbosity++;
7597 break;
7598 default:
7599 usage_tag();
7600 /* NOTREACHED */
7604 argc -= optind;
7605 argv += optind;
7607 if (do_list || verify_tags) {
7608 if (commit_id_arg != NULL)
7609 errx(1,
7610 "-c option can only be used when creating a tag");
7611 if (tagmsg) {
7612 if (do_list)
7613 option_conflict('l', 'm');
7614 else
7615 option_conflict('V', 'm');
7617 if (signer_id) {
7618 if (do_list)
7619 option_conflict('l', 's');
7620 else
7621 option_conflict('V', 's');
7623 if (argc > 1)
7624 usage_tag();
7625 } else if (argc != 1)
7626 usage_tag();
7628 if (argc == 1)
7629 tag_name = argv[0];
7631 cwd = getcwd(NULL, 0);
7632 if (cwd == NULL) {
7633 error = got_error_from_errno("getcwd");
7634 goto done;
7637 error = got_repo_pack_fds_open(&pack_fds);
7638 if (error != NULL)
7639 goto done;
7641 if (repo_path == NULL) {
7642 error = got_worktree_open(&worktree, cwd);
7643 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7644 goto done;
7645 else
7646 error = NULL;
7647 if (worktree) {
7648 repo_path =
7649 strdup(got_worktree_get_repo_path(worktree));
7650 if (repo_path == NULL)
7651 error = got_error_from_errno("strdup");
7652 if (error)
7653 goto done;
7654 } else {
7655 repo_path = strdup(cwd);
7656 if (repo_path == NULL) {
7657 error = got_error_from_errno("strdup");
7658 goto done;
7663 if (do_list || verify_tags) {
7664 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7665 if (error != NULL)
7666 goto done;
7667 error = get_allowed_signers(&allowed_signers, repo, worktree);
7668 if (error)
7669 goto done;
7670 error = get_revoked_signers(&revoked_signers, repo, worktree);
7671 if (error)
7672 goto done;
7673 if (worktree) {
7674 /* Release work tree lock. */
7675 got_worktree_close(worktree);
7676 worktree = NULL;
7680 * Remove "cpath" promise unless needed for signature tmpfile
7681 * creation.
7683 if (verify_tags)
7684 got_sigs_apply_unveil();
7685 else {
7686 #ifndef PROFILE
7687 if (pledge("stdio rpath wpath flock proc exec sendfd "
7688 "unveil", NULL) == -1)
7689 err(1, "pledge");
7690 #endif
7692 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7693 if (error)
7694 goto done;
7695 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7696 revoked_signers, verbosity);
7697 } else {
7698 error = get_gitconfig_path(&gitconfig_path);
7699 if (error)
7700 goto done;
7701 error = got_repo_open(&repo, repo_path, gitconfig_path,
7702 pack_fds);
7703 if (error != NULL)
7704 goto done;
7706 error = get_author(&tagger, repo, worktree);
7707 if (error)
7708 goto done;
7709 if (signer_id == NULL)
7710 signer_id = get_signer_id(repo, worktree);
7712 if (tagmsg) {
7713 if (signer_id) {
7714 error = got_sigs_apply_unveil();
7715 if (error)
7716 goto done;
7718 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7719 if (error)
7720 goto done;
7723 if (commit_id_arg == NULL) {
7724 struct got_reference *head_ref;
7725 struct got_object_id *commit_id;
7726 error = got_ref_open(&head_ref, repo,
7727 worktree ? got_worktree_get_head_ref_name(worktree)
7728 : GOT_REF_HEAD, 0);
7729 if (error)
7730 goto done;
7731 error = got_ref_resolve(&commit_id, repo, head_ref);
7732 got_ref_close(head_ref);
7733 if (error)
7734 goto done;
7735 error = got_object_id_str(&commit_id_str, commit_id);
7736 free(commit_id);
7737 if (error)
7738 goto done;
7741 if (worktree) {
7742 /* Release work tree lock. */
7743 got_worktree_close(worktree);
7744 worktree = NULL;
7747 error = add_tag(repo, tagger, tag_name,
7748 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7749 signer_id, verbosity);
7751 done:
7752 if (repo) {
7753 const struct got_error *close_err = got_repo_close(repo);
7754 if (error == NULL)
7755 error = close_err;
7757 if (worktree)
7758 got_worktree_close(worktree);
7759 if (pack_fds) {
7760 const struct got_error *pack_err =
7761 got_repo_pack_fds_close(pack_fds);
7762 if (error == NULL)
7763 error = pack_err;
7765 free(cwd);
7766 free(repo_path);
7767 free(gitconfig_path);
7768 free(commit_id_str);
7769 free(tagger);
7770 free(allowed_signers);
7771 free(revoked_signers);
7772 return error;
7775 __dead static void
7776 usage_add(void)
7778 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7779 exit(1);
7782 static const struct got_error *
7783 add_progress(void *arg, unsigned char status, const char *path)
7785 while (path[0] == '/')
7786 path++;
7787 printf("%c %s\n", status, path);
7788 return NULL;
7791 static const struct got_error *
7792 cmd_add(int argc, char *argv[])
7794 const struct got_error *error = NULL;
7795 struct got_repository *repo = NULL;
7796 struct got_worktree *worktree = NULL;
7797 char *cwd = NULL;
7798 struct got_pathlist_head paths;
7799 struct got_pathlist_entry *pe;
7800 int ch, can_recurse = 0, no_ignores = 0;
7801 int *pack_fds = NULL;
7803 TAILQ_INIT(&paths);
7805 #ifndef PROFILE
7806 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7807 NULL) == -1)
7808 err(1, "pledge");
7809 #endif
7811 while ((ch = getopt(argc, argv, "IR")) != -1) {
7812 switch (ch) {
7813 case 'I':
7814 no_ignores = 1;
7815 break;
7816 case 'R':
7817 can_recurse = 1;
7818 break;
7819 default:
7820 usage_add();
7821 /* NOTREACHED */
7825 argc -= optind;
7826 argv += optind;
7828 if (argc < 1)
7829 usage_add();
7831 cwd = getcwd(NULL, 0);
7832 if (cwd == NULL) {
7833 error = got_error_from_errno("getcwd");
7834 goto done;
7837 error = got_repo_pack_fds_open(&pack_fds);
7838 if (error != NULL)
7839 goto done;
7841 error = got_worktree_open(&worktree, cwd);
7842 if (error) {
7843 if (error->code == GOT_ERR_NOT_WORKTREE)
7844 error = wrap_not_worktree_error(error, "add", cwd);
7845 goto done;
7848 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7849 NULL, pack_fds);
7850 if (error != NULL)
7851 goto done;
7853 error = apply_unveil(got_repo_get_path(repo), 1,
7854 got_worktree_get_root_path(worktree));
7855 if (error)
7856 goto done;
7858 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7859 if (error)
7860 goto done;
7862 if (!can_recurse) {
7863 char *ondisk_path;
7864 struct stat sb;
7865 TAILQ_FOREACH(pe, &paths, entry) {
7866 if (asprintf(&ondisk_path, "%s/%s",
7867 got_worktree_get_root_path(worktree),
7868 pe->path) == -1) {
7869 error = got_error_from_errno("asprintf");
7870 goto done;
7872 if (lstat(ondisk_path, &sb) == -1) {
7873 if (errno == ENOENT) {
7874 free(ondisk_path);
7875 continue;
7877 error = got_error_from_errno2("lstat",
7878 ondisk_path);
7879 free(ondisk_path);
7880 goto done;
7882 free(ondisk_path);
7883 if (S_ISDIR(sb.st_mode)) {
7884 error = got_error_msg(GOT_ERR_BAD_PATH,
7885 "adding directories requires -R option");
7886 goto done;
7891 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7892 NULL, repo, no_ignores);
7893 done:
7894 if (repo) {
7895 const struct got_error *close_err = got_repo_close(repo);
7896 if (error == NULL)
7897 error = close_err;
7899 if (worktree)
7900 got_worktree_close(worktree);
7901 if (pack_fds) {
7902 const struct got_error *pack_err =
7903 got_repo_pack_fds_close(pack_fds);
7904 if (error == NULL)
7905 error = pack_err;
7907 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7908 free(cwd);
7909 return error;
7912 __dead static void
7913 usage_remove(void)
7915 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7916 getprogname());
7917 exit(1);
7920 static const struct got_error *
7921 print_remove_status(void *arg, unsigned char status,
7922 unsigned char staged_status, const char *path)
7924 while (path[0] == '/')
7925 path++;
7926 if (status == GOT_STATUS_NONEXISTENT)
7927 return NULL;
7928 if (status == staged_status && (status == GOT_STATUS_DELETE))
7929 status = GOT_STATUS_NO_CHANGE;
7930 printf("%c%c %s\n", status, staged_status, path);
7931 return NULL;
7934 static const struct got_error *
7935 cmd_remove(int argc, char *argv[])
7937 const struct got_error *error = NULL;
7938 struct got_worktree *worktree = NULL;
7939 struct got_repository *repo = NULL;
7940 const char *status_codes = NULL;
7941 char *cwd = NULL;
7942 struct got_pathlist_head paths;
7943 struct got_pathlist_entry *pe;
7944 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7945 int ignore_missing_paths = 0;
7946 int *pack_fds = NULL;
7948 TAILQ_INIT(&paths);
7950 #ifndef PROFILE
7951 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7952 NULL) == -1)
7953 err(1, "pledge");
7954 #endif
7956 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7957 switch (ch) {
7958 case 'f':
7959 delete_local_mods = 1;
7960 ignore_missing_paths = 1;
7961 break;
7962 case 'k':
7963 keep_on_disk = 1;
7964 break;
7965 case 'R':
7966 can_recurse = 1;
7967 break;
7968 case 's':
7969 for (i = 0; i < strlen(optarg); i++) {
7970 switch (optarg[i]) {
7971 case GOT_STATUS_MODIFY:
7972 delete_local_mods = 1;
7973 break;
7974 case GOT_STATUS_MISSING:
7975 ignore_missing_paths = 1;
7976 break;
7977 default:
7978 errx(1, "invalid status code '%c'",
7979 optarg[i]);
7982 status_codes = optarg;
7983 break;
7984 default:
7985 usage_remove();
7986 /* NOTREACHED */
7990 argc -= optind;
7991 argv += optind;
7993 if (argc < 1)
7994 usage_remove();
7996 cwd = getcwd(NULL, 0);
7997 if (cwd == NULL) {
7998 error = got_error_from_errno("getcwd");
7999 goto done;
8002 error = got_repo_pack_fds_open(&pack_fds);
8003 if (error != NULL)
8004 goto done;
8006 error = got_worktree_open(&worktree, cwd);
8007 if (error) {
8008 if (error->code == GOT_ERR_NOT_WORKTREE)
8009 error = wrap_not_worktree_error(error, "remove", cwd);
8010 goto done;
8013 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8014 NULL, pack_fds);
8015 if (error)
8016 goto done;
8018 error = apply_unveil(got_repo_get_path(repo), 1,
8019 got_worktree_get_root_path(worktree));
8020 if (error)
8021 goto done;
8023 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8024 if (error)
8025 goto done;
8027 if (!can_recurse) {
8028 char *ondisk_path;
8029 struct stat sb;
8030 TAILQ_FOREACH(pe, &paths, entry) {
8031 if (asprintf(&ondisk_path, "%s/%s",
8032 got_worktree_get_root_path(worktree),
8033 pe->path) == -1) {
8034 error = got_error_from_errno("asprintf");
8035 goto done;
8037 if (lstat(ondisk_path, &sb) == -1) {
8038 if (errno == ENOENT) {
8039 free(ondisk_path);
8040 continue;
8042 error = got_error_from_errno2("lstat",
8043 ondisk_path);
8044 free(ondisk_path);
8045 goto done;
8047 free(ondisk_path);
8048 if (S_ISDIR(sb.st_mode)) {
8049 error = got_error_msg(GOT_ERR_BAD_PATH,
8050 "removing directories requires -R option");
8051 goto done;
8056 error = got_worktree_schedule_delete(worktree, &paths,
8057 delete_local_mods, status_codes, print_remove_status, NULL,
8058 repo, keep_on_disk, ignore_missing_paths);
8059 done:
8060 if (repo) {
8061 const struct got_error *close_err = got_repo_close(repo);
8062 if (error == NULL)
8063 error = close_err;
8065 if (worktree)
8066 got_worktree_close(worktree);
8067 if (pack_fds) {
8068 const struct got_error *pack_err =
8069 got_repo_pack_fds_close(pack_fds);
8070 if (error == NULL)
8071 error = pack_err;
8073 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8074 free(cwd);
8075 return error;
8078 __dead static void
8079 usage_patch(void)
8081 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8082 "[patchfile]\n", getprogname());
8083 exit(1);
8086 static const struct got_error *
8087 patch_from_stdin(int *patchfd)
8089 const struct got_error *err = NULL;
8090 ssize_t r;
8091 char buf[BUFSIZ];
8092 sig_t sighup, sigint, sigquit;
8094 *patchfd = got_opentempfd();
8095 if (*patchfd == -1)
8096 return got_error_from_errno("got_opentempfd");
8098 sighup = signal(SIGHUP, SIG_DFL);
8099 sigint = signal(SIGINT, SIG_DFL);
8100 sigquit = signal(SIGQUIT, SIG_DFL);
8102 for (;;) {
8103 r = read(0, buf, sizeof(buf));
8104 if (r == -1) {
8105 err = got_error_from_errno("read");
8106 break;
8108 if (r == 0)
8109 break;
8110 if (write(*patchfd, buf, r) == -1) {
8111 err = got_error_from_errno("write");
8112 break;
8116 signal(SIGHUP, sighup);
8117 signal(SIGINT, sigint);
8118 signal(SIGQUIT, sigquit);
8120 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8121 err = got_error_from_errno("lseek");
8123 if (err != NULL) {
8124 close(*patchfd);
8125 *patchfd = -1;
8128 return err;
8131 static const struct got_error *
8132 patch_progress(void *arg, const char *old, const char *new,
8133 unsigned char status, const struct got_error *error, int old_from,
8134 int old_lines, int new_from, int new_lines, int offset,
8135 int ws_mangled, const struct got_error *hunk_err)
8137 const char *path = new == NULL ? old : new;
8139 while (*path == '/')
8140 path++;
8142 if (status != 0)
8143 printf("%c %s\n", status, path);
8145 if (error != NULL)
8146 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8148 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8149 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8150 old_lines, new_from, new_lines);
8151 if (hunk_err != NULL)
8152 printf("%s\n", hunk_err->msg);
8153 else if (offset != 0)
8154 printf("applied with offset %d\n", offset);
8155 else
8156 printf("hunk contains mangled whitespace\n");
8159 return NULL;
8162 static const struct got_error *
8163 cmd_patch(int argc, char *argv[])
8165 const struct got_error *error = NULL, *close_error = NULL;
8166 struct got_worktree *worktree = NULL;
8167 struct got_repository *repo = NULL;
8168 struct got_reflist_head refs;
8169 struct got_object_id *commit_id = NULL;
8170 const char *commit_id_str = NULL;
8171 struct stat sb;
8172 const char *errstr;
8173 char *cwd = NULL;
8174 int ch, nop = 0, strip = -1, reverse = 0;
8175 int patchfd;
8176 int *pack_fds = NULL;
8178 TAILQ_INIT(&refs);
8180 #ifndef PROFILE
8181 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8182 "unveil", NULL) == -1)
8183 err(1, "pledge");
8184 #endif
8186 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8187 switch (ch) {
8188 case 'c':
8189 commit_id_str = optarg;
8190 break;
8191 case 'n':
8192 nop = 1;
8193 break;
8194 case 'p':
8195 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8196 if (errstr != NULL)
8197 errx(1, "pathname strip count is %s: %s",
8198 errstr, optarg);
8199 break;
8200 case 'R':
8201 reverse = 1;
8202 break;
8203 default:
8204 usage_patch();
8205 /* NOTREACHED */
8209 argc -= optind;
8210 argv += optind;
8212 if (argc == 0) {
8213 error = patch_from_stdin(&patchfd);
8214 if (error)
8215 return error;
8216 } else if (argc == 1) {
8217 patchfd = open(argv[0], O_RDONLY);
8218 if (patchfd == -1) {
8219 error = got_error_from_errno2("open", argv[0]);
8220 return error;
8222 if (fstat(patchfd, &sb) == -1) {
8223 error = got_error_from_errno2("fstat", argv[0]);
8224 goto done;
8226 if (!S_ISREG(sb.st_mode)) {
8227 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8228 goto done;
8230 } else
8231 usage_patch();
8233 if ((cwd = getcwd(NULL, 0)) == NULL) {
8234 error = got_error_from_errno("getcwd");
8235 goto done;
8238 error = got_repo_pack_fds_open(&pack_fds);
8239 if (error != NULL)
8240 goto done;
8242 error = got_worktree_open(&worktree, cwd);
8243 if (error != NULL)
8244 goto done;
8246 const char *repo_path = got_worktree_get_repo_path(worktree);
8247 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8248 if (error != NULL)
8249 goto done;
8251 error = apply_unveil(got_repo_get_path(repo), 0,
8252 got_worktree_get_root_path(worktree));
8253 if (error != NULL)
8254 goto done;
8256 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8257 if (error)
8258 goto done;
8260 if (commit_id_str != NULL) {
8261 error = got_repo_match_object_id(&commit_id, NULL,
8262 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8263 if (error)
8264 goto done;
8267 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8268 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8270 done:
8271 got_ref_list_free(&refs);
8272 free(commit_id);
8273 if (repo) {
8274 close_error = got_repo_close(repo);
8275 if (error == NULL)
8276 error = close_error;
8278 if (worktree != NULL) {
8279 close_error = got_worktree_close(worktree);
8280 if (error == NULL)
8281 error = close_error;
8283 if (pack_fds) {
8284 const struct got_error *pack_err =
8285 got_repo_pack_fds_close(pack_fds);
8286 if (error == NULL)
8287 error = pack_err;
8289 free(cwd);
8290 return error;
8293 __dead static void
8294 usage_revert(void)
8296 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8297 getprogname());
8298 exit(1);
8301 static const struct got_error *
8302 revert_progress(void *arg, unsigned char status, const char *path)
8304 if (status == GOT_STATUS_UNVERSIONED)
8305 return NULL;
8307 while (path[0] == '/')
8308 path++;
8309 printf("%c %s\n", status, path);
8310 return NULL;
8313 struct choose_patch_arg {
8314 FILE *patch_script_file;
8315 const char *action;
8318 static const struct got_error *
8319 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8320 int nchanges, const char *action)
8322 const struct got_error *err;
8323 char *line = NULL;
8324 size_t linesize = 0;
8325 ssize_t linelen;
8327 switch (status) {
8328 case GOT_STATUS_ADD:
8329 printf("A %s\n%s this addition? [y/n] ", path, action);
8330 break;
8331 case GOT_STATUS_DELETE:
8332 printf("D %s\n%s this deletion? [y/n] ", path, action);
8333 break;
8334 case GOT_STATUS_MODIFY:
8335 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8336 return got_error_from_errno("fseek");
8337 printf(GOT_COMMIT_SEP_STR);
8338 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8339 printf("%s", line);
8340 if (linelen == -1 && ferror(patch_file)) {
8341 err = got_error_from_errno("getline");
8342 free(line);
8343 return err;
8345 free(line);
8346 printf(GOT_COMMIT_SEP_STR);
8347 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8348 path, n, nchanges, action);
8349 break;
8350 default:
8351 return got_error_path(path, GOT_ERR_FILE_STATUS);
8354 fflush(stdout);
8355 return NULL;
8358 static const struct got_error *
8359 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8360 FILE *patch_file, int n, int nchanges)
8362 const struct got_error *err = NULL;
8363 char *line = NULL;
8364 size_t linesize = 0;
8365 ssize_t linelen;
8366 int resp = ' ';
8367 struct choose_patch_arg *a = arg;
8369 *choice = GOT_PATCH_CHOICE_NONE;
8371 if (a->patch_script_file) {
8372 char *nl;
8373 err = show_change(status, path, patch_file, n, nchanges,
8374 a->action);
8375 if (err)
8376 return err;
8377 linelen = getline(&line, &linesize, a->patch_script_file);
8378 if (linelen == -1) {
8379 if (ferror(a->patch_script_file))
8380 return got_error_from_errno("getline");
8381 return NULL;
8383 nl = strchr(line, '\n');
8384 if (nl)
8385 *nl = '\0';
8386 if (strcmp(line, "y") == 0) {
8387 *choice = GOT_PATCH_CHOICE_YES;
8388 printf("y\n");
8389 } else if (strcmp(line, "n") == 0) {
8390 *choice = GOT_PATCH_CHOICE_NO;
8391 printf("n\n");
8392 } else if (strcmp(line, "q") == 0 &&
8393 status == GOT_STATUS_MODIFY) {
8394 *choice = GOT_PATCH_CHOICE_QUIT;
8395 printf("q\n");
8396 } else
8397 printf("invalid response '%s'\n", line);
8398 free(line);
8399 return NULL;
8402 while (resp != 'y' && resp != 'n' && resp != 'q') {
8403 err = show_change(status, path, patch_file, n, nchanges,
8404 a->action);
8405 if (err)
8406 return err;
8407 resp = getchar();
8408 if (resp == '\n')
8409 resp = getchar();
8410 if (status == GOT_STATUS_MODIFY) {
8411 if (resp != 'y' && resp != 'n' && resp != 'q') {
8412 printf("invalid response '%c'\n", resp);
8413 resp = ' ';
8415 } else if (resp != 'y' && resp != 'n') {
8416 printf("invalid response '%c'\n", resp);
8417 resp = ' ';
8421 if (resp == 'y')
8422 *choice = GOT_PATCH_CHOICE_YES;
8423 else if (resp == 'n')
8424 *choice = GOT_PATCH_CHOICE_NO;
8425 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8426 *choice = GOT_PATCH_CHOICE_QUIT;
8428 return NULL;
8431 struct wt_commitable_path_arg {
8432 struct got_pathlist_head *commit_paths;
8433 int *has_changes;
8437 * Shortcut work tree status callback to determine if the set of paths scanned
8438 * has at least one versioned path that is being modified and, if not NULL, is
8439 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8440 * soon as a path is passed with a status that satisfies this criteria.
8442 static const struct got_error *
8443 worktree_has_commitable_path(void *arg, unsigned char status,
8444 unsigned char staged_status, const char *path,
8445 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8446 struct got_object_id *commit_id, int dirfd, const char *de_name)
8448 struct wt_commitable_path_arg *a = arg;
8450 if (status == staged_status && (status == GOT_STATUS_DELETE))
8451 status = GOT_STATUS_NO_CHANGE;
8453 if (!(status == GOT_STATUS_NO_CHANGE ||
8454 status == GOT_STATUS_UNVERSIONED) ||
8455 staged_status != GOT_STATUS_NO_CHANGE) {
8456 if (a->commit_paths != NULL) {
8457 struct got_pathlist_entry *pe;
8459 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8460 if (strncmp(path, pe->path,
8461 pe->path_len) == 0) {
8462 *a->has_changes = 1;
8463 break;
8466 } else
8467 *a->has_changes = 1;
8469 if (*a->has_changes)
8470 return got_error(GOT_ERR_FILE_MODIFIED);
8473 return NULL;
8477 * Check that the changeset of the commit identified by id is
8478 * comprised of at least one modified path that is being committed.
8480 static const struct got_error *
8481 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8482 struct got_object_id *id, struct got_worktree *worktree,
8483 struct got_repository *repo)
8485 const struct got_error *err;
8486 struct got_pathlist_head paths;
8487 struct got_commit_object *commit = NULL, *pcommit = NULL;
8488 struct got_tree_object *tree = NULL, *ptree = NULL;
8489 struct got_object_qid *pid;
8491 TAILQ_INIT(&paths);
8493 err = got_object_open_as_commit(&commit, repo, id);
8494 if (err)
8495 goto done;
8497 err = got_object_open_as_tree(&tree, repo,
8498 got_object_commit_get_tree_id(commit));
8499 if (err)
8500 goto done;
8502 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8503 if (pid != NULL) {
8504 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8505 if (err)
8506 goto done;
8508 err = got_object_open_as_tree(&ptree, repo,
8509 got_object_commit_get_tree_id(pcommit));
8510 if (err)
8511 goto done;
8514 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8515 got_diff_tree_collect_changed_paths, &paths, 0);
8516 if (err)
8517 goto done;
8519 err = got_worktree_status(worktree, &paths, repo, 0,
8520 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8521 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8523 * At least one changed path in the referenced commit is
8524 * modified in the work tree, that's all we need to know!
8526 err = NULL;
8529 done:
8530 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8531 if (commit)
8532 got_object_commit_close(commit);
8533 if (pcommit)
8534 got_object_commit_close(pcommit);
8535 if (tree)
8536 got_object_tree_close(tree);
8537 if (ptree)
8538 got_object_tree_close(ptree);
8539 return err;
8543 * Remove any "logmsg" reference comprised entirely of paths that have
8544 * been reverted in this work tree. If any path in the logmsg ref changeset
8545 * remains in a changed state in the worktree, do not remove the reference.
8547 static const struct got_error *
8548 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8550 const struct got_error *err;
8551 struct got_reflist_head refs;
8552 struct got_reflist_entry *re;
8553 struct got_commit_object *commit = NULL;
8554 struct got_object_id *commit_id = NULL;
8555 struct wt_commitable_path_arg wcpa;
8556 char *uuidstr = NULL;
8558 TAILQ_INIT(&refs);
8560 err = got_worktree_get_uuid(&uuidstr, worktree);
8561 if (err)
8562 goto done;
8564 err = got_ref_list(&refs, repo, "refs/got/worktree",
8565 got_ref_cmp_by_name, repo);
8566 if (err)
8567 goto done;
8569 TAILQ_FOREACH(re, &refs, entry) {
8570 const char *refname;
8571 int has_changes = 0;
8573 refname = got_ref_get_name(re->ref);
8575 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8576 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8577 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8578 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8579 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8580 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8581 else
8582 continue;
8584 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8585 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8586 else
8587 continue;
8589 err = got_repo_match_object_id(&commit_id, NULL, refname,
8590 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8591 if (err)
8592 goto done;
8594 err = got_object_open_as_commit(&commit, repo, commit_id);
8595 if (err)
8596 goto done;
8598 wcpa.commit_paths = NULL;
8599 wcpa.has_changes = &has_changes;
8601 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8602 worktree, repo);
8603 if (err)
8604 goto done;
8606 if (!has_changes) {
8607 err = got_ref_delete(re->ref, repo);
8608 if (err)
8609 goto done;
8612 got_object_commit_close(commit);
8613 commit = NULL;
8614 free(commit_id);
8615 commit_id = NULL;
8618 done:
8619 free(uuidstr);
8620 free(commit_id);
8621 got_ref_list_free(&refs);
8622 if (commit)
8623 got_object_commit_close(commit);
8624 return err;
8627 static const struct got_error *
8628 cmd_revert(int argc, char *argv[])
8630 const struct got_error *error = NULL;
8631 struct got_worktree *worktree = NULL;
8632 struct got_repository *repo = NULL;
8633 char *cwd = NULL, *path = NULL;
8634 struct got_pathlist_head paths;
8635 struct got_pathlist_entry *pe;
8636 int ch, can_recurse = 0, pflag = 0;
8637 FILE *patch_script_file = NULL;
8638 const char *patch_script_path = NULL;
8639 struct choose_patch_arg cpa;
8640 int *pack_fds = NULL;
8642 TAILQ_INIT(&paths);
8644 #ifndef PROFILE
8645 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8646 "unveil", NULL) == -1)
8647 err(1, "pledge");
8648 #endif
8650 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8651 switch (ch) {
8652 case 'F':
8653 patch_script_path = optarg;
8654 break;
8655 case 'p':
8656 pflag = 1;
8657 break;
8658 case 'R':
8659 can_recurse = 1;
8660 break;
8661 default:
8662 usage_revert();
8663 /* NOTREACHED */
8667 argc -= optind;
8668 argv += optind;
8670 if (argc < 1)
8671 usage_revert();
8672 if (patch_script_path && !pflag)
8673 errx(1, "-F option can only be used together with -p option");
8675 cwd = getcwd(NULL, 0);
8676 if (cwd == NULL) {
8677 error = got_error_from_errno("getcwd");
8678 goto done;
8681 error = got_repo_pack_fds_open(&pack_fds);
8682 if (error != NULL)
8683 goto done;
8685 error = got_worktree_open(&worktree, cwd);
8686 if (error) {
8687 if (error->code == GOT_ERR_NOT_WORKTREE)
8688 error = wrap_not_worktree_error(error, "revert", cwd);
8689 goto done;
8692 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8693 NULL, pack_fds);
8694 if (error != NULL)
8695 goto done;
8697 if (patch_script_path) {
8698 patch_script_file = fopen(patch_script_path, "re");
8699 if (patch_script_file == NULL) {
8700 error = got_error_from_errno2("fopen",
8701 patch_script_path);
8702 goto done;
8707 * XXX "c" perm needed on repo dir to delete merge references.
8709 error = apply_unveil(got_repo_get_path(repo), 0,
8710 got_worktree_get_root_path(worktree));
8711 if (error)
8712 goto done;
8714 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8715 if (error)
8716 goto done;
8718 if (!can_recurse) {
8719 char *ondisk_path;
8720 struct stat sb;
8721 TAILQ_FOREACH(pe, &paths, entry) {
8722 if (asprintf(&ondisk_path, "%s/%s",
8723 got_worktree_get_root_path(worktree),
8724 pe->path) == -1) {
8725 error = got_error_from_errno("asprintf");
8726 goto done;
8728 if (lstat(ondisk_path, &sb) == -1) {
8729 if (errno == ENOENT) {
8730 free(ondisk_path);
8731 continue;
8733 error = got_error_from_errno2("lstat",
8734 ondisk_path);
8735 free(ondisk_path);
8736 goto done;
8738 free(ondisk_path);
8739 if (S_ISDIR(sb.st_mode)) {
8740 error = got_error_msg(GOT_ERR_BAD_PATH,
8741 "reverting directories requires -R option");
8742 goto done;
8747 cpa.patch_script_file = patch_script_file;
8748 cpa.action = "revert";
8749 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8750 pflag ? choose_patch : NULL, &cpa, repo);
8752 error = rm_logmsg_ref(worktree, repo);
8753 done:
8754 if (patch_script_file && fclose(patch_script_file) == EOF &&
8755 error == NULL)
8756 error = got_error_from_errno2("fclose", patch_script_path);
8757 if (repo) {
8758 const struct got_error *close_err = got_repo_close(repo);
8759 if (error == NULL)
8760 error = close_err;
8762 if (worktree)
8763 got_worktree_close(worktree);
8764 if (pack_fds) {
8765 const struct got_error *pack_err =
8766 got_repo_pack_fds_close(pack_fds);
8767 if (error == NULL)
8768 error = pack_err;
8770 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8771 free(path);
8772 free(cwd);
8773 return error;
8776 __dead static void
8777 usage_commit(void)
8779 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8780 "[-m message] [path ...]\n", getprogname());
8781 exit(1);
8784 struct collect_commit_logmsg_arg {
8785 const char *cmdline_log;
8786 const char *prepared_log;
8787 const char *merged_log;
8788 int non_interactive;
8789 const char *editor;
8790 const char *worktree_path;
8791 const char *branch_name;
8792 const char *repo_path;
8793 char *logmsg_path;
8797 static const struct got_error *
8798 read_prepared_logmsg(char **logmsg, const char *path)
8800 const struct got_error *err = NULL;
8801 FILE *f = NULL;
8802 struct stat sb;
8803 size_t r;
8805 *logmsg = NULL;
8806 memset(&sb, 0, sizeof(sb));
8808 f = fopen(path, "re");
8809 if (f == NULL)
8810 return got_error_from_errno2("fopen", path);
8812 if (fstat(fileno(f), &sb) == -1) {
8813 err = got_error_from_errno2("fstat", path);
8814 goto done;
8816 if (sb.st_size == 0) {
8817 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8818 goto done;
8821 *logmsg = malloc(sb.st_size + 1);
8822 if (*logmsg == NULL) {
8823 err = got_error_from_errno("malloc");
8824 goto done;
8827 r = fread(*logmsg, 1, sb.st_size, f);
8828 if (r != sb.st_size) {
8829 if (ferror(f))
8830 err = got_error_from_errno2("fread", path);
8831 else
8832 err = got_error(GOT_ERR_IO);
8833 goto done;
8835 (*logmsg)[sb.st_size] = '\0';
8836 done:
8837 if (fclose(f) == EOF && err == NULL)
8838 err = got_error_from_errno2("fclose", path);
8839 if (err) {
8840 free(*logmsg);
8841 *logmsg = NULL;
8843 return err;
8846 static const struct got_error *
8847 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8848 const char *diff_path, char **logmsg, void *arg)
8850 char *initial_content = NULL;
8851 struct got_pathlist_entry *pe;
8852 const struct got_error *err = NULL;
8853 char *template = NULL;
8854 char *prepared_msg = NULL, *merged_msg = NULL;
8855 struct collect_commit_logmsg_arg *a = arg;
8856 int initial_content_len;
8857 int fd = -1;
8858 size_t len;
8860 /* if a message was specified on the command line, just use it */
8861 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8862 len = strlen(a->cmdline_log) + 1;
8863 *logmsg = malloc(len + 1);
8864 if (*logmsg == NULL)
8865 return got_error_from_errno("malloc");
8866 strlcpy(*logmsg, a->cmdline_log, len);
8867 return NULL;
8868 } else if (a->prepared_log != NULL && a->non_interactive)
8869 return read_prepared_logmsg(logmsg, a->prepared_log);
8871 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8872 return got_error_from_errno("asprintf");
8874 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8875 if (err)
8876 goto done;
8878 if (a->prepared_log) {
8879 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8880 if (err)
8881 goto done;
8882 } else if (a->merged_log) {
8883 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8884 if (err)
8885 goto done;
8888 initial_content_len = asprintf(&initial_content,
8889 "%s%s\n# changes to be committed on branch %s:\n",
8890 prepared_msg ? prepared_msg : "",
8891 merged_msg ? merged_msg : "", a->branch_name);
8892 if (initial_content_len == -1) {
8893 err = got_error_from_errno("asprintf");
8894 goto done;
8897 if (write(fd, initial_content, initial_content_len) == -1) {
8898 err = got_error_from_errno2("write", a->logmsg_path);
8899 goto done;
8902 TAILQ_FOREACH(pe, commitable_paths, entry) {
8903 struct got_commitable *ct = pe->data;
8904 dprintf(fd, "# %c %s\n",
8905 got_commitable_get_status(ct),
8906 got_commitable_get_path(ct));
8909 if (diff_path) {
8910 dprintf(fd, "# detailed changes can be viewed in %s\n",
8911 diff_path);
8914 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8915 initial_content_len, a->prepared_log ? 0 : 1);
8916 done:
8917 free(initial_content);
8918 free(template);
8919 free(prepared_msg);
8920 free(merged_msg);
8922 if (fd != -1 && close(fd) == -1 && err == NULL)
8923 err = got_error_from_errno2("close", a->logmsg_path);
8925 /* Editor is done; we can now apply unveil(2) */
8926 if (err == NULL)
8927 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8928 if (err) {
8929 free(*logmsg);
8930 *logmsg = NULL;
8932 return err;
8935 static const struct got_error *
8936 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8937 const char *type, int has_content)
8939 const struct got_error *err = NULL;
8940 char *logmsg = NULL;
8942 err = got_object_commit_get_logmsg(&logmsg, commit);
8943 if (err)
8944 return err;
8946 if (fprintf(f, "%s# log message of %s commit %s:%s",
8947 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8948 err = got_ferror(f, GOT_ERR_IO);
8950 free(logmsg);
8951 return err;
8955 * Lookup "logmsg" references of backed-out and cherrypicked commits
8956 * belonging to the current work tree. If found, and the worktree has
8957 * at least one modified file that was changed in the referenced commit,
8958 * add its log message to a new temporary file at *logmsg_path.
8959 * Add all refs found to matched_refs to be scheduled for removal on
8960 * successful commit.
8962 static const struct got_error *
8963 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8964 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8965 struct got_repository *repo)
8967 const struct got_error *err;
8968 struct got_commit_object *commit = NULL;
8969 struct got_object_id *id = NULL;
8970 struct got_reflist_head refs;
8971 struct got_reflist_entry *re, *re_match;
8972 FILE *f = NULL;
8973 char *uuidstr = NULL;
8974 int added_logmsg = 0;
8976 TAILQ_INIT(&refs);
8978 *logmsg_path = NULL;
8980 err = got_worktree_get_uuid(&uuidstr, worktree);
8981 if (err)
8982 goto done;
8984 err = got_ref_list(&refs, repo, "refs/got/worktree",
8985 got_ref_cmp_by_name, repo);
8986 if (err)
8987 goto done;
8989 TAILQ_FOREACH(re, &refs, entry) {
8990 const char *refname, *type;
8991 struct wt_commitable_path_arg wcpa;
8992 int add_logmsg = 0;
8994 refname = got_ref_get_name(re->ref);
8996 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8997 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8998 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8999 type = "cherrypicked";
9000 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9001 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9002 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9003 type = "backed-out";
9004 } else
9005 continue;
9007 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9008 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9009 else
9010 continue;
9012 err = got_repo_match_object_id(&id, NULL, refname,
9013 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9014 if (err)
9015 goto done;
9017 err = got_object_open_as_commit(&commit, repo, id);
9018 if (err)
9019 goto done;
9021 wcpa.commit_paths = paths;
9022 wcpa.has_changes = &add_logmsg;
9024 err = commit_path_changed_in_worktree(&wcpa, id,
9025 worktree, repo);
9026 if (err)
9027 goto done;
9029 if (add_logmsg) {
9030 if (f == NULL) {
9031 err = got_opentemp_named(logmsg_path, &f,
9032 "got-commit-logmsg", "");
9033 if (err)
9034 goto done;
9036 err = cat_logmsg(f, commit, refname, type,
9037 added_logmsg);
9038 if (err)
9039 goto done;
9040 if (!added_logmsg)
9041 ++added_logmsg;
9043 err = got_reflist_entry_dup(&re_match, re);
9044 if (err)
9045 goto done;
9046 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9049 got_object_commit_close(commit);
9050 commit = NULL;
9051 free(id);
9052 id = NULL;
9055 done:
9056 free(id);
9057 free(uuidstr);
9058 got_ref_list_free(&refs);
9059 if (commit)
9060 got_object_commit_close(commit);
9061 if (f && fclose(f) == EOF && err == NULL)
9062 err = got_error_from_errno("fclose");
9063 if (!added_logmsg) {
9064 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9065 err = got_error_from_errno2("unlink", *logmsg_path);
9066 *logmsg_path = NULL;
9068 return err;
9071 static const struct got_error *
9072 cmd_commit(int argc, char *argv[])
9074 const struct got_error *error = NULL;
9075 struct got_worktree *worktree = NULL;
9076 struct got_repository *repo = NULL;
9077 char *cwd = NULL, *id_str = NULL;
9078 struct got_object_id *id = NULL;
9079 const char *logmsg = NULL;
9080 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9081 struct collect_commit_logmsg_arg cl_arg;
9082 const char *author = NULL;
9083 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9084 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9085 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9086 int show_diff = 1, commit_conflicts = 0;
9087 struct got_pathlist_head paths;
9088 struct got_reflist_head refs;
9089 struct got_reflist_entry *re;
9090 int *pack_fds = NULL;
9092 TAILQ_INIT(&refs);
9093 TAILQ_INIT(&paths);
9094 cl_arg.logmsg_path = NULL;
9096 #ifndef PROFILE
9097 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9098 "unveil", NULL) == -1)
9099 err(1, "pledge");
9100 #endif
9102 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9103 switch (ch) {
9104 case 'A':
9105 author = optarg;
9106 error = valid_author(author);
9107 if (error)
9108 return error;
9109 break;
9110 case 'C':
9111 commit_conflicts = 1;
9112 break;
9113 case 'F':
9114 if (logmsg != NULL)
9115 option_conflict('F', 'm');
9116 prepared_logmsg = realpath(optarg, NULL);
9117 if (prepared_logmsg == NULL)
9118 return got_error_from_errno2("realpath",
9119 optarg);
9120 break;
9121 case 'm':
9122 if (prepared_logmsg)
9123 option_conflict('m', 'F');
9124 logmsg = optarg;
9125 break;
9126 case 'N':
9127 non_interactive = 1;
9128 break;
9129 case 'n':
9130 show_diff = 0;
9131 break;
9132 case 'S':
9133 allow_bad_symlinks = 1;
9134 break;
9135 default:
9136 usage_commit();
9137 /* NOTREACHED */
9141 argc -= optind;
9142 argv += optind;
9144 cwd = getcwd(NULL, 0);
9145 if (cwd == NULL) {
9146 error = got_error_from_errno("getcwd");
9147 goto done;
9150 error = got_repo_pack_fds_open(&pack_fds);
9151 if (error != NULL)
9152 goto done;
9154 error = got_worktree_open(&worktree, cwd);
9155 if (error) {
9156 if (error->code == GOT_ERR_NOT_WORKTREE)
9157 error = wrap_not_worktree_error(error, "commit", cwd);
9158 goto done;
9161 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9162 if (error)
9163 goto done;
9164 if (rebase_in_progress) {
9165 error = got_error(GOT_ERR_REBASING);
9166 goto done;
9169 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9170 worktree);
9171 if (error)
9172 goto done;
9174 error = get_gitconfig_path(&gitconfig_path);
9175 if (error)
9176 goto done;
9177 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9178 gitconfig_path, pack_fds);
9179 if (error != NULL)
9180 goto done;
9182 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9183 if (error)
9184 goto done;
9185 if (merge_in_progress) {
9186 error = got_error(GOT_ERR_MERGE_BUSY);
9187 goto done;
9190 error = get_author(&committer, repo, worktree);
9191 if (error)
9192 goto done;
9194 if (author == NULL)
9195 author = committer;
9198 * unveil(2) traverses exec(2); if an editor is used we have
9199 * to apply unveil after the log message has been written.
9201 if (logmsg == NULL || strlen(logmsg) == 0)
9202 error = get_editor(&editor);
9203 else
9204 error = apply_unveil(got_repo_get_path(repo), 0,
9205 got_worktree_get_root_path(worktree));
9206 if (error)
9207 goto done;
9209 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9210 if (error)
9211 goto done;
9213 if (prepared_logmsg == NULL) {
9214 error = lookup_logmsg_ref(&merged_logmsg,
9215 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9216 if (error)
9217 goto done;
9220 cl_arg.editor = editor;
9221 cl_arg.cmdline_log = logmsg;
9222 cl_arg.prepared_log = prepared_logmsg;
9223 cl_arg.merged_log = merged_logmsg;
9224 cl_arg.non_interactive = non_interactive;
9225 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9226 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9227 if (!histedit_in_progress) {
9228 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9229 error = got_error(GOT_ERR_COMMIT_BRANCH);
9230 goto done;
9232 cl_arg.branch_name += 11;
9234 cl_arg.repo_path = got_repo_get_path(repo);
9235 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9236 allow_bad_symlinks, show_diff, commit_conflicts,
9237 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9238 if (error) {
9239 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9240 cl_arg.logmsg_path != NULL)
9241 preserve_logmsg = 1;
9242 goto done;
9245 error = got_object_id_str(&id_str, id);
9246 if (error)
9247 goto done;
9248 printf("Created commit %s\n", id_str);
9250 TAILQ_FOREACH(re, &refs, entry) {
9251 error = got_ref_delete(re->ref, repo);
9252 if (error)
9253 goto done;
9256 done:
9257 if (preserve_logmsg) {
9258 fprintf(stderr, "%s: log message preserved in %s\n",
9259 getprogname(), cl_arg.logmsg_path);
9260 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9261 error == NULL)
9262 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9263 free(cl_arg.logmsg_path);
9264 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9265 error = got_error_from_errno2("unlink", merged_logmsg);
9266 free(merged_logmsg);
9267 if (repo) {
9268 const struct got_error *close_err = got_repo_close(repo);
9269 if (error == NULL)
9270 error = close_err;
9272 if (worktree)
9273 got_worktree_close(worktree);
9274 if (pack_fds) {
9275 const struct got_error *pack_err =
9276 got_repo_pack_fds_close(pack_fds);
9277 if (error == NULL)
9278 error = pack_err;
9280 got_ref_list_free(&refs);
9281 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9282 free(cwd);
9283 free(id_str);
9284 free(gitconfig_path);
9285 free(editor);
9286 free(committer);
9287 free(prepared_logmsg);
9288 return error;
9291 __dead static void
9292 usage_send(void)
9294 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9295 "[-r repository-path] [-t tag] [remote-repository]\n",
9296 getprogname());
9297 exit(1);
9300 static void
9301 print_load_info(int print_colored, int print_found, int print_trees,
9302 int ncolored, int nfound, int ntrees)
9304 if (print_colored) {
9305 printf("%d commit%s colored", ncolored,
9306 ncolored == 1 ? "" : "s");
9308 if (print_found) {
9309 printf("%s%d object%s found",
9310 ncolored > 0 ? "; " : "",
9311 nfound, nfound == 1 ? "" : "s");
9313 if (print_trees) {
9314 printf("; %d tree%s scanned", ntrees,
9315 ntrees == 1 ? "" : "s");
9319 struct got_send_progress_arg {
9320 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9321 int verbosity;
9322 int last_ncolored;
9323 int last_nfound;
9324 int last_ntrees;
9325 int loading_done;
9326 int last_ncommits;
9327 int last_nobj_total;
9328 int last_p_deltify;
9329 int last_p_written;
9330 int last_p_sent;
9331 int printed_something;
9332 int sent_something;
9333 struct got_pathlist_head *delete_branches;
9336 static const struct got_error *
9337 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9338 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9339 int nobj_written, off_t bytes_sent, const char *refname,
9340 const char *errmsg, int success)
9342 struct got_send_progress_arg *a = arg;
9343 char scaled_packsize[FMT_SCALED_STRSIZE];
9344 char scaled_sent[FMT_SCALED_STRSIZE];
9345 int p_deltify = 0, p_written = 0, p_sent = 0;
9346 int print_colored = 0, print_found = 0, print_trees = 0;
9347 int print_searching = 0, print_total = 0;
9348 int print_deltify = 0, print_written = 0, print_sent = 0;
9350 if (a->verbosity < 0)
9351 return NULL;
9353 if (refname) {
9354 const char *status = success ? "accepted" : "rejected";
9356 if (success) {
9357 struct got_pathlist_entry *pe;
9358 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9359 const char *branchname = pe->path;
9360 if (got_path_cmp(branchname, refname,
9361 strlen(branchname), strlen(refname)) == 0) {
9362 status = "deleted";
9363 a->sent_something = 1;
9364 break;
9369 if (a->printed_something)
9370 putchar('\n');
9371 printf("Server has %s %s", status, refname);
9372 if (errmsg)
9373 printf(": %s", errmsg);
9374 a->printed_something = 1;
9375 return NULL;
9378 if (a->last_ncolored != ncolored) {
9379 print_colored = 1;
9380 a->last_ncolored = ncolored;
9383 if (a->last_nfound != nfound) {
9384 print_colored = 1;
9385 print_found = 1;
9386 a->last_nfound = nfound;
9389 if (a->last_ntrees != ntrees) {
9390 print_colored = 1;
9391 print_found = 1;
9392 print_trees = 1;
9393 a->last_ntrees = ntrees;
9396 if ((print_colored || print_found || print_trees) &&
9397 !a->loading_done) {
9398 printf("\r");
9399 print_load_info(print_colored, print_found, print_trees,
9400 ncolored, nfound, ntrees);
9401 a->printed_something = 1;
9402 fflush(stdout);
9403 return NULL;
9404 } else if (!a->loading_done) {
9405 printf("\r");
9406 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9407 printf("\n");
9408 a->loading_done = 1;
9411 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9412 return got_error_from_errno("fmt_scaled");
9413 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9414 return got_error_from_errno("fmt_scaled");
9416 if (a->last_ncommits != ncommits) {
9417 print_searching = 1;
9418 a->last_ncommits = ncommits;
9421 if (a->last_nobj_total != nobj_total) {
9422 print_searching = 1;
9423 print_total = 1;
9424 a->last_nobj_total = nobj_total;
9427 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9428 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9429 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9430 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9431 return got_error(GOT_ERR_NO_SPACE);
9434 if (nobj_deltify > 0 || nobj_written > 0) {
9435 if (nobj_deltify > 0) {
9436 p_deltify = (nobj_deltify * 100) / nobj_total;
9437 if (p_deltify != a->last_p_deltify) {
9438 a->last_p_deltify = p_deltify;
9439 print_searching = 1;
9440 print_total = 1;
9441 print_deltify = 1;
9444 if (nobj_written > 0) {
9445 p_written = (nobj_written * 100) / nobj_total;
9446 if (p_written != a->last_p_written) {
9447 a->last_p_written = p_written;
9448 print_searching = 1;
9449 print_total = 1;
9450 print_deltify = 1;
9451 print_written = 1;
9456 if (bytes_sent > 0) {
9457 p_sent = (bytes_sent * 100) / packfile_size;
9458 if (p_sent != a->last_p_sent) {
9459 a->last_p_sent = p_sent;
9460 print_searching = 1;
9461 print_total = 1;
9462 print_deltify = 1;
9463 print_written = 1;
9464 print_sent = 1;
9466 a->sent_something = 1;
9469 if (print_searching || print_total || print_deltify || print_written ||
9470 print_sent)
9471 printf("\r");
9472 if (print_searching)
9473 printf("packing %d reference%s", ncommits,
9474 ncommits == 1 ? "" : "s");
9475 if (print_total)
9476 printf("; %d object%s", nobj_total,
9477 nobj_total == 1 ? "" : "s");
9478 if (print_deltify)
9479 printf("; deltify: %d%%", p_deltify);
9480 if (print_sent)
9481 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9482 scaled_packsize, p_sent);
9483 else if (print_written)
9484 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9485 scaled_packsize, p_written);
9486 if (print_searching || print_total || print_deltify ||
9487 print_written || print_sent) {
9488 a->printed_something = 1;
9489 fflush(stdout);
9491 return NULL;
9494 static const struct got_error *
9495 cmd_send(int argc, char *argv[])
9497 const struct got_error *error = NULL;
9498 char *cwd = NULL, *repo_path = NULL;
9499 const char *remote_name;
9500 char *proto = NULL, *host = NULL, *port = NULL;
9501 char *repo_name = NULL, *server_path = NULL;
9502 const struct got_remote_repo *remotes, *remote = NULL;
9503 int nremotes, nbranches = 0, ndelete_branches = 0;
9504 struct got_repository *repo = NULL;
9505 struct got_worktree *worktree = NULL;
9506 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9507 struct got_pathlist_head branches;
9508 struct got_pathlist_head tags;
9509 struct got_reflist_head all_branches;
9510 struct got_reflist_head all_tags;
9511 struct got_pathlist_head delete_args;
9512 struct got_pathlist_head delete_branches;
9513 struct got_reflist_entry *re;
9514 struct got_pathlist_entry *pe;
9515 int i, ch, sendfd = -1, sendstatus;
9516 pid_t sendpid = -1;
9517 struct got_send_progress_arg spa;
9518 int verbosity = 0, overwrite_refs = 0;
9519 int send_all_branches = 0, send_all_tags = 0;
9520 struct got_reference *ref = NULL;
9521 int *pack_fds = NULL;
9523 TAILQ_INIT(&branches);
9524 TAILQ_INIT(&tags);
9525 TAILQ_INIT(&all_branches);
9526 TAILQ_INIT(&all_tags);
9527 TAILQ_INIT(&delete_args);
9528 TAILQ_INIT(&delete_branches);
9530 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9531 switch (ch) {
9532 case 'a':
9533 send_all_branches = 1;
9534 break;
9535 case 'b':
9536 error = got_pathlist_append(&branches, optarg, NULL);
9537 if (error)
9538 return error;
9539 nbranches++;
9540 break;
9541 case 'd':
9542 error = got_pathlist_append(&delete_args, optarg, NULL);
9543 if (error)
9544 return error;
9545 break;
9546 case 'f':
9547 overwrite_refs = 1;
9548 break;
9549 case 'q':
9550 verbosity = -1;
9551 break;
9552 case 'r':
9553 repo_path = realpath(optarg, NULL);
9554 if (repo_path == NULL)
9555 return got_error_from_errno2("realpath",
9556 optarg);
9557 got_path_strip_trailing_slashes(repo_path);
9558 break;
9559 case 'T':
9560 send_all_tags = 1;
9561 break;
9562 case 't':
9563 error = got_pathlist_append(&tags, optarg, NULL);
9564 if (error)
9565 return error;
9566 break;
9567 case 'v':
9568 if (verbosity < 0)
9569 verbosity = 0;
9570 else if (verbosity < 3)
9571 verbosity++;
9572 break;
9573 default:
9574 usage_send();
9575 /* NOTREACHED */
9578 argc -= optind;
9579 argv += optind;
9581 if (send_all_branches && !TAILQ_EMPTY(&branches))
9582 option_conflict('a', 'b');
9583 if (send_all_tags && !TAILQ_EMPTY(&tags))
9584 option_conflict('T', 't');
9587 if (argc == 0)
9588 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9589 else if (argc == 1)
9590 remote_name = argv[0];
9591 else
9592 usage_send();
9594 cwd = getcwd(NULL, 0);
9595 if (cwd == NULL) {
9596 error = got_error_from_errno("getcwd");
9597 goto done;
9600 error = got_repo_pack_fds_open(&pack_fds);
9601 if (error != NULL)
9602 goto done;
9604 if (repo_path == NULL) {
9605 error = got_worktree_open(&worktree, cwd);
9606 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9607 goto done;
9608 else
9609 error = NULL;
9610 if (worktree) {
9611 repo_path =
9612 strdup(got_worktree_get_repo_path(worktree));
9613 if (repo_path == NULL)
9614 error = got_error_from_errno("strdup");
9615 if (error)
9616 goto done;
9617 } else {
9618 repo_path = strdup(cwd);
9619 if (repo_path == NULL) {
9620 error = got_error_from_errno("strdup");
9621 goto done;
9626 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9627 if (error)
9628 goto done;
9630 if (worktree) {
9631 worktree_conf = got_worktree_get_gotconfig(worktree);
9632 if (worktree_conf) {
9633 got_gotconfig_get_remotes(&nremotes, &remotes,
9634 worktree_conf);
9635 for (i = 0; i < nremotes; i++) {
9636 if (strcmp(remotes[i].name, remote_name) == 0) {
9637 remote = &remotes[i];
9638 break;
9643 if (remote == NULL) {
9644 repo_conf = got_repo_get_gotconfig(repo);
9645 if (repo_conf) {
9646 got_gotconfig_get_remotes(&nremotes, &remotes,
9647 repo_conf);
9648 for (i = 0; i < nremotes; i++) {
9649 if (strcmp(remotes[i].name, remote_name) == 0) {
9650 remote = &remotes[i];
9651 break;
9656 if (remote == NULL) {
9657 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9658 for (i = 0; i < nremotes; i++) {
9659 if (strcmp(remotes[i].name, remote_name) == 0) {
9660 remote = &remotes[i];
9661 break;
9665 if (remote == NULL) {
9666 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9667 goto done;
9670 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9671 &repo_name, remote->send_url);
9672 if (error)
9673 goto done;
9675 if (strcmp(proto, "git") == 0) {
9676 #ifndef PROFILE
9677 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9678 "sendfd dns inet unveil", NULL) == -1)
9679 err(1, "pledge");
9680 #endif
9681 } else if (strcmp(proto, "git+ssh") == 0 ||
9682 strcmp(proto, "ssh") == 0) {
9683 #ifndef PROFILE
9684 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9685 "sendfd unveil", NULL) == -1)
9686 err(1, "pledge");
9687 #endif
9688 } else if (strcmp(proto, "http") == 0 ||
9689 strcmp(proto, "git+http") == 0) {
9690 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9691 goto done;
9692 } else {
9693 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9694 goto done;
9697 error = got_dial_apply_unveil(proto);
9698 if (error)
9699 goto done;
9701 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9702 if (error)
9703 goto done;
9705 if (send_all_branches) {
9706 error = got_ref_list(&all_branches, repo, "refs/heads",
9707 got_ref_cmp_by_name, NULL);
9708 if (error)
9709 goto done;
9710 TAILQ_FOREACH(re, &all_branches, entry) {
9711 const char *branchname = got_ref_get_name(re->ref);
9712 error = got_pathlist_append(&branches,
9713 branchname, NULL);
9714 if (error)
9715 goto done;
9716 nbranches++;
9718 } else if (nbranches == 0) {
9719 for (i = 0; i < remote->nsend_branches; i++) {
9720 error = got_pathlist_append(&branches,
9721 remote->send_branches[i], NULL);
9722 if (error)
9723 goto done;
9727 if (send_all_tags) {
9728 error = got_ref_list(&all_tags, repo, "refs/tags",
9729 got_ref_cmp_by_name, NULL);
9730 if (error)
9731 goto done;
9732 TAILQ_FOREACH(re, &all_tags, entry) {
9733 const char *tagname = got_ref_get_name(re->ref);
9734 error = got_pathlist_append(&tags,
9735 tagname, NULL);
9736 if (error)
9737 goto done;
9742 * To prevent accidents only branches in refs/heads/ can be deleted
9743 * with 'got send -d'.
9744 * Deleting anything else requires local repository access or Git.
9746 TAILQ_FOREACH(pe, &delete_args, entry) {
9747 const char *branchname = pe->path;
9748 char *s;
9749 struct got_pathlist_entry *new;
9750 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9751 s = strdup(branchname);
9752 if (s == NULL) {
9753 error = got_error_from_errno("strdup");
9754 goto done;
9756 } else {
9757 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9758 error = got_error_from_errno("asprintf");
9759 goto done;
9762 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9763 if (error || new == NULL /* duplicate */)
9764 free(s);
9765 if (error)
9766 goto done;
9767 ndelete_branches++;
9770 if (nbranches == 0 && ndelete_branches == 0) {
9771 struct got_reference *head_ref;
9772 if (worktree)
9773 error = got_ref_open(&head_ref, repo,
9774 got_worktree_get_head_ref_name(worktree), 0);
9775 else
9776 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9777 if (error)
9778 goto done;
9779 if (got_ref_is_symbolic(head_ref)) {
9780 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9781 got_ref_close(head_ref);
9782 if (error)
9783 goto done;
9784 } else
9785 ref = head_ref;
9786 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9787 NULL);
9788 if (error)
9789 goto done;
9790 nbranches++;
9793 if (verbosity >= 0) {
9794 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9795 remote->name, proto, host,
9796 port ? ":" : "", port ? port : "",
9797 *server_path == '/' ? "" : "/", server_path);
9800 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9801 server_path, verbosity);
9802 if (error)
9803 goto done;
9805 memset(&spa, 0, sizeof(spa));
9806 spa.last_scaled_packsize[0] = '\0';
9807 spa.last_p_deltify = -1;
9808 spa.last_p_written = -1;
9809 spa.verbosity = verbosity;
9810 spa.delete_branches = &delete_branches;
9811 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9812 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9813 check_cancelled, NULL);
9814 if (spa.printed_something)
9815 putchar('\n');
9816 if (error)
9817 goto done;
9818 if (!spa.sent_something && verbosity >= 0)
9819 printf("Already up-to-date\n");
9820 done:
9821 if (sendpid > 0) {
9822 if (kill(sendpid, SIGTERM) == -1)
9823 error = got_error_from_errno("kill");
9824 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9825 error = got_error_from_errno("waitpid");
9827 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9828 error = got_error_from_errno("close");
9829 if (repo) {
9830 const struct got_error *close_err = got_repo_close(repo);
9831 if (error == NULL)
9832 error = close_err;
9834 if (worktree)
9835 got_worktree_close(worktree);
9836 if (pack_fds) {
9837 const struct got_error *pack_err =
9838 got_repo_pack_fds_close(pack_fds);
9839 if (error == NULL)
9840 error = pack_err;
9842 if (ref)
9843 got_ref_close(ref);
9844 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9845 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9846 got_ref_list_free(&all_branches);
9847 got_ref_list_free(&all_tags);
9848 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9849 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9850 free(cwd);
9851 free(repo_path);
9852 free(proto);
9853 free(host);
9854 free(port);
9855 free(server_path);
9856 free(repo_name);
9857 return error;
9861 * Print and if delete is set delete all ref_prefix references.
9862 * If wanted_ref is not NULL, only print or delete this reference.
9864 static const struct got_error *
9865 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9866 const char *wanted_ref, int delete, struct got_worktree *worktree,
9867 struct got_repository *repo)
9869 const struct got_error *err;
9870 struct got_pathlist_head paths;
9871 struct got_reflist_head refs;
9872 struct got_reflist_entry *re;
9873 struct got_reflist_object_id_map *refs_idmap = NULL;
9874 struct got_commit_object *commit = NULL;
9875 struct got_object_id *id = NULL;
9876 const char *header_prefix;
9877 char *uuidstr = NULL;
9878 int found = 0;
9880 TAILQ_INIT(&refs);
9881 TAILQ_INIT(&paths);
9883 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9884 if (err)
9885 goto done;
9887 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9888 if (err)
9889 goto done;
9891 if (worktree != NULL) {
9892 err = got_worktree_get_uuid(&uuidstr, worktree);
9893 if (err)
9894 goto done;
9897 if (wanted_ref) {
9898 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9899 wanted_ref += 11;
9902 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9903 header_prefix = "backout";
9904 else
9905 header_prefix = "cherrypick";
9907 TAILQ_FOREACH(re, &refs, entry) {
9908 const char *refname, *wt;
9910 refname = got_ref_get_name(re->ref);
9912 err = check_cancelled(NULL);
9913 if (err)
9914 goto done;
9916 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9917 refname += prefix_len + 1; /* skip '-' delimiter */
9918 else
9919 continue;
9921 wt = refname;
9923 if (worktree == NULL || strncmp(refname, uuidstr,
9924 GOT_WORKTREE_UUID_STRLEN) == 0)
9925 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9926 else
9927 continue;
9929 err = got_repo_match_object_id(&id, NULL, refname,
9930 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9931 if (err)
9932 goto done;
9934 err = got_object_open_as_commit(&commit, repo, id);
9935 if (err)
9936 goto done;
9938 if (wanted_ref)
9939 found = strncmp(wanted_ref, refname,
9940 strlen(wanted_ref)) == 0;
9941 if (wanted_ref && !found) {
9942 struct got_reflist_head *ci_refs;
9944 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9945 id);
9947 if (ci_refs) {
9948 char *refs_str = NULL;
9949 char const *r = NULL;
9951 err = build_refs_str(&refs_str, ci_refs, id,
9952 repo, 1);
9953 if (err)
9954 goto done;
9956 r = refs_str;
9957 while (r) {
9958 if (strncmp(r, wanted_ref,
9959 strlen(wanted_ref)) == 0) {
9960 found = 1;
9961 break;
9963 r = strchr(r, ' ');
9964 if (r)
9965 ++r;
9967 free(refs_str);
9971 if (wanted_ref == NULL || found) {
9972 if (delete) {
9973 err = got_ref_delete(re->ref, repo);
9974 if (err)
9975 goto done;
9976 printf("Deleted: ");
9977 err = print_commit_oneline(commit, id, repo,
9978 refs_idmap);
9979 } else {
9981 * Print paths modified by commit to help
9982 * associate commits with worktree changes.
9984 err = get_changed_paths(&paths, commit,
9985 repo, NULL);
9986 if (err)
9987 goto done;
9989 err = print_commit(commit, id, repo, NULL,
9990 &paths, NULL, 0, 0, refs_idmap, NULL,
9991 header_prefix);
9992 got_pathlist_free(&paths,
9993 GOT_PATHLIST_FREE_ALL);
9995 if (worktree == NULL)
9996 printf("work tree: %.*s\n\n",
9997 GOT_WORKTREE_UUID_STRLEN, wt);
9999 if (err || found)
10000 goto done;
10003 got_object_commit_close(commit);
10004 commit = NULL;
10005 free(id);
10006 id = NULL;
10009 if (wanted_ref != NULL && !found)
10010 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10012 done:
10013 free(id);
10014 free(uuidstr);
10015 got_ref_list_free(&refs);
10016 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10017 if (refs_idmap)
10018 got_reflist_object_id_map_free(refs_idmap);
10019 if (commit)
10020 got_object_commit_close(commit);
10021 return err;
10025 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10026 * identified by id for log messages to prepopulate the editor on commit.
10028 static const struct got_error *
10029 logmsg_ref(struct got_object_id *id, const char *prefix,
10030 struct got_worktree *worktree, struct got_repository *repo)
10032 const struct got_error *err = NULL;
10033 char *idstr, *ref = NULL, *refname = NULL;
10034 int histedit_in_progress;
10035 int rebase_in_progress, merge_in_progress;
10038 * Silenty refuse to create merge reference if any histedit, merge,
10039 * or rebase operation is in progress.
10041 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10042 worktree);
10043 if (err)
10044 return err;
10045 if (histedit_in_progress)
10046 return NULL;
10048 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10049 if (err)
10050 return err;
10051 if (rebase_in_progress)
10052 return NULL;
10054 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10055 repo);
10056 if (err)
10057 return err;
10058 if (merge_in_progress)
10059 return NULL;
10061 err = got_object_id_str(&idstr, id);
10062 if (err)
10063 return err;
10065 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10066 if (err)
10067 goto done;
10069 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10070 err = got_error_from_errno("asprintf");
10071 goto done;
10074 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10075 -1, repo);
10076 done:
10077 free(ref);
10078 free(idstr);
10079 free(refname);
10080 return err;
10083 __dead static void
10084 usage_cherrypick(void)
10086 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10087 getprogname());
10088 exit(1);
10091 static const struct got_error *
10092 cmd_cherrypick(int argc, char *argv[])
10094 const struct got_error *error = NULL;
10095 struct got_worktree *worktree = NULL;
10096 struct got_repository *repo = NULL;
10097 char *cwd = NULL, *commit_id_str = NULL;
10098 struct got_object_id *commit_id = NULL;
10099 struct got_commit_object *commit = NULL;
10100 struct got_object_qid *pid;
10101 int ch, list_refs = 0, remove_refs = 0;
10102 struct got_update_progress_arg upa;
10103 int *pack_fds = NULL;
10105 #ifndef PROFILE
10106 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10107 "unveil", NULL) == -1)
10108 err(1, "pledge");
10109 #endif
10111 while ((ch = getopt(argc, argv, "lX")) != -1) {
10112 switch (ch) {
10113 case 'l':
10114 list_refs = 1;
10115 break;
10116 case 'X':
10117 remove_refs = 1;
10118 break;
10119 default:
10120 usage_cherrypick();
10121 /* NOTREACHED */
10125 argc -= optind;
10126 argv += optind;
10128 if (list_refs || remove_refs) {
10129 if (argc != 0 && argc != 1)
10130 usage_cherrypick();
10131 } else if (argc != 1)
10132 usage_cherrypick();
10133 if (list_refs && remove_refs)
10134 option_conflict('l', 'X');
10136 cwd = getcwd(NULL, 0);
10137 if (cwd == NULL) {
10138 error = got_error_from_errno("getcwd");
10139 goto done;
10142 error = got_repo_pack_fds_open(&pack_fds);
10143 if (error != NULL)
10144 goto done;
10146 error = got_worktree_open(&worktree, cwd);
10147 if (error) {
10148 if (list_refs || remove_refs) {
10149 if (error->code != GOT_ERR_NOT_WORKTREE)
10150 goto done;
10151 } else {
10152 if (error->code == GOT_ERR_NOT_WORKTREE)
10153 error = wrap_not_worktree_error(error,
10154 "cherrypick", cwd);
10155 goto done;
10159 error = got_repo_open(&repo,
10160 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10161 NULL, pack_fds);
10162 if (error != NULL)
10163 goto done;
10165 error = apply_unveil(got_repo_get_path(repo), 0,
10166 worktree ? got_worktree_get_root_path(worktree) : NULL);
10167 if (error)
10168 goto done;
10170 if (list_refs || remove_refs) {
10171 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10172 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10173 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10174 goto done;
10177 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10178 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10179 if (error)
10180 goto done;
10181 error = got_object_id_str(&commit_id_str, commit_id);
10182 if (error)
10183 goto done;
10185 error = got_object_open_as_commit(&commit, repo, commit_id);
10186 if (error)
10187 goto done;
10188 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10189 memset(&upa, 0, sizeof(upa));
10190 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10191 commit_id, repo, update_progress, &upa, check_cancelled,
10192 NULL);
10193 if (error != NULL)
10194 goto done;
10196 if (upa.did_something) {
10197 error = logmsg_ref(commit_id,
10198 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10199 if (error)
10200 goto done;
10201 printf("Merged commit %s\n", commit_id_str);
10203 print_merge_progress_stats(&upa);
10204 done:
10205 free(cwd);
10206 if (commit)
10207 got_object_commit_close(commit);
10208 free(commit_id_str);
10209 if (worktree)
10210 got_worktree_close(worktree);
10211 if (repo) {
10212 const struct got_error *close_err = got_repo_close(repo);
10213 if (error == NULL)
10214 error = close_err;
10216 if (pack_fds) {
10217 const struct got_error *pack_err =
10218 got_repo_pack_fds_close(pack_fds);
10219 if (error == NULL)
10220 error = pack_err;
10223 return error;
10226 __dead static void
10227 usage_backout(void)
10229 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10230 exit(1);
10233 static const struct got_error *
10234 cmd_backout(int argc, char *argv[])
10236 const struct got_error *error = NULL;
10237 struct got_worktree *worktree = NULL;
10238 struct got_repository *repo = NULL;
10239 char *cwd = NULL, *commit_id_str = NULL;
10240 struct got_object_id *commit_id = NULL;
10241 struct got_commit_object *commit = NULL;
10242 struct got_object_qid *pid;
10243 int ch, list_refs = 0, remove_refs = 0;
10244 struct got_update_progress_arg upa;
10245 int *pack_fds = NULL;
10247 #ifndef PROFILE
10248 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10249 "unveil", NULL) == -1)
10250 err(1, "pledge");
10251 #endif
10253 while ((ch = getopt(argc, argv, "lX")) != -1) {
10254 switch (ch) {
10255 case 'l':
10256 list_refs = 1;
10257 break;
10258 case 'X':
10259 remove_refs = 1;
10260 break;
10261 default:
10262 usage_backout();
10263 /* NOTREACHED */
10267 argc -= optind;
10268 argv += optind;
10270 if (list_refs || remove_refs) {
10271 if (argc != 0 && argc != 1)
10272 usage_backout();
10273 } else if (argc != 1)
10274 usage_backout();
10275 if (list_refs && remove_refs)
10276 option_conflict('l', 'X');
10278 cwd = getcwd(NULL, 0);
10279 if (cwd == NULL) {
10280 error = got_error_from_errno("getcwd");
10281 goto done;
10284 error = got_repo_pack_fds_open(&pack_fds);
10285 if (error != NULL)
10286 goto done;
10288 error = got_worktree_open(&worktree, cwd);
10289 if (error) {
10290 if (list_refs || remove_refs) {
10291 if (error->code != GOT_ERR_NOT_WORKTREE)
10292 goto done;
10293 } else {
10294 if (error->code == GOT_ERR_NOT_WORKTREE)
10295 error = wrap_not_worktree_error(error,
10296 "backout", cwd);
10297 goto done;
10301 error = got_repo_open(&repo,
10302 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10303 NULL, pack_fds);
10304 if (error != NULL)
10305 goto done;
10307 error = apply_unveil(got_repo_get_path(repo), 0,
10308 worktree ? got_worktree_get_root_path(worktree) : NULL);
10309 if (error)
10310 goto done;
10312 if (list_refs || remove_refs) {
10313 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10314 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10315 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10316 goto done;
10319 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10320 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10321 if (error)
10322 goto done;
10323 error = got_object_id_str(&commit_id_str, commit_id);
10324 if (error)
10325 goto done;
10327 error = got_object_open_as_commit(&commit, repo, commit_id);
10328 if (error)
10329 goto done;
10330 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10331 if (pid == NULL) {
10332 error = got_error(GOT_ERR_ROOT_COMMIT);
10333 goto done;
10336 memset(&upa, 0, sizeof(upa));
10337 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10338 repo, update_progress, &upa, check_cancelled, NULL);
10339 if (error != NULL)
10340 goto done;
10342 if (upa.did_something) {
10343 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10344 worktree, repo);
10345 if (error)
10346 goto done;
10347 printf("Backed out commit %s\n", commit_id_str);
10349 print_merge_progress_stats(&upa);
10350 done:
10351 free(cwd);
10352 if (commit)
10353 got_object_commit_close(commit);
10354 free(commit_id_str);
10355 if (worktree)
10356 got_worktree_close(worktree);
10357 if (repo) {
10358 const struct got_error *close_err = got_repo_close(repo);
10359 if (error == NULL)
10360 error = close_err;
10362 if (pack_fds) {
10363 const struct got_error *pack_err =
10364 got_repo_pack_fds_close(pack_fds);
10365 if (error == NULL)
10366 error = pack_err;
10368 return error;
10371 __dead static void
10372 usage_rebase(void)
10374 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10375 exit(1);
10378 static void
10379 trim_logmsg(char *logmsg, int limit)
10381 char *nl;
10382 size_t len;
10384 len = strlen(logmsg);
10385 if (len > limit)
10386 len = limit;
10387 logmsg[len] = '\0';
10388 nl = strchr(logmsg, '\n');
10389 if (nl)
10390 *nl = '\0';
10393 static const struct got_error *
10394 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10396 const struct got_error *err;
10397 char *logmsg0 = NULL;
10398 const char *s;
10400 err = got_object_commit_get_logmsg(&logmsg0, commit);
10401 if (err)
10402 return err;
10404 s = logmsg0;
10405 while (isspace((unsigned char)s[0]))
10406 s++;
10408 *logmsg = strdup(s);
10409 if (*logmsg == NULL) {
10410 err = got_error_from_errno("strdup");
10411 goto done;
10414 trim_logmsg(*logmsg, limit);
10415 done:
10416 free(logmsg0);
10417 return err;
10420 static const struct got_error *
10421 show_rebase_merge_conflict(struct got_object_id *id,
10422 struct got_repository *repo)
10424 const struct got_error *err;
10425 struct got_commit_object *commit = NULL;
10426 char *id_str = NULL, *logmsg = NULL;
10428 err = got_object_open_as_commit(&commit, repo, id);
10429 if (err)
10430 return err;
10432 err = got_object_id_str(&id_str, id);
10433 if (err)
10434 goto done;
10436 id_str[12] = '\0';
10438 err = get_short_logmsg(&logmsg, 42, commit);
10439 if (err)
10440 goto done;
10442 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10443 done:
10444 free(id_str);
10445 got_object_commit_close(commit);
10446 free(logmsg);
10447 return err;
10450 static const struct got_error *
10451 show_rebase_progress(struct got_commit_object *commit,
10452 struct got_object_id *old_id, struct got_object_id *new_id)
10454 const struct got_error *err;
10455 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10457 err = got_object_id_str(&old_id_str, old_id);
10458 if (err)
10459 goto done;
10461 if (new_id) {
10462 err = got_object_id_str(&new_id_str, new_id);
10463 if (err)
10464 goto done;
10467 old_id_str[12] = '\0';
10468 if (new_id_str)
10469 new_id_str[12] = '\0';
10471 err = get_short_logmsg(&logmsg, 42, commit);
10472 if (err)
10473 goto done;
10475 printf("%s -> %s: %s\n", old_id_str,
10476 new_id_str ? new_id_str : "no-op change", logmsg);
10477 done:
10478 free(old_id_str);
10479 free(new_id_str);
10480 free(logmsg);
10481 return err;
10484 static const struct got_error *
10485 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10486 struct got_reference *branch, struct got_reference *tmp_branch,
10487 struct got_repository *repo, int create_backup)
10489 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10490 return got_worktree_rebase_complete(worktree, fileindex,
10491 tmp_branch, branch, repo, create_backup);
10494 static const struct got_error *
10495 rebase_commit(struct got_pathlist_head *merged_paths,
10496 struct got_worktree *worktree, struct got_fileindex *fileindex,
10497 struct got_reference *tmp_branch, const char *committer,
10498 struct got_object_id *commit_id, int allow_conflict,
10499 struct got_repository *repo)
10501 const struct got_error *error;
10502 struct got_commit_object *commit;
10503 struct got_object_id *new_commit_id;
10505 error = got_object_open_as_commit(&commit, repo, commit_id);
10506 if (error)
10507 return error;
10509 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10510 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10511 allow_conflict, repo);
10512 if (error) {
10513 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10514 goto done;
10515 error = show_rebase_progress(commit, commit_id, NULL);
10516 } else {
10517 error = show_rebase_progress(commit, commit_id, new_commit_id);
10518 free(new_commit_id);
10520 done:
10521 got_object_commit_close(commit);
10522 return error;
10525 struct check_path_prefix_arg {
10526 const char *path_prefix;
10527 size_t len;
10528 int errcode;
10531 static const struct got_error *
10532 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10533 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10534 struct got_object_id *id1, struct got_object_id *id2,
10535 const char *path1, const char *path2,
10536 mode_t mode1, mode_t mode2, struct got_repository *repo)
10538 struct check_path_prefix_arg *a = arg;
10540 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10541 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10542 return got_error(a->errcode);
10544 return NULL;
10547 static const struct got_error *
10548 check_path_prefix(struct got_object_id *parent_id,
10549 struct got_object_id *commit_id, const char *path_prefix,
10550 int errcode, struct got_repository *repo)
10552 const struct got_error *err;
10553 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10554 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10555 struct check_path_prefix_arg cpp_arg;
10557 if (got_path_is_root_dir(path_prefix))
10558 return NULL;
10560 err = got_object_open_as_commit(&commit, repo, commit_id);
10561 if (err)
10562 goto done;
10564 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10565 if (err)
10566 goto done;
10568 err = got_object_open_as_tree(&tree1, repo,
10569 got_object_commit_get_tree_id(parent_commit));
10570 if (err)
10571 goto done;
10573 err = got_object_open_as_tree(&tree2, repo,
10574 got_object_commit_get_tree_id(commit));
10575 if (err)
10576 goto done;
10578 cpp_arg.path_prefix = path_prefix;
10579 while (cpp_arg.path_prefix[0] == '/')
10580 cpp_arg.path_prefix++;
10581 cpp_arg.len = strlen(cpp_arg.path_prefix);
10582 cpp_arg.errcode = errcode;
10583 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10584 check_path_prefix_in_diff, &cpp_arg, 0);
10585 done:
10586 if (tree1)
10587 got_object_tree_close(tree1);
10588 if (tree2)
10589 got_object_tree_close(tree2);
10590 if (commit)
10591 got_object_commit_close(commit);
10592 if (parent_commit)
10593 got_object_commit_close(parent_commit);
10594 return err;
10597 static const struct got_error *
10598 collect_commits(struct got_object_id_queue *commits,
10599 struct got_object_id *initial_commit_id,
10600 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10601 const char *path_prefix, int path_prefix_errcode,
10602 struct got_repository *repo)
10604 const struct got_error *err = NULL;
10605 struct got_commit_graph *graph = NULL;
10606 struct got_object_id parent_id, commit_id;
10607 struct got_object_qid *qid;
10609 err = got_commit_graph_open(&graph, "/", 1);
10610 if (err)
10611 return err;
10613 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10614 check_cancelled, NULL);
10615 if (err)
10616 goto done;
10618 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10619 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10620 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10621 check_cancelled, NULL);
10622 if (err) {
10623 if (err->code == GOT_ERR_ITER_COMPLETED) {
10624 err = got_error_msg(GOT_ERR_ANCESTRY,
10625 "ran out of commits to rebase before "
10626 "youngest common ancestor commit has "
10627 "been reached?!?");
10629 goto done;
10630 } else {
10631 err = check_path_prefix(&parent_id, &commit_id,
10632 path_prefix, path_prefix_errcode, repo);
10633 if (err)
10634 goto done;
10636 err = got_object_qid_alloc(&qid, &commit_id);
10637 if (err)
10638 goto done;
10639 STAILQ_INSERT_HEAD(commits, qid, entry);
10641 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10644 done:
10645 got_commit_graph_close(graph);
10646 return err;
10649 static const struct got_error *
10650 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10652 const struct got_error *err = NULL;
10653 time_t committer_time;
10654 struct tm tm;
10655 char datebuf[11]; /* YYYY-MM-DD + NUL */
10656 char *author0 = NULL, *author, *smallerthan;
10657 char *logmsg0 = NULL, *logmsg, *newline;
10659 committer_time = got_object_commit_get_committer_time(commit);
10660 if (gmtime_r(&committer_time, &tm) == NULL)
10661 return got_error_from_errno("gmtime_r");
10662 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10663 return got_error(GOT_ERR_NO_SPACE);
10665 author0 = strdup(got_object_commit_get_author(commit));
10666 if (author0 == NULL)
10667 return got_error_from_errno("strdup");
10668 author = author0;
10669 smallerthan = strchr(author, '<');
10670 if (smallerthan && smallerthan[1] != '\0')
10671 author = smallerthan + 1;
10672 author[strcspn(author, "@>")] = '\0';
10674 err = got_object_commit_get_logmsg(&logmsg0, commit);
10675 if (err)
10676 goto done;
10677 logmsg = logmsg0;
10678 while (*logmsg == '\n')
10679 logmsg++;
10680 newline = strchr(logmsg, '\n');
10681 if (newline)
10682 *newline = '\0';
10684 if (asprintf(brief_str, "%s %s %s",
10685 datebuf, author, logmsg) == -1)
10686 err = got_error_from_errno("asprintf");
10687 done:
10688 free(author0);
10689 free(logmsg0);
10690 return err;
10693 static const struct got_error *
10694 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10695 struct got_repository *repo)
10697 const struct got_error *err;
10698 char *id_str;
10700 err = got_object_id_str(&id_str, id);
10701 if (err)
10702 return err;
10704 err = got_ref_delete(ref, repo);
10705 if (err)
10706 goto done;
10708 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10709 done:
10710 free(id_str);
10711 return err;
10714 static const struct got_error *
10715 print_backup_ref(const char *branch_name, const char *new_id_str,
10716 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10717 struct got_reflist_object_id_map *refs_idmap,
10718 struct got_repository *repo)
10720 const struct got_error *err = NULL;
10721 struct got_reflist_head *refs;
10722 char *refs_str = NULL;
10723 struct got_object_id *new_commit_id = NULL;
10724 struct got_commit_object *new_commit = NULL;
10725 char *new_commit_brief_str = NULL;
10726 struct got_object_id *yca_id = NULL;
10727 struct got_commit_object *yca_commit = NULL;
10728 char *yca_id_str = NULL, *yca_brief_str = NULL;
10729 char *custom_refs_str;
10731 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10732 return got_error_from_errno("asprintf");
10734 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10735 0, 0, refs_idmap, custom_refs_str, NULL);
10736 if (err)
10737 goto done;
10739 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10740 if (err)
10741 goto done;
10743 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10744 if (refs) {
10745 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10746 if (err)
10747 goto done;
10750 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10751 if (err)
10752 goto done;
10754 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10755 if (err)
10756 goto done;
10758 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10759 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10760 if (err)
10761 goto done;
10763 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10764 refs_str ? " (" : "", refs_str ? refs_str : "",
10765 refs_str ? ")" : "", new_commit_brief_str);
10766 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10767 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10768 free(refs_str);
10769 refs_str = NULL;
10771 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10772 if (err)
10773 goto done;
10775 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10776 if (err)
10777 goto done;
10779 err = got_object_id_str(&yca_id_str, yca_id);
10780 if (err)
10781 goto done;
10783 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10784 if (refs) {
10785 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10786 if (err)
10787 goto done;
10789 printf("history forked at %s%s%s%s\n %s\n",
10790 yca_id_str,
10791 refs_str ? " (" : "", refs_str ? refs_str : "",
10792 refs_str ? ")" : "", yca_brief_str);
10794 done:
10795 free(custom_refs_str);
10796 free(new_commit_id);
10797 free(refs_str);
10798 free(yca_id);
10799 free(yca_id_str);
10800 free(yca_brief_str);
10801 if (new_commit)
10802 got_object_commit_close(new_commit);
10803 if (yca_commit)
10804 got_object_commit_close(yca_commit);
10806 return err;
10809 static const struct got_error *
10810 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10811 struct got_repository *repo)
10813 const struct got_error *err;
10814 struct got_reflist_head refs;
10815 struct got_reflist_entry *re;
10816 char *uuidstr = NULL;
10817 static char msg[160];
10819 TAILQ_INIT(&refs);
10821 err = got_worktree_get_uuid(&uuidstr, worktree);
10822 if (err)
10823 goto done;
10825 err = got_ref_list(&refs, repo, "refs/got/worktree",
10826 got_ref_cmp_by_name, repo);
10827 if (err)
10828 goto done;
10830 TAILQ_FOREACH(re, &refs, entry) {
10831 const char *cmd, *refname, *type;
10833 refname = got_ref_get_name(re->ref);
10835 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10836 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10837 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10838 cmd = "cherrypick";
10839 type = "cherrypicked";
10840 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10841 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10842 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10843 cmd = "backout";
10844 type = "backed-out";
10845 } else
10846 continue;
10848 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10849 continue;
10851 snprintf(msg, sizeof(msg),
10852 "work tree has references created by %s commits which "
10853 "must be removed with 'got %s -X' before running the %s "
10854 "command", type, cmd, caller);
10855 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10856 goto done;
10859 done:
10860 free(uuidstr);
10861 got_ref_list_free(&refs);
10862 return err;
10865 static const struct got_error *
10866 process_backup_refs(const char *backup_ref_prefix,
10867 const char *wanted_branch_name,
10868 int delete, struct got_repository *repo)
10870 const struct got_error *err;
10871 struct got_reflist_head refs, backup_refs;
10872 struct got_reflist_entry *re;
10873 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10874 struct got_object_id *old_commit_id = NULL;
10875 char *branch_name = NULL;
10876 struct got_commit_object *old_commit = NULL;
10877 struct got_reflist_object_id_map *refs_idmap = NULL;
10878 int wanted_branch_found = 0;
10880 TAILQ_INIT(&refs);
10881 TAILQ_INIT(&backup_refs);
10883 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10884 if (err)
10885 return err;
10887 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10888 if (err)
10889 goto done;
10891 if (wanted_branch_name) {
10892 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10893 wanted_branch_name += 11;
10896 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10897 got_ref_cmp_by_commit_timestamp_descending, repo);
10898 if (err)
10899 goto done;
10901 TAILQ_FOREACH(re, &backup_refs, entry) {
10902 const char *refname = got_ref_get_name(re->ref);
10903 char *slash;
10905 err = check_cancelled(NULL);
10906 if (err)
10907 break;
10909 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10910 if (err)
10911 break;
10913 err = got_object_open_as_commit(&old_commit, repo,
10914 old_commit_id);
10915 if (err)
10916 break;
10918 if (strncmp(backup_ref_prefix, refname,
10919 backup_ref_prefix_len) == 0)
10920 refname += backup_ref_prefix_len;
10922 while (refname[0] == '/')
10923 refname++;
10925 branch_name = strdup(refname);
10926 if (branch_name == NULL) {
10927 err = got_error_from_errno("strdup");
10928 break;
10930 slash = strrchr(branch_name, '/');
10931 if (slash) {
10932 *slash = '\0';
10933 refname += strlen(branch_name) + 1;
10936 if (wanted_branch_name == NULL ||
10937 strcmp(wanted_branch_name, branch_name) == 0) {
10938 wanted_branch_found = 1;
10939 if (delete) {
10940 err = delete_backup_ref(re->ref,
10941 old_commit_id, repo);
10942 } else {
10943 err = print_backup_ref(branch_name, refname,
10944 old_commit_id, old_commit, refs_idmap,
10945 repo);
10947 if (err)
10948 break;
10951 free(old_commit_id);
10952 old_commit_id = NULL;
10953 free(branch_name);
10954 branch_name = NULL;
10955 got_object_commit_close(old_commit);
10956 old_commit = NULL;
10959 if (wanted_branch_name && !wanted_branch_found) {
10960 err = got_error_fmt(GOT_ERR_NOT_REF,
10961 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10963 done:
10964 if (refs_idmap)
10965 got_reflist_object_id_map_free(refs_idmap);
10966 got_ref_list_free(&refs);
10967 got_ref_list_free(&backup_refs);
10968 free(old_commit_id);
10969 free(branch_name);
10970 if (old_commit)
10971 got_object_commit_close(old_commit);
10972 return err;
10975 static const struct got_error *
10976 abort_progress(void *arg, unsigned char status, const char *path)
10979 * Unversioned files should not clutter progress output when
10980 * an operation is aborted.
10982 if (status == GOT_STATUS_UNVERSIONED)
10983 return NULL;
10985 return update_progress(arg, status, path);
10988 static const struct got_error *
10989 cmd_rebase(int argc, char *argv[])
10991 const struct got_error *error = NULL;
10992 struct got_worktree *worktree = NULL;
10993 struct got_repository *repo = NULL;
10994 struct got_fileindex *fileindex = NULL;
10995 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10996 struct got_reference *branch = NULL;
10997 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10998 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10999 struct got_object_id *resume_commit_id = NULL;
11000 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11001 struct got_object_id *head_commit_id = NULL;
11002 struct got_reference *head_ref = NULL;
11003 struct got_commit_object *commit = NULL;
11004 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11005 int histedit_in_progress = 0, merge_in_progress = 0;
11006 int create_backup = 1, list_backups = 0, delete_backups = 0;
11007 int allow_conflict = 0;
11008 struct got_object_id_queue commits;
11009 struct got_pathlist_head merged_paths;
11010 const struct got_object_id_queue *parent_ids;
11011 struct got_object_qid *qid, *pid;
11012 struct got_update_progress_arg upa;
11013 int *pack_fds = NULL;
11015 STAILQ_INIT(&commits);
11016 TAILQ_INIT(&merged_paths);
11017 memset(&upa, 0, sizeof(upa));
11019 #ifndef PROFILE
11020 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11021 "unveil", NULL) == -1)
11022 err(1, "pledge");
11023 #endif
11025 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11026 switch (ch) {
11027 case 'a':
11028 abort_rebase = 1;
11029 break;
11030 case 'C':
11031 allow_conflict = 1;
11032 break;
11033 case 'c':
11034 continue_rebase = 1;
11035 break;
11036 case 'l':
11037 list_backups = 1;
11038 break;
11039 case 'X':
11040 delete_backups = 1;
11041 break;
11042 default:
11043 usage_rebase();
11044 /* NOTREACHED */
11048 argc -= optind;
11049 argv += optind;
11051 if (list_backups) {
11052 if (abort_rebase)
11053 option_conflict('l', 'a');
11054 if (allow_conflict)
11055 option_conflict('l', 'C');
11056 if (continue_rebase)
11057 option_conflict('l', 'c');
11058 if (delete_backups)
11059 option_conflict('l', 'X');
11060 if (argc != 0 && argc != 1)
11061 usage_rebase();
11062 } else if (delete_backups) {
11063 if (abort_rebase)
11064 option_conflict('X', 'a');
11065 if (allow_conflict)
11066 option_conflict('X', 'C');
11067 if (continue_rebase)
11068 option_conflict('X', 'c');
11069 if (list_backups)
11070 option_conflict('l', 'X');
11071 if (argc != 0 && argc != 1)
11072 usage_rebase();
11073 } else if (allow_conflict) {
11074 if (abort_rebase)
11075 option_conflict('C', 'a');
11076 if (!continue_rebase)
11077 errx(1, "-C option requires -c");
11078 } else {
11079 if (abort_rebase && continue_rebase)
11080 usage_rebase();
11081 else if (abort_rebase || continue_rebase) {
11082 if (argc != 0)
11083 usage_rebase();
11084 } else if (argc != 1)
11085 usage_rebase();
11088 cwd = getcwd(NULL, 0);
11089 if (cwd == NULL) {
11090 error = got_error_from_errno("getcwd");
11091 goto done;
11094 error = got_repo_pack_fds_open(&pack_fds);
11095 if (error != NULL)
11096 goto done;
11098 error = got_worktree_open(&worktree, cwd);
11099 if (error) {
11100 if (list_backups || delete_backups) {
11101 if (error->code != GOT_ERR_NOT_WORKTREE)
11102 goto done;
11103 } else {
11104 if (error->code == GOT_ERR_NOT_WORKTREE)
11105 error = wrap_not_worktree_error(error,
11106 "rebase", cwd);
11107 goto done;
11111 error = get_gitconfig_path(&gitconfig_path);
11112 if (error)
11113 goto done;
11114 error = got_repo_open(&repo,
11115 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11116 gitconfig_path, pack_fds);
11117 if (error != NULL)
11118 goto done;
11120 if (worktree != NULL && !list_backups && !delete_backups) {
11121 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11122 if (error)
11123 goto done;
11126 error = get_author(&committer, repo, worktree);
11127 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11128 goto done;
11130 error = apply_unveil(got_repo_get_path(repo), 0,
11131 worktree ? got_worktree_get_root_path(worktree) : NULL);
11132 if (error)
11133 goto done;
11135 if (list_backups || delete_backups) {
11136 error = process_backup_refs(
11137 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11138 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11139 goto done; /* nothing else to do */
11142 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11143 worktree);
11144 if (error)
11145 goto done;
11146 if (histedit_in_progress) {
11147 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11148 goto done;
11151 error = got_worktree_merge_in_progress(&merge_in_progress,
11152 worktree, repo);
11153 if (error)
11154 goto done;
11155 if (merge_in_progress) {
11156 error = got_error(GOT_ERR_MERGE_BUSY);
11157 goto done;
11160 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11161 if (error)
11162 goto done;
11164 if (abort_rebase) {
11165 if (!rebase_in_progress) {
11166 error = got_error(GOT_ERR_NOT_REBASING);
11167 goto done;
11169 error = got_worktree_rebase_continue(&resume_commit_id,
11170 &new_base_branch, &tmp_branch, &branch, &fileindex,
11171 worktree, repo);
11172 if (error)
11173 goto done;
11174 printf("Switching work tree to %s\n",
11175 got_ref_get_symref_target(new_base_branch));
11176 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11177 new_base_branch, abort_progress, &upa);
11178 if (error)
11179 goto done;
11180 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11181 print_merge_progress_stats(&upa);
11182 goto done; /* nothing else to do */
11185 if (continue_rebase) {
11186 if (!rebase_in_progress) {
11187 error = got_error(GOT_ERR_NOT_REBASING);
11188 goto done;
11190 error = got_worktree_rebase_continue(&resume_commit_id,
11191 &new_base_branch, &tmp_branch, &branch, &fileindex,
11192 worktree, repo);
11193 if (error)
11194 goto done;
11196 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11197 committer, resume_commit_id, allow_conflict, repo);
11198 if (error)
11199 goto done;
11201 yca_id = got_object_id_dup(resume_commit_id);
11202 if (yca_id == NULL) {
11203 error = got_error_from_errno("got_object_id_dup");
11204 goto done;
11206 } else {
11207 error = got_ref_open(&branch, repo, argv[0], 0);
11208 if (error != NULL)
11209 goto done;
11210 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11211 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11212 "will not rebase a branch which lives outside "
11213 "the \"refs/heads/\" reference namespace");
11214 goto done;
11218 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11219 if (error)
11220 goto done;
11222 if (!continue_rebase) {
11223 struct got_object_id *base_commit_id;
11225 error = got_ref_open(&head_ref, repo,
11226 got_worktree_get_head_ref_name(worktree), 0);
11227 if (error)
11228 goto done;
11229 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11230 if (error)
11231 goto done;
11232 base_commit_id = got_worktree_get_base_commit_id(worktree);
11233 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11234 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11235 goto done;
11238 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11239 base_commit_id, branch_head_commit_id, 1, repo,
11240 check_cancelled, NULL);
11241 if (error) {
11242 if (error->code == GOT_ERR_ANCESTRY) {
11243 error = got_error_msg(GOT_ERR_ANCESTRY,
11244 "specified branch shares no common "
11245 "ancestry with work tree's branch");
11247 goto done;
11250 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11251 if (error) {
11252 if (error->code != GOT_ERR_ANCESTRY)
11253 goto done;
11254 error = NULL;
11255 } else {
11256 struct got_pathlist_head paths;
11257 printf("%s is already based on %s\n",
11258 got_ref_get_name(branch),
11259 got_worktree_get_head_ref_name(worktree));
11260 error = switch_head_ref(branch, branch_head_commit_id,
11261 worktree, repo);
11262 if (error)
11263 goto done;
11264 error = got_worktree_set_base_commit_id(worktree, repo,
11265 branch_head_commit_id);
11266 if (error)
11267 goto done;
11268 TAILQ_INIT(&paths);
11269 error = got_pathlist_append(&paths, "", NULL);
11270 if (error)
11271 goto done;
11272 error = got_worktree_checkout_files(worktree,
11273 &paths, repo, update_progress, &upa,
11274 check_cancelled, NULL);
11275 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11276 if (error)
11277 goto done;
11278 if (upa.did_something) {
11279 char *id_str;
11280 error = got_object_id_str(&id_str,
11281 branch_head_commit_id);
11282 if (error)
11283 goto done;
11284 printf("Updated to %s: %s\n",
11285 got_worktree_get_head_ref_name(worktree),
11286 id_str);
11287 free(id_str);
11288 } else
11289 printf("Already up-to-date\n");
11290 print_update_progress_stats(&upa);
11291 goto done;
11295 commit_id = branch_head_commit_id;
11296 error = got_object_open_as_commit(&commit, repo, commit_id);
11297 if (error)
11298 goto done;
11300 parent_ids = got_object_commit_get_parent_ids(commit);
11301 pid = STAILQ_FIRST(parent_ids);
11302 if (pid) {
11303 error = collect_commits(&commits, commit_id, &pid->id,
11304 yca_id, got_worktree_get_path_prefix(worktree),
11305 GOT_ERR_REBASE_PATH, repo);
11306 if (error)
11307 goto done;
11310 got_object_commit_close(commit);
11311 commit = NULL;
11313 if (!continue_rebase) {
11314 error = got_worktree_rebase_prepare(&new_base_branch,
11315 &tmp_branch, &fileindex, worktree, branch, repo);
11316 if (error)
11317 goto done;
11320 if (STAILQ_EMPTY(&commits)) {
11321 if (continue_rebase) {
11322 error = rebase_complete(worktree, fileindex,
11323 branch, tmp_branch, repo, create_backup);
11324 goto done;
11325 } else {
11326 /* Fast-forward the reference of the branch. */
11327 struct got_object_id *new_head_commit_id;
11328 char *id_str;
11329 error = got_ref_resolve(&new_head_commit_id, repo,
11330 new_base_branch);
11331 if (error)
11332 goto done;
11333 error = got_object_id_str(&id_str, new_head_commit_id);
11334 if (error)
11335 goto done;
11336 printf("Forwarding %s to commit %s\n",
11337 got_ref_get_name(branch), id_str);
11338 free(id_str);
11339 error = got_ref_change_ref(branch,
11340 new_head_commit_id);
11341 if (error)
11342 goto done;
11343 /* No backup needed since objects did not change. */
11344 create_backup = 0;
11348 pid = NULL;
11349 STAILQ_FOREACH(qid, &commits, entry) {
11351 commit_id = &qid->id;
11352 parent_id = pid ? &pid->id : yca_id;
11353 pid = qid;
11355 memset(&upa, 0, sizeof(upa));
11356 error = got_worktree_rebase_merge_files(&merged_paths,
11357 worktree, fileindex, parent_id, commit_id, repo,
11358 update_progress, &upa, check_cancelled, NULL);
11359 if (error)
11360 goto done;
11362 print_merge_progress_stats(&upa);
11363 if (upa.conflicts > 0 || upa.missing > 0 ||
11364 upa.not_deleted > 0 || upa.unversioned > 0) {
11365 if (upa.conflicts > 0) {
11366 error = show_rebase_merge_conflict(&qid->id,
11367 repo);
11368 if (error)
11369 goto done;
11371 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11372 break;
11375 error = rebase_commit(&merged_paths, worktree, fileindex,
11376 tmp_branch, committer, commit_id, 0, repo);
11377 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11378 if (error)
11379 goto done;
11382 if (upa.conflicts > 0 || upa.missing > 0 ||
11383 upa.not_deleted > 0 || upa.unversioned > 0) {
11384 error = got_worktree_rebase_postpone(worktree, fileindex);
11385 if (error)
11386 goto done;
11387 if (upa.conflicts > 0 && upa.missing == 0 &&
11388 upa.not_deleted == 0 && upa.unversioned == 0) {
11389 error = got_error_msg(GOT_ERR_CONFLICTS,
11390 "conflicts must be resolved before rebasing "
11391 "can continue");
11392 } else if (upa.conflicts > 0) {
11393 error = got_error_msg(GOT_ERR_CONFLICTS,
11394 "conflicts must be resolved before rebasing "
11395 "can continue; changes destined for some "
11396 "files were not yet merged and should be "
11397 "merged manually if required before the "
11398 "rebase operation is continued");
11399 } else {
11400 error = got_error_msg(GOT_ERR_CONFLICTS,
11401 "changes destined for some files were not "
11402 "yet merged and should be merged manually "
11403 "if required before the rebase operation "
11404 "is continued");
11406 } else
11407 error = rebase_complete(worktree, fileindex, branch,
11408 tmp_branch, repo, create_backup);
11409 done:
11410 free(cwd);
11411 free(committer);
11412 free(gitconfig_path);
11413 got_object_id_queue_free(&commits);
11414 free(branch_head_commit_id);
11415 free(resume_commit_id);
11416 free(head_commit_id);
11417 free(yca_id);
11418 if (commit)
11419 got_object_commit_close(commit);
11420 if (branch)
11421 got_ref_close(branch);
11422 if (new_base_branch)
11423 got_ref_close(new_base_branch);
11424 if (tmp_branch)
11425 got_ref_close(tmp_branch);
11426 if (head_ref)
11427 got_ref_close(head_ref);
11428 if (worktree)
11429 got_worktree_close(worktree);
11430 if (repo) {
11431 const struct got_error *close_err = got_repo_close(repo);
11432 if (error == NULL)
11433 error = close_err;
11435 if (pack_fds) {
11436 const struct got_error *pack_err =
11437 got_repo_pack_fds_close(pack_fds);
11438 if (error == NULL)
11439 error = pack_err;
11441 return error;
11444 __dead static void
11445 usage_histedit(void)
11447 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11448 "[branch]\n", getprogname());
11449 exit(1);
11452 #define GOT_HISTEDIT_PICK 'p'
11453 #define GOT_HISTEDIT_EDIT 'e'
11454 #define GOT_HISTEDIT_FOLD 'f'
11455 #define GOT_HISTEDIT_DROP 'd'
11456 #define GOT_HISTEDIT_MESG 'm'
11458 static const struct got_histedit_cmd {
11459 unsigned char code;
11460 const char *name;
11461 const char *desc;
11462 } got_histedit_cmds[] = {
11463 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11464 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11465 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11466 "be used" },
11467 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11468 { GOT_HISTEDIT_MESG, "mesg",
11469 "single-line log message for commit above (open editor if empty)" },
11472 struct got_histedit_list_entry {
11473 TAILQ_ENTRY(got_histedit_list_entry) entry;
11474 struct got_object_id *commit_id;
11475 const struct got_histedit_cmd *cmd;
11476 char *logmsg;
11478 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11480 static const struct got_error *
11481 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11482 FILE *f, struct got_repository *repo)
11484 const struct got_error *err = NULL;
11485 char *logmsg = NULL, *id_str = NULL;
11486 struct got_commit_object *commit = NULL;
11487 int n;
11489 err = got_object_open_as_commit(&commit, repo, commit_id);
11490 if (err)
11491 goto done;
11493 err = get_short_logmsg(&logmsg, 34, commit);
11494 if (err)
11495 goto done;
11497 err = got_object_id_str(&id_str, commit_id);
11498 if (err)
11499 goto done;
11501 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11502 if (n < 0)
11503 err = got_ferror(f, GOT_ERR_IO);
11504 done:
11505 if (commit)
11506 got_object_commit_close(commit);
11507 free(id_str);
11508 free(logmsg);
11509 return err;
11512 static const struct got_error *
11513 histedit_write_commit_list(struct got_object_id_queue *commits,
11514 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11515 int edit_only, struct got_repository *repo)
11517 const struct got_error *err = NULL;
11518 struct got_object_qid *qid;
11519 const char *histedit_cmd = NULL;
11521 if (STAILQ_EMPTY(commits))
11522 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11524 STAILQ_FOREACH(qid, commits, entry) {
11525 histedit_cmd = got_histedit_cmds[0].name;
11526 if (drop_only)
11527 histedit_cmd = "drop";
11528 else if (edit_only)
11529 histedit_cmd = "edit";
11530 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11531 histedit_cmd = "fold";
11532 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11533 if (err)
11534 break;
11535 if (edit_logmsg_only) {
11536 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11537 if (n < 0) {
11538 err = got_ferror(f, GOT_ERR_IO);
11539 break;
11544 return err;
11547 static const struct got_error *
11548 write_cmd_list(FILE *f, const char *branch_name,
11549 struct got_object_id_queue *commits)
11551 const struct got_error *err = NULL;
11552 size_t i;
11553 int n;
11554 char *id_str;
11555 struct got_object_qid *qid;
11557 qid = STAILQ_FIRST(commits);
11558 err = got_object_id_str(&id_str, &qid->id);
11559 if (err)
11560 return err;
11562 n = fprintf(f,
11563 "# Editing the history of branch '%s' starting at\n"
11564 "# commit %s\n"
11565 "# Commits will be processed in order from top to "
11566 "bottom of this file.\n", branch_name, id_str);
11567 if (n < 0) {
11568 err = got_ferror(f, GOT_ERR_IO);
11569 goto done;
11572 n = fprintf(f, "# Available histedit commands:\n");
11573 if (n < 0) {
11574 err = got_ferror(f, GOT_ERR_IO);
11575 goto done;
11578 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11579 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11580 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11581 cmd->desc);
11582 if (n < 0) {
11583 err = got_ferror(f, GOT_ERR_IO);
11584 break;
11587 done:
11588 free(id_str);
11589 return err;
11592 static const struct got_error *
11593 histedit_syntax_error(int lineno)
11595 static char msg[42];
11596 int ret;
11598 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11599 lineno);
11600 if (ret < 0 || (size_t)ret >= sizeof(msg))
11601 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11603 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11606 static const struct got_error *
11607 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11608 char *logmsg, struct got_repository *repo)
11610 const struct got_error *err;
11611 struct got_commit_object *folded_commit = NULL;
11612 char *id_str, *folded_logmsg = NULL;
11614 err = got_object_id_str(&id_str, hle->commit_id);
11615 if (err)
11616 return err;
11618 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11619 if (err)
11620 goto done;
11622 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11623 if (err)
11624 goto done;
11625 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11626 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11627 folded_logmsg) == -1) {
11628 err = got_error_from_errno("asprintf");
11630 done:
11631 if (folded_commit)
11632 got_object_commit_close(folded_commit);
11633 free(id_str);
11634 free(folded_logmsg);
11635 return err;
11638 static struct got_histedit_list_entry *
11639 get_folded_commits(struct got_histedit_list_entry *hle)
11641 struct got_histedit_list_entry *prev, *folded = NULL;
11643 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11644 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11645 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11646 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11647 folded = prev;
11648 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11651 return folded;
11654 static const struct got_error *
11655 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11656 struct got_repository *repo)
11658 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11659 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11660 const struct got_error *err = NULL;
11661 struct got_commit_object *commit = NULL;
11662 int logmsg_len;
11663 int fd;
11664 struct got_histedit_list_entry *folded = NULL;
11666 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11667 if (err)
11668 return err;
11670 folded = get_folded_commits(hle);
11671 if (folded) {
11672 while (folded != hle) {
11673 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11674 folded = TAILQ_NEXT(folded, entry);
11675 continue;
11677 err = append_folded_commit_msg(&new_msg, folded,
11678 logmsg, repo);
11679 if (err)
11680 goto done;
11681 free(logmsg);
11682 logmsg = new_msg;
11683 folded = TAILQ_NEXT(folded, entry);
11687 err = got_object_id_str(&id_str, hle->commit_id);
11688 if (err)
11689 goto done;
11690 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11691 if (err)
11692 goto done;
11693 logmsg_len = asprintf(&new_msg,
11694 "%s\n# original log message of commit %s: %s",
11695 logmsg ? logmsg : "", id_str, orig_logmsg);
11696 if (logmsg_len == -1) {
11697 err = got_error_from_errno("asprintf");
11698 goto done;
11700 free(logmsg);
11701 logmsg = new_msg;
11703 err = got_object_id_str(&id_str, hle->commit_id);
11704 if (err)
11705 goto done;
11707 err = got_opentemp_named_fd(&logmsg_path, &fd,
11708 GOT_TMPDIR_STR "/got-logmsg", "");
11709 if (err)
11710 goto done;
11712 write(fd, logmsg, logmsg_len);
11713 close(fd);
11715 err = get_editor(&editor);
11716 if (err)
11717 goto done;
11719 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11720 logmsg_len, 0);
11721 if (err) {
11722 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11723 goto done;
11724 err = NULL;
11725 hle->logmsg = strdup(new_msg);
11726 if (hle->logmsg == NULL)
11727 err = got_error_from_errno("strdup");
11729 done:
11730 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11731 err = got_error_from_errno2("unlink", logmsg_path);
11732 free(logmsg_path);
11733 free(logmsg);
11734 free(orig_logmsg);
11735 free(editor);
11736 if (commit)
11737 got_object_commit_close(commit);
11738 return err;
11741 static const struct got_error *
11742 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11743 FILE *f, struct got_repository *repo)
11745 const struct got_error *err = NULL;
11746 char *line = NULL, *p, *end;
11747 size_t i, linesize = 0;
11748 ssize_t linelen;
11749 int lineno = 0, lastcmd = -1;
11750 const struct got_histedit_cmd *cmd;
11751 struct got_object_id *commit_id = NULL;
11752 struct got_histedit_list_entry *hle = NULL;
11754 for (;;) {
11755 linelen = getline(&line, &linesize, f);
11756 if (linelen == -1) {
11757 const struct got_error *getline_err;
11758 if (feof(f))
11759 break;
11760 getline_err = got_error_from_errno("getline");
11761 err = got_ferror(f, getline_err->code);
11762 break;
11764 lineno++;
11765 p = line;
11766 while (isspace((unsigned char)p[0]))
11767 p++;
11768 if (p[0] == '#' || p[0] == '\0')
11769 continue;
11770 cmd = NULL;
11771 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11772 cmd = &got_histedit_cmds[i];
11773 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11774 isspace((unsigned char)p[strlen(cmd->name)])) {
11775 p += strlen(cmd->name);
11776 break;
11778 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11779 p++;
11780 break;
11783 if (i == nitems(got_histedit_cmds)) {
11784 err = histedit_syntax_error(lineno);
11785 break;
11787 while (isspace((unsigned char)p[0]))
11788 p++;
11789 if (cmd->code == GOT_HISTEDIT_MESG) {
11790 if (lastcmd != GOT_HISTEDIT_PICK &&
11791 lastcmd != GOT_HISTEDIT_EDIT) {
11792 err = got_error(GOT_ERR_HISTEDIT_CMD);
11793 break;
11795 if (p[0] == '\0') {
11796 err = histedit_edit_logmsg(hle, repo);
11797 if (err)
11798 break;
11799 } else {
11800 hle->logmsg = strdup(p);
11801 if (hle->logmsg == NULL) {
11802 err = got_error_from_errno("strdup");
11803 break;
11806 lastcmd = cmd->code;
11807 continue;
11808 } else {
11809 end = p;
11810 while (end[0] && !isspace((unsigned char)end[0]))
11811 end++;
11812 *end = '\0';
11814 err = got_object_resolve_id_str(&commit_id, repo, p);
11815 if (err) {
11816 /* override error code */
11817 err = histedit_syntax_error(lineno);
11818 break;
11821 hle = malloc(sizeof(*hle));
11822 if (hle == NULL) {
11823 err = got_error_from_errno("malloc");
11824 break;
11826 hle->cmd = cmd;
11827 hle->commit_id = commit_id;
11828 hle->logmsg = NULL;
11829 commit_id = NULL;
11830 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11831 lastcmd = cmd->code;
11834 free(line);
11835 free(commit_id);
11836 return err;
11839 static const struct got_error *
11840 histedit_check_script(struct got_histedit_list *histedit_cmds,
11841 struct got_object_id_queue *commits, struct got_repository *repo)
11843 const struct got_error *err = NULL;
11844 struct got_object_qid *qid;
11845 struct got_histedit_list_entry *hle;
11846 static char msg[92];
11847 char *id_str;
11849 if (TAILQ_EMPTY(histedit_cmds))
11850 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11851 "histedit script contains no commands");
11852 if (STAILQ_EMPTY(commits))
11853 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11855 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11856 struct got_histedit_list_entry *hle2;
11857 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11858 if (hle == hle2)
11859 continue;
11860 if (got_object_id_cmp(hle->commit_id,
11861 hle2->commit_id) != 0)
11862 continue;
11863 err = got_object_id_str(&id_str, hle->commit_id);
11864 if (err)
11865 return err;
11866 snprintf(msg, sizeof(msg), "commit %s is listed "
11867 "more than once in histedit script", id_str);
11868 free(id_str);
11869 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11873 STAILQ_FOREACH(qid, commits, entry) {
11874 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11875 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11876 break;
11878 if (hle == NULL) {
11879 err = got_object_id_str(&id_str, &qid->id);
11880 if (err)
11881 return err;
11882 snprintf(msg, sizeof(msg),
11883 "commit %s missing from histedit script", id_str);
11884 free(id_str);
11885 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11889 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11890 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11891 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11892 "last commit in histedit script cannot be folded");
11894 return NULL;
11897 static const struct got_error *
11898 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11899 const char *path, struct got_object_id_queue *commits,
11900 struct got_repository *repo)
11902 const struct got_error *err = NULL;
11903 char *editor;
11904 FILE *f = NULL;
11906 err = get_editor(&editor);
11907 if (err)
11908 return err;
11910 if (spawn_editor(editor, path) == -1) {
11911 err = got_error_from_errno("failed spawning editor");
11912 goto done;
11915 f = fopen(path, "re");
11916 if (f == NULL) {
11917 err = got_error_from_errno("fopen");
11918 goto done;
11920 err = histedit_parse_list(histedit_cmds, f, repo);
11921 if (err)
11922 goto done;
11924 err = histedit_check_script(histedit_cmds, commits, repo);
11925 done:
11926 if (f && fclose(f) == EOF && err == NULL)
11927 err = got_error_from_errno("fclose");
11928 free(editor);
11929 return err;
11932 static const struct got_error *
11933 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11934 struct got_object_id_queue *, const char *, const char *,
11935 struct got_repository *);
11937 static const struct got_error *
11938 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11939 struct got_object_id_queue *commits, const char *branch_name,
11940 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11941 struct got_repository *repo)
11943 const struct got_error *err;
11944 FILE *f = NULL;
11945 char *path = NULL;
11947 err = got_opentemp_named(&path, &f, "got-histedit", "");
11948 if (err)
11949 return err;
11951 err = write_cmd_list(f, branch_name, commits);
11952 if (err)
11953 goto done;
11955 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11956 fold_only, drop_only, edit_only, repo);
11957 if (err)
11958 goto done;
11960 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11961 rewind(f);
11962 err = histedit_parse_list(histedit_cmds, f, repo);
11963 } else {
11964 if (fclose(f) == EOF) {
11965 err = got_error_from_errno("fclose");
11966 goto done;
11968 f = NULL;
11969 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11970 if (err) {
11971 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11972 err->code != GOT_ERR_HISTEDIT_CMD)
11973 goto done;
11974 err = histedit_edit_list_retry(histedit_cmds, err,
11975 commits, path, branch_name, repo);
11978 done:
11979 if (f && fclose(f) == EOF && err == NULL)
11980 err = got_error_from_errno("fclose");
11981 if (path && unlink(path) != 0 && err == NULL)
11982 err = got_error_from_errno2("unlink", path);
11983 free(path);
11984 return err;
11987 static const struct got_error *
11988 histedit_save_list(struct got_histedit_list *histedit_cmds,
11989 struct got_worktree *worktree, struct got_repository *repo)
11991 const struct got_error *err = NULL;
11992 char *path = NULL;
11993 FILE *f = NULL;
11994 struct got_histedit_list_entry *hle;
11995 struct got_commit_object *commit = NULL;
11997 err = got_worktree_get_histedit_script_path(&path, worktree);
11998 if (err)
11999 return err;
12001 f = fopen(path, "we");
12002 if (f == NULL) {
12003 err = got_error_from_errno2("fopen", path);
12004 goto done;
12006 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12007 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12008 repo);
12009 if (err)
12010 break;
12012 if (hle->logmsg) {
12013 int n = fprintf(f, "%c %s\n",
12014 GOT_HISTEDIT_MESG, hle->logmsg);
12015 if (n < 0) {
12016 err = got_ferror(f, GOT_ERR_IO);
12017 break;
12021 done:
12022 if (f && fclose(f) == EOF && err == NULL)
12023 err = got_error_from_errno("fclose");
12024 free(path);
12025 if (commit)
12026 got_object_commit_close(commit);
12027 return err;
12030 static void
12031 histedit_free_list(struct got_histedit_list *histedit_cmds)
12033 struct got_histedit_list_entry *hle;
12035 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12036 TAILQ_REMOVE(histedit_cmds, hle, entry);
12037 free(hle);
12041 static const struct got_error *
12042 histedit_load_list(struct got_histedit_list *histedit_cmds,
12043 const char *path, struct got_repository *repo)
12045 const struct got_error *err = NULL;
12046 FILE *f = NULL;
12048 f = fopen(path, "re");
12049 if (f == NULL) {
12050 err = got_error_from_errno2("fopen", path);
12051 goto done;
12054 err = histedit_parse_list(histedit_cmds, f, repo);
12055 done:
12056 if (f && fclose(f) == EOF && err == NULL)
12057 err = got_error_from_errno("fclose");
12058 return err;
12061 static const struct got_error *
12062 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12063 const struct got_error *edit_err, struct got_object_id_queue *commits,
12064 const char *path, const char *branch_name, struct got_repository *repo)
12066 const struct got_error *err = NULL, *prev_err = edit_err;
12067 int resp = ' ';
12069 while (resp != 'c' && resp != 'r' && resp != 'a') {
12070 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12071 "or (a)bort: ", getprogname(), prev_err->msg);
12072 resp = getchar();
12073 if (resp == '\n')
12074 resp = getchar();
12075 if (resp == 'c') {
12076 histedit_free_list(histedit_cmds);
12077 err = histedit_run_editor(histedit_cmds, path, commits,
12078 repo);
12079 if (err) {
12080 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12081 err->code != GOT_ERR_HISTEDIT_CMD)
12082 break;
12083 prev_err = err;
12084 resp = ' ';
12085 continue;
12087 break;
12088 } else if (resp == 'r') {
12089 histedit_free_list(histedit_cmds);
12090 err = histedit_edit_script(histedit_cmds,
12091 commits, branch_name, 0, 0, 0, 0, repo);
12092 if (err) {
12093 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12094 err->code != GOT_ERR_HISTEDIT_CMD)
12095 break;
12096 prev_err = err;
12097 resp = ' ';
12098 continue;
12100 break;
12101 } else if (resp == 'a') {
12102 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12103 break;
12104 } else
12105 printf("invalid response '%c'\n", resp);
12108 return err;
12111 static const struct got_error *
12112 histedit_complete(struct got_worktree *worktree,
12113 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12114 struct got_reference *branch, struct got_repository *repo)
12116 printf("Switching work tree to %s\n",
12117 got_ref_get_symref_target(branch));
12118 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12119 branch, repo);
12122 static const struct got_error *
12123 show_histedit_progress(struct got_commit_object *commit,
12124 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12126 const struct got_error *err;
12127 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12129 err = got_object_id_str(&old_id_str, hle->commit_id);
12130 if (err)
12131 goto done;
12133 if (new_id) {
12134 err = got_object_id_str(&new_id_str, new_id);
12135 if (err)
12136 goto done;
12139 old_id_str[12] = '\0';
12140 if (new_id_str)
12141 new_id_str[12] = '\0';
12143 if (hle->logmsg) {
12144 logmsg = strdup(hle->logmsg);
12145 if (logmsg == NULL) {
12146 err = got_error_from_errno("strdup");
12147 goto done;
12149 trim_logmsg(logmsg, 42);
12150 } else {
12151 err = get_short_logmsg(&logmsg, 42, commit);
12152 if (err)
12153 goto done;
12156 switch (hle->cmd->code) {
12157 case GOT_HISTEDIT_PICK:
12158 case GOT_HISTEDIT_EDIT:
12159 printf("%s -> %s: %s\n", old_id_str,
12160 new_id_str ? new_id_str : "no-op change", logmsg);
12161 break;
12162 case GOT_HISTEDIT_DROP:
12163 case GOT_HISTEDIT_FOLD:
12164 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12165 logmsg);
12166 break;
12167 default:
12168 break;
12170 done:
12171 free(old_id_str);
12172 free(new_id_str);
12173 return err;
12176 static const struct got_error *
12177 histedit_commit(struct got_pathlist_head *merged_paths,
12178 struct got_worktree *worktree, struct got_fileindex *fileindex,
12179 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12180 const char *committer, int allow_conflict, struct got_repository *repo)
12182 const struct got_error *err;
12183 struct got_commit_object *commit;
12184 struct got_object_id *new_commit_id;
12186 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12187 && hle->logmsg == NULL) {
12188 err = histedit_edit_logmsg(hle, repo);
12189 if (err)
12190 return err;
12193 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12194 if (err)
12195 return err;
12197 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12198 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12199 hle->logmsg, allow_conflict, repo);
12200 if (err) {
12201 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12202 goto done;
12203 err = show_histedit_progress(commit, hle, NULL);
12204 } else {
12205 err = show_histedit_progress(commit, hle, new_commit_id);
12206 free(new_commit_id);
12208 done:
12209 got_object_commit_close(commit);
12210 return err;
12213 static const struct got_error *
12214 histedit_skip_commit(struct got_histedit_list_entry *hle,
12215 struct got_worktree *worktree, struct got_repository *repo)
12217 const struct got_error *error;
12218 struct got_commit_object *commit;
12220 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12221 repo);
12222 if (error)
12223 return error;
12225 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12226 if (error)
12227 return error;
12229 error = show_histedit_progress(commit, hle, NULL);
12230 got_object_commit_close(commit);
12231 return error;
12234 static const struct got_error *
12235 check_local_changes(void *arg, unsigned char status,
12236 unsigned char staged_status, const char *path,
12237 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12238 struct got_object_id *commit_id, int dirfd, const char *de_name)
12240 int *have_local_changes = arg;
12242 switch (status) {
12243 case GOT_STATUS_ADD:
12244 case GOT_STATUS_DELETE:
12245 case GOT_STATUS_MODIFY:
12246 case GOT_STATUS_CONFLICT:
12247 *have_local_changes = 1;
12248 return got_error(GOT_ERR_CANCELLED);
12249 default:
12250 break;
12253 switch (staged_status) {
12254 case GOT_STATUS_ADD:
12255 case GOT_STATUS_DELETE:
12256 case GOT_STATUS_MODIFY:
12257 *have_local_changes = 1;
12258 return got_error(GOT_ERR_CANCELLED);
12259 default:
12260 break;
12263 return NULL;
12266 static const struct got_error *
12267 cmd_histedit(int argc, char *argv[])
12269 const struct got_error *error = NULL;
12270 struct got_worktree *worktree = NULL;
12271 struct got_fileindex *fileindex = NULL;
12272 struct got_repository *repo = NULL;
12273 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12274 struct got_reference *branch = NULL;
12275 struct got_reference *tmp_branch = NULL;
12276 struct got_object_id *resume_commit_id = NULL;
12277 struct got_object_id *base_commit_id = NULL;
12278 struct got_object_id *head_commit_id = NULL;
12279 struct got_commit_object *commit = NULL;
12280 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12281 struct got_update_progress_arg upa;
12282 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12283 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12284 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12285 const char *edit_script_path = NULL;
12286 struct got_object_id_queue commits;
12287 struct got_pathlist_head merged_paths;
12288 const struct got_object_id_queue *parent_ids;
12289 struct got_object_qid *pid;
12290 struct got_histedit_list histedit_cmds;
12291 struct got_histedit_list_entry *hle;
12292 int *pack_fds = NULL;
12294 STAILQ_INIT(&commits);
12295 TAILQ_INIT(&histedit_cmds);
12296 TAILQ_INIT(&merged_paths);
12297 memset(&upa, 0, sizeof(upa));
12299 #ifndef PROFILE
12300 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12301 "unveil", NULL) == -1)
12302 err(1, "pledge");
12303 #endif
12305 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12306 switch (ch) {
12307 case 'a':
12308 abort_edit = 1;
12309 break;
12310 case 'C':
12311 allow_conflict = 1;
12312 break;
12313 case 'c':
12314 continue_edit = 1;
12315 break;
12316 case 'd':
12317 drop_only = 1;
12318 break;
12319 case 'e':
12320 edit_only = 1;
12321 break;
12322 case 'F':
12323 edit_script_path = optarg;
12324 break;
12325 case 'f':
12326 fold_only = 1;
12327 break;
12328 case 'l':
12329 list_backups = 1;
12330 break;
12331 case 'm':
12332 edit_logmsg_only = 1;
12333 break;
12334 case 'X':
12335 delete_backups = 1;
12336 break;
12337 default:
12338 usage_histedit();
12339 /* NOTREACHED */
12343 argc -= optind;
12344 argv += optind;
12346 if (abort_edit && allow_conflict)
12347 option_conflict('a', 'C');
12348 if (abort_edit && continue_edit)
12349 option_conflict('a', 'c');
12350 if (edit_script_path && allow_conflict)
12351 option_conflict('F', 'C');
12352 if (edit_script_path && edit_logmsg_only)
12353 option_conflict('F', 'm');
12354 if (abort_edit && edit_logmsg_only)
12355 option_conflict('a', 'm');
12356 if (edit_logmsg_only && allow_conflict)
12357 option_conflict('m', 'C');
12358 if (continue_edit && edit_logmsg_only)
12359 option_conflict('c', 'm');
12360 if (abort_edit && fold_only)
12361 option_conflict('a', 'f');
12362 if (fold_only && allow_conflict)
12363 option_conflict('f', 'C');
12364 if (continue_edit && fold_only)
12365 option_conflict('c', 'f');
12366 if (fold_only && edit_logmsg_only)
12367 option_conflict('f', 'm');
12368 if (edit_script_path && fold_only)
12369 option_conflict('F', 'f');
12370 if (abort_edit && edit_only)
12371 option_conflict('a', 'e');
12372 if (continue_edit && edit_only)
12373 option_conflict('c', 'e');
12374 if (edit_only && edit_logmsg_only)
12375 option_conflict('e', 'm');
12376 if (edit_script_path && edit_only)
12377 option_conflict('F', 'e');
12378 if (fold_only && edit_only)
12379 option_conflict('f', 'e');
12380 if (drop_only && abort_edit)
12381 option_conflict('d', 'a');
12382 if (drop_only && allow_conflict)
12383 option_conflict('d', 'C');
12384 if (drop_only && continue_edit)
12385 option_conflict('d', 'c');
12386 if (drop_only && edit_logmsg_only)
12387 option_conflict('d', 'm');
12388 if (drop_only && edit_only)
12389 option_conflict('d', 'e');
12390 if (drop_only && edit_script_path)
12391 option_conflict('d', 'F');
12392 if (drop_only && fold_only)
12393 option_conflict('d', 'f');
12394 if (list_backups) {
12395 if (abort_edit)
12396 option_conflict('l', 'a');
12397 if (allow_conflict)
12398 option_conflict('l', 'C');
12399 if (continue_edit)
12400 option_conflict('l', 'c');
12401 if (edit_script_path)
12402 option_conflict('l', 'F');
12403 if (edit_logmsg_only)
12404 option_conflict('l', 'm');
12405 if (drop_only)
12406 option_conflict('l', 'd');
12407 if (fold_only)
12408 option_conflict('l', 'f');
12409 if (edit_only)
12410 option_conflict('l', 'e');
12411 if (delete_backups)
12412 option_conflict('l', 'X');
12413 if (argc != 0 && argc != 1)
12414 usage_histedit();
12415 } else if (delete_backups) {
12416 if (abort_edit)
12417 option_conflict('X', 'a');
12418 if (allow_conflict)
12419 option_conflict('X', 'C');
12420 if (continue_edit)
12421 option_conflict('X', 'c');
12422 if (drop_only)
12423 option_conflict('X', 'd');
12424 if (edit_script_path)
12425 option_conflict('X', 'F');
12426 if (edit_logmsg_only)
12427 option_conflict('X', 'm');
12428 if (fold_only)
12429 option_conflict('X', 'f');
12430 if (edit_only)
12431 option_conflict('X', 'e');
12432 if (list_backups)
12433 option_conflict('X', 'l');
12434 if (argc != 0 && argc != 1)
12435 usage_histedit();
12436 } else if (allow_conflict && !continue_edit)
12437 errx(1, "-C option requires -c");
12438 else if (argc != 0)
12439 usage_histedit();
12442 * This command cannot apply unveil(2) in all cases because the
12443 * user may choose to run an editor to edit the histedit script
12444 * and to edit individual commit log messages.
12445 * unveil(2) traverses exec(2); if an editor is used we have to
12446 * apply unveil after edit script and log messages have been written.
12447 * XXX TODO: Make use of unveil(2) where possible.
12450 cwd = getcwd(NULL, 0);
12451 if (cwd == NULL) {
12452 error = got_error_from_errno("getcwd");
12453 goto done;
12456 error = got_repo_pack_fds_open(&pack_fds);
12457 if (error != NULL)
12458 goto done;
12460 error = got_worktree_open(&worktree, cwd);
12461 if (error) {
12462 if (list_backups || delete_backups) {
12463 if (error->code != GOT_ERR_NOT_WORKTREE)
12464 goto done;
12465 } else {
12466 if (error->code == GOT_ERR_NOT_WORKTREE)
12467 error = wrap_not_worktree_error(error,
12468 "histedit", cwd);
12469 goto done;
12473 if (list_backups || delete_backups) {
12474 error = got_repo_open(&repo,
12475 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12476 NULL, pack_fds);
12477 if (error != NULL)
12478 goto done;
12479 error = apply_unveil(got_repo_get_path(repo), 0,
12480 worktree ? got_worktree_get_root_path(worktree) : NULL);
12481 if (error)
12482 goto done;
12483 error = process_backup_refs(
12484 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12485 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12486 goto done; /* nothing else to do */
12489 error = get_gitconfig_path(&gitconfig_path);
12490 if (error)
12491 goto done;
12492 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12493 gitconfig_path, pack_fds);
12494 if (error != NULL)
12495 goto done;
12497 if (worktree != NULL && !list_backups && !delete_backups) {
12498 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12499 if (error)
12500 goto done;
12503 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12504 if (error)
12505 goto done;
12506 if (rebase_in_progress) {
12507 error = got_error(GOT_ERR_REBASING);
12508 goto done;
12511 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12512 repo);
12513 if (error)
12514 goto done;
12515 if (merge_in_progress) {
12516 error = got_error(GOT_ERR_MERGE_BUSY);
12517 goto done;
12520 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12521 if (error)
12522 goto done;
12524 if (edit_in_progress && edit_logmsg_only) {
12525 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12526 "histedit operation is in progress in this "
12527 "work tree and must be continued or aborted "
12528 "before the -m option can be used");
12529 goto done;
12531 if (edit_in_progress && drop_only) {
12532 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12533 "histedit operation is in progress in this "
12534 "work tree and must be continued or aborted "
12535 "before the -d option can be used");
12536 goto done;
12538 if (edit_in_progress && fold_only) {
12539 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12540 "histedit operation is in progress in this "
12541 "work tree and must be continued or aborted "
12542 "before the -f option can be used");
12543 goto done;
12545 if (edit_in_progress && edit_only) {
12546 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12547 "histedit operation is in progress in this "
12548 "work tree and must be continued or aborted "
12549 "before the -e option can be used");
12550 goto done;
12553 if (edit_in_progress && abort_edit) {
12554 error = got_worktree_histedit_continue(&resume_commit_id,
12555 &tmp_branch, &branch, &base_commit_id, &fileindex,
12556 worktree, repo);
12557 if (error)
12558 goto done;
12559 printf("Switching work tree to %s\n",
12560 got_ref_get_symref_target(branch));
12561 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12562 branch, base_commit_id, abort_progress, &upa);
12563 if (error)
12564 goto done;
12565 printf("Histedit of %s aborted\n",
12566 got_ref_get_symref_target(branch));
12567 print_merge_progress_stats(&upa);
12568 goto done; /* nothing else to do */
12569 } else if (abort_edit) {
12570 error = got_error(GOT_ERR_NOT_HISTEDIT);
12571 goto done;
12574 error = get_author(&committer, repo, worktree);
12575 if (error)
12576 goto done;
12578 if (continue_edit) {
12579 char *path;
12581 if (!edit_in_progress) {
12582 error = got_error(GOT_ERR_NOT_HISTEDIT);
12583 goto done;
12586 error = got_worktree_get_histedit_script_path(&path, worktree);
12587 if (error)
12588 goto done;
12590 error = histedit_load_list(&histedit_cmds, path, repo);
12591 free(path);
12592 if (error)
12593 goto done;
12595 error = got_worktree_histedit_continue(&resume_commit_id,
12596 &tmp_branch, &branch, &base_commit_id, &fileindex,
12597 worktree, repo);
12598 if (error)
12599 goto done;
12601 error = got_ref_resolve(&head_commit_id, repo, branch);
12602 if (error)
12603 goto done;
12605 error = got_object_open_as_commit(&commit, repo,
12606 head_commit_id);
12607 if (error)
12608 goto done;
12609 parent_ids = got_object_commit_get_parent_ids(commit);
12610 pid = STAILQ_FIRST(parent_ids);
12611 if (pid == NULL) {
12612 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12613 goto done;
12615 error = collect_commits(&commits, head_commit_id, &pid->id,
12616 base_commit_id, got_worktree_get_path_prefix(worktree),
12617 GOT_ERR_HISTEDIT_PATH, repo);
12618 got_object_commit_close(commit);
12619 commit = NULL;
12620 if (error)
12621 goto done;
12622 } else {
12623 if (edit_in_progress) {
12624 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12625 goto done;
12628 error = got_ref_open(&branch, repo,
12629 got_worktree_get_head_ref_name(worktree), 0);
12630 if (error != NULL)
12631 goto done;
12633 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12634 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12635 "will not edit commit history of a branch outside "
12636 "the \"refs/heads/\" reference namespace");
12637 goto done;
12640 error = got_ref_resolve(&head_commit_id, repo, branch);
12641 got_ref_close(branch);
12642 branch = NULL;
12643 if (error)
12644 goto done;
12646 error = got_object_open_as_commit(&commit, repo,
12647 head_commit_id);
12648 if (error)
12649 goto done;
12650 parent_ids = got_object_commit_get_parent_ids(commit);
12651 pid = STAILQ_FIRST(parent_ids);
12652 if (pid == NULL) {
12653 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12654 goto done;
12656 error = collect_commits(&commits, head_commit_id, &pid->id,
12657 got_worktree_get_base_commit_id(worktree),
12658 got_worktree_get_path_prefix(worktree),
12659 GOT_ERR_HISTEDIT_PATH, repo);
12660 got_object_commit_close(commit);
12661 commit = NULL;
12662 if (error)
12663 goto done;
12665 if (STAILQ_EMPTY(&commits)) {
12666 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12667 goto done;
12670 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12671 &base_commit_id, &fileindex, worktree, repo);
12672 if (error)
12673 goto done;
12675 if (edit_script_path) {
12676 error = histedit_load_list(&histedit_cmds,
12677 edit_script_path, repo);
12678 if (error) {
12679 got_worktree_histedit_abort(worktree, fileindex,
12680 repo, branch, base_commit_id,
12681 abort_progress, &upa);
12682 print_merge_progress_stats(&upa);
12683 goto done;
12685 } else {
12686 const char *branch_name;
12687 branch_name = got_ref_get_symref_target(branch);
12688 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12689 branch_name += 11;
12690 error = histedit_edit_script(&histedit_cmds, &commits,
12691 branch_name, edit_logmsg_only, fold_only,
12692 drop_only, edit_only, repo);
12693 if (error) {
12694 got_worktree_histedit_abort(worktree, fileindex,
12695 repo, branch, base_commit_id,
12696 abort_progress, &upa);
12697 print_merge_progress_stats(&upa);
12698 goto done;
12703 error = histedit_save_list(&histedit_cmds, worktree,
12704 repo);
12705 if (error) {
12706 got_worktree_histedit_abort(worktree, fileindex,
12707 repo, branch, base_commit_id,
12708 abort_progress, &upa);
12709 print_merge_progress_stats(&upa);
12710 goto done;
12715 error = histedit_check_script(&histedit_cmds, &commits, repo);
12716 if (error)
12717 goto done;
12719 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12720 if (resume_commit_id) {
12721 if (got_object_id_cmp(hle->commit_id,
12722 resume_commit_id) != 0)
12723 continue;
12725 resume_commit_id = NULL;
12726 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12727 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12728 error = histedit_skip_commit(hle, worktree,
12729 repo);
12730 if (error)
12731 goto done;
12732 } else {
12733 struct got_pathlist_head paths;
12734 int have_changes = 0;
12736 TAILQ_INIT(&paths);
12737 error = got_pathlist_append(&paths, "", NULL);
12738 if (error)
12739 goto done;
12740 error = got_worktree_status(worktree, &paths,
12741 repo, 0, check_local_changes, &have_changes,
12742 check_cancelled, NULL);
12743 got_pathlist_free(&paths,
12744 GOT_PATHLIST_FREE_NONE);
12745 if (error) {
12746 if (error->code != GOT_ERR_CANCELLED)
12747 goto done;
12748 if (sigint_received || sigpipe_received)
12749 goto done;
12751 if (have_changes) {
12752 error = histedit_commit(NULL, worktree,
12753 fileindex, tmp_branch, hle,
12754 committer, allow_conflict, repo);
12755 if (error)
12756 goto done;
12757 } else {
12758 error = got_object_open_as_commit(
12759 &commit, repo, hle->commit_id);
12760 if (error)
12761 goto done;
12762 error = show_histedit_progress(commit,
12763 hle, NULL);
12764 got_object_commit_close(commit);
12765 commit = NULL;
12766 if (error)
12767 goto done;
12770 continue;
12773 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12774 error = histedit_skip_commit(hle, worktree, repo);
12775 if (error)
12776 goto done;
12777 continue;
12780 error = got_object_open_as_commit(&commit, repo,
12781 hle->commit_id);
12782 if (error)
12783 goto done;
12784 parent_ids = got_object_commit_get_parent_ids(commit);
12785 pid = STAILQ_FIRST(parent_ids);
12787 error = got_worktree_histedit_merge_files(&merged_paths,
12788 worktree, fileindex, &pid->id, hle->commit_id, repo,
12789 update_progress, &upa, check_cancelled, NULL);
12790 if (error)
12791 goto done;
12792 got_object_commit_close(commit);
12793 commit = NULL;
12795 print_merge_progress_stats(&upa);
12796 if (upa.conflicts > 0 || upa.missing > 0 ||
12797 upa.not_deleted > 0 || upa.unversioned > 0) {
12798 if (upa.conflicts > 0) {
12799 error = show_rebase_merge_conflict(
12800 hle->commit_id, repo);
12801 if (error)
12802 goto done;
12804 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12805 break;
12808 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12809 char *id_str;
12810 error = got_object_id_str(&id_str, hle->commit_id);
12811 if (error)
12812 goto done;
12813 printf("Stopping histedit for amending commit %s\n",
12814 id_str);
12815 free(id_str);
12816 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12817 error = got_worktree_histedit_postpone(worktree,
12818 fileindex);
12819 goto done;
12822 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12823 error = histedit_skip_commit(hle, worktree, repo);
12824 if (error)
12825 goto done;
12826 continue;
12829 error = histedit_commit(&merged_paths, worktree, fileindex,
12830 tmp_branch, hle, committer, allow_conflict, repo);
12831 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12832 if (error)
12833 goto done;
12836 if (upa.conflicts > 0 || upa.missing > 0 ||
12837 upa.not_deleted > 0 || upa.unversioned > 0) {
12838 error = got_worktree_histedit_postpone(worktree, fileindex);
12839 if (error)
12840 goto done;
12841 if (upa.conflicts > 0 && upa.missing == 0 &&
12842 upa.not_deleted == 0 && upa.unversioned == 0) {
12843 error = got_error_msg(GOT_ERR_CONFLICTS,
12844 "conflicts must be resolved before histedit "
12845 "can continue");
12846 } else if (upa.conflicts > 0) {
12847 error = got_error_msg(GOT_ERR_CONFLICTS,
12848 "conflicts must be resolved before histedit "
12849 "can continue; changes destined for some "
12850 "files were not yet merged and should be "
12851 "merged manually if required before the "
12852 "histedit operation is continued");
12853 } else {
12854 error = got_error_msg(GOT_ERR_CONFLICTS,
12855 "changes destined for some files were not "
12856 "yet merged and should be merged manually "
12857 "if required before the histedit operation "
12858 "is continued");
12860 } else
12861 error = histedit_complete(worktree, fileindex, tmp_branch,
12862 branch, repo);
12863 done:
12864 free(cwd);
12865 free(committer);
12866 free(gitconfig_path);
12867 got_object_id_queue_free(&commits);
12868 histedit_free_list(&histedit_cmds);
12869 free(head_commit_id);
12870 free(base_commit_id);
12871 free(resume_commit_id);
12872 if (commit)
12873 got_object_commit_close(commit);
12874 if (branch)
12875 got_ref_close(branch);
12876 if (tmp_branch)
12877 got_ref_close(tmp_branch);
12878 if (worktree)
12879 got_worktree_close(worktree);
12880 if (repo) {
12881 const struct got_error *close_err = got_repo_close(repo);
12882 if (error == NULL)
12883 error = close_err;
12885 if (pack_fds) {
12886 const struct got_error *pack_err =
12887 got_repo_pack_fds_close(pack_fds);
12888 if (error == NULL)
12889 error = pack_err;
12891 return error;
12894 __dead static void
12895 usage_integrate(void)
12897 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12898 exit(1);
12901 static const struct got_error *
12902 cmd_integrate(int argc, char *argv[])
12904 const struct got_error *error = NULL;
12905 struct got_repository *repo = NULL;
12906 struct got_worktree *worktree = NULL;
12907 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12908 const char *branch_arg = NULL;
12909 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12910 struct got_fileindex *fileindex = NULL;
12911 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12912 int ch;
12913 struct got_update_progress_arg upa;
12914 int *pack_fds = NULL;
12916 #ifndef PROFILE
12917 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12918 "unveil", NULL) == -1)
12919 err(1, "pledge");
12920 #endif
12922 while ((ch = getopt(argc, argv, "")) != -1) {
12923 switch (ch) {
12924 default:
12925 usage_integrate();
12926 /* NOTREACHED */
12930 argc -= optind;
12931 argv += optind;
12933 if (argc != 1)
12934 usage_integrate();
12935 branch_arg = argv[0];
12937 cwd = getcwd(NULL, 0);
12938 if (cwd == NULL) {
12939 error = got_error_from_errno("getcwd");
12940 goto done;
12943 error = got_repo_pack_fds_open(&pack_fds);
12944 if (error != NULL)
12945 goto done;
12947 error = got_worktree_open(&worktree, cwd);
12948 if (error) {
12949 if (error->code == GOT_ERR_NOT_WORKTREE)
12950 error = wrap_not_worktree_error(error, "integrate",
12951 cwd);
12952 goto done;
12955 error = check_rebase_or_histedit_in_progress(worktree);
12956 if (error)
12957 goto done;
12959 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12960 NULL, pack_fds);
12961 if (error != NULL)
12962 goto done;
12964 error = apply_unveil(got_repo_get_path(repo), 0,
12965 got_worktree_get_root_path(worktree));
12966 if (error)
12967 goto done;
12969 error = check_merge_in_progress(worktree, repo);
12970 if (error)
12971 goto done;
12973 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12974 error = got_error_from_errno("asprintf");
12975 goto done;
12978 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12979 &base_branch_ref, worktree, refname, repo);
12980 if (error)
12981 goto done;
12983 refname = strdup(got_ref_get_name(branch_ref));
12984 if (refname == NULL) {
12985 error = got_error_from_errno("strdup");
12986 got_worktree_integrate_abort(worktree, fileindex, repo,
12987 branch_ref, base_branch_ref);
12988 goto done;
12990 base_refname = strdup(got_ref_get_name(base_branch_ref));
12991 if (base_refname == NULL) {
12992 error = got_error_from_errno("strdup");
12993 got_worktree_integrate_abort(worktree, fileindex, repo,
12994 branch_ref, base_branch_ref);
12995 goto done;
12997 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12998 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12999 got_worktree_integrate_abort(worktree, fileindex, repo,
13000 branch_ref, base_branch_ref);
13001 goto done;
13004 error = got_ref_resolve(&commit_id, repo, branch_ref);
13005 if (error)
13006 goto done;
13008 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13009 if (error)
13010 goto done;
13012 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13013 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13014 "specified branch has already been integrated");
13015 got_worktree_integrate_abort(worktree, fileindex, repo,
13016 branch_ref, base_branch_ref);
13017 goto done;
13020 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13021 if (error) {
13022 if (error->code == GOT_ERR_ANCESTRY)
13023 error = got_error(GOT_ERR_REBASE_REQUIRED);
13024 got_worktree_integrate_abort(worktree, fileindex, repo,
13025 branch_ref, base_branch_ref);
13026 goto done;
13029 memset(&upa, 0, sizeof(upa));
13030 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13031 branch_ref, base_branch_ref, update_progress, &upa,
13032 check_cancelled, NULL);
13033 if (error)
13034 goto done;
13036 printf("Integrated %s into %s\n", refname, base_refname);
13037 print_update_progress_stats(&upa);
13038 done:
13039 if (repo) {
13040 const struct got_error *close_err = got_repo_close(repo);
13041 if (error == NULL)
13042 error = close_err;
13044 if (worktree)
13045 got_worktree_close(worktree);
13046 if (pack_fds) {
13047 const struct got_error *pack_err =
13048 got_repo_pack_fds_close(pack_fds);
13049 if (error == NULL)
13050 error = pack_err;
13052 free(cwd);
13053 free(base_commit_id);
13054 free(commit_id);
13055 free(refname);
13056 free(base_refname);
13057 return error;
13060 __dead static void
13061 usage_merge(void)
13063 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13064 exit(1);
13067 static const struct got_error *
13068 cmd_merge(int argc, char *argv[])
13070 const struct got_error *error = NULL;
13071 struct got_worktree *worktree = NULL;
13072 struct got_repository *repo = NULL;
13073 struct got_fileindex *fileindex = NULL;
13074 char *cwd = NULL, *id_str = NULL, *author = NULL;
13075 char *gitconfig_path = NULL;
13076 struct got_reference *branch = NULL, *wt_branch = NULL;
13077 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13078 struct got_object_id *wt_branch_tip = NULL;
13079 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13080 int allow_conflict = 0, interrupt_merge = 0;
13081 struct got_update_progress_arg upa;
13082 struct got_object_id *merge_commit_id = NULL;
13083 char *branch_name = NULL;
13084 int *pack_fds = NULL;
13086 memset(&upa, 0, sizeof(upa));
13088 #ifndef PROFILE
13089 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13090 "unveil", NULL) == -1)
13091 err(1, "pledge");
13092 #endif
13094 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13095 switch (ch) {
13096 case 'a':
13097 abort_merge = 1;
13098 break;
13099 case 'C':
13100 allow_conflict = 1;
13101 case 'c':
13102 continue_merge = 1;
13103 break;
13104 case 'n':
13105 interrupt_merge = 1;
13106 break;
13107 default:
13108 usage_merge();
13109 /* NOTREACHED */
13113 argc -= optind;
13114 argv += optind;
13116 if (allow_conflict) {
13117 if (abort_merge)
13118 option_conflict('a', 'C');
13119 if (!continue_merge)
13120 errx(1, "-C option requires -c");
13122 if (abort_merge && continue_merge)
13123 option_conflict('a', 'c');
13124 if (abort_merge || continue_merge) {
13125 if (argc != 0)
13126 usage_merge();
13127 } else if (argc != 1)
13128 usage_merge();
13130 cwd = getcwd(NULL, 0);
13131 if (cwd == NULL) {
13132 error = got_error_from_errno("getcwd");
13133 goto done;
13136 error = got_repo_pack_fds_open(&pack_fds);
13137 if (error != NULL)
13138 goto done;
13140 error = got_worktree_open(&worktree, cwd);
13141 if (error) {
13142 if (error->code == GOT_ERR_NOT_WORKTREE)
13143 error = wrap_not_worktree_error(error,
13144 "merge", cwd);
13145 goto done;
13148 error = get_gitconfig_path(&gitconfig_path);
13149 if (error)
13150 goto done;
13151 error = got_repo_open(&repo,
13152 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13153 gitconfig_path, pack_fds);
13154 if (error != NULL)
13155 goto done;
13157 if (worktree != NULL) {
13158 error = worktree_has_logmsg_ref("merge", worktree, repo);
13159 if (error)
13160 goto done;
13163 error = apply_unveil(got_repo_get_path(repo), 0,
13164 worktree ? got_worktree_get_root_path(worktree) : NULL);
13165 if (error)
13166 goto done;
13168 error = check_rebase_or_histedit_in_progress(worktree);
13169 if (error)
13170 goto done;
13172 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13173 repo);
13174 if (error)
13175 goto done;
13177 if (abort_merge) {
13178 if (!merge_in_progress) {
13179 error = got_error(GOT_ERR_NOT_MERGING);
13180 goto done;
13182 error = got_worktree_merge_continue(&branch_name,
13183 &branch_tip, &fileindex, worktree, repo);
13184 if (error)
13185 goto done;
13186 error = got_worktree_merge_abort(worktree, fileindex, repo,
13187 abort_progress, &upa);
13188 if (error)
13189 goto done;
13190 printf("Merge of %s aborted\n", branch_name);
13191 goto done; /* nothing else to do */
13194 error = get_author(&author, repo, worktree);
13195 if (error)
13196 goto done;
13198 if (continue_merge) {
13199 if (!merge_in_progress) {
13200 error = got_error(GOT_ERR_NOT_MERGING);
13201 goto done;
13203 error = got_worktree_merge_continue(&branch_name,
13204 &branch_tip, &fileindex, worktree, repo);
13205 if (error)
13206 goto done;
13207 } else {
13208 error = got_ref_open(&branch, repo, argv[0], 0);
13209 if (error != NULL)
13210 goto done;
13211 branch_name = strdup(got_ref_get_name(branch));
13212 if (branch_name == NULL) {
13213 error = got_error_from_errno("strdup");
13214 goto done;
13216 error = got_ref_resolve(&branch_tip, repo, branch);
13217 if (error)
13218 goto done;
13221 error = got_ref_open(&wt_branch, repo,
13222 got_worktree_get_head_ref_name(worktree), 0);
13223 if (error)
13224 goto done;
13225 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13226 if (error)
13227 goto done;
13228 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13229 wt_branch_tip, branch_tip, 0, repo,
13230 check_cancelled, NULL);
13231 if (error && error->code != GOT_ERR_ANCESTRY)
13232 goto done;
13234 if (!continue_merge) {
13235 error = check_path_prefix(wt_branch_tip, branch_tip,
13236 got_worktree_get_path_prefix(worktree),
13237 GOT_ERR_MERGE_PATH, repo);
13238 if (error)
13239 goto done;
13240 if (yca_id) {
13241 error = check_same_branch(wt_branch_tip, branch,
13242 yca_id, repo);
13243 if (error) {
13244 if (error->code != GOT_ERR_ANCESTRY)
13245 goto done;
13246 error = NULL;
13247 } else {
13248 static char msg[512];
13249 snprintf(msg, sizeof(msg),
13250 "cannot create a merge commit because "
13251 "%s is based on %s; %s can be integrated "
13252 "with 'got integrate' instead", branch_name,
13253 got_worktree_get_head_ref_name(worktree),
13254 branch_name);
13255 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13256 goto done;
13259 error = got_worktree_merge_prepare(&fileindex, worktree,
13260 branch, repo);
13261 if (error)
13262 goto done;
13264 error = got_worktree_merge_branch(worktree, fileindex,
13265 yca_id, branch_tip, repo, update_progress, &upa,
13266 check_cancelled, NULL);
13267 if (error)
13268 goto done;
13269 print_merge_progress_stats(&upa);
13270 if (!upa.did_something) {
13271 error = got_worktree_merge_abort(worktree, fileindex,
13272 repo, abort_progress, &upa);
13273 if (error)
13274 goto done;
13275 printf("Already up-to-date\n");
13276 goto done;
13280 if (interrupt_merge) {
13281 error = got_worktree_merge_postpone(worktree, fileindex);
13282 if (error)
13283 goto done;
13284 printf("Merge of %s interrupted on request\n", branch_name);
13285 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13286 upa.not_deleted > 0 || upa.unversioned > 0) {
13287 error = got_worktree_merge_postpone(worktree, fileindex);
13288 if (error)
13289 goto done;
13290 if (upa.conflicts > 0 && upa.missing == 0 &&
13291 upa.not_deleted == 0 && upa.unversioned == 0) {
13292 error = got_error_msg(GOT_ERR_CONFLICTS,
13293 "conflicts must be resolved before merging "
13294 "can continue");
13295 } else if (upa.conflicts > 0) {
13296 error = got_error_msg(GOT_ERR_CONFLICTS,
13297 "conflicts must be resolved before merging "
13298 "can continue; changes destined for some "
13299 "files were not yet merged and "
13300 "should be merged manually if required before the "
13301 "merge operation is continued");
13302 } else {
13303 error = got_error_msg(GOT_ERR_CONFLICTS,
13304 "changes destined for some "
13305 "files were not yet merged and should be "
13306 "merged manually if required before the "
13307 "merge operation is continued");
13309 goto done;
13310 } else {
13311 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13312 fileindex, author, NULL, 1, branch_tip, branch_name,
13313 allow_conflict, repo, continue_merge ? print_status : NULL,
13314 NULL);
13315 if (error)
13316 goto done;
13317 error = got_worktree_merge_complete(worktree, fileindex, repo);
13318 if (error)
13319 goto done;
13320 error = got_object_id_str(&id_str, merge_commit_id);
13321 if (error)
13322 goto done;
13323 printf("Merged %s into %s: %s\n", branch_name,
13324 got_worktree_get_head_ref_name(worktree),
13325 id_str);
13328 done:
13329 free(gitconfig_path);
13330 free(id_str);
13331 free(merge_commit_id);
13332 free(author);
13333 free(branch_tip);
13334 free(branch_name);
13335 free(yca_id);
13336 if (branch)
13337 got_ref_close(branch);
13338 if (wt_branch)
13339 got_ref_close(wt_branch);
13340 if (worktree)
13341 got_worktree_close(worktree);
13342 if (repo) {
13343 const struct got_error *close_err = got_repo_close(repo);
13344 if (error == NULL)
13345 error = close_err;
13347 if (pack_fds) {
13348 const struct got_error *pack_err =
13349 got_repo_pack_fds_close(pack_fds);
13350 if (error == NULL)
13351 error = pack_err;
13353 return error;
13356 __dead static void
13357 usage_stage(void)
13359 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13360 "[path ...]\n", getprogname());
13361 exit(1);
13364 static const struct got_error *
13365 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13366 const char *path, struct got_object_id *blob_id,
13367 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13368 int dirfd, const char *de_name)
13370 const struct got_error *err = NULL;
13371 char *id_str = NULL;
13373 if (staged_status != GOT_STATUS_ADD &&
13374 staged_status != GOT_STATUS_MODIFY &&
13375 staged_status != GOT_STATUS_DELETE)
13376 return NULL;
13378 if (staged_status == GOT_STATUS_ADD ||
13379 staged_status == GOT_STATUS_MODIFY)
13380 err = got_object_id_str(&id_str, staged_blob_id);
13381 else
13382 err = got_object_id_str(&id_str, blob_id);
13383 if (err)
13384 return err;
13386 printf("%s %c %s\n", id_str, staged_status, path);
13387 free(id_str);
13388 return NULL;
13391 static const struct got_error *
13392 cmd_stage(int argc, char *argv[])
13394 const struct got_error *error = NULL;
13395 struct got_repository *repo = NULL;
13396 struct got_worktree *worktree = NULL;
13397 char *cwd = NULL;
13398 struct got_pathlist_head paths;
13399 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13400 FILE *patch_script_file = NULL;
13401 const char *patch_script_path = NULL;
13402 struct choose_patch_arg cpa;
13403 int *pack_fds = NULL;
13405 TAILQ_INIT(&paths);
13407 #ifndef PROFILE
13408 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13409 "unveil", NULL) == -1)
13410 err(1, "pledge");
13411 #endif
13413 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13414 switch (ch) {
13415 case 'F':
13416 patch_script_path = optarg;
13417 break;
13418 case 'l':
13419 list_stage = 1;
13420 break;
13421 case 'p':
13422 pflag = 1;
13423 break;
13424 case 'S':
13425 allow_bad_symlinks = 1;
13426 break;
13427 default:
13428 usage_stage();
13429 /* NOTREACHED */
13433 argc -= optind;
13434 argv += optind;
13436 if (list_stage && (pflag || patch_script_path))
13437 errx(1, "-l option cannot be used with other options");
13438 if (patch_script_path && !pflag)
13439 errx(1, "-F option can only be used together with -p option");
13441 cwd = getcwd(NULL, 0);
13442 if (cwd == NULL) {
13443 error = got_error_from_errno("getcwd");
13444 goto done;
13447 error = got_repo_pack_fds_open(&pack_fds);
13448 if (error != NULL)
13449 goto done;
13451 error = got_worktree_open(&worktree, cwd);
13452 if (error) {
13453 if (error->code == GOT_ERR_NOT_WORKTREE)
13454 error = wrap_not_worktree_error(error, "stage", cwd);
13455 goto done;
13458 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13459 NULL, pack_fds);
13460 if (error != NULL)
13461 goto done;
13463 if (patch_script_path) {
13464 patch_script_file = fopen(patch_script_path, "re");
13465 if (patch_script_file == NULL) {
13466 error = got_error_from_errno2("fopen",
13467 patch_script_path);
13468 goto done;
13471 error = apply_unveil(got_repo_get_path(repo), 0,
13472 got_worktree_get_root_path(worktree));
13473 if (error)
13474 goto done;
13476 error = check_merge_in_progress(worktree, repo);
13477 if (error)
13478 goto done;
13480 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13481 if (error)
13482 goto done;
13484 if (list_stage)
13485 error = got_worktree_status(worktree, &paths, repo, 0,
13486 print_stage, NULL, check_cancelled, NULL);
13487 else {
13488 cpa.patch_script_file = patch_script_file;
13489 cpa.action = "stage";
13490 error = got_worktree_stage(worktree, &paths,
13491 pflag ? NULL : print_status, NULL,
13492 pflag ? choose_patch : NULL, &cpa,
13493 allow_bad_symlinks, repo);
13495 done:
13496 if (patch_script_file && fclose(patch_script_file) == EOF &&
13497 error == NULL)
13498 error = got_error_from_errno2("fclose", patch_script_path);
13499 if (repo) {
13500 const struct got_error *close_err = got_repo_close(repo);
13501 if (error == NULL)
13502 error = close_err;
13504 if (worktree)
13505 got_worktree_close(worktree);
13506 if (pack_fds) {
13507 const struct got_error *pack_err =
13508 got_repo_pack_fds_close(pack_fds);
13509 if (error == NULL)
13510 error = pack_err;
13512 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13513 free(cwd);
13514 return error;
13517 __dead static void
13518 usage_unstage(void)
13520 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13521 "[path ...]\n", getprogname());
13522 exit(1);
13526 static const struct got_error *
13527 cmd_unstage(int argc, char *argv[])
13529 const struct got_error *error = NULL;
13530 struct got_repository *repo = NULL;
13531 struct got_worktree *worktree = NULL;
13532 char *cwd = NULL;
13533 struct got_pathlist_head paths;
13534 int ch, pflag = 0;
13535 struct got_update_progress_arg upa;
13536 FILE *patch_script_file = NULL;
13537 const char *patch_script_path = NULL;
13538 struct choose_patch_arg cpa;
13539 int *pack_fds = NULL;
13541 TAILQ_INIT(&paths);
13543 #ifndef PROFILE
13544 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13545 "unveil", NULL) == -1)
13546 err(1, "pledge");
13547 #endif
13549 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13550 switch (ch) {
13551 case 'F':
13552 patch_script_path = optarg;
13553 break;
13554 case 'p':
13555 pflag = 1;
13556 break;
13557 default:
13558 usage_unstage();
13559 /* NOTREACHED */
13563 argc -= optind;
13564 argv += optind;
13566 if (patch_script_path && !pflag)
13567 errx(1, "-F option can only be used together with -p option");
13569 cwd = getcwd(NULL, 0);
13570 if (cwd == NULL) {
13571 error = got_error_from_errno("getcwd");
13572 goto done;
13575 error = got_repo_pack_fds_open(&pack_fds);
13576 if (error != NULL)
13577 goto done;
13579 error = got_worktree_open(&worktree, cwd);
13580 if (error) {
13581 if (error->code == GOT_ERR_NOT_WORKTREE)
13582 error = wrap_not_worktree_error(error, "unstage", cwd);
13583 goto done;
13586 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13587 NULL, pack_fds);
13588 if (error != NULL)
13589 goto done;
13591 if (patch_script_path) {
13592 patch_script_file = fopen(patch_script_path, "re");
13593 if (patch_script_file == NULL) {
13594 error = got_error_from_errno2("fopen",
13595 patch_script_path);
13596 goto done;
13600 error = apply_unveil(got_repo_get_path(repo), 0,
13601 got_worktree_get_root_path(worktree));
13602 if (error)
13603 goto done;
13605 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13606 if (error)
13607 goto done;
13609 cpa.patch_script_file = patch_script_file;
13610 cpa.action = "unstage";
13611 memset(&upa, 0, sizeof(upa));
13612 error = got_worktree_unstage(worktree, &paths, update_progress,
13613 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13614 if (!error)
13615 print_merge_progress_stats(&upa);
13616 done:
13617 if (patch_script_file && fclose(patch_script_file) == EOF &&
13618 error == NULL)
13619 error = got_error_from_errno2("fclose", patch_script_path);
13620 if (repo) {
13621 const struct got_error *close_err = got_repo_close(repo);
13622 if (error == NULL)
13623 error = close_err;
13625 if (worktree)
13626 got_worktree_close(worktree);
13627 if (pack_fds) {
13628 const struct got_error *pack_err =
13629 got_repo_pack_fds_close(pack_fds);
13630 if (error == NULL)
13631 error = pack_err;
13633 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13634 free(cwd);
13635 return error;
13638 __dead static void
13639 usage_cat(void)
13641 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13642 "arg ...\n", getprogname());
13643 exit(1);
13646 static const struct got_error *
13647 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13649 const struct got_error *err;
13650 struct got_blob_object *blob;
13651 int fd = -1;
13653 fd = got_opentempfd();
13654 if (fd == -1)
13655 return got_error_from_errno("got_opentempfd");
13657 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13658 if (err)
13659 goto done;
13661 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13662 done:
13663 if (fd != -1 && close(fd) == -1 && err == NULL)
13664 err = got_error_from_errno("close");
13665 if (blob)
13666 got_object_blob_close(blob);
13667 return err;
13670 static const struct got_error *
13671 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13673 const struct got_error *err;
13674 struct got_tree_object *tree;
13675 int nentries, i;
13677 err = got_object_open_as_tree(&tree, repo, id);
13678 if (err)
13679 return err;
13681 nentries = got_object_tree_get_nentries(tree);
13682 for (i = 0; i < nentries; i++) {
13683 struct got_tree_entry *te;
13684 char *id_str;
13685 if (sigint_received || sigpipe_received)
13686 break;
13687 te = got_object_tree_get_entry(tree, i);
13688 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13689 if (err)
13690 break;
13691 fprintf(outfile, "%s %.7o %s\n", id_str,
13692 got_tree_entry_get_mode(te),
13693 got_tree_entry_get_name(te));
13694 free(id_str);
13697 got_object_tree_close(tree);
13698 return err;
13701 static const struct got_error *
13702 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13704 const struct got_error *err;
13705 struct got_commit_object *commit;
13706 const struct got_object_id_queue *parent_ids;
13707 struct got_object_qid *pid;
13708 char *id_str = NULL;
13709 const char *logmsg = NULL;
13710 char gmtoff[6];
13712 err = got_object_open_as_commit(&commit, repo, id);
13713 if (err)
13714 return err;
13716 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13717 if (err)
13718 goto done;
13720 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13721 parent_ids = got_object_commit_get_parent_ids(commit);
13722 fprintf(outfile, "numparents %d\n",
13723 got_object_commit_get_nparents(commit));
13724 STAILQ_FOREACH(pid, parent_ids, entry) {
13725 char *pid_str;
13726 err = got_object_id_str(&pid_str, &pid->id);
13727 if (err)
13728 goto done;
13729 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13730 free(pid_str);
13732 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13733 got_object_commit_get_author_gmtoff(commit));
13734 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13735 got_object_commit_get_author(commit),
13736 (long long)got_object_commit_get_author_time(commit),
13737 gmtoff);
13739 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13740 got_object_commit_get_committer_gmtoff(commit));
13741 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13742 got_object_commit_get_committer(commit),
13743 (long long)got_object_commit_get_committer_time(commit),
13744 gmtoff);
13746 logmsg = got_object_commit_get_logmsg_raw(commit);
13747 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13748 fprintf(outfile, "%s", logmsg);
13749 done:
13750 free(id_str);
13751 got_object_commit_close(commit);
13752 return err;
13755 static const struct got_error *
13756 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13758 const struct got_error *err;
13759 struct got_tag_object *tag;
13760 char *id_str = NULL;
13761 const char *tagmsg = NULL;
13762 char gmtoff[6];
13764 err = got_object_open_as_tag(&tag, repo, id);
13765 if (err)
13766 return err;
13768 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13769 if (err)
13770 goto done;
13772 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13774 switch (got_object_tag_get_object_type(tag)) {
13775 case GOT_OBJ_TYPE_BLOB:
13776 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13777 GOT_OBJ_LABEL_BLOB);
13778 break;
13779 case GOT_OBJ_TYPE_TREE:
13780 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13781 GOT_OBJ_LABEL_TREE);
13782 break;
13783 case GOT_OBJ_TYPE_COMMIT:
13784 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13785 GOT_OBJ_LABEL_COMMIT);
13786 break;
13787 case GOT_OBJ_TYPE_TAG:
13788 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13789 GOT_OBJ_LABEL_TAG);
13790 break;
13791 default:
13792 break;
13795 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13796 got_object_tag_get_name(tag));
13798 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13799 got_object_tag_get_tagger_gmtoff(tag));
13800 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13801 got_object_tag_get_tagger(tag),
13802 (long long)got_object_tag_get_tagger_time(tag),
13803 gmtoff);
13805 tagmsg = got_object_tag_get_message(tag);
13806 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13807 fprintf(outfile, "%s", tagmsg);
13808 done:
13809 free(id_str);
13810 got_object_tag_close(tag);
13811 return err;
13814 static const struct got_error *
13815 cmd_cat(int argc, char *argv[])
13817 const struct got_error *error;
13818 struct got_repository *repo = NULL;
13819 struct got_worktree *worktree = NULL;
13820 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13821 const char *commit_id_str = NULL;
13822 struct got_object_id *id = NULL, *commit_id = NULL;
13823 struct got_commit_object *commit = NULL;
13824 int ch, obj_type, i, force_path = 0;
13825 struct got_reflist_head refs;
13826 int *pack_fds = NULL;
13828 TAILQ_INIT(&refs);
13830 #ifndef PROFILE
13831 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13832 NULL) == -1)
13833 err(1, "pledge");
13834 #endif
13836 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13837 switch (ch) {
13838 case 'c':
13839 commit_id_str = optarg;
13840 break;
13841 case 'P':
13842 force_path = 1;
13843 break;
13844 case 'r':
13845 repo_path = realpath(optarg, NULL);
13846 if (repo_path == NULL)
13847 return got_error_from_errno2("realpath",
13848 optarg);
13849 got_path_strip_trailing_slashes(repo_path);
13850 break;
13851 default:
13852 usage_cat();
13853 /* NOTREACHED */
13857 argc -= optind;
13858 argv += optind;
13860 cwd = getcwd(NULL, 0);
13861 if (cwd == NULL) {
13862 error = got_error_from_errno("getcwd");
13863 goto done;
13866 error = got_repo_pack_fds_open(&pack_fds);
13867 if (error != NULL)
13868 goto done;
13870 if (repo_path == NULL) {
13871 error = got_worktree_open(&worktree, cwd);
13872 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13873 goto done;
13874 if (worktree) {
13875 repo_path = strdup(
13876 got_worktree_get_repo_path(worktree));
13877 if (repo_path == NULL) {
13878 error = got_error_from_errno("strdup");
13879 goto done;
13882 /* Release work tree lock. */
13883 got_worktree_close(worktree);
13884 worktree = NULL;
13888 if (repo_path == NULL) {
13889 repo_path = strdup(cwd);
13890 if (repo_path == NULL)
13891 return got_error_from_errno("strdup");
13894 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13895 free(repo_path);
13896 if (error != NULL)
13897 goto done;
13899 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13900 if (error)
13901 goto done;
13903 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13904 if (error)
13905 goto done;
13907 if (commit_id_str == NULL)
13908 commit_id_str = GOT_REF_HEAD;
13909 error = got_repo_match_object_id(&commit_id, NULL,
13910 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13911 if (error)
13912 goto done;
13914 error = got_object_open_as_commit(&commit, repo, commit_id);
13915 if (error)
13916 goto done;
13918 for (i = 0; i < argc; i++) {
13919 if (force_path) {
13920 error = got_object_id_by_path(&id, repo, commit,
13921 argv[i]);
13922 if (error)
13923 break;
13924 } else {
13925 error = got_repo_match_object_id(&id, &label, argv[i],
13926 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13927 repo);
13928 if (error) {
13929 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13930 error->code != GOT_ERR_NOT_REF)
13931 break;
13932 error = got_object_id_by_path(&id, repo,
13933 commit, argv[i]);
13934 if (error)
13935 break;
13939 error = got_object_get_type(&obj_type, repo, id);
13940 if (error)
13941 break;
13943 switch (obj_type) {
13944 case GOT_OBJ_TYPE_BLOB:
13945 error = cat_blob(id, repo, stdout);
13946 break;
13947 case GOT_OBJ_TYPE_TREE:
13948 error = cat_tree(id, repo, stdout);
13949 break;
13950 case GOT_OBJ_TYPE_COMMIT:
13951 error = cat_commit(id, repo, stdout);
13952 break;
13953 case GOT_OBJ_TYPE_TAG:
13954 error = cat_tag(id, repo, stdout);
13955 break;
13956 default:
13957 error = got_error(GOT_ERR_OBJ_TYPE);
13958 break;
13960 if (error)
13961 break;
13962 free(label);
13963 label = NULL;
13964 free(id);
13965 id = NULL;
13967 done:
13968 free(label);
13969 free(id);
13970 free(commit_id);
13971 if (commit)
13972 got_object_commit_close(commit);
13973 if (worktree)
13974 got_worktree_close(worktree);
13975 if (repo) {
13976 const struct got_error *close_err = got_repo_close(repo);
13977 if (error == NULL)
13978 error = close_err;
13980 if (pack_fds) {
13981 const struct got_error *pack_err =
13982 got_repo_pack_fds_close(pack_fds);
13983 if (error == NULL)
13984 error = pack_err;
13987 got_ref_list_free(&refs);
13988 return error;
13991 __dead static void
13992 usage_info(void)
13994 fprintf(stderr, "usage: %s info [path ...]\n",
13995 getprogname());
13996 exit(1);
13999 static const struct got_error *
14000 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14001 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14002 struct got_object_id *commit_id)
14004 const struct got_error *err = NULL;
14005 char *id_str = NULL;
14006 char datebuf[128];
14007 struct tm mytm, *tm;
14008 struct got_pathlist_head *paths = arg;
14009 struct got_pathlist_entry *pe;
14012 * Clear error indication from any of the path arguments which
14013 * would cause this file index entry to be displayed.
14015 TAILQ_FOREACH(pe, paths, entry) {
14016 if (got_path_cmp(path, pe->path, strlen(path),
14017 pe->path_len) == 0 ||
14018 got_path_is_child(path, pe->path, pe->path_len))
14019 pe->data = NULL; /* no error */
14022 printf(GOT_COMMIT_SEP_STR);
14023 if (S_ISLNK(mode))
14024 printf("symlink: %s\n", path);
14025 else if (S_ISREG(mode)) {
14026 printf("file: %s\n", path);
14027 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14028 } else if (S_ISDIR(mode))
14029 printf("directory: %s\n", path);
14030 else
14031 printf("something: %s\n", path);
14033 tm = localtime_r(&mtime, &mytm);
14034 if (tm == NULL)
14035 return NULL;
14036 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14037 return got_error(GOT_ERR_NO_SPACE);
14038 printf("timestamp: %s\n", datebuf);
14040 if (blob_id) {
14041 err = got_object_id_str(&id_str, blob_id);
14042 if (err)
14043 return err;
14044 printf("based on blob: %s\n", id_str);
14045 free(id_str);
14048 if (staged_blob_id) {
14049 err = got_object_id_str(&id_str, staged_blob_id);
14050 if (err)
14051 return err;
14052 printf("based on staged blob: %s\n", id_str);
14053 free(id_str);
14056 if (commit_id) {
14057 err = got_object_id_str(&id_str, commit_id);
14058 if (err)
14059 return err;
14060 printf("based on commit: %s\n", id_str);
14061 free(id_str);
14064 return NULL;
14067 static const struct got_error *
14068 cmd_info(int argc, char *argv[])
14070 const struct got_error *error = NULL;
14071 struct got_worktree *worktree = NULL;
14072 char *cwd = NULL, *id_str = NULL;
14073 struct got_pathlist_head paths;
14074 char *uuidstr = NULL;
14075 int ch, show_files = 0;
14077 TAILQ_INIT(&paths);
14079 #ifndef PROFILE
14080 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14081 NULL) == -1)
14082 err(1, "pledge");
14083 #endif
14085 while ((ch = getopt(argc, argv, "")) != -1) {
14086 switch (ch) {
14087 default:
14088 usage_info();
14089 /* NOTREACHED */
14093 argc -= optind;
14094 argv += optind;
14096 cwd = getcwd(NULL, 0);
14097 if (cwd == NULL) {
14098 error = got_error_from_errno("getcwd");
14099 goto done;
14102 error = got_worktree_open(&worktree, cwd);
14103 if (error) {
14104 if (error->code == GOT_ERR_NOT_WORKTREE)
14105 error = wrap_not_worktree_error(error, "info", cwd);
14106 goto done;
14109 #ifndef PROFILE
14110 /* Remove "wpath cpath proc exec sendfd" promises. */
14111 if (pledge("stdio rpath flock unveil", NULL) == -1)
14112 err(1, "pledge");
14113 #endif
14114 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14115 if (error)
14116 goto done;
14118 if (argc >= 1) {
14119 error = get_worktree_paths_from_argv(&paths, argc, argv,
14120 worktree);
14121 if (error)
14122 goto done;
14123 show_files = 1;
14126 error = got_object_id_str(&id_str,
14127 got_worktree_get_base_commit_id(worktree));
14128 if (error)
14129 goto done;
14131 error = got_worktree_get_uuid(&uuidstr, worktree);
14132 if (error)
14133 goto done;
14135 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14136 printf("work tree base commit: %s\n", id_str);
14137 printf("work tree path prefix: %s\n",
14138 got_worktree_get_path_prefix(worktree));
14139 printf("work tree branch reference: %s\n",
14140 got_worktree_get_head_ref_name(worktree));
14141 printf("work tree UUID: %s\n", uuidstr);
14142 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14144 if (show_files) {
14145 struct got_pathlist_entry *pe;
14146 TAILQ_FOREACH(pe, &paths, entry) {
14147 if (pe->path_len == 0)
14148 continue;
14150 * Assume this path will fail. This will be corrected
14151 * in print_path_info() in case the path does suceeed.
14153 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14155 error = got_worktree_path_info(worktree, &paths,
14156 print_path_info, &paths, check_cancelled, NULL);
14157 if (error)
14158 goto done;
14159 TAILQ_FOREACH(pe, &paths, entry) {
14160 if (pe->data != NULL) {
14161 const struct got_error *perr;
14163 perr = pe->data;
14164 error = got_error_fmt(perr->code, "%s",
14165 pe->path);
14166 break;
14170 done:
14171 if (worktree)
14172 got_worktree_close(worktree);
14173 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14174 free(cwd);
14175 free(id_str);
14176 free(uuidstr);
14177 return error;