Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-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("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-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, 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_object_id *pack_hash = NULL;
2287 int i, ch, fetchfd = -1, fetchstatus;
2288 pid_t fetchpid = -1;
2289 struct got_fetch_progress_arg fpa;
2290 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2291 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2292 int *pack_fds = NULL, have_bflag = 0;
2293 const char *worktree_branch = NULL;
2295 TAILQ_INIT(&refs);
2296 TAILQ_INIT(&symrefs);
2297 TAILQ_INIT(&wanted_branches);
2298 TAILQ_INIT(&wanted_refs);
2300 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2301 switch (ch) {
2302 case 'a':
2303 fetch_all_branches = 1;
2304 break;
2305 case 'b':
2306 error = got_pathlist_append(&wanted_branches,
2307 optarg, NULL);
2308 if (error)
2309 return error;
2310 have_bflag = 1;
2311 break;
2312 case 'd':
2313 delete_refs = 1;
2314 break;
2315 case 'l':
2316 list_refs_only = 1;
2317 break;
2318 case 'q':
2319 verbosity = -1;
2320 break;
2321 case 'R':
2322 error = got_pathlist_append(&wanted_refs,
2323 optarg, NULL);
2324 if (error)
2325 return error;
2326 break;
2327 case 'r':
2328 repo_path = realpath(optarg, NULL);
2329 if (repo_path == NULL)
2330 return got_error_from_errno2("realpath",
2331 optarg);
2332 got_path_strip_trailing_slashes(repo_path);
2333 break;
2334 case 't':
2335 replace_tags = 1;
2336 break;
2337 case 'v':
2338 if (verbosity < 0)
2339 verbosity = 0;
2340 else if (verbosity < 3)
2341 verbosity++;
2342 break;
2343 case 'X':
2344 delete_remote = 1;
2345 break;
2346 default:
2347 usage_fetch();
2348 break;
2351 argc -= optind;
2352 argv += optind;
2354 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2355 option_conflict('a', 'b');
2356 if (list_refs_only) {
2357 if (!TAILQ_EMPTY(&wanted_branches))
2358 option_conflict('l', 'b');
2359 if (fetch_all_branches)
2360 option_conflict('l', 'a');
2361 if (delete_refs)
2362 option_conflict('l', 'd');
2363 if (delete_remote)
2364 option_conflict('l', 'X');
2366 if (delete_remote) {
2367 if (fetch_all_branches)
2368 option_conflict('X', 'a');
2369 if (!TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('X', 'b');
2371 if (delete_refs)
2372 option_conflict('X', 'd');
2373 if (replace_tags)
2374 option_conflict('X', 't');
2375 if (!TAILQ_EMPTY(&wanted_refs))
2376 option_conflict('X', 'R');
2379 if (argc == 0) {
2380 if (delete_remote)
2381 errx(1, "-X option requires a remote name");
2382 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2383 } else if (argc == 1)
2384 remote_name = argv[0];
2385 else
2386 usage_fetch();
2388 cwd = getcwd(NULL, 0);
2389 if (cwd == NULL) {
2390 error = got_error_from_errno("getcwd");
2391 goto done;
2394 error = got_repo_pack_fds_open(&pack_fds);
2395 if (error != NULL)
2396 goto done;
2398 if (repo_path == NULL) {
2399 error = got_worktree_open(&worktree, cwd);
2400 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2401 goto done;
2402 else
2403 error = NULL;
2404 if (worktree) {
2405 repo_path =
2406 strdup(got_worktree_get_repo_path(worktree));
2407 if (repo_path == NULL)
2408 error = got_error_from_errno("strdup");
2409 if (error)
2410 goto done;
2411 } else {
2412 repo_path = strdup(cwd);
2413 if (repo_path == NULL) {
2414 error = got_error_from_errno("strdup");
2415 goto done;
2420 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2421 if (error)
2422 goto done;
2424 if (delete_remote) {
2425 error = delete_refs_for_remote(repo, remote_name);
2426 goto done; /* nothing else to do */
2429 if (worktree) {
2430 worktree_conf = got_worktree_get_gotconfig(worktree);
2431 if (worktree_conf) {
2432 got_gotconfig_get_remotes(&nremotes, &remotes,
2433 worktree_conf);
2434 for (i = 0; i < nremotes; i++) {
2435 if (strcmp(remotes[i].name, remote_name) == 0) {
2436 remote = &remotes[i];
2437 break;
2442 if (remote == NULL) {
2443 repo_conf = got_repo_get_gotconfig(repo);
2444 if (repo_conf) {
2445 got_gotconfig_get_remotes(&nremotes, &remotes,
2446 repo_conf);
2447 for (i = 0; i < nremotes; i++) {
2448 if (strcmp(remotes[i].name, remote_name) == 0) {
2449 remote = &remotes[i];
2450 break;
2455 if (remote == NULL) {
2456 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2457 for (i = 0; i < nremotes; i++) {
2458 if (strcmp(remotes[i].name, remote_name) == 0) {
2459 remote = &remotes[i];
2460 break;
2464 if (remote == NULL) {
2465 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2466 goto done;
2469 if (TAILQ_EMPTY(&wanted_branches)) {
2470 if (!fetch_all_branches)
2471 fetch_all_branches = remote->fetch_all_branches;
2472 for (i = 0; i < remote->nfetch_branches; i++) {
2473 error = got_pathlist_append(&wanted_branches,
2474 remote->fetch_branches[i], NULL);
2475 if (error)
2476 goto done;
2479 if (TAILQ_EMPTY(&wanted_refs)) {
2480 for (i = 0; i < remote->nfetch_refs; i++) {
2481 error = got_pathlist_append(&wanted_refs,
2482 remote->fetch_refs[i], NULL);
2483 if (error)
2484 goto done;
2488 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2489 &repo_name, remote->fetch_url);
2490 if (error)
2491 goto done;
2493 if (strcmp(proto, "git") == 0) {
2494 #ifndef PROFILE
2495 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2496 "sendfd dns inet unveil", NULL) == -1)
2497 err(1, "pledge");
2498 #endif
2499 } else if (strcmp(proto, "git+ssh") == 0 ||
2500 strcmp(proto, "ssh") == 0) {
2501 #ifndef PROFILE
2502 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2503 "sendfd unveil", NULL) == -1)
2504 err(1, "pledge");
2505 #endif
2506 } else if (strcmp(proto, "http") == 0 ||
2507 strcmp(proto, "git+http") == 0) {
2508 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2509 goto done;
2510 } else {
2511 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2512 goto done;
2515 error = got_dial_apply_unveil(proto);
2516 if (error)
2517 goto done;
2519 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2520 if (error)
2521 goto done;
2523 if (verbosity >= 0) {
2524 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2525 remote->name, proto, host,
2526 port ? ":" : "", port ? port : "",
2527 *server_path == '/' ? "" : "/", server_path);
2530 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2531 server_path, verbosity);
2532 if (error)
2533 goto done;
2535 if (worktree && !have_bflag) {
2536 const char *refname;
2538 refname = got_worktree_get_head_ref_name(worktree);
2539 if (strncmp(refname, "refs/heads/", 11) == 0)
2540 worktree_branch = refname;
2543 fpa.last_scaled_size[0] = '\0';
2544 fpa.last_p_indexed = -1;
2545 fpa.last_p_resolved = -1;
2546 fpa.verbosity = verbosity;
2547 fpa.repo = repo;
2548 fpa.create_configs = 0;
2549 fpa.configs_created = 0;
2550 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2552 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2553 remote->mirror_references, fetch_all_branches, &wanted_branches,
2554 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2555 worktree_branch, have_bflag, fetch_progress, &fpa);
2556 if (error)
2557 goto done;
2559 if (list_refs_only) {
2560 error = list_remote_refs(&symrefs, &refs);
2561 goto done;
2564 if (pack_hash == NULL) {
2565 if (verbosity >= 0)
2566 printf("Already up-to-date\n");
2567 } else if (verbosity >= 0) {
2568 error = got_object_id_str(&id_str, pack_hash);
2569 if (error)
2570 goto done;
2571 printf("\nFetched %s.pack\n", id_str);
2572 free(id_str);
2573 id_str = NULL;
2576 /* Update references provided with the pack file. */
2577 TAILQ_FOREACH(pe, &refs, entry) {
2578 const char *refname = pe->path;
2579 struct got_object_id *id = pe->data;
2580 struct got_reference *ref;
2581 char *remote_refname;
2583 if (is_wanted_ref(&wanted_refs, refname) &&
2584 !remote->mirror_references) {
2585 error = update_wanted_ref(refname, id,
2586 remote->name, verbosity, repo);
2587 if (error)
2588 goto done;
2589 continue;
2592 if (remote->mirror_references ||
2593 strncmp("refs/tags/", refname, 10) == 0) {
2594 error = got_ref_open(&ref, repo, refname, 1);
2595 if (error) {
2596 if (error->code != GOT_ERR_NOT_REF)
2597 goto done;
2598 error = create_ref(refname, id, verbosity,
2599 repo);
2600 if (error)
2601 goto done;
2602 } else {
2603 error = update_ref(ref, id, replace_tags,
2604 verbosity, repo);
2605 unlock_err = got_ref_unlock(ref);
2606 if (unlock_err && error == NULL)
2607 error = unlock_err;
2608 got_ref_close(ref);
2609 if (error)
2610 goto done;
2612 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2613 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2614 remote_name, refname + 11) == -1) {
2615 error = got_error_from_errno("asprintf");
2616 goto done;
2619 error = got_ref_open(&ref, repo, remote_refname, 1);
2620 if (error) {
2621 if (error->code != GOT_ERR_NOT_REF)
2622 goto done;
2623 error = create_ref(remote_refname, id,
2624 verbosity, repo);
2625 if (error)
2626 goto done;
2627 } else {
2628 error = update_ref(ref, id, replace_tags,
2629 verbosity, repo);
2630 unlock_err = got_ref_unlock(ref);
2631 if (unlock_err && error == NULL)
2632 error = unlock_err;
2633 got_ref_close(ref);
2634 if (error)
2635 goto done;
2638 /* Also create a local branch if none exists yet. */
2639 error = got_ref_open(&ref, repo, refname, 1);
2640 if (error) {
2641 if (error->code != GOT_ERR_NOT_REF)
2642 goto done;
2643 error = create_ref(refname, id, verbosity,
2644 repo);
2645 if (error)
2646 goto done;
2647 } else {
2648 unlock_err = got_ref_unlock(ref);
2649 if (unlock_err && error == NULL)
2650 error = unlock_err;
2651 got_ref_close(ref);
2655 if (delete_refs) {
2656 error = delete_missing_refs(&refs, &symrefs, remote,
2657 verbosity, repo);
2658 if (error)
2659 goto done;
2662 if (!remote->mirror_references) {
2663 /* Update remote HEAD reference if the server provided one. */
2664 TAILQ_FOREACH(pe, &symrefs, entry) {
2665 struct got_reference *target_ref;
2666 const char *refname = pe->path;
2667 const char *target = pe->data;
2668 char *remote_refname = NULL, *remote_target = NULL;
2670 if (strcmp(refname, GOT_REF_HEAD) != 0)
2671 continue;
2673 if (strncmp("refs/heads/", target, 11) != 0)
2674 continue;
2676 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2677 remote->name, refname) == -1) {
2678 error = got_error_from_errno("asprintf");
2679 goto done;
2681 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2682 remote->name, target + 11) == -1) {
2683 error = got_error_from_errno("asprintf");
2684 free(remote_refname);
2685 goto done;
2688 error = got_ref_open(&target_ref, repo, remote_target,
2689 0);
2690 if (error) {
2691 free(remote_refname);
2692 free(remote_target);
2693 if (error->code == GOT_ERR_NOT_REF) {
2694 error = NULL;
2695 continue;
2697 goto done;
2699 error = update_symref(remote_refname, target_ref,
2700 verbosity, repo);
2701 free(remote_refname);
2702 free(remote_target);
2703 got_ref_close(target_ref);
2704 if (error)
2705 goto done;
2708 done:
2709 if (fetchpid > 0) {
2710 if (kill(fetchpid, SIGTERM) == -1)
2711 error = got_error_from_errno("kill");
2712 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2713 error = got_error_from_errno("waitpid");
2715 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2716 error = got_error_from_errno("close");
2717 if (repo) {
2718 const struct got_error *close_err = got_repo_close(repo);
2719 if (error == NULL)
2720 error = close_err;
2722 if (worktree)
2723 got_worktree_close(worktree);
2724 if (pack_fds) {
2725 const struct got_error *pack_err =
2726 got_repo_pack_fds_close(pack_fds);
2727 if (error == NULL)
2728 error = pack_err;
2730 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2731 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2732 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2733 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2734 free(id_str);
2735 free(cwd);
2736 free(repo_path);
2737 free(pack_hash);
2738 free(proto);
2739 free(host);
2740 free(port);
2741 free(server_path);
2742 free(repo_name);
2743 return error;
2747 __dead static void
2748 usage_checkout(void)
2750 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2751 "[-p path-prefix] repository-path [work-tree-path]\n",
2752 getprogname());
2753 exit(1);
2756 static void
2757 show_worktree_base_ref_warning(void)
2759 fprintf(stderr, "%s: warning: could not create a reference "
2760 "to the work tree's base commit; the commit could be "
2761 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2762 "repository writable and running 'got update' will prevent this\n",
2763 getprogname());
2766 struct got_checkout_progress_arg {
2767 const char *worktree_path;
2768 int had_base_commit_ref_error;
2769 int verbosity;
2772 static const struct got_error *
2773 checkout_progress(void *arg, unsigned char status, const char *path)
2775 struct got_checkout_progress_arg *a = arg;
2777 /* Base commit bump happens silently. */
2778 if (status == GOT_STATUS_BUMP_BASE)
2779 return NULL;
2781 if (status == GOT_STATUS_BASE_REF_ERR) {
2782 a->had_base_commit_ref_error = 1;
2783 return NULL;
2786 while (path[0] == '/')
2787 path++;
2789 if (a->verbosity >= 0)
2790 printf("%c %s/%s\n", status, a->worktree_path, path);
2792 return NULL;
2795 static const struct got_error *
2796 check_cancelled(void *arg)
2798 if (sigint_received || sigpipe_received)
2799 return got_error(GOT_ERR_CANCELLED);
2800 return NULL;
2803 static const struct got_error *
2804 check_linear_ancestry(struct got_object_id *commit_id,
2805 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2806 struct got_repository *repo)
2808 const struct got_error *err = NULL;
2809 struct got_object_id *yca_id;
2811 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2812 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2813 if (err)
2814 return err;
2816 if (yca_id == NULL)
2817 return got_error(GOT_ERR_ANCESTRY);
2820 * Require a straight line of history between the target commit
2821 * and the work tree's base commit.
2823 * Non-linear situations such as this require a rebase:
2825 * (commit) D F (base_commit)
2826 * \ /
2827 * C E
2828 * \ /
2829 * B (yca)
2830 * |
2831 * A
2833 * 'got update' only handles linear cases:
2834 * Update forwards in time: A (base/yca) - B - C - D (commit)
2835 * Update backwards in time: D (base) - C - B - A (commit/yca)
2837 if (allow_forwards_in_time_only) {
2838 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2839 return got_error(GOT_ERR_ANCESTRY);
2840 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2841 got_object_id_cmp(base_commit_id, yca_id) != 0)
2842 return got_error(GOT_ERR_ANCESTRY);
2844 free(yca_id);
2845 return NULL;
2848 static const struct got_error *
2849 check_same_branch(struct got_object_id *commit_id,
2850 struct got_reference *head_ref, struct got_object_id *yca_id,
2851 struct got_repository *repo)
2853 const struct got_error *err = NULL;
2854 struct got_commit_graph *graph = NULL;
2855 struct got_object_id *head_commit_id = NULL;
2856 int is_same_branch = 0;
2858 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2859 if (err)
2860 goto done;
2862 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2863 is_same_branch = 1;
2864 goto done;
2866 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2867 is_same_branch = 1;
2868 goto done;
2871 err = got_commit_graph_open(&graph, "/", 1);
2872 if (err)
2873 goto done;
2875 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2876 check_cancelled, NULL);
2877 if (err)
2878 goto done;
2880 for (;;) {
2881 struct got_object_id id;
2883 err = got_commit_graph_iter_next(&id, graph, repo,
2884 check_cancelled, NULL);
2885 if (err) {
2886 if (err->code == GOT_ERR_ITER_COMPLETED)
2887 err = NULL;
2888 break;
2891 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2892 break;
2893 if (got_object_id_cmp(&id, commit_id) == 0) {
2894 is_same_branch = 1;
2895 break;
2898 done:
2899 if (graph)
2900 got_commit_graph_close(graph);
2901 free(head_commit_id);
2902 if (!err && !is_same_branch)
2903 err = got_error(GOT_ERR_ANCESTRY);
2904 return err;
2907 static const struct got_error *
2908 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2910 static char msg[512];
2911 const char *branch_name;
2913 if (got_ref_is_symbolic(ref))
2914 branch_name = got_ref_get_symref_target(ref);
2915 else
2916 branch_name = got_ref_get_name(ref);
2918 if (strncmp("refs/heads/", branch_name, 11) == 0)
2919 branch_name += 11;
2921 snprintf(msg, sizeof(msg),
2922 "target commit is not contained in branch '%s'; "
2923 "the branch to use must be specified with -b; "
2924 "if necessary a new branch can be created for "
2925 "this commit with 'got branch -c %s BRANCH_NAME'",
2926 branch_name, commit_id_str);
2928 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2931 static const struct got_error *
2932 cmd_checkout(int argc, char *argv[])
2934 const struct got_error *error = NULL;
2935 struct got_repository *repo = NULL;
2936 struct got_reference *head_ref = NULL, *ref = NULL;
2937 struct got_worktree *worktree = NULL;
2938 char *repo_path = NULL;
2939 char *worktree_path = NULL;
2940 const char *path_prefix = "";
2941 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2942 char *commit_id_str = NULL;
2943 struct got_object_id *commit_id = NULL;
2944 char *cwd = NULL;
2945 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2946 struct got_pathlist_head paths;
2947 struct got_checkout_progress_arg cpa;
2948 int *pack_fds = NULL;
2950 TAILQ_INIT(&paths);
2952 #ifndef PROFILE
2953 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2954 "unveil", NULL) == -1)
2955 err(1, "pledge");
2956 #endif
2958 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2959 switch (ch) {
2960 case 'b':
2961 branch_name = optarg;
2962 break;
2963 case 'c':
2964 commit_id_str = strdup(optarg);
2965 if (commit_id_str == NULL)
2966 return got_error_from_errno("strdup");
2967 break;
2968 case 'E':
2969 allow_nonempty = 1;
2970 break;
2971 case 'p':
2972 path_prefix = optarg;
2973 break;
2974 case 'q':
2975 verbosity = -1;
2976 break;
2977 default:
2978 usage_checkout();
2979 /* NOTREACHED */
2983 argc -= optind;
2984 argv += optind;
2986 if (argc == 1) {
2987 char *base, *dotgit;
2988 const char *path;
2989 repo_path = realpath(argv[0], NULL);
2990 if (repo_path == NULL)
2991 return got_error_from_errno2("realpath", argv[0]);
2992 cwd = getcwd(NULL, 0);
2993 if (cwd == NULL) {
2994 error = got_error_from_errno("getcwd");
2995 goto done;
2997 if (path_prefix[0])
2998 path = path_prefix;
2999 else
3000 path = repo_path;
3001 error = got_path_basename(&base, path);
3002 if (error)
3003 goto done;
3004 dotgit = strstr(base, ".git");
3005 if (dotgit)
3006 *dotgit = '\0';
3007 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3008 error = got_error_from_errno("asprintf");
3009 free(base);
3010 goto done;
3012 free(base);
3013 } else if (argc == 2) {
3014 repo_path = realpath(argv[0], NULL);
3015 if (repo_path == NULL) {
3016 error = got_error_from_errno2("realpath", argv[0]);
3017 goto done;
3019 worktree_path = realpath(argv[1], NULL);
3020 if (worktree_path == NULL) {
3021 if (errno != ENOENT) {
3022 error = got_error_from_errno2("realpath",
3023 argv[1]);
3024 goto done;
3026 worktree_path = strdup(argv[1]);
3027 if (worktree_path == NULL) {
3028 error = got_error_from_errno("strdup");
3029 goto done;
3032 } else
3033 usage_checkout();
3035 got_path_strip_trailing_slashes(repo_path);
3036 got_path_strip_trailing_slashes(worktree_path);
3038 error = got_repo_pack_fds_open(&pack_fds);
3039 if (error != NULL)
3040 goto done;
3042 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3043 if (error != NULL)
3044 goto done;
3046 /* Pre-create work tree path for unveil(2) */
3047 error = got_path_mkdir(worktree_path);
3048 if (error) {
3049 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3050 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3051 goto done;
3052 if (!allow_nonempty &&
3053 !got_path_dir_is_empty(worktree_path)) {
3054 error = got_error_path(worktree_path,
3055 GOT_ERR_DIR_NOT_EMPTY);
3056 goto done;
3060 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3061 if (error)
3062 goto done;
3064 error = got_ref_open(&head_ref, repo, branch_name, 0);
3065 if (error != NULL)
3066 goto done;
3068 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3069 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3070 goto done;
3072 error = got_worktree_open(&worktree, worktree_path);
3073 if (error != NULL)
3074 goto done;
3076 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3077 path_prefix);
3078 if (error != NULL)
3079 goto done;
3080 if (!same_path_prefix) {
3081 error = got_error(GOT_ERR_PATH_PREFIX);
3082 goto done;
3085 if (commit_id_str) {
3086 struct got_reflist_head refs;
3087 TAILQ_INIT(&refs);
3088 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3089 NULL);
3090 if (error)
3091 goto done;
3092 error = got_repo_match_object_id(&commit_id, NULL,
3093 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3094 got_ref_list_free(&refs);
3095 if (error)
3096 goto done;
3097 error = check_linear_ancestry(commit_id,
3098 got_worktree_get_base_commit_id(worktree), 0, repo);
3099 if (error != NULL) {
3100 if (error->code == GOT_ERR_ANCESTRY) {
3101 error = checkout_ancestry_error(
3102 head_ref, commit_id_str);
3104 goto done;
3106 error = check_same_branch(commit_id, head_ref, NULL, repo);
3107 if (error) {
3108 if (error->code == GOT_ERR_ANCESTRY) {
3109 error = checkout_ancestry_error(
3110 head_ref, commit_id_str);
3112 goto done;
3114 error = got_worktree_set_base_commit_id(worktree, repo,
3115 commit_id);
3116 if (error)
3117 goto done;
3118 /* Expand potentially abbreviated commit ID string. */
3119 free(commit_id_str);
3120 error = got_object_id_str(&commit_id_str, commit_id);
3121 if (error)
3122 goto done;
3123 } else {
3124 commit_id = got_object_id_dup(
3125 got_worktree_get_base_commit_id(worktree));
3126 if (commit_id == NULL) {
3127 error = got_error_from_errno("got_object_id_dup");
3128 goto done;
3130 error = got_object_id_str(&commit_id_str, commit_id);
3131 if (error)
3132 goto done;
3135 error = got_pathlist_append(&paths, "", NULL);
3136 if (error)
3137 goto done;
3138 cpa.worktree_path = worktree_path;
3139 cpa.had_base_commit_ref_error = 0;
3140 cpa.verbosity = verbosity;
3141 error = got_worktree_checkout_files(worktree, &paths, repo,
3142 checkout_progress, &cpa, check_cancelled, NULL);
3143 if (error != NULL)
3144 goto done;
3146 if (got_ref_is_symbolic(head_ref)) {
3147 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3148 if (error)
3149 goto done;
3150 refname = got_ref_get_name(ref);
3151 } else
3152 refname = got_ref_get_name(head_ref);
3153 printf("Checked out %s: %s\n", refname, commit_id_str);
3154 printf("Now shut up and hack\n");
3155 if (cpa.had_base_commit_ref_error)
3156 show_worktree_base_ref_warning();
3157 done:
3158 if (pack_fds) {
3159 const struct got_error *pack_err =
3160 got_repo_pack_fds_close(pack_fds);
3161 if (error == NULL)
3162 error = pack_err;
3164 if (head_ref)
3165 got_ref_close(head_ref);
3166 if (ref)
3167 got_ref_close(ref);
3168 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3169 free(commit_id_str);
3170 free(commit_id);
3171 free(repo_path);
3172 free(worktree_path);
3173 free(cwd);
3174 return error;
3177 struct got_update_progress_arg {
3178 int did_something;
3179 int conflicts;
3180 int obstructed;
3181 int not_updated;
3182 int missing;
3183 int not_deleted;
3184 int unversioned;
3185 int verbosity;
3188 static void
3189 print_update_progress_stats(struct got_update_progress_arg *upa)
3191 if (!upa->did_something)
3192 return;
3194 if (upa->conflicts > 0)
3195 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3196 if (upa->obstructed > 0)
3197 printf("File paths obstructed by a non-regular file: %d\n",
3198 upa->obstructed);
3199 if (upa->not_updated > 0)
3200 printf("Files not updated because of existing merge "
3201 "conflicts: %d\n", upa->not_updated);
3205 * The meaning of some status codes differs between merge-style operations and
3206 * update operations. For example, the ! status code means "file was missing"
3207 * if changes were merged into the work tree, and "missing file was restored"
3208 * if the work tree was updated. This function should be used by any operation
3209 * which merges changes into the work tree without updating the work tree.
3211 static void
3212 print_merge_progress_stats(struct got_update_progress_arg *upa)
3214 if (!upa->did_something)
3215 return;
3217 if (upa->conflicts > 0)
3218 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3219 if (upa->obstructed > 0)
3220 printf("File paths obstructed by a non-regular file: %d\n",
3221 upa->obstructed);
3222 if (upa->missing > 0)
3223 printf("Files which had incoming changes but could not be "
3224 "found in the work tree: %d\n", upa->missing);
3225 if (upa->not_deleted > 0)
3226 printf("Files not deleted due to differences in deleted "
3227 "content: %d\n", upa->not_deleted);
3228 if (upa->unversioned > 0)
3229 printf("Files not merged because an unversioned file was "
3230 "found in the work tree: %d\n", upa->unversioned);
3233 __dead static void
3234 usage_update(void)
3236 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3237 "[path ...]\n", getprogname());
3238 exit(1);
3241 static const struct got_error *
3242 update_progress(void *arg, unsigned char status, const char *path)
3244 struct got_update_progress_arg *upa = arg;
3246 if (status == GOT_STATUS_EXISTS ||
3247 status == GOT_STATUS_BASE_REF_ERR)
3248 return NULL;
3250 upa->did_something = 1;
3252 /* Base commit bump happens silently. */
3253 if (status == GOT_STATUS_BUMP_BASE)
3254 return NULL;
3256 if (status == GOT_STATUS_CONFLICT)
3257 upa->conflicts++;
3258 if (status == GOT_STATUS_OBSTRUCTED)
3259 upa->obstructed++;
3260 if (status == GOT_STATUS_CANNOT_UPDATE)
3261 upa->not_updated++;
3262 if (status == GOT_STATUS_MISSING)
3263 upa->missing++;
3264 if (status == GOT_STATUS_CANNOT_DELETE)
3265 upa->not_deleted++;
3266 if (status == GOT_STATUS_UNVERSIONED)
3267 upa->unversioned++;
3269 while (path[0] == '/')
3270 path++;
3271 if (upa->verbosity >= 0)
3272 printf("%c %s\n", status, path);
3274 return NULL;
3277 static const struct got_error *
3278 switch_head_ref(struct got_reference *head_ref,
3279 struct got_object_id *commit_id, struct got_worktree *worktree,
3280 struct got_repository *repo)
3282 const struct got_error *err = NULL;
3283 char *base_id_str;
3284 int ref_has_moved = 0;
3286 /* Trivial case: switching between two different references. */
3287 if (strcmp(got_ref_get_name(head_ref),
3288 got_worktree_get_head_ref_name(worktree)) != 0) {
3289 printf("Switching work tree from %s to %s\n",
3290 got_worktree_get_head_ref_name(worktree),
3291 got_ref_get_name(head_ref));
3292 return got_worktree_set_head_ref(worktree, head_ref);
3295 err = check_linear_ancestry(commit_id,
3296 got_worktree_get_base_commit_id(worktree), 0, repo);
3297 if (err) {
3298 if (err->code != GOT_ERR_ANCESTRY)
3299 return err;
3300 ref_has_moved = 1;
3302 if (!ref_has_moved)
3303 return NULL;
3305 /* Switching to a rebased branch with the same reference name. */
3306 err = got_object_id_str(&base_id_str,
3307 got_worktree_get_base_commit_id(worktree));
3308 if (err)
3309 return err;
3310 printf("Reference %s now points at a different branch\n",
3311 got_worktree_get_head_ref_name(worktree));
3312 printf("Switching work tree from %s to %s\n", base_id_str,
3313 got_worktree_get_head_ref_name(worktree));
3314 return NULL;
3317 static const struct got_error *
3318 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3320 const struct got_error *err;
3321 int in_progress;
3323 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3324 if (err)
3325 return err;
3326 if (in_progress)
3327 return got_error(GOT_ERR_REBASING);
3329 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3330 if (err)
3331 return err;
3332 if (in_progress)
3333 return got_error(GOT_ERR_HISTEDIT_BUSY);
3335 return NULL;
3338 static const struct got_error *
3339 check_merge_in_progress(struct got_worktree *worktree,
3340 struct got_repository *repo)
3342 const struct got_error *err;
3343 int in_progress;
3345 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3346 if (err)
3347 return err;
3348 if (in_progress)
3349 return got_error(GOT_ERR_MERGE_BUSY);
3351 return NULL;
3354 static const struct got_error *
3355 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3356 char *argv[], struct got_worktree *worktree)
3358 const struct got_error *err = NULL;
3359 char *path;
3360 struct got_pathlist_entry *new;
3361 int i;
3363 if (argc == 0) {
3364 path = strdup("");
3365 if (path == NULL)
3366 return got_error_from_errno("strdup");
3367 return got_pathlist_append(paths, path, NULL);
3370 for (i = 0; i < argc; i++) {
3371 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3372 if (err)
3373 break;
3374 err = got_pathlist_insert(&new, paths, path, NULL);
3375 if (err || new == NULL /* duplicate */) {
3376 free(path);
3377 if (err)
3378 break;
3382 return err;
3385 static const struct got_error *
3386 wrap_not_worktree_error(const struct got_error *orig_err,
3387 const char *cmdname, const char *path)
3389 const struct got_error *err;
3390 struct got_repository *repo;
3391 static char msg[512];
3392 int *pack_fds = NULL;
3394 err = got_repo_pack_fds_open(&pack_fds);
3395 if (err)
3396 return err;
3398 err = got_repo_open(&repo, path, NULL, pack_fds);
3399 if (err)
3400 return orig_err;
3402 snprintf(msg, sizeof(msg),
3403 "'got %s' needs a work tree in addition to a git repository\n"
3404 "Work trees can be checked out from this Git repository with "
3405 "'got checkout'.\n"
3406 "The got(1) manual page contains more information.", cmdname);
3407 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3408 got_repo_close(repo);
3409 if (pack_fds) {
3410 const struct got_error *pack_err =
3411 got_repo_pack_fds_close(pack_fds);
3412 if (err == NULL)
3413 err = pack_err;
3415 return err;
3418 static const struct got_error *
3419 cmd_update(int argc, char *argv[])
3421 const struct got_error *error = NULL;
3422 struct got_repository *repo = NULL;
3423 struct got_worktree *worktree = NULL;
3424 char *worktree_path = NULL;
3425 struct got_object_id *commit_id = NULL;
3426 char *commit_id_str = NULL;
3427 const char *branch_name = NULL;
3428 struct got_reference *head_ref = NULL;
3429 struct got_pathlist_head paths;
3430 struct got_pathlist_entry *pe;
3431 int ch, verbosity = 0;
3432 struct got_update_progress_arg upa;
3433 int *pack_fds = NULL;
3435 TAILQ_INIT(&paths);
3437 #ifndef PROFILE
3438 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3439 "unveil", NULL) == -1)
3440 err(1, "pledge");
3441 #endif
3443 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3444 switch (ch) {
3445 case 'b':
3446 branch_name = optarg;
3447 break;
3448 case 'c':
3449 commit_id_str = strdup(optarg);
3450 if (commit_id_str == NULL)
3451 return got_error_from_errno("strdup");
3452 break;
3453 case 'q':
3454 verbosity = -1;
3455 break;
3456 default:
3457 usage_update();
3458 /* NOTREACHED */
3462 argc -= optind;
3463 argv += optind;
3465 worktree_path = getcwd(NULL, 0);
3466 if (worktree_path == NULL) {
3467 error = got_error_from_errno("getcwd");
3468 goto done;
3471 error = got_repo_pack_fds_open(&pack_fds);
3472 if (error != NULL)
3473 goto done;
3475 error = got_worktree_open(&worktree, worktree_path);
3476 if (error) {
3477 if (error->code == GOT_ERR_NOT_WORKTREE)
3478 error = wrap_not_worktree_error(error, "update",
3479 worktree_path);
3480 goto done;
3483 error = check_rebase_or_histedit_in_progress(worktree);
3484 if (error)
3485 goto done;
3487 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3488 NULL, pack_fds);
3489 if (error != NULL)
3490 goto done;
3492 error = apply_unveil(got_repo_get_path(repo), 0,
3493 got_worktree_get_root_path(worktree));
3494 if (error)
3495 goto done;
3497 error = check_merge_in_progress(worktree, repo);
3498 if (error)
3499 goto done;
3501 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3502 if (error)
3503 goto done;
3505 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3506 got_worktree_get_head_ref_name(worktree), 0);
3507 if (error != NULL)
3508 goto done;
3509 if (commit_id_str == NULL) {
3510 error = got_ref_resolve(&commit_id, repo, head_ref);
3511 if (error != NULL)
3512 goto done;
3513 error = got_object_id_str(&commit_id_str, commit_id);
3514 if (error != NULL)
3515 goto done;
3516 } else {
3517 struct got_reflist_head refs;
3518 TAILQ_INIT(&refs);
3519 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3520 NULL);
3521 if (error)
3522 goto done;
3523 error = got_repo_match_object_id(&commit_id, NULL,
3524 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3525 got_ref_list_free(&refs);
3526 free(commit_id_str);
3527 commit_id_str = NULL;
3528 if (error)
3529 goto done;
3530 error = got_object_id_str(&commit_id_str, commit_id);
3531 if (error)
3532 goto done;
3535 if (branch_name) {
3536 struct got_object_id *head_commit_id;
3537 TAILQ_FOREACH(pe, &paths, entry) {
3538 if (pe->path_len == 0)
3539 continue;
3540 error = got_error_msg(GOT_ERR_BAD_PATH,
3541 "switching between branches requires that "
3542 "the entire work tree gets updated");
3543 goto done;
3545 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3546 if (error)
3547 goto done;
3548 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3549 repo);
3550 free(head_commit_id);
3551 if (error != NULL)
3552 goto done;
3553 error = check_same_branch(commit_id, head_ref, NULL, repo);
3554 if (error)
3555 goto done;
3556 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3557 if (error)
3558 goto done;
3559 } else {
3560 error = check_linear_ancestry(commit_id,
3561 got_worktree_get_base_commit_id(worktree), 0, repo);
3562 if (error != NULL) {
3563 if (error->code == GOT_ERR_ANCESTRY)
3564 error = got_error(GOT_ERR_BRANCH_MOVED);
3565 goto done;
3567 error = check_same_branch(commit_id, head_ref, NULL, repo);
3568 if (error)
3569 goto done;
3572 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3573 commit_id) != 0) {
3574 error = got_worktree_set_base_commit_id(worktree, repo,
3575 commit_id);
3576 if (error)
3577 goto done;
3580 memset(&upa, 0, sizeof(upa));
3581 upa.verbosity = verbosity;
3582 error = got_worktree_checkout_files(worktree, &paths, repo,
3583 update_progress, &upa, check_cancelled, NULL);
3584 if (error != NULL)
3585 goto done;
3587 if (upa.did_something) {
3588 printf("Updated to %s: %s\n",
3589 got_worktree_get_head_ref_name(worktree), commit_id_str);
3590 } else
3591 printf("Already up-to-date\n");
3593 print_update_progress_stats(&upa);
3594 done:
3595 if (pack_fds) {
3596 const struct got_error *pack_err =
3597 got_repo_pack_fds_close(pack_fds);
3598 if (error == NULL)
3599 error = pack_err;
3601 free(worktree_path);
3602 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3603 free(commit_id);
3604 free(commit_id_str);
3605 return error;
3608 static const struct got_error *
3609 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3610 const char *path, int diff_context, int ignore_whitespace,
3611 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3612 struct got_repository *repo, FILE *outfile)
3614 const struct got_error *err = NULL;
3615 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3616 FILE *f1 = NULL, *f2 = NULL;
3617 int fd1 = -1, fd2 = -1;
3619 fd1 = got_opentempfd();
3620 if (fd1 == -1)
3621 return got_error_from_errno("got_opentempfd");
3622 fd2 = got_opentempfd();
3623 if (fd2 == -1) {
3624 err = got_error_from_errno("got_opentempfd");
3625 goto done;
3628 if (blob_id1) {
3629 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3630 fd1);
3631 if (err)
3632 goto done;
3635 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3636 if (err)
3637 goto done;
3639 f1 = got_opentemp();
3640 if (f1 == NULL) {
3641 err = got_error_from_errno("got_opentemp");
3642 goto done;
3644 f2 = got_opentemp();
3645 if (f2 == NULL) {
3646 err = got_error_from_errno("got_opentemp");
3647 goto done;
3650 while (path[0] == '/')
3651 path++;
3652 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3653 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3654 force_text_diff, dsa, outfile);
3655 done:
3656 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3657 err = got_error_from_errno("close");
3658 if (blob1)
3659 got_object_blob_close(blob1);
3660 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3661 err = got_error_from_errno("close");
3662 got_object_blob_close(blob2);
3663 if (f1 && fclose(f1) == EOF && err == NULL)
3664 err = got_error_from_errno("fclose");
3665 if (f2 && fclose(f2) == EOF && err == NULL)
3666 err = got_error_from_errno("fclose");
3667 return err;
3670 static const struct got_error *
3671 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3672 const char *path, int diff_context, int ignore_whitespace,
3673 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3674 struct got_repository *repo, FILE *outfile)
3676 const struct got_error *err = NULL;
3677 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3678 struct got_diff_blob_output_unidiff_arg arg;
3679 FILE *f1 = NULL, *f2 = NULL;
3680 int fd1 = -1, fd2 = -1;
3682 if (tree_id1) {
3683 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3684 if (err)
3685 goto done;
3686 fd1 = got_opentempfd();
3687 if (fd1 == -1) {
3688 err = got_error_from_errno("got_opentempfd");
3689 goto done;
3693 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3694 if (err)
3695 goto done;
3697 f1 = got_opentemp();
3698 if (f1 == NULL) {
3699 err = got_error_from_errno("got_opentemp");
3700 goto done;
3703 f2 = got_opentemp();
3704 if (f2 == NULL) {
3705 err = got_error_from_errno("got_opentemp");
3706 goto done;
3708 fd2 = got_opentempfd();
3709 if (fd2 == -1) {
3710 err = got_error_from_errno("got_opentempfd");
3711 goto done;
3713 arg.diff_context = diff_context;
3714 arg.ignore_whitespace = ignore_whitespace;
3715 arg.force_text_diff = force_text_diff;
3716 arg.diffstat = dsa;
3717 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3718 arg.outfile = outfile;
3719 arg.lines = NULL;
3720 arg.nlines = 0;
3721 while (path[0] == '/')
3722 path++;
3723 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3724 got_diff_blob_output_unidiff, &arg, 1);
3725 done:
3726 if (tree1)
3727 got_object_tree_close(tree1);
3728 if (tree2)
3729 got_object_tree_close(tree2);
3730 if (f1 && fclose(f1) == EOF && err == NULL)
3731 err = got_error_from_errno("fclose");
3732 if (f2 && fclose(f2) == EOF && err == NULL)
3733 err = got_error_from_errno("fclose");
3734 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3735 err = got_error_from_errno("close");
3736 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3737 err = got_error_from_errno("close");
3738 return err;
3741 static const struct got_error *
3742 get_changed_paths(struct got_pathlist_head *paths,
3743 struct got_commit_object *commit, struct got_repository *repo,
3744 struct got_diffstat_cb_arg *dsa)
3746 const struct got_error *err = NULL;
3747 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3748 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3749 struct got_object_qid *qid;
3750 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3751 FILE *f1 = NULL, *f2 = NULL;
3752 int fd1 = -1, fd2 = -1;
3754 if (dsa) {
3755 cb = got_diff_tree_compute_diffstat;
3757 f1 = got_opentemp();
3758 if (f1 == NULL) {
3759 err = got_error_from_errno("got_opentemp");
3760 goto done;
3762 f2 = got_opentemp();
3763 if (f2 == NULL) {
3764 err = got_error_from_errno("got_opentemp");
3765 goto done;
3767 fd1 = got_opentempfd();
3768 if (fd1 == -1) {
3769 err = got_error_from_errno("got_opentempfd");
3770 goto done;
3772 fd2 = got_opentempfd();
3773 if (fd2 == -1) {
3774 err = got_error_from_errno("got_opentempfd");
3775 goto done;
3779 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3780 if (qid != NULL) {
3781 struct got_commit_object *pcommit;
3782 err = got_object_open_as_commit(&pcommit, repo,
3783 &qid->id);
3784 if (err)
3785 return err;
3787 tree_id1 = got_object_id_dup(
3788 got_object_commit_get_tree_id(pcommit));
3789 if (tree_id1 == NULL) {
3790 got_object_commit_close(pcommit);
3791 return got_error_from_errno("got_object_id_dup");
3793 got_object_commit_close(pcommit);
3797 if (tree_id1) {
3798 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3799 if (err)
3800 goto done;
3803 tree_id2 = got_object_commit_get_tree_id(commit);
3804 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3805 if (err)
3806 goto done;
3808 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3809 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3810 done:
3811 if (tree1)
3812 got_object_tree_close(tree1);
3813 if (tree2)
3814 got_object_tree_close(tree2);
3815 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3816 err = got_error_from_errno("close");
3817 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3818 err = got_error_from_errno("close");
3819 if (f1 && fclose(f1) == EOF && err == NULL)
3820 err = got_error_from_errno("fclose");
3821 if (f2 && fclose(f2) == EOF && err == NULL)
3822 err = got_error_from_errno("fclose");
3823 free(tree_id1);
3824 return err;
3827 static const struct got_error *
3828 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3829 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3830 struct got_repository *repo, FILE *outfile)
3832 const struct got_error *err = NULL;
3833 struct got_commit_object *pcommit = NULL;
3834 char *id_str1 = NULL, *id_str2 = NULL;
3835 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3836 struct got_object_qid *qid;
3838 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3839 if (qid != NULL) {
3840 err = got_object_open_as_commit(&pcommit, repo,
3841 &qid->id);
3842 if (err)
3843 return err;
3844 err = got_object_id_str(&id_str1, &qid->id);
3845 if (err)
3846 goto done;
3849 err = got_object_id_str(&id_str2, id);
3850 if (err)
3851 goto done;
3853 if (path && path[0] != '\0') {
3854 int obj_type;
3855 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3856 if (err)
3857 goto done;
3858 if (pcommit) {
3859 err = got_object_id_by_path(&obj_id1, repo,
3860 pcommit, path);
3861 if (err) {
3862 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3863 free(obj_id2);
3864 goto done;
3868 err = got_object_get_type(&obj_type, repo, obj_id2);
3869 if (err) {
3870 free(obj_id2);
3871 goto done;
3873 fprintf(outfile,
3874 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3875 fprintf(outfile, "commit - %s\n",
3876 id_str1 ? id_str1 : "/dev/null");
3877 fprintf(outfile, "commit + %s\n", id_str2);
3878 switch (obj_type) {
3879 case GOT_OBJ_TYPE_BLOB:
3880 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3881 0, 0, dsa, repo, outfile);
3882 break;
3883 case GOT_OBJ_TYPE_TREE:
3884 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3885 0, 0, dsa, repo, outfile);
3886 break;
3887 default:
3888 err = got_error(GOT_ERR_OBJ_TYPE);
3889 break;
3891 free(obj_id1);
3892 free(obj_id2);
3893 } else {
3894 obj_id2 = got_object_commit_get_tree_id(commit);
3895 if (pcommit)
3896 obj_id1 = got_object_commit_get_tree_id(pcommit);
3897 fprintf(outfile,
3898 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3899 fprintf(outfile, "commit - %s\n",
3900 id_str1 ? id_str1 : "/dev/null");
3901 fprintf(outfile, "commit + %s\n", id_str2);
3902 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3903 dsa, repo, outfile);
3905 done:
3906 free(id_str1);
3907 free(id_str2);
3908 if (pcommit)
3909 got_object_commit_close(pcommit);
3910 return err;
3913 static char *
3914 get_datestr(time_t *time, char *datebuf)
3916 struct tm mytm, *tm;
3917 char *p, *s;
3919 tm = gmtime_r(time, &mytm);
3920 if (tm == NULL)
3921 return NULL;
3922 s = asctime_r(tm, datebuf);
3923 if (s == NULL)
3924 return NULL;
3925 p = strchr(s, '\n');
3926 if (p)
3927 *p = '\0';
3928 return s;
3931 static const struct got_error *
3932 match_commit(int *have_match, struct got_object_id *id,
3933 struct got_commit_object *commit, regex_t *regex)
3935 const struct got_error *err = NULL;
3936 regmatch_t regmatch;
3937 char *id_str = NULL, *logmsg = NULL;
3939 *have_match = 0;
3941 err = got_object_id_str(&id_str, id);
3942 if (err)
3943 return err;
3945 err = got_object_commit_get_logmsg(&logmsg, commit);
3946 if (err)
3947 goto done;
3949 if (regexec(regex, got_object_commit_get_author(commit), 1,
3950 &regmatch, 0) == 0 ||
3951 regexec(regex, got_object_commit_get_committer(commit), 1,
3952 &regmatch, 0) == 0 ||
3953 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3954 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3955 *have_match = 1;
3956 done:
3957 free(id_str);
3958 free(logmsg);
3959 return err;
3962 static void
3963 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3964 regex_t *regex)
3966 regmatch_t regmatch;
3967 struct got_pathlist_entry *pe;
3969 *have_match = 0;
3971 TAILQ_FOREACH(pe, changed_paths, entry) {
3972 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3973 *have_match = 1;
3974 break;
3979 static const struct got_error *
3980 match_patch(int *have_match, struct got_commit_object *commit,
3981 struct got_object_id *id, const char *path, int diff_context,
3982 struct got_repository *repo, regex_t *regex, FILE *f)
3984 const struct got_error *err = NULL;
3985 char *line = NULL;
3986 size_t linesize = 0;
3987 regmatch_t regmatch;
3989 *have_match = 0;
3991 err = got_opentemp_truncate(f);
3992 if (err)
3993 return err;
3995 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3996 if (err)
3997 goto done;
3999 if (fseeko(f, 0L, SEEK_SET) == -1) {
4000 err = got_error_from_errno("fseeko");
4001 goto done;
4004 while (getline(&line, &linesize, f) != -1) {
4005 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4006 *have_match = 1;
4007 break;
4010 done:
4011 free(line);
4012 return err;
4015 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4017 static const struct got_error*
4018 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4019 struct got_object_id *id, struct got_repository *repo,
4020 int local_only)
4022 static const struct got_error *err = NULL;
4023 struct got_reflist_entry *re;
4024 char *s;
4025 const char *name;
4027 *refs_str = NULL;
4029 TAILQ_FOREACH(re, refs, entry) {
4030 struct got_tag_object *tag = NULL;
4031 struct got_object_id *ref_id;
4032 int cmp;
4034 name = got_ref_get_name(re->ref);
4035 if (strcmp(name, GOT_REF_HEAD) == 0)
4036 continue;
4037 if (strncmp(name, "refs/", 5) == 0)
4038 name += 5;
4039 if (strncmp(name, "got/", 4) == 0)
4040 continue;
4041 if (strncmp(name, "heads/", 6) == 0)
4042 name += 6;
4043 if (strncmp(name, "remotes/", 8) == 0) {
4044 if (local_only)
4045 continue;
4046 name += 8;
4047 s = strstr(name, "/" GOT_REF_HEAD);
4048 if (s != NULL && s[strlen(s)] == '\0')
4049 continue;
4051 err = got_ref_resolve(&ref_id, repo, re->ref);
4052 if (err)
4053 break;
4054 if (strncmp(name, "tags/", 5) == 0) {
4055 err = got_object_open_as_tag(&tag, repo, ref_id);
4056 if (err) {
4057 if (err->code != GOT_ERR_OBJ_TYPE) {
4058 free(ref_id);
4059 break;
4061 /* Ref points at something other than a tag. */
4062 err = NULL;
4063 tag = NULL;
4066 cmp = got_object_id_cmp(tag ?
4067 got_object_tag_get_object_id(tag) : ref_id, id);
4068 free(ref_id);
4069 if (tag)
4070 got_object_tag_close(tag);
4071 if (cmp != 0)
4072 continue;
4073 s = *refs_str;
4074 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4075 s ? ", " : "", name) == -1) {
4076 err = got_error_from_errno("asprintf");
4077 free(s);
4078 *refs_str = NULL;
4079 break;
4081 free(s);
4084 return err;
4087 static const struct got_error *
4088 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4089 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4091 const struct got_error *err = NULL;
4092 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4093 char *comma, *s, *nl;
4094 struct got_reflist_head *refs;
4095 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4096 struct tm tm;
4097 time_t committer_time;
4099 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4100 if (refs) {
4101 err = build_refs_str(&ref_str, refs, id, repo, 1);
4102 if (err)
4103 return err;
4105 /* Display the first matching ref only. */
4106 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4107 *comma = '\0';
4110 if (ref_str == NULL) {
4111 err = got_object_id_str(&id_str, id);
4112 if (err)
4113 return err;
4116 committer_time = got_object_commit_get_committer_time(commit);
4117 if (gmtime_r(&committer_time, &tm) == NULL) {
4118 err = got_error_from_errno("gmtime_r");
4119 goto done;
4121 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4122 err = got_error(GOT_ERR_NO_SPACE);
4123 goto done;
4126 err = got_object_commit_get_logmsg(&logmsg0, commit);
4127 if (err)
4128 goto done;
4130 s = logmsg0;
4131 while (isspace((unsigned char)s[0]))
4132 s++;
4134 nl = strchr(s, '\n');
4135 if (nl) {
4136 *nl = '\0';
4139 if (ref_str)
4140 printf("%s%-7s %s\n", datebuf, ref_str, s);
4141 else
4142 printf("%s%.7s %s\n", datebuf, id_str, s);
4144 if (fflush(stdout) != 0 && err == NULL)
4145 err = got_error_from_errno("fflush");
4146 done:
4147 free(id_str);
4148 free(ref_str);
4149 free(logmsg0);
4150 return err;
4153 static const struct got_error *
4154 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4156 struct got_pathlist_entry *pe;
4158 if (header != NULL)
4159 printf("%s\n", header);
4161 TAILQ_FOREACH(pe, dsa->paths, entry) {
4162 struct got_diff_changed_path *cp = pe->data;
4163 int pad = dsa->max_path_len - pe->path_len + 1;
4165 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4166 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4168 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4169 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4170 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4172 if (fflush(stdout) != 0)
4173 return got_error_from_errno("fflush");
4175 return NULL;
4178 static const struct got_error *
4179 printfile(FILE *f)
4181 char buf[8192];
4182 size_t r;
4184 if (fseeko(f, 0L, SEEK_SET) == -1)
4185 return got_error_from_errno("fseek");
4187 for (;;) {
4188 r = fread(buf, 1, sizeof(buf), f);
4189 if (r == 0) {
4190 if (ferror(f))
4191 return got_error_from_errno("fread");
4192 if (feof(f))
4193 break;
4195 if (fwrite(buf, 1, r, stdout) != r)
4196 return got_ferror(stdout, GOT_ERR_IO);
4199 return NULL;
4202 static const struct got_error *
4203 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4204 struct got_repository *repo, const char *path,
4205 struct got_pathlist_head *changed_paths,
4206 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4207 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4208 const char *prefix)
4210 const struct got_error *err = NULL;
4211 FILE *f = NULL;
4212 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4213 char datebuf[26];
4214 time_t committer_time;
4215 const char *author, *committer;
4216 char *refs_str = NULL;
4218 err = got_object_id_str(&id_str, id);
4219 if (err)
4220 return err;
4222 if (custom_refs_str == NULL) {
4223 struct got_reflist_head *refs;
4224 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4225 if (refs) {
4226 err = build_refs_str(&refs_str, refs, id, repo, 0);
4227 if (err)
4228 goto done;
4232 printf(GOT_COMMIT_SEP_STR);
4233 if (custom_refs_str)
4234 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4235 custom_refs_str);
4236 else
4237 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4238 refs_str ? " (" : "", refs_str ? refs_str : "",
4239 refs_str ? ")" : "");
4240 free(id_str);
4241 id_str = NULL;
4242 free(refs_str);
4243 refs_str = NULL;
4244 printf("from: %s\n", got_object_commit_get_author(commit));
4245 author = got_object_commit_get_author(commit);
4246 committer = got_object_commit_get_committer(commit);
4247 if (strcmp(author, committer) != 0)
4248 printf("via: %s\n", committer);
4249 committer_time = got_object_commit_get_committer_time(commit);
4250 datestr = get_datestr(&committer_time, datebuf);
4251 if (datestr)
4252 printf("date: %s UTC\n", datestr);
4253 if (got_object_commit_get_nparents(commit) > 1) {
4254 const struct got_object_id_queue *parent_ids;
4255 struct got_object_qid *qid;
4256 int n = 1;
4257 parent_ids = got_object_commit_get_parent_ids(commit);
4258 STAILQ_FOREACH(qid, parent_ids, entry) {
4259 err = got_object_id_str(&id_str, &qid->id);
4260 if (err)
4261 goto done;
4262 printf("parent %d: %s\n", n++, id_str);
4263 free(id_str);
4264 id_str = NULL;
4268 err = got_object_commit_get_logmsg(&logmsg0, commit);
4269 if (err)
4270 goto done;
4272 logmsg = logmsg0;
4273 do {
4274 line = strsep(&logmsg, "\n");
4275 if (line)
4276 printf(" %s\n", line);
4277 } while (line);
4278 free(logmsg0);
4280 if (changed_paths && diffstat == NULL) {
4281 struct got_pathlist_entry *pe;
4283 TAILQ_FOREACH(pe, changed_paths, entry) {
4284 struct got_diff_changed_path *cp = pe->data;
4286 printf(" %c %s\n", cp->status, pe->path);
4288 printf("\n");
4290 if (show_patch) {
4291 if (diffstat) {
4292 f = got_opentemp();
4293 if (f == NULL) {
4294 err = got_error_from_errno("got_opentemp");
4295 goto done;
4299 err = print_patch(commit, id, path, diff_context, diffstat,
4300 repo, diffstat == NULL ? stdout : f);
4301 if (err)
4302 goto done;
4304 if (diffstat) {
4305 err = print_diffstat(diffstat, NULL);
4306 if (err)
4307 goto done;
4308 if (show_patch) {
4309 err = printfile(f);
4310 if (err)
4311 goto done;
4314 if (show_patch)
4315 printf("\n");
4317 if (fflush(stdout) != 0 && err == NULL)
4318 err = got_error_from_errno("fflush");
4319 done:
4320 if (f && fclose(f) == EOF && err == NULL)
4321 err = got_error_from_errno("fclose");
4322 free(id_str);
4323 free(refs_str);
4324 return err;
4327 static const struct got_error *
4328 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4329 struct got_repository *repo, const char *path, int show_changed_paths,
4330 int show_diffstat, int show_patch, const char *search_pattern,
4331 int diff_context, int limit, int log_branches, int reverse_display_order,
4332 struct got_reflist_object_id_map *refs_idmap, int one_line,
4333 FILE *tmpfile)
4335 const struct got_error *err;
4336 struct got_commit_graph *graph;
4337 regex_t regex;
4338 int have_match;
4339 struct got_object_id_queue reversed_commits;
4340 struct got_object_qid *qid;
4341 struct got_commit_object *commit;
4342 struct got_pathlist_head changed_paths;
4344 STAILQ_INIT(&reversed_commits);
4345 TAILQ_INIT(&changed_paths);
4347 if (search_pattern && regcomp(&regex, search_pattern,
4348 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4349 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4351 err = got_commit_graph_open(&graph, path, !log_branches);
4352 if (err)
4353 return err;
4354 err = got_commit_graph_iter_start(graph, root_id, repo,
4355 check_cancelled, NULL);
4356 if (err)
4357 goto done;
4358 for (;;) {
4359 struct got_object_id id;
4360 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4361 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4363 if (sigint_received || sigpipe_received)
4364 break;
4366 err = got_commit_graph_iter_next(&id, graph, repo,
4367 check_cancelled, NULL);
4368 if (err) {
4369 if (err->code == GOT_ERR_ITER_COMPLETED)
4370 err = NULL;
4371 break;
4374 err = got_object_open_as_commit(&commit, repo, &id);
4375 if (err)
4376 break;
4378 if ((show_changed_paths || (show_diffstat && !show_patch))
4379 && !reverse_display_order) {
4380 err = get_changed_paths(&changed_paths, commit, repo,
4381 show_diffstat ? &dsa : NULL);
4382 if (err)
4383 break;
4386 if (search_pattern) {
4387 err = match_commit(&have_match, &id, commit, &regex);
4388 if (err) {
4389 got_object_commit_close(commit);
4390 break;
4392 if (have_match == 0 && show_changed_paths)
4393 match_changed_paths(&have_match,
4394 &changed_paths, &regex);
4395 if (have_match == 0 && show_patch) {
4396 err = match_patch(&have_match, commit, &id,
4397 path, diff_context, repo, &regex, tmpfile);
4398 if (err)
4399 break;
4401 if (have_match == 0) {
4402 got_object_commit_close(commit);
4403 got_pathlist_free(&changed_paths,
4404 GOT_PATHLIST_FREE_ALL);
4405 continue;
4409 if (reverse_display_order) {
4410 err = got_object_qid_alloc(&qid, &id);
4411 if (err)
4412 break;
4413 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4414 got_object_commit_close(commit);
4415 } else {
4416 if (one_line)
4417 err = print_commit_oneline(commit, &id,
4418 repo, refs_idmap);
4419 else
4420 err = print_commit(commit, &id, repo, path,
4421 (show_changed_paths || show_diffstat) ?
4422 &changed_paths : NULL,
4423 show_diffstat ? &dsa : NULL, show_patch,
4424 diff_context, refs_idmap, NULL, NULL);
4425 got_object_commit_close(commit);
4426 if (err)
4427 break;
4429 if ((limit && --limit == 0) ||
4430 (end_id && got_object_id_cmp(&id, end_id) == 0))
4431 break;
4433 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4435 if (reverse_display_order) {
4436 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4437 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4438 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4440 err = got_object_open_as_commit(&commit, repo,
4441 &qid->id);
4442 if (err)
4443 break;
4444 if (show_changed_paths ||
4445 (show_diffstat && !show_patch)) {
4446 err = get_changed_paths(&changed_paths, commit,
4447 repo, show_diffstat ? &dsa : NULL);
4448 if (err)
4449 break;
4451 if (one_line)
4452 err = print_commit_oneline(commit, &qid->id,
4453 repo, refs_idmap);
4454 else
4455 err = print_commit(commit, &qid->id, repo, path,
4456 (show_changed_paths || show_diffstat) ?
4457 &changed_paths : NULL,
4458 show_diffstat ? &dsa : NULL, show_patch,
4459 diff_context, refs_idmap, NULL, NULL);
4460 got_object_commit_close(commit);
4461 if (err)
4462 break;
4463 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4466 done:
4467 while (!STAILQ_EMPTY(&reversed_commits)) {
4468 qid = STAILQ_FIRST(&reversed_commits);
4469 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4470 got_object_qid_free(qid);
4472 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4473 if (search_pattern)
4474 regfree(&regex);
4475 got_commit_graph_close(graph);
4476 return err;
4479 __dead static void
4480 usage_log(void)
4482 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4483 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4484 "[path]\n", getprogname());
4485 exit(1);
4488 static int
4489 get_default_log_limit(void)
4491 const char *got_default_log_limit;
4492 long long n;
4493 const char *errstr;
4495 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4496 if (got_default_log_limit == NULL)
4497 return 0;
4498 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4499 if (errstr != NULL)
4500 return 0;
4501 return n;
4504 static const struct got_error *
4505 cmd_log(int argc, char *argv[])
4507 const struct got_error *error;
4508 struct got_repository *repo = NULL;
4509 struct got_worktree *worktree = NULL;
4510 struct got_object_id *start_id = NULL, *end_id = NULL;
4511 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4512 const char *start_commit = NULL, *end_commit = NULL;
4513 const char *search_pattern = NULL;
4514 int diff_context = -1, ch;
4515 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4516 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4517 const char *errstr;
4518 struct got_reflist_head refs;
4519 struct got_reflist_object_id_map *refs_idmap = NULL;
4520 FILE *tmpfile = NULL;
4521 int *pack_fds = NULL;
4523 TAILQ_INIT(&refs);
4525 #ifndef PROFILE
4526 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4527 NULL)
4528 == -1)
4529 err(1, "pledge");
4530 #endif
4532 limit = get_default_log_limit();
4534 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4535 switch (ch) {
4536 case 'b':
4537 log_branches = 1;
4538 break;
4539 case 'C':
4540 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4541 &errstr);
4542 if (errstr != NULL)
4543 errx(1, "number of context lines is %s: %s",
4544 errstr, optarg);
4545 break;
4546 case 'c':
4547 start_commit = optarg;
4548 break;
4549 case 'd':
4550 show_diffstat = 1;
4551 break;
4552 case 'l':
4553 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4554 if (errstr != NULL)
4555 errx(1, "number of commits is %s: %s",
4556 errstr, optarg);
4557 break;
4558 case 'P':
4559 show_changed_paths = 1;
4560 break;
4561 case 'p':
4562 show_patch = 1;
4563 break;
4564 case 'R':
4565 reverse_display_order = 1;
4566 break;
4567 case 'r':
4568 repo_path = realpath(optarg, NULL);
4569 if (repo_path == NULL)
4570 return got_error_from_errno2("realpath",
4571 optarg);
4572 got_path_strip_trailing_slashes(repo_path);
4573 break;
4574 case 'S':
4575 search_pattern = optarg;
4576 break;
4577 case 's':
4578 one_line = 1;
4579 break;
4580 case 'x':
4581 end_commit = optarg;
4582 break;
4583 default:
4584 usage_log();
4585 /* NOTREACHED */
4589 argc -= optind;
4590 argv += optind;
4592 if (diff_context == -1)
4593 diff_context = 3;
4594 else if (!show_patch)
4595 errx(1, "-C requires -p");
4597 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4598 errx(1, "cannot use -s with -d, -p or -P");
4600 cwd = getcwd(NULL, 0);
4601 if (cwd == NULL) {
4602 error = got_error_from_errno("getcwd");
4603 goto done;
4606 error = got_repo_pack_fds_open(&pack_fds);
4607 if (error != NULL)
4608 goto done;
4610 if (repo_path == NULL) {
4611 error = got_worktree_open(&worktree, cwd);
4612 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4613 goto done;
4614 error = NULL;
4617 if (argc == 1) {
4618 if (worktree) {
4619 error = got_worktree_resolve_path(&path, worktree,
4620 argv[0]);
4621 if (error)
4622 goto done;
4623 } else {
4624 path = strdup(argv[0]);
4625 if (path == NULL) {
4626 error = got_error_from_errno("strdup");
4627 goto done;
4630 } else if (argc != 0)
4631 usage_log();
4633 if (repo_path == NULL) {
4634 repo_path = worktree ?
4635 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4637 if (repo_path == NULL) {
4638 error = got_error_from_errno("strdup");
4639 goto done;
4642 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4643 if (error != NULL)
4644 goto done;
4646 error = apply_unveil(got_repo_get_path(repo), 1,
4647 worktree ? got_worktree_get_root_path(worktree) : NULL);
4648 if (error)
4649 goto done;
4651 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4652 if (error)
4653 goto done;
4655 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4656 if (error)
4657 goto done;
4659 if (start_commit == NULL) {
4660 struct got_reference *head_ref;
4661 struct got_commit_object *commit = NULL;
4662 error = got_ref_open(&head_ref, repo,
4663 worktree ? got_worktree_get_head_ref_name(worktree)
4664 : GOT_REF_HEAD, 0);
4665 if (error != NULL)
4666 goto done;
4667 error = got_ref_resolve(&start_id, repo, head_ref);
4668 got_ref_close(head_ref);
4669 if (error != NULL)
4670 goto done;
4671 error = got_object_open_as_commit(&commit, repo,
4672 start_id);
4673 if (error != NULL)
4674 goto done;
4675 got_object_commit_close(commit);
4676 } else {
4677 error = got_repo_match_object_id(&start_id, NULL,
4678 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4679 if (error != NULL)
4680 goto done;
4682 if (end_commit != NULL) {
4683 error = got_repo_match_object_id(&end_id, NULL,
4684 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4685 if (error != NULL)
4686 goto done;
4689 if (worktree) {
4691 * If a path was specified on the command line it was resolved
4692 * to a path in the work tree above. Prepend the work tree's
4693 * path prefix to obtain the corresponding in-repository path.
4695 if (path) {
4696 const char *prefix;
4697 prefix = got_worktree_get_path_prefix(worktree);
4698 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4699 (path[0] != '\0') ? "/" : "", path) == -1) {
4700 error = got_error_from_errno("asprintf");
4701 goto done;
4704 } else
4705 error = got_repo_map_path(&in_repo_path, repo,
4706 path ? path : "");
4707 if (error != NULL)
4708 goto done;
4709 if (in_repo_path) {
4710 free(path);
4711 path = in_repo_path;
4714 if (worktree) {
4715 /* Release work tree lock. */
4716 got_worktree_close(worktree);
4717 worktree = NULL;
4720 if (search_pattern && show_patch) {
4721 tmpfile = got_opentemp();
4722 if (tmpfile == NULL) {
4723 error = got_error_from_errno("got_opentemp");
4724 goto done;
4728 error = print_commits(start_id, end_id, repo, path ? path : "",
4729 show_changed_paths, show_diffstat, show_patch, search_pattern,
4730 diff_context, limit, log_branches, reverse_display_order,
4731 refs_idmap, one_line, tmpfile);
4732 done:
4733 free(path);
4734 free(repo_path);
4735 free(cwd);
4736 if (worktree)
4737 got_worktree_close(worktree);
4738 if (repo) {
4739 const struct got_error *close_err = got_repo_close(repo);
4740 if (error == NULL)
4741 error = close_err;
4743 if (pack_fds) {
4744 const struct got_error *pack_err =
4745 got_repo_pack_fds_close(pack_fds);
4746 if (error == NULL)
4747 error = pack_err;
4749 if (refs_idmap)
4750 got_reflist_object_id_map_free(refs_idmap);
4751 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4752 error = got_error_from_errno("fclose");
4753 got_ref_list_free(&refs);
4754 return error;
4757 __dead static void
4758 usage_diff(void)
4760 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4761 "[-r repository-path] [object1 object2 | path ...]\n",
4762 getprogname());
4763 exit(1);
4766 struct print_diff_arg {
4767 struct got_repository *repo;
4768 struct got_worktree *worktree;
4769 struct got_diffstat_cb_arg *diffstat;
4770 int diff_context;
4771 const char *id_str;
4772 int header_shown;
4773 int diff_staged;
4774 enum got_diff_algorithm diff_algo;
4775 int ignore_whitespace;
4776 int force_text_diff;
4777 FILE *f1;
4778 FILE *f2;
4779 FILE *outfile;
4783 * Create a file which contains the target path of a symlink so we can feed
4784 * it as content to the diff engine.
4786 static const struct got_error *
4787 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4788 const char *abspath)
4790 const struct got_error *err = NULL;
4791 char target_path[PATH_MAX];
4792 ssize_t target_len, outlen;
4794 *fd = -1;
4796 if (dirfd != -1) {
4797 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4798 if (target_len == -1)
4799 return got_error_from_errno2("readlinkat", abspath);
4800 } else {
4801 target_len = readlink(abspath, target_path, PATH_MAX);
4802 if (target_len == -1)
4803 return got_error_from_errno2("readlink", abspath);
4806 *fd = got_opentempfd();
4807 if (*fd == -1)
4808 return got_error_from_errno("got_opentempfd");
4810 outlen = write(*fd, target_path, target_len);
4811 if (outlen == -1) {
4812 err = got_error_from_errno("got_opentempfd");
4813 goto done;
4816 if (lseek(*fd, 0, SEEK_SET) == -1) {
4817 err = got_error_from_errno2("lseek", abspath);
4818 goto done;
4820 done:
4821 if (err) {
4822 close(*fd);
4823 *fd = -1;
4825 return err;
4828 static const struct got_error *
4829 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4830 const char *path, struct got_object_id *blob_id,
4831 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4832 int dirfd, const char *de_name)
4834 struct print_diff_arg *a = arg;
4835 const struct got_error *err = NULL;
4836 struct got_blob_object *blob1 = NULL;
4837 int fd = -1, fd1 = -1, fd2 = -1;
4838 FILE *f2 = NULL;
4839 char *abspath = NULL, *label1 = NULL;
4840 struct stat sb;
4841 off_t size1 = 0;
4842 int f2_exists = 0;
4844 memset(&sb, 0, sizeof(sb));
4846 if (a->diff_staged) {
4847 if (staged_status != GOT_STATUS_MODIFY &&
4848 staged_status != GOT_STATUS_ADD &&
4849 staged_status != GOT_STATUS_DELETE)
4850 return NULL;
4851 } else {
4852 if (staged_status == GOT_STATUS_DELETE)
4853 return NULL;
4854 if (status == GOT_STATUS_NONEXISTENT)
4855 return got_error_set_errno(ENOENT, path);
4856 if (status != GOT_STATUS_MODIFY &&
4857 status != GOT_STATUS_ADD &&
4858 status != GOT_STATUS_DELETE &&
4859 status != GOT_STATUS_CONFLICT)
4860 return NULL;
4863 err = got_opentemp_truncate(a->f1);
4864 if (err)
4865 return got_error_from_errno("got_opentemp_truncate");
4866 err = got_opentemp_truncate(a->f2);
4867 if (err)
4868 return got_error_from_errno("got_opentemp_truncate");
4870 if (!a->header_shown) {
4871 if (fprintf(a->outfile, "diff %s%s\n",
4872 a->diff_staged ? "-s " : "",
4873 got_worktree_get_root_path(a->worktree)) < 0) {
4874 err = got_error_from_errno("fprintf");
4875 goto done;
4877 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4878 err = got_error_from_errno("fprintf");
4879 goto done;
4881 if (fprintf(a->outfile, "path + %s%s\n",
4882 got_worktree_get_root_path(a->worktree),
4883 a->diff_staged ? " (staged changes)" : "") < 0) {
4884 err = got_error_from_errno("fprintf");
4885 goto done;
4887 a->header_shown = 1;
4890 if (a->diff_staged) {
4891 const char *label1 = NULL, *label2 = NULL;
4892 switch (staged_status) {
4893 case GOT_STATUS_MODIFY:
4894 label1 = path;
4895 label2 = path;
4896 break;
4897 case GOT_STATUS_ADD:
4898 label2 = path;
4899 break;
4900 case GOT_STATUS_DELETE:
4901 label1 = path;
4902 break;
4903 default:
4904 return got_error(GOT_ERR_FILE_STATUS);
4906 fd1 = got_opentempfd();
4907 if (fd1 == -1) {
4908 err = got_error_from_errno("got_opentempfd");
4909 goto done;
4911 fd2 = got_opentempfd();
4912 if (fd2 == -1) {
4913 err = got_error_from_errno("got_opentempfd");
4914 goto done;
4916 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4917 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4918 a->diff_algo, a->diff_context, a->ignore_whitespace,
4919 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4920 goto done;
4923 fd1 = got_opentempfd();
4924 if (fd1 == -1) {
4925 err = got_error_from_errno("got_opentempfd");
4926 goto done;
4929 if (staged_status == GOT_STATUS_ADD ||
4930 staged_status == GOT_STATUS_MODIFY) {
4931 char *id_str;
4932 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4933 8192, fd1);
4934 if (err)
4935 goto done;
4936 err = got_object_id_str(&id_str, staged_blob_id);
4937 if (err)
4938 goto done;
4939 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4940 err = got_error_from_errno("asprintf");
4941 free(id_str);
4942 goto done;
4944 free(id_str);
4945 } else if (status != GOT_STATUS_ADD) {
4946 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4947 fd1);
4948 if (err)
4949 goto done;
4952 if (status != GOT_STATUS_DELETE) {
4953 if (asprintf(&abspath, "%s/%s",
4954 got_worktree_get_root_path(a->worktree), path) == -1) {
4955 err = got_error_from_errno("asprintf");
4956 goto done;
4959 if (dirfd != -1) {
4960 fd = openat(dirfd, de_name,
4961 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4962 if (fd == -1) {
4963 if (!got_err_open_nofollow_on_symlink()) {
4964 err = got_error_from_errno2("openat",
4965 abspath);
4966 goto done;
4968 err = get_symlink_target_file(&fd, dirfd,
4969 de_name, abspath);
4970 if (err)
4971 goto done;
4973 } else {
4974 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4975 if (fd == -1) {
4976 if (!got_err_open_nofollow_on_symlink()) {
4977 err = got_error_from_errno2("open",
4978 abspath);
4979 goto done;
4981 err = get_symlink_target_file(&fd, dirfd,
4982 de_name, abspath);
4983 if (err)
4984 goto done;
4987 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4988 err = got_error_from_errno2("fstatat", abspath);
4989 goto done;
4991 f2 = fdopen(fd, "r");
4992 if (f2 == NULL) {
4993 err = got_error_from_errno2("fdopen", abspath);
4994 goto done;
4996 fd = -1;
4997 f2_exists = 1;
5000 if (blob1) {
5001 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5002 a->f1, blob1);
5003 if (err)
5004 goto done;
5007 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5008 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5009 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5010 done:
5011 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5012 err = got_error_from_errno("close");
5013 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5014 err = got_error_from_errno("close");
5015 if (blob1)
5016 got_object_blob_close(blob1);
5017 if (fd != -1 && close(fd) == -1 && err == NULL)
5018 err = got_error_from_errno("close");
5019 if (f2 && fclose(f2) == EOF && err == NULL)
5020 err = got_error_from_errno("fclose");
5021 free(abspath);
5022 return err;
5025 static const struct got_error *
5026 cmd_diff(int argc, char *argv[])
5028 const struct got_error *error;
5029 struct got_repository *repo = NULL;
5030 struct got_worktree *worktree = NULL;
5031 char *cwd = NULL, *repo_path = NULL;
5032 const char *commit_args[2] = { NULL, NULL };
5033 int ncommit_args = 0;
5034 struct got_object_id *ids[2] = { NULL, NULL };
5035 char *labels[2] = { NULL, NULL };
5036 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5037 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5038 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5039 const char *errstr;
5040 struct got_reflist_head refs;
5041 struct got_pathlist_head diffstat_paths, paths;
5042 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5043 int fd1 = -1, fd2 = -1;
5044 int *pack_fds = NULL;
5045 struct got_diffstat_cb_arg dsa;
5047 memset(&dsa, 0, sizeof(dsa));
5049 TAILQ_INIT(&refs);
5050 TAILQ_INIT(&paths);
5051 TAILQ_INIT(&diffstat_paths);
5053 #ifndef PROFILE
5054 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5055 NULL) == -1)
5056 err(1, "pledge");
5057 #endif
5059 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5060 switch (ch) {
5061 case 'a':
5062 force_text_diff = 1;
5063 break;
5064 case 'C':
5065 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5066 &errstr);
5067 if (errstr != NULL)
5068 errx(1, "number of context lines is %s: %s",
5069 errstr, optarg);
5070 break;
5071 case 'c':
5072 if (ncommit_args >= 2)
5073 errx(1, "too many -c options used");
5074 commit_args[ncommit_args++] = optarg;
5075 break;
5076 case 'd':
5077 show_diffstat = 1;
5078 break;
5079 case 'P':
5080 force_path = 1;
5081 break;
5082 case 'r':
5083 repo_path = realpath(optarg, NULL);
5084 if (repo_path == NULL)
5085 return got_error_from_errno2("realpath",
5086 optarg);
5087 got_path_strip_trailing_slashes(repo_path);
5088 rflag = 1;
5089 break;
5090 case 's':
5091 diff_staged = 1;
5092 break;
5093 case 'w':
5094 ignore_whitespace = 1;
5095 break;
5096 default:
5097 usage_diff();
5098 /* NOTREACHED */
5102 argc -= optind;
5103 argv += optind;
5105 cwd = getcwd(NULL, 0);
5106 if (cwd == NULL) {
5107 error = got_error_from_errno("getcwd");
5108 goto done;
5111 error = got_repo_pack_fds_open(&pack_fds);
5112 if (error != NULL)
5113 goto done;
5115 if (repo_path == NULL) {
5116 error = got_worktree_open(&worktree, cwd);
5117 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5118 goto done;
5119 else
5120 error = NULL;
5121 if (worktree) {
5122 repo_path =
5123 strdup(got_worktree_get_repo_path(worktree));
5124 if (repo_path == NULL) {
5125 error = got_error_from_errno("strdup");
5126 goto done;
5128 } else {
5129 repo_path = strdup(cwd);
5130 if (repo_path == NULL) {
5131 error = got_error_from_errno("strdup");
5132 goto done;
5137 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5138 free(repo_path);
5139 if (error != NULL)
5140 goto done;
5142 if (show_diffstat) {
5143 dsa.paths = &diffstat_paths;
5144 dsa.force_text = force_text_diff;
5145 dsa.ignore_ws = ignore_whitespace;
5146 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5149 if (rflag || worktree == NULL || ncommit_args > 0) {
5150 if (force_path) {
5151 error = got_error_msg(GOT_ERR_NOT_IMPL,
5152 "-P option can only be used when diffing "
5153 "a work tree");
5154 goto done;
5156 if (diff_staged) {
5157 error = got_error_msg(GOT_ERR_NOT_IMPL,
5158 "-s option can only be used when diffing "
5159 "a work tree");
5160 goto done;
5164 error = apply_unveil(got_repo_get_path(repo), 1,
5165 worktree ? got_worktree_get_root_path(worktree) : NULL);
5166 if (error)
5167 goto done;
5169 if ((!force_path && argc == 2) || ncommit_args > 0) {
5170 int obj_type = (ncommit_args > 0 ?
5171 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5172 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5173 NULL);
5174 if (error)
5175 goto done;
5176 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5177 const char *arg;
5178 if (ncommit_args > 0)
5179 arg = commit_args[i];
5180 else
5181 arg = argv[i];
5182 error = got_repo_match_object_id(&ids[i], &labels[i],
5183 arg, obj_type, &refs, repo);
5184 if (error) {
5185 if (error->code != GOT_ERR_NOT_REF &&
5186 error->code != GOT_ERR_NO_OBJ)
5187 goto done;
5188 if (ncommit_args > 0)
5189 goto done;
5190 error = NULL;
5191 break;
5196 f1 = got_opentemp();
5197 if (f1 == NULL) {
5198 error = got_error_from_errno("got_opentemp");
5199 goto done;
5202 f2 = got_opentemp();
5203 if (f2 == NULL) {
5204 error = got_error_from_errno("got_opentemp");
5205 goto done;
5208 outfile = got_opentemp();
5209 if (outfile == NULL) {
5210 error = got_error_from_errno("got_opentemp");
5211 goto done;
5214 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5215 struct print_diff_arg arg;
5216 char *id_str;
5218 if (worktree == NULL) {
5219 if (argc == 2 && ids[0] == NULL) {
5220 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5221 goto done;
5222 } else if (argc == 2 && ids[1] == NULL) {
5223 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5224 goto done;
5225 } else if (argc > 0) {
5226 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5227 "%s", "specified paths cannot be resolved");
5228 goto done;
5229 } else {
5230 error = got_error(GOT_ERR_NOT_WORKTREE);
5231 goto done;
5235 error = get_worktree_paths_from_argv(&paths, argc, argv,
5236 worktree);
5237 if (error)
5238 goto done;
5240 error = got_object_id_str(&id_str,
5241 got_worktree_get_base_commit_id(worktree));
5242 if (error)
5243 goto done;
5244 arg.repo = repo;
5245 arg.worktree = worktree;
5246 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5247 arg.diff_context = diff_context;
5248 arg.id_str = id_str;
5249 arg.header_shown = 0;
5250 arg.diff_staged = diff_staged;
5251 arg.ignore_whitespace = ignore_whitespace;
5252 arg.force_text_diff = force_text_diff;
5253 arg.diffstat = show_diffstat ? &dsa : NULL;
5254 arg.f1 = f1;
5255 arg.f2 = f2;
5256 arg.outfile = outfile;
5258 error = got_worktree_status(worktree, &paths, repo, 0,
5259 print_diff, &arg, check_cancelled, NULL);
5260 free(id_str);
5261 if (error)
5262 goto done;
5264 if (show_diffstat && dsa.nfiles > 0) {
5265 char *header;
5267 if (asprintf(&header, "diffstat %s%s",
5268 diff_staged ? "-s " : "",
5269 got_worktree_get_root_path(worktree)) == -1) {
5270 error = got_error_from_errno("asprintf");
5271 goto done;
5274 error = print_diffstat(&dsa, header);
5275 free(header);
5276 if (error)
5277 goto done;
5280 error = printfile(outfile);
5281 goto done;
5284 if (ncommit_args == 1) {
5285 struct got_commit_object *commit;
5286 error = got_object_open_as_commit(&commit, repo, ids[0]);
5287 if (error)
5288 goto done;
5290 labels[1] = labels[0];
5291 ids[1] = ids[0];
5292 if (got_object_commit_get_nparents(commit) > 0) {
5293 const struct got_object_id_queue *pids;
5294 struct got_object_qid *pid;
5295 pids = got_object_commit_get_parent_ids(commit);
5296 pid = STAILQ_FIRST(pids);
5297 ids[0] = got_object_id_dup(&pid->id);
5298 if (ids[0] == NULL) {
5299 error = got_error_from_errno(
5300 "got_object_id_dup");
5301 got_object_commit_close(commit);
5302 goto done;
5304 error = got_object_id_str(&labels[0], ids[0]);
5305 if (error) {
5306 got_object_commit_close(commit);
5307 goto done;
5309 } else {
5310 ids[0] = NULL;
5311 labels[0] = strdup("/dev/null");
5312 if (labels[0] == NULL) {
5313 error = got_error_from_errno("strdup");
5314 got_object_commit_close(commit);
5315 goto done;
5319 got_object_commit_close(commit);
5322 if (ncommit_args == 0 && argc > 2) {
5323 error = got_error_msg(GOT_ERR_BAD_PATH,
5324 "path arguments cannot be used when diffing two objects");
5325 goto done;
5328 if (ids[0]) {
5329 error = got_object_get_type(&type1, repo, ids[0]);
5330 if (error)
5331 goto done;
5334 error = got_object_get_type(&type2, repo, ids[1]);
5335 if (error)
5336 goto done;
5337 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5338 error = got_error(GOT_ERR_OBJ_TYPE);
5339 goto done;
5341 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5342 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5343 "path arguments cannot be used when diffing blobs");
5344 goto done;
5347 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5348 char *in_repo_path;
5349 struct got_pathlist_entry *new;
5350 if (worktree) {
5351 const char *prefix;
5352 char *p;
5353 error = got_worktree_resolve_path(&p, worktree,
5354 argv[i]);
5355 if (error)
5356 goto done;
5357 prefix = got_worktree_get_path_prefix(worktree);
5358 while (prefix[0] == '/')
5359 prefix++;
5360 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5361 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5362 p) == -1) {
5363 error = got_error_from_errno("asprintf");
5364 free(p);
5365 goto done;
5367 free(p);
5368 } else {
5369 char *mapped_path, *s;
5370 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5371 if (error)
5372 goto done;
5373 s = mapped_path;
5374 while (s[0] == '/')
5375 s++;
5376 in_repo_path = strdup(s);
5377 if (in_repo_path == NULL) {
5378 error = got_error_from_errno("asprintf");
5379 free(mapped_path);
5380 goto done;
5382 free(mapped_path);
5385 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5386 if (error || new == NULL /* duplicate */)
5387 free(in_repo_path);
5388 if (error)
5389 goto done;
5392 if (worktree) {
5393 /* Release work tree lock. */
5394 got_worktree_close(worktree);
5395 worktree = NULL;
5398 fd1 = got_opentempfd();
5399 if (fd1 == -1) {
5400 error = got_error_from_errno("got_opentempfd");
5401 goto done;
5404 fd2 = got_opentempfd();
5405 if (fd2 == -1) {
5406 error = got_error_from_errno("got_opentempfd");
5407 goto done;
5410 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5411 case GOT_OBJ_TYPE_BLOB:
5412 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5413 fd1, fd2, ids[0], ids[1], NULL, NULL,
5414 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5415 ignore_whitespace, force_text_diff,
5416 show_diffstat ? &dsa : NULL, repo, outfile);
5417 break;
5418 case GOT_OBJ_TYPE_TREE:
5419 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5420 ids[0], ids[1], &paths, "", "",
5421 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5422 ignore_whitespace, force_text_diff,
5423 show_diffstat ? &dsa : NULL, repo, outfile);
5424 break;
5425 case GOT_OBJ_TYPE_COMMIT:
5426 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5427 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5428 fd1, fd2, ids[0], ids[1], &paths,
5429 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5430 ignore_whitespace, force_text_diff,
5431 show_diffstat ? &dsa : NULL, repo, outfile);
5432 break;
5433 default:
5434 error = got_error(GOT_ERR_OBJ_TYPE);
5436 if (error)
5437 goto done;
5439 if (show_diffstat && dsa.nfiles > 0) {
5440 char *header = NULL;
5442 if (asprintf(&header, "diffstat %s %s",
5443 labels[0], labels[1]) == -1) {
5444 error = got_error_from_errno("asprintf");
5445 goto done;
5448 error = print_diffstat(&dsa, header);
5449 free(header);
5450 if (error)
5451 goto done;
5454 error = printfile(outfile);
5456 done:
5457 free(labels[0]);
5458 free(labels[1]);
5459 free(ids[0]);
5460 free(ids[1]);
5461 if (worktree)
5462 got_worktree_close(worktree);
5463 if (repo) {
5464 const struct got_error *close_err = got_repo_close(repo);
5465 if (error == NULL)
5466 error = close_err;
5468 if (pack_fds) {
5469 const struct got_error *pack_err =
5470 got_repo_pack_fds_close(pack_fds);
5471 if (error == NULL)
5472 error = pack_err;
5474 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5475 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5476 got_ref_list_free(&refs);
5477 if (outfile && fclose(outfile) == EOF && error == NULL)
5478 error = got_error_from_errno("fclose");
5479 if (f1 && fclose(f1) == EOF && error == NULL)
5480 error = got_error_from_errno("fclose");
5481 if (f2 && fclose(f2) == EOF && error == NULL)
5482 error = got_error_from_errno("fclose");
5483 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5484 error = got_error_from_errno("close");
5485 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5486 error = got_error_from_errno("close");
5487 return error;
5490 __dead static void
5491 usage_blame(void)
5493 fprintf(stderr,
5494 "usage: %s blame [-c commit] [-r repository-path] path\n",
5495 getprogname());
5496 exit(1);
5499 struct blame_line {
5500 int annotated;
5501 char *id_str;
5502 char *committer;
5503 char datebuf[11]; /* YYYY-MM-DD + NUL */
5506 struct blame_cb_args {
5507 struct blame_line *lines;
5508 int nlines;
5509 int nlines_prec;
5510 int lineno_cur;
5511 off_t *line_offsets;
5512 FILE *f;
5513 struct got_repository *repo;
5516 static const struct got_error *
5517 blame_cb(void *arg, int nlines, int lineno,
5518 struct got_commit_object *commit, struct got_object_id *id)
5520 const struct got_error *err = NULL;
5521 struct blame_cb_args *a = arg;
5522 struct blame_line *bline;
5523 char *line = NULL;
5524 size_t linesize = 0;
5525 off_t offset;
5526 struct tm tm;
5527 time_t committer_time;
5529 if (nlines != a->nlines ||
5530 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5531 return got_error(GOT_ERR_RANGE);
5533 if (sigint_received)
5534 return got_error(GOT_ERR_ITER_COMPLETED);
5536 if (lineno == -1)
5537 return NULL; /* no change in this commit */
5539 /* Annotate this line. */
5540 bline = &a->lines[lineno - 1];
5541 if (bline->annotated)
5542 return NULL;
5543 err = got_object_id_str(&bline->id_str, id);
5544 if (err)
5545 return err;
5547 bline->committer = strdup(got_object_commit_get_committer(commit));
5548 if (bline->committer == NULL) {
5549 err = got_error_from_errno("strdup");
5550 goto done;
5553 committer_time = got_object_commit_get_committer_time(commit);
5554 if (gmtime_r(&committer_time, &tm) == NULL)
5555 return got_error_from_errno("gmtime_r");
5556 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5557 &tm) == 0) {
5558 err = got_error(GOT_ERR_NO_SPACE);
5559 goto done;
5561 bline->annotated = 1;
5563 /* Print lines annotated so far. */
5564 bline = &a->lines[a->lineno_cur - 1];
5565 if (!bline->annotated)
5566 goto done;
5568 offset = a->line_offsets[a->lineno_cur - 1];
5569 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5570 err = got_error_from_errno("fseeko");
5571 goto done;
5574 while (a->lineno_cur <= a->nlines && bline->annotated) {
5575 char *smallerthan, *at, *nl, *committer;
5576 size_t len;
5578 if (getline(&line, &linesize, a->f) == -1) {
5579 if (ferror(a->f))
5580 err = got_error_from_errno("getline");
5581 break;
5584 committer = bline->committer;
5585 smallerthan = strchr(committer, '<');
5586 if (smallerthan && smallerthan[1] != '\0')
5587 committer = smallerthan + 1;
5588 at = strchr(committer, '@');
5589 if (at)
5590 *at = '\0';
5591 len = strlen(committer);
5592 if (len >= 9)
5593 committer[8] = '\0';
5595 nl = strchr(line, '\n');
5596 if (nl)
5597 *nl = '\0';
5598 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5599 bline->id_str, bline->datebuf, committer, line);
5601 a->lineno_cur++;
5602 bline = &a->lines[a->lineno_cur - 1];
5604 done:
5605 free(line);
5606 return err;
5609 static const struct got_error *
5610 cmd_blame(int argc, char *argv[])
5612 const struct got_error *error;
5613 struct got_repository *repo = NULL;
5614 struct got_worktree *worktree = NULL;
5615 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5616 char *link_target = NULL;
5617 struct got_object_id *obj_id = NULL;
5618 struct got_object_id *commit_id = NULL;
5619 struct got_commit_object *commit = NULL;
5620 struct got_blob_object *blob = NULL;
5621 char *commit_id_str = NULL;
5622 struct blame_cb_args bca;
5623 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5624 off_t filesize;
5625 int *pack_fds = NULL;
5626 FILE *f1 = NULL, *f2 = NULL;
5628 fd1 = got_opentempfd();
5629 if (fd1 == -1)
5630 return got_error_from_errno("got_opentempfd");
5632 memset(&bca, 0, sizeof(bca));
5634 #ifndef PROFILE
5635 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5636 NULL) == -1)
5637 err(1, "pledge");
5638 #endif
5640 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5641 switch (ch) {
5642 case 'c':
5643 commit_id_str = optarg;
5644 break;
5645 case 'r':
5646 repo_path = realpath(optarg, NULL);
5647 if (repo_path == NULL)
5648 return got_error_from_errno2("realpath",
5649 optarg);
5650 got_path_strip_trailing_slashes(repo_path);
5651 break;
5652 default:
5653 usage_blame();
5654 /* NOTREACHED */
5658 argc -= optind;
5659 argv += optind;
5661 if (argc == 1)
5662 path = argv[0];
5663 else
5664 usage_blame();
5666 cwd = getcwd(NULL, 0);
5667 if (cwd == NULL) {
5668 error = got_error_from_errno("getcwd");
5669 goto done;
5672 error = got_repo_pack_fds_open(&pack_fds);
5673 if (error != NULL)
5674 goto done;
5676 if (repo_path == NULL) {
5677 error = got_worktree_open(&worktree, cwd);
5678 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5679 goto done;
5680 else
5681 error = NULL;
5682 if (worktree) {
5683 repo_path =
5684 strdup(got_worktree_get_repo_path(worktree));
5685 if (repo_path == NULL) {
5686 error = got_error_from_errno("strdup");
5687 if (error)
5688 goto done;
5690 } else {
5691 repo_path = strdup(cwd);
5692 if (repo_path == NULL) {
5693 error = got_error_from_errno("strdup");
5694 goto done;
5699 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5700 if (error != NULL)
5701 goto done;
5703 if (worktree) {
5704 const char *prefix = got_worktree_get_path_prefix(worktree);
5705 char *p;
5707 error = got_worktree_resolve_path(&p, worktree, path);
5708 if (error)
5709 goto done;
5710 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5711 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5712 p) == -1) {
5713 error = got_error_from_errno("asprintf");
5714 free(p);
5715 goto done;
5717 free(p);
5718 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5719 } else {
5720 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5721 if (error)
5722 goto done;
5723 error = got_repo_map_path(&in_repo_path, repo, path);
5725 if (error)
5726 goto done;
5728 if (commit_id_str == NULL) {
5729 struct got_reference *head_ref;
5730 error = got_ref_open(&head_ref, repo, worktree ?
5731 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5732 if (error != NULL)
5733 goto done;
5734 error = got_ref_resolve(&commit_id, repo, head_ref);
5735 got_ref_close(head_ref);
5736 if (error != NULL)
5737 goto done;
5738 } else {
5739 struct got_reflist_head refs;
5740 TAILQ_INIT(&refs);
5741 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5742 NULL);
5743 if (error)
5744 goto done;
5745 error = got_repo_match_object_id(&commit_id, NULL,
5746 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5747 got_ref_list_free(&refs);
5748 if (error)
5749 goto done;
5752 if (worktree) {
5753 /* Release work tree lock. */
5754 got_worktree_close(worktree);
5755 worktree = NULL;
5758 error = got_object_open_as_commit(&commit, repo, commit_id);
5759 if (error)
5760 goto done;
5762 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5763 commit, repo);
5764 if (error)
5765 goto done;
5767 error = got_object_id_by_path(&obj_id, repo, commit,
5768 link_target ? link_target : in_repo_path);
5769 if (error)
5770 goto done;
5772 error = got_object_get_type(&obj_type, repo, obj_id);
5773 if (error)
5774 goto done;
5776 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5777 error = got_error_path(link_target ? link_target : in_repo_path,
5778 GOT_ERR_OBJ_TYPE);
5779 goto done;
5782 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5783 if (error)
5784 goto done;
5785 bca.f = got_opentemp();
5786 if (bca.f == NULL) {
5787 error = got_error_from_errno("got_opentemp");
5788 goto done;
5790 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5791 &bca.line_offsets, bca.f, blob);
5792 if (error || bca.nlines == 0)
5793 goto done;
5795 /* Don't include \n at EOF in the blame line count. */
5796 if (bca.line_offsets[bca.nlines - 1] == filesize)
5797 bca.nlines--;
5799 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5800 if (bca.lines == NULL) {
5801 error = got_error_from_errno("calloc");
5802 goto done;
5804 bca.lineno_cur = 1;
5805 bca.nlines_prec = 0;
5806 i = bca.nlines;
5807 while (i > 0) {
5808 i /= 10;
5809 bca.nlines_prec++;
5811 bca.repo = repo;
5813 fd2 = got_opentempfd();
5814 if (fd2 == -1) {
5815 error = got_error_from_errno("got_opentempfd");
5816 goto done;
5818 fd3 = got_opentempfd();
5819 if (fd3 == -1) {
5820 error = got_error_from_errno("got_opentempfd");
5821 goto done;
5823 f1 = got_opentemp();
5824 if (f1 == NULL) {
5825 error = got_error_from_errno("got_opentemp");
5826 goto done;
5828 f2 = got_opentemp();
5829 if (f2 == NULL) {
5830 error = got_error_from_errno("got_opentemp");
5831 goto done;
5833 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5834 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5835 check_cancelled, NULL, fd2, fd3, f1, f2);
5836 done:
5837 free(in_repo_path);
5838 free(link_target);
5839 free(repo_path);
5840 free(cwd);
5841 free(commit_id);
5842 free(obj_id);
5843 if (commit)
5844 got_object_commit_close(commit);
5846 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5847 error = got_error_from_errno("close");
5848 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5849 error = got_error_from_errno("close");
5850 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5851 error = got_error_from_errno("close");
5852 if (f1 && fclose(f1) == EOF && error == NULL)
5853 error = got_error_from_errno("fclose");
5854 if (f2 && fclose(f2) == EOF && error == NULL)
5855 error = got_error_from_errno("fclose");
5857 if (blob)
5858 got_object_blob_close(blob);
5859 if (worktree)
5860 got_worktree_close(worktree);
5861 if (repo) {
5862 const struct got_error *close_err = got_repo_close(repo);
5863 if (error == NULL)
5864 error = close_err;
5866 if (pack_fds) {
5867 const struct got_error *pack_err =
5868 got_repo_pack_fds_close(pack_fds);
5869 if (error == NULL)
5870 error = pack_err;
5872 if (bca.lines) {
5873 for (i = 0; i < bca.nlines; i++) {
5874 struct blame_line *bline = &bca.lines[i];
5875 free(bline->id_str);
5876 free(bline->committer);
5878 free(bca.lines);
5880 free(bca.line_offsets);
5881 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5882 error = got_error_from_errno("fclose");
5883 return error;
5886 __dead static void
5887 usage_tree(void)
5889 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5890 "[path]\n", getprogname());
5891 exit(1);
5894 static const struct got_error *
5895 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5896 const char *root_path, struct got_repository *repo)
5898 const struct got_error *err = NULL;
5899 int is_root_path = (strcmp(path, root_path) == 0);
5900 const char *modestr = "";
5901 mode_t mode = got_tree_entry_get_mode(te);
5902 char *link_target = NULL;
5904 path += strlen(root_path);
5905 while (path[0] == '/')
5906 path++;
5908 if (got_object_tree_entry_is_submodule(te))
5909 modestr = "$";
5910 else if (S_ISLNK(mode)) {
5911 int i;
5913 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5914 if (err)
5915 return err;
5916 for (i = 0; i < strlen(link_target); i++) {
5917 if (!isprint((unsigned char)link_target[i]))
5918 link_target[i] = '?';
5921 modestr = "@";
5923 else if (S_ISDIR(mode))
5924 modestr = "/";
5925 else if (mode & S_IXUSR)
5926 modestr = "*";
5928 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5929 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5930 link_target ? " -> ": "", link_target ? link_target : "");
5932 free(link_target);
5933 return NULL;
5936 static const struct got_error *
5937 print_tree(const char *path, struct got_commit_object *commit,
5938 int show_ids, int recurse, const char *root_path,
5939 struct got_repository *repo)
5941 const struct got_error *err = NULL;
5942 struct got_object_id *tree_id = NULL;
5943 struct got_tree_object *tree = NULL;
5944 int nentries, i;
5946 err = got_object_id_by_path(&tree_id, repo, commit, path);
5947 if (err)
5948 goto done;
5950 err = got_object_open_as_tree(&tree, repo, tree_id);
5951 if (err)
5952 goto done;
5953 nentries = got_object_tree_get_nentries(tree);
5954 for (i = 0; i < nentries; i++) {
5955 struct got_tree_entry *te;
5956 char *id = NULL;
5958 if (sigint_received || sigpipe_received)
5959 break;
5961 te = got_object_tree_get_entry(tree, i);
5962 if (show_ids) {
5963 char *id_str;
5964 err = got_object_id_str(&id_str,
5965 got_tree_entry_get_id(te));
5966 if (err)
5967 goto done;
5968 if (asprintf(&id, "%s ", id_str) == -1) {
5969 err = got_error_from_errno("asprintf");
5970 free(id_str);
5971 goto done;
5973 free(id_str);
5975 err = print_entry(te, id, path, root_path, repo);
5976 free(id);
5977 if (err)
5978 goto done;
5980 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5981 char *child_path;
5982 if (asprintf(&child_path, "%s%s%s", path,
5983 path[0] == '/' && path[1] == '\0' ? "" : "/",
5984 got_tree_entry_get_name(te)) == -1) {
5985 err = got_error_from_errno("asprintf");
5986 goto done;
5988 err = print_tree(child_path, commit, show_ids, 1,
5989 root_path, repo);
5990 free(child_path);
5991 if (err)
5992 goto done;
5995 done:
5996 if (tree)
5997 got_object_tree_close(tree);
5998 free(tree_id);
5999 return err;
6002 static const struct got_error *
6003 cmd_tree(int argc, char *argv[])
6005 const struct got_error *error;
6006 struct got_repository *repo = NULL;
6007 struct got_worktree *worktree = NULL;
6008 const char *path, *refname = NULL;
6009 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6010 struct got_object_id *commit_id = NULL;
6011 struct got_commit_object *commit = NULL;
6012 char *commit_id_str = NULL;
6013 int show_ids = 0, recurse = 0;
6014 int ch;
6015 int *pack_fds = NULL;
6017 #ifndef PROFILE
6018 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6019 NULL) == -1)
6020 err(1, "pledge");
6021 #endif
6023 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6024 switch (ch) {
6025 case 'c':
6026 commit_id_str = optarg;
6027 break;
6028 case 'i':
6029 show_ids = 1;
6030 break;
6031 case 'R':
6032 recurse = 1;
6033 break;
6034 case 'r':
6035 repo_path = realpath(optarg, NULL);
6036 if (repo_path == NULL)
6037 return got_error_from_errno2("realpath",
6038 optarg);
6039 got_path_strip_trailing_slashes(repo_path);
6040 break;
6041 default:
6042 usage_tree();
6043 /* NOTREACHED */
6047 argc -= optind;
6048 argv += optind;
6050 if (argc == 1)
6051 path = argv[0];
6052 else if (argc > 1)
6053 usage_tree();
6054 else
6055 path = NULL;
6057 cwd = getcwd(NULL, 0);
6058 if (cwd == NULL) {
6059 error = got_error_from_errno("getcwd");
6060 goto done;
6063 error = got_repo_pack_fds_open(&pack_fds);
6064 if (error != NULL)
6065 goto done;
6067 if (repo_path == NULL) {
6068 error = got_worktree_open(&worktree, cwd);
6069 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6070 goto done;
6071 else
6072 error = NULL;
6073 if (worktree) {
6074 repo_path =
6075 strdup(got_worktree_get_repo_path(worktree));
6076 if (repo_path == NULL)
6077 error = got_error_from_errno("strdup");
6078 if (error)
6079 goto done;
6080 } else {
6081 repo_path = strdup(cwd);
6082 if (repo_path == NULL) {
6083 error = got_error_from_errno("strdup");
6084 goto done;
6089 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6090 if (error != NULL)
6091 goto done;
6093 if (worktree) {
6094 const char *prefix = got_worktree_get_path_prefix(worktree);
6095 char *p;
6097 if (path == NULL)
6098 path = "";
6099 error = got_worktree_resolve_path(&p, worktree, path);
6100 if (error)
6101 goto done;
6102 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6103 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6104 p) == -1) {
6105 error = got_error_from_errno("asprintf");
6106 free(p);
6107 goto done;
6109 free(p);
6110 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6111 if (error)
6112 goto done;
6113 } else {
6114 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6115 if (error)
6116 goto done;
6117 if (path == NULL)
6118 path = "/";
6119 error = got_repo_map_path(&in_repo_path, repo, path);
6120 if (error != NULL)
6121 goto done;
6124 if (commit_id_str == NULL) {
6125 struct got_reference *head_ref;
6126 if (worktree)
6127 refname = got_worktree_get_head_ref_name(worktree);
6128 else
6129 refname = GOT_REF_HEAD;
6130 error = got_ref_open(&head_ref, repo, refname, 0);
6131 if (error != NULL)
6132 goto done;
6133 error = got_ref_resolve(&commit_id, repo, head_ref);
6134 got_ref_close(head_ref);
6135 if (error != NULL)
6136 goto done;
6137 } else {
6138 struct got_reflist_head refs;
6139 TAILQ_INIT(&refs);
6140 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6141 NULL);
6142 if (error)
6143 goto done;
6144 error = got_repo_match_object_id(&commit_id, NULL,
6145 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6146 got_ref_list_free(&refs);
6147 if (error)
6148 goto done;
6151 if (worktree) {
6152 /* Release work tree lock. */
6153 got_worktree_close(worktree);
6154 worktree = NULL;
6157 error = got_object_open_as_commit(&commit, repo, commit_id);
6158 if (error)
6159 goto done;
6161 error = print_tree(in_repo_path, commit, show_ids, recurse,
6162 in_repo_path, repo);
6163 done:
6164 free(in_repo_path);
6165 free(repo_path);
6166 free(cwd);
6167 free(commit_id);
6168 if (commit)
6169 got_object_commit_close(commit);
6170 if (worktree)
6171 got_worktree_close(worktree);
6172 if (repo) {
6173 const struct got_error *close_err = got_repo_close(repo);
6174 if (error == NULL)
6175 error = close_err;
6177 if (pack_fds) {
6178 const struct got_error *pack_err =
6179 got_repo_pack_fds_close(pack_fds);
6180 if (error == NULL)
6181 error = pack_err;
6183 return error;
6186 __dead static void
6187 usage_status(void)
6189 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6190 "[-s status-codes] [path ...]\n", getprogname());
6191 exit(1);
6194 struct got_status_arg {
6195 char *status_codes;
6196 int suppress;
6199 static const struct got_error *
6200 print_status(void *arg, unsigned char status, unsigned char staged_status,
6201 const char *path, struct got_object_id *blob_id,
6202 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6203 int dirfd, const char *de_name)
6205 struct got_status_arg *st = arg;
6207 if (status == staged_status && (status == GOT_STATUS_DELETE))
6208 status = GOT_STATUS_NO_CHANGE;
6209 if (st != NULL && st->status_codes) {
6210 size_t ncodes = strlen(st->status_codes);
6211 int i, j = 0;
6213 for (i = 0; i < ncodes ; i++) {
6214 if (st->suppress) {
6215 if (status == st->status_codes[i] ||
6216 staged_status == st->status_codes[i]) {
6217 j++;
6218 continue;
6220 } else {
6221 if (status == st->status_codes[i] ||
6222 staged_status == st->status_codes[i])
6223 break;
6227 if (st->suppress && j == 0)
6228 goto print;
6230 if (i == ncodes)
6231 return NULL;
6233 print:
6234 printf("%c%c %s\n", status, staged_status, path);
6235 return NULL;
6238 static const struct got_error *
6239 cmd_status(int argc, char *argv[])
6241 const struct got_error *error = NULL;
6242 struct got_repository *repo = NULL;
6243 struct got_worktree *worktree = NULL;
6244 struct got_status_arg st;
6245 char *cwd = NULL;
6246 struct got_pathlist_head paths;
6247 int ch, i, no_ignores = 0;
6248 int *pack_fds = NULL;
6250 TAILQ_INIT(&paths);
6252 memset(&st, 0, sizeof(st));
6253 st.status_codes = NULL;
6254 st.suppress = 0;
6256 #ifndef PROFILE
6257 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6258 NULL) == -1)
6259 err(1, "pledge");
6260 #endif
6262 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6263 switch (ch) {
6264 case 'I':
6265 no_ignores = 1;
6266 break;
6267 case 'S':
6268 if (st.status_codes != NULL && st.suppress == 0)
6269 option_conflict('S', 's');
6270 st.suppress = 1;
6271 /* fallthrough */
6272 case 's':
6273 for (i = 0; i < strlen(optarg); i++) {
6274 switch (optarg[i]) {
6275 case GOT_STATUS_MODIFY:
6276 case GOT_STATUS_ADD:
6277 case GOT_STATUS_DELETE:
6278 case GOT_STATUS_CONFLICT:
6279 case GOT_STATUS_MISSING:
6280 case GOT_STATUS_OBSTRUCTED:
6281 case GOT_STATUS_UNVERSIONED:
6282 case GOT_STATUS_MODE_CHANGE:
6283 case GOT_STATUS_NONEXISTENT:
6284 break;
6285 default:
6286 errx(1, "invalid status code '%c'",
6287 optarg[i]);
6290 if (ch == 's' && st.suppress)
6291 option_conflict('s', 'S');
6292 st.status_codes = optarg;
6293 break;
6294 default:
6295 usage_status();
6296 /* NOTREACHED */
6300 argc -= optind;
6301 argv += optind;
6303 cwd = getcwd(NULL, 0);
6304 if (cwd == NULL) {
6305 error = got_error_from_errno("getcwd");
6306 goto done;
6309 error = got_repo_pack_fds_open(&pack_fds);
6310 if (error != NULL)
6311 goto done;
6313 error = got_worktree_open(&worktree, cwd);
6314 if (error) {
6315 if (error->code == GOT_ERR_NOT_WORKTREE)
6316 error = wrap_not_worktree_error(error, "status", cwd);
6317 goto done;
6320 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6321 NULL, pack_fds);
6322 if (error != NULL)
6323 goto done;
6325 error = apply_unveil(got_repo_get_path(repo), 1,
6326 got_worktree_get_root_path(worktree));
6327 if (error)
6328 goto done;
6330 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6331 if (error)
6332 goto done;
6334 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6335 print_status, &st, check_cancelled, NULL);
6336 done:
6337 if (pack_fds) {
6338 const struct got_error *pack_err =
6339 got_repo_pack_fds_close(pack_fds);
6340 if (error == NULL)
6341 error = pack_err;
6344 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6345 free(cwd);
6346 return error;
6349 __dead static void
6350 usage_ref(void)
6352 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6353 "[-s reference] [name]\n", getprogname());
6354 exit(1);
6357 static const struct got_error *
6358 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6360 static const struct got_error *err = NULL;
6361 struct got_reflist_head refs;
6362 struct got_reflist_entry *re;
6364 TAILQ_INIT(&refs);
6365 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6366 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6367 repo);
6368 if (err)
6369 return err;
6371 TAILQ_FOREACH(re, &refs, entry) {
6372 char *refstr;
6373 refstr = got_ref_to_str(re->ref);
6374 if (refstr == NULL) {
6375 err = got_error_from_errno("got_ref_to_str");
6376 break;
6378 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6379 free(refstr);
6382 got_ref_list_free(&refs);
6383 return err;
6386 static const struct got_error *
6387 delete_ref_by_name(struct got_repository *repo, const char *refname)
6389 const struct got_error *err;
6390 struct got_reference *ref;
6392 err = got_ref_open(&ref, repo, refname, 0);
6393 if (err)
6394 return err;
6396 err = delete_ref(repo, ref);
6397 got_ref_close(ref);
6398 return err;
6401 static const struct got_error *
6402 add_ref(struct got_repository *repo, const char *refname, const char *target)
6404 const struct got_error *err = NULL;
6405 struct got_object_id *id = NULL;
6406 struct got_reference *ref = NULL;
6407 struct got_reflist_head refs;
6410 * Don't let the user create a reference name with a leading '-'.
6411 * While technically a valid reference name, this case is usually
6412 * an unintended typo.
6414 if (refname[0] == '-')
6415 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6417 TAILQ_INIT(&refs);
6418 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6419 if (err)
6420 goto done;
6421 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6422 &refs, repo);
6423 got_ref_list_free(&refs);
6424 if (err)
6425 goto done;
6427 err = got_ref_alloc(&ref, refname, id);
6428 if (err)
6429 goto done;
6431 err = got_ref_write(ref, repo);
6432 done:
6433 if (ref)
6434 got_ref_close(ref);
6435 free(id);
6436 return err;
6439 static const struct got_error *
6440 add_symref(struct got_repository *repo, const char *refname, const char *target)
6442 const struct got_error *err = NULL;
6443 struct got_reference *ref = NULL;
6444 struct got_reference *target_ref = NULL;
6447 * Don't let the user create a reference name with a leading '-'.
6448 * While technically a valid reference name, this case is usually
6449 * an unintended typo.
6451 if (refname[0] == '-')
6452 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6454 err = got_ref_open(&target_ref, repo, target, 0);
6455 if (err)
6456 return err;
6458 err = got_ref_alloc_symref(&ref, refname, target_ref);
6459 if (err)
6460 goto done;
6462 err = got_ref_write(ref, repo);
6463 done:
6464 if (target_ref)
6465 got_ref_close(target_ref);
6466 if (ref)
6467 got_ref_close(ref);
6468 return err;
6471 static const struct got_error *
6472 cmd_ref(int argc, char *argv[])
6474 const struct got_error *error = NULL;
6475 struct got_repository *repo = NULL;
6476 struct got_worktree *worktree = NULL;
6477 char *cwd = NULL, *repo_path = NULL;
6478 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6479 const char *obj_arg = NULL, *symref_target= NULL;
6480 char *refname = NULL;
6481 int *pack_fds = NULL;
6483 #ifndef PROFILE
6484 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6485 "sendfd unveil", NULL) == -1)
6486 err(1, "pledge");
6487 #endif
6489 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6490 switch (ch) {
6491 case 'c':
6492 obj_arg = optarg;
6493 break;
6494 case 'd':
6495 do_delete = 1;
6496 break;
6497 case 'l':
6498 do_list = 1;
6499 break;
6500 case 'r':
6501 repo_path = realpath(optarg, NULL);
6502 if (repo_path == NULL)
6503 return got_error_from_errno2("realpath",
6504 optarg);
6505 got_path_strip_trailing_slashes(repo_path);
6506 break;
6507 case 's':
6508 symref_target = optarg;
6509 break;
6510 case 't':
6511 sort_by_time = 1;
6512 break;
6513 default:
6514 usage_ref();
6515 /* NOTREACHED */
6519 if (obj_arg && do_list)
6520 option_conflict('c', 'l');
6521 if (obj_arg && do_delete)
6522 option_conflict('c', 'd');
6523 if (obj_arg && symref_target)
6524 option_conflict('c', 's');
6525 if (symref_target && do_delete)
6526 option_conflict('s', 'd');
6527 if (symref_target && do_list)
6528 option_conflict('s', 'l');
6529 if (do_delete && do_list)
6530 option_conflict('d', 'l');
6531 if (sort_by_time && !do_list)
6532 errx(1, "-t option requires -l option");
6534 argc -= optind;
6535 argv += optind;
6537 if (do_list) {
6538 if (argc != 0 && argc != 1)
6539 usage_ref();
6540 if (argc == 1) {
6541 refname = strdup(argv[0]);
6542 if (refname == NULL) {
6543 error = got_error_from_errno("strdup");
6544 goto done;
6547 } else {
6548 if (argc != 1)
6549 usage_ref();
6550 refname = strdup(argv[0]);
6551 if (refname == NULL) {
6552 error = got_error_from_errno("strdup");
6553 goto done;
6557 if (refname)
6558 got_path_strip_trailing_slashes(refname);
6560 cwd = getcwd(NULL, 0);
6561 if (cwd == NULL) {
6562 error = got_error_from_errno("getcwd");
6563 goto done;
6566 error = got_repo_pack_fds_open(&pack_fds);
6567 if (error != NULL)
6568 goto done;
6570 if (repo_path == NULL) {
6571 error = got_worktree_open(&worktree, cwd);
6572 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6573 goto done;
6574 else
6575 error = NULL;
6576 if (worktree) {
6577 repo_path =
6578 strdup(got_worktree_get_repo_path(worktree));
6579 if (repo_path == NULL)
6580 error = got_error_from_errno("strdup");
6581 if (error)
6582 goto done;
6583 } else {
6584 repo_path = strdup(cwd);
6585 if (repo_path == NULL) {
6586 error = got_error_from_errno("strdup");
6587 goto done;
6592 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6593 if (error != NULL)
6594 goto done;
6596 #ifndef PROFILE
6597 if (do_list) {
6598 /* Remove "cpath" promise. */
6599 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6600 NULL) == -1)
6601 err(1, "pledge");
6603 #endif
6605 error = apply_unveil(got_repo_get_path(repo), do_list,
6606 worktree ? got_worktree_get_root_path(worktree) : NULL);
6607 if (error)
6608 goto done;
6610 if (do_list)
6611 error = list_refs(repo, refname, sort_by_time);
6612 else if (do_delete)
6613 error = delete_ref_by_name(repo, refname);
6614 else if (symref_target)
6615 error = add_symref(repo, refname, symref_target);
6616 else {
6617 if (obj_arg == NULL)
6618 usage_ref();
6619 error = add_ref(repo, refname, obj_arg);
6621 done:
6622 free(refname);
6623 if (repo) {
6624 const struct got_error *close_err = got_repo_close(repo);
6625 if (error == NULL)
6626 error = close_err;
6628 if (worktree)
6629 got_worktree_close(worktree);
6630 if (pack_fds) {
6631 const struct got_error *pack_err =
6632 got_repo_pack_fds_close(pack_fds);
6633 if (error == NULL)
6634 error = pack_err;
6636 free(cwd);
6637 free(repo_path);
6638 return error;
6641 __dead static void
6642 usage_branch(void)
6644 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6645 "[-r repository-path] [name]\n", getprogname());
6646 exit(1);
6649 static const struct got_error *
6650 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6651 struct got_reference *ref)
6653 const struct got_error *err = NULL;
6654 const char *refname, *marker = " ";
6655 char *refstr;
6657 refname = got_ref_get_name(ref);
6658 if (worktree && strcmp(refname,
6659 got_worktree_get_head_ref_name(worktree)) == 0) {
6660 struct got_object_id *id = NULL;
6662 err = got_ref_resolve(&id, repo, ref);
6663 if (err)
6664 return err;
6665 if (got_object_id_cmp(id,
6666 got_worktree_get_base_commit_id(worktree)) == 0)
6667 marker = "* ";
6668 else
6669 marker = "~ ";
6670 free(id);
6673 if (strncmp(refname, "refs/heads/", 11) == 0)
6674 refname += 11;
6675 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6676 refname += 18;
6677 if (strncmp(refname, "refs/remotes/", 13) == 0)
6678 refname += 13;
6680 refstr = got_ref_to_str(ref);
6681 if (refstr == NULL)
6682 return got_error_from_errno("got_ref_to_str");
6684 printf("%s%s: %s\n", marker, refname, refstr);
6685 free(refstr);
6686 return NULL;
6689 static const struct got_error *
6690 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6692 const char *refname;
6694 if (worktree == NULL)
6695 return got_error(GOT_ERR_NOT_WORKTREE);
6697 refname = got_worktree_get_head_ref_name(worktree);
6699 if (strncmp(refname, "refs/heads/", 11) == 0)
6700 refname += 11;
6701 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6702 refname += 18;
6704 printf("%s\n", refname);
6706 return NULL;
6709 static const struct got_error *
6710 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6711 int sort_by_time)
6713 static const struct got_error *err = NULL;
6714 struct got_reflist_head refs;
6715 struct got_reflist_entry *re;
6716 struct got_reference *temp_ref = NULL;
6717 int rebase_in_progress, histedit_in_progress;
6719 TAILQ_INIT(&refs);
6721 if (worktree) {
6722 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6723 worktree);
6724 if (err)
6725 return err;
6727 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6728 worktree);
6729 if (err)
6730 return err;
6732 if (rebase_in_progress || histedit_in_progress) {
6733 err = got_ref_open(&temp_ref, repo,
6734 got_worktree_get_head_ref_name(worktree), 0);
6735 if (err)
6736 return err;
6737 list_branch(repo, worktree, temp_ref);
6738 got_ref_close(temp_ref);
6742 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6743 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6744 repo);
6745 if (err)
6746 return err;
6748 TAILQ_FOREACH(re, &refs, entry)
6749 list_branch(repo, worktree, re->ref);
6751 got_ref_list_free(&refs);
6753 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6754 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6755 repo);
6756 if (err)
6757 return err;
6759 TAILQ_FOREACH(re, &refs, entry)
6760 list_branch(repo, worktree, re->ref);
6762 got_ref_list_free(&refs);
6764 return NULL;
6767 static const struct got_error *
6768 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6769 const char *branch_name)
6771 const struct got_error *err = NULL;
6772 struct got_reference *ref = NULL;
6773 char *refname, *remote_refname = NULL;
6775 if (strncmp(branch_name, "refs/", 5) == 0)
6776 branch_name += 5;
6777 if (strncmp(branch_name, "heads/", 6) == 0)
6778 branch_name += 6;
6779 else if (strncmp(branch_name, "remotes/", 8) == 0)
6780 branch_name += 8;
6782 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6783 return got_error_from_errno("asprintf");
6785 if (asprintf(&remote_refname, "refs/remotes/%s",
6786 branch_name) == -1) {
6787 err = got_error_from_errno("asprintf");
6788 goto done;
6791 err = got_ref_open(&ref, repo, refname, 0);
6792 if (err) {
6793 const struct got_error *err2;
6794 if (err->code != GOT_ERR_NOT_REF)
6795 goto done;
6797 * Keep 'err' intact such that if neither branch exists
6798 * we report "refs/heads" rather than "refs/remotes" in
6799 * our error message.
6801 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6802 if (err2)
6803 goto done;
6804 err = NULL;
6807 if (worktree &&
6808 strcmp(got_worktree_get_head_ref_name(worktree),
6809 got_ref_get_name(ref)) == 0) {
6810 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6811 "will not delete this work tree's current branch");
6812 goto done;
6815 err = delete_ref(repo, ref);
6816 done:
6817 if (ref)
6818 got_ref_close(ref);
6819 free(refname);
6820 free(remote_refname);
6821 return err;
6824 static const struct got_error *
6825 add_branch(struct got_repository *repo, const char *branch_name,
6826 struct got_object_id *base_commit_id)
6828 const struct got_error *err = NULL;
6829 struct got_reference *ref = NULL;
6830 char *refname = NULL;
6833 * Don't let the user create a branch name with a leading '-'.
6834 * While technically a valid reference name, this case is usually
6835 * an unintended typo.
6837 if (branch_name[0] == '-')
6838 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6840 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6841 branch_name += 11;
6843 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6844 err = got_error_from_errno("asprintf");
6845 goto done;
6848 err = got_ref_open(&ref, repo, refname, 0);
6849 if (err == NULL) {
6850 err = got_error(GOT_ERR_BRANCH_EXISTS);
6851 goto done;
6852 } else if (err->code != GOT_ERR_NOT_REF)
6853 goto done;
6855 err = got_ref_alloc(&ref, refname, base_commit_id);
6856 if (err)
6857 goto done;
6859 err = got_ref_write(ref, repo);
6860 done:
6861 if (ref)
6862 got_ref_close(ref);
6863 free(refname);
6864 return err;
6867 static const struct got_error *
6868 cmd_branch(int argc, char *argv[])
6870 const struct got_error *error = NULL;
6871 struct got_repository *repo = NULL;
6872 struct got_worktree *worktree = NULL;
6873 char *cwd = NULL, *repo_path = NULL;
6874 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6875 const char *delref = NULL, *commit_id_arg = NULL;
6876 struct got_reference *ref = NULL;
6877 struct got_pathlist_head paths;
6878 struct got_object_id *commit_id = NULL;
6879 char *commit_id_str = NULL;
6880 int *pack_fds = NULL;
6882 TAILQ_INIT(&paths);
6884 #ifndef PROFILE
6885 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6886 "sendfd unveil", NULL) == -1)
6887 err(1, "pledge");
6888 #endif
6890 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6891 switch (ch) {
6892 case 'c':
6893 commit_id_arg = optarg;
6894 break;
6895 case 'd':
6896 delref = optarg;
6897 break;
6898 case 'l':
6899 do_list = 1;
6900 break;
6901 case 'n':
6902 do_update = 0;
6903 break;
6904 case 'r':
6905 repo_path = realpath(optarg, NULL);
6906 if (repo_path == NULL)
6907 return got_error_from_errno2("realpath",
6908 optarg);
6909 got_path_strip_trailing_slashes(repo_path);
6910 break;
6911 case 't':
6912 sort_by_time = 1;
6913 break;
6914 default:
6915 usage_branch();
6916 /* NOTREACHED */
6920 if (do_list && delref)
6921 option_conflict('l', 'd');
6922 if (sort_by_time && !do_list)
6923 errx(1, "-t option requires -l option");
6925 argc -= optind;
6926 argv += optind;
6928 if (!do_list && !delref && argc == 0)
6929 do_show = 1;
6931 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6932 errx(1, "-c option can only be used when creating a branch");
6934 if (do_list || delref) {
6935 if (argc > 0)
6936 usage_branch();
6937 } else if (!do_show && argc != 1)
6938 usage_branch();
6940 cwd = getcwd(NULL, 0);
6941 if (cwd == NULL) {
6942 error = got_error_from_errno("getcwd");
6943 goto done;
6946 error = got_repo_pack_fds_open(&pack_fds);
6947 if (error != NULL)
6948 goto done;
6950 if (repo_path == NULL) {
6951 error = got_worktree_open(&worktree, cwd);
6952 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6953 goto done;
6954 else
6955 error = NULL;
6956 if (worktree) {
6957 repo_path =
6958 strdup(got_worktree_get_repo_path(worktree));
6959 if (repo_path == NULL)
6960 error = got_error_from_errno("strdup");
6961 if (error)
6962 goto done;
6963 } else {
6964 repo_path = strdup(cwd);
6965 if (repo_path == NULL) {
6966 error = got_error_from_errno("strdup");
6967 goto done;
6972 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6973 if (error != NULL)
6974 goto done;
6976 #ifndef PROFILE
6977 if (do_list || do_show) {
6978 /* Remove "cpath" promise. */
6979 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6980 NULL) == -1)
6981 err(1, "pledge");
6983 #endif
6985 error = apply_unveil(got_repo_get_path(repo), do_list,
6986 worktree ? got_worktree_get_root_path(worktree) : NULL);
6987 if (error)
6988 goto done;
6990 if (do_show)
6991 error = show_current_branch(repo, worktree);
6992 else if (do_list)
6993 error = list_branches(repo, worktree, sort_by_time);
6994 else if (delref)
6995 error = delete_branch(repo, worktree, delref);
6996 else {
6997 struct got_reflist_head refs;
6998 TAILQ_INIT(&refs);
6999 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7000 NULL);
7001 if (error)
7002 goto done;
7003 if (commit_id_arg == NULL)
7004 commit_id_arg = worktree ?
7005 got_worktree_get_head_ref_name(worktree) :
7006 GOT_REF_HEAD;
7007 error = got_repo_match_object_id(&commit_id, NULL,
7008 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7009 got_ref_list_free(&refs);
7010 if (error)
7011 goto done;
7012 error = add_branch(repo, argv[0], commit_id);
7013 if (error)
7014 goto done;
7015 if (worktree && do_update) {
7016 struct got_update_progress_arg upa;
7017 char *branch_refname = NULL;
7019 error = got_object_id_str(&commit_id_str, commit_id);
7020 if (error)
7021 goto done;
7022 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7023 worktree);
7024 if (error)
7025 goto done;
7026 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7027 == -1) {
7028 error = got_error_from_errno("asprintf");
7029 goto done;
7031 error = got_ref_open(&ref, repo, branch_refname, 0);
7032 free(branch_refname);
7033 if (error)
7034 goto done;
7035 error = switch_head_ref(ref, commit_id, worktree,
7036 repo);
7037 if (error)
7038 goto done;
7039 error = got_worktree_set_base_commit_id(worktree, repo,
7040 commit_id);
7041 if (error)
7042 goto done;
7043 memset(&upa, 0, sizeof(upa));
7044 error = got_worktree_checkout_files(worktree, &paths,
7045 repo, update_progress, &upa, check_cancelled,
7046 NULL);
7047 if (error)
7048 goto done;
7049 if (upa.did_something) {
7050 printf("Updated to %s: %s\n",
7051 got_worktree_get_head_ref_name(worktree),
7052 commit_id_str);
7054 print_update_progress_stats(&upa);
7057 done:
7058 if (ref)
7059 got_ref_close(ref);
7060 if (repo) {
7061 const struct got_error *close_err = got_repo_close(repo);
7062 if (error == NULL)
7063 error = close_err;
7065 if (worktree)
7066 got_worktree_close(worktree);
7067 if (pack_fds) {
7068 const struct got_error *pack_err =
7069 got_repo_pack_fds_close(pack_fds);
7070 if (error == NULL)
7071 error = pack_err;
7073 free(cwd);
7074 free(repo_path);
7075 free(commit_id);
7076 free(commit_id_str);
7077 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7078 return error;
7082 __dead static void
7083 usage_tag(void)
7085 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7086 "[-r repository-path] [-s signer-id] name\n", getprogname());
7087 exit(1);
7090 #if 0
7091 static const struct got_error *
7092 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7094 const struct got_error *err = NULL;
7095 struct got_reflist_entry *re, *se, *new;
7096 struct got_object_id *re_id, *se_id;
7097 struct got_tag_object *re_tag, *se_tag;
7098 time_t re_time, se_time;
7100 STAILQ_FOREACH(re, tags, entry) {
7101 se = STAILQ_FIRST(sorted);
7102 if (se == NULL) {
7103 err = got_reflist_entry_dup(&new, re);
7104 if (err)
7105 return err;
7106 STAILQ_INSERT_HEAD(sorted, new, entry);
7107 continue;
7108 } else {
7109 err = got_ref_resolve(&re_id, repo, re->ref);
7110 if (err)
7111 break;
7112 err = got_object_open_as_tag(&re_tag, repo, re_id);
7113 free(re_id);
7114 if (err)
7115 break;
7116 re_time = got_object_tag_get_tagger_time(re_tag);
7117 got_object_tag_close(re_tag);
7120 while (se) {
7121 err = got_ref_resolve(&se_id, repo, re->ref);
7122 if (err)
7123 break;
7124 err = got_object_open_as_tag(&se_tag, repo, se_id);
7125 free(se_id);
7126 if (err)
7127 break;
7128 se_time = got_object_tag_get_tagger_time(se_tag);
7129 got_object_tag_close(se_tag);
7131 if (se_time > re_time) {
7132 err = got_reflist_entry_dup(&new, re);
7133 if (err)
7134 return err;
7135 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7136 break;
7138 se = STAILQ_NEXT(se, entry);
7139 continue;
7142 done:
7143 return err;
7145 #endif
7147 static const struct got_error *
7148 get_tag_refname(char **refname, const char *tag_name)
7150 const struct got_error *err;
7152 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7153 *refname = strdup(tag_name);
7154 if (*refname == NULL)
7155 return got_error_from_errno("strdup");
7156 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7157 err = got_error_from_errno("asprintf");
7158 *refname = NULL;
7159 return err;
7162 return NULL;
7165 static const struct got_error *
7166 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7167 const char *allowed_signers, const char *revoked_signers, int verbosity)
7169 static const struct got_error *err = NULL;
7170 struct got_reflist_head refs;
7171 struct got_reflist_entry *re;
7172 char *wanted_refname = NULL;
7173 int bad_sigs = 0;
7175 TAILQ_INIT(&refs);
7177 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7178 if (err)
7179 return err;
7181 if (tag_name) {
7182 struct got_reference *ref;
7183 err = get_tag_refname(&wanted_refname, tag_name);
7184 if (err)
7185 goto done;
7186 /* Wanted tag reference should exist. */
7187 err = got_ref_open(&ref, repo, wanted_refname, 0);
7188 if (err)
7189 goto done;
7190 got_ref_close(ref);
7193 TAILQ_FOREACH(re, &refs, entry) {
7194 const char *refname;
7195 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7196 char datebuf[26];
7197 const char *tagger, *ssh_sig = NULL;
7198 char *sig_msg = NULL;
7199 time_t tagger_time;
7200 struct got_object_id *id;
7201 struct got_tag_object *tag;
7202 struct got_commit_object *commit = NULL;
7204 refname = got_ref_get_name(re->ref);
7205 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7206 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7207 continue;
7208 refname += 10;
7209 refstr = got_ref_to_str(re->ref);
7210 if (refstr == NULL) {
7211 err = got_error_from_errno("got_ref_to_str");
7212 break;
7215 err = got_ref_resolve(&id, repo, re->ref);
7216 if (err)
7217 break;
7218 err = got_object_open_as_tag(&tag, repo, id);
7219 if (err) {
7220 if (err->code != GOT_ERR_OBJ_TYPE) {
7221 free(id);
7222 break;
7224 /* "lightweight" tag */
7225 err = got_object_open_as_commit(&commit, repo, id);
7226 if (err) {
7227 free(id);
7228 break;
7230 tagger = got_object_commit_get_committer(commit);
7231 tagger_time =
7232 got_object_commit_get_committer_time(commit);
7233 err = got_object_id_str(&id_str, id);
7234 free(id);
7235 if (err)
7236 break;
7237 } else {
7238 free(id);
7239 tagger = got_object_tag_get_tagger(tag);
7240 tagger_time = got_object_tag_get_tagger_time(tag);
7241 err = got_object_id_str(&id_str,
7242 got_object_tag_get_object_id(tag));
7243 if (err)
7244 break;
7247 if (tag && verify_tags) {
7248 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7249 got_object_tag_get_message(tag));
7250 if (ssh_sig && allowed_signers == NULL) {
7251 err = got_error_msg(
7252 GOT_ERR_VERIFY_TAG_SIGNATURE,
7253 "SSH signature verification requires "
7254 "setting allowed_signers in "
7255 "got.conf(5)");
7256 break;
7260 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7261 free(refstr);
7262 printf("from: %s\n", tagger);
7263 datestr = get_datestr(&tagger_time, datebuf);
7264 if (datestr)
7265 printf("date: %s UTC\n", datestr);
7266 if (commit)
7267 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7268 else {
7269 switch (got_object_tag_get_object_type(tag)) {
7270 case GOT_OBJ_TYPE_BLOB:
7271 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7272 id_str);
7273 break;
7274 case GOT_OBJ_TYPE_TREE:
7275 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7276 id_str);
7277 break;
7278 case GOT_OBJ_TYPE_COMMIT:
7279 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7280 id_str);
7281 break;
7282 case GOT_OBJ_TYPE_TAG:
7283 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7284 id_str);
7285 break;
7286 default:
7287 break;
7290 free(id_str);
7292 if (ssh_sig) {
7293 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7294 allowed_signers, revoked_signers, verbosity);
7295 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7296 bad_sigs = 1;
7297 else if (err)
7298 break;
7299 printf("signature: %s", sig_msg);
7300 free(sig_msg);
7301 sig_msg = NULL;
7304 if (commit) {
7305 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7306 if (err)
7307 break;
7308 got_object_commit_close(commit);
7309 } else {
7310 tagmsg0 = strdup(got_object_tag_get_message(tag));
7311 got_object_tag_close(tag);
7312 if (tagmsg0 == NULL) {
7313 err = got_error_from_errno("strdup");
7314 break;
7318 tagmsg = tagmsg0;
7319 do {
7320 line = strsep(&tagmsg, "\n");
7321 if (line)
7322 printf(" %s\n", line);
7323 } while (line);
7324 free(tagmsg0);
7326 done:
7327 got_ref_list_free(&refs);
7328 free(wanted_refname);
7330 if (err == NULL && bad_sigs)
7331 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7332 return err;
7335 static const struct got_error *
7336 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7337 const char *tag_name, const char *repo_path)
7339 const struct got_error *err = NULL;
7340 char *template = NULL, *initial_content = NULL;
7341 char *editor = NULL;
7342 int initial_content_len;
7343 int fd = -1;
7345 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7346 err = got_error_from_errno("asprintf");
7347 goto done;
7350 initial_content_len = asprintf(&initial_content,
7351 "\n# tagging commit %s as %s\n",
7352 commit_id_str, tag_name);
7353 if (initial_content_len == -1) {
7354 err = got_error_from_errno("asprintf");
7355 goto done;
7358 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7359 if (err)
7360 goto done;
7362 if (write(fd, initial_content, initial_content_len) == -1) {
7363 err = got_error_from_errno2("write", *tagmsg_path);
7364 goto done;
7367 err = get_editor(&editor);
7368 if (err)
7369 goto done;
7370 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7371 initial_content_len, 1);
7372 done:
7373 free(initial_content);
7374 free(template);
7375 free(editor);
7377 if (fd != -1 && close(fd) == -1 && err == NULL)
7378 err = got_error_from_errno2("close", *tagmsg_path);
7380 if (err) {
7381 free(*tagmsg);
7382 *tagmsg = NULL;
7384 return err;
7387 static const struct got_error *
7388 add_tag(struct got_repository *repo, const char *tagger,
7389 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7390 const char *signer_id, int verbosity)
7392 const struct got_error *err = NULL;
7393 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7394 char *label = NULL, *commit_id_str = NULL;
7395 struct got_reference *ref = NULL;
7396 char *refname = NULL, *tagmsg = NULL;
7397 char *tagmsg_path = NULL, *tag_id_str = NULL;
7398 int preserve_tagmsg = 0;
7399 struct got_reflist_head refs;
7401 TAILQ_INIT(&refs);
7404 * Don't let the user create a tag name with a leading '-'.
7405 * While technically a valid reference name, this case is usually
7406 * an unintended typo.
7408 if (tag_name[0] == '-')
7409 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7411 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7412 if (err)
7413 goto done;
7415 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7416 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7417 if (err)
7418 goto done;
7420 err = got_object_id_str(&commit_id_str, commit_id);
7421 if (err)
7422 goto done;
7424 err = get_tag_refname(&refname, tag_name);
7425 if (err)
7426 goto done;
7427 if (strncmp("refs/tags/", tag_name, 10) == 0)
7428 tag_name += 10;
7430 err = got_ref_open(&ref, repo, refname, 0);
7431 if (err == NULL) {
7432 err = got_error(GOT_ERR_TAG_EXISTS);
7433 goto done;
7434 } else if (err->code != GOT_ERR_NOT_REF)
7435 goto done;
7437 if (tagmsg_arg == NULL) {
7438 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7439 tag_name, got_repo_get_path(repo));
7440 if (err) {
7441 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7442 tagmsg_path != NULL)
7443 preserve_tagmsg = 1;
7444 goto done;
7446 /* Editor is done; we can now apply unveil(2) */
7447 err = got_sigs_apply_unveil();
7448 if (err)
7449 goto done;
7450 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7451 if (err)
7452 goto done;
7455 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7456 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7457 verbosity);
7458 if (err) {
7459 if (tagmsg_path)
7460 preserve_tagmsg = 1;
7461 goto done;
7464 err = got_ref_alloc(&ref, refname, tag_id);
7465 if (err) {
7466 if (tagmsg_path)
7467 preserve_tagmsg = 1;
7468 goto done;
7471 err = got_ref_write(ref, repo);
7472 if (err) {
7473 if (tagmsg_path)
7474 preserve_tagmsg = 1;
7475 goto done;
7478 err = got_object_id_str(&tag_id_str, tag_id);
7479 if (err) {
7480 if (tagmsg_path)
7481 preserve_tagmsg = 1;
7482 goto done;
7484 printf("Created tag %s\n", tag_id_str);
7485 done:
7486 if (preserve_tagmsg) {
7487 fprintf(stderr, "%s: tag message preserved in %s\n",
7488 getprogname(), tagmsg_path);
7489 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7490 err = got_error_from_errno2("unlink", tagmsg_path);
7491 free(tag_id_str);
7492 if (ref)
7493 got_ref_close(ref);
7494 free(commit_id);
7495 free(commit_id_str);
7496 free(refname);
7497 free(tagmsg);
7498 free(tagmsg_path);
7499 got_ref_list_free(&refs);
7500 return err;
7503 static const struct got_error *
7504 cmd_tag(int argc, char *argv[])
7506 const struct got_error *error = NULL;
7507 struct got_repository *repo = NULL;
7508 struct got_worktree *worktree = NULL;
7509 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7510 char *gitconfig_path = NULL, *tagger = NULL;
7511 char *allowed_signers = NULL, *revoked_signers = NULL;
7512 const char *signer_id = NULL;
7513 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7514 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7515 int *pack_fds = NULL;
7517 #ifndef PROFILE
7518 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7519 "sendfd unveil", NULL) == -1)
7520 err(1, "pledge");
7521 #endif
7523 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7524 switch (ch) {
7525 case 'c':
7526 commit_id_arg = optarg;
7527 break;
7528 case 'l':
7529 do_list = 1;
7530 break;
7531 case 'm':
7532 tagmsg = optarg;
7533 break;
7534 case 'r':
7535 repo_path = realpath(optarg, NULL);
7536 if (repo_path == NULL) {
7537 error = got_error_from_errno2("realpath",
7538 optarg);
7539 goto done;
7541 got_path_strip_trailing_slashes(repo_path);
7542 break;
7543 case 's':
7544 signer_id = optarg;
7545 break;
7546 case 'V':
7547 verify_tags = 1;
7548 break;
7549 case 'v':
7550 if (verbosity < 0)
7551 verbosity = 0;
7552 else if (verbosity < 3)
7553 verbosity++;
7554 break;
7555 default:
7556 usage_tag();
7557 /* NOTREACHED */
7561 argc -= optind;
7562 argv += optind;
7564 if (do_list || verify_tags) {
7565 if (commit_id_arg != NULL)
7566 errx(1,
7567 "-c option can only be used when creating a tag");
7568 if (tagmsg) {
7569 if (do_list)
7570 option_conflict('l', 'm');
7571 else
7572 option_conflict('V', 'm');
7574 if (signer_id) {
7575 if (do_list)
7576 option_conflict('l', 's');
7577 else
7578 option_conflict('V', 's');
7580 if (argc > 1)
7581 usage_tag();
7582 } else if (argc != 1)
7583 usage_tag();
7585 if (argc == 1)
7586 tag_name = argv[0];
7588 cwd = getcwd(NULL, 0);
7589 if (cwd == NULL) {
7590 error = got_error_from_errno("getcwd");
7591 goto done;
7594 error = got_repo_pack_fds_open(&pack_fds);
7595 if (error != NULL)
7596 goto done;
7598 if (repo_path == NULL) {
7599 error = got_worktree_open(&worktree, cwd);
7600 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7601 goto done;
7602 else
7603 error = NULL;
7604 if (worktree) {
7605 repo_path =
7606 strdup(got_worktree_get_repo_path(worktree));
7607 if (repo_path == NULL)
7608 error = got_error_from_errno("strdup");
7609 if (error)
7610 goto done;
7611 } else {
7612 repo_path = strdup(cwd);
7613 if (repo_path == NULL) {
7614 error = got_error_from_errno("strdup");
7615 goto done;
7620 if (do_list || verify_tags) {
7621 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7622 if (error != NULL)
7623 goto done;
7624 error = get_allowed_signers(&allowed_signers, repo, worktree);
7625 if (error)
7626 goto done;
7627 error = get_revoked_signers(&revoked_signers, repo, worktree);
7628 if (error)
7629 goto done;
7630 if (worktree) {
7631 /* Release work tree lock. */
7632 got_worktree_close(worktree);
7633 worktree = NULL;
7637 * Remove "cpath" promise unless needed for signature tmpfile
7638 * creation.
7640 if (verify_tags)
7641 got_sigs_apply_unveil();
7642 else {
7643 #ifndef PROFILE
7644 if (pledge("stdio rpath wpath flock proc exec sendfd "
7645 "unveil", NULL) == -1)
7646 err(1, "pledge");
7647 #endif
7649 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7650 if (error)
7651 goto done;
7652 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7653 revoked_signers, verbosity);
7654 } else {
7655 error = get_gitconfig_path(&gitconfig_path);
7656 if (error)
7657 goto done;
7658 error = got_repo_open(&repo, repo_path, gitconfig_path,
7659 pack_fds);
7660 if (error != NULL)
7661 goto done;
7663 error = get_author(&tagger, repo, worktree);
7664 if (error)
7665 goto done;
7666 if (signer_id == NULL)
7667 signer_id = get_signer_id(repo, worktree);
7669 if (tagmsg) {
7670 if (signer_id) {
7671 error = got_sigs_apply_unveil();
7672 if (error)
7673 goto done;
7675 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7676 if (error)
7677 goto done;
7680 if (commit_id_arg == NULL) {
7681 struct got_reference *head_ref;
7682 struct got_object_id *commit_id;
7683 error = got_ref_open(&head_ref, repo,
7684 worktree ? got_worktree_get_head_ref_name(worktree)
7685 : GOT_REF_HEAD, 0);
7686 if (error)
7687 goto done;
7688 error = got_ref_resolve(&commit_id, repo, head_ref);
7689 got_ref_close(head_ref);
7690 if (error)
7691 goto done;
7692 error = got_object_id_str(&commit_id_str, commit_id);
7693 free(commit_id);
7694 if (error)
7695 goto done;
7698 if (worktree) {
7699 /* Release work tree lock. */
7700 got_worktree_close(worktree);
7701 worktree = NULL;
7704 error = add_tag(repo, tagger, tag_name,
7705 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7706 signer_id, verbosity);
7708 done:
7709 if (repo) {
7710 const struct got_error *close_err = got_repo_close(repo);
7711 if (error == NULL)
7712 error = close_err;
7714 if (worktree)
7715 got_worktree_close(worktree);
7716 if (pack_fds) {
7717 const struct got_error *pack_err =
7718 got_repo_pack_fds_close(pack_fds);
7719 if (error == NULL)
7720 error = pack_err;
7722 free(cwd);
7723 free(repo_path);
7724 free(gitconfig_path);
7725 free(commit_id_str);
7726 free(tagger);
7727 free(allowed_signers);
7728 free(revoked_signers);
7729 return error;
7732 __dead static void
7733 usage_add(void)
7735 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7736 exit(1);
7739 static const struct got_error *
7740 add_progress(void *arg, unsigned char status, const char *path)
7742 while (path[0] == '/')
7743 path++;
7744 printf("%c %s\n", status, path);
7745 return NULL;
7748 static const struct got_error *
7749 cmd_add(int argc, char *argv[])
7751 const struct got_error *error = NULL;
7752 struct got_repository *repo = NULL;
7753 struct got_worktree *worktree = NULL;
7754 char *cwd = NULL;
7755 struct got_pathlist_head paths;
7756 struct got_pathlist_entry *pe;
7757 int ch, can_recurse = 0, no_ignores = 0;
7758 int *pack_fds = NULL;
7760 TAILQ_INIT(&paths);
7762 #ifndef PROFILE
7763 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7764 NULL) == -1)
7765 err(1, "pledge");
7766 #endif
7768 while ((ch = getopt(argc, argv, "IR")) != -1) {
7769 switch (ch) {
7770 case 'I':
7771 no_ignores = 1;
7772 break;
7773 case 'R':
7774 can_recurse = 1;
7775 break;
7776 default:
7777 usage_add();
7778 /* NOTREACHED */
7782 argc -= optind;
7783 argv += optind;
7785 if (argc < 1)
7786 usage_add();
7788 cwd = getcwd(NULL, 0);
7789 if (cwd == NULL) {
7790 error = got_error_from_errno("getcwd");
7791 goto done;
7794 error = got_repo_pack_fds_open(&pack_fds);
7795 if (error != NULL)
7796 goto done;
7798 error = got_worktree_open(&worktree, cwd);
7799 if (error) {
7800 if (error->code == GOT_ERR_NOT_WORKTREE)
7801 error = wrap_not_worktree_error(error, "add", cwd);
7802 goto done;
7805 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7806 NULL, pack_fds);
7807 if (error != NULL)
7808 goto done;
7810 error = apply_unveil(got_repo_get_path(repo), 1,
7811 got_worktree_get_root_path(worktree));
7812 if (error)
7813 goto done;
7815 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7816 if (error)
7817 goto done;
7819 if (!can_recurse) {
7820 char *ondisk_path;
7821 struct stat sb;
7822 TAILQ_FOREACH(pe, &paths, entry) {
7823 if (asprintf(&ondisk_path, "%s/%s",
7824 got_worktree_get_root_path(worktree),
7825 pe->path) == -1) {
7826 error = got_error_from_errno("asprintf");
7827 goto done;
7829 if (lstat(ondisk_path, &sb) == -1) {
7830 if (errno == ENOENT) {
7831 free(ondisk_path);
7832 continue;
7834 error = got_error_from_errno2("lstat",
7835 ondisk_path);
7836 free(ondisk_path);
7837 goto done;
7839 free(ondisk_path);
7840 if (S_ISDIR(sb.st_mode)) {
7841 error = got_error_msg(GOT_ERR_BAD_PATH,
7842 "adding directories requires -R option");
7843 goto done;
7848 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7849 NULL, repo, no_ignores);
7850 done:
7851 if (repo) {
7852 const struct got_error *close_err = got_repo_close(repo);
7853 if (error == NULL)
7854 error = close_err;
7856 if (worktree)
7857 got_worktree_close(worktree);
7858 if (pack_fds) {
7859 const struct got_error *pack_err =
7860 got_repo_pack_fds_close(pack_fds);
7861 if (error == NULL)
7862 error = pack_err;
7864 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7865 free(cwd);
7866 return error;
7869 __dead static void
7870 usage_remove(void)
7872 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7873 getprogname());
7874 exit(1);
7877 static const struct got_error *
7878 print_remove_status(void *arg, unsigned char status,
7879 unsigned char staged_status, const char *path)
7881 while (path[0] == '/')
7882 path++;
7883 if (status == GOT_STATUS_NONEXISTENT)
7884 return NULL;
7885 if (status == staged_status && (status == GOT_STATUS_DELETE))
7886 status = GOT_STATUS_NO_CHANGE;
7887 printf("%c%c %s\n", status, staged_status, path);
7888 return NULL;
7891 static const struct got_error *
7892 cmd_remove(int argc, char *argv[])
7894 const struct got_error *error = NULL;
7895 struct got_worktree *worktree = NULL;
7896 struct got_repository *repo = NULL;
7897 const char *status_codes = NULL;
7898 char *cwd = NULL;
7899 struct got_pathlist_head paths;
7900 struct got_pathlist_entry *pe;
7901 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7902 int ignore_missing_paths = 0;
7903 int *pack_fds = NULL;
7905 TAILQ_INIT(&paths);
7907 #ifndef PROFILE
7908 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7909 NULL) == -1)
7910 err(1, "pledge");
7911 #endif
7913 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7914 switch (ch) {
7915 case 'f':
7916 delete_local_mods = 1;
7917 ignore_missing_paths = 1;
7918 break;
7919 case 'k':
7920 keep_on_disk = 1;
7921 break;
7922 case 'R':
7923 can_recurse = 1;
7924 break;
7925 case 's':
7926 for (i = 0; i < strlen(optarg); i++) {
7927 switch (optarg[i]) {
7928 case GOT_STATUS_MODIFY:
7929 delete_local_mods = 1;
7930 break;
7931 case GOT_STATUS_MISSING:
7932 ignore_missing_paths = 1;
7933 break;
7934 default:
7935 errx(1, "invalid status code '%c'",
7936 optarg[i]);
7939 status_codes = optarg;
7940 break;
7941 default:
7942 usage_remove();
7943 /* NOTREACHED */
7947 argc -= optind;
7948 argv += optind;
7950 if (argc < 1)
7951 usage_remove();
7953 cwd = getcwd(NULL, 0);
7954 if (cwd == NULL) {
7955 error = got_error_from_errno("getcwd");
7956 goto done;
7959 error = got_repo_pack_fds_open(&pack_fds);
7960 if (error != NULL)
7961 goto done;
7963 error = got_worktree_open(&worktree, cwd);
7964 if (error) {
7965 if (error->code == GOT_ERR_NOT_WORKTREE)
7966 error = wrap_not_worktree_error(error, "remove", cwd);
7967 goto done;
7970 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7971 NULL, pack_fds);
7972 if (error)
7973 goto done;
7975 error = apply_unveil(got_repo_get_path(repo), 1,
7976 got_worktree_get_root_path(worktree));
7977 if (error)
7978 goto done;
7980 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7981 if (error)
7982 goto done;
7984 if (!can_recurse) {
7985 char *ondisk_path;
7986 struct stat sb;
7987 TAILQ_FOREACH(pe, &paths, entry) {
7988 if (asprintf(&ondisk_path, "%s/%s",
7989 got_worktree_get_root_path(worktree),
7990 pe->path) == -1) {
7991 error = got_error_from_errno("asprintf");
7992 goto done;
7994 if (lstat(ondisk_path, &sb) == -1) {
7995 if (errno == ENOENT) {
7996 free(ondisk_path);
7997 continue;
7999 error = got_error_from_errno2("lstat",
8000 ondisk_path);
8001 free(ondisk_path);
8002 goto done;
8004 free(ondisk_path);
8005 if (S_ISDIR(sb.st_mode)) {
8006 error = got_error_msg(GOT_ERR_BAD_PATH,
8007 "removing directories requires -R option");
8008 goto done;
8013 error = got_worktree_schedule_delete(worktree, &paths,
8014 delete_local_mods, status_codes, print_remove_status, NULL,
8015 repo, keep_on_disk, ignore_missing_paths);
8016 done:
8017 if (repo) {
8018 const struct got_error *close_err = got_repo_close(repo);
8019 if (error == NULL)
8020 error = close_err;
8022 if (worktree)
8023 got_worktree_close(worktree);
8024 if (pack_fds) {
8025 const struct got_error *pack_err =
8026 got_repo_pack_fds_close(pack_fds);
8027 if (error == NULL)
8028 error = pack_err;
8030 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8031 free(cwd);
8032 return error;
8035 __dead static void
8036 usage_patch(void)
8038 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8039 "[patchfile]\n", getprogname());
8040 exit(1);
8043 static const struct got_error *
8044 patch_from_stdin(int *patchfd)
8046 const struct got_error *err = NULL;
8047 ssize_t r;
8048 char buf[BUFSIZ];
8049 sig_t sighup, sigint, sigquit;
8051 *patchfd = got_opentempfd();
8052 if (*patchfd == -1)
8053 return got_error_from_errno("got_opentempfd");
8055 sighup = signal(SIGHUP, SIG_DFL);
8056 sigint = signal(SIGINT, SIG_DFL);
8057 sigquit = signal(SIGQUIT, SIG_DFL);
8059 for (;;) {
8060 r = read(0, buf, sizeof(buf));
8061 if (r == -1) {
8062 err = got_error_from_errno("read");
8063 break;
8065 if (r == 0)
8066 break;
8067 if (write(*patchfd, buf, r) == -1) {
8068 err = got_error_from_errno("write");
8069 break;
8073 signal(SIGHUP, sighup);
8074 signal(SIGINT, sigint);
8075 signal(SIGQUIT, sigquit);
8077 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8078 err = got_error_from_errno("lseek");
8080 if (err != NULL) {
8081 close(*patchfd);
8082 *patchfd = -1;
8085 return err;
8088 static const struct got_error *
8089 patch_progress(void *arg, const char *old, const char *new,
8090 unsigned char status, const struct got_error *error, int old_from,
8091 int old_lines, int new_from, int new_lines, int offset,
8092 int ws_mangled, const struct got_error *hunk_err)
8094 const char *path = new == NULL ? old : new;
8096 while (*path == '/')
8097 path++;
8099 if (status != 0)
8100 printf("%c %s\n", status, path);
8102 if (error != NULL)
8103 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8105 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8106 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8107 old_lines, new_from, new_lines);
8108 if (hunk_err != NULL)
8109 printf("%s\n", hunk_err->msg);
8110 else if (offset != 0)
8111 printf("applied with offset %d\n", offset);
8112 else
8113 printf("hunk contains mangled whitespace\n");
8116 return NULL;
8119 static const struct got_error *
8120 cmd_patch(int argc, char *argv[])
8122 const struct got_error *error = NULL, *close_error = NULL;
8123 struct got_worktree *worktree = NULL;
8124 struct got_repository *repo = NULL;
8125 struct got_reflist_head refs;
8126 struct got_object_id *commit_id = NULL;
8127 const char *commit_id_str = NULL;
8128 struct stat sb;
8129 const char *errstr;
8130 char *cwd = NULL;
8131 int ch, nop = 0, strip = -1, reverse = 0;
8132 int patchfd;
8133 int *pack_fds = NULL;
8135 TAILQ_INIT(&refs);
8137 #ifndef PROFILE
8138 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8139 "unveil", NULL) == -1)
8140 err(1, "pledge");
8141 #endif
8143 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8144 switch (ch) {
8145 case 'c':
8146 commit_id_str = optarg;
8147 break;
8148 case 'n':
8149 nop = 1;
8150 break;
8151 case 'p':
8152 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8153 if (errstr != NULL)
8154 errx(1, "pathname strip count is %s: %s",
8155 errstr, optarg);
8156 break;
8157 case 'R':
8158 reverse = 1;
8159 break;
8160 default:
8161 usage_patch();
8162 /* NOTREACHED */
8166 argc -= optind;
8167 argv += optind;
8169 if (argc == 0) {
8170 error = patch_from_stdin(&patchfd);
8171 if (error)
8172 return error;
8173 } else if (argc == 1) {
8174 patchfd = open(argv[0], O_RDONLY);
8175 if (patchfd == -1) {
8176 error = got_error_from_errno2("open", argv[0]);
8177 return error;
8179 if (fstat(patchfd, &sb) == -1) {
8180 error = got_error_from_errno2("fstat", argv[0]);
8181 goto done;
8183 if (!S_ISREG(sb.st_mode)) {
8184 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8185 goto done;
8187 } else
8188 usage_patch();
8190 if ((cwd = getcwd(NULL, 0)) == NULL) {
8191 error = got_error_from_errno("getcwd");
8192 goto done;
8195 error = got_repo_pack_fds_open(&pack_fds);
8196 if (error != NULL)
8197 goto done;
8199 error = got_worktree_open(&worktree, cwd);
8200 if (error != NULL)
8201 goto done;
8203 const char *repo_path = got_worktree_get_repo_path(worktree);
8204 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8205 if (error != NULL)
8206 goto done;
8208 error = apply_unveil(got_repo_get_path(repo), 0,
8209 got_worktree_get_root_path(worktree));
8210 if (error != NULL)
8211 goto done;
8213 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8214 if (error)
8215 goto done;
8217 if (commit_id_str != NULL) {
8218 error = got_repo_match_object_id(&commit_id, NULL,
8219 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8220 if (error)
8221 goto done;
8224 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8225 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8227 done:
8228 got_ref_list_free(&refs);
8229 free(commit_id);
8230 if (repo) {
8231 close_error = got_repo_close(repo);
8232 if (error == NULL)
8233 error = close_error;
8235 if (worktree != NULL) {
8236 close_error = got_worktree_close(worktree);
8237 if (error == NULL)
8238 error = close_error;
8240 if (pack_fds) {
8241 const struct got_error *pack_err =
8242 got_repo_pack_fds_close(pack_fds);
8243 if (error == NULL)
8244 error = pack_err;
8246 free(cwd);
8247 return error;
8250 __dead static void
8251 usage_revert(void)
8253 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8254 getprogname());
8255 exit(1);
8258 static const struct got_error *
8259 revert_progress(void *arg, unsigned char status, const char *path)
8261 if (status == GOT_STATUS_UNVERSIONED)
8262 return NULL;
8264 while (path[0] == '/')
8265 path++;
8266 printf("%c %s\n", status, path);
8267 return NULL;
8270 struct choose_patch_arg {
8271 FILE *patch_script_file;
8272 const char *action;
8275 static const struct got_error *
8276 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8277 int nchanges, const char *action)
8279 const struct got_error *err;
8280 char *line = NULL;
8281 size_t linesize = 0;
8282 ssize_t linelen;
8284 switch (status) {
8285 case GOT_STATUS_ADD:
8286 printf("A %s\n%s this addition? [y/n] ", path, action);
8287 break;
8288 case GOT_STATUS_DELETE:
8289 printf("D %s\n%s this deletion? [y/n] ", path, action);
8290 break;
8291 case GOT_STATUS_MODIFY:
8292 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8293 return got_error_from_errno("fseek");
8294 printf(GOT_COMMIT_SEP_STR);
8295 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8296 printf("%s", line);
8297 if (linelen == -1 && ferror(patch_file)) {
8298 err = got_error_from_errno("getline");
8299 free(line);
8300 return err;
8302 free(line);
8303 printf(GOT_COMMIT_SEP_STR);
8304 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8305 path, n, nchanges, action);
8306 break;
8307 default:
8308 return got_error_path(path, GOT_ERR_FILE_STATUS);
8311 fflush(stdout);
8312 return NULL;
8315 static const struct got_error *
8316 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8317 FILE *patch_file, int n, int nchanges)
8319 const struct got_error *err = NULL;
8320 char *line = NULL;
8321 size_t linesize = 0;
8322 ssize_t linelen;
8323 int resp = ' ';
8324 struct choose_patch_arg *a = arg;
8326 *choice = GOT_PATCH_CHOICE_NONE;
8328 if (a->patch_script_file) {
8329 char *nl;
8330 err = show_change(status, path, patch_file, n, nchanges,
8331 a->action);
8332 if (err)
8333 return err;
8334 linelen = getline(&line, &linesize, a->patch_script_file);
8335 if (linelen == -1) {
8336 if (ferror(a->patch_script_file))
8337 return got_error_from_errno("getline");
8338 return NULL;
8340 nl = strchr(line, '\n');
8341 if (nl)
8342 *nl = '\0';
8343 if (strcmp(line, "y") == 0) {
8344 *choice = GOT_PATCH_CHOICE_YES;
8345 printf("y\n");
8346 } else if (strcmp(line, "n") == 0) {
8347 *choice = GOT_PATCH_CHOICE_NO;
8348 printf("n\n");
8349 } else if (strcmp(line, "q") == 0 &&
8350 status == GOT_STATUS_MODIFY) {
8351 *choice = GOT_PATCH_CHOICE_QUIT;
8352 printf("q\n");
8353 } else
8354 printf("invalid response '%s'\n", line);
8355 free(line);
8356 return NULL;
8359 while (resp != 'y' && resp != 'n' && resp != 'q') {
8360 err = show_change(status, path, patch_file, n, nchanges,
8361 a->action);
8362 if (err)
8363 return err;
8364 resp = getchar();
8365 if (resp == '\n')
8366 resp = getchar();
8367 if (status == GOT_STATUS_MODIFY) {
8368 if (resp != 'y' && resp != 'n' && resp != 'q') {
8369 printf("invalid response '%c'\n", resp);
8370 resp = ' ';
8372 } else if (resp != 'y' && resp != 'n') {
8373 printf("invalid response '%c'\n", resp);
8374 resp = ' ';
8378 if (resp == 'y')
8379 *choice = GOT_PATCH_CHOICE_YES;
8380 else if (resp == 'n')
8381 *choice = GOT_PATCH_CHOICE_NO;
8382 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8383 *choice = GOT_PATCH_CHOICE_QUIT;
8385 return NULL;
8388 struct wt_commitable_path_arg {
8389 struct got_pathlist_head *commit_paths;
8390 int *has_changes;
8394 * Shortcut work tree status callback to determine if the set of paths scanned
8395 * has at least one versioned path that is being modified and, if not NULL, is
8396 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8397 * soon as a path is passed with a status that satisfies this criteria.
8399 static const struct got_error *
8400 worktree_has_commitable_path(void *arg, unsigned char status,
8401 unsigned char staged_status, const char *path,
8402 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8403 struct got_object_id *commit_id, int dirfd, const char *de_name)
8405 struct wt_commitable_path_arg *a = arg;
8407 if (status == staged_status && (status == GOT_STATUS_DELETE))
8408 status = GOT_STATUS_NO_CHANGE;
8410 if (!(status == GOT_STATUS_NO_CHANGE ||
8411 status == GOT_STATUS_UNVERSIONED) ||
8412 staged_status != GOT_STATUS_NO_CHANGE) {
8413 if (a->commit_paths != NULL) {
8414 struct got_pathlist_entry *pe;
8416 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8417 if (strncmp(path, pe->path,
8418 pe->path_len) == 0) {
8419 *a->has_changes = 1;
8420 break;
8423 } else
8424 *a->has_changes = 1;
8426 if (*a->has_changes)
8427 return got_error(GOT_ERR_FILE_MODIFIED);
8430 return NULL;
8434 * Check that the changeset of the commit identified by id is
8435 * comprised of at least one modified path that is being committed.
8437 static const struct got_error *
8438 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8439 struct got_object_id *id, struct got_worktree *worktree,
8440 struct got_repository *repo)
8442 const struct got_error *err;
8443 struct got_pathlist_head paths;
8444 struct got_commit_object *commit = NULL, *pcommit = NULL;
8445 struct got_tree_object *tree = NULL, *ptree = NULL;
8446 struct got_object_qid *pid;
8448 TAILQ_INIT(&paths);
8450 err = got_object_open_as_commit(&commit, repo, id);
8451 if (err)
8452 goto done;
8454 err = got_object_open_as_tree(&tree, repo,
8455 got_object_commit_get_tree_id(commit));
8456 if (err)
8457 goto done;
8459 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8460 if (pid != NULL) {
8461 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8462 if (err)
8463 goto done;
8465 err = got_object_open_as_tree(&ptree, repo,
8466 got_object_commit_get_tree_id(pcommit));
8467 if (err)
8468 goto done;
8471 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8472 got_diff_tree_collect_changed_paths, &paths, 0);
8473 if (err)
8474 goto done;
8476 err = got_worktree_status(worktree, &paths, repo, 0,
8477 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8478 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8480 * At least one changed path in the referenced commit is
8481 * modified in the work tree, that's all we need to know!
8483 err = NULL;
8486 done:
8487 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8488 if (commit)
8489 got_object_commit_close(commit);
8490 if (pcommit)
8491 got_object_commit_close(pcommit);
8492 if (tree)
8493 got_object_tree_close(tree);
8494 if (ptree)
8495 got_object_tree_close(ptree);
8496 return err;
8500 * Remove any "logmsg" reference comprised entirely of paths that have
8501 * been reverted in this work tree. If any path in the logmsg ref changeset
8502 * remains in a changed state in the worktree, do not remove the reference.
8504 static const struct got_error *
8505 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8507 const struct got_error *err;
8508 struct got_reflist_head refs;
8509 struct got_reflist_entry *re;
8510 struct got_commit_object *commit = NULL;
8511 struct got_object_id *commit_id = NULL;
8512 struct wt_commitable_path_arg wcpa;
8513 char *uuidstr = NULL;
8515 TAILQ_INIT(&refs);
8517 err = got_worktree_get_uuid(&uuidstr, worktree);
8518 if (err)
8519 goto done;
8521 err = got_ref_list(&refs, repo, "refs/got/worktree",
8522 got_ref_cmp_by_name, repo);
8523 if (err)
8524 goto done;
8526 TAILQ_FOREACH(re, &refs, entry) {
8527 const char *refname;
8528 int has_changes = 0;
8530 refname = got_ref_get_name(re->ref);
8532 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8533 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8534 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8535 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8536 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8537 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8538 else
8539 continue;
8541 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8542 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8543 else
8544 continue;
8546 err = got_repo_match_object_id(&commit_id, NULL, refname,
8547 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8548 if (err)
8549 goto done;
8551 err = got_object_open_as_commit(&commit, repo, commit_id);
8552 if (err)
8553 goto done;
8555 wcpa.commit_paths = NULL;
8556 wcpa.has_changes = &has_changes;
8558 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8559 worktree, repo);
8560 if (err)
8561 goto done;
8563 if (!has_changes) {
8564 err = got_ref_delete(re->ref, repo);
8565 if (err)
8566 goto done;
8569 got_object_commit_close(commit);
8570 commit = NULL;
8571 free(commit_id);
8572 commit_id = NULL;
8575 done:
8576 free(uuidstr);
8577 free(commit_id);
8578 got_ref_list_free(&refs);
8579 if (commit)
8580 got_object_commit_close(commit);
8581 return err;
8584 static const struct got_error *
8585 cmd_revert(int argc, char *argv[])
8587 const struct got_error *error = NULL;
8588 struct got_worktree *worktree = NULL;
8589 struct got_repository *repo = NULL;
8590 char *cwd = NULL, *path = NULL;
8591 struct got_pathlist_head paths;
8592 struct got_pathlist_entry *pe;
8593 int ch, can_recurse = 0, pflag = 0;
8594 FILE *patch_script_file = NULL;
8595 const char *patch_script_path = NULL;
8596 struct choose_patch_arg cpa;
8597 int *pack_fds = NULL;
8599 TAILQ_INIT(&paths);
8601 #ifndef PROFILE
8602 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8603 "unveil", NULL) == -1)
8604 err(1, "pledge");
8605 #endif
8607 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8608 switch (ch) {
8609 case 'F':
8610 patch_script_path = optarg;
8611 break;
8612 case 'p':
8613 pflag = 1;
8614 break;
8615 case 'R':
8616 can_recurse = 1;
8617 break;
8618 default:
8619 usage_revert();
8620 /* NOTREACHED */
8624 argc -= optind;
8625 argv += optind;
8627 if (argc < 1)
8628 usage_revert();
8629 if (patch_script_path && !pflag)
8630 errx(1, "-F option can only be used together with -p option");
8632 cwd = getcwd(NULL, 0);
8633 if (cwd == NULL) {
8634 error = got_error_from_errno("getcwd");
8635 goto done;
8638 error = got_repo_pack_fds_open(&pack_fds);
8639 if (error != NULL)
8640 goto done;
8642 error = got_worktree_open(&worktree, cwd);
8643 if (error) {
8644 if (error->code == GOT_ERR_NOT_WORKTREE)
8645 error = wrap_not_worktree_error(error, "revert", cwd);
8646 goto done;
8649 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8650 NULL, pack_fds);
8651 if (error != NULL)
8652 goto done;
8654 if (patch_script_path) {
8655 patch_script_file = fopen(patch_script_path, "re");
8656 if (patch_script_file == NULL) {
8657 error = got_error_from_errno2("fopen",
8658 patch_script_path);
8659 goto done;
8664 * XXX "c" perm needed on repo dir to delete merge references.
8666 error = apply_unveil(got_repo_get_path(repo), 0,
8667 got_worktree_get_root_path(worktree));
8668 if (error)
8669 goto done;
8671 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8672 if (error)
8673 goto done;
8675 if (!can_recurse) {
8676 char *ondisk_path;
8677 struct stat sb;
8678 TAILQ_FOREACH(pe, &paths, entry) {
8679 if (asprintf(&ondisk_path, "%s/%s",
8680 got_worktree_get_root_path(worktree),
8681 pe->path) == -1) {
8682 error = got_error_from_errno("asprintf");
8683 goto done;
8685 if (lstat(ondisk_path, &sb) == -1) {
8686 if (errno == ENOENT) {
8687 free(ondisk_path);
8688 continue;
8690 error = got_error_from_errno2("lstat",
8691 ondisk_path);
8692 free(ondisk_path);
8693 goto done;
8695 free(ondisk_path);
8696 if (S_ISDIR(sb.st_mode)) {
8697 error = got_error_msg(GOT_ERR_BAD_PATH,
8698 "reverting directories requires -R option");
8699 goto done;
8704 cpa.patch_script_file = patch_script_file;
8705 cpa.action = "revert";
8706 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8707 pflag ? choose_patch : NULL, &cpa, repo);
8709 error = rm_logmsg_ref(worktree, repo);
8710 done:
8711 if (patch_script_file && fclose(patch_script_file) == EOF &&
8712 error == NULL)
8713 error = got_error_from_errno2("fclose", patch_script_path);
8714 if (repo) {
8715 const struct got_error *close_err = got_repo_close(repo);
8716 if (error == NULL)
8717 error = close_err;
8719 if (worktree)
8720 got_worktree_close(worktree);
8721 if (pack_fds) {
8722 const struct got_error *pack_err =
8723 got_repo_pack_fds_close(pack_fds);
8724 if (error == NULL)
8725 error = pack_err;
8727 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8728 free(path);
8729 free(cwd);
8730 return error;
8733 __dead static void
8734 usage_commit(void)
8736 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8737 "[-m message] [path ...]\n", getprogname());
8738 exit(1);
8741 struct collect_commit_logmsg_arg {
8742 const char *cmdline_log;
8743 const char *prepared_log;
8744 const char *merged_log;
8745 int non_interactive;
8746 const char *editor;
8747 const char *worktree_path;
8748 const char *branch_name;
8749 const char *repo_path;
8750 char *logmsg_path;
8754 static const struct got_error *
8755 read_prepared_logmsg(char **logmsg, const char *path)
8757 const struct got_error *err = NULL;
8758 FILE *f = NULL;
8759 struct stat sb;
8760 size_t r;
8762 *logmsg = NULL;
8763 memset(&sb, 0, sizeof(sb));
8765 f = fopen(path, "re");
8766 if (f == NULL)
8767 return got_error_from_errno2("fopen", path);
8769 if (fstat(fileno(f), &sb) == -1) {
8770 err = got_error_from_errno2("fstat", path);
8771 goto done;
8773 if (sb.st_size == 0) {
8774 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8775 goto done;
8778 *logmsg = malloc(sb.st_size + 1);
8779 if (*logmsg == NULL) {
8780 err = got_error_from_errno("malloc");
8781 goto done;
8784 r = fread(*logmsg, 1, sb.st_size, f);
8785 if (r != sb.st_size) {
8786 if (ferror(f))
8787 err = got_error_from_errno2("fread", path);
8788 else
8789 err = got_error(GOT_ERR_IO);
8790 goto done;
8792 (*logmsg)[sb.st_size] = '\0';
8793 done:
8794 if (fclose(f) == EOF && err == NULL)
8795 err = got_error_from_errno2("fclose", path);
8796 if (err) {
8797 free(*logmsg);
8798 *logmsg = NULL;
8800 return err;
8803 static const struct got_error *
8804 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8805 const char *diff_path, char **logmsg, void *arg)
8807 char *initial_content = NULL;
8808 struct got_pathlist_entry *pe;
8809 const struct got_error *err = NULL;
8810 char *template = NULL;
8811 char *prepared_msg = NULL, *merged_msg = NULL;
8812 struct collect_commit_logmsg_arg *a = arg;
8813 int initial_content_len;
8814 int fd = -1;
8815 size_t len;
8817 /* if a message was specified on the command line, just use it */
8818 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8819 len = strlen(a->cmdline_log) + 1;
8820 *logmsg = malloc(len + 1);
8821 if (*logmsg == NULL)
8822 return got_error_from_errno("malloc");
8823 strlcpy(*logmsg, a->cmdline_log, len);
8824 return NULL;
8825 } else if (a->prepared_log != NULL && a->non_interactive)
8826 return read_prepared_logmsg(logmsg, a->prepared_log);
8828 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8829 return got_error_from_errno("asprintf");
8831 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8832 if (err)
8833 goto done;
8835 if (a->prepared_log) {
8836 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8837 if (err)
8838 goto done;
8839 } else if (a->merged_log) {
8840 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8841 if (err)
8842 goto done;
8845 initial_content_len = asprintf(&initial_content,
8846 "%s%s\n# changes to be committed on branch %s:\n",
8847 prepared_msg ? prepared_msg : "",
8848 merged_msg ? merged_msg : "", a->branch_name);
8849 if (initial_content_len == -1) {
8850 err = got_error_from_errno("asprintf");
8851 goto done;
8854 if (write(fd, initial_content, initial_content_len) == -1) {
8855 err = got_error_from_errno2("write", a->logmsg_path);
8856 goto done;
8859 TAILQ_FOREACH(pe, commitable_paths, entry) {
8860 struct got_commitable *ct = pe->data;
8861 dprintf(fd, "# %c %s\n",
8862 got_commitable_get_status(ct),
8863 got_commitable_get_path(ct));
8866 if (diff_path) {
8867 dprintf(fd, "# detailed changes can be viewed in %s\n",
8868 diff_path);
8871 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8872 initial_content_len, a->prepared_log ? 0 : 1);
8873 done:
8874 free(initial_content);
8875 free(template);
8876 free(prepared_msg);
8877 free(merged_msg);
8879 if (fd != -1 && close(fd) == -1 && err == NULL)
8880 err = got_error_from_errno2("close", a->logmsg_path);
8882 /* Editor is done; we can now apply unveil(2) */
8883 if (err == NULL)
8884 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8885 if (err) {
8886 free(*logmsg);
8887 *logmsg = NULL;
8889 return err;
8892 static const struct got_error *
8893 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8894 const char *type, int has_content)
8896 const struct got_error *err = NULL;
8897 char *logmsg = NULL;
8899 err = got_object_commit_get_logmsg(&logmsg, commit);
8900 if (err)
8901 return err;
8903 if (fprintf(f, "%s# log message of %s commit %s:%s",
8904 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8905 err = got_ferror(f, GOT_ERR_IO);
8907 free(logmsg);
8908 return err;
8912 * Lookup "logmsg" references of backed-out and cherrypicked commits
8913 * belonging to the current work tree. If found, and the worktree has
8914 * at least one modified file that was changed in the referenced commit,
8915 * add its log message to a new temporary file at *logmsg_path.
8916 * Add all refs found to matched_refs to be scheduled for removal on
8917 * successful commit.
8919 static const struct got_error *
8920 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8921 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8922 struct got_repository *repo)
8924 const struct got_error *err;
8925 struct got_commit_object *commit = NULL;
8926 struct got_object_id *id = NULL;
8927 struct got_reflist_head refs;
8928 struct got_reflist_entry *re, *re_match;
8929 FILE *f = NULL;
8930 char *uuidstr = NULL;
8931 int added_logmsg = 0;
8933 TAILQ_INIT(&refs);
8935 *logmsg_path = NULL;
8937 err = got_worktree_get_uuid(&uuidstr, worktree);
8938 if (err)
8939 goto done;
8941 err = got_ref_list(&refs, repo, "refs/got/worktree",
8942 got_ref_cmp_by_name, repo);
8943 if (err)
8944 goto done;
8946 TAILQ_FOREACH(re, &refs, entry) {
8947 const char *refname, *type;
8948 struct wt_commitable_path_arg wcpa;
8949 int add_logmsg = 0;
8951 refname = got_ref_get_name(re->ref);
8953 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8954 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8955 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8956 type = "cherrypicked";
8957 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8958 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8959 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8960 type = "backed-out";
8961 } else
8962 continue;
8964 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8965 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8966 else
8967 continue;
8969 err = got_repo_match_object_id(&id, NULL, refname,
8970 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8971 if (err)
8972 goto done;
8974 err = got_object_open_as_commit(&commit, repo, id);
8975 if (err)
8976 goto done;
8978 wcpa.commit_paths = paths;
8979 wcpa.has_changes = &add_logmsg;
8981 err = commit_path_changed_in_worktree(&wcpa, id,
8982 worktree, repo);
8983 if (err)
8984 goto done;
8986 if (add_logmsg) {
8987 if (f == NULL) {
8988 err = got_opentemp_named(logmsg_path, &f,
8989 "got-commit-logmsg", "");
8990 if (err)
8991 goto done;
8993 err = cat_logmsg(f, commit, refname, type,
8994 added_logmsg);
8995 if (err)
8996 goto done;
8997 if (!added_logmsg)
8998 ++added_logmsg;
9000 err = got_reflist_entry_dup(&re_match, re);
9001 if (err)
9002 goto done;
9003 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9006 got_object_commit_close(commit);
9007 commit = NULL;
9008 free(id);
9009 id = NULL;
9012 done:
9013 free(id);
9014 free(uuidstr);
9015 got_ref_list_free(&refs);
9016 if (commit)
9017 got_object_commit_close(commit);
9018 if (f && fclose(f) == EOF && err == NULL)
9019 err = got_error_from_errno("fclose");
9020 if (!added_logmsg) {
9021 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9022 err = got_error_from_errno2("unlink", *logmsg_path);
9023 *logmsg_path = NULL;
9025 return err;
9028 static const struct got_error *
9029 cmd_commit(int argc, char *argv[])
9031 const struct got_error *error = NULL;
9032 struct got_worktree *worktree = NULL;
9033 struct got_repository *repo = NULL;
9034 char *cwd = NULL, *id_str = NULL;
9035 struct got_object_id *id = NULL;
9036 const char *logmsg = NULL;
9037 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9038 struct collect_commit_logmsg_arg cl_arg;
9039 const char *author = NULL;
9040 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9041 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9042 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9043 int show_diff = 1;
9044 struct got_pathlist_head paths;
9045 struct got_reflist_head refs;
9046 struct got_reflist_entry *re;
9047 int *pack_fds = NULL;
9049 TAILQ_INIT(&refs);
9050 TAILQ_INIT(&paths);
9051 cl_arg.logmsg_path = NULL;
9053 #ifndef PROFILE
9054 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9055 "unveil", NULL) == -1)
9056 err(1, "pledge");
9057 #endif
9059 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9060 switch (ch) {
9061 case 'A':
9062 author = optarg;
9063 error = valid_author(author);
9064 if (error)
9065 return error;
9066 break;
9067 case 'F':
9068 if (logmsg != NULL)
9069 option_conflict('F', 'm');
9070 prepared_logmsg = realpath(optarg, NULL);
9071 if (prepared_logmsg == NULL)
9072 return got_error_from_errno2("realpath",
9073 optarg);
9074 break;
9075 case 'm':
9076 if (prepared_logmsg)
9077 option_conflict('m', 'F');
9078 logmsg = optarg;
9079 break;
9080 case 'N':
9081 non_interactive = 1;
9082 break;
9083 case 'n':
9084 show_diff = 0;
9085 break;
9086 case 'S':
9087 allow_bad_symlinks = 1;
9088 break;
9089 default:
9090 usage_commit();
9091 /* NOTREACHED */
9095 argc -= optind;
9096 argv += optind;
9098 cwd = getcwd(NULL, 0);
9099 if (cwd == NULL) {
9100 error = got_error_from_errno("getcwd");
9101 goto done;
9104 error = got_repo_pack_fds_open(&pack_fds);
9105 if (error != NULL)
9106 goto done;
9108 error = got_worktree_open(&worktree, cwd);
9109 if (error) {
9110 if (error->code == GOT_ERR_NOT_WORKTREE)
9111 error = wrap_not_worktree_error(error, "commit", cwd);
9112 goto done;
9115 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9116 if (error)
9117 goto done;
9118 if (rebase_in_progress) {
9119 error = got_error(GOT_ERR_REBASING);
9120 goto done;
9123 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9124 worktree);
9125 if (error)
9126 goto done;
9128 error = get_gitconfig_path(&gitconfig_path);
9129 if (error)
9130 goto done;
9131 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9132 gitconfig_path, pack_fds);
9133 if (error != NULL)
9134 goto done;
9136 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9137 if (error)
9138 goto done;
9139 if (merge_in_progress) {
9140 error = got_error(GOT_ERR_MERGE_BUSY);
9141 goto done;
9144 error = get_author(&committer, repo, worktree);
9145 if (error)
9146 goto done;
9148 if (author == NULL)
9149 author = committer;
9152 * unveil(2) traverses exec(2); if an editor is used we have
9153 * to apply unveil after the log message has been written.
9155 if (logmsg == NULL || strlen(logmsg) == 0)
9156 error = get_editor(&editor);
9157 else
9158 error = apply_unveil(got_repo_get_path(repo), 0,
9159 got_worktree_get_root_path(worktree));
9160 if (error)
9161 goto done;
9163 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9164 if (error)
9165 goto done;
9167 if (prepared_logmsg == NULL) {
9168 error = lookup_logmsg_ref(&merged_logmsg,
9169 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9170 if (error)
9171 goto done;
9174 cl_arg.editor = editor;
9175 cl_arg.cmdline_log = logmsg;
9176 cl_arg.prepared_log = prepared_logmsg;
9177 cl_arg.merged_log = merged_logmsg;
9178 cl_arg.non_interactive = non_interactive;
9179 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9180 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9181 if (!histedit_in_progress) {
9182 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9183 error = got_error(GOT_ERR_COMMIT_BRANCH);
9184 goto done;
9186 cl_arg.branch_name += 11;
9188 cl_arg.repo_path = got_repo_get_path(repo);
9189 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9190 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9191 print_status, NULL, repo);
9192 if (error) {
9193 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9194 cl_arg.logmsg_path != NULL)
9195 preserve_logmsg = 1;
9196 goto done;
9199 error = got_object_id_str(&id_str, id);
9200 if (error)
9201 goto done;
9202 printf("Created commit %s\n", id_str);
9204 TAILQ_FOREACH(re, &refs, entry) {
9205 error = got_ref_delete(re->ref, repo);
9206 if (error)
9207 goto done;
9210 done:
9211 if (preserve_logmsg) {
9212 fprintf(stderr, "%s: log message preserved in %s\n",
9213 getprogname(), cl_arg.logmsg_path);
9214 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9215 error == NULL)
9216 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9217 free(cl_arg.logmsg_path);
9218 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9219 error = got_error_from_errno2("unlink", merged_logmsg);
9220 free(merged_logmsg);
9221 if (repo) {
9222 const struct got_error *close_err = got_repo_close(repo);
9223 if (error == NULL)
9224 error = close_err;
9226 if (worktree)
9227 got_worktree_close(worktree);
9228 if (pack_fds) {
9229 const struct got_error *pack_err =
9230 got_repo_pack_fds_close(pack_fds);
9231 if (error == NULL)
9232 error = pack_err;
9234 got_ref_list_free(&refs);
9235 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9236 free(cwd);
9237 free(id_str);
9238 free(gitconfig_path);
9239 free(editor);
9240 free(committer);
9241 free(prepared_logmsg);
9242 return error;
9245 __dead static void
9246 usage_send(void)
9248 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9249 "[-r repository-path] [-t tag] [remote-repository]\n",
9250 getprogname());
9251 exit(1);
9254 static void
9255 print_load_info(int print_colored, int print_found, int print_trees,
9256 int ncolored, int nfound, int ntrees)
9258 if (print_colored) {
9259 printf("%d commit%s colored", ncolored,
9260 ncolored == 1 ? "" : "s");
9262 if (print_found) {
9263 printf("%s%d object%s found",
9264 ncolored > 0 ? "; " : "",
9265 nfound, nfound == 1 ? "" : "s");
9267 if (print_trees) {
9268 printf("; %d tree%s scanned", ntrees,
9269 ntrees == 1 ? "" : "s");
9273 struct got_send_progress_arg {
9274 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9275 int verbosity;
9276 int last_ncolored;
9277 int last_nfound;
9278 int last_ntrees;
9279 int loading_done;
9280 int last_ncommits;
9281 int last_nobj_total;
9282 int last_p_deltify;
9283 int last_p_written;
9284 int last_p_sent;
9285 int printed_something;
9286 int sent_something;
9287 struct got_pathlist_head *delete_branches;
9290 static const struct got_error *
9291 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9292 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9293 int nobj_written, off_t bytes_sent, const char *refname,
9294 const char *errmsg, int success)
9296 struct got_send_progress_arg *a = arg;
9297 char scaled_packsize[FMT_SCALED_STRSIZE];
9298 char scaled_sent[FMT_SCALED_STRSIZE];
9299 int p_deltify = 0, p_written = 0, p_sent = 0;
9300 int print_colored = 0, print_found = 0, print_trees = 0;
9301 int print_searching = 0, print_total = 0;
9302 int print_deltify = 0, print_written = 0, print_sent = 0;
9304 if (a->verbosity < 0)
9305 return NULL;
9307 if (refname) {
9308 const char *status = success ? "accepted" : "rejected";
9310 if (success) {
9311 struct got_pathlist_entry *pe;
9312 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9313 const char *branchname = pe->path;
9314 if (got_path_cmp(branchname, refname,
9315 strlen(branchname), strlen(refname)) == 0) {
9316 status = "deleted";
9317 a->sent_something = 1;
9318 break;
9323 if (a->printed_something)
9324 putchar('\n');
9325 printf("Server has %s %s", status, refname);
9326 if (errmsg)
9327 printf(": %s", errmsg);
9328 a->printed_something = 1;
9329 return NULL;
9332 if (a->last_ncolored != ncolored) {
9333 print_colored = 1;
9334 a->last_ncolored = ncolored;
9337 if (a->last_nfound != nfound) {
9338 print_colored = 1;
9339 print_found = 1;
9340 a->last_nfound = nfound;
9343 if (a->last_ntrees != ntrees) {
9344 print_colored = 1;
9345 print_found = 1;
9346 print_trees = 1;
9347 a->last_ntrees = ntrees;
9350 if ((print_colored || print_found || print_trees) &&
9351 !a->loading_done) {
9352 printf("\r");
9353 print_load_info(print_colored, print_found, print_trees,
9354 ncolored, nfound, ntrees);
9355 a->printed_something = 1;
9356 fflush(stdout);
9357 return NULL;
9358 } else if (!a->loading_done) {
9359 printf("\r");
9360 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9361 printf("\n");
9362 a->loading_done = 1;
9365 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9366 return got_error_from_errno("fmt_scaled");
9367 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9368 return got_error_from_errno("fmt_scaled");
9370 if (a->last_ncommits != ncommits) {
9371 print_searching = 1;
9372 a->last_ncommits = ncommits;
9375 if (a->last_nobj_total != nobj_total) {
9376 print_searching = 1;
9377 print_total = 1;
9378 a->last_nobj_total = nobj_total;
9381 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9382 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9383 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9384 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9385 return got_error(GOT_ERR_NO_SPACE);
9388 if (nobj_deltify > 0 || nobj_written > 0) {
9389 if (nobj_deltify > 0) {
9390 p_deltify = (nobj_deltify * 100) / nobj_total;
9391 if (p_deltify != a->last_p_deltify) {
9392 a->last_p_deltify = p_deltify;
9393 print_searching = 1;
9394 print_total = 1;
9395 print_deltify = 1;
9398 if (nobj_written > 0) {
9399 p_written = (nobj_written * 100) / nobj_total;
9400 if (p_written != a->last_p_written) {
9401 a->last_p_written = p_written;
9402 print_searching = 1;
9403 print_total = 1;
9404 print_deltify = 1;
9405 print_written = 1;
9410 if (bytes_sent > 0) {
9411 p_sent = (bytes_sent * 100) / packfile_size;
9412 if (p_sent != a->last_p_sent) {
9413 a->last_p_sent = p_sent;
9414 print_searching = 1;
9415 print_total = 1;
9416 print_deltify = 1;
9417 print_written = 1;
9418 print_sent = 1;
9420 a->sent_something = 1;
9423 if (print_searching || print_total || print_deltify || print_written ||
9424 print_sent)
9425 printf("\r");
9426 if (print_searching)
9427 printf("packing %d reference%s", ncommits,
9428 ncommits == 1 ? "" : "s");
9429 if (print_total)
9430 printf("; %d object%s", nobj_total,
9431 nobj_total == 1 ? "" : "s");
9432 if (print_deltify)
9433 printf("; deltify: %d%%", p_deltify);
9434 if (print_sent)
9435 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9436 scaled_packsize, p_sent);
9437 else if (print_written)
9438 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9439 scaled_packsize, p_written);
9440 if (print_searching || print_total || print_deltify ||
9441 print_written || print_sent) {
9442 a->printed_something = 1;
9443 fflush(stdout);
9445 return NULL;
9448 static const struct got_error *
9449 cmd_send(int argc, char *argv[])
9451 const struct got_error *error = NULL;
9452 char *cwd = NULL, *repo_path = NULL;
9453 const char *remote_name;
9454 char *proto = NULL, *host = NULL, *port = NULL;
9455 char *repo_name = NULL, *server_path = NULL;
9456 const struct got_remote_repo *remotes, *remote = NULL;
9457 int nremotes, nbranches = 0, ndelete_branches = 0;
9458 struct got_repository *repo = NULL;
9459 struct got_worktree *worktree = NULL;
9460 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9461 struct got_pathlist_head branches;
9462 struct got_pathlist_head tags;
9463 struct got_reflist_head all_branches;
9464 struct got_reflist_head all_tags;
9465 struct got_pathlist_head delete_args;
9466 struct got_pathlist_head delete_branches;
9467 struct got_reflist_entry *re;
9468 struct got_pathlist_entry *pe;
9469 int i, ch, sendfd = -1, sendstatus;
9470 pid_t sendpid = -1;
9471 struct got_send_progress_arg spa;
9472 int verbosity = 0, overwrite_refs = 0;
9473 int send_all_branches = 0, send_all_tags = 0;
9474 struct got_reference *ref = NULL;
9475 int *pack_fds = NULL;
9477 TAILQ_INIT(&branches);
9478 TAILQ_INIT(&tags);
9479 TAILQ_INIT(&all_branches);
9480 TAILQ_INIT(&all_tags);
9481 TAILQ_INIT(&delete_args);
9482 TAILQ_INIT(&delete_branches);
9484 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9485 switch (ch) {
9486 case 'a':
9487 send_all_branches = 1;
9488 break;
9489 case 'b':
9490 error = got_pathlist_append(&branches, optarg, NULL);
9491 if (error)
9492 return error;
9493 nbranches++;
9494 break;
9495 case 'd':
9496 error = got_pathlist_append(&delete_args, optarg, NULL);
9497 if (error)
9498 return error;
9499 break;
9500 case 'f':
9501 overwrite_refs = 1;
9502 break;
9503 case 'q':
9504 verbosity = -1;
9505 break;
9506 case 'r':
9507 repo_path = realpath(optarg, NULL);
9508 if (repo_path == NULL)
9509 return got_error_from_errno2("realpath",
9510 optarg);
9511 got_path_strip_trailing_slashes(repo_path);
9512 break;
9513 case 'T':
9514 send_all_tags = 1;
9515 break;
9516 case 't':
9517 error = got_pathlist_append(&tags, optarg, NULL);
9518 if (error)
9519 return error;
9520 break;
9521 case 'v':
9522 if (verbosity < 0)
9523 verbosity = 0;
9524 else if (verbosity < 3)
9525 verbosity++;
9526 break;
9527 default:
9528 usage_send();
9529 /* NOTREACHED */
9532 argc -= optind;
9533 argv += optind;
9535 if (send_all_branches && !TAILQ_EMPTY(&branches))
9536 option_conflict('a', 'b');
9537 if (send_all_tags && !TAILQ_EMPTY(&tags))
9538 option_conflict('T', 't');
9541 if (argc == 0)
9542 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9543 else if (argc == 1)
9544 remote_name = argv[0];
9545 else
9546 usage_send();
9548 cwd = getcwd(NULL, 0);
9549 if (cwd == NULL) {
9550 error = got_error_from_errno("getcwd");
9551 goto done;
9554 error = got_repo_pack_fds_open(&pack_fds);
9555 if (error != NULL)
9556 goto done;
9558 if (repo_path == NULL) {
9559 error = got_worktree_open(&worktree, cwd);
9560 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9561 goto done;
9562 else
9563 error = NULL;
9564 if (worktree) {
9565 repo_path =
9566 strdup(got_worktree_get_repo_path(worktree));
9567 if (repo_path == NULL)
9568 error = got_error_from_errno("strdup");
9569 if (error)
9570 goto done;
9571 } else {
9572 repo_path = strdup(cwd);
9573 if (repo_path == NULL) {
9574 error = got_error_from_errno("strdup");
9575 goto done;
9580 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9581 if (error)
9582 goto done;
9584 if (worktree) {
9585 worktree_conf = got_worktree_get_gotconfig(worktree);
9586 if (worktree_conf) {
9587 got_gotconfig_get_remotes(&nremotes, &remotes,
9588 worktree_conf);
9589 for (i = 0; i < nremotes; i++) {
9590 if (strcmp(remotes[i].name, remote_name) == 0) {
9591 remote = &remotes[i];
9592 break;
9597 if (remote == NULL) {
9598 repo_conf = got_repo_get_gotconfig(repo);
9599 if (repo_conf) {
9600 got_gotconfig_get_remotes(&nremotes, &remotes,
9601 repo_conf);
9602 for (i = 0; i < nremotes; i++) {
9603 if (strcmp(remotes[i].name, remote_name) == 0) {
9604 remote = &remotes[i];
9605 break;
9610 if (remote == NULL) {
9611 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9612 for (i = 0; i < nremotes; i++) {
9613 if (strcmp(remotes[i].name, remote_name) == 0) {
9614 remote = &remotes[i];
9615 break;
9619 if (remote == NULL) {
9620 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9621 goto done;
9624 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9625 &repo_name, remote->send_url);
9626 if (error)
9627 goto done;
9629 if (strcmp(proto, "git") == 0) {
9630 #ifndef PROFILE
9631 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9632 "sendfd dns inet unveil", NULL) == -1)
9633 err(1, "pledge");
9634 #endif
9635 } else if (strcmp(proto, "git+ssh") == 0 ||
9636 strcmp(proto, "ssh") == 0) {
9637 #ifndef PROFILE
9638 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9639 "sendfd unveil", NULL) == -1)
9640 err(1, "pledge");
9641 #endif
9642 } else if (strcmp(proto, "http") == 0 ||
9643 strcmp(proto, "git+http") == 0) {
9644 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9645 goto done;
9646 } else {
9647 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9648 goto done;
9651 error = got_dial_apply_unveil(proto);
9652 if (error)
9653 goto done;
9655 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9656 if (error)
9657 goto done;
9659 if (send_all_branches) {
9660 error = got_ref_list(&all_branches, repo, "refs/heads",
9661 got_ref_cmp_by_name, NULL);
9662 if (error)
9663 goto done;
9664 TAILQ_FOREACH(re, &all_branches, entry) {
9665 const char *branchname = got_ref_get_name(re->ref);
9666 error = got_pathlist_append(&branches,
9667 branchname, NULL);
9668 if (error)
9669 goto done;
9670 nbranches++;
9672 } else if (nbranches == 0) {
9673 for (i = 0; i < remote->nsend_branches; i++) {
9674 error = got_pathlist_append(&branches,
9675 remote->send_branches[i], NULL);
9676 if (error)
9677 goto done;
9681 if (send_all_tags) {
9682 error = got_ref_list(&all_tags, repo, "refs/tags",
9683 got_ref_cmp_by_name, NULL);
9684 if (error)
9685 goto done;
9686 TAILQ_FOREACH(re, &all_tags, entry) {
9687 const char *tagname = got_ref_get_name(re->ref);
9688 error = got_pathlist_append(&tags,
9689 tagname, NULL);
9690 if (error)
9691 goto done;
9696 * To prevent accidents only branches in refs/heads/ can be deleted
9697 * with 'got send -d'.
9698 * Deleting anything else requires local repository access or Git.
9700 TAILQ_FOREACH(pe, &delete_args, entry) {
9701 const char *branchname = pe->path;
9702 char *s;
9703 struct got_pathlist_entry *new;
9704 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9705 s = strdup(branchname);
9706 if (s == NULL) {
9707 error = got_error_from_errno("strdup");
9708 goto done;
9710 } else {
9711 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9712 error = got_error_from_errno("asprintf");
9713 goto done;
9716 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9717 if (error || new == NULL /* duplicate */)
9718 free(s);
9719 if (error)
9720 goto done;
9721 ndelete_branches++;
9724 if (nbranches == 0 && ndelete_branches == 0) {
9725 struct got_reference *head_ref;
9726 if (worktree)
9727 error = got_ref_open(&head_ref, repo,
9728 got_worktree_get_head_ref_name(worktree), 0);
9729 else
9730 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9731 if (error)
9732 goto done;
9733 if (got_ref_is_symbolic(head_ref)) {
9734 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9735 got_ref_close(head_ref);
9736 if (error)
9737 goto done;
9738 } else
9739 ref = head_ref;
9740 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9741 NULL);
9742 if (error)
9743 goto done;
9744 nbranches++;
9747 if (verbosity >= 0) {
9748 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9749 remote->name, proto, host,
9750 port ? ":" : "", port ? port : "",
9751 *server_path == '/' ? "" : "/", server_path);
9754 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9755 server_path, verbosity);
9756 if (error)
9757 goto done;
9759 memset(&spa, 0, sizeof(spa));
9760 spa.last_scaled_packsize[0] = '\0';
9761 spa.last_p_deltify = -1;
9762 spa.last_p_written = -1;
9763 spa.verbosity = verbosity;
9764 spa.delete_branches = &delete_branches;
9765 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9766 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9767 check_cancelled, NULL);
9768 if (spa.printed_something)
9769 putchar('\n');
9770 if (error)
9771 goto done;
9772 if (!spa.sent_something && verbosity >= 0)
9773 printf("Already up-to-date\n");
9774 done:
9775 if (sendpid > 0) {
9776 if (kill(sendpid, SIGTERM) == -1)
9777 error = got_error_from_errno("kill");
9778 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9779 error = got_error_from_errno("waitpid");
9781 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9782 error = got_error_from_errno("close");
9783 if (repo) {
9784 const struct got_error *close_err = got_repo_close(repo);
9785 if (error == NULL)
9786 error = close_err;
9788 if (worktree)
9789 got_worktree_close(worktree);
9790 if (pack_fds) {
9791 const struct got_error *pack_err =
9792 got_repo_pack_fds_close(pack_fds);
9793 if (error == NULL)
9794 error = pack_err;
9796 if (ref)
9797 got_ref_close(ref);
9798 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9799 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9800 got_ref_list_free(&all_branches);
9801 got_ref_list_free(&all_tags);
9802 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9803 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9804 free(cwd);
9805 free(repo_path);
9806 free(proto);
9807 free(host);
9808 free(port);
9809 free(server_path);
9810 free(repo_name);
9811 return error;
9815 * Print and if delete is set delete all ref_prefix references.
9816 * If wanted_ref is not NULL, only print or delete this reference.
9818 static const struct got_error *
9819 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9820 const char *wanted_ref, int delete, struct got_worktree *worktree,
9821 struct got_repository *repo)
9823 const struct got_error *err;
9824 struct got_pathlist_head paths;
9825 struct got_reflist_head refs;
9826 struct got_reflist_entry *re;
9827 struct got_reflist_object_id_map *refs_idmap = NULL;
9828 struct got_commit_object *commit = NULL;
9829 struct got_object_id *id = NULL;
9830 const char *header_prefix;
9831 char *uuidstr = NULL;
9832 int found = 0;
9834 TAILQ_INIT(&refs);
9835 TAILQ_INIT(&paths);
9837 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9838 if (err)
9839 goto done;
9841 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9842 if (err)
9843 goto done;
9845 if (worktree != NULL) {
9846 err = got_worktree_get_uuid(&uuidstr, worktree);
9847 if (err)
9848 goto done;
9851 if (wanted_ref) {
9852 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9853 wanted_ref += 11;
9856 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9857 header_prefix = "backout";
9858 else
9859 header_prefix = "cherrypick";
9861 TAILQ_FOREACH(re, &refs, entry) {
9862 const char *refname, *wt;
9864 refname = got_ref_get_name(re->ref);
9866 err = check_cancelled(NULL);
9867 if (err)
9868 goto done;
9870 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9871 refname += prefix_len + 1; /* skip '-' delimiter */
9872 else
9873 continue;
9875 wt = refname;
9877 if (worktree == NULL || strncmp(refname, uuidstr,
9878 GOT_WORKTREE_UUID_STRLEN) == 0)
9879 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9880 else
9881 continue;
9883 err = got_repo_match_object_id(&id, NULL, refname,
9884 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9885 if (err)
9886 goto done;
9888 err = got_object_open_as_commit(&commit, repo, id);
9889 if (err)
9890 goto done;
9892 if (wanted_ref)
9893 found = strncmp(wanted_ref, refname,
9894 strlen(wanted_ref)) == 0;
9895 if (wanted_ref && !found) {
9896 struct got_reflist_head *ci_refs;
9898 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9899 id);
9901 if (ci_refs) {
9902 char *refs_str = NULL;
9903 char const *r = NULL;
9905 err = build_refs_str(&refs_str, ci_refs, id,
9906 repo, 1);
9907 if (err)
9908 goto done;
9910 r = refs_str;
9911 while (r) {
9912 if (strncmp(r, wanted_ref,
9913 strlen(wanted_ref)) == 0) {
9914 found = 1;
9915 break;
9917 r = strchr(r, ' ');
9918 if (r)
9919 ++r;
9921 free(refs_str);
9925 if (wanted_ref == NULL || found) {
9926 if (delete) {
9927 err = got_ref_delete(re->ref, repo);
9928 if (err)
9929 goto done;
9930 printf("Deleted: ");
9931 err = print_commit_oneline(commit, id, repo,
9932 refs_idmap);
9933 } else {
9935 * Print paths modified by commit to help
9936 * associate commits with worktree changes.
9938 err = get_changed_paths(&paths, commit,
9939 repo, NULL);
9940 if (err)
9941 goto done;
9943 err = print_commit(commit, id, repo, NULL,
9944 &paths, NULL, 0, 0, refs_idmap, NULL,
9945 header_prefix);
9946 got_pathlist_free(&paths,
9947 GOT_PATHLIST_FREE_ALL);
9949 if (worktree == NULL)
9950 printf("work tree: %.*s\n\n",
9951 GOT_WORKTREE_UUID_STRLEN, wt);
9953 if (err || found)
9954 goto done;
9957 got_object_commit_close(commit);
9958 commit = NULL;
9959 free(id);
9960 id = NULL;
9963 if (wanted_ref != NULL && !found)
9964 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9966 done:
9967 free(id);
9968 free(uuidstr);
9969 got_ref_list_free(&refs);
9970 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9971 if (refs_idmap)
9972 got_reflist_object_id_map_free(refs_idmap);
9973 if (commit)
9974 got_object_commit_close(commit);
9975 return err;
9979 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9980 * identified by id for log messages to prepopulate the editor on commit.
9982 static const struct got_error *
9983 logmsg_ref(struct got_object_id *id, const char *prefix,
9984 struct got_worktree *worktree, struct got_repository *repo)
9986 const struct got_error *err = NULL;
9987 char *idstr, *ref = NULL, *refname = NULL;
9988 int histedit_in_progress;
9989 int rebase_in_progress, merge_in_progress;
9992 * Silenty refuse to create merge reference if any histedit, merge,
9993 * or rebase operation is in progress.
9995 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9996 worktree);
9997 if (err)
9998 return err;
9999 if (histedit_in_progress)
10000 return NULL;
10002 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10003 if (err)
10004 return err;
10005 if (rebase_in_progress)
10006 return NULL;
10008 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10009 repo);
10010 if (err)
10011 return err;
10012 if (merge_in_progress)
10013 return NULL;
10015 err = got_object_id_str(&idstr, id);
10016 if (err)
10017 return err;
10019 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10020 if (err)
10021 goto done;
10023 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10024 err = got_error_from_errno("asprintf");
10025 goto done;
10028 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10029 -1, repo);
10030 done:
10031 free(ref);
10032 free(idstr);
10033 free(refname);
10034 return err;
10037 __dead static void
10038 usage_cherrypick(void)
10040 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10041 getprogname());
10042 exit(1);
10045 static const struct got_error *
10046 cmd_cherrypick(int argc, char *argv[])
10048 const struct got_error *error = NULL;
10049 struct got_worktree *worktree = NULL;
10050 struct got_repository *repo = NULL;
10051 char *cwd = NULL, *commit_id_str = NULL;
10052 struct got_object_id *commit_id = NULL;
10053 struct got_commit_object *commit = NULL;
10054 struct got_object_qid *pid;
10055 int ch, list_refs = 0, remove_refs = 0;
10056 struct got_update_progress_arg upa;
10057 int *pack_fds = NULL;
10059 #ifndef PROFILE
10060 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10061 "unveil", NULL) == -1)
10062 err(1, "pledge");
10063 #endif
10065 while ((ch = getopt(argc, argv, "lX")) != -1) {
10066 switch (ch) {
10067 case 'l':
10068 list_refs = 1;
10069 break;
10070 case 'X':
10071 remove_refs = 1;
10072 break;
10073 default:
10074 usage_cherrypick();
10075 /* NOTREACHED */
10079 argc -= optind;
10080 argv += optind;
10082 if (list_refs || remove_refs) {
10083 if (argc != 0 && argc != 1)
10084 usage_cherrypick();
10085 } else if (argc != 1)
10086 usage_cherrypick();
10087 if (list_refs && remove_refs)
10088 option_conflict('l', 'X');
10090 cwd = getcwd(NULL, 0);
10091 if (cwd == NULL) {
10092 error = got_error_from_errno("getcwd");
10093 goto done;
10096 error = got_repo_pack_fds_open(&pack_fds);
10097 if (error != NULL)
10098 goto done;
10100 error = got_worktree_open(&worktree, cwd);
10101 if (error) {
10102 if (list_refs || remove_refs) {
10103 if (error->code != GOT_ERR_NOT_WORKTREE)
10104 goto done;
10105 } else {
10106 if (error->code == GOT_ERR_NOT_WORKTREE)
10107 error = wrap_not_worktree_error(error,
10108 "cherrypick", cwd);
10109 goto done;
10113 error = got_repo_open(&repo,
10114 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10115 NULL, pack_fds);
10116 if (error != NULL)
10117 goto done;
10119 error = apply_unveil(got_repo_get_path(repo), 0,
10120 worktree ? got_worktree_get_root_path(worktree) : NULL);
10121 if (error)
10122 goto done;
10124 if (list_refs || remove_refs) {
10125 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10126 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10127 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10128 goto done;
10131 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10132 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10133 if (error)
10134 goto done;
10135 error = got_object_id_str(&commit_id_str, commit_id);
10136 if (error)
10137 goto done;
10139 error = got_object_open_as_commit(&commit, repo, commit_id);
10140 if (error)
10141 goto done;
10142 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10143 memset(&upa, 0, sizeof(upa));
10144 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10145 commit_id, repo, update_progress, &upa, check_cancelled,
10146 NULL);
10147 if (error != NULL)
10148 goto done;
10150 if (upa.did_something) {
10151 error = logmsg_ref(commit_id,
10152 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10153 if (error)
10154 goto done;
10155 printf("Merged commit %s\n", commit_id_str);
10157 print_merge_progress_stats(&upa);
10158 done:
10159 free(cwd);
10160 if (commit)
10161 got_object_commit_close(commit);
10162 free(commit_id_str);
10163 if (worktree)
10164 got_worktree_close(worktree);
10165 if (repo) {
10166 const struct got_error *close_err = got_repo_close(repo);
10167 if (error == NULL)
10168 error = close_err;
10170 if (pack_fds) {
10171 const struct got_error *pack_err =
10172 got_repo_pack_fds_close(pack_fds);
10173 if (error == NULL)
10174 error = pack_err;
10177 return error;
10180 __dead static void
10181 usage_backout(void)
10183 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10184 exit(1);
10187 static const struct got_error *
10188 cmd_backout(int argc, char *argv[])
10190 const struct got_error *error = NULL;
10191 struct got_worktree *worktree = NULL;
10192 struct got_repository *repo = NULL;
10193 char *cwd = NULL, *commit_id_str = NULL;
10194 struct got_object_id *commit_id = NULL;
10195 struct got_commit_object *commit = NULL;
10196 struct got_object_qid *pid;
10197 int ch, list_refs = 0, remove_refs = 0;
10198 struct got_update_progress_arg upa;
10199 int *pack_fds = NULL;
10201 #ifndef PROFILE
10202 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10203 "unveil", NULL) == -1)
10204 err(1, "pledge");
10205 #endif
10207 while ((ch = getopt(argc, argv, "lX")) != -1) {
10208 switch (ch) {
10209 case 'l':
10210 list_refs = 1;
10211 break;
10212 case 'X':
10213 remove_refs = 1;
10214 break;
10215 default:
10216 usage_backout();
10217 /* NOTREACHED */
10221 argc -= optind;
10222 argv += optind;
10224 if (list_refs || remove_refs) {
10225 if (argc != 0 && argc != 1)
10226 usage_backout();
10227 } else if (argc != 1)
10228 usage_backout();
10229 if (list_refs && remove_refs)
10230 option_conflict('l', 'X');
10232 cwd = getcwd(NULL, 0);
10233 if (cwd == NULL) {
10234 error = got_error_from_errno("getcwd");
10235 goto done;
10238 error = got_repo_pack_fds_open(&pack_fds);
10239 if (error != NULL)
10240 goto done;
10242 error = got_worktree_open(&worktree, cwd);
10243 if (error) {
10244 if (list_refs || remove_refs) {
10245 if (error->code != GOT_ERR_NOT_WORKTREE)
10246 goto done;
10247 } else {
10248 if (error->code == GOT_ERR_NOT_WORKTREE)
10249 error = wrap_not_worktree_error(error,
10250 "backout", cwd);
10251 goto done;
10255 error = got_repo_open(&repo,
10256 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10257 NULL, pack_fds);
10258 if (error != NULL)
10259 goto done;
10261 error = apply_unveil(got_repo_get_path(repo), 0,
10262 worktree ? got_worktree_get_root_path(worktree) : NULL);
10263 if (error)
10264 goto done;
10266 if (list_refs || remove_refs) {
10267 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10268 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10269 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10270 goto done;
10273 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10274 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10275 if (error)
10276 goto done;
10277 error = got_object_id_str(&commit_id_str, commit_id);
10278 if (error)
10279 goto done;
10281 error = got_object_open_as_commit(&commit, repo, commit_id);
10282 if (error)
10283 goto done;
10284 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10285 if (pid == NULL) {
10286 error = got_error(GOT_ERR_ROOT_COMMIT);
10287 goto done;
10290 memset(&upa, 0, sizeof(upa));
10291 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10292 repo, update_progress, &upa, check_cancelled, NULL);
10293 if (error != NULL)
10294 goto done;
10296 if (upa.did_something) {
10297 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10298 worktree, repo);
10299 if (error)
10300 goto done;
10301 printf("Backed out commit %s\n", commit_id_str);
10303 print_merge_progress_stats(&upa);
10304 done:
10305 free(cwd);
10306 if (commit)
10307 got_object_commit_close(commit);
10308 free(commit_id_str);
10309 if (worktree)
10310 got_worktree_close(worktree);
10311 if (repo) {
10312 const struct got_error *close_err = got_repo_close(repo);
10313 if (error == NULL)
10314 error = close_err;
10316 if (pack_fds) {
10317 const struct got_error *pack_err =
10318 got_repo_pack_fds_close(pack_fds);
10319 if (error == NULL)
10320 error = pack_err;
10322 return error;
10325 __dead static void
10326 usage_rebase(void)
10328 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10329 exit(1);
10332 static void
10333 trim_logmsg(char *logmsg, int limit)
10335 char *nl;
10336 size_t len;
10338 len = strlen(logmsg);
10339 if (len > limit)
10340 len = limit;
10341 logmsg[len] = '\0';
10342 nl = strchr(logmsg, '\n');
10343 if (nl)
10344 *nl = '\0';
10347 static const struct got_error *
10348 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10350 const struct got_error *err;
10351 char *logmsg0 = NULL;
10352 const char *s;
10354 err = got_object_commit_get_logmsg(&logmsg0, commit);
10355 if (err)
10356 return err;
10358 s = logmsg0;
10359 while (isspace((unsigned char)s[0]))
10360 s++;
10362 *logmsg = strdup(s);
10363 if (*logmsg == NULL) {
10364 err = got_error_from_errno("strdup");
10365 goto done;
10368 trim_logmsg(*logmsg, limit);
10369 done:
10370 free(logmsg0);
10371 return err;
10374 static const struct got_error *
10375 show_rebase_merge_conflict(struct got_object_id *id,
10376 struct got_repository *repo)
10378 const struct got_error *err;
10379 struct got_commit_object *commit = NULL;
10380 char *id_str = NULL, *logmsg = NULL;
10382 err = got_object_open_as_commit(&commit, repo, id);
10383 if (err)
10384 return err;
10386 err = got_object_id_str(&id_str, id);
10387 if (err)
10388 goto done;
10390 id_str[12] = '\0';
10392 err = get_short_logmsg(&logmsg, 42, commit);
10393 if (err)
10394 goto done;
10396 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10397 done:
10398 free(id_str);
10399 got_object_commit_close(commit);
10400 free(logmsg);
10401 return err;
10404 static const struct got_error *
10405 show_rebase_progress(struct got_commit_object *commit,
10406 struct got_object_id *old_id, struct got_object_id *new_id)
10408 const struct got_error *err;
10409 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10411 err = got_object_id_str(&old_id_str, old_id);
10412 if (err)
10413 goto done;
10415 if (new_id) {
10416 err = got_object_id_str(&new_id_str, new_id);
10417 if (err)
10418 goto done;
10421 old_id_str[12] = '\0';
10422 if (new_id_str)
10423 new_id_str[12] = '\0';
10425 err = get_short_logmsg(&logmsg, 42, commit);
10426 if (err)
10427 goto done;
10429 printf("%s -> %s: %s\n", old_id_str,
10430 new_id_str ? new_id_str : "no-op change", logmsg);
10431 done:
10432 free(old_id_str);
10433 free(new_id_str);
10434 free(logmsg);
10435 return err;
10438 static const struct got_error *
10439 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10440 struct got_reference *branch, struct got_reference *tmp_branch,
10441 struct got_repository *repo, int create_backup)
10443 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10444 return got_worktree_rebase_complete(worktree, fileindex,
10445 tmp_branch, branch, repo, create_backup);
10448 static const struct got_error *
10449 rebase_commit(struct got_pathlist_head *merged_paths,
10450 struct got_worktree *worktree, struct got_fileindex *fileindex,
10451 struct got_reference *tmp_branch, const char *committer,
10452 struct got_object_id *commit_id, struct got_repository *repo)
10454 const struct got_error *error;
10455 struct got_commit_object *commit;
10456 struct got_object_id *new_commit_id;
10458 error = got_object_open_as_commit(&commit, repo, commit_id);
10459 if (error)
10460 return error;
10462 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10463 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10464 repo);
10465 if (error) {
10466 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10467 goto done;
10468 error = show_rebase_progress(commit, commit_id, NULL);
10469 } else {
10470 error = show_rebase_progress(commit, commit_id, new_commit_id);
10471 free(new_commit_id);
10473 done:
10474 got_object_commit_close(commit);
10475 return error;
10478 struct check_path_prefix_arg {
10479 const char *path_prefix;
10480 size_t len;
10481 int errcode;
10484 static const struct got_error *
10485 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10486 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10487 struct got_object_id *id1, struct got_object_id *id2,
10488 const char *path1, const char *path2,
10489 mode_t mode1, mode_t mode2, struct got_repository *repo)
10491 struct check_path_prefix_arg *a = arg;
10493 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10494 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10495 return got_error(a->errcode);
10497 return NULL;
10500 static const struct got_error *
10501 check_path_prefix(struct got_object_id *parent_id,
10502 struct got_object_id *commit_id, const char *path_prefix,
10503 int errcode, struct got_repository *repo)
10505 const struct got_error *err;
10506 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10507 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10508 struct check_path_prefix_arg cpp_arg;
10510 if (got_path_is_root_dir(path_prefix))
10511 return NULL;
10513 err = got_object_open_as_commit(&commit, repo, commit_id);
10514 if (err)
10515 goto done;
10517 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10518 if (err)
10519 goto done;
10521 err = got_object_open_as_tree(&tree1, repo,
10522 got_object_commit_get_tree_id(parent_commit));
10523 if (err)
10524 goto done;
10526 err = got_object_open_as_tree(&tree2, repo,
10527 got_object_commit_get_tree_id(commit));
10528 if (err)
10529 goto done;
10531 cpp_arg.path_prefix = path_prefix;
10532 while (cpp_arg.path_prefix[0] == '/')
10533 cpp_arg.path_prefix++;
10534 cpp_arg.len = strlen(cpp_arg.path_prefix);
10535 cpp_arg.errcode = errcode;
10536 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10537 check_path_prefix_in_diff, &cpp_arg, 0);
10538 done:
10539 if (tree1)
10540 got_object_tree_close(tree1);
10541 if (tree2)
10542 got_object_tree_close(tree2);
10543 if (commit)
10544 got_object_commit_close(commit);
10545 if (parent_commit)
10546 got_object_commit_close(parent_commit);
10547 return err;
10550 static const struct got_error *
10551 collect_commits(struct got_object_id_queue *commits,
10552 struct got_object_id *initial_commit_id,
10553 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10554 const char *path_prefix, int path_prefix_errcode,
10555 struct got_repository *repo)
10557 const struct got_error *err = NULL;
10558 struct got_commit_graph *graph = NULL;
10559 struct got_object_id parent_id, commit_id;
10560 struct got_object_qid *qid;
10562 err = got_commit_graph_open(&graph, "/", 1);
10563 if (err)
10564 return err;
10566 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10567 check_cancelled, NULL);
10568 if (err)
10569 goto done;
10571 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10572 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10573 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10574 check_cancelled, NULL);
10575 if (err) {
10576 if (err->code == GOT_ERR_ITER_COMPLETED) {
10577 err = got_error_msg(GOT_ERR_ANCESTRY,
10578 "ran out of commits to rebase before "
10579 "youngest common ancestor commit has "
10580 "been reached?!?");
10582 goto done;
10583 } else {
10584 err = check_path_prefix(&parent_id, &commit_id,
10585 path_prefix, path_prefix_errcode, repo);
10586 if (err)
10587 goto done;
10589 err = got_object_qid_alloc(&qid, &commit_id);
10590 if (err)
10591 goto done;
10592 STAILQ_INSERT_HEAD(commits, qid, entry);
10594 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10597 done:
10598 got_commit_graph_close(graph);
10599 return err;
10602 static const struct got_error *
10603 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10605 const struct got_error *err = NULL;
10606 time_t committer_time;
10607 struct tm tm;
10608 char datebuf[11]; /* YYYY-MM-DD + NUL */
10609 char *author0 = NULL, *author, *smallerthan;
10610 char *logmsg0 = NULL, *logmsg, *newline;
10612 committer_time = got_object_commit_get_committer_time(commit);
10613 if (gmtime_r(&committer_time, &tm) == NULL)
10614 return got_error_from_errno("gmtime_r");
10615 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10616 return got_error(GOT_ERR_NO_SPACE);
10618 author0 = strdup(got_object_commit_get_author(commit));
10619 if (author0 == NULL)
10620 return got_error_from_errno("strdup");
10621 author = author0;
10622 smallerthan = strchr(author, '<');
10623 if (smallerthan && smallerthan[1] != '\0')
10624 author = smallerthan + 1;
10625 author[strcspn(author, "@>")] = '\0';
10627 err = got_object_commit_get_logmsg(&logmsg0, commit);
10628 if (err)
10629 goto done;
10630 logmsg = logmsg0;
10631 while (*logmsg == '\n')
10632 logmsg++;
10633 newline = strchr(logmsg, '\n');
10634 if (newline)
10635 *newline = '\0';
10637 if (asprintf(brief_str, "%s %s %s",
10638 datebuf, author, logmsg) == -1)
10639 err = got_error_from_errno("asprintf");
10640 done:
10641 free(author0);
10642 free(logmsg0);
10643 return err;
10646 static const struct got_error *
10647 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10648 struct got_repository *repo)
10650 const struct got_error *err;
10651 char *id_str;
10653 err = got_object_id_str(&id_str, id);
10654 if (err)
10655 return err;
10657 err = got_ref_delete(ref, repo);
10658 if (err)
10659 goto done;
10661 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10662 done:
10663 free(id_str);
10664 return err;
10667 static const struct got_error *
10668 print_backup_ref(const char *branch_name, const char *new_id_str,
10669 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10670 struct got_reflist_object_id_map *refs_idmap,
10671 struct got_repository *repo)
10673 const struct got_error *err = NULL;
10674 struct got_reflist_head *refs;
10675 char *refs_str = NULL;
10676 struct got_object_id *new_commit_id = NULL;
10677 struct got_commit_object *new_commit = NULL;
10678 char *new_commit_brief_str = NULL;
10679 struct got_object_id *yca_id = NULL;
10680 struct got_commit_object *yca_commit = NULL;
10681 char *yca_id_str = NULL, *yca_brief_str = NULL;
10682 char *custom_refs_str;
10684 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10685 return got_error_from_errno("asprintf");
10687 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10688 0, 0, refs_idmap, custom_refs_str, NULL);
10689 if (err)
10690 goto done;
10692 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10693 if (err)
10694 goto done;
10696 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10697 if (refs) {
10698 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10699 if (err)
10700 goto done;
10703 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10704 if (err)
10705 goto done;
10707 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10708 if (err)
10709 goto done;
10711 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10712 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10713 if (err)
10714 goto done;
10716 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10717 refs_str ? " (" : "", refs_str ? refs_str : "",
10718 refs_str ? ")" : "", new_commit_brief_str);
10719 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10720 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10721 free(refs_str);
10722 refs_str = NULL;
10724 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10725 if (err)
10726 goto done;
10728 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10729 if (err)
10730 goto done;
10732 err = got_object_id_str(&yca_id_str, yca_id);
10733 if (err)
10734 goto done;
10736 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10737 if (refs) {
10738 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10739 if (err)
10740 goto done;
10742 printf("history forked at %s%s%s%s\n %s\n",
10743 yca_id_str,
10744 refs_str ? " (" : "", refs_str ? refs_str : "",
10745 refs_str ? ")" : "", yca_brief_str);
10747 done:
10748 free(custom_refs_str);
10749 free(new_commit_id);
10750 free(refs_str);
10751 free(yca_id);
10752 free(yca_id_str);
10753 free(yca_brief_str);
10754 if (new_commit)
10755 got_object_commit_close(new_commit);
10756 if (yca_commit)
10757 got_object_commit_close(yca_commit);
10759 return err;
10762 static const struct got_error *
10763 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10764 struct got_repository *repo)
10766 const struct got_error *err;
10767 struct got_reflist_head refs;
10768 struct got_reflist_entry *re;
10769 char *uuidstr = NULL;
10770 static char msg[160];
10772 TAILQ_INIT(&refs);
10774 err = got_worktree_get_uuid(&uuidstr, worktree);
10775 if (err)
10776 goto done;
10778 err = got_ref_list(&refs, repo, "refs/got/worktree",
10779 got_ref_cmp_by_name, repo);
10780 if (err)
10781 goto done;
10783 TAILQ_FOREACH(re, &refs, entry) {
10784 const char *cmd, *refname, *type;
10786 refname = got_ref_get_name(re->ref);
10788 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10789 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10790 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10791 cmd = "cherrypick";
10792 type = "cherrypicked";
10793 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10794 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10795 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10796 cmd = "backout";
10797 type = "backed-out";
10798 } else
10799 continue;
10801 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10802 continue;
10804 snprintf(msg, sizeof(msg),
10805 "work tree has references created by %s commits which "
10806 "must be removed with 'got %s -X' before running the %s "
10807 "command", type, cmd, caller);
10808 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10809 goto done;
10812 done:
10813 free(uuidstr);
10814 got_ref_list_free(&refs);
10815 return err;
10818 static const struct got_error *
10819 process_backup_refs(const char *backup_ref_prefix,
10820 const char *wanted_branch_name,
10821 int delete, struct got_repository *repo)
10823 const struct got_error *err;
10824 struct got_reflist_head refs, backup_refs;
10825 struct got_reflist_entry *re;
10826 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10827 struct got_object_id *old_commit_id = NULL;
10828 char *branch_name = NULL;
10829 struct got_commit_object *old_commit = NULL;
10830 struct got_reflist_object_id_map *refs_idmap = NULL;
10831 int wanted_branch_found = 0;
10833 TAILQ_INIT(&refs);
10834 TAILQ_INIT(&backup_refs);
10836 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10837 if (err)
10838 return err;
10840 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10841 if (err)
10842 goto done;
10844 if (wanted_branch_name) {
10845 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10846 wanted_branch_name += 11;
10849 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10850 got_ref_cmp_by_commit_timestamp_descending, repo);
10851 if (err)
10852 goto done;
10854 TAILQ_FOREACH(re, &backup_refs, entry) {
10855 const char *refname = got_ref_get_name(re->ref);
10856 char *slash;
10858 err = check_cancelled(NULL);
10859 if (err)
10860 break;
10862 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10863 if (err)
10864 break;
10866 err = got_object_open_as_commit(&old_commit, repo,
10867 old_commit_id);
10868 if (err)
10869 break;
10871 if (strncmp(backup_ref_prefix, refname,
10872 backup_ref_prefix_len) == 0)
10873 refname += backup_ref_prefix_len;
10875 while (refname[0] == '/')
10876 refname++;
10878 branch_name = strdup(refname);
10879 if (branch_name == NULL) {
10880 err = got_error_from_errno("strdup");
10881 break;
10883 slash = strrchr(branch_name, '/');
10884 if (slash) {
10885 *slash = '\0';
10886 refname += strlen(branch_name) + 1;
10889 if (wanted_branch_name == NULL ||
10890 strcmp(wanted_branch_name, branch_name) == 0) {
10891 wanted_branch_found = 1;
10892 if (delete) {
10893 err = delete_backup_ref(re->ref,
10894 old_commit_id, repo);
10895 } else {
10896 err = print_backup_ref(branch_name, refname,
10897 old_commit_id, old_commit, refs_idmap,
10898 repo);
10900 if (err)
10901 break;
10904 free(old_commit_id);
10905 old_commit_id = NULL;
10906 free(branch_name);
10907 branch_name = NULL;
10908 got_object_commit_close(old_commit);
10909 old_commit = NULL;
10912 if (wanted_branch_name && !wanted_branch_found) {
10913 err = got_error_fmt(GOT_ERR_NOT_REF,
10914 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10916 done:
10917 if (refs_idmap)
10918 got_reflist_object_id_map_free(refs_idmap);
10919 got_ref_list_free(&refs);
10920 got_ref_list_free(&backup_refs);
10921 free(old_commit_id);
10922 free(branch_name);
10923 if (old_commit)
10924 got_object_commit_close(old_commit);
10925 return err;
10928 static const struct got_error *
10929 abort_progress(void *arg, unsigned char status, const char *path)
10932 * Unversioned files should not clutter progress output when
10933 * an operation is aborted.
10935 if (status == GOT_STATUS_UNVERSIONED)
10936 return NULL;
10938 return update_progress(arg, status, path);
10941 static const struct got_error *
10942 cmd_rebase(int argc, char *argv[])
10944 const struct got_error *error = NULL;
10945 struct got_worktree *worktree = NULL;
10946 struct got_repository *repo = NULL;
10947 struct got_fileindex *fileindex = NULL;
10948 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10949 struct got_reference *branch = NULL;
10950 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10951 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10952 struct got_object_id *resume_commit_id = NULL;
10953 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10954 struct got_object_id *head_commit_id = NULL;
10955 struct got_reference *head_ref = NULL;
10956 struct got_commit_object *commit = NULL;
10957 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10958 int histedit_in_progress = 0, merge_in_progress = 0;
10959 int create_backup = 1, list_backups = 0, delete_backups = 0;
10960 struct got_object_id_queue commits;
10961 struct got_pathlist_head merged_paths;
10962 const struct got_object_id_queue *parent_ids;
10963 struct got_object_qid *qid, *pid;
10964 struct got_update_progress_arg upa;
10965 int *pack_fds = NULL;
10967 STAILQ_INIT(&commits);
10968 TAILQ_INIT(&merged_paths);
10969 memset(&upa, 0, sizeof(upa));
10971 #ifndef PROFILE
10972 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10973 "unveil", NULL) == -1)
10974 err(1, "pledge");
10975 #endif
10977 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10978 switch (ch) {
10979 case 'a':
10980 abort_rebase = 1;
10981 break;
10982 case 'c':
10983 continue_rebase = 1;
10984 break;
10985 case 'l':
10986 list_backups = 1;
10987 break;
10988 case 'X':
10989 delete_backups = 1;
10990 break;
10991 default:
10992 usage_rebase();
10993 /* NOTREACHED */
10997 argc -= optind;
10998 argv += optind;
11000 if (list_backups) {
11001 if (abort_rebase)
11002 option_conflict('l', 'a');
11003 if (continue_rebase)
11004 option_conflict('l', 'c');
11005 if (delete_backups)
11006 option_conflict('l', 'X');
11007 if (argc != 0 && argc != 1)
11008 usage_rebase();
11009 } else if (delete_backups) {
11010 if (abort_rebase)
11011 option_conflict('X', 'a');
11012 if (continue_rebase)
11013 option_conflict('X', 'c');
11014 if (list_backups)
11015 option_conflict('l', 'X');
11016 if (argc != 0 && argc != 1)
11017 usage_rebase();
11018 } else {
11019 if (abort_rebase && continue_rebase)
11020 usage_rebase();
11021 else if (abort_rebase || continue_rebase) {
11022 if (argc != 0)
11023 usage_rebase();
11024 } else if (argc != 1)
11025 usage_rebase();
11028 cwd = getcwd(NULL, 0);
11029 if (cwd == NULL) {
11030 error = got_error_from_errno("getcwd");
11031 goto done;
11034 error = got_repo_pack_fds_open(&pack_fds);
11035 if (error != NULL)
11036 goto done;
11038 error = got_worktree_open(&worktree, cwd);
11039 if (error) {
11040 if (list_backups || delete_backups) {
11041 if (error->code != GOT_ERR_NOT_WORKTREE)
11042 goto done;
11043 } else {
11044 if (error->code == GOT_ERR_NOT_WORKTREE)
11045 error = wrap_not_worktree_error(error,
11046 "rebase", cwd);
11047 goto done;
11051 error = get_gitconfig_path(&gitconfig_path);
11052 if (error)
11053 goto done;
11054 error = got_repo_open(&repo,
11055 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11056 gitconfig_path, pack_fds);
11057 if (error != NULL)
11058 goto done;
11060 if (worktree != NULL && !list_backups && !delete_backups) {
11061 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11062 if (error)
11063 goto done;
11066 error = get_author(&committer, repo, worktree);
11067 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11068 goto done;
11070 error = apply_unveil(got_repo_get_path(repo), 0,
11071 worktree ? got_worktree_get_root_path(worktree) : NULL);
11072 if (error)
11073 goto done;
11075 if (list_backups || delete_backups) {
11076 error = process_backup_refs(
11077 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11078 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11079 goto done; /* nothing else to do */
11082 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11083 worktree);
11084 if (error)
11085 goto done;
11086 if (histedit_in_progress) {
11087 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11088 goto done;
11091 error = got_worktree_merge_in_progress(&merge_in_progress,
11092 worktree, repo);
11093 if (error)
11094 goto done;
11095 if (merge_in_progress) {
11096 error = got_error(GOT_ERR_MERGE_BUSY);
11097 goto done;
11100 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11101 if (error)
11102 goto done;
11104 if (abort_rebase) {
11105 if (!rebase_in_progress) {
11106 error = got_error(GOT_ERR_NOT_REBASING);
11107 goto done;
11109 error = got_worktree_rebase_continue(&resume_commit_id,
11110 &new_base_branch, &tmp_branch, &branch, &fileindex,
11111 worktree, repo);
11112 if (error)
11113 goto done;
11114 printf("Switching work tree to %s\n",
11115 got_ref_get_symref_target(new_base_branch));
11116 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11117 new_base_branch, abort_progress, &upa);
11118 if (error)
11119 goto done;
11120 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11121 print_merge_progress_stats(&upa);
11122 goto done; /* nothing else to do */
11125 if (continue_rebase) {
11126 if (!rebase_in_progress) {
11127 error = got_error(GOT_ERR_NOT_REBASING);
11128 goto done;
11130 error = got_worktree_rebase_continue(&resume_commit_id,
11131 &new_base_branch, &tmp_branch, &branch, &fileindex,
11132 worktree, repo);
11133 if (error)
11134 goto done;
11136 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11137 committer, resume_commit_id, repo);
11138 if (error)
11139 goto done;
11141 yca_id = got_object_id_dup(resume_commit_id);
11142 if (yca_id == NULL) {
11143 error = got_error_from_errno("got_object_id_dup");
11144 goto done;
11146 } else {
11147 error = got_ref_open(&branch, repo, argv[0], 0);
11148 if (error != NULL)
11149 goto done;
11150 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11151 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11152 "will not rebase a branch which lives outside "
11153 "the \"refs/heads/\" reference namespace");
11154 goto done;
11158 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11159 if (error)
11160 goto done;
11162 if (!continue_rebase) {
11163 struct got_object_id *base_commit_id;
11165 error = got_ref_open(&head_ref, repo,
11166 got_worktree_get_head_ref_name(worktree), 0);
11167 if (error)
11168 goto done;
11169 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11170 if (error)
11171 goto done;
11172 base_commit_id = got_worktree_get_base_commit_id(worktree);
11173 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11174 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11175 goto done;
11178 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11179 base_commit_id, branch_head_commit_id, 1, repo,
11180 check_cancelled, NULL);
11181 if (error) {
11182 if (error->code == GOT_ERR_ANCESTRY) {
11183 error = got_error_msg(GOT_ERR_ANCESTRY,
11184 "specified branch shares no common "
11185 "ancestry with work tree's branch");
11187 goto done;
11190 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11191 if (error) {
11192 if (error->code != GOT_ERR_ANCESTRY)
11193 goto done;
11194 error = NULL;
11195 } else {
11196 struct got_pathlist_head paths;
11197 printf("%s is already based on %s\n",
11198 got_ref_get_name(branch),
11199 got_worktree_get_head_ref_name(worktree));
11200 error = switch_head_ref(branch, branch_head_commit_id,
11201 worktree, repo);
11202 if (error)
11203 goto done;
11204 error = got_worktree_set_base_commit_id(worktree, repo,
11205 branch_head_commit_id);
11206 if (error)
11207 goto done;
11208 TAILQ_INIT(&paths);
11209 error = got_pathlist_append(&paths, "", NULL);
11210 if (error)
11211 goto done;
11212 error = got_worktree_checkout_files(worktree,
11213 &paths, repo, update_progress, &upa,
11214 check_cancelled, NULL);
11215 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11216 if (error)
11217 goto done;
11218 if (upa.did_something) {
11219 char *id_str;
11220 error = got_object_id_str(&id_str,
11221 branch_head_commit_id);
11222 if (error)
11223 goto done;
11224 printf("Updated to %s: %s\n",
11225 got_worktree_get_head_ref_name(worktree),
11226 id_str);
11227 free(id_str);
11228 } else
11229 printf("Already up-to-date\n");
11230 print_update_progress_stats(&upa);
11231 goto done;
11235 commit_id = branch_head_commit_id;
11236 error = got_object_open_as_commit(&commit, repo, commit_id);
11237 if (error)
11238 goto done;
11240 parent_ids = got_object_commit_get_parent_ids(commit);
11241 pid = STAILQ_FIRST(parent_ids);
11242 if (pid) {
11243 error = collect_commits(&commits, commit_id, &pid->id,
11244 yca_id, got_worktree_get_path_prefix(worktree),
11245 GOT_ERR_REBASE_PATH, repo);
11246 if (error)
11247 goto done;
11250 got_object_commit_close(commit);
11251 commit = NULL;
11253 if (!continue_rebase) {
11254 error = got_worktree_rebase_prepare(&new_base_branch,
11255 &tmp_branch, &fileindex, worktree, branch, repo);
11256 if (error)
11257 goto done;
11260 if (STAILQ_EMPTY(&commits)) {
11261 if (continue_rebase) {
11262 error = rebase_complete(worktree, fileindex,
11263 branch, tmp_branch, repo, create_backup);
11264 goto done;
11265 } else {
11266 /* Fast-forward the reference of the branch. */
11267 struct got_object_id *new_head_commit_id;
11268 char *id_str;
11269 error = got_ref_resolve(&new_head_commit_id, repo,
11270 new_base_branch);
11271 if (error)
11272 goto done;
11273 error = got_object_id_str(&id_str, new_head_commit_id);
11274 if (error)
11275 goto done;
11276 printf("Forwarding %s to commit %s\n",
11277 got_ref_get_name(branch), id_str);
11278 free(id_str);
11279 error = got_ref_change_ref(branch,
11280 new_head_commit_id);
11281 if (error)
11282 goto done;
11283 /* No backup needed since objects did not change. */
11284 create_backup = 0;
11288 pid = NULL;
11289 STAILQ_FOREACH(qid, &commits, entry) {
11291 commit_id = &qid->id;
11292 parent_id = pid ? &pid->id : yca_id;
11293 pid = qid;
11295 memset(&upa, 0, sizeof(upa));
11296 error = got_worktree_rebase_merge_files(&merged_paths,
11297 worktree, fileindex, parent_id, commit_id, repo,
11298 update_progress, &upa, check_cancelled, NULL);
11299 if (error)
11300 goto done;
11302 print_merge_progress_stats(&upa);
11303 if (upa.conflicts > 0 || upa.missing > 0 ||
11304 upa.not_deleted > 0 || upa.unversioned > 0) {
11305 if (upa.conflicts > 0) {
11306 error = show_rebase_merge_conflict(&qid->id,
11307 repo);
11308 if (error)
11309 goto done;
11311 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11312 break;
11315 error = rebase_commit(&merged_paths, worktree, fileindex,
11316 tmp_branch, committer, commit_id, repo);
11317 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11318 if (error)
11319 goto done;
11322 if (upa.conflicts > 0 || upa.missing > 0 ||
11323 upa.not_deleted > 0 || upa.unversioned > 0) {
11324 error = got_worktree_rebase_postpone(worktree, fileindex);
11325 if (error)
11326 goto done;
11327 if (upa.conflicts > 0 && upa.missing == 0 &&
11328 upa.not_deleted == 0 && upa.unversioned == 0) {
11329 error = got_error_msg(GOT_ERR_CONFLICTS,
11330 "conflicts must be resolved before rebasing "
11331 "can continue");
11332 } else if (upa.conflicts > 0) {
11333 error = got_error_msg(GOT_ERR_CONFLICTS,
11334 "conflicts must be resolved before rebasing "
11335 "can continue; changes destined for some "
11336 "files were not yet merged and should be "
11337 "merged manually if required before the "
11338 "rebase operation is continued");
11339 } else {
11340 error = got_error_msg(GOT_ERR_CONFLICTS,
11341 "changes destined for some files were not "
11342 "yet merged and should be merged manually "
11343 "if required before the rebase operation "
11344 "is continued");
11346 } else
11347 error = rebase_complete(worktree, fileindex, branch,
11348 tmp_branch, repo, create_backup);
11349 done:
11350 free(cwd);
11351 free(committer);
11352 free(gitconfig_path);
11353 got_object_id_queue_free(&commits);
11354 free(branch_head_commit_id);
11355 free(resume_commit_id);
11356 free(head_commit_id);
11357 free(yca_id);
11358 if (commit)
11359 got_object_commit_close(commit);
11360 if (branch)
11361 got_ref_close(branch);
11362 if (new_base_branch)
11363 got_ref_close(new_base_branch);
11364 if (tmp_branch)
11365 got_ref_close(tmp_branch);
11366 if (head_ref)
11367 got_ref_close(head_ref);
11368 if (worktree)
11369 got_worktree_close(worktree);
11370 if (repo) {
11371 const struct got_error *close_err = got_repo_close(repo);
11372 if (error == NULL)
11373 error = close_err;
11375 if (pack_fds) {
11376 const struct got_error *pack_err =
11377 got_repo_pack_fds_close(pack_fds);
11378 if (error == NULL)
11379 error = pack_err;
11381 return error;
11384 __dead static void
11385 usage_histedit(void)
11387 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11388 "[branch]\n", getprogname());
11389 exit(1);
11392 #define GOT_HISTEDIT_PICK 'p'
11393 #define GOT_HISTEDIT_EDIT 'e'
11394 #define GOT_HISTEDIT_FOLD 'f'
11395 #define GOT_HISTEDIT_DROP 'd'
11396 #define GOT_HISTEDIT_MESG 'm'
11398 static const struct got_histedit_cmd {
11399 unsigned char code;
11400 const char *name;
11401 const char *desc;
11402 } got_histedit_cmds[] = {
11403 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11404 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11405 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11406 "be used" },
11407 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11408 { GOT_HISTEDIT_MESG, "mesg",
11409 "single-line log message for commit above (open editor if empty)" },
11412 struct got_histedit_list_entry {
11413 TAILQ_ENTRY(got_histedit_list_entry) entry;
11414 struct got_object_id *commit_id;
11415 const struct got_histedit_cmd *cmd;
11416 char *logmsg;
11418 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11420 static const struct got_error *
11421 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11422 FILE *f, struct got_repository *repo)
11424 const struct got_error *err = NULL;
11425 char *logmsg = NULL, *id_str = NULL;
11426 struct got_commit_object *commit = NULL;
11427 int n;
11429 err = got_object_open_as_commit(&commit, repo, commit_id);
11430 if (err)
11431 goto done;
11433 err = get_short_logmsg(&logmsg, 34, commit);
11434 if (err)
11435 goto done;
11437 err = got_object_id_str(&id_str, commit_id);
11438 if (err)
11439 goto done;
11441 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11442 if (n < 0)
11443 err = got_ferror(f, GOT_ERR_IO);
11444 done:
11445 if (commit)
11446 got_object_commit_close(commit);
11447 free(id_str);
11448 free(logmsg);
11449 return err;
11452 static const struct got_error *
11453 histedit_write_commit_list(struct got_object_id_queue *commits,
11454 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11455 int edit_only, struct got_repository *repo)
11457 const struct got_error *err = NULL;
11458 struct got_object_qid *qid;
11459 const char *histedit_cmd = NULL;
11461 if (STAILQ_EMPTY(commits))
11462 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11464 STAILQ_FOREACH(qid, commits, entry) {
11465 histedit_cmd = got_histedit_cmds[0].name;
11466 if (drop_only)
11467 histedit_cmd = "drop";
11468 else if (edit_only)
11469 histedit_cmd = "edit";
11470 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11471 histedit_cmd = "fold";
11472 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11473 if (err)
11474 break;
11475 if (edit_logmsg_only) {
11476 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11477 if (n < 0) {
11478 err = got_ferror(f, GOT_ERR_IO);
11479 break;
11484 return err;
11487 static const struct got_error *
11488 write_cmd_list(FILE *f, const char *branch_name,
11489 struct got_object_id_queue *commits)
11491 const struct got_error *err = NULL;
11492 size_t i;
11493 int n;
11494 char *id_str;
11495 struct got_object_qid *qid;
11497 qid = STAILQ_FIRST(commits);
11498 err = got_object_id_str(&id_str, &qid->id);
11499 if (err)
11500 return err;
11502 n = fprintf(f,
11503 "# Editing the history of branch '%s' starting at\n"
11504 "# commit %s\n"
11505 "# Commits will be processed in order from top to "
11506 "bottom of this file.\n", branch_name, id_str);
11507 if (n < 0) {
11508 err = got_ferror(f, GOT_ERR_IO);
11509 goto done;
11512 n = fprintf(f, "# Available histedit commands:\n");
11513 if (n < 0) {
11514 err = got_ferror(f, GOT_ERR_IO);
11515 goto done;
11518 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11519 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11520 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11521 cmd->desc);
11522 if (n < 0) {
11523 err = got_ferror(f, GOT_ERR_IO);
11524 break;
11527 done:
11528 free(id_str);
11529 return err;
11532 static const struct got_error *
11533 histedit_syntax_error(int lineno)
11535 static char msg[42];
11536 int ret;
11538 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11539 lineno);
11540 if (ret < 0 || (size_t)ret >= sizeof(msg))
11541 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11543 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11546 static const struct got_error *
11547 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11548 char *logmsg, struct got_repository *repo)
11550 const struct got_error *err;
11551 struct got_commit_object *folded_commit = NULL;
11552 char *id_str, *folded_logmsg = NULL;
11554 err = got_object_id_str(&id_str, hle->commit_id);
11555 if (err)
11556 return err;
11558 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11559 if (err)
11560 goto done;
11562 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11563 if (err)
11564 goto done;
11565 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11566 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11567 folded_logmsg) == -1) {
11568 err = got_error_from_errno("asprintf");
11570 done:
11571 if (folded_commit)
11572 got_object_commit_close(folded_commit);
11573 free(id_str);
11574 free(folded_logmsg);
11575 return err;
11578 static struct got_histedit_list_entry *
11579 get_folded_commits(struct got_histedit_list_entry *hle)
11581 struct got_histedit_list_entry *prev, *folded = NULL;
11583 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11584 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11585 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11586 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11587 folded = prev;
11588 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11591 return folded;
11594 static const struct got_error *
11595 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11596 struct got_repository *repo)
11598 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11599 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11600 const struct got_error *err = NULL;
11601 struct got_commit_object *commit = NULL;
11602 int logmsg_len;
11603 int fd;
11604 struct got_histedit_list_entry *folded = NULL;
11606 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11607 if (err)
11608 return err;
11610 folded = get_folded_commits(hle);
11611 if (folded) {
11612 while (folded != hle) {
11613 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11614 folded = TAILQ_NEXT(folded, entry);
11615 continue;
11617 err = append_folded_commit_msg(&new_msg, folded,
11618 logmsg, repo);
11619 if (err)
11620 goto done;
11621 free(logmsg);
11622 logmsg = new_msg;
11623 folded = TAILQ_NEXT(folded, entry);
11627 err = got_object_id_str(&id_str, hle->commit_id);
11628 if (err)
11629 goto done;
11630 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11631 if (err)
11632 goto done;
11633 logmsg_len = asprintf(&new_msg,
11634 "%s\n# original log message of commit %s: %s",
11635 logmsg ? logmsg : "", id_str, orig_logmsg);
11636 if (logmsg_len == -1) {
11637 err = got_error_from_errno("asprintf");
11638 goto done;
11640 free(logmsg);
11641 logmsg = new_msg;
11643 err = got_object_id_str(&id_str, hle->commit_id);
11644 if (err)
11645 goto done;
11647 err = got_opentemp_named_fd(&logmsg_path, &fd,
11648 GOT_TMPDIR_STR "/got-logmsg", "");
11649 if (err)
11650 goto done;
11652 write(fd, logmsg, logmsg_len);
11653 close(fd);
11655 err = get_editor(&editor);
11656 if (err)
11657 goto done;
11659 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11660 logmsg_len, 0);
11661 if (err) {
11662 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11663 goto done;
11664 err = NULL;
11665 hle->logmsg = strdup(new_msg);
11666 if (hle->logmsg == NULL)
11667 err = got_error_from_errno("strdup");
11669 done:
11670 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11671 err = got_error_from_errno2("unlink", logmsg_path);
11672 free(logmsg_path);
11673 free(logmsg);
11674 free(orig_logmsg);
11675 free(editor);
11676 if (commit)
11677 got_object_commit_close(commit);
11678 return err;
11681 static const struct got_error *
11682 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11683 FILE *f, struct got_repository *repo)
11685 const struct got_error *err = NULL;
11686 char *line = NULL, *p, *end;
11687 size_t i, size;
11688 ssize_t len;
11689 int lineno = 0, lastcmd = -1;
11690 const struct got_histedit_cmd *cmd;
11691 struct got_object_id *commit_id = NULL;
11692 struct got_histedit_list_entry *hle = NULL;
11694 for (;;) {
11695 len = getline(&line, &size, f);
11696 if (len == -1) {
11697 const struct got_error *getline_err;
11698 if (feof(f))
11699 break;
11700 getline_err = got_error_from_errno("getline");
11701 err = got_ferror(f, getline_err->code);
11702 break;
11704 lineno++;
11705 p = line;
11706 while (isspace((unsigned char)p[0]))
11707 p++;
11708 if (p[0] == '#' || p[0] == '\0') {
11709 free(line);
11710 line = NULL;
11711 continue;
11713 cmd = NULL;
11714 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11715 cmd = &got_histedit_cmds[i];
11716 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11717 isspace((unsigned char)p[strlen(cmd->name)])) {
11718 p += strlen(cmd->name);
11719 break;
11721 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11722 p++;
11723 break;
11726 if (i == nitems(got_histedit_cmds)) {
11727 err = histedit_syntax_error(lineno);
11728 break;
11730 while (isspace((unsigned char)p[0]))
11731 p++;
11732 if (cmd->code == GOT_HISTEDIT_MESG) {
11733 if (lastcmd != GOT_HISTEDIT_PICK &&
11734 lastcmd != GOT_HISTEDIT_EDIT) {
11735 err = got_error(GOT_ERR_HISTEDIT_CMD);
11736 break;
11738 if (p[0] == '\0') {
11739 err = histedit_edit_logmsg(hle, repo);
11740 if (err)
11741 break;
11742 } else {
11743 hle->logmsg = strdup(p);
11744 if (hle->logmsg == NULL) {
11745 err = got_error_from_errno("strdup");
11746 break;
11749 free(line);
11750 line = NULL;
11751 lastcmd = cmd->code;
11752 continue;
11753 } else {
11754 end = p;
11755 while (end[0] && !isspace((unsigned char)end[0]))
11756 end++;
11757 *end = '\0';
11759 err = got_object_resolve_id_str(&commit_id, repo, p);
11760 if (err) {
11761 /* override error code */
11762 err = histedit_syntax_error(lineno);
11763 break;
11766 hle = malloc(sizeof(*hle));
11767 if (hle == NULL) {
11768 err = got_error_from_errno("malloc");
11769 break;
11771 hle->cmd = cmd;
11772 hle->commit_id = commit_id;
11773 hle->logmsg = NULL;
11774 commit_id = NULL;
11775 free(line);
11776 line = NULL;
11777 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11778 lastcmd = cmd->code;
11781 free(line);
11782 free(commit_id);
11783 return err;
11786 static const struct got_error *
11787 histedit_check_script(struct got_histedit_list *histedit_cmds,
11788 struct got_object_id_queue *commits, struct got_repository *repo)
11790 const struct got_error *err = NULL;
11791 struct got_object_qid *qid;
11792 struct got_histedit_list_entry *hle;
11793 static char msg[92];
11794 char *id_str;
11796 if (TAILQ_EMPTY(histedit_cmds))
11797 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11798 "histedit script contains no commands");
11799 if (STAILQ_EMPTY(commits))
11800 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11802 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11803 struct got_histedit_list_entry *hle2;
11804 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11805 if (hle == hle2)
11806 continue;
11807 if (got_object_id_cmp(hle->commit_id,
11808 hle2->commit_id) != 0)
11809 continue;
11810 err = got_object_id_str(&id_str, hle->commit_id);
11811 if (err)
11812 return err;
11813 snprintf(msg, sizeof(msg), "commit %s is listed "
11814 "more than once in histedit script", id_str);
11815 free(id_str);
11816 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11820 STAILQ_FOREACH(qid, commits, entry) {
11821 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11822 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11823 break;
11825 if (hle == NULL) {
11826 err = got_object_id_str(&id_str, &qid->id);
11827 if (err)
11828 return err;
11829 snprintf(msg, sizeof(msg),
11830 "commit %s missing from histedit script", id_str);
11831 free(id_str);
11832 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11836 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11837 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11838 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11839 "last commit in histedit script cannot be folded");
11841 return NULL;
11844 static const struct got_error *
11845 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11846 const char *path, struct got_object_id_queue *commits,
11847 struct got_repository *repo)
11849 const struct got_error *err = NULL;
11850 char *editor;
11851 FILE *f = NULL;
11853 err = get_editor(&editor);
11854 if (err)
11855 return err;
11857 if (spawn_editor(editor, path) == -1) {
11858 err = got_error_from_errno("failed spawning editor");
11859 goto done;
11862 f = fopen(path, "re");
11863 if (f == NULL) {
11864 err = got_error_from_errno("fopen");
11865 goto done;
11867 err = histedit_parse_list(histedit_cmds, f, repo);
11868 if (err)
11869 goto done;
11871 err = histedit_check_script(histedit_cmds, commits, repo);
11872 done:
11873 if (f && fclose(f) == EOF && err == NULL)
11874 err = got_error_from_errno("fclose");
11875 free(editor);
11876 return err;
11879 static const struct got_error *
11880 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11881 struct got_object_id_queue *, const char *, const char *,
11882 struct got_repository *);
11884 static const struct got_error *
11885 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11886 struct got_object_id_queue *commits, const char *branch_name,
11887 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11888 struct got_repository *repo)
11890 const struct got_error *err;
11891 FILE *f = NULL;
11892 char *path = NULL;
11894 err = got_opentemp_named(&path, &f, "got-histedit", "");
11895 if (err)
11896 return err;
11898 err = write_cmd_list(f, branch_name, commits);
11899 if (err)
11900 goto done;
11902 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11903 fold_only, drop_only, edit_only, repo);
11904 if (err)
11905 goto done;
11907 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11908 rewind(f);
11909 err = histedit_parse_list(histedit_cmds, f, repo);
11910 } else {
11911 if (fclose(f) == EOF) {
11912 err = got_error_from_errno("fclose");
11913 goto done;
11915 f = NULL;
11916 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11917 if (err) {
11918 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11919 err->code != GOT_ERR_HISTEDIT_CMD)
11920 goto done;
11921 err = histedit_edit_list_retry(histedit_cmds, err,
11922 commits, path, branch_name, repo);
11925 done:
11926 if (f && fclose(f) == EOF && err == NULL)
11927 err = got_error_from_errno("fclose");
11928 if (path && unlink(path) != 0 && err == NULL)
11929 err = got_error_from_errno2("unlink", path);
11930 free(path);
11931 return err;
11934 static const struct got_error *
11935 histedit_save_list(struct got_histedit_list *histedit_cmds,
11936 struct got_worktree *worktree, struct got_repository *repo)
11938 const struct got_error *err = NULL;
11939 char *path = NULL;
11940 FILE *f = NULL;
11941 struct got_histedit_list_entry *hle;
11942 struct got_commit_object *commit = NULL;
11944 err = got_worktree_get_histedit_script_path(&path, worktree);
11945 if (err)
11946 return err;
11948 f = fopen(path, "we");
11949 if (f == NULL) {
11950 err = got_error_from_errno2("fopen", path);
11951 goto done;
11953 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11954 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11955 repo);
11956 if (err)
11957 break;
11959 if (hle->logmsg) {
11960 int n = fprintf(f, "%c %s\n",
11961 GOT_HISTEDIT_MESG, hle->logmsg);
11962 if (n < 0) {
11963 err = got_ferror(f, GOT_ERR_IO);
11964 break;
11968 done:
11969 if (f && fclose(f) == EOF && err == NULL)
11970 err = got_error_from_errno("fclose");
11971 free(path);
11972 if (commit)
11973 got_object_commit_close(commit);
11974 return err;
11977 static void
11978 histedit_free_list(struct got_histedit_list *histedit_cmds)
11980 struct got_histedit_list_entry *hle;
11982 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11983 TAILQ_REMOVE(histedit_cmds, hle, entry);
11984 free(hle);
11988 static const struct got_error *
11989 histedit_load_list(struct got_histedit_list *histedit_cmds,
11990 const char *path, struct got_repository *repo)
11992 const struct got_error *err = NULL;
11993 FILE *f = NULL;
11995 f = fopen(path, "re");
11996 if (f == NULL) {
11997 err = got_error_from_errno2("fopen", path);
11998 goto done;
12001 err = histedit_parse_list(histedit_cmds, f, repo);
12002 done:
12003 if (f && fclose(f) == EOF && err == NULL)
12004 err = got_error_from_errno("fclose");
12005 return err;
12008 static const struct got_error *
12009 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12010 const struct got_error *edit_err, struct got_object_id_queue *commits,
12011 const char *path, const char *branch_name, struct got_repository *repo)
12013 const struct got_error *err = NULL, *prev_err = edit_err;
12014 int resp = ' ';
12016 while (resp != 'c' && resp != 'r' && resp != 'a') {
12017 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12018 "or (a)bort: ", getprogname(), prev_err->msg);
12019 resp = getchar();
12020 if (resp == '\n')
12021 resp = getchar();
12022 if (resp == 'c') {
12023 histedit_free_list(histedit_cmds);
12024 err = histedit_run_editor(histedit_cmds, path, commits,
12025 repo);
12026 if (err) {
12027 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12028 err->code != GOT_ERR_HISTEDIT_CMD)
12029 break;
12030 prev_err = err;
12031 resp = ' ';
12032 continue;
12034 break;
12035 } else if (resp == 'r') {
12036 histedit_free_list(histedit_cmds);
12037 err = histedit_edit_script(histedit_cmds,
12038 commits, branch_name, 0, 0, 0, 0, repo);
12039 if (err) {
12040 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12041 err->code != GOT_ERR_HISTEDIT_CMD)
12042 break;
12043 prev_err = err;
12044 resp = ' ';
12045 continue;
12047 break;
12048 } else if (resp == 'a') {
12049 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12050 break;
12051 } else
12052 printf("invalid response '%c'\n", resp);
12055 return err;
12058 static const struct got_error *
12059 histedit_complete(struct got_worktree *worktree,
12060 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12061 struct got_reference *branch, struct got_repository *repo)
12063 printf("Switching work tree to %s\n",
12064 got_ref_get_symref_target(branch));
12065 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12066 branch, repo);
12069 static const struct got_error *
12070 show_histedit_progress(struct got_commit_object *commit,
12071 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12073 const struct got_error *err;
12074 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12076 err = got_object_id_str(&old_id_str, hle->commit_id);
12077 if (err)
12078 goto done;
12080 if (new_id) {
12081 err = got_object_id_str(&new_id_str, new_id);
12082 if (err)
12083 goto done;
12086 old_id_str[12] = '\0';
12087 if (new_id_str)
12088 new_id_str[12] = '\0';
12090 if (hle->logmsg) {
12091 logmsg = strdup(hle->logmsg);
12092 if (logmsg == NULL) {
12093 err = got_error_from_errno("strdup");
12094 goto done;
12096 trim_logmsg(logmsg, 42);
12097 } else {
12098 err = get_short_logmsg(&logmsg, 42, commit);
12099 if (err)
12100 goto done;
12103 switch (hle->cmd->code) {
12104 case GOT_HISTEDIT_PICK:
12105 case GOT_HISTEDIT_EDIT:
12106 printf("%s -> %s: %s\n", old_id_str,
12107 new_id_str ? new_id_str : "no-op change", logmsg);
12108 break;
12109 case GOT_HISTEDIT_DROP:
12110 case GOT_HISTEDIT_FOLD:
12111 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12112 logmsg);
12113 break;
12114 default:
12115 break;
12117 done:
12118 free(old_id_str);
12119 free(new_id_str);
12120 return err;
12123 static const struct got_error *
12124 histedit_commit(struct got_pathlist_head *merged_paths,
12125 struct got_worktree *worktree, struct got_fileindex *fileindex,
12126 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12127 const char *committer, struct got_repository *repo)
12129 const struct got_error *err;
12130 struct got_commit_object *commit;
12131 struct got_object_id *new_commit_id;
12133 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12134 && hle->logmsg == NULL) {
12135 err = histedit_edit_logmsg(hle, repo);
12136 if (err)
12137 return err;
12140 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12141 if (err)
12142 return err;
12144 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12145 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12146 hle->logmsg, repo);
12147 if (err) {
12148 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12149 goto done;
12150 err = show_histedit_progress(commit, hle, NULL);
12151 } else {
12152 err = show_histedit_progress(commit, hle, new_commit_id);
12153 free(new_commit_id);
12155 done:
12156 got_object_commit_close(commit);
12157 return err;
12160 static const struct got_error *
12161 histedit_skip_commit(struct got_histedit_list_entry *hle,
12162 struct got_worktree *worktree, struct got_repository *repo)
12164 const struct got_error *error;
12165 struct got_commit_object *commit;
12167 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12168 repo);
12169 if (error)
12170 return error;
12172 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12173 if (error)
12174 return error;
12176 error = show_histedit_progress(commit, hle, NULL);
12177 got_object_commit_close(commit);
12178 return error;
12181 static const struct got_error *
12182 check_local_changes(void *arg, unsigned char status,
12183 unsigned char staged_status, const char *path,
12184 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12185 struct got_object_id *commit_id, int dirfd, const char *de_name)
12187 int *have_local_changes = arg;
12189 switch (status) {
12190 case GOT_STATUS_ADD:
12191 case GOT_STATUS_DELETE:
12192 case GOT_STATUS_MODIFY:
12193 case GOT_STATUS_CONFLICT:
12194 *have_local_changes = 1;
12195 return got_error(GOT_ERR_CANCELLED);
12196 default:
12197 break;
12200 switch (staged_status) {
12201 case GOT_STATUS_ADD:
12202 case GOT_STATUS_DELETE:
12203 case GOT_STATUS_MODIFY:
12204 *have_local_changes = 1;
12205 return got_error(GOT_ERR_CANCELLED);
12206 default:
12207 break;
12210 return NULL;
12213 static const struct got_error *
12214 cmd_histedit(int argc, char *argv[])
12216 const struct got_error *error = NULL;
12217 struct got_worktree *worktree = NULL;
12218 struct got_fileindex *fileindex = NULL;
12219 struct got_repository *repo = NULL;
12220 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12221 struct got_reference *branch = NULL;
12222 struct got_reference *tmp_branch = NULL;
12223 struct got_object_id *resume_commit_id = NULL;
12224 struct got_object_id *base_commit_id = NULL;
12225 struct got_object_id *head_commit_id = NULL;
12226 struct got_commit_object *commit = NULL;
12227 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12228 struct got_update_progress_arg upa;
12229 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12230 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12231 int list_backups = 0, delete_backups = 0;
12232 const char *edit_script_path = NULL;
12233 struct got_object_id_queue commits;
12234 struct got_pathlist_head merged_paths;
12235 const struct got_object_id_queue *parent_ids;
12236 struct got_object_qid *pid;
12237 struct got_histedit_list histedit_cmds;
12238 struct got_histedit_list_entry *hle;
12239 int *pack_fds = NULL;
12241 STAILQ_INIT(&commits);
12242 TAILQ_INIT(&histedit_cmds);
12243 TAILQ_INIT(&merged_paths);
12244 memset(&upa, 0, sizeof(upa));
12246 #ifndef PROFILE
12247 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12248 "unveil", NULL) == -1)
12249 err(1, "pledge");
12250 #endif
12252 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12253 switch (ch) {
12254 case 'a':
12255 abort_edit = 1;
12256 break;
12257 case 'c':
12258 continue_edit = 1;
12259 break;
12260 case 'd':
12261 drop_only = 1;
12262 break;
12263 case 'e':
12264 edit_only = 1;
12265 break;
12266 case 'F':
12267 edit_script_path = optarg;
12268 break;
12269 case 'f':
12270 fold_only = 1;
12271 break;
12272 case 'l':
12273 list_backups = 1;
12274 break;
12275 case 'm':
12276 edit_logmsg_only = 1;
12277 break;
12278 case 'X':
12279 delete_backups = 1;
12280 break;
12281 default:
12282 usage_histedit();
12283 /* NOTREACHED */
12287 argc -= optind;
12288 argv += optind;
12290 if (abort_edit && continue_edit)
12291 option_conflict('a', 'c');
12292 if (edit_script_path && edit_logmsg_only)
12293 option_conflict('F', 'm');
12294 if (abort_edit && edit_logmsg_only)
12295 option_conflict('a', 'm');
12296 if (continue_edit && edit_logmsg_only)
12297 option_conflict('c', 'm');
12298 if (abort_edit && fold_only)
12299 option_conflict('a', 'f');
12300 if (continue_edit && fold_only)
12301 option_conflict('c', 'f');
12302 if (fold_only && edit_logmsg_only)
12303 option_conflict('f', 'm');
12304 if (edit_script_path && fold_only)
12305 option_conflict('F', 'f');
12306 if (abort_edit && edit_only)
12307 option_conflict('a', 'e');
12308 if (continue_edit && edit_only)
12309 option_conflict('c', 'e');
12310 if (edit_only && edit_logmsg_only)
12311 option_conflict('e', 'm');
12312 if (edit_script_path && edit_only)
12313 option_conflict('F', 'e');
12314 if (fold_only && edit_only)
12315 option_conflict('f', 'e');
12316 if (drop_only && abort_edit)
12317 option_conflict('d', 'a');
12318 if (drop_only && continue_edit)
12319 option_conflict('d', 'c');
12320 if (drop_only && edit_logmsg_only)
12321 option_conflict('d', 'm');
12322 if (drop_only && edit_only)
12323 option_conflict('d', 'e');
12324 if (drop_only && edit_script_path)
12325 option_conflict('d', 'F');
12326 if (drop_only && fold_only)
12327 option_conflict('d', 'f');
12328 if (list_backups) {
12329 if (abort_edit)
12330 option_conflict('l', 'a');
12331 if (continue_edit)
12332 option_conflict('l', 'c');
12333 if (edit_script_path)
12334 option_conflict('l', 'F');
12335 if (edit_logmsg_only)
12336 option_conflict('l', 'm');
12337 if (drop_only)
12338 option_conflict('l', 'd');
12339 if (fold_only)
12340 option_conflict('l', 'f');
12341 if (edit_only)
12342 option_conflict('l', 'e');
12343 if (delete_backups)
12344 option_conflict('l', 'X');
12345 if (argc != 0 && argc != 1)
12346 usage_histedit();
12347 } else if (delete_backups) {
12348 if (abort_edit)
12349 option_conflict('X', 'a');
12350 if (continue_edit)
12351 option_conflict('X', 'c');
12352 if (drop_only)
12353 option_conflict('X', 'd');
12354 if (edit_script_path)
12355 option_conflict('X', 'F');
12356 if (edit_logmsg_only)
12357 option_conflict('X', 'm');
12358 if (fold_only)
12359 option_conflict('X', 'f');
12360 if (edit_only)
12361 option_conflict('X', 'e');
12362 if (list_backups)
12363 option_conflict('X', 'l');
12364 if (argc != 0 && argc != 1)
12365 usage_histedit();
12366 } else if (argc != 0)
12367 usage_histedit();
12370 * This command cannot apply unveil(2) in all cases because the
12371 * user may choose to run an editor to edit the histedit script
12372 * and to edit individual commit log messages.
12373 * unveil(2) traverses exec(2); if an editor is used we have to
12374 * apply unveil after edit script and log messages have been written.
12375 * XXX TODO: Make use of unveil(2) where possible.
12378 cwd = getcwd(NULL, 0);
12379 if (cwd == NULL) {
12380 error = got_error_from_errno("getcwd");
12381 goto done;
12384 error = got_repo_pack_fds_open(&pack_fds);
12385 if (error != NULL)
12386 goto done;
12388 error = got_worktree_open(&worktree, cwd);
12389 if (error) {
12390 if (list_backups || delete_backups) {
12391 if (error->code != GOT_ERR_NOT_WORKTREE)
12392 goto done;
12393 } else {
12394 if (error->code == GOT_ERR_NOT_WORKTREE)
12395 error = wrap_not_worktree_error(error,
12396 "histedit", cwd);
12397 goto done;
12401 if (list_backups || delete_backups) {
12402 error = got_repo_open(&repo,
12403 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12404 NULL, pack_fds);
12405 if (error != NULL)
12406 goto done;
12407 error = apply_unveil(got_repo_get_path(repo), 0,
12408 worktree ? got_worktree_get_root_path(worktree) : NULL);
12409 if (error)
12410 goto done;
12411 error = process_backup_refs(
12412 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12413 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12414 goto done; /* nothing else to do */
12417 error = get_gitconfig_path(&gitconfig_path);
12418 if (error)
12419 goto done;
12420 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12421 gitconfig_path, pack_fds);
12422 if (error != NULL)
12423 goto done;
12425 if (worktree != NULL && !list_backups && !delete_backups) {
12426 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12427 if (error)
12428 goto done;
12431 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12432 if (error)
12433 goto done;
12434 if (rebase_in_progress) {
12435 error = got_error(GOT_ERR_REBASING);
12436 goto done;
12439 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12440 repo);
12441 if (error)
12442 goto done;
12443 if (merge_in_progress) {
12444 error = got_error(GOT_ERR_MERGE_BUSY);
12445 goto done;
12448 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12449 if (error)
12450 goto done;
12452 if (edit_in_progress && edit_logmsg_only) {
12453 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12454 "histedit operation is in progress in this "
12455 "work tree and must be continued or aborted "
12456 "before the -m option can be used");
12457 goto done;
12459 if (edit_in_progress && drop_only) {
12460 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12461 "histedit operation is in progress in this "
12462 "work tree and must be continued or aborted "
12463 "before the -d option can be used");
12464 goto done;
12466 if (edit_in_progress && fold_only) {
12467 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12468 "histedit operation is in progress in this "
12469 "work tree and must be continued or aborted "
12470 "before the -f option can be used");
12471 goto done;
12473 if (edit_in_progress && edit_only) {
12474 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12475 "histedit operation is in progress in this "
12476 "work tree and must be continued or aborted "
12477 "before the -e option can be used");
12478 goto done;
12481 if (edit_in_progress && abort_edit) {
12482 error = got_worktree_histedit_continue(&resume_commit_id,
12483 &tmp_branch, &branch, &base_commit_id, &fileindex,
12484 worktree, repo);
12485 if (error)
12486 goto done;
12487 printf("Switching work tree to %s\n",
12488 got_ref_get_symref_target(branch));
12489 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12490 branch, base_commit_id, abort_progress, &upa);
12491 if (error)
12492 goto done;
12493 printf("Histedit of %s aborted\n",
12494 got_ref_get_symref_target(branch));
12495 print_merge_progress_stats(&upa);
12496 goto done; /* nothing else to do */
12497 } else if (abort_edit) {
12498 error = got_error(GOT_ERR_NOT_HISTEDIT);
12499 goto done;
12502 error = get_author(&committer, repo, worktree);
12503 if (error)
12504 goto done;
12506 if (continue_edit) {
12507 char *path;
12509 if (!edit_in_progress) {
12510 error = got_error(GOT_ERR_NOT_HISTEDIT);
12511 goto done;
12514 error = got_worktree_get_histedit_script_path(&path, worktree);
12515 if (error)
12516 goto done;
12518 error = histedit_load_list(&histedit_cmds, path, repo);
12519 free(path);
12520 if (error)
12521 goto done;
12523 error = got_worktree_histedit_continue(&resume_commit_id,
12524 &tmp_branch, &branch, &base_commit_id, &fileindex,
12525 worktree, repo);
12526 if (error)
12527 goto done;
12529 error = got_ref_resolve(&head_commit_id, repo, branch);
12530 if (error)
12531 goto done;
12533 error = got_object_open_as_commit(&commit, repo,
12534 head_commit_id);
12535 if (error)
12536 goto done;
12537 parent_ids = got_object_commit_get_parent_ids(commit);
12538 pid = STAILQ_FIRST(parent_ids);
12539 if (pid == NULL) {
12540 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12541 goto done;
12543 error = collect_commits(&commits, head_commit_id, &pid->id,
12544 base_commit_id, got_worktree_get_path_prefix(worktree),
12545 GOT_ERR_HISTEDIT_PATH, repo);
12546 got_object_commit_close(commit);
12547 commit = NULL;
12548 if (error)
12549 goto done;
12550 } else {
12551 if (edit_in_progress) {
12552 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12553 goto done;
12556 error = got_ref_open(&branch, repo,
12557 got_worktree_get_head_ref_name(worktree), 0);
12558 if (error != NULL)
12559 goto done;
12561 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12562 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12563 "will not edit commit history of a branch outside "
12564 "the \"refs/heads/\" reference namespace");
12565 goto done;
12568 error = got_ref_resolve(&head_commit_id, repo, branch);
12569 got_ref_close(branch);
12570 branch = NULL;
12571 if (error)
12572 goto done;
12574 error = got_object_open_as_commit(&commit, repo,
12575 head_commit_id);
12576 if (error)
12577 goto done;
12578 parent_ids = got_object_commit_get_parent_ids(commit);
12579 pid = STAILQ_FIRST(parent_ids);
12580 if (pid == NULL) {
12581 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12582 goto done;
12584 error = collect_commits(&commits, head_commit_id, &pid->id,
12585 got_worktree_get_base_commit_id(worktree),
12586 got_worktree_get_path_prefix(worktree),
12587 GOT_ERR_HISTEDIT_PATH, repo);
12588 got_object_commit_close(commit);
12589 commit = NULL;
12590 if (error)
12591 goto done;
12593 if (STAILQ_EMPTY(&commits)) {
12594 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12595 goto done;
12598 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12599 &base_commit_id, &fileindex, worktree, repo);
12600 if (error)
12601 goto done;
12603 if (edit_script_path) {
12604 error = histedit_load_list(&histedit_cmds,
12605 edit_script_path, repo);
12606 if (error) {
12607 got_worktree_histedit_abort(worktree, fileindex,
12608 repo, branch, base_commit_id,
12609 abort_progress, &upa);
12610 print_merge_progress_stats(&upa);
12611 goto done;
12613 } else {
12614 const char *branch_name;
12615 branch_name = got_ref_get_symref_target(branch);
12616 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12617 branch_name += 11;
12618 error = histedit_edit_script(&histedit_cmds, &commits,
12619 branch_name, edit_logmsg_only, fold_only,
12620 drop_only, edit_only, repo);
12621 if (error) {
12622 got_worktree_histedit_abort(worktree, fileindex,
12623 repo, branch, base_commit_id,
12624 abort_progress, &upa);
12625 print_merge_progress_stats(&upa);
12626 goto done;
12631 error = histedit_save_list(&histedit_cmds, worktree,
12632 repo);
12633 if (error) {
12634 got_worktree_histedit_abort(worktree, fileindex,
12635 repo, branch, base_commit_id,
12636 abort_progress, &upa);
12637 print_merge_progress_stats(&upa);
12638 goto done;
12643 error = histedit_check_script(&histedit_cmds, &commits, repo);
12644 if (error)
12645 goto done;
12647 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12648 if (resume_commit_id) {
12649 if (got_object_id_cmp(hle->commit_id,
12650 resume_commit_id) != 0)
12651 continue;
12653 resume_commit_id = NULL;
12654 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12655 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12656 error = histedit_skip_commit(hle, worktree,
12657 repo);
12658 if (error)
12659 goto done;
12660 } else {
12661 struct got_pathlist_head paths;
12662 int have_changes = 0;
12664 TAILQ_INIT(&paths);
12665 error = got_pathlist_append(&paths, "", NULL);
12666 if (error)
12667 goto done;
12668 error = got_worktree_status(worktree, &paths,
12669 repo, 0, check_local_changes, &have_changes,
12670 check_cancelled, NULL);
12671 got_pathlist_free(&paths,
12672 GOT_PATHLIST_FREE_NONE);
12673 if (error) {
12674 if (error->code != GOT_ERR_CANCELLED)
12675 goto done;
12676 if (sigint_received || sigpipe_received)
12677 goto done;
12679 if (have_changes) {
12680 error = histedit_commit(NULL, worktree,
12681 fileindex, tmp_branch, hle,
12682 committer, repo);
12683 if (error)
12684 goto done;
12685 } else {
12686 error = got_object_open_as_commit(
12687 &commit, repo, hle->commit_id);
12688 if (error)
12689 goto done;
12690 error = show_histedit_progress(commit,
12691 hle, NULL);
12692 got_object_commit_close(commit);
12693 commit = NULL;
12694 if (error)
12695 goto done;
12698 continue;
12701 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12702 error = histedit_skip_commit(hle, worktree, repo);
12703 if (error)
12704 goto done;
12705 continue;
12708 error = got_object_open_as_commit(&commit, repo,
12709 hle->commit_id);
12710 if (error)
12711 goto done;
12712 parent_ids = got_object_commit_get_parent_ids(commit);
12713 pid = STAILQ_FIRST(parent_ids);
12715 error = got_worktree_histedit_merge_files(&merged_paths,
12716 worktree, fileindex, &pid->id, hle->commit_id, repo,
12717 update_progress, &upa, check_cancelled, NULL);
12718 if (error)
12719 goto done;
12720 got_object_commit_close(commit);
12721 commit = NULL;
12723 print_merge_progress_stats(&upa);
12724 if (upa.conflicts > 0 || upa.missing > 0 ||
12725 upa.not_deleted > 0 || upa.unversioned > 0) {
12726 if (upa.conflicts > 0) {
12727 error = show_rebase_merge_conflict(
12728 hle->commit_id, repo);
12729 if (error)
12730 goto done;
12732 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12733 break;
12736 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12737 char *id_str;
12738 error = got_object_id_str(&id_str, hle->commit_id);
12739 if (error)
12740 goto done;
12741 printf("Stopping histedit for amending commit %s\n",
12742 id_str);
12743 free(id_str);
12744 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12745 error = got_worktree_histedit_postpone(worktree,
12746 fileindex);
12747 goto done;
12750 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12751 error = histedit_skip_commit(hle, worktree, repo);
12752 if (error)
12753 goto done;
12754 continue;
12757 error = histedit_commit(&merged_paths, worktree, fileindex,
12758 tmp_branch, hle, committer, repo);
12759 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12760 if (error)
12761 goto done;
12764 if (upa.conflicts > 0 || upa.missing > 0 ||
12765 upa.not_deleted > 0 || upa.unversioned > 0) {
12766 error = got_worktree_histedit_postpone(worktree, fileindex);
12767 if (error)
12768 goto done;
12769 if (upa.conflicts > 0 && upa.missing == 0 &&
12770 upa.not_deleted == 0 && upa.unversioned == 0) {
12771 error = got_error_msg(GOT_ERR_CONFLICTS,
12772 "conflicts must be resolved before histedit "
12773 "can continue");
12774 } else if (upa.conflicts > 0) {
12775 error = got_error_msg(GOT_ERR_CONFLICTS,
12776 "conflicts must be resolved before histedit "
12777 "can continue; changes destined for some "
12778 "files were not yet merged and should be "
12779 "merged manually if required before the "
12780 "histedit operation is continued");
12781 } else {
12782 error = got_error_msg(GOT_ERR_CONFLICTS,
12783 "changes destined for some files were not "
12784 "yet merged and should be merged manually "
12785 "if required before the histedit operation "
12786 "is continued");
12788 } else
12789 error = histedit_complete(worktree, fileindex, tmp_branch,
12790 branch, repo);
12791 done:
12792 free(cwd);
12793 free(committer);
12794 free(gitconfig_path);
12795 got_object_id_queue_free(&commits);
12796 histedit_free_list(&histedit_cmds);
12797 free(head_commit_id);
12798 free(base_commit_id);
12799 free(resume_commit_id);
12800 if (commit)
12801 got_object_commit_close(commit);
12802 if (branch)
12803 got_ref_close(branch);
12804 if (tmp_branch)
12805 got_ref_close(tmp_branch);
12806 if (worktree)
12807 got_worktree_close(worktree);
12808 if (repo) {
12809 const struct got_error *close_err = got_repo_close(repo);
12810 if (error == NULL)
12811 error = close_err;
12813 if (pack_fds) {
12814 const struct got_error *pack_err =
12815 got_repo_pack_fds_close(pack_fds);
12816 if (error == NULL)
12817 error = pack_err;
12819 return error;
12822 __dead static void
12823 usage_integrate(void)
12825 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12826 exit(1);
12829 static const struct got_error *
12830 cmd_integrate(int argc, char *argv[])
12832 const struct got_error *error = NULL;
12833 struct got_repository *repo = NULL;
12834 struct got_worktree *worktree = NULL;
12835 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12836 const char *branch_arg = NULL;
12837 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12838 struct got_fileindex *fileindex = NULL;
12839 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12840 int ch;
12841 struct got_update_progress_arg upa;
12842 int *pack_fds = NULL;
12844 #ifndef PROFILE
12845 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12846 "unveil", NULL) == -1)
12847 err(1, "pledge");
12848 #endif
12850 while ((ch = getopt(argc, argv, "")) != -1) {
12851 switch (ch) {
12852 default:
12853 usage_integrate();
12854 /* NOTREACHED */
12858 argc -= optind;
12859 argv += optind;
12861 if (argc != 1)
12862 usage_integrate();
12863 branch_arg = argv[0];
12865 cwd = getcwd(NULL, 0);
12866 if (cwd == NULL) {
12867 error = got_error_from_errno("getcwd");
12868 goto done;
12871 error = got_repo_pack_fds_open(&pack_fds);
12872 if (error != NULL)
12873 goto done;
12875 error = got_worktree_open(&worktree, cwd);
12876 if (error) {
12877 if (error->code == GOT_ERR_NOT_WORKTREE)
12878 error = wrap_not_worktree_error(error, "integrate",
12879 cwd);
12880 goto done;
12883 error = check_rebase_or_histedit_in_progress(worktree);
12884 if (error)
12885 goto done;
12887 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12888 NULL, pack_fds);
12889 if (error != NULL)
12890 goto done;
12892 error = apply_unveil(got_repo_get_path(repo), 0,
12893 got_worktree_get_root_path(worktree));
12894 if (error)
12895 goto done;
12897 error = check_merge_in_progress(worktree, repo);
12898 if (error)
12899 goto done;
12901 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12902 error = got_error_from_errno("asprintf");
12903 goto done;
12906 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12907 &base_branch_ref, worktree, refname, repo);
12908 if (error)
12909 goto done;
12911 refname = strdup(got_ref_get_name(branch_ref));
12912 if (refname == NULL) {
12913 error = got_error_from_errno("strdup");
12914 got_worktree_integrate_abort(worktree, fileindex, repo,
12915 branch_ref, base_branch_ref);
12916 goto done;
12918 base_refname = strdup(got_ref_get_name(base_branch_ref));
12919 if (base_refname == NULL) {
12920 error = got_error_from_errno("strdup");
12921 got_worktree_integrate_abort(worktree, fileindex, repo,
12922 branch_ref, base_branch_ref);
12923 goto done;
12925 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12926 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12927 got_worktree_integrate_abort(worktree, fileindex, repo,
12928 branch_ref, base_branch_ref);
12929 goto done;
12932 error = got_ref_resolve(&commit_id, repo, branch_ref);
12933 if (error)
12934 goto done;
12936 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12937 if (error)
12938 goto done;
12940 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12941 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12942 "specified branch has already been integrated");
12943 got_worktree_integrate_abort(worktree, fileindex, repo,
12944 branch_ref, base_branch_ref);
12945 goto done;
12948 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12949 if (error) {
12950 if (error->code == GOT_ERR_ANCESTRY)
12951 error = got_error(GOT_ERR_REBASE_REQUIRED);
12952 got_worktree_integrate_abort(worktree, fileindex, repo,
12953 branch_ref, base_branch_ref);
12954 goto done;
12957 memset(&upa, 0, sizeof(upa));
12958 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12959 branch_ref, base_branch_ref, update_progress, &upa,
12960 check_cancelled, NULL);
12961 if (error)
12962 goto done;
12964 printf("Integrated %s into %s\n", refname, base_refname);
12965 print_update_progress_stats(&upa);
12966 done:
12967 if (repo) {
12968 const struct got_error *close_err = got_repo_close(repo);
12969 if (error == NULL)
12970 error = close_err;
12972 if (worktree)
12973 got_worktree_close(worktree);
12974 if (pack_fds) {
12975 const struct got_error *pack_err =
12976 got_repo_pack_fds_close(pack_fds);
12977 if (error == NULL)
12978 error = pack_err;
12980 free(cwd);
12981 free(base_commit_id);
12982 free(commit_id);
12983 free(refname);
12984 free(base_refname);
12985 return error;
12988 __dead static void
12989 usage_merge(void)
12991 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12992 exit(1);
12995 static const struct got_error *
12996 cmd_merge(int argc, char *argv[])
12998 const struct got_error *error = NULL;
12999 struct got_worktree *worktree = NULL;
13000 struct got_repository *repo = NULL;
13001 struct got_fileindex *fileindex = NULL;
13002 char *cwd = NULL, *id_str = NULL, *author = NULL;
13003 struct got_reference *branch = NULL, *wt_branch = NULL;
13004 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13005 struct got_object_id *wt_branch_tip = NULL;
13006 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13007 int interrupt_merge = 0;
13008 struct got_update_progress_arg upa;
13009 struct got_object_id *merge_commit_id = NULL;
13010 char *branch_name = NULL;
13011 int *pack_fds = NULL;
13013 memset(&upa, 0, sizeof(upa));
13015 #ifndef PROFILE
13016 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13017 "unveil", NULL) == -1)
13018 err(1, "pledge");
13019 #endif
13021 while ((ch = getopt(argc, argv, "acn")) != -1) {
13022 switch (ch) {
13023 case 'a':
13024 abort_merge = 1;
13025 break;
13026 case 'c':
13027 continue_merge = 1;
13028 break;
13029 case 'n':
13030 interrupt_merge = 1;
13031 break;
13032 default:
13033 usage_merge();
13034 /* NOTREACHED */
13038 argc -= optind;
13039 argv += optind;
13041 if (abort_merge && continue_merge)
13042 option_conflict('a', 'c');
13043 if (abort_merge || continue_merge) {
13044 if (argc != 0)
13045 usage_merge();
13046 } else if (argc != 1)
13047 usage_merge();
13049 cwd = getcwd(NULL, 0);
13050 if (cwd == NULL) {
13051 error = got_error_from_errno("getcwd");
13052 goto done;
13055 error = got_repo_pack_fds_open(&pack_fds);
13056 if (error != NULL)
13057 goto done;
13059 error = got_worktree_open(&worktree, cwd);
13060 if (error) {
13061 if (error->code == GOT_ERR_NOT_WORKTREE)
13062 error = wrap_not_worktree_error(error,
13063 "merge", cwd);
13064 goto done;
13067 error = got_repo_open(&repo,
13068 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13069 pack_fds);
13070 if (error != NULL)
13071 goto done;
13073 if (worktree != NULL) {
13074 error = worktree_has_logmsg_ref("merge", worktree, repo);
13075 if (error)
13076 goto done;
13079 error = apply_unveil(got_repo_get_path(repo), 0,
13080 worktree ? got_worktree_get_root_path(worktree) : NULL);
13081 if (error)
13082 goto done;
13084 error = check_rebase_or_histedit_in_progress(worktree);
13085 if (error)
13086 goto done;
13088 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13089 repo);
13090 if (error)
13091 goto done;
13093 if (abort_merge) {
13094 if (!merge_in_progress) {
13095 error = got_error(GOT_ERR_NOT_MERGING);
13096 goto done;
13098 error = got_worktree_merge_continue(&branch_name,
13099 &branch_tip, &fileindex, worktree, repo);
13100 if (error)
13101 goto done;
13102 error = got_worktree_merge_abort(worktree, fileindex, repo,
13103 abort_progress, &upa);
13104 if (error)
13105 goto done;
13106 printf("Merge of %s aborted\n", branch_name);
13107 goto done; /* nothing else to do */
13110 error = get_author(&author, repo, worktree);
13111 if (error)
13112 goto done;
13114 if (continue_merge) {
13115 if (!merge_in_progress) {
13116 error = got_error(GOT_ERR_NOT_MERGING);
13117 goto done;
13119 error = got_worktree_merge_continue(&branch_name,
13120 &branch_tip, &fileindex, worktree, repo);
13121 if (error)
13122 goto done;
13123 } else {
13124 error = got_ref_open(&branch, repo, argv[0], 0);
13125 if (error != NULL)
13126 goto done;
13127 branch_name = strdup(got_ref_get_name(branch));
13128 if (branch_name == NULL) {
13129 error = got_error_from_errno("strdup");
13130 goto done;
13132 error = got_ref_resolve(&branch_tip, repo, branch);
13133 if (error)
13134 goto done;
13137 error = got_ref_open(&wt_branch, repo,
13138 got_worktree_get_head_ref_name(worktree), 0);
13139 if (error)
13140 goto done;
13141 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13142 if (error)
13143 goto done;
13144 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13145 wt_branch_tip, branch_tip, 0, repo,
13146 check_cancelled, NULL);
13147 if (error && error->code != GOT_ERR_ANCESTRY)
13148 goto done;
13150 if (!continue_merge) {
13151 error = check_path_prefix(wt_branch_tip, branch_tip,
13152 got_worktree_get_path_prefix(worktree),
13153 GOT_ERR_MERGE_PATH, repo);
13154 if (error)
13155 goto done;
13156 if (yca_id) {
13157 error = check_same_branch(wt_branch_tip, branch,
13158 yca_id, repo);
13159 if (error) {
13160 if (error->code != GOT_ERR_ANCESTRY)
13161 goto done;
13162 error = NULL;
13163 } else {
13164 static char msg[512];
13165 snprintf(msg, sizeof(msg),
13166 "cannot create a merge commit because "
13167 "%s is based on %s; %s can be integrated "
13168 "with 'got integrate' instead", branch_name,
13169 got_worktree_get_head_ref_name(worktree),
13170 branch_name);
13171 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13172 goto done;
13175 error = got_worktree_merge_prepare(&fileindex, worktree,
13176 branch, repo);
13177 if (error)
13178 goto done;
13180 error = got_worktree_merge_branch(worktree, fileindex,
13181 yca_id, branch_tip, repo, update_progress, &upa,
13182 check_cancelled, NULL);
13183 if (error)
13184 goto done;
13185 print_merge_progress_stats(&upa);
13186 if (!upa.did_something) {
13187 error = got_worktree_merge_abort(worktree, fileindex,
13188 repo, abort_progress, &upa);
13189 if (error)
13190 goto done;
13191 printf("Already up-to-date\n");
13192 goto done;
13196 if (interrupt_merge) {
13197 error = got_worktree_merge_postpone(worktree, fileindex);
13198 if (error)
13199 goto done;
13200 printf("Merge of %s interrupted on request\n", branch_name);
13201 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13202 upa.not_deleted > 0 || upa.unversioned > 0) {
13203 error = got_worktree_merge_postpone(worktree, fileindex);
13204 if (error)
13205 goto done;
13206 if (upa.conflicts > 0 && upa.missing == 0 &&
13207 upa.not_deleted == 0 && upa.unversioned == 0) {
13208 error = got_error_msg(GOT_ERR_CONFLICTS,
13209 "conflicts must be resolved before merging "
13210 "can continue");
13211 } else if (upa.conflicts > 0) {
13212 error = got_error_msg(GOT_ERR_CONFLICTS,
13213 "conflicts must be resolved before merging "
13214 "can continue; changes destined for some "
13215 "files were not yet merged and "
13216 "should be merged manually if required before the "
13217 "merge operation is continued");
13218 } else {
13219 error = got_error_msg(GOT_ERR_CONFLICTS,
13220 "changes destined for some "
13221 "files were not yet merged and should be "
13222 "merged manually if required before the "
13223 "merge operation is continued");
13225 goto done;
13226 } else {
13227 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13228 fileindex, author, NULL, 1, branch_tip, branch_name,
13229 repo, continue_merge ? print_status : NULL, NULL);
13230 if (error)
13231 goto done;
13232 error = got_worktree_merge_complete(worktree, fileindex, repo);
13233 if (error)
13234 goto done;
13235 error = got_object_id_str(&id_str, merge_commit_id);
13236 if (error)
13237 goto done;
13238 printf("Merged %s into %s: %s\n", branch_name,
13239 got_worktree_get_head_ref_name(worktree),
13240 id_str);
13243 done:
13244 free(id_str);
13245 free(merge_commit_id);
13246 free(author);
13247 free(branch_tip);
13248 free(branch_name);
13249 free(yca_id);
13250 if (branch)
13251 got_ref_close(branch);
13252 if (wt_branch)
13253 got_ref_close(wt_branch);
13254 if (worktree)
13255 got_worktree_close(worktree);
13256 if (repo) {
13257 const struct got_error *close_err = got_repo_close(repo);
13258 if (error == NULL)
13259 error = close_err;
13261 if (pack_fds) {
13262 const struct got_error *pack_err =
13263 got_repo_pack_fds_close(pack_fds);
13264 if (error == NULL)
13265 error = pack_err;
13267 return error;
13270 __dead static void
13271 usage_stage(void)
13273 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13274 "[path ...]\n", getprogname());
13275 exit(1);
13278 static const struct got_error *
13279 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13280 const char *path, struct got_object_id *blob_id,
13281 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13282 int dirfd, const char *de_name)
13284 const struct got_error *err = NULL;
13285 char *id_str = NULL;
13287 if (staged_status != GOT_STATUS_ADD &&
13288 staged_status != GOT_STATUS_MODIFY &&
13289 staged_status != GOT_STATUS_DELETE)
13290 return NULL;
13292 if (staged_status == GOT_STATUS_ADD ||
13293 staged_status == GOT_STATUS_MODIFY)
13294 err = got_object_id_str(&id_str, staged_blob_id);
13295 else
13296 err = got_object_id_str(&id_str, blob_id);
13297 if (err)
13298 return err;
13300 printf("%s %c %s\n", id_str, staged_status, path);
13301 free(id_str);
13302 return NULL;
13305 static const struct got_error *
13306 cmd_stage(int argc, char *argv[])
13308 const struct got_error *error = NULL;
13309 struct got_repository *repo = NULL;
13310 struct got_worktree *worktree = NULL;
13311 char *cwd = NULL;
13312 struct got_pathlist_head paths;
13313 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13314 FILE *patch_script_file = NULL;
13315 const char *patch_script_path = NULL;
13316 struct choose_patch_arg cpa;
13317 int *pack_fds = NULL;
13319 TAILQ_INIT(&paths);
13321 #ifndef PROFILE
13322 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13323 "unveil", NULL) == -1)
13324 err(1, "pledge");
13325 #endif
13327 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13328 switch (ch) {
13329 case 'F':
13330 patch_script_path = optarg;
13331 break;
13332 case 'l':
13333 list_stage = 1;
13334 break;
13335 case 'p':
13336 pflag = 1;
13337 break;
13338 case 'S':
13339 allow_bad_symlinks = 1;
13340 break;
13341 default:
13342 usage_stage();
13343 /* NOTREACHED */
13347 argc -= optind;
13348 argv += optind;
13350 if (list_stage && (pflag || patch_script_path))
13351 errx(1, "-l option cannot be used with other options");
13352 if (patch_script_path && !pflag)
13353 errx(1, "-F option can only be used together with -p option");
13355 cwd = getcwd(NULL, 0);
13356 if (cwd == NULL) {
13357 error = got_error_from_errno("getcwd");
13358 goto done;
13361 error = got_repo_pack_fds_open(&pack_fds);
13362 if (error != NULL)
13363 goto done;
13365 error = got_worktree_open(&worktree, cwd);
13366 if (error) {
13367 if (error->code == GOT_ERR_NOT_WORKTREE)
13368 error = wrap_not_worktree_error(error, "stage", cwd);
13369 goto done;
13372 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13373 NULL, pack_fds);
13374 if (error != NULL)
13375 goto done;
13377 if (patch_script_path) {
13378 patch_script_file = fopen(patch_script_path, "re");
13379 if (patch_script_file == NULL) {
13380 error = got_error_from_errno2("fopen",
13381 patch_script_path);
13382 goto done;
13385 error = apply_unveil(got_repo_get_path(repo), 0,
13386 got_worktree_get_root_path(worktree));
13387 if (error)
13388 goto done;
13390 error = check_merge_in_progress(worktree, repo);
13391 if (error)
13392 goto done;
13394 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13395 if (error)
13396 goto done;
13398 if (list_stage)
13399 error = got_worktree_status(worktree, &paths, repo, 0,
13400 print_stage, NULL, check_cancelled, NULL);
13401 else {
13402 cpa.patch_script_file = patch_script_file;
13403 cpa.action = "stage";
13404 error = got_worktree_stage(worktree, &paths,
13405 pflag ? NULL : print_status, NULL,
13406 pflag ? choose_patch : NULL, &cpa,
13407 allow_bad_symlinks, repo);
13409 done:
13410 if (patch_script_file && fclose(patch_script_file) == EOF &&
13411 error == NULL)
13412 error = got_error_from_errno2("fclose", patch_script_path);
13413 if (repo) {
13414 const struct got_error *close_err = got_repo_close(repo);
13415 if (error == NULL)
13416 error = close_err;
13418 if (worktree)
13419 got_worktree_close(worktree);
13420 if (pack_fds) {
13421 const struct got_error *pack_err =
13422 got_repo_pack_fds_close(pack_fds);
13423 if (error == NULL)
13424 error = pack_err;
13426 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13427 free(cwd);
13428 return error;
13431 __dead static void
13432 usage_unstage(void)
13434 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13435 "[path ...]\n", getprogname());
13436 exit(1);
13440 static const struct got_error *
13441 cmd_unstage(int argc, char *argv[])
13443 const struct got_error *error = NULL;
13444 struct got_repository *repo = NULL;
13445 struct got_worktree *worktree = NULL;
13446 char *cwd = NULL;
13447 struct got_pathlist_head paths;
13448 int ch, pflag = 0;
13449 struct got_update_progress_arg upa;
13450 FILE *patch_script_file = NULL;
13451 const char *patch_script_path = NULL;
13452 struct choose_patch_arg cpa;
13453 int *pack_fds = NULL;
13455 TAILQ_INIT(&paths);
13457 #ifndef PROFILE
13458 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13459 "unveil", NULL) == -1)
13460 err(1, "pledge");
13461 #endif
13463 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13464 switch (ch) {
13465 case 'F':
13466 patch_script_path = optarg;
13467 break;
13468 case 'p':
13469 pflag = 1;
13470 break;
13471 default:
13472 usage_unstage();
13473 /* NOTREACHED */
13477 argc -= optind;
13478 argv += optind;
13480 if (patch_script_path && !pflag)
13481 errx(1, "-F option can only be used together with -p option");
13483 cwd = getcwd(NULL, 0);
13484 if (cwd == NULL) {
13485 error = got_error_from_errno("getcwd");
13486 goto done;
13489 error = got_repo_pack_fds_open(&pack_fds);
13490 if (error != NULL)
13491 goto done;
13493 error = got_worktree_open(&worktree, cwd);
13494 if (error) {
13495 if (error->code == GOT_ERR_NOT_WORKTREE)
13496 error = wrap_not_worktree_error(error, "unstage", cwd);
13497 goto done;
13500 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13501 NULL, pack_fds);
13502 if (error != NULL)
13503 goto done;
13505 if (patch_script_path) {
13506 patch_script_file = fopen(patch_script_path, "re");
13507 if (patch_script_file == NULL) {
13508 error = got_error_from_errno2("fopen",
13509 patch_script_path);
13510 goto done;
13514 error = apply_unveil(got_repo_get_path(repo), 0,
13515 got_worktree_get_root_path(worktree));
13516 if (error)
13517 goto done;
13519 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13520 if (error)
13521 goto done;
13523 cpa.patch_script_file = patch_script_file;
13524 cpa.action = "unstage";
13525 memset(&upa, 0, sizeof(upa));
13526 error = got_worktree_unstage(worktree, &paths, update_progress,
13527 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13528 if (!error)
13529 print_merge_progress_stats(&upa);
13530 done:
13531 if (patch_script_file && fclose(patch_script_file) == EOF &&
13532 error == NULL)
13533 error = got_error_from_errno2("fclose", patch_script_path);
13534 if (repo) {
13535 const struct got_error *close_err = got_repo_close(repo);
13536 if (error == NULL)
13537 error = close_err;
13539 if (worktree)
13540 got_worktree_close(worktree);
13541 if (pack_fds) {
13542 const struct got_error *pack_err =
13543 got_repo_pack_fds_close(pack_fds);
13544 if (error == NULL)
13545 error = pack_err;
13547 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13548 free(cwd);
13549 return error;
13552 __dead static void
13553 usage_cat(void)
13555 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13556 "arg ...\n", getprogname());
13557 exit(1);
13560 static const struct got_error *
13561 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13563 const struct got_error *err;
13564 struct got_blob_object *blob;
13565 int fd = -1;
13567 fd = got_opentempfd();
13568 if (fd == -1)
13569 return got_error_from_errno("got_opentempfd");
13571 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13572 if (err)
13573 goto done;
13575 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13576 done:
13577 if (fd != -1 && close(fd) == -1 && err == NULL)
13578 err = got_error_from_errno("close");
13579 if (blob)
13580 got_object_blob_close(blob);
13581 return err;
13584 static const struct got_error *
13585 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13587 const struct got_error *err;
13588 struct got_tree_object *tree;
13589 int nentries, i;
13591 err = got_object_open_as_tree(&tree, repo, id);
13592 if (err)
13593 return err;
13595 nentries = got_object_tree_get_nentries(tree);
13596 for (i = 0; i < nentries; i++) {
13597 struct got_tree_entry *te;
13598 char *id_str;
13599 if (sigint_received || sigpipe_received)
13600 break;
13601 te = got_object_tree_get_entry(tree, i);
13602 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13603 if (err)
13604 break;
13605 fprintf(outfile, "%s %.7o %s\n", id_str,
13606 got_tree_entry_get_mode(te),
13607 got_tree_entry_get_name(te));
13608 free(id_str);
13611 got_object_tree_close(tree);
13612 return err;
13615 static const struct got_error *
13616 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13618 const struct got_error *err;
13619 struct got_commit_object *commit;
13620 const struct got_object_id_queue *parent_ids;
13621 struct got_object_qid *pid;
13622 char *id_str = NULL;
13623 const char *logmsg = NULL;
13624 char gmtoff[6];
13626 err = got_object_open_as_commit(&commit, repo, id);
13627 if (err)
13628 return err;
13630 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13631 if (err)
13632 goto done;
13634 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13635 parent_ids = got_object_commit_get_parent_ids(commit);
13636 fprintf(outfile, "numparents %d\n",
13637 got_object_commit_get_nparents(commit));
13638 STAILQ_FOREACH(pid, parent_ids, entry) {
13639 char *pid_str;
13640 err = got_object_id_str(&pid_str, &pid->id);
13641 if (err)
13642 goto done;
13643 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13644 free(pid_str);
13646 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13647 got_object_commit_get_author_gmtoff(commit));
13648 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13649 got_object_commit_get_author(commit),
13650 (long long)got_object_commit_get_author_time(commit),
13651 gmtoff);
13653 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13654 got_object_commit_get_committer_gmtoff(commit));
13655 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13656 got_object_commit_get_committer(commit),
13657 (long long)got_object_commit_get_committer_time(commit),
13658 gmtoff);
13660 logmsg = got_object_commit_get_logmsg_raw(commit);
13661 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13662 fprintf(outfile, "%s", logmsg);
13663 done:
13664 free(id_str);
13665 got_object_commit_close(commit);
13666 return err;
13669 static const struct got_error *
13670 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13672 const struct got_error *err;
13673 struct got_tag_object *tag;
13674 char *id_str = NULL;
13675 const char *tagmsg = NULL;
13676 char gmtoff[6];
13678 err = got_object_open_as_tag(&tag, repo, id);
13679 if (err)
13680 return err;
13682 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13683 if (err)
13684 goto done;
13686 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13688 switch (got_object_tag_get_object_type(tag)) {
13689 case GOT_OBJ_TYPE_BLOB:
13690 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13691 GOT_OBJ_LABEL_BLOB);
13692 break;
13693 case GOT_OBJ_TYPE_TREE:
13694 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13695 GOT_OBJ_LABEL_TREE);
13696 break;
13697 case GOT_OBJ_TYPE_COMMIT:
13698 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13699 GOT_OBJ_LABEL_COMMIT);
13700 break;
13701 case GOT_OBJ_TYPE_TAG:
13702 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13703 GOT_OBJ_LABEL_TAG);
13704 break;
13705 default:
13706 break;
13709 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13710 got_object_tag_get_name(tag));
13712 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13713 got_object_tag_get_tagger_gmtoff(tag));
13714 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13715 got_object_tag_get_tagger(tag),
13716 (long long)got_object_tag_get_tagger_time(tag),
13717 gmtoff);
13719 tagmsg = got_object_tag_get_message(tag);
13720 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13721 fprintf(outfile, "%s", tagmsg);
13722 done:
13723 free(id_str);
13724 got_object_tag_close(tag);
13725 return err;
13728 static const struct got_error *
13729 cmd_cat(int argc, char *argv[])
13731 const struct got_error *error;
13732 struct got_repository *repo = NULL;
13733 struct got_worktree *worktree = NULL;
13734 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13735 const char *commit_id_str = NULL;
13736 struct got_object_id *id = NULL, *commit_id = NULL;
13737 struct got_commit_object *commit = NULL;
13738 int ch, obj_type, i, force_path = 0;
13739 struct got_reflist_head refs;
13740 int *pack_fds = NULL;
13742 TAILQ_INIT(&refs);
13744 #ifndef PROFILE
13745 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13746 NULL) == -1)
13747 err(1, "pledge");
13748 #endif
13750 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13751 switch (ch) {
13752 case 'c':
13753 commit_id_str = optarg;
13754 break;
13755 case 'P':
13756 force_path = 1;
13757 break;
13758 case 'r':
13759 repo_path = realpath(optarg, NULL);
13760 if (repo_path == NULL)
13761 return got_error_from_errno2("realpath",
13762 optarg);
13763 got_path_strip_trailing_slashes(repo_path);
13764 break;
13765 default:
13766 usage_cat();
13767 /* NOTREACHED */
13771 argc -= optind;
13772 argv += optind;
13774 cwd = getcwd(NULL, 0);
13775 if (cwd == NULL) {
13776 error = got_error_from_errno("getcwd");
13777 goto done;
13780 error = got_repo_pack_fds_open(&pack_fds);
13781 if (error != NULL)
13782 goto done;
13784 if (repo_path == NULL) {
13785 error = got_worktree_open(&worktree, cwd);
13786 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13787 goto done;
13788 if (worktree) {
13789 repo_path = strdup(
13790 got_worktree_get_repo_path(worktree));
13791 if (repo_path == NULL) {
13792 error = got_error_from_errno("strdup");
13793 goto done;
13796 /* Release work tree lock. */
13797 got_worktree_close(worktree);
13798 worktree = NULL;
13802 if (repo_path == NULL) {
13803 repo_path = strdup(cwd);
13804 if (repo_path == NULL)
13805 return got_error_from_errno("strdup");
13808 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13809 free(repo_path);
13810 if (error != NULL)
13811 goto done;
13813 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13814 if (error)
13815 goto done;
13817 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13818 if (error)
13819 goto done;
13821 if (commit_id_str == NULL)
13822 commit_id_str = GOT_REF_HEAD;
13823 error = got_repo_match_object_id(&commit_id, NULL,
13824 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13825 if (error)
13826 goto done;
13828 error = got_object_open_as_commit(&commit, repo, commit_id);
13829 if (error)
13830 goto done;
13832 for (i = 0; i < argc; i++) {
13833 if (force_path) {
13834 error = got_object_id_by_path(&id, repo, commit,
13835 argv[i]);
13836 if (error)
13837 break;
13838 } else {
13839 error = got_repo_match_object_id(&id, &label, argv[i],
13840 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13841 repo);
13842 if (error) {
13843 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13844 error->code != GOT_ERR_NOT_REF)
13845 break;
13846 error = got_object_id_by_path(&id, repo,
13847 commit, argv[i]);
13848 if (error)
13849 break;
13853 error = got_object_get_type(&obj_type, repo, id);
13854 if (error)
13855 break;
13857 switch (obj_type) {
13858 case GOT_OBJ_TYPE_BLOB:
13859 error = cat_blob(id, repo, stdout);
13860 break;
13861 case GOT_OBJ_TYPE_TREE:
13862 error = cat_tree(id, repo, stdout);
13863 break;
13864 case GOT_OBJ_TYPE_COMMIT:
13865 error = cat_commit(id, repo, stdout);
13866 break;
13867 case GOT_OBJ_TYPE_TAG:
13868 error = cat_tag(id, repo, stdout);
13869 break;
13870 default:
13871 error = got_error(GOT_ERR_OBJ_TYPE);
13872 break;
13874 if (error)
13875 break;
13876 free(label);
13877 label = NULL;
13878 free(id);
13879 id = NULL;
13881 done:
13882 free(label);
13883 free(id);
13884 free(commit_id);
13885 if (commit)
13886 got_object_commit_close(commit);
13887 if (worktree)
13888 got_worktree_close(worktree);
13889 if (repo) {
13890 const struct got_error *close_err = got_repo_close(repo);
13891 if (error == NULL)
13892 error = close_err;
13894 if (pack_fds) {
13895 const struct got_error *pack_err =
13896 got_repo_pack_fds_close(pack_fds);
13897 if (error == NULL)
13898 error = pack_err;
13901 got_ref_list_free(&refs);
13902 return error;
13905 __dead static void
13906 usage_info(void)
13908 fprintf(stderr, "usage: %s info [path ...]\n",
13909 getprogname());
13910 exit(1);
13913 static const struct got_error *
13914 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13915 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13916 struct got_object_id *commit_id)
13918 const struct got_error *err = NULL;
13919 char *id_str = NULL;
13920 char datebuf[128];
13921 struct tm mytm, *tm;
13922 struct got_pathlist_head *paths = arg;
13923 struct got_pathlist_entry *pe;
13926 * Clear error indication from any of the path arguments which
13927 * would cause this file index entry to be displayed.
13929 TAILQ_FOREACH(pe, paths, entry) {
13930 if (got_path_cmp(path, pe->path, strlen(path),
13931 pe->path_len) == 0 ||
13932 got_path_is_child(path, pe->path, pe->path_len))
13933 pe->data = NULL; /* no error */
13936 printf(GOT_COMMIT_SEP_STR);
13937 if (S_ISLNK(mode))
13938 printf("symlink: %s\n", path);
13939 else if (S_ISREG(mode)) {
13940 printf("file: %s\n", path);
13941 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13942 } else if (S_ISDIR(mode))
13943 printf("directory: %s\n", path);
13944 else
13945 printf("something: %s\n", path);
13947 tm = localtime_r(&mtime, &mytm);
13948 if (tm == NULL)
13949 return NULL;
13950 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13951 return got_error(GOT_ERR_NO_SPACE);
13952 printf("timestamp: %s\n", datebuf);
13954 if (blob_id) {
13955 err = got_object_id_str(&id_str, blob_id);
13956 if (err)
13957 return err;
13958 printf("based on blob: %s\n", id_str);
13959 free(id_str);
13962 if (staged_blob_id) {
13963 err = got_object_id_str(&id_str, staged_blob_id);
13964 if (err)
13965 return err;
13966 printf("based on staged blob: %s\n", id_str);
13967 free(id_str);
13970 if (commit_id) {
13971 err = got_object_id_str(&id_str, commit_id);
13972 if (err)
13973 return err;
13974 printf("based on commit: %s\n", id_str);
13975 free(id_str);
13978 return NULL;
13981 static const struct got_error *
13982 cmd_info(int argc, char *argv[])
13984 const struct got_error *error = NULL;
13985 struct got_worktree *worktree = NULL;
13986 char *cwd = NULL, *id_str = NULL;
13987 struct got_pathlist_head paths;
13988 char *uuidstr = NULL;
13989 int ch, show_files = 0;
13991 TAILQ_INIT(&paths);
13993 #ifndef PROFILE
13994 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13995 NULL) == -1)
13996 err(1, "pledge");
13997 #endif
13999 while ((ch = getopt(argc, argv, "")) != -1) {
14000 switch (ch) {
14001 default:
14002 usage_info();
14003 /* NOTREACHED */
14007 argc -= optind;
14008 argv += optind;
14010 cwd = getcwd(NULL, 0);
14011 if (cwd == NULL) {
14012 error = got_error_from_errno("getcwd");
14013 goto done;
14016 error = got_worktree_open(&worktree, cwd);
14017 if (error) {
14018 if (error->code == GOT_ERR_NOT_WORKTREE)
14019 error = wrap_not_worktree_error(error, "info", cwd);
14020 goto done;
14023 #ifndef PROFILE
14024 /* Remove "wpath cpath proc exec sendfd" promises. */
14025 if (pledge("stdio rpath flock unveil", NULL) == -1)
14026 err(1, "pledge");
14027 #endif
14028 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14029 if (error)
14030 goto done;
14032 if (argc >= 1) {
14033 error = get_worktree_paths_from_argv(&paths, argc, argv,
14034 worktree);
14035 if (error)
14036 goto done;
14037 show_files = 1;
14040 error = got_object_id_str(&id_str,
14041 got_worktree_get_base_commit_id(worktree));
14042 if (error)
14043 goto done;
14045 error = got_worktree_get_uuid(&uuidstr, worktree);
14046 if (error)
14047 goto done;
14049 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14050 printf("work tree base commit: %s\n", id_str);
14051 printf("work tree path prefix: %s\n",
14052 got_worktree_get_path_prefix(worktree));
14053 printf("work tree branch reference: %s\n",
14054 got_worktree_get_head_ref_name(worktree));
14055 printf("work tree UUID: %s\n", uuidstr);
14056 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14058 if (show_files) {
14059 struct got_pathlist_entry *pe;
14060 TAILQ_FOREACH(pe, &paths, entry) {
14061 if (pe->path_len == 0)
14062 continue;
14064 * Assume this path will fail. This will be corrected
14065 * in print_path_info() in case the path does suceeed.
14067 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14069 error = got_worktree_path_info(worktree, &paths,
14070 print_path_info, &paths, check_cancelled, NULL);
14071 if (error)
14072 goto done;
14073 TAILQ_FOREACH(pe, &paths, entry) {
14074 if (pe->data != NULL) {
14075 const struct got_error *perr;
14077 perr = pe->data;
14078 error = got_error_fmt(perr->code, "%s",
14079 pe->path);
14080 break;
14084 done:
14085 if (worktree)
14086 got_worktree_close(worktree);
14087 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14088 free(cwd);
14089 free(id_str);
14090 free(uuidstr);
14091 return error;