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 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 break;
1566 case 'l':
1567 list_refs_only = 1;
1568 break;
1569 case 'm':
1570 mirror_references = 1;
1571 break;
1572 case 'q':
1573 verbosity = -1;
1574 break;
1575 case 'R':
1576 error = got_pathlist_append(&wanted_refs,
1577 optarg, NULL);
1578 if (error)
1579 return error;
1580 break;
1581 case 'v':
1582 if (verbosity < 0)
1583 verbosity = 0;
1584 else if (verbosity < 3)
1585 verbosity++;
1586 break;
1587 default:
1588 usage_clone();
1589 break;
1592 argc -= optind;
1593 argv += optind;
1595 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1596 option_conflict('a', 'b');
1597 if (list_refs_only) {
1598 if (!TAILQ_EMPTY(&wanted_branches))
1599 option_conflict('l', 'b');
1600 if (fetch_all_branches)
1601 option_conflict('l', 'a');
1602 if (mirror_references)
1603 option_conflict('l', 'm');
1604 if (!TAILQ_EMPTY(&wanted_refs))
1605 option_conflict('l', 'R');
1608 uri = argv[0];
1610 if (argc == 1)
1611 dirname = NULL;
1612 else if (argc == 2)
1613 dirname = argv[1];
1614 else
1615 usage_clone();
1617 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1618 &repo_name, uri);
1619 if (error)
1620 goto done;
1622 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1623 host, port ? ":" : "", port ? port : "",
1624 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1625 error = got_error_from_errno("asprintf");
1626 goto done;
1629 if (strcmp(proto, "git") == 0) {
1630 #ifndef PROFILE
1631 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1632 "sendfd dns inet unveil", NULL) == -1)
1633 err(1, "pledge");
1634 #endif
1635 } else if (strcmp(proto, "git+ssh") == 0 ||
1636 strcmp(proto, "ssh") == 0) {
1637 #ifndef PROFILE
1638 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1639 "sendfd unveil", NULL) == -1)
1640 err(1, "pledge");
1641 #endif
1642 } else if (strcmp(proto, "http") == 0 ||
1643 strcmp(proto, "git+http") == 0) {
1644 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1645 goto done;
1646 } else {
1647 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1648 goto done;
1650 if (dirname == NULL) {
1651 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1652 error = got_error_from_errno("asprintf");
1653 goto done;
1655 repo_path = default_destdir;
1656 } else
1657 repo_path = dirname;
1659 if (!list_refs_only) {
1660 error = got_path_mkdir(repo_path);
1661 if (error &&
1662 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1663 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1664 goto done;
1665 if (!got_path_dir_is_empty(repo_path)) {
1666 error = got_error_path(repo_path,
1667 GOT_ERR_DIR_NOT_EMPTY);
1668 goto done;
1672 error = got_dial_apply_unveil(proto);
1673 if (error)
1674 goto done;
1676 error = apply_unveil(repo_path, 0, NULL);
1677 if (error)
1678 goto done;
1680 if (verbosity >= 0)
1681 printf("Connecting to %s\n", git_url);
1683 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1684 server_path, verbosity);
1685 if (error)
1686 goto done;
1688 if (!list_refs_only) {
1689 error = got_repo_init(repo_path, NULL);
1690 if (error)
1691 goto done;
1692 error = got_repo_pack_fds_open(&pack_fds);
1693 if (error != NULL)
1694 goto done;
1695 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1696 if (error)
1697 goto done;
1700 fpa.last_scaled_size[0] = '\0';
1701 fpa.last_p_indexed = -1;
1702 fpa.last_p_resolved = -1;
1703 fpa.verbosity = verbosity;
1704 fpa.create_configs = 1;
1705 fpa.configs_created = 0;
1706 fpa.repo = repo;
1707 fpa.config_info.symrefs = &symrefs;
1708 fpa.config_info.wanted_branches = &wanted_branches;
1709 fpa.config_info.wanted_refs = &wanted_refs;
1710 fpa.config_info.proto = proto;
1711 fpa.config_info.host = host;
1712 fpa.config_info.port = port;
1713 fpa.config_info.remote_repo_path = server_path;
1714 fpa.config_info.git_url = git_url;
1715 fpa.config_info.fetch_all_branches = fetch_all_branches;
1716 fpa.config_info.mirror_references = mirror_references;
1717 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1718 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1719 fetch_all_branches, &wanted_branches, &wanted_refs,
1720 list_refs_only, verbosity, fetchfd, repo, NULL, 0,
1721 fetch_progress, &fpa);
1722 if (error)
1723 goto done;
1725 if (list_refs_only) {
1726 error = list_remote_refs(&symrefs, &refs);
1727 goto done;
1730 if (pack_hash == NULL) {
1731 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1732 "server sent an empty pack file");
1733 goto done;
1735 error = got_object_id_str(&id_str, pack_hash);
1736 if (error)
1737 goto done;
1738 if (verbosity >= 0)
1739 printf("\nFetched %s.pack\n", id_str);
1740 free(id_str);
1742 /* Set up references provided with the pack file. */
1743 TAILQ_FOREACH(pe, &refs, entry) {
1744 const char *refname = pe->path;
1745 struct got_object_id *id = pe->data;
1746 char *remote_refname;
1748 if (is_wanted_ref(&wanted_refs, refname) &&
1749 !mirror_references) {
1750 error = create_wanted_ref(refname, id,
1751 GOT_FETCH_DEFAULT_REMOTE_NAME,
1752 verbosity - 1, repo);
1753 if (error)
1754 goto done;
1755 continue;
1758 error = create_ref(refname, id, verbosity - 1, repo);
1759 if (error)
1760 goto done;
1762 if (mirror_references)
1763 continue;
1765 if (strncmp("refs/heads/", refname, 11) != 0)
1766 continue;
1768 if (asprintf(&remote_refname,
1769 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1770 refname + 11) == -1) {
1771 error = got_error_from_errno("asprintf");
1772 goto done;
1774 error = create_ref(remote_refname, id, verbosity - 1, repo);
1775 free(remote_refname);
1776 if (error)
1777 goto done;
1780 /* Set the HEAD reference if the server provided one. */
1781 TAILQ_FOREACH(pe, &symrefs, entry) {
1782 struct got_reference *target_ref;
1783 const char *refname = pe->path;
1784 const char *target = pe->data;
1785 char *remote_refname = NULL, *remote_target = NULL;
1787 if (strcmp(refname, GOT_REF_HEAD) != 0)
1788 continue;
1790 error = got_ref_open(&target_ref, repo, target, 0);
1791 if (error) {
1792 if (error->code == GOT_ERR_NOT_REF) {
1793 error = NULL;
1794 continue;
1796 goto done;
1799 error = create_symref(refname, target_ref, verbosity, repo);
1800 got_ref_close(target_ref);
1801 if (error)
1802 goto done;
1804 if (mirror_references)
1805 continue;
1807 if (strncmp("refs/heads/", target, 11) != 0)
1808 continue;
1810 if (asprintf(&remote_refname,
1811 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1812 refname) == -1) {
1813 error = got_error_from_errno("asprintf");
1814 goto done;
1816 if (asprintf(&remote_target,
1817 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1818 target + 11) == -1) {
1819 error = got_error_from_errno("asprintf");
1820 free(remote_refname);
1821 goto done;
1823 error = got_ref_open(&target_ref, repo, remote_target, 0);
1824 if (error) {
1825 free(remote_refname);
1826 free(remote_target);
1827 if (error->code == GOT_ERR_NOT_REF) {
1828 error = NULL;
1829 continue;
1831 goto done;
1833 error = create_symref(remote_refname, target_ref,
1834 verbosity - 1, repo);
1835 free(remote_refname);
1836 free(remote_target);
1837 got_ref_close(target_ref);
1838 if (error)
1839 goto done;
1841 if (pe == NULL) {
1843 * We failed to set the HEAD reference. If we asked for
1844 * a set of wanted branches use the first of one of those
1845 * which could be fetched instead.
1847 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1848 const char *target = pe->path;
1849 struct got_reference *target_ref;
1851 error = got_ref_open(&target_ref, repo, target, 0);
1852 if (error) {
1853 if (error->code == GOT_ERR_NOT_REF) {
1854 error = NULL;
1855 continue;
1857 goto done;
1860 error = create_symref(GOT_REF_HEAD, target_ref,
1861 verbosity, repo);
1862 got_ref_close(target_ref);
1863 if (error)
1864 goto done;
1865 break;
1868 if (!fpa.configs_created && pe != NULL) {
1869 error = create_config_files(fpa.config_info.proto,
1870 fpa.config_info.host, fpa.config_info.port,
1871 fpa.config_info.remote_repo_path,
1872 fpa.config_info.git_url,
1873 fpa.config_info.fetch_all_branches,
1874 fpa.config_info.mirror_references,
1875 fpa.config_info.symrefs,
1876 fpa.config_info.wanted_branches,
1877 fpa.config_info.wanted_refs, fpa.repo);
1878 if (error)
1879 goto done;
1883 if (verbosity >= 0)
1884 printf("Created %s repository '%s'\n",
1885 mirror_references ? "mirrored" : "cloned", repo_path);
1886 done:
1887 if (pack_fds) {
1888 const struct got_error *pack_err =
1889 got_repo_pack_fds_close(pack_fds);
1890 if (error == NULL)
1891 error = pack_err;
1893 if (fetchpid > 0) {
1894 if (kill(fetchpid, SIGTERM) == -1)
1895 error = got_error_from_errno("kill");
1896 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1897 error = got_error_from_errno("waitpid");
1899 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1900 error = got_error_from_errno("close");
1901 if (repo) {
1902 const struct got_error *close_err = got_repo_close(repo);
1903 if (error == NULL)
1904 error = close_err;
1906 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1907 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1908 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1909 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1910 free(pack_hash);
1911 free(proto);
1912 free(host);
1913 free(port);
1914 free(server_path);
1915 free(repo_name);
1916 free(default_destdir);
1917 free(git_url);
1918 return error;
1921 static const struct got_error *
1922 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1923 int replace_tags, int verbosity, struct got_repository *repo)
1925 const struct got_error *err = NULL;
1926 char *new_id_str = NULL;
1927 struct got_object_id *old_id = NULL;
1929 err = got_object_id_str(&new_id_str, new_id);
1930 if (err)
1931 goto done;
1933 if (!replace_tags &&
1934 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1935 err = got_ref_resolve(&old_id, repo, ref);
1936 if (err)
1937 goto done;
1938 if (got_object_id_cmp(old_id, new_id) == 0)
1939 goto done;
1940 if (verbosity >= 0) {
1941 printf("Rejecting update of existing tag %s: %s\n",
1942 got_ref_get_name(ref), new_id_str);
1944 goto done;
1947 if (got_ref_is_symbolic(ref)) {
1948 if (verbosity >= 0) {
1949 printf("Replacing reference %s: %s\n",
1950 got_ref_get_name(ref),
1951 got_ref_get_symref_target(ref));
1953 err = got_ref_change_symref_to_ref(ref, new_id);
1954 if (err)
1955 goto done;
1956 err = got_ref_write(ref, repo);
1957 if (err)
1958 goto done;
1959 } else {
1960 err = got_ref_resolve(&old_id, repo, ref);
1961 if (err)
1962 goto done;
1963 if (got_object_id_cmp(old_id, new_id) == 0)
1964 goto done;
1966 err = got_ref_change_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1974 if (verbosity >= 0)
1975 printf("Updated %s: %s\n", got_ref_get_name(ref),
1976 new_id_str);
1977 done:
1978 free(old_id);
1979 free(new_id_str);
1980 return err;
1983 static const struct got_error *
1984 update_symref(const char *refname, struct got_reference *target_ref,
1985 int verbosity, struct got_repository *repo)
1987 const struct got_error *err = NULL, *unlock_err;
1988 struct got_reference *symref;
1989 int symref_is_locked = 0;
1991 err = got_ref_open(&symref, repo, refname, 1);
1992 if (err) {
1993 if (err->code != GOT_ERR_NOT_REF)
1994 return err;
1995 err = got_ref_alloc_symref(&symref, refname, target_ref);
1996 if (err)
1997 goto done;
1999 err = got_ref_write(symref, repo);
2000 if (err)
2001 goto done;
2003 if (verbosity >= 0)
2004 printf("Created reference %s: %s\n",
2005 got_ref_get_name(symref),
2006 got_ref_get_symref_target(symref));
2007 } else {
2008 symref_is_locked = 1;
2010 if (strcmp(got_ref_get_symref_target(symref),
2011 got_ref_get_name(target_ref)) == 0)
2012 goto done;
2014 err = got_ref_change_symref(symref,
2015 got_ref_get_name(target_ref));
2016 if (err)
2017 goto done;
2019 err = got_ref_write(symref, repo);
2020 if (err)
2021 goto done;
2023 if (verbosity >= 0)
2024 printf("Updated %s: %s\n", got_ref_get_name(symref),
2025 got_ref_get_symref_target(symref));
2028 done:
2029 if (symref_is_locked) {
2030 unlock_err = got_ref_unlock(symref);
2031 if (unlock_err && err == NULL)
2032 err = unlock_err;
2034 got_ref_close(symref);
2035 return err;
2038 __dead static void
2039 usage_fetch(void)
2041 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2042 "[-R reference] [-r repository-path] [remote-repository]\n",
2043 getprogname());
2044 exit(1);
2047 static const struct got_error *
2048 delete_missing_ref(struct got_reference *ref,
2049 int verbosity, struct got_repository *repo)
2051 const struct got_error *err = NULL;
2052 struct got_object_id *id = NULL;
2053 char *id_str = NULL;
2055 if (got_ref_is_symbolic(ref)) {
2056 err = got_ref_delete(ref, repo);
2057 if (err)
2058 return err;
2059 if (verbosity >= 0) {
2060 printf("Deleted %s: %s\n",
2061 got_ref_get_name(ref),
2062 got_ref_get_symref_target(ref));
2064 } else {
2065 err = got_ref_resolve(&id, repo, ref);
2066 if (err)
2067 return err;
2068 err = got_object_id_str(&id_str, id);
2069 if (err)
2070 goto done;
2072 err = got_ref_delete(ref, repo);
2073 if (err)
2074 goto done;
2075 if (verbosity >= 0) {
2076 printf("Deleted %s: %s\n",
2077 got_ref_get_name(ref), id_str);
2080 done:
2081 free(id);
2082 free(id_str);
2083 return err;
2086 static const struct got_error *
2087 delete_missing_refs(struct got_pathlist_head *their_refs,
2088 struct got_pathlist_head *their_symrefs,
2089 const struct got_remote_repo *remote,
2090 int verbosity, struct got_repository *repo)
2092 const struct got_error *err = NULL, *unlock_err;
2093 struct got_reflist_head my_refs;
2094 struct got_reflist_entry *re;
2095 struct got_pathlist_entry *pe;
2096 char *remote_namespace = NULL;
2097 char *local_refname = NULL;
2099 TAILQ_INIT(&my_refs);
2101 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2102 == -1)
2103 return got_error_from_errno("asprintf");
2105 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2106 if (err)
2107 goto done;
2109 TAILQ_FOREACH(re, &my_refs, entry) {
2110 const char *refname = got_ref_get_name(re->ref);
2111 const char *their_refname;
2113 if (remote->mirror_references) {
2114 their_refname = refname;
2115 } else {
2116 if (strncmp(refname, remote_namespace,
2117 strlen(remote_namespace)) == 0) {
2118 if (strcmp(refname + strlen(remote_namespace),
2119 GOT_REF_HEAD) == 0)
2120 continue;
2121 if (asprintf(&local_refname, "refs/heads/%s",
2122 refname + strlen(remote_namespace)) == -1) {
2123 err = got_error_from_errno("asprintf");
2124 goto done;
2126 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2127 continue;
2129 their_refname = local_refname;
2132 TAILQ_FOREACH(pe, their_refs, entry) {
2133 if (strcmp(their_refname, pe->path) == 0)
2134 break;
2136 if (pe != NULL)
2137 continue;
2139 TAILQ_FOREACH(pe, their_symrefs, entry) {
2140 if (strcmp(their_refname, pe->path) == 0)
2141 break;
2143 if (pe != NULL)
2144 continue;
2146 err = delete_missing_ref(re->ref, verbosity, repo);
2147 if (err)
2148 break;
2150 if (local_refname) {
2151 struct got_reference *ref;
2152 err = got_ref_open(&ref, repo, local_refname, 1);
2153 if (err) {
2154 if (err->code != GOT_ERR_NOT_REF)
2155 break;
2156 free(local_refname);
2157 local_refname = NULL;
2158 continue;
2160 err = delete_missing_ref(ref, verbosity, repo);
2161 if (err)
2162 break;
2163 unlock_err = got_ref_unlock(ref);
2164 got_ref_close(ref);
2165 if (unlock_err && err == NULL) {
2166 err = unlock_err;
2167 break;
2170 free(local_refname);
2171 local_refname = NULL;
2174 done:
2175 got_ref_list_free(&my_refs);
2176 free(remote_namespace);
2177 free(local_refname);
2178 return err;
2181 static const struct got_error *
2182 update_wanted_ref(const char *refname, struct got_object_id *id,
2183 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2185 const struct got_error *err, *unlock_err;
2186 char *remote_refname;
2187 struct got_reference *ref;
2189 if (strncmp("refs/", refname, 5) == 0)
2190 refname += 5;
2192 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2193 remote_repo_name, refname) == -1)
2194 return got_error_from_errno("asprintf");
2196 err = got_ref_open(&ref, repo, remote_refname, 1);
2197 if (err) {
2198 if (err->code != GOT_ERR_NOT_REF)
2199 goto done;
2200 err = create_ref(remote_refname, id, verbosity, repo);
2201 } else {
2202 err = update_ref(ref, id, 0, verbosity, repo);
2203 unlock_err = got_ref_unlock(ref);
2204 if (unlock_err && err == NULL)
2205 err = unlock_err;
2206 got_ref_close(ref);
2208 done:
2209 free(remote_refname);
2210 return err;
2213 static const struct got_error *
2214 delete_ref(struct got_repository *repo, struct got_reference *ref)
2216 const struct got_error *err = NULL;
2217 struct got_object_id *id = NULL;
2218 char *id_str = NULL;
2219 const char *target;
2221 if (got_ref_is_symbolic(ref)) {
2222 target = got_ref_get_symref_target(ref);
2223 } else {
2224 err = got_ref_resolve(&id, repo, ref);
2225 if (err)
2226 goto done;
2227 err = got_object_id_str(&id_str, id);
2228 if (err)
2229 goto done;
2230 target = id_str;
2233 err = got_ref_delete(ref, repo);
2234 if (err)
2235 goto done;
2237 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2238 done:
2239 free(id);
2240 free(id_str);
2241 return err;
2244 static const struct got_error *
2245 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2247 const struct got_error *err = NULL;
2248 struct got_reflist_head refs;
2249 struct got_reflist_entry *re;
2250 char *prefix;
2252 TAILQ_INIT(&refs);
2254 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2255 err = got_error_from_errno("asprintf");
2256 goto done;
2258 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2259 if (err)
2260 goto done;
2262 TAILQ_FOREACH(re, &refs, entry)
2263 delete_ref(repo, re->ref);
2264 done:
2265 got_ref_list_free(&refs);
2266 return err;
2269 static const struct got_error *
2270 cmd_fetch(int argc, char *argv[])
2272 const struct got_error *error = NULL, *unlock_err;
2273 char *cwd = NULL, *repo_path = NULL;
2274 const char *remote_name;
2275 char *proto = NULL, *host = NULL, *port = NULL;
2276 char *repo_name = NULL, *server_path = NULL;
2277 const struct got_remote_repo *remotes, *remote = NULL;
2278 int nremotes;
2279 char *id_str = NULL;
2280 struct got_repository *repo = NULL;
2281 struct got_worktree *worktree = NULL;
2282 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2283 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2284 struct got_pathlist_entry *pe;
2285 struct got_object_id *pack_hash = NULL;
2286 int i, ch, fetchfd = -1, fetchstatus;
2287 pid_t fetchpid = -1;
2288 struct got_fetch_progress_arg fpa;
2289 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2290 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2291 int *pack_fds = NULL, have_bflag = 0;
2292 const char *worktree_branch = NULL;
2294 TAILQ_INIT(&refs);
2295 TAILQ_INIT(&symrefs);
2296 TAILQ_INIT(&wanted_branches);
2297 TAILQ_INIT(&wanted_refs);
2299 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2300 switch (ch) {
2301 case 'a':
2302 fetch_all_branches = 1;
2303 break;
2304 case 'b':
2305 error = got_pathlist_append(&wanted_branches,
2306 optarg, NULL);
2307 if (error)
2308 return error;
2309 have_bflag = 1;
2310 break;
2311 case 'd':
2312 delete_refs = 1;
2313 break;
2314 case 'l':
2315 list_refs_only = 1;
2316 break;
2317 case 'q':
2318 verbosity = -1;
2319 break;
2320 case 'R':
2321 error = got_pathlist_append(&wanted_refs,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 break;
2326 case 'r':
2327 repo_path = realpath(optarg, NULL);
2328 if (repo_path == NULL)
2329 return got_error_from_errno2("realpath",
2330 optarg);
2331 got_path_strip_trailing_slashes(repo_path);
2332 break;
2333 case 't':
2334 replace_tags = 1;
2335 break;
2336 case 'v':
2337 if (verbosity < 0)
2338 verbosity = 0;
2339 else if (verbosity < 3)
2340 verbosity++;
2341 break;
2342 case 'X':
2343 delete_remote = 1;
2344 break;
2345 default:
2346 usage_fetch();
2347 break;
2350 argc -= optind;
2351 argv += optind;
2353 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2354 option_conflict('a', 'b');
2355 if (list_refs_only) {
2356 if (!TAILQ_EMPTY(&wanted_branches))
2357 option_conflict('l', 'b');
2358 if (fetch_all_branches)
2359 option_conflict('l', 'a');
2360 if (delete_refs)
2361 option_conflict('l', 'd');
2362 if (delete_remote)
2363 option_conflict('l', 'X');
2365 if (delete_remote) {
2366 if (fetch_all_branches)
2367 option_conflict('X', 'a');
2368 if (!TAILQ_EMPTY(&wanted_branches))
2369 option_conflict('X', 'b');
2370 if (delete_refs)
2371 option_conflict('X', 'd');
2372 if (replace_tags)
2373 option_conflict('X', 't');
2374 if (!TAILQ_EMPTY(&wanted_refs))
2375 option_conflict('X', 'R');
2378 if (argc == 0) {
2379 if (delete_remote)
2380 errx(1, "-X option requires a remote name");
2381 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2382 } else if (argc == 1)
2383 remote_name = argv[0];
2384 else
2385 usage_fetch();
2387 cwd = getcwd(NULL, 0);
2388 if (cwd == NULL) {
2389 error = got_error_from_errno("getcwd");
2390 goto done;
2393 error = got_repo_pack_fds_open(&pack_fds);
2394 if (error != NULL)
2395 goto done;
2397 if (repo_path == NULL) {
2398 error = got_worktree_open(&worktree, cwd);
2399 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2400 goto done;
2401 else
2402 error = NULL;
2403 if (worktree) {
2404 repo_path =
2405 strdup(got_worktree_get_repo_path(worktree));
2406 if (repo_path == NULL)
2407 error = got_error_from_errno("strdup");
2408 if (error)
2409 goto done;
2410 } else {
2411 repo_path = strdup(cwd);
2412 if (repo_path == NULL) {
2413 error = got_error_from_errno("strdup");
2414 goto done;
2419 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2420 if (error)
2421 goto done;
2423 if (delete_remote) {
2424 error = delete_refs_for_remote(repo, remote_name);
2425 goto done; /* nothing else to do */
2428 if (worktree) {
2429 worktree_conf = got_worktree_get_gotconfig(worktree);
2430 if (worktree_conf) {
2431 got_gotconfig_get_remotes(&nremotes, &remotes,
2432 worktree_conf);
2433 for (i = 0; i < nremotes; i++) {
2434 if (strcmp(remotes[i].name, remote_name) == 0) {
2435 remote = &remotes[i];
2436 break;
2441 if (remote == NULL) {
2442 repo_conf = got_repo_get_gotconfig(repo);
2443 if (repo_conf) {
2444 got_gotconfig_get_remotes(&nremotes, &remotes,
2445 repo_conf);
2446 for (i = 0; i < nremotes; i++) {
2447 if (strcmp(remotes[i].name, remote_name) == 0) {
2448 remote = &remotes[i];
2449 break;
2454 if (remote == NULL) {
2455 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2456 for (i = 0; i < nremotes; i++) {
2457 if (strcmp(remotes[i].name, remote_name) == 0) {
2458 remote = &remotes[i];
2459 break;
2463 if (remote == NULL) {
2464 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2465 goto done;
2468 if (TAILQ_EMPTY(&wanted_branches)) {
2469 if (!fetch_all_branches)
2470 fetch_all_branches = remote->fetch_all_branches;
2471 for (i = 0; i < remote->nfetch_branches; i++) {
2472 error = got_pathlist_append(&wanted_branches,
2473 remote->fetch_branches[i], NULL);
2474 if (error)
2475 goto done;
2478 if (TAILQ_EMPTY(&wanted_refs)) {
2479 for (i = 0; i < remote->nfetch_refs; i++) {
2480 error = got_pathlist_append(&wanted_refs,
2481 remote->fetch_refs[i], NULL);
2482 if (error)
2483 goto done;
2487 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2488 &repo_name, remote->fetch_url);
2489 if (error)
2490 goto done;
2492 if (strcmp(proto, "git") == 0) {
2493 #ifndef PROFILE
2494 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2495 "sendfd dns inet unveil", NULL) == -1)
2496 err(1, "pledge");
2497 #endif
2498 } else if (strcmp(proto, "git+ssh") == 0 ||
2499 strcmp(proto, "ssh") == 0) {
2500 #ifndef PROFILE
2501 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2502 "sendfd unveil", NULL) == -1)
2503 err(1, "pledge");
2504 #endif
2505 } else if (strcmp(proto, "http") == 0 ||
2506 strcmp(proto, "git+http") == 0) {
2507 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2508 goto done;
2509 } else {
2510 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2511 goto done;
2514 error = got_dial_apply_unveil(proto);
2515 if (error)
2516 goto done;
2518 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2519 if (error)
2520 goto done;
2522 if (verbosity >= 0) {
2523 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2524 remote->name, proto, host,
2525 port ? ":" : "", port ? port : "",
2526 *server_path == '/' ? "" : "/", server_path);
2529 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2530 server_path, verbosity);
2531 if (error)
2532 goto done;
2534 if (worktree && !have_bflag) {
2535 const char *refname;
2537 refname = got_worktree_get_head_ref_name(worktree);
2538 if (strncmp(refname, "refs/heads/", 11) == 0)
2539 worktree_branch = refname;
2542 fpa.last_scaled_size[0] = '\0';
2543 fpa.last_p_indexed = -1;
2544 fpa.last_p_resolved = -1;
2545 fpa.verbosity = verbosity;
2546 fpa.repo = repo;
2547 fpa.create_configs = 0;
2548 fpa.configs_created = 0;
2549 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2551 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2552 remote->mirror_references, fetch_all_branches, &wanted_branches,
2553 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2554 worktree_branch, have_bflag, fetch_progress, &fpa);
2555 if (error)
2556 goto done;
2558 if (list_refs_only) {
2559 error = list_remote_refs(&symrefs, &refs);
2560 goto done;
2563 if (pack_hash == NULL) {
2564 if (verbosity >= 0)
2565 printf("Already up-to-date\n");
2566 } else if (verbosity >= 0) {
2567 error = got_object_id_str(&id_str, pack_hash);
2568 if (error)
2569 goto done;
2570 printf("\nFetched %s.pack\n", id_str);
2571 free(id_str);
2572 id_str = NULL;
2575 /* Update references provided with the pack file. */
2576 TAILQ_FOREACH(pe, &refs, entry) {
2577 const char *refname = pe->path;
2578 struct got_object_id *id = pe->data;
2579 struct got_reference *ref;
2580 char *remote_refname;
2582 if (is_wanted_ref(&wanted_refs, refname) &&
2583 !remote->mirror_references) {
2584 error = update_wanted_ref(refname, id,
2585 remote->name, verbosity, repo);
2586 if (error)
2587 goto done;
2588 continue;
2591 if (remote->mirror_references ||
2592 strncmp("refs/tags/", refname, 10) == 0) {
2593 error = got_ref_open(&ref, repo, refname, 1);
2594 if (error) {
2595 if (error->code != GOT_ERR_NOT_REF)
2596 goto done;
2597 error = create_ref(refname, id, verbosity,
2598 repo);
2599 if (error)
2600 goto done;
2601 } else {
2602 error = update_ref(ref, id, replace_tags,
2603 verbosity, repo);
2604 unlock_err = got_ref_unlock(ref);
2605 if (unlock_err && error == NULL)
2606 error = unlock_err;
2607 got_ref_close(ref);
2608 if (error)
2609 goto done;
2611 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2612 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2613 remote_name, refname + 11) == -1) {
2614 error = got_error_from_errno("asprintf");
2615 goto done;
2618 error = got_ref_open(&ref, repo, remote_refname, 1);
2619 if (error) {
2620 if (error->code != GOT_ERR_NOT_REF)
2621 goto done;
2622 error = create_ref(remote_refname, id,
2623 verbosity, repo);
2624 if (error)
2625 goto done;
2626 } else {
2627 error = update_ref(ref, id, replace_tags,
2628 verbosity, repo);
2629 unlock_err = got_ref_unlock(ref);
2630 if (unlock_err && error == NULL)
2631 error = unlock_err;
2632 got_ref_close(ref);
2633 if (error)
2634 goto done;
2637 /* Also create a local branch if none exists yet. */
2638 error = got_ref_open(&ref, repo, refname, 1);
2639 if (error) {
2640 if (error->code != GOT_ERR_NOT_REF)
2641 goto done;
2642 error = create_ref(refname, id, verbosity,
2643 repo);
2644 if (error)
2645 goto done;
2646 } else {
2647 unlock_err = got_ref_unlock(ref);
2648 if (unlock_err && error == NULL)
2649 error = unlock_err;
2650 got_ref_close(ref);
2654 if (delete_refs) {
2655 error = delete_missing_refs(&refs, &symrefs, remote,
2656 verbosity, repo);
2657 if (error)
2658 goto done;
2661 if (!remote->mirror_references) {
2662 /* Update remote HEAD reference if the server provided one. */
2663 TAILQ_FOREACH(pe, &symrefs, entry) {
2664 struct got_reference *target_ref;
2665 const char *refname = pe->path;
2666 const char *target = pe->data;
2667 char *remote_refname = NULL, *remote_target = NULL;
2669 if (strcmp(refname, GOT_REF_HEAD) != 0)
2670 continue;
2672 if (strncmp("refs/heads/", target, 11) != 0)
2673 continue;
2675 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2676 remote->name, refname) == -1) {
2677 error = got_error_from_errno("asprintf");
2678 goto done;
2680 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2681 remote->name, target + 11) == -1) {
2682 error = got_error_from_errno("asprintf");
2683 free(remote_refname);
2684 goto done;
2687 error = got_ref_open(&target_ref, repo, remote_target,
2688 0);
2689 if (error) {
2690 free(remote_refname);
2691 free(remote_target);
2692 if (error->code == GOT_ERR_NOT_REF) {
2693 error = NULL;
2694 continue;
2696 goto done;
2698 error = update_symref(remote_refname, target_ref,
2699 verbosity, repo);
2700 free(remote_refname);
2701 free(remote_target);
2702 got_ref_close(target_ref);
2703 if (error)
2704 goto done;
2707 done:
2708 if (fetchpid > 0) {
2709 if (kill(fetchpid, SIGTERM) == -1)
2710 error = got_error_from_errno("kill");
2711 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2712 error = got_error_from_errno("waitpid");
2714 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2715 error = got_error_from_errno("close");
2716 if (repo) {
2717 const struct got_error *close_err = got_repo_close(repo);
2718 if (error == NULL)
2719 error = close_err;
2721 if (worktree)
2722 got_worktree_close(worktree);
2723 if (pack_fds) {
2724 const struct got_error *pack_err =
2725 got_repo_pack_fds_close(pack_fds);
2726 if (error == NULL)
2727 error = pack_err;
2729 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2730 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2731 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2732 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2733 free(id_str);
2734 free(cwd);
2735 free(repo_path);
2736 free(pack_hash);
2737 free(proto);
2738 free(host);
2739 free(port);
2740 free(server_path);
2741 free(repo_name);
2742 return error;
2746 __dead static void
2747 usage_checkout(void)
2749 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2750 "[-p path-prefix] repository-path [work-tree-path]\n",
2751 getprogname());
2752 exit(1);
2755 static void
2756 show_worktree_base_ref_warning(void)
2758 fprintf(stderr, "%s: warning: could not create a reference "
2759 "to the work tree's base commit; the commit could be "
2760 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2761 "repository writable and running 'got update' will prevent this\n",
2762 getprogname());
2765 struct got_checkout_progress_arg {
2766 const char *worktree_path;
2767 int had_base_commit_ref_error;
2768 int verbosity;
2771 static const struct got_error *
2772 checkout_progress(void *arg, unsigned char status, const char *path)
2774 struct got_checkout_progress_arg *a = arg;
2776 /* Base commit bump happens silently. */
2777 if (status == GOT_STATUS_BUMP_BASE)
2778 return NULL;
2780 if (status == GOT_STATUS_BASE_REF_ERR) {
2781 a->had_base_commit_ref_error = 1;
2782 return NULL;
2785 while (path[0] == '/')
2786 path++;
2788 if (a->verbosity >= 0)
2789 printf("%c %s/%s\n", status, a->worktree_path, path);
2791 return NULL;
2794 static const struct got_error *
2795 check_cancelled(void *arg)
2797 if (sigint_received || sigpipe_received)
2798 return got_error(GOT_ERR_CANCELLED);
2799 return NULL;
2802 static const struct got_error *
2803 check_linear_ancestry(struct got_object_id *commit_id,
2804 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2805 struct got_repository *repo)
2807 const struct got_error *err = NULL;
2808 struct got_object_id *yca_id;
2810 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2811 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2812 if (err)
2813 return err;
2815 if (yca_id == NULL)
2816 return got_error(GOT_ERR_ANCESTRY);
2819 * Require a straight line of history between the target commit
2820 * and the work tree's base commit.
2822 * Non-linear situations such as this require a rebase:
2824 * (commit) D F (base_commit)
2825 * \ /
2826 * C E
2827 * \ /
2828 * B (yca)
2829 * |
2830 * A
2832 * 'got update' only handles linear cases:
2833 * Update forwards in time: A (base/yca) - B - C - D (commit)
2834 * Update backwards in time: D (base) - C - B - A (commit/yca)
2836 if (allow_forwards_in_time_only) {
2837 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2838 return got_error(GOT_ERR_ANCESTRY);
2839 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2840 got_object_id_cmp(base_commit_id, yca_id) != 0)
2841 return got_error(GOT_ERR_ANCESTRY);
2843 free(yca_id);
2844 return NULL;
2847 static const struct got_error *
2848 check_same_branch(struct got_object_id *commit_id,
2849 struct got_reference *head_ref, struct got_object_id *yca_id,
2850 struct got_repository *repo)
2852 const struct got_error *err = NULL;
2853 struct got_commit_graph *graph = NULL;
2854 struct got_object_id *head_commit_id = NULL;
2855 int is_same_branch = 0;
2857 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2858 if (err)
2859 goto done;
2861 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2862 is_same_branch = 1;
2863 goto done;
2865 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2866 is_same_branch = 1;
2867 goto done;
2870 err = got_commit_graph_open(&graph, "/", 1);
2871 if (err)
2872 goto done;
2874 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2875 check_cancelled, NULL);
2876 if (err)
2877 goto done;
2879 for (;;) {
2880 struct got_object_id id;
2882 err = got_commit_graph_iter_next(&id, graph, repo,
2883 check_cancelled, NULL);
2884 if (err) {
2885 if (err->code == GOT_ERR_ITER_COMPLETED)
2886 err = NULL;
2887 break;
2890 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2891 break;
2892 if (got_object_id_cmp(&id, commit_id) == 0) {
2893 is_same_branch = 1;
2894 break;
2897 done:
2898 if (graph)
2899 got_commit_graph_close(graph);
2900 free(head_commit_id);
2901 if (!err && !is_same_branch)
2902 err = got_error(GOT_ERR_ANCESTRY);
2903 return err;
2906 static const struct got_error *
2907 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2909 static char msg[512];
2910 const char *branch_name;
2912 if (got_ref_is_symbolic(ref))
2913 branch_name = got_ref_get_symref_target(ref);
2914 else
2915 branch_name = got_ref_get_name(ref);
2917 if (strncmp("refs/heads/", branch_name, 11) == 0)
2918 branch_name += 11;
2920 snprintf(msg, sizeof(msg),
2921 "target commit is not contained in branch '%s'; "
2922 "the branch to use must be specified with -b; "
2923 "if necessary a new branch can be created for "
2924 "this commit with 'got branch -c %s BRANCH_NAME'",
2925 branch_name, commit_id_str);
2927 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2930 static const struct got_error *
2931 cmd_checkout(int argc, char *argv[])
2933 const struct got_error *error = NULL;
2934 struct got_repository *repo = NULL;
2935 struct got_reference *head_ref = NULL, *ref = NULL;
2936 struct got_worktree *worktree = NULL;
2937 char *repo_path = NULL;
2938 char *worktree_path = NULL;
2939 const char *path_prefix = "";
2940 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2941 char *commit_id_str = NULL;
2942 struct got_object_id *commit_id = NULL;
2943 char *cwd = NULL;
2944 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2945 struct got_pathlist_head paths;
2946 struct got_checkout_progress_arg cpa;
2947 int *pack_fds = NULL;
2949 TAILQ_INIT(&paths);
2951 #ifndef PROFILE
2952 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2953 "unveil", NULL) == -1)
2954 err(1, "pledge");
2955 #endif
2957 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2958 switch (ch) {
2959 case 'b':
2960 branch_name = optarg;
2961 break;
2962 case 'c':
2963 commit_id_str = strdup(optarg);
2964 if (commit_id_str == NULL)
2965 return got_error_from_errno("strdup");
2966 break;
2967 case 'E':
2968 allow_nonempty = 1;
2969 break;
2970 case 'p':
2971 path_prefix = optarg;
2972 break;
2973 case 'q':
2974 verbosity = -1;
2975 break;
2976 default:
2977 usage_checkout();
2978 /* NOTREACHED */
2982 argc -= optind;
2983 argv += optind;
2985 if (argc == 1) {
2986 char *base, *dotgit;
2987 const char *path;
2988 repo_path = realpath(argv[0], NULL);
2989 if (repo_path == NULL)
2990 return got_error_from_errno2("realpath", argv[0]);
2991 cwd = getcwd(NULL, 0);
2992 if (cwd == NULL) {
2993 error = got_error_from_errno("getcwd");
2994 goto done;
2996 if (path_prefix[0])
2997 path = path_prefix;
2998 else
2999 path = repo_path;
3000 error = got_path_basename(&base, path);
3001 if (error)
3002 goto done;
3003 dotgit = strstr(base, ".git");
3004 if (dotgit)
3005 *dotgit = '\0';
3006 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3007 error = got_error_from_errno("asprintf");
3008 free(base);
3009 goto done;
3011 free(base);
3012 } else if (argc == 2) {
3013 repo_path = realpath(argv[0], NULL);
3014 if (repo_path == NULL) {
3015 error = got_error_from_errno2("realpath", argv[0]);
3016 goto done;
3018 worktree_path = realpath(argv[1], NULL);
3019 if (worktree_path == NULL) {
3020 if (errno != ENOENT) {
3021 error = got_error_from_errno2("realpath",
3022 argv[1]);
3023 goto done;
3025 worktree_path = strdup(argv[1]);
3026 if (worktree_path == NULL) {
3027 error = got_error_from_errno("strdup");
3028 goto done;
3031 } else
3032 usage_checkout();
3034 got_path_strip_trailing_slashes(repo_path);
3035 got_path_strip_trailing_slashes(worktree_path);
3037 error = got_repo_pack_fds_open(&pack_fds);
3038 if (error != NULL)
3039 goto done;
3041 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3042 if (error != NULL)
3043 goto done;
3045 /* Pre-create work tree path for unveil(2) */
3046 error = got_path_mkdir(worktree_path);
3047 if (error) {
3048 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3049 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3050 goto done;
3051 if (!allow_nonempty &&
3052 !got_path_dir_is_empty(worktree_path)) {
3053 error = got_error_path(worktree_path,
3054 GOT_ERR_DIR_NOT_EMPTY);
3055 goto done;
3059 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3060 if (error)
3061 goto done;
3063 error = got_ref_open(&head_ref, repo, branch_name, 0);
3064 if (error != NULL)
3065 goto done;
3067 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3068 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3069 goto done;
3071 error = got_worktree_open(&worktree, worktree_path);
3072 if (error != NULL)
3073 goto done;
3075 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3076 path_prefix);
3077 if (error != NULL)
3078 goto done;
3079 if (!same_path_prefix) {
3080 error = got_error(GOT_ERR_PATH_PREFIX);
3081 goto done;
3084 if (commit_id_str) {
3085 struct got_reflist_head refs;
3086 TAILQ_INIT(&refs);
3087 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3088 NULL);
3089 if (error)
3090 goto done;
3091 error = got_repo_match_object_id(&commit_id, NULL,
3092 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3093 got_ref_list_free(&refs);
3094 if (error)
3095 goto done;
3096 error = check_linear_ancestry(commit_id,
3097 got_worktree_get_base_commit_id(worktree), 0, repo);
3098 if (error != NULL) {
3099 if (error->code == GOT_ERR_ANCESTRY) {
3100 error = checkout_ancestry_error(
3101 head_ref, commit_id_str);
3103 goto done;
3105 error = check_same_branch(commit_id, head_ref, NULL, repo);
3106 if (error) {
3107 if (error->code == GOT_ERR_ANCESTRY) {
3108 error = checkout_ancestry_error(
3109 head_ref, commit_id_str);
3111 goto done;
3113 error = got_worktree_set_base_commit_id(worktree, repo,
3114 commit_id);
3115 if (error)
3116 goto done;
3117 /* Expand potentially abbreviated commit ID string. */
3118 free(commit_id_str);
3119 error = got_object_id_str(&commit_id_str, commit_id);
3120 if (error)
3121 goto done;
3122 } else {
3123 commit_id = got_object_id_dup(
3124 got_worktree_get_base_commit_id(worktree));
3125 if (commit_id == NULL) {
3126 error = got_error_from_errno("got_object_id_dup");
3127 goto done;
3129 error = got_object_id_str(&commit_id_str, commit_id);
3130 if (error)
3131 goto done;
3134 error = got_pathlist_append(&paths, "", NULL);
3135 if (error)
3136 goto done;
3137 cpa.worktree_path = worktree_path;
3138 cpa.had_base_commit_ref_error = 0;
3139 cpa.verbosity = verbosity;
3140 error = got_worktree_checkout_files(worktree, &paths, repo,
3141 checkout_progress, &cpa, check_cancelled, NULL);
3142 if (error != NULL)
3143 goto done;
3145 if (got_ref_is_symbolic(head_ref)) {
3146 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3147 if (error)
3148 goto done;
3149 refname = got_ref_get_name(ref);
3150 } else
3151 refname = got_ref_get_name(head_ref);
3152 printf("Checked out %s: %s\n", refname, commit_id_str);
3153 printf("Now shut up and hack\n");
3154 if (cpa.had_base_commit_ref_error)
3155 show_worktree_base_ref_warning();
3156 done:
3157 if (pack_fds) {
3158 const struct got_error *pack_err =
3159 got_repo_pack_fds_close(pack_fds);
3160 if (error == NULL)
3161 error = pack_err;
3163 if (head_ref)
3164 got_ref_close(head_ref);
3165 if (ref)
3166 got_ref_close(ref);
3167 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3168 free(commit_id_str);
3169 free(commit_id);
3170 free(repo_path);
3171 free(worktree_path);
3172 free(cwd);
3173 return error;
3176 struct got_update_progress_arg {
3177 int did_something;
3178 int conflicts;
3179 int obstructed;
3180 int not_updated;
3181 int missing;
3182 int not_deleted;
3183 int unversioned;
3184 int verbosity;
3187 static void
3188 print_update_progress_stats(struct got_update_progress_arg *upa)
3190 if (!upa->did_something)
3191 return;
3193 if (upa->conflicts > 0)
3194 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3195 if (upa->obstructed > 0)
3196 printf("File paths obstructed by a non-regular file: %d\n",
3197 upa->obstructed);
3198 if (upa->not_updated > 0)
3199 printf("Files not updated because of existing merge "
3200 "conflicts: %d\n", upa->not_updated);
3204 * The meaning of some status codes differs between merge-style operations and
3205 * update operations. For example, the ! status code means "file was missing"
3206 * if changes were merged into the work tree, and "missing file was restored"
3207 * if the work tree was updated. This function should be used by any operation
3208 * which merges changes into the work tree without updating the work tree.
3210 static void
3211 print_merge_progress_stats(struct got_update_progress_arg *upa)
3213 if (!upa->did_something)
3214 return;
3216 if (upa->conflicts > 0)
3217 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3218 if (upa->obstructed > 0)
3219 printf("File paths obstructed by a non-regular file: %d\n",
3220 upa->obstructed);
3221 if (upa->missing > 0)
3222 printf("Files which had incoming changes but could not be "
3223 "found in the work tree: %d\n", upa->missing);
3224 if (upa->not_deleted > 0)
3225 printf("Files not deleted due to differences in deleted "
3226 "content: %d\n", upa->not_deleted);
3227 if (upa->unversioned > 0)
3228 printf("Files not merged because an unversioned file was "
3229 "found in the work tree: %d\n", upa->unversioned);
3232 __dead static void
3233 usage_update(void)
3235 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3236 "[path ...]\n", getprogname());
3237 exit(1);
3240 static const struct got_error *
3241 update_progress(void *arg, unsigned char status, const char *path)
3243 struct got_update_progress_arg *upa = arg;
3245 if (status == GOT_STATUS_EXISTS ||
3246 status == GOT_STATUS_BASE_REF_ERR)
3247 return NULL;
3249 upa->did_something = 1;
3251 /* Base commit bump happens silently. */
3252 if (status == GOT_STATUS_BUMP_BASE)
3253 return NULL;
3255 if (status == GOT_STATUS_CONFLICT)
3256 upa->conflicts++;
3257 if (status == GOT_STATUS_OBSTRUCTED)
3258 upa->obstructed++;
3259 if (status == GOT_STATUS_CANNOT_UPDATE)
3260 upa->not_updated++;
3261 if (status == GOT_STATUS_MISSING)
3262 upa->missing++;
3263 if (status == GOT_STATUS_CANNOT_DELETE)
3264 upa->not_deleted++;
3265 if (status == GOT_STATUS_UNVERSIONED)
3266 upa->unversioned++;
3268 while (path[0] == '/')
3269 path++;
3270 if (upa->verbosity >= 0)
3271 printf("%c %s\n", status, path);
3273 return NULL;
3276 static const struct got_error *
3277 switch_head_ref(struct got_reference *head_ref,
3278 struct got_object_id *commit_id, struct got_worktree *worktree,
3279 struct got_repository *repo)
3281 const struct got_error *err = NULL;
3282 char *base_id_str;
3283 int ref_has_moved = 0;
3285 /* Trivial case: switching between two different references. */
3286 if (strcmp(got_ref_get_name(head_ref),
3287 got_worktree_get_head_ref_name(worktree)) != 0) {
3288 printf("Switching work tree from %s to %s\n",
3289 got_worktree_get_head_ref_name(worktree),
3290 got_ref_get_name(head_ref));
3291 return got_worktree_set_head_ref(worktree, head_ref);
3294 err = check_linear_ancestry(commit_id,
3295 got_worktree_get_base_commit_id(worktree), 0, repo);
3296 if (err) {
3297 if (err->code != GOT_ERR_ANCESTRY)
3298 return err;
3299 ref_has_moved = 1;
3301 if (!ref_has_moved)
3302 return NULL;
3304 /* Switching to a rebased branch with the same reference name. */
3305 err = got_object_id_str(&base_id_str,
3306 got_worktree_get_base_commit_id(worktree));
3307 if (err)
3308 return err;
3309 printf("Reference %s now points at a different branch\n",
3310 got_worktree_get_head_ref_name(worktree));
3311 printf("Switching work tree from %s to %s\n", base_id_str,
3312 got_worktree_get_head_ref_name(worktree));
3313 return NULL;
3316 static const struct got_error *
3317 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3319 const struct got_error *err;
3320 int in_progress;
3322 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3323 if (err)
3324 return err;
3325 if (in_progress)
3326 return got_error(GOT_ERR_REBASING);
3328 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3329 if (err)
3330 return err;
3331 if (in_progress)
3332 return got_error(GOT_ERR_HISTEDIT_BUSY);
3334 return NULL;
3337 static const struct got_error *
3338 check_merge_in_progress(struct got_worktree *worktree,
3339 struct got_repository *repo)
3341 const struct got_error *err;
3342 int in_progress;
3344 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3345 if (err)
3346 return err;
3347 if (in_progress)
3348 return got_error(GOT_ERR_MERGE_BUSY);
3350 return NULL;
3353 static const struct got_error *
3354 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3355 char *argv[], struct got_worktree *worktree)
3357 const struct got_error *err = NULL;
3358 char *path;
3359 struct got_pathlist_entry *new;
3360 int i;
3362 if (argc == 0) {
3363 path = strdup("");
3364 if (path == NULL)
3365 return got_error_from_errno("strdup");
3366 return got_pathlist_append(paths, path, NULL);
3369 for (i = 0; i < argc; i++) {
3370 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3371 if (err)
3372 break;
3373 err = got_pathlist_insert(&new, paths, path, NULL);
3374 if (err || new == NULL /* duplicate */) {
3375 free(path);
3376 if (err)
3377 break;
3381 return err;
3384 static const struct got_error *
3385 wrap_not_worktree_error(const struct got_error *orig_err,
3386 const char *cmdname, const char *path)
3388 const struct got_error *err;
3389 struct got_repository *repo;
3390 static char msg[512];
3391 int *pack_fds = NULL;
3393 err = got_repo_pack_fds_open(&pack_fds);
3394 if (err)
3395 return err;
3397 err = got_repo_open(&repo, path, NULL, pack_fds);
3398 if (err)
3399 return orig_err;
3401 snprintf(msg, sizeof(msg),
3402 "'got %s' needs a work tree in addition to a git repository\n"
3403 "Work trees can be checked out from this Git repository with "
3404 "'got checkout'.\n"
3405 "The got(1) manual page contains more information.", cmdname);
3406 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3407 got_repo_close(repo);
3408 if (pack_fds) {
3409 const struct got_error *pack_err =
3410 got_repo_pack_fds_close(pack_fds);
3411 if (err == NULL)
3412 err = pack_err;
3414 return err;
3417 static const struct got_error *
3418 cmd_update(int argc, char *argv[])
3420 const struct got_error *error = NULL;
3421 struct got_repository *repo = NULL;
3422 struct got_worktree *worktree = NULL;
3423 char *worktree_path = NULL;
3424 struct got_object_id *commit_id = NULL;
3425 char *commit_id_str = NULL;
3426 const char *branch_name = NULL;
3427 struct got_reference *head_ref = NULL;
3428 struct got_pathlist_head paths;
3429 struct got_pathlist_entry *pe;
3430 int ch, verbosity = 0;
3431 struct got_update_progress_arg upa;
3432 int *pack_fds = NULL;
3434 TAILQ_INIT(&paths);
3436 #ifndef PROFILE
3437 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3438 "unveil", NULL) == -1)
3439 err(1, "pledge");
3440 #endif
3442 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3443 switch (ch) {
3444 case 'b':
3445 branch_name = optarg;
3446 break;
3447 case 'c':
3448 commit_id_str = strdup(optarg);
3449 if (commit_id_str == NULL)
3450 return got_error_from_errno("strdup");
3451 break;
3452 case 'q':
3453 verbosity = -1;
3454 break;
3455 default:
3456 usage_update();
3457 /* NOTREACHED */
3461 argc -= optind;
3462 argv += optind;
3464 worktree_path = getcwd(NULL, 0);
3465 if (worktree_path == NULL) {
3466 error = got_error_from_errno("getcwd");
3467 goto done;
3470 error = got_repo_pack_fds_open(&pack_fds);
3471 if (error != NULL)
3472 goto done;
3474 error = got_worktree_open(&worktree, worktree_path);
3475 if (error) {
3476 if (error->code == GOT_ERR_NOT_WORKTREE)
3477 error = wrap_not_worktree_error(error, "update",
3478 worktree_path);
3479 goto done;
3482 error = check_rebase_or_histedit_in_progress(worktree);
3483 if (error)
3484 goto done;
3486 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3487 NULL, pack_fds);
3488 if (error != NULL)
3489 goto done;
3491 error = apply_unveil(got_repo_get_path(repo), 0,
3492 got_worktree_get_root_path(worktree));
3493 if (error)
3494 goto done;
3496 error = check_merge_in_progress(worktree, repo);
3497 if (error)
3498 goto done;
3500 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3501 if (error)
3502 goto done;
3504 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3505 got_worktree_get_head_ref_name(worktree), 0);
3506 if (error != NULL)
3507 goto done;
3508 if (commit_id_str == NULL) {
3509 error = got_ref_resolve(&commit_id, repo, head_ref);
3510 if (error != NULL)
3511 goto done;
3512 error = got_object_id_str(&commit_id_str, commit_id);
3513 if (error != NULL)
3514 goto done;
3515 } else {
3516 struct got_reflist_head refs;
3517 TAILQ_INIT(&refs);
3518 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3519 NULL);
3520 if (error)
3521 goto done;
3522 error = got_repo_match_object_id(&commit_id, NULL,
3523 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3524 got_ref_list_free(&refs);
3525 free(commit_id_str);
3526 commit_id_str = NULL;
3527 if (error)
3528 goto done;
3529 error = got_object_id_str(&commit_id_str, commit_id);
3530 if (error)
3531 goto done;
3534 if (branch_name) {
3535 struct got_object_id *head_commit_id;
3536 TAILQ_FOREACH(pe, &paths, entry) {
3537 if (pe->path_len == 0)
3538 continue;
3539 error = got_error_msg(GOT_ERR_BAD_PATH,
3540 "switching between branches requires that "
3541 "the entire work tree gets updated");
3542 goto done;
3544 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3545 if (error)
3546 goto done;
3547 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3548 repo);
3549 free(head_commit_id);
3550 if (error != NULL)
3551 goto done;
3552 error = check_same_branch(commit_id, head_ref, NULL, repo);
3553 if (error)
3554 goto done;
3555 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3556 if (error)
3557 goto done;
3558 } else {
3559 error = check_linear_ancestry(commit_id,
3560 got_worktree_get_base_commit_id(worktree), 0, repo);
3561 if (error != NULL) {
3562 if (error->code == GOT_ERR_ANCESTRY)
3563 error = got_error(GOT_ERR_BRANCH_MOVED);
3564 goto done;
3566 error = check_same_branch(commit_id, head_ref, NULL, repo);
3567 if (error)
3568 goto done;
3571 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3572 commit_id) != 0) {
3573 error = got_worktree_set_base_commit_id(worktree, repo,
3574 commit_id);
3575 if (error)
3576 goto done;
3579 memset(&upa, 0, sizeof(upa));
3580 upa.verbosity = verbosity;
3581 error = got_worktree_checkout_files(worktree, &paths, repo,
3582 update_progress, &upa, check_cancelled, NULL);
3583 if (error != NULL)
3584 goto done;
3586 if (upa.did_something) {
3587 printf("Updated to %s: %s\n",
3588 got_worktree_get_head_ref_name(worktree), commit_id_str);
3589 } else
3590 printf("Already up-to-date\n");
3592 print_update_progress_stats(&upa);
3593 done:
3594 if (pack_fds) {
3595 const struct got_error *pack_err =
3596 got_repo_pack_fds_close(pack_fds);
3597 if (error == NULL)
3598 error = pack_err;
3600 free(worktree_path);
3601 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3602 free(commit_id);
3603 free(commit_id_str);
3604 return error;
3607 static const struct got_error *
3608 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3609 const char *path, int diff_context, int ignore_whitespace,
3610 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3611 struct got_repository *repo, FILE *outfile)
3613 const struct got_error *err = NULL;
3614 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3615 FILE *f1 = NULL, *f2 = NULL;
3616 int fd1 = -1, fd2 = -1;
3618 fd1 = got_opentempfd();
3619 if (fd1 == -1)
3620 return got_error_from_errno("got_opentempfd");
3621 fd2 = got_opentempfd();
3622 if (fd2 == -1) {
3623 err = got_error_from_errno("got_opentempfd");
3624 goto done;
3627 if (blob_id1) {
3628 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3629 fd1);
3630 if (err)
3631 goto done;
3634 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3635 if (err)
3636 goto done;
3638 f1 = got_opentemp();
3639 if (f1 == NULL) {
3640 err = got_error_from_errno("got_opentemp");
3641 goto done;
3643 f2 = got_opentemp();
3644 if (f2 == NULL) {
3645 err = got_error_from_errno("got_opentemp");
3646 goto done;
3649 while (path[0] == '/')
3650 path++;
3651 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3652 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3653 force_text_diff, dsa, outfile);
3654 done:
3655 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3656 err = got_error_from_errno("close");
3657 if (blob1)
3658 got_object_blob_close(blob1);
3659 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3660 err = got_error_from_errno("close");
3661 got_object_blob_close(blob2);
3662 if (f1 && fclose(f1) == EOF && err == NULL)
3663 err = got_error_from_errno("fclose");
3664 if (f2 && fclose(f2) == EOF && err == NULL)
3665 err = got_error_from_errno("fclose");
3666 return err;
3669 static const struct got_error *
3670 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3671 const char *path, int diff_context, int ignore_whitespace,
3672 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3673 struct got_repository *repo, FILE *outfile)
3675 const struct got_error *err = NULL;
3676 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3677 struct got_diff_blob_output_unidiff_arg arg;
3678 FILE *f1 = NULL, *f2 = NULL;
3679 int fd1 = -1, fd2 = -1;
3681 if (tree_id1) {
3682 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3683 if (err)
3684 goto done;
3685 fd1 = got_opentempfd();
3686 if (fd1 == -1) {
3687 err = got_error_from_errno("got_opentempfd");
3688 goto done;
3692 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3693 if (err)
3694 goto done;
3696 f1 = got_opentemp();
3697 if (f1 == NULL) {
3698 err = got_error_from_errno("got_opentemp");
3699 goto done;
3702 f2 = got_opentemp();
3703 if (f2 == NULL) {
3704 err = got_error_from_errno("got_opentemp");
3705 goto done;
3707 fd2 = got_opentempfd();
3708 if (fd2 == -1) {
3709 err = got_error_from_errno("got_opentempfd");
3710 goto done;
3712 arg.diff_context = diff_context;
3713 arg.ignore_whitespace = ignore_whitespace;
3714 arg.force_text_diff = force_text_diff;
3715 arg.diffstat = dsa;
3716 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3717 arg.outfile = outfile;
3718 arg.lines = NULL;
3719 arg.nlines = 0;
3720 while (path[0] == '/')
3721 path++;
3722 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3723 got_diff_blob_output_unidiff, &arg, 1);
3724 done:
3725 if (tree1)
3726 got_object_tree_close(tree1);
3727 if (tree2)
3728 got_object_tree_close(tree2);
3729 if (f1 && fclose(f1) == EOF && err == NULL)
3730 err = got_error_from_errno("fclose");
3731 if (f2 && fclose(f2) == EOF && err == NULL)
3732 err = got_error_from_errno("fclose");
3733 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3734 err = got_error_from_errno("close");
3735 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3736 err = got_error_from_errno("close");
3737 return err;
3740 static const struct got_error *
3741 get_changed_paths(struct got_pathlist_head *paths,
3742 struct got_commit_object *commit, struct got_repository *repo,
3743 struct got_diffstat_cb_arg *dsa)
3745 const struct got_error *err = NULL;
3746 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3747 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3748 struct got_object_qid *qid;
3749 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3750 FILE *f1 = NULL, *f2 = NULL;
3751 int fd1 = -1, fd2 = -1;
3753 if (dsa) {
3754 cb = got_diff_tree_compute_diffstat;
3756 f1 = got_opentemp();
3757 if (f1 == NULL) {
3758 err = got_error_from_errno("got_opentemp");
3759 goto done;
3761 f2 = got_opentemp();
3762 if (f2 == NULL) {
3763 err = got_error_from_errno("got_opentemp");
3764 goto done;
3766 fd1 = got_opentempfd();
3767 if (fd1 == -1) {
3768 err = got_error_from_errno("got_opentempfd");
3769 goto done;
3771 fd2 = got_opentempfd();
3772 if (fd2 == -1) {
3773 err = got_error_from_errno("got_opentempfd");
3774 goto done;
3778 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3779 if (qid != NULL) {
3780 struct got_commit_object *pcommit;
3781 err = got_object_open_as_commit(&pcommit, repo,
3782 &qid->id);
3783 if (err)
3784 return err;
3786 tree_id1 = got_object_id_dup(
3787 got_object_commit_get_tree_id(pcommit));
3788 if (tree_id1 == NULL) {
3789 got_object_commit_close(pcommit);
3790 return got_error_from_errno("got_object_id_dup");
3792 got_object_commit_close(pcommit);
3796 if (tree_id1) {
3797 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3798 if (err)
3799 goto done;
3802 tree_id2 = got_object_commit_get_tree_id(commit);
3803 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3804 if (err)
3805 goto done;
3807 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3808 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3809 done:
3810 if (tree1)
3811 got_object_tree_close(tree1);
3812 if (tree2)
3813 got_object_tree_close(tree2);
3814 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3815 err = got_error_from_errno("close");
3816 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3817 err = got_error_from_errno("close");
3818 if (f1 && fclose(f1) == EOF && err == NULL)
3819 err = got_error_from_errno("fclose");
3820 if (f2 && fclose(f2) == EOF && err == NULL)
3821 err = got_error_from_errno("fclose");
3822 free(tree_id1);
3823 return err;
3826 static const struct got_error *
3827 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3828 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3829 struct got_repository *repo, FILE *outfile)
3831 const struct got_error *err = NULL;
3832 struct got_commit_object *pcommit = NULL;
3833 char *id_str1 = NULL, *id_str2 = NULL;
3834 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3835 struct got_object_qid *qid;
3837 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3838 if (qid != NULL) {
3839 err = got_object_open_as_commit(&pcommit, repo,
3840 &qid->id);
3841 if (err)
3842 return err;
3843 err = got_object_id_str(&id_str1, &qid->id);
3844 if (err)
3845 goto done;
3848 err = got_object_id_str(&id_str2, id);
3849 if (err)
3850 goto done;
3852 if (path && path[0] != '\0') {
3853 int obj_type;
3854 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3855 if (err)
3856 goto done;
3857 if (pcommit) {
3858 err = got_object_id_by_path(&obj_id1, repo,
3859 pcommit, path);
3860 if (err) {
3861 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3862 free(obj_id2);
3863 goto done;
3867 err = got_object_get_type(&obj_type, repo, obj_id2);
3868 if (err) {
3869 free(obj_id2);
3870 goto done;
3872 fprintf(outfile,
3873 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3874 fprintf(outfile, "commit - %s\n",
3875 id_str1 ? id_str1 : "/dev/null");
3876 fprintf(outfile, "commit + %s\n", id_str2);
3877 switch (obj_type) {
3878 case GOT_OBJ_TYPE_BLOB:
3879 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3880 0, 0, dsa, repo, outfile);
3881 break;
3882 case GOT_OBJ_TYPE_TREE:
3883 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3884 0, 0, dsa, repo, outfile);
3885 break;
3886 default:
3887 err = got_error(GOT_ERR_OBJ_TYPE);
3888 break;
3890 free(obj_id1);
3891 free(obj_id2);
3892 } else {
3893 obj_id2 = got_object_commit_get_tree_id(commit);
3894 if (pcommit)
3895 obj_id1 = got_object_commit_get_tree_id(pcommit);
3896 fprintf(outfile,
3897 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3898 fprintf(outfile, "commit - %s\n",
3899 id_str1 ? id_str1 : "/dev/null");
3900 fprintf(outfile, "commit + %s\n", id_str2);
3901 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3902 dsa, repo, outfile);
3904 done:
3905 free(id_str1);
3906 free(id_str2);
3907 if (pcommit)
3908 got_object_commit_close(pcommit);
3909 return err;
3912 static char *
3913 get_datestr(time_t *time, char *datebuf)
3915 struct tm mytm, *tm;
3916 char *p, *s;
3918 tm = gmtime_r(time, &mytm);
3919 if (tm == NULL)
3920 return NULL;
3921 s = asctime_r(tm, datebuf);
3922 if (s == NULL)
3923 return NULL;
3924 p = strchr(s, '\n');
3925 if (p)
3926 *p = '\0';
3927 return s;
3930 static const struct got_error *
3931 match_commit(int *have_match, struct got_object_id *id,
3932 struct got_commit_object *commit, regex_t *regex)
3934 const struct got_error *err = NULL;
3935 regmatch_t regmatch;
3936 char *id_str = NULL, *logmsg = NULL;
3938 *have_match = 0;
3940 err = got_object_id_str(&id_str, id);
3941 if (err)
3942 return err;
3944 err = got_object_commit_get_logmsg(&logmsg, commit);
3945 if (err)
3946 goto done;
3948 if (regexec(regex, got_object_commit_get_author(commit), 1,
3949 &regmatch, 0) == 0 ||
3950 regexec(regex, got_object_commit_get_committer(commit), 1,
3951 &regmatch, 0) == 0 ||
3952 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3953 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3954 *have_match = 1;
3955 done:
3956 free(id_str);
3957 free(logmsg);
3958 return err;
3961 static void
3962 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3963 regex_t *regex)
3965 regmatch_t regmatch;
3966 struct got_pathlist_entry *pe;
3968 *have_match = 0;
3970 TAILQ_FOREACH(pe, changed_paths, entry) {
3971 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3972 *have_match = 1;
3973 break;
3978 static const struct got_error *
3979 match_patch(int *have_match, struct got_commit_object *commit,
3980 struct got_object_id *id, const char *path, int diff_context,
3981 struct got_repository *repo, regex_t *regex, FILE *f)
3983 const struct got_error *err = NULL;
3984 char *line = NULL;
3985 size_t linesize = 0;
3986 regmatch_t regmatch;
3988 *have_match = 0;
3990 err = got_opentemp_truncate(f);
3991 if (err)
3992 return err;
3994 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3995 if (err)
3996 goto done;
3998 if (fseeko(f, 0L, SEEK_SET) == -1) {
3999 err = got_error_from_errno("fseeko");
4000 goto done;
4003 while (getline(&line, &linesize, f) != -1) {
4004 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4005 *have_match = 1;
4006 break;
4009 done:
4010 free(line);
4011 return err;
4014 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4016 static const struct got_error*
4017 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4018 struct got_object_id *id, struct got_repository *repo,
4019 int local_only)
4021 static const struct got_error *err = NULL;
4022 struct got_reflist_entry *re;
4023 char *s;
4024 const char *name;
4026 *refs_str = NULL;
4028 TAILQ_FOREACH(re, refs, entry) {
4029 struct got_tag_object *tag = NULL;
4030 struct got_object_id *ref_id;
4031 int cmp;
4033 name = got_ref_get_name(re->ref);
4034 if (strcmp(name, GOT_REF_HEAD) == 0)
4035 continue;
4036 if (strncmp(name, "refs/", 5) == 0)
4037 name += 5;
4038 if (strncmp(name, "got/", 4) == 0)
4039 continue;
4040 if (strncmp(name, "heads/", 6) == 0)
4041 name += 6;
4042 if (strncmp(name, "remotes/", 8) == 0) {
4043 if (local_only)
4044 continue;
4045 name += 8;
4046 s = strstr(name, "/" GOT_REF_HEAD);
4047 if (s != NULL && s[strlen(s)] == '\0')
4048 continue;
4050 err = got_ref_resolve(&ref_id, repo, re->ref);
4051 if (err)
4052 break;
4053 if (strncmp(name, "tags/", 5) == 0) {
4054 err = got_object_open_as_tag(&tag, repo, ref_id);
4055 if (err) {
4056 if (err->code != GOT_ERR_OBJ_TYPE) {
4057 free(ref_id);
4058 break;
4060 /* Ref points at something other than a tag. */
4061 err = NULL;
4062 tag = NULL;
4065 cmp = got_object_id_cmp(tag ?
4066 got_object_tag_get_object_id(tag) : ref_id, id);
4067 free(ref_id);
4068 if (tag)
4069 got_object_tag_close(tag);
4070 if (cmp != 0)
4071 continue;
4072 s = *refs_str;
4073 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4074 s ? ", " : "", name) == -1) {
4075 err = got_error_from_errno("asprintf");
4076 free(s);
4077 *refs_str = NULL;
4078 break;
4080 free(s);
4083 return err;
4086 static const struct got_error *
4087 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4088 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4090 const struct got_error *err = NULL;
4091 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4092 char *comma, *s, *nl;
4093 struct got_reflist_head *refs;
4094 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4095 struct tm tm;
4096 time_t committer_time;
4098 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4099 if (refs) {
4100 err = build_refs_str(&ref_str, refs, id, repo, 1);
4101 if (err)
4102 return err;
4104 /* Display the first matching ref only. */
4105 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4106 *comma = '\0';
4109 if (ref_str == NULL) {
4110 err = got_object_id_str(&id_str, id);
4111 if (err)
4112 return err;
4115 committer_time = got_object_commit_get_committer_time(commit);
4116 if (gmtime_r(&committer_time, &tm) == NULL) {
4117 err = got_error_from_errno("gmtime_r");
4118 goto done;
4120 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4121 err = got_error(GOT_ERR_NO_SPACE);
4122 goto done;
4125 err = got_object_commit_get_logmsg(&logmsg0, commit);
4126 if (err)
4127 goto done;
4129 s = logmsg0;
4130 while (isspace((unsigned char)s[0]))
4131 s++;
4133 nl = strchr(s, '\n');
4134 if (nl) {
4135 *nl = '\0';
4138 if (ref_str)
4139 printf("%s%-7s %s\n", datebuf, ref_str, s);
4140 else
4141 printf("%s%.7s %s\n", datebuf, id_str, s);
4143 if (fflush(stdout) != 0 && err == NULL)
4144 err = got_error_from_errno("fflush");
4145 done:
4146 free(id_str);
4147 free(ref_str);
4148 free(logmsg0);
4149 return err;
4152 static const struct got_error *
4153 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4155 struct got_pathlist_entry *pe;
4157 if (header != NULL)
4158 printf("%s\n", header);
4160 TAILQ_FOREACH(pe, dsa->paths, entry) {
4161 struct got_diff_changed_path *cp = pe->data;
4162 int pad = dsa->max_path_len - pe->path_len + 1;
4164 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4165 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4167 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4168 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4169 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4171 if (fflush(stdout) != 0)
4172 return got_error_from_errno("fflush");
4174 return NULL;
4177 static const struct got_error *
4178 printfile(FILE *f)
4180 char buf[8192];
4181 size_t r;
4183 if (fseeko(f, 0L, SEEK_SET) == -1)
4184 return got_error_from_errno("fseek");
4186 for (;;) {
4187 r = fread(buf, 1, sizeof(buf), f);
4188 if (r == 0) {
4189 if (ferror(f))
4190 return got_error_from_errno("fread");
4191 if (feof(f))
4192 break;
4194 if (fwrite(buf, 1, r, stdout) != r)
4195 return got_ferror(stdout, GOT_ERR_IO);
4198 return NULL;
4201 static const struct got_error *
4202 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4203 struct got_repository *repo, const char *path,
4204 struct got_pathlist_head *changed_paths,
4205 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4206 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4207 const char *prefix)
4209 const struct got_error *err = NULL;
4210 FILE *f = NULL;
4211 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4212 char datebuf[26];
4213 time_t committer_time;
4214 const char *author, *committer;
4215 char *refs_str = NULL;
4217 err = got_object_id_str(&id_str, id);
4218 if (err)
4219 return err;
4221 if (custom_refs_str == NULL) {
4222 struct got_reflist_head *refs;
4223 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4224 if (refs) {
4225 err = build_refs_str(&refs_str, refs, id, repo, 0);
4226 if (err)
4227 goto done;
4231 printf(GOT_COMMIT_SEP_STR);
4232 if (custom_refs_str)
4233 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4234 custom_refs_str);
4235 else
4236 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4237 refs_str ? " (" : "", refs_str ? refs_str : "",
4238 refs_str ? ")" : "");
4239 free(id_str);
4240 id_str = NULL;
4241 free(refs_str);
4242 refs_str = NULL;
4243 printf("from: %s\n", got_object_commit_get_author(commit));
4244 author = got_object_commit_get_author(commit);
4245 committer = got_object_commit_get_committer(commit);
4246 if (strcmp(author, committer) != 0)
4247 printf("via: %s\n", committer);
4248 committer_time = got_object_commit_get_committer_time(commit);
4249 datestr = get_datestr(&committer_time, datebuf);
4250 if (datestr)
4251 printf("date: %s UTC\n", datestr);
4252 if (got_object_commit_get_nparents(commit) > 1) {
4253 const struct got_object_id_queue *parent_ids;
4254 struct got_object_qid *qid;
4255 int n = 1;
4256 parent_ids = got_object_commit_get_parent_ids(commit);
4257 STAILQ_FOREACH(qid, parent_ids, entry) {
4258 err = got_object_id_str(&id_str, &qid->id);
4259 if (err)
4260 goto done;
4261 printf("parent %d: %s\n", n++, id_str);
4262 free(id_str);
4263 id_str = NULL;
4267 err = got_object_commit_get_logmsg(&logmsg0, commit);
4268 if (err)
4269 goto done;
4271 logmsg = logmsg0;
4272 do {
4273 line = strsep(&logmsg, "\n");
4274 if (line)
4275 printf(" %s\n", line);
4276 } while (line);
4277 free(logmsg0);
4279 if (changed_paths && diffstat == NULL) {
4280 struct got_pathlist_entry *pe;
4282 TAILQ_FOREACH(pe, changed_paths, entry) {
4283 struct got_diff_changed_path *cp = pe->data;
4285 printf(" %c %s\n", cp->status, pe->path);
4287 printf("\n");
4289 if (show_patch) {
4290 if (diffstat) {
4291 f = got_opentemp();
4292 if (f == NULL) {
4293 err = got_error_from_errno("got_opentemp");
4294 goto done;
4298 err = print_patch(commit, id, path, diff_context, diffstat,
4299 repo, diffstat == NULL ? stdout : f);
4300 if (err)
4301 goto done;
4303 if (diffstat) {
4304 err = print_diffstat(diffstat, NULL);
4305 if (err)
4306 goto done;
4307 if (show_patch) {
4308 err = printfile(f);
4309 if (err)
4310 goto done;
4313 if (show_patch)
4314 printf("\n");
4316 if (fflush(stdout) != 0 && err == NULL)
4317 err = got_error_from_errno("fflush");
4318 done:
4319 if (f && fclose(f) == EOF && err == NULL)
4320 err = got_error_from_errno("fclose");
4321 free(id_str);
4322 free(refs_str);
4323 return err;
4326 static const struct got_error *
4327 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4328 struct got_repository *repo, const char *path, int show_changed_paths,
4329 int show_diffstat, int show_patch, const char *search_pattern,
4330 int diff_context, int limit, int log_branches, int reverse_display_order,
4331 struct got_reflist_object_id_map *refs_idmap, int one_line,
4332 FILE *tmpfile)
4334 const struct got_error *err;
4335 struct got_commit_graph *graph;
4336 regex_t regex;
4337 int have_match;
4338 struct got_object_id_queue reversed_commits;
4339 struct got_object_qid *qid;
4340 struct got_commit_object *commit;
4341 struct got_pathlist_head changed_paths;
4343 STAILQ_INIT(&reversed_commits);
4344 TAILQ_INIT(&changed_paths);
4346 if (search_pattern && regcomp(&regex, search_pattern,
4347 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4348 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4350 err = got_commit_graph_open(&graph, path, !log_branches);
4351 if (err)
4352 return err;
4353 err = got_commit_graph_iter_start(graph, root_id, repo,
4354 check_cancelled, NULL);
4355 if (err)
4356 goto done;
4357 for (;;) {
4358 struct got_object_id id;
4359 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4360 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4362 if (sigint_received || sigpipe_received)
4363 break;
4365 err = got_commit_graph_iter_next(&id, graph, repo,
4366 check_cancelled, NULL);
4367 if (err) {
4368 if (err->code == GOT_ERR_ITER_COMPLETED)
4369 err = NULL;
4370 break;
4373 err = got_object_open_as_commit(&commit, repo, &id);
4374 if (err)
4375 break;
4377 if ((show_changed_paths || (show_diffstat && !show_patch))
4378 && !reverse_display_order) {
4379 err = get_changed_paths(&changed_paths, commit, repo,
4380 show_diffstat ? &dsa : NULL);
4381 if (err)
4382 break;
4385 if (search_pattern) {
4386 err = match_commit(&have_match, &id, commit, &regex);
4387 if (err) {
4388 got_object_commit_close(commit);
4389 break;
4391 if (have_match == 0 && show_changed_paths)
4392 match_changed_paths(&have_match,
4393 &changed_paths, &regex);
4394 if (have_match == 0 && show_patch) {
4395 err = match_patch(&have_match, commit, &id,
4396 path, diff_context, repo, &regex, tmpfile);
4397 if (err)
4398 break;
4400 if (have_match == 0) {
4401 got_object_commit_close(commit);
4402 got_pathlist_free(&changed_paths,
4403 GOT_PATHLIST_FREE_ALL);
4404 continue;
4408 if (reverse_display_order) {
4409 err = got_object_qid_alloc(&qid, &id);
4410 if (err)
4411 break;
4412 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4413 got_object_commit_close(commit);
4414 } else {
4415 if (one_line)
4416 err = print_commit_oneline(commit, &id,
4417 repo, refs_idmap);
4418 else
4419 err = print_commit(commit, &id, repo, path,
4420 (show_changed_paths || show_diffstat) ?
4421 &changed_paths : NULL,
4422 show_diffstat ? &dsa : NULL, show_patch,
4423 diff_context, refs_idmap, NULL, NULL);
4424 got_object_commit_close(commit);
4425 if (err)
4426 break;
4428 if ((limit && --limit == 0) ||
4429 (end_id && got_object_id_cmp(&id, end_id) == 0))
4430 break;
4432 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4434 if (reverse_display_order) {
4435 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4436 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4437 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4439 err = got_object_open_as_commit(&commit, repo,
4440 &qid->id);
4441 if (err)
4442 break;
4443 if (show_changed_paths ||
4444 (show_diffstat && !show_patch)) {
4445 err = get_changed_paths(&changed_paths, commit,
4446 repo, show_diffstat ? &dsa : NULL);
4447 if (err)
4448 break;
4450 if (one_line)
4451 err = print_commit_oneline(commit, &qid->id,
4452 repo, refs_idmap);
4453 else
4454 err = print_commit(commit, &qid->id, repo, path,
4455 (show_changed_paths || show_diffstat) ?
4456 &changed_paths : NULL,
4457 show_diffstat ? &dsa : NULL, show_patch,
4458 diff_context, refs_idmap, NULL, NULL);
4459 got_object_commit_close(commit);
4460 if (err)
4461 break;
4462 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4465 done:
4466 while (!STAILQ_EMPTY(&reversed_commits)) {
4467 qid = STAILQ_FIRST(&reversed_commits);
4468 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4469 got_object_qid_free(qid);
4471 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4472 if (search_pattern)
4473 regfree(&regex);
4474 got_commit_graph_close(graph);
4475 return err;
4478 __dead static void
4479 usage_log(void)
4481 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4482 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4483 "[path]\n", getprogname());
4484 exit(1);
4487 static int
4488 get_default_log_limit(void)
4490 const char *got_default_log_limit;
4491 long long n;
4492 const char *errstr;
4494 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4495 if (got_default_log_limit == NULL)
4496 return 0;
4497 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4498 if (errstr != NULL)
4499 return 0;
4500 return n;
4503 static const struct got_error *
4504 cmd_log(int argc, char *argv[])
4506 const struct got_error *error;
4507 struct got_repository *repo = NULL;
4508 struct got_worktree *worktree = NULL;
4509 struct got_object_id *start_id = NULL, *end_id = NULL;
4510 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4511 const char *start_commit = NULL, *end_commit = NULL;
4512 const char *search_pattern = NULL;
4513 int diff_context = -1, ch;
4514 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4515 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4516 const char *errstr;
4517 struct got_reflist_head refs;
4518 struct got_reflist_object_id_map *refs_idmap = NULL;
4519 FILE *tmpfile = NULL;
4520 int *pack_fds = NULL;
4522 TAILQ_INIT(&refs);
4524 #ifndef PROFILE
4525 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4526 NULL)
4527 == -1)
4528 err(1, "pledge");
4529 #endif
4531 limit = get_default_log_limit();
4533 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4534 switch (ch) {
4535 case 'b':
4536 log_branches = 1;
4537 break;
4538 case 'C':
4539 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4540 &errstr);
4541 if (errstr != NULL)
4542 errx(1, "number of context lines is %s: %s",
4543 errstr, optarg);
4544 break;
4545 case 'c':
4546 start_commit = optarg;
4547 break;
4548 case 'd':
4549 show_diffstat = 1;
4550 break;
4551 case 'l':
4552 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4553 if (errstr != NULL)
4554 errx(1, "number of commits is %s: %s",
4555 errstr, optarg);
4556 break;
4557 case 'P':
4558 show_changed_paths = 1;
4559 break;
4560 case 'p':
4561 show_patch = 1;
4562 break;
4563 case 'R':
4564 reverse_display_order = 1;
4565 break;
4566 case 'r':
4567 repo_path = realpath(optarg, NULL);
4568 if (repo_path == NULL)
4569 return got_error_from_errno2("realpath",
4570 optarg);
4571 got_path_strip_trailing_slashes(repo_path);
4572 break;
4573 case 'S':
4574 search_pattern = optarg;
4575 break;
4576 case 's':
4577 one_line = 1;
4578 break;
4579 case 'x':
4580 end_commit = optarg;
4581 break;
4582 default:
4583 usage_log();
4584 /* NOTREACHED */
4588 argc -= optind;
4589 argv += optind;
4591 if (diff_context == -1)
4592 diff_context = 3;
4593 else if (!show_patch)
4594 errx(1, "-C requires -p");
4596 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4597 errx(1, "cannot use -s with -d, -p or -P");
4599 cwd = getcwd(NULL, 0);
4600 if (cwd == NULL) {
4601 error = got_error_from_errno("getcwd");
4602 goto done;
4605 error = got_repo_pack_fds_open(&pack_fds);
4606 if (error != NULL)
4607 goto done;
4609 if (repo_path == NULL) {
4610 error = got_worktree_open(&worktree, cwd);
4611 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4612 goto done;
4613 error = NULL;
4616 if (argc == 1) {
4617 if (worktree) {
4618 error = got_worktree_resolve_path(&path, worktree,
4619 argv[0]);
4620 if (error)
4621 goto done;
4622 } else {
4623 path = strdup(argv[0]);
4624 if (path == NULL) {
4625 error = got_error_from_errno("strdup");
4626 goto done;
4629 } else if (argc != 0)
4630 usage_log();
4632 if (repo_path == NULL) {
4633 repo_path = worktree ?
4634 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4636 if (repo_path == NULL) {
4637 error = got_error_from_errno("strdup");
4638 goto done;
4641 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4642 if (error != NULL)
4643 goto done;
4645 error = apply_unveil(got_repo_get_path(repo), 1,
4646 worktree ? got_worktree_get_root_path(worktree) : NULL);
4647 if (error)
4648 goto done;
4650 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4651 if (error)
4652 goto done;
4654 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4655 if (error)
4656 goto done;
4658 if (start_commit == NULL) {
4659 struct got_reference *head_ref;
4660 struct got_commit_object *commit = NULL;
4661 error = got_ref_open(&head_ref, repo,
4662 worktree ? got_worktree_get_head_ref_name(worktree)
4663 : GOT_REF_HEAD, 0);
4664 if (error != NULL)
4665 goto done;
4666 error = got_ref_resolve(&start_id, repo, head_ref);
4667 got_ref_close(head_ref);
4668 if (error != NULL)
4669 goto done;
4670 error = got_object_open_as_commit(&commit, repo,
4671 start_id);
4672 if (error != NULL)
4673 goto done;
4674 got_object_commit_close(commit);
4675 } else {
4676 error = got_repo_match_object_id(&start_id, NULL,
4677 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4678 if (error != NULL)
4679 goto done;
4681 if (end_commit != NULL) {
4682 error = got_repo_match_object_id(&end_id, NULL,
4683 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4684 if (error != NULL)
4685 goto done;
4688 if (worktree) {
4690 * If a path was specified on the command line it was resolved
4691 * to a path in the work tree above. Prepend the work tree's
4692 * path prefix to obtain the corresponding in-repository path.
4694 if (path) {
4695 const char *prefix;
4696 prefix = got_worktree_get_path_prefix(worktree);
4697 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4698 (path[0] != '\0') ? "/" : "", path) == -1) {
4699 error = got_error_from_errno("asprintf");
4700 goto done;
4703 } else
4704 error = got_repo_map_path(&in_repo_path, repo,
4705 path ? path : "");
4706 if (error != NULL)
4707 goto done;
4708 if (in_repo_path) {
4709 free(path);
4710 path = in_repo_path;
4713 if (worktree) {
4714 /* Release work tree lock. */
4715 got_worktree_close(worktree);
4716 worktree = NULL;
4719 if (search_pattern && show_patch) {
4720 tmpfile = got_opentemp();
4721 if (tmpfile == NULL) {
4722 error = got_error_from_errno("got_opentemp");
4723 goto done;
4727 error = print_commits(start_id, end_id, repo, path ? path : "",
4728 show_changed_paths, show_diffstat, show_patch, search_pattern,
4729 diff_context, limit, log_branches, reverse_display_order,
4730 refs_idmap, one_line, tmpfile);
4731 done:
4732 free(path);
4733 free(repo_path);
4734 free(cwd);
4735 if (worktree)
4736 got_worktree_close(worktree);
4737 if (repo) {
4738 const struct got_error *close_err = got_repo_close(repo);
4739 if (error == NULL)
4740 error = close_err;
4742 if (pack_fds) {
4743 const struct got_error *pack_err =
4744 got_repo_pack_fds_close(pack_fds);
4745 if (error == NULL)
4746 error = pack_err;
4748 if (refs_idmap)
4749 got_reflist_object_id_map_free(refs_idmap);
4750 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4751 error = got_error_from_errno("fclose");
4752 got_ref_list_free(&refs);
4753 return error;
4756 __dead static void
4757 usage_diff(void)
4759 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4760 "[-r repository-path] [object1 object2 | path ...]\n",
4761 getprogname());
4762 exit(1);
4765 struct print_diff_arg {
4766 struct got_repository *repo;
4767 struct got_worktree *worktree;
4768 struct got_diffstat_cb_arg *diffstat;
4769 int diff_context;
4770 const char *id_str;
4771 int header_shown;
4772 int diff_staged;
4773 enum got_diff_algorithm diff_algo;
4774 int ignore_whitespace;
4775 int force_text_diff;
4776 FILE *f1;
4777 FILE *f2;
4778 FILE *outfile;
4782 * Create a file which contains the target path of a symlink so we can feed
4783 * it as content to the diff engine.
4785 static const struct got_error *
4786 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4787 const char *abspath)
4789 const struct got_error *err = NULL;
4790 char target_path[PATH_MAX];
4791 ssize_t target_len, outlen;
4793 *fd = -1;
4795 if (dirfd != -1) {
4796 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4797 if (target_len == -1)
4798 return got_error_from_errno2("readlinkat", abspath);
4799 } else {
4800 target_len = readlink(abspath, target_path, PATH_MAX);
4801 if (target_len == -1)
4802 return got_error_from_errno2("readlink", abspath);
4805 *fd = got_opentempfd();
4806 if (*fd == -1)
4807 return got_error_from_errno("got_opentempfd");
4809 outlen = write(*fd, target_path, target_len);
4810 if (outlen == -1) {
4811 err = got_error_from_errno("got_opentempfd");
4812 goto done;
4815 if (lseek(*fd, 0, SEEK_SET) == -1) {
4816 err = got_error_from_errno2("lseek", abspath);
4817 goto done;
4819 done:
4820 if (err) {
4821 close(*fd);
4822 *fd = -1;
4824 return err;
4827 static const struct got_error *
4828 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4829 const char *path, struct got_object_id *blob_id,
4830 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4831 int dirfd, const char *de_name)
4833 struct print_diff_arg *a = arg;
4834 const struct got_error *err = NULL;
4835 struct got_blob_object *blob1 = NULL;
4836 int fd = -1, fd1 = -1, fd2 = -1;
4837 FILE *f2 = NULL;
4838 char *abspath = NULL, *label1 = NULL;
4839 struct stat sb;
4840 off_t size1 = 0;
4841 int f2_exists = 0;
4843 memset(&sb, 0, sizeof(sb));
4845 if (a->diff_staged) {
4846 if (staged_status != GOT_STATUS_MODIFY &&
4847 staged_status != GOT_STATUS_ADD &&
4848 staged_status != GOT_STATUS_DELETE)
4849 return NULL;
4850 } else {
4851 if (staged_status == GOT_STATUS_DELETE)
4852 return NULL;
4853 if (status == GOT_STATUS_NONEXISTENT)
4854 return got_error_set_errno(ENOENT, path);
4855 if (status != GOT_STATUS_MODIFY &&
4856 status != GOT_STATUS_ADD &&
4857 status != GOT_STATUS_DELETE &&
4858 status != GOT_STATUS_CONFLICT)
4859 return NULL;
4862 err = got_opentemp_truncate(a->f1);
4863 if (err)
4864 return got_error_from_errno("got_opentemp_truncate");
4865 err = got_opentemp_truncate(a->f2);
4866 if (err)
4867 return got_error_from_errno("got_opentemp_truncate");
4869 if (!a->header_shown) {
4870 if (fprintf(a->outfile, "diff %s%s\n",
4871 a->diff_staged ? "-s " : "",
4872 got_worktree_get_root_path(a->worktree)) < 0) {
4873 err = got_error_from_errno("fprintf");
4874 goto done;
4876 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4877 err = got_error_from_errno("fprintf");
4878 goto done;
4880 if (fprintf(a->outfile, "path + %s%s\n",
4881 got_worktree_get_root_path(a->worktree),
4882 a->diff_staged ? " (staged changes)" : "") < 0) {
4883 err = got_error_from_errno("fprintf");
4884 goto done;
4886 a->header_shown = 1;
4889 if (a->diff_staged) {
4890 const char *label1 = NULL, *label2 = NULL;
4891 switch (staged_status) {
4892 case GOT_STATUS_MODIFY:
4893 label1 = path;
4894 label2 = path;
4895 break;
4896 case GOT_STATUS_ADD:
4897 label2 = path;
4898 break;
4899 case GOT_STATUS_DELETE:
4900 label1 = path;
4901 break;
4902 default:
4903 return got_error(GOT_ERR_FILE_STATUS);
4905 fd1 = got_opentempfd();
4906 if (fd1 == -1) {
4907 err = got_error_from_errno("got_opentempfd");
4908 goto done;
4910 fd2 = got_opentempfd();
4911 if (fd2 == -1) {
4912 err = got_error_from_errno("got_opentempfd");
4913 goto done;
4915 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4916 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4917 a->diff_algo, a->diff_context, a->ignore_whitespace,
4918 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4919 goto done;
4922 fd1 = got_opentempfd();
4923 if (fd1 == -1) {
4924 err = got_error_from_errno("got_opentempfd");
4925 goto done;
4928 if (staged_status == GOT_STATUS_ADD ||
4929 staged_status == GOT_STATUS_MODIFY) {
4930 char *id_str;
4931 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4932 8192, fd1);
4933 if (err)
4934 goto done;
4935 err = got_object_id_str(&id_str, staged_blob_id);
4936 if (err)
4937 goto done;
4938 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4939 err = got_error_from_errno("asprintf");
4940 free(id_str);
4941 goto done;
4943 free(id_str);
4944 } else if (status != GOT_STATUS_ADD) {
4945 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4946 fd1);
4947 if (err)
4948 goto done;
4951 if (status != GOT_STATUS_DELETE) {
4952 if (asprintf(&abspath, "%s/%s",
4953 got_worktree_get_root_path(a->worktree), path) == -1) {
4954 err = got_error_from_errno("asprintf");
4955 goto done;
4958 if (dirfd != -1) {
4959 fd = openat(dirfd, de_name,
4960 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4961 if (fd == -1) {
4962 if (!got_err_open_nofollow_on_symlink()) {
4963 err = got_error_from_errno2("openat",
4964 abspath);
4965 goto done;
4967 err = get_symlink_target_file(&fd, dirfd,
4968 de_name, abspath);
4969 if (err)
4970 goto done;
4972 } else {
4973 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4974 if (fd == -1) {
4975 if (!got_err_open_nofollow_on_symlink()) {
4976 err = got_error_from_errno2("open",
4977 abspath);
4978 goto done;
4980 err = get_symlink_target_file(&fd, dirfd,
4981 de_name, abspath);
4982 if (err)
4983 goto done;
4986 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4987 err = got_error_from_errno2("fstatat", abspath);
4988 goto done;
4990 f2 = fdopen(fd, "r");
4991 if (f2 == NULL) {
4992 err = got_error_from_errno2("fdopen", abspath);
4993 goto done;
4995 fd = -1;
4996 f2_exists = 1;
4999 if (blob1) {
5000 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5001 a->f1, blob1);
5002 if (err)
5003 goto done;
5006 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5007 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5008 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5009 done:
5010 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5011 err = got_error_from_errno("close");
5012 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5013 err = got_error_from_errno("close");
5014 if (blob1)
5015 got_object_blob_close(blob1);
5016 if (fd != -1 && close(fd) == -1 && err == NULL)
5017 err = got_error_from_errno("close");
5018 if (f2 && fclose(f2) == EOF && err == NULL)
5019 err = got_error_from_errno("fclose");
5020 free(abspath);
5021 return err;
5024 static const struct got_error *
5025 cmd_diff(int argc, char *argv[])
5027 const struct got_error *error;
5028 struct got_repository *repo = NULL;
5029 struct got_worktree *worktree = NULL;
5030 char *cwd = NULL, *repo_path = NULL;
5031 const char *commit_args[2] = { NULL, NULL };
5032 int ncommit_args = 0;
5033 struct got_object_id *ids[2] = { NULL, NULL };
5034 char *labels[2] = { NULL, NULL };
5035 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5036 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5037 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5038 const char *errstr;
5039 struct got_reflist_head refs;
5040 struct got_pathlist_head diffstat_paths, paths;
5041 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5042 int fd1 = -1, fd2 = -1;
5043 int *pack_fds = NULL;
5044 struct got_diffstat_cb_arg dsa;
5046 memset(&dsa, 0, sizeof(dsa));
5048 TAILQ_INIT(&refs);
5049 TAILQ_INIT(&paths);
5050 TAILQ_INIT(&diffstat_paths);
5052 #ifndef PROFILE
5053 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5054 NULL) == -1)
5055 err(1, "pledge");
5056 #endif
5058 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5059 switch (ch) {
5060 case 'a':
5061 force_text_diff = 1;
5062 break;
5063 case 'C':
5064 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5065 &errstr);
5066 if (errstr != NULL)
5067 errx(1, "number of context lines is %s: %s",
5068 errstr, optarg);
5069 break;
5070 case 'c':
5071 if (ncommit_args >= 2)
5072 errx(1, "too many -c options used");
5073 commit_args[ncommit_args++] = optarg;
5074 break;
5075 case 'd':
5076 show_diffstat = 1;
5077 break;
5078 case 'P':
5079 force_path = 1;
5080 break;
5081 case 'r':
5082 repo_path = realpath(optarg, NULL);
5083 if (repo_path == NULL)
5084 return got_error_from_errno2("realpath",
5085 optarg);
5086 got_path_strip_trailing_slashes(repo_path);
5087 rflag = 1;
5088 break;
5089 case 's':
5090 diff_staged = 1;
5091 break;
5092 case 'w':
5093 ignore_whitespace = 1;
5094 break;
5095 default:
5096 usage_diff();
5097 /* NOTREACHED */
5101 argc -= optind;
5102 argv += optind;
5104 cwd = getcwd(NULL, 0);
5105 if (cwd == NULL) {
5106 error = got_error_from_errno("getcwd");
5107 goto done;
5110 error = got_repo_pack_fds_open(&pack_fds);
5111 if (error != NULL)
5112 goto done;
5114 if (repo_path == NULL) {
5115 error = got_worktree_open(&worktree, cwd);
5116 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5117 goto done;
5118 else
5119 error = NULL;
5120 if (worktree) {
5121 repo_path =
5122 strdup(got_worktree_get_repo_path(worktree));
5123 if (repo_path == NULL) {
5124 error = got_error_from_errno("strdup");
5125 goto done;
5127 } else {
5128 repo_path = strdup(cwd);
5129 if (repo_path == NULL) {
5130 error = got_error_from_errno("strdup");
5131 goto done;
5136 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5137 free(repo_path);
5138 if (error != NULL)
5139 goto done;
5141 if (show_diffstat) {
5142 dsa.paths = &diffstat_paths;
5143 dsa.force_text = force_text_diff;
5144 dsa.ignore_ws = ignore_whitespace;
5145 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5148 if (rflag || worktree == NULL || ncommit_args > 0) {
5149 if (force_path) {
5150 error = got_error_msg(GOT_ERR_NOT_IMPL,
5151 "-P option can only be used when diffing "
5152 "a work tree");
5153 goto done;
5155 if (diff_staged) {
5156 error = got_error_msg(GOT_ERR_NOT_IMPL,
5157 "-s option can only be used when diffing "
5158 "a work tree");
5159 goto done;
5163 error = apply_unveil(got_repo_get_path(repo), 1,
5164 worktree ? got_worktree_get_root_path(worktree) : NULL);
5165 if (error)
5166 goto done;
5168 if ((!force_path && argc == 2) || ncommit_args > 0) {
5169 int obj_type = (ncommit_args > 0 ?
5170 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5171 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5172 NULL);
5173 if (error)
5174 goto done;
5175 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5176 const char *arg;
5177 if (ncommit_args > 0)
5178 arg = commit_args[i];
5179 else
5180 arg = argv[i];
5181 error = got_repo_match_object_id(&ids[i], &labels[i],
5182 arg, obj_type, &refs, repo);
5183 if (error) {
5184 if (error->code != GOT_ERR_NOT_REF &&
5185 error->code != GOT_ERR_NO_OBJ)
5186 goto done;
5187 if (ncommit_args > 0)
5188 goto done;
5189 error = NULL;
5190 break;
5195 f1 = got_opentemp();
5196 if (f1 == NULL) {
5197 error = got_error_from_errno("got_opentemp");
5198 goto done;
5201 f2 = got_opentemp();
5202 if (f2 == NULL) {
5203 error = got_error_from_errno("got_opentemp");
5204 goto done;
5207 outfile = got_opentemp();
5208 if (outfile == NULL) {
5209 error = got_error_from_errno("got_opentemp");
5210 goto done;
5213 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5214 struct print_diff_arg arg;
5215 char *id_str;
5217 if (worktree == NULL) {
5218 if (argc == 2 && ids[0] == NULL) {
5219 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5220 goto done;
5221 } else if (argc == 2 && ids[1] == NULL) {
5222 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5223 goto done;
5224 } else if (argc > 0) {
5225 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5226 "%s", "specified paths cannot be resolved");
5227 goto done;
5228 } else {
5229 error = got_error(GOT_ERR_NOT_WORKTREE);
5230 goto done;
5234 error = get_worktree_paths_from_argv(&paths, argc, argv,
5235 worktree);
5236 if (error)
5237 goto done;
5239 error = got_object_id_str(&id_str,
5240 got_worktree_get_base_commit_id(worktree));
5241 if (error)
5242 goto done;
5243 arg.repo = repo;
5244 arg.worktree = worktree;
5245 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5246 arg.diff_context = diff_context;
5247 arg.id_str = id_str;
5248 arg.header_shown = 0;
5249 arg.diff_staged = diff_staged;
5250 arg.ignore_whitespace = ignore_whitespace;
5251 arg.force_text_diff = force_text_diff;
5252 arg.diffstat = show_diffstat ? &dsa : NULL;
5253 arg.f1 = f1;
5254 arg.f2 = f2;
5255 arg.outfile = outfile;
5257 error = got_worktree_status(worktree, &paths, repo, 0,
5258 print_diff, &arg, check_cancelled, NULL);
5259 free(id_str);
5260 if (error)
5261 goto done;
5263 if (show_diffstat && dsa.nfiles > 0) {
5264 char *header;
5266 if (asprintf(&header, "diffstat %s%s",
5267 diff_staged ? "-s " : "",
5268 got_worktree_get_root_path(worktree)) == -1) {
5269 error = got_error_from_errno("asprintf");
5270 goto done;
5273 error = print_diffstat(&dsa, header);
5274 free(header);
5275 if (error)
5276 goto done;
5279 error = printfile(outfile);
5280 goto done;
5283 if (ncommit_args == 1) {
5284 struct got_commit_object *commit;
5285 error = got_object_open_as_commit(&commit, repo, ids[0]);
5286 if (error)
5287 goto done;
5289 labels[1] = labels[0];
5290 ids[1] = ids[0];
5291 if (got_object_commit_get_nparents(commit) > 0) {
5292 const struct got_object_id_queue *pids;
5293 struct got_object_qid *pid;
5294 pids = got_object_commit_get_parent_ids(commit);
5295 pid = STAILQ_FIRST(pids);
5296 ids[0] = got_object_id_dup(&pid->id);
5297 if (ids[0] == NULL) {
5298 error = got_error_from_errno(
5299 "got_object_id_dup");
5300 got_object_commit_close(commit);
5301 goto done;
5303 error = got_object_id_str(&labels[0], ids[0]);
5304 if (error) {
5305 got_object_commit_close(commit);
5306 goto done;
5308 } else {
5309 ids[0] = NULL;
5310 labels[0] = strdup("/dev/null");
5311 if (labels[0] == NULL) {
5312 error = got_error_from_errno("strdup");
5313 got_object_commit_close(commit);
5314 goto done;
5318 got_object_commit_close(commit);
5321 if (ncommit_args == 0 && argc > 2) {
5322 error = got_error_msg(GOT_ERR_BAD_PATH,
5323 "path arguments cannot be used when diffing two objects");
5324 goto done;
5327 if (ids[0]) {
5328 error = got_object_get_type(&type1, repo, ids[0]);
5329 if (error)
5330 goto done;
5333 error = got_object_get_type(&type2, repo, ids[1]);
5334 if (error)
5335 goto done;
5336 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5337 error = got_error(GOT_ERR_OBJ_TYPE);
5338 goto done;
5340 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5341 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5342 "path arguments cannot be used when diffing blobs");
5343 goto done;
5346 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5347 char *in_repo_path;
5348 struct got_pathlist_entry *new;
5349 if (worktree) {
5350 const char *prefix;
5351 char *p;
5352 error = got_worktree_resolve_path(&p, worktree,
5353 argv[i]);
5354 if (error)
5355 goto done;
5356 prefix = got_worktree_get_path_prefix(worktree);
5357 while (prefix[0] == '/')
5358 prefix++;
5359 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5360 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5361 p) == -1) {
5362 error = got_error_from_errno("asprintf");
5363 free(p);
5364 goto done;
5366 free(p);
5367 } else {
5368 char *mapped_path, *s;
5369 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5370 if (error)
5371 goto done;
5372 s = mapped_path;
5373 while (s[0] == '/')
5374 s++;
5375 in_repo_path = strdup(s);
5376 if (in_repo_path == NULL) {
5377 error = got_error_from_errno("asprintf");
5378 free(mapped_path);
5379 goto done;
5381 free(mapped_path);
5384 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5385 if (error || new == NULL /* duplicate */)
5386 free(in_repo_path);
5387 if (error)
5388 goto done;
5391 if (worktree) {
5392 /* Release work tree lock. */
5393 got_worktree_close(worktree);
5394 worktree = NULL;
5397 fd1 = got_opentempfd();
5398 if (fd1 == -1) {
5399 error = got_error_from_errno("got_opentempfd");
5400 goto done;
5403 fd2 = got_opentempfd();
5404 if (fd2 == -1) {
5405 error = got_error_from_errno("got_opentempfd");
5406 goto done;
5409 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5410 case GOT_OBJ_TYPE_BLOB:
5411 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5412 fd1, fd2, ids[0], ids[1], NULL, NULL,
5413 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5414 ignore_whitespace, force_text_diff,
5415 show_diffstat ? &dsa : NULL, repo, outfile);
5416 break;
5417 case GOT_OBJ_TYPE_TREE:
5418 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5419 ids[0], ids[1], &paths, "", "",
5420 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5421 ignore_whitespace, force_text_diff,
5422 show_diffstat ? &dsa : NULL, repo, outfile);
5423 break;
5424 case GOT_OBJ_TYPE_COMMIT:
5425 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5426 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5427 fd1, fd2, ids[0], ids[1], &paths,
5428 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5429 ignore_whitespace, force_text_diff,
5430 show_diffstat ? &dsa : NULL, repo, outfile);
5431 break;
5432 default:
5433 error = got_error(GOT_ERR_OBJ_TYPE);
5435 if (error)
5436 goto done;
5438 if (show_diffstat && dsa.nfiles > 0) {
5439 char *header = NULL;
5441 if (asprintf(&header, "diffstat %s %s",
5442 labels[0], labels[1]) == -1) {
5443 error = got_error_from_errno("asprintf");
5444 goto done;
5447 error = print_diffstat(&dsa, header);
5448 free(header);
5449 if (error)
5450 goto done;
5453 error = printfile(outfile);
5455 done:
5456 free(labels[0]);
5457 free(labels[1]);
5458 free(ids[0]);
5459 free(ids[1]);
5460 if (worktree)
5461 got_worktree_close(worktree);
5462 if (repo) {
5463 const struct got_error *close_err = got_repo_close(repo);
5464 if (error == NULL)
5465 error = close_err;
5467 if (pack_fds) {
5468 const struct got_error *pack_err =
5469 got_repo_pack_fds_close(pack_fds);
5470 if (error == NULL)
5471 error = pack_err;
5473 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5474 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5475 got_ref_list_free(&refs);
5476 if (outfile && fclose(outfile) == EOF && error == NULL)
5477 error = got_error_from_errno("fclose");
5478 if (f1 && fclose(f1) == EOF && error == NULL)
5479 error = got_error_from_errno("fclose");
5480 if (f2 && fclose(f2) == EOF && error == NULL)
5481 error = got_error_from_errno("fclose");
5482 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5483 error = got_error_from_errno("close");
5484 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5485 error = got_error_from_errno("close");
5486 return error;
5489 __dead static void
5490 usage_blame(void)
5492 fprintf(stderr,
5493 "usage: %s blame [-c commit] [-r repository-path] path\n",
5494 getprogname());
5495 exit(1);
5498 struct blame_line {
5499 int annotated;
5500 char *id_str;
5501 char *committer;
5502 char datebuf[11]; /* YYYY-MM-DD + NUL */
5505 struct blame_cb_args {
5506 struct blame_line *lines;
5507 int nlines;
5508 int nlines_prec;
5509 int lineno_cur;
5510 off_t *line_offsets;
5511 FILE *f;
5512 struct got_repository *repo;
5515 static const struct got_error *
5516 blame_cb(void *arg, int nlines, int lineno,
5517 struct got_commit_object *commit, struct got_object_id *id)
5519 const struct got_error *err = NULL;
5520 struct blame_cb_args *a = arg;
5521 struct blame_line *bline;
5522 char *line = NULL;
5523 size_t linesize = 0;
5524 off_t offset;
5525 struct tm tm;
5526 time_t committer_time;
5528 if (nlines != a->nlines ||
5529 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5530 return got_error(GOT_ERR_RANGE);
5532 if (sigint_received)
5533 return got_error(GOT_ERR_ITER_COMPLETED);
5535 if (lineno == -1)
5536 return NULL; /* no change in this commit */
5538 /* Annotate this line. */
5539 bline = &a->lines[lineno - 1];
5540 if (bline->annotated)
5541 return NULL;
5542 err = got_object_id_str(&bline->id_str, id);
5543 if (err)
5544 return err;
5546 bline->committer = strdup(got_object_commit_get_committer(commit));
5547 if (bline->committer == NULL) {
5548 err = got_error_from_errno("strdup");
5549 goto done;
5552 committer_time = got_object_commit_get_committer_time(commit);
5553 if (gmtime_r(&committer_time, &tm) == NULL)
5554 return got_error_from_errno("gmtime_r");
5555 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5556 &tm) == 0) {
5557 err = got_error(GOT_ERR_NO_SPACE);
5558 goto done;
5560 bline->annotated = 1;
5562 /* Print lines annotated so far. */
5563 bline = &a->lines[a->lineno_cur - 1];
5564 if (!bline->annotated)
5565 goto done;
5567 offset = a->line_offsets[a->lineno_cur - 1];
5568 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5569 err = got_error_from_errno("fseeko");
5570 goto done;
5573 while (a->lineno_cur <= a->nlines && bline->annotated) {
5574 char *smallerthan, *at, *nl, *committer;
5575 size_t len;
5577 if (getline(&line, &linesize, a->f) == -1) {
5578 if (ferror(a->f))
5579 err = got_error_from_errno("getline");
5580 break;
5583 committer = bline->committer;
5584 smallerthan = strchr(committer, '<');
5585 if (smallerthan && smallerthan[1] != '\0')
5586 committer = smallerthan + 1;
5587 at = strchr(committer, '@');
5588 if (at)
5589 *at = '\0';
5590 len = strlen(committer);
5591 if (len >= 9)
5592 committer[8] = '\0';
5594 nl = strchr(line, '\n');
5595 if (nl)
5596 *nl = '\0';
5597 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5598 bline->id_str, bline->datebuf, committer, line);
5600 a->lineno_cur++;
5601 bline = &a->lines[a->lineno_cur - 1];
5603 done:
5604 free(line);
5605 return err;
5608 static const struct got_error *
5609 cmd_blame(int argc, char *argv[])
5611 const struct got_error *error;
5612 struct got_repository *repo = NULL;
5613 struct got_worktree *worktree = NULL;
5614 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5615 char *link_target = NULL;
5616 struct got_object_id *obj_id = NULL;
5617 struct got_object_id *commit_id = NULL;
5618 struct got_commit_object *commit = NULL;
5619 struct got_blob_object *blob = NULL;
5620 char *commit_id_str = NULL;
5621 struct blame_cb_args bca;
5622 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5623 off_t filesize;
5624 int *pack_fds = NULL;
5625 FILE *f1 = NULL, *f2 = NULL;
5627 fd1 = got_opentempfd();
5628 if (fd1 == -1)
5629 return got_error_from_errno("got_opentempfd");
5631 memset(&bca, 0, sizeof(bca));
5633 #ifndef PROFILE
5634 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5635 NULL) == -1)
5636 err(1, "pledge");
5637 #endif
5639 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5640 switch (ch) {
5641 case 'c':
5642 commit_id_str = optarg;
5643 break;
5644 case 'r':
5645 repo_path = realpath(optarg, NULL);
5646 if (repo_path == NULL)
5647 return got_error_from_errno2("realpath",
5648 optarg);
5649 got_path_strip_trailing_slashes(repo_path);
5650 break;
5651 default:
5652 usage_blame();
5653 /* NOTREACHED */
5657 argc -= optind;
5658 argv += optind;
5660 if (argc == 1)
5661 path = argv[0];
5662 else
5663 usage_blame();
5665 cwd = getcwd(NULL, 0);
5666 if (cwd == NULL) {
5667 error = got_error_from_errno("getcwd");
5668 goto done;
5671 error = got_repo_pack_fds_open(&pack_fds);
5672 if (error != NULL)
5673 goto done;
5675 if (repo_path == NULL) {
5676 error = got_worktree_open(&worktree, cwd);
5677 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5678 goto done;
5679 else
5680 error = NULL;
5681 if (worktree) {
5682 repo_path =
5683 strdup(got_worktree_get_repo_path(worktree));
5684 if (repo_path == NULL) {
5685 error = got_error_from_errno("strdup");
5686 if (error)
5687 goto done;
5689 } else {
5690 repo_path = strdup(cwd);
5691 if (repo_path == NULL) {
5692 error = got_error_from_errno("strdup");
5693 goto done;
5698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5699 if (error != NULL)
5700 goto done;
5702 if (worktree) {
5703 const char *prefix = got_worktree_get_path_prefix(worktree);
5704 char *p;
5706 error = got_worktree_resolve_path(&p, worktree, path);
5707 if (error)
5708 goto done;
5709 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5710 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5711 p) == -1) {
5712 error = got_error_from_errno("asprintf");
5713 free(p);
5714 goto done;
5716 free(p);
5717 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5718 } else {
5719 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5720 if (error)
5721 goto done;
5722 error = got_repo_map_path(&in_repo_path, repo, path);
5724 if (error)
5725 goto done;
5727 if (commit_id_str == NULL) {
5728 struct got_reference *head_ref;
5729 error = got_ref_open(&head_ref, repo, worktree ?
5730 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5731 if (error != NULL)
5732 goto done;
5733 error = got_ref_resolve(&commit_id, repo, head_ref);
5734 got_ref_close(head_ref);
5735 if (error != NULL)
5736 goto done;
5737 } else {
5738 struct got_reflist_head refs;
5739 TAILQ_INIT(&refs);
5740 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5741 NULL);
5742 if (error)
5743 goto done;
5744 error = got_repo_match_object_id(&commit_id, NULL,
5745 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5746 got_ref_list_free(&refs);
5747 if (error)
5748 goto done;
5751 if (worktree) {
5752 /* Release work tree lock. */
5753 got_worktree_close(worktree);
5754 worktree = NULL;
5757 error = got_object_open_as_commit(&commit, repo, commit_id);
5758 if (error)
5759 goto done;
5761 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5762 commit, repo);
5763 if (error)
5764 goto done;
5766 error = got_object_id_by_path(&obj_id, repo, commit,
5767 link_target ? link_target : in_repo_path);
5768 if (error)
5769 goto done;
5771 error = got_object_get_type(&obj_type, repo, obj_id);
5772 if (error)
5773 goto done;
5775 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5776 error = got_error_path(link_target ? link_target : in_repo_path,
5777 GOT_ERR_OBJ_TYPE);
5778 goto done;
5781 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5782 if (error)
5783 goto done;
5784 bca.f = got_opentemp();
5785 if (bca.f == NULL) {
5786 error = got_error_from_errno("got_opentemp");
5787 goto done;
5789 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5790 &bca.line_offsets, bca.f, blob);
5791 if (error || bca.nlines == 0)
5792 goto done;
5794 /* Don't include \n at EOF in the blame line count. */
5795 if (bca.line_offsets[bca.nlines - 1] == filesize)
5796 bca.nlines--;
5798 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5799 if (bca.lines == NULL) {
5800 error = got_error_from_errno("calloc");
5801 goto done;
5803 bca.lineno_cur = 1;
5804 bca.nlines_prec = 0;
5805 i = bca.nlines;
5806 while (i > 0) {
5807 i /= 10;
5808 bca.nlines_prec++;
5810 bca.repo = repo;
5812 fd2 = got_opentempfd();
5813 if (fd2 == -1) {
5814 error = got_error_from_errno("got_opentempfd");
5815 goto done;
5817 fd3 = got_opentempfd();
5818 if (fd3 == -1) {
5819 error = got_error_from_errno("got_opentempfd");
5820 goto done;
5822 f1 = got_opentemp();
5823 if (f1 == NULL) {
5824 error = got_error_from_errno("got_opentemp");
5825 goto done;
5827 f2 = got_opentemp();
5828 if (f2 == NULL) {
5829 error = got_error_from_errno("got_opentemp");
5830 goto done;
5832 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5833 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5834 check_cancelled, NULL, fd2, fd3, f1, f2);
5835 done:
5836 free(in_repo_path);
5837 free(link_target);
5838 free(repo_path);
5839 free(cwd);
5840 free(commit_id);
5841 free(obj_id);
5842 if (commit)
5843 got_object_commit_close(commit);
5845 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5846 error = got_error_from_errno("close");
5847 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5848 error = got_error_from_errno("close");
5849 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5850 error = got_error_from_errno("close");
5851 if (f1 && fclose(f1) == EOF && error == NULL)
5852 error = got_error_from_errno("fclose");
5853 if (f2 && fclose(f2) == EOF && error == NULL)
5854 error = got_error_from_errno("fclose");
5856 if (blob)
5857 got_object_blob_close(blob);
5858 if (worktree)
5859 got_worktree_close(worktree);
5860 if (repo) {
5861 const struct got_error *close_err = got_repo_close(repo);
5862 if (error == NULL)
5863 error = close_err;
5865 if (pack_fds) {
5866 const struct got_error *pack_err =
5867 got_repo_pack_fds_close(pack_fds);
5868 if (error == NULL)
5869 error = pack_err;
5871 if (bca.lines) {
5872 for (i = 0; i < bca.nlines; i++) {
5873 struct blame_line *bline = &bca.lines[i];
5874 free(bline->id_str);
5875 free(bline->committer);
5877 free(bca.lines);
5879 free(bca.line_offsets);
5880 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5881 error = got_error_from_errno("fclose");
5882 return error;
5885 __dead static void
5886 usage_tree(void)
5888 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5889 "[path]\n", getprogname());
5890 exit(1);
5893 static const struct got_error *
5894 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5895 const char *root_path, struct got_repository *repo)
5897 const struct got_error *err = NULL;
5898 int is_root_path = (strcmp(path, root_path) == 0);
5899 const char *modestr = "";
5900 mode_t mode = got_tree_entry_get_mode(te);
5901 char *link_target = NULL;
5903 path += strlen(root_path);
5904 while (path[0] == '/')
5905 path++;
5907 if (got_object_tree_entry_is_submodule(te))
5908 modestr = "$";
5909 else if (S_ISLNK(mode)) {
5910 int i;
5912 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5913 if (err)
5914 return err;
5915 for (i = 0; i < strlen(link_target); i++) {
5916 if (!isprint((unsigned char)link_target[i]))
5917 link_target[i] = '?';
5920 modestr = "@";
5922 else if (S_ISDIR(mode))
5923 modestr = "/";
5924 else if (mode & S_IXUSR)
5925 modestr = "*";
5927 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5928 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5929 link_target ? " -> ": "", link_target ? link_target : "");
5931 free(link_target);
5932 return NULL;
5935 static const struct got_error *
5936 print_tree(const char *path, struct got_commit_object *commit,
5937 int show_ids, int recurse, const char *root_path,
5938 struct got_repository *repo)
5940 const struct got_error *err = NULL;
5941 struct got_object_id *tree_id = NULL;
5942 struct got_tree_object *tree = NULL;
5943 int nentries, i;
5945 err = got_object_id_by_path(&tree_id, repo, commit, path);
5946 if (err)
5947 goto done;
5949 err = got_object_open_as_tree(&tree, repo, tree_id);
5950 if (err)
5951 goto done;
5952 nentries = got_object_tree_get_nentries(tree);
5953 for (i = 0; i < nentries; i++) {
5954 struct got_tree_entry *te;
5955 char *id = NULL;
5957 if (sigint_received || sigpipe_received)
5958 break;
5960 te = got_object_tree_get_entry(tree, i);
5961 if (show_ids) {
5962 char *id_str;
5963 err = got_object_id_str(&id_str,
5964 got_tree_entry_get_id(te));
5965 if (err)
5966 goto done;
5967 if (asprintf(&id, "%s ", id_str) == -1) {
5968 err = got_error_from_errno("asprintf");
5969 free(id_str);
5970 goto done;
5972 free(id_str);
5974 err = print_entry(te, id, path, root_path, repo);
5975 free(id);
5976 if (err)
5977 goto done;
5979 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5980 char *child_path;
5981 if (asprintf(&child_path, "%s%s%s", path,
5982 path[0] == '/' && path[1] == '\0' ? "" : "/",
5983 got_tree_entry_get_name(te)) == -1) {
5984 err = got_error_from_errno("asprintf");
5985 goto done;
5987 err = print_tree(child_path, commit, show_ids, 1,
5988 root_path, repo);
5989 free(child_path);
5990 if (err)
5991 goto done;
5994 done:
5995 if (tree)
5996 got_object_tree_close(tree);
5997 free(tree_id);
5998 return err;
6001 static const struct got_error *
6002 cmd_tree(int argc, char *argv[])
6004 const struct got_error *error;
6005 struct got_repository *repo = NULL;
6006 struct got_worktree *worktree = NULL;
6007 const char *path, *refname = NULL;
6008 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6009 struct got_object_id *commit_id = NULL;
6010 struct got_commit_object *commit = NULL;
6011 char *commit_id_str = NULL;
6012 int show_ids = 0, recurse = 0;
6013 int ch;
6014 int *pack_fds = NULL;
6016 #ifndef PROFILE
6017 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6018 NULL) == -1)
6019 err(1, "pledge");
6020 #endif
6022 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6023 switch (ch) {
6024 case 'c':
6025 commit_id_str = optarg;
6026 break;
6027 case 'i':
6028 show_ids = 1;
6029 break;
6030 case 'R':
6031 recurse = 1;
6032 break;
6033 case 'r':
6034 repo_path = realpath(optarg, NULL);
6035 if (repo_path == NULL)
6036 return got_error_from_errno2("realpath",
6037 optarg);
6038 got_path_strip_trailing_slashes(repo_path);
6039 break;
6040 default:
6041 usage_tree();
6042 /* NOTREACHED */
6046 argc -= optind;
6047 argv += optind;
6049 if (argc == 1)
6050 path = argv[0];
6051 else if (argc > 1)
6052 usage_tree();
6053 else
6054 path = NULL;
6056 cwd = getcwd(NULL, 0);
6057 if (cwd == NULL) {
6058 error = got_error_from_errno("getcwd");
6059 goto done;
6062 error = got_repo_pack_fds_open(&pack_fds);
6063 if (error != NULL)
6064 goto done;
6066 if (repo_path == NULL) {
6067 error = got_worktree_open(&worktree, cwd);
6068 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6069 goto done;
6070 else
6071 error = NULL;
6072 if (worktree) {
6073 repo_path =
6074 strdup(got_worktree_get_repo_path(worktree));
6075 if (repo_path == NULL)
6076 error = got_error_from_errno("strdup");
6077 if (error)
6078 goto done;
6079 } else {
6080 repo_path = strdup(cwd);
6081 if (repo_path == NULL) {
6082 error = got_error_from_errno("strdup");
6083 goto done;
6088 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6089 if (error != NULL)
6090 goto done;
6092 if (worktree) {
6093 const char *prefix = got_worktree_get_path_prefix(worktree);
6094 char *p;
6096 if (path == NULL)
6097 path = "";
6098 error = got_worktree_resolve_path(&p, worktree, path);
6099 if (error)
6100 goto done;
6101 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6102 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6103 p) == -1) {
6104 error = got_error_from_errno("asprintf");
6105 free(p);
6106 goto done;
6108 free(p);
6109 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6110 if (error)
6111 goto done;
6112 } else {
6113 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6114 if (error)
6115 goto done;
6116 if (path == NULL)
6117 path = "/";
6118 error = got_repo_map_path(&in_repo_path, repo, path);
6119 if (error != NULL)
6120 goto done;
6123 if (commit_id_str == NULL) {
6124 struct got_reference *head_ref;
6125 if (worktree)
6126 refname = got_worktree_get_head_ref_name(worktree);
6127 else
6128 refname = GOT_REF_HEAD;
6129 error = got_ref_open(&head_ref, repo, refname, 0);
6130 if (error != NULL)
6131 goto done;
6132 error = got_ref_resolve(&commit_id, repo, head_ref);
6133 got_ref_close(head_ref);
6134 if (error != NULL)
6135 goto done;
6136 } else {
6137 struct got_reflist_head refs;
6138 TAILQ_INIT(&refs);
6139 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6140 NULL);
6141 if (error)
6142 goto done;
6143 error = got_repo_match_object_id(&commit_id, NULL,
6144 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6145 got_ref_list_free(&refs);
6146 if (error)
6147 goto done;
6150 if (worktree) {
6151 /* Release work tree lock. */
6152 got_worktree_close(worktree);
6153 worktree = NULL;
6156 error = got_object_open_as_commit(&commit, repo, commit_id);
6157 if (error)
6158 goto done;
6160 error = print_tree(in_repo_path, commit, show_ids, recurse,
6161 in_repo_path, repo);
6162 done:
6163 free(in_repo_path);
6164 free(repo_path);
6165 free(cwd);
6166 free(commit_id);
6167 if (commit)
6168 got_object_commit_close(commit);
6169 if (worktree)
6170 got_worktree_close(worktree);
6171 if (repo) {
6172 const struct got_error *close_err = got_repo_close(repo);
6173 if (error == NULL)
6174 error = close_err;
6176 if (pack_fds) {
6177 const struct got_error *pack_err =
6178 got_repo_pack_fds_close(pack_fds);
6179 if (error == NULL)
6180 error = pack_err;
6182 return error;
6185 __dead static void
6186 usage_status(void)
6188 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6189 "[-s status-codes] [path ...]\n", getprogname());
6190 exit(1);
6193 struct got_status_arg {
6194 char *status_codes;
6195 int suppress;
6198 static const struct got_error *
6199 print_status(void *arg, unsigned char status, unsigned char staged_status,
6200 const char *path, struct got_object_id *blob_id,
6201 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6202 int dirfd, const char *de_name)
6204 struct got_status_arg *st = arg;
6206 if (status == staged_status && (status == GOT_STATUS_DELETE))
6207 status = GOT_STATUS_NO_CHANGE;
6208 if (st != NULL && st->status_codes) {
6209 size_t ncodes = strlen(st->status_codes);
6210 int i, j = 0;
6212 for (i = 0; i < ncodes ; i++) {
6213 if (st->suppress) {
6214 if (status == st->status_codes[i] ||
6215 staged_status == st->status_codes[i]) {
6216 j++;
6217 continue;
6219 } else {
6220 if (status == st->status_codes[i] ||
6221 staged_status == st->status_codes[i])
6222 break;
6226 if (st->suppress && j == 0)
6227 goto print;
6229 if (i == ncodes)
6230 return NULL;
6232 print:
6233 printf("%c%c %s\n", status, staged_status, path);
6234 return NULL;
6237 static const struct got_error *
6238 cmd_status(int argc, char *argv[])
6240 const struct got_error *error = NULL;
6241 struct got_repository *repo = NULL;
6242 struct got_worktree *worktree = NULL;
6243 struct got_status_arg st;
6244 char *cwd = NULL;
6245 struct got_pathlist_head paths;
6246 int ch, i, no_ignores = 0;
6247 int *pack_fds = NULL;
6249 TAILQ_INIT(&paths);
6251 memset(&st, 0, sizeof(st));
6252 st.status_codes = NULL;
6253 st.suppress = 0;
6255 #ifndef PROFILE
6256 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6257 NULL) == -1)
6258 err(1, "pledge");
6259 #endif
6261 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6262 switch (ch) {
6263 case 'I':
6264 no_ignores = 1;
6265 break;
6266 case 'S':
6267 if (st.status_codes != NULL && st.suppress == 0)
6268 option_conflict('S', 's');
6269 st.suppress = 1;
6270 /* fallthrough */
6271 case 's':
6272 for (i = 0; i < strlen(optarg); i++) {
6273 switch (optarg[i]) {
6274 case GOT_STATUS_MODIFY:
6275 case GOT_STATUS_ADD:
6276 case GOT_STATUS_DELETE:
6277 case GOT_STATUS_CONFLICT:
6278 case GOT_STATUS_MISSING:
6279 case GOT_STATUS_OBSTRUCTED:
6280 case GOT_STATUS_UNVERSIONED:
6281 case GOT_STATUS_MODE_CHANGE:
6282 case GOT_STATUS_NONEXISTENT:
6283 break;
6284 default:
6285 errx(1, "invalid status code '%c'",
6286 optarg[i]);
6289 if (ch == 's' && st.suppress)
6290 option_conflict('s', 'S');
6291 st.status_codes = optarg;
6292 break;
6293 default:
6294 usage_status();
6295 /* NOTREACHED */
6299 argc -= optind;
6300 argv += optind;
6302 cwd = getcwd(NULL, 0);
6303 if (cwd == NULL) {
6304 error = got_error_from_errno("getcwd");
6305 goto done;
6308 error = got_repo_pack_fds_open(&pack_fds);
6309 if (error != NULL)
6310 goto done;
6312 error = got_worktree_open(&worktree, cwd);
6313 if (error) {
6314 if (error->code == GOT_ERR_NOT_WORKTREE)
6315 error = wrap_not_worktree_error(error, "status", cwd);
6316 goto done;
6319 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6320 NULL, pack_fds);
6321 if (error != NULL)
6322 goto done;
6324 error = apply_unveil(got_repo_get_path(repo), 1,
6325 got_worktree_get_root_path(worktree));
6326 if (error)
6327 goto done;
6329 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6330 if (error)
6331 goto done;
6333 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6334 print_status, &st, check_cancelled, NULL);
6335 done:
6336 if (pack_fds) {
6337 const struct got_error *pack_err =
6338 got_repo_pack_fds_close(pack_fds);
6339 if (error == NULL)
6340 error = pack_err;
6343 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6344 free(cwd);
6345 return error;
6348 __dead static void
6349 usage_ref(void)
6351 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6352 "[-s reference] [name]\n", getprogname());
6353 exit(1);
6356 static const struct got_error *
6357 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6359 static const struct got_error *err = NULL;
6360 struct got_reflist_head refs;
6361 struct got_reflist_entry *re;
6363 TAILQ_INIT(&refs);
6364 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6365 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6366 repo);
6367 if (err)
6368 return err;
6370 TAILQ_FOREACH(re, &refs, entry) {
6371 char *refstr;
6372 refstr = got_ref_to_str(re->ref);
6373 if (refstr == NULL) {
6374 err = got_error_from_errno("got_ref_to_str");
6375 break;
6377 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6378 free(refstr);
6381 got_ref_list_free(&refs);
6382 return err;
6385 static const struct got_error *
6386 delete_ref_by_name(struct got_repository *repo, const char *refname)
6388 const struct got_error *err;
6389 struct got_reference *ref;
6391 err = got_ref_open(&ref, repo, refname, 0);
6392 if (err)
6393 return err;
6395 err = delete_ref(repo, ref);
6396 got_ref_close(ref);
6397 return err;
6400 static const struct got_error *
6401 add_ref(struct got_repository *repo, const char *refname, const char *target)
6403 const struct got_error *err = NULL;
6404 struct got_object_id *id = NULL;
6405 struct got_reference *ref = NULL;
6406 struct got_reflist_head refs;
6409 * Don't let the user create a reference name with a leading '-'.
6410 * While technically a valid reference name, this case is usually
6411 * an unintended typo.
6413 if (refname[0] == '-')
6414 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6416 TAILQ_INIT(&refs);
6417 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6418 if (err)
6419 goto done;
6420 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6421 &refs, repo);
6422 got_ref_list_free(&refs);
6423 if (err)
6424 goto done;
6426 err = got_ref_alloc(&ref, refname, id);
6427 if (err)
6428 goto done;
6430 err = got_ref_write(ref, repo);
6431 done:
6432 if (ref)
6433 got_ref_close(ref);
6434 free(id);
6435 return err;
6438 static const struct got_error *
6439 add_symref(struct got_repository *repo, const char *refname, const char *target)
6441 const struct got_error *err = NULL;
6442 struct got_reference *ref = NULL;
6443 struct got_reference *target_ref = NULL;
6446 * Don't let the user create a reference name with a leading '-'.
6447 * While technically a valid reference name, this case is usually
6448 * an unintended typo.
6450 if (refname[0] == '-')
6451 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6453 err = got_ref_open(&target_ref, repo, target, 0);
6454 if (err)
6455 return err;
6457 err = got_ref_alloc_symref(&ref, refname, target_ref);
6458 if (err)
6459 goto done;
6461 err = got_ref_write(ref, repo);
6462 done:
6463 if (target_ref)
6464 got_ref_close(target_ref);
6465 if (ref)
6466 got_ref_close(ref);
6467 return err;
6470 static const struct got_error *
6471 cmd_ref(int argc, char *argv[])
6473 const struct got_error *error = NULL;
6474 struct got_repository *repo = NULL;
6475 struct got_worktree *worktree = NULL;
6476 char *cwd = NULL, *repo_path = NULL;
6477 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6478 const char *obj_arg = NULL, *symref_target= NULL;
6479 char *refname = NULL;
6480 int *pack_fds = NULL;
6482 #ifndef PROFILE
6483 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6484 "sendfd unveil", NULL) == -1)
6485 err(1, "pledge");
6486 #endif
6488 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6489 switch (ch) {
6490 case 'c':
6491 obj_arg = optarg;
6492 break;
6493 case 'd':
6494 do_delete = 1;
6495 break;
6496 case 'l':
6497 do_list = 1;
6498 break;
6499 case 'r':
6500 repo_path = realpath(optarg, NULL);
6501 if (repo_path == NULL)
6502 return got_error_from_errno2("realpath",
6503 optarg);
6504 got_path_strip_trailing_slashes(repo_path);
6505 break;
6506 case 's':
6507 symref_target = optarg;
6508 break;
6509 case 't':
6510 sort_by_time = 1;
6511 break;
6512 default:
6513 usage_ref();
6514 /* NOTREACHED */
6518 if (obj_arg && do_list)
6519 option_conflict('c', 'l');
6520 if (obj_arg && do_delete)
6521 option_conflict('c', 'd');
6522 if (obj_arg && symref_target)
6523 option_conflict('c', 's');
6524 if (symref_target && do_delete)
6525 option_conflict('s', 'd');
6526 if (symref_target && do_list)
6527 option_conflict('s', 'l');
6528 if (do_delete && do_list)
6529 option_conflict('d', 'l');
6530 if (sort_by_time && !do_list)
6531 errx(1, "-t option requires -l option");
6533 argc -= optind;
6534 argv += optind;
6536 if (do_list) {
6537 if (argc != 0 && argc != 1)
6538 usage_ref();
6539 if (argc == 1) {
6540 refname = strdup(argv[0]);
6541 if (refname == NULL) {
6542 error = got_error_from_errno("strdup");
6543 goto done;
6546 } else {
6547 if (argc != 1)
6548 usage_ref();
6549 refname = strdup(argv[0]);
6550 if (refname == NULL) {
6551 error = got_error_from_errno("strdup");
6552 goto done;
6556 if (refname)
6557 got_path_strip_trailing_slashes(refname);
6559 cwd = getcwd(NULL, 0);
6560 if (cwd == NULL) {
6561 error = got_error_from_errno("getcwd");
6562 goto done;
6565 error = got_repo_pack_fds_open(&pack_fds);
6566 if (error != NULL)
6567 goto done;
6569 if (repo_path == NULL) {
6570 error = got_worktree_open(&worktree, cwd);
6571 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6572 goto done;
6573 else
6574 error = NULL;
6575 if (worktree) {
6576 repo_path =
6577 strdup(got_worktree_get_repo_path(worktree));
6578 if (repo_path == NULL)
6579 error = got_error_from_errno("strdup");
6580 if (error)
6581 goto done;
6582 } else {
6583 repo_path = strdup(cwd);
6584 if (repo_path == NULL) {
6585 error = got_error_from_errno("strdup");
6586 goto done;
6591 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6592 if (error != NULL)
6593 goto done;
6595 #ifndef PROFILE
6596 if (do_list) {
6597 /* Remove "cpath" promise. */
6598 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6599 NULL) == -1)
6600 err(1, "pledge");
6602 #endif
6604 error = apply_unveil(got_repo_get_path(repo), do_list,
6605 worktree ? got_worktree_get_root_path(worktree) : NULL);
6606 if (error)
6607 goto done;
6609 if (do_list)
6610 error = list_refs(repo, refname, sort_by_time);
6611 else if (do_delete)
6612 error = delete_ref_by_name(repo, refname);
6613 else if (symref_target)
6614 error = add_symref(repo, refname, symref_target);
6615 else {
6616 if (obj_arg == NULL)
6617 usage_ref();
6618 error = add_ref(repo, refname, obj_arg);
6620 done:
6621 free(refname);
6622 if (repo) {
6623 const struct got_error *close_err = got_repo_close(repo);
6624 if (error == NULL)
6625 error = close_err;
6627 if (worktree)
6628 got_worktree_close(worktree);
6629 if (pack_fds) {
6630 const struct got_error *pack_err =
6631 got_repo_pack_fds_close(pack_fds);
6632 if (error == NULL)
6633 error = pack_err;
6635 free(cwd);
6636 free(repo_path);
6637 return error;
6640 __dead static void
6641 usage_branch(void)
6643 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6644 "[-r repository-path] [name]\n", getprogname());
6645 exit(1);
6648 static const struct got_error *
6649 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6650 struct got_reference *ref)
6652 const struct got_error *err = NULL;
6653 const char *refname, *marker = " ";
6654 char *refstr;
6656 refname = got_ref_get_name(ref);
6657 if (worktree && strcmp(refname,
6658 got_worktree_get_head_ref_name(worktree)) == 0) {
6659 struct got_object_id *id = NULL;
6661 err = got_ref_resolve(&id, repo, ref);
6662 if (err)
6663 return err;
6664 if (got_object_id_cmp(id,
6665 got_worktree_get_base_commit_id(worktree)) == 0)
6666 marker = "* ";
6667 else
6668 marker = "~ ";
6669 free(id);
6672 if (strncmp(refname, "refs/heads/", 11) == 0)
6673 refname += 11;
6674 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6675 refname += 18;
6676 if (strncmp(refname, "refs/remotes/", 13) == 0)
6677 refname += 13;
6679 refstr = got_ref_to_str(ref);
6680 if (refstr == NULL)
6681 return got_error_from_errno("got_ref_to_str");
6683 printf("%s%s: %s\n", marker, refname, refstr);
6684 free(refstr);
6685 return NULL;
6688 static const struct got_error *
6689 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6691 const char *refname;
6693 if (worktree == NULL)
6694 return got_error(GOT_ERR_NOT_WORKTREE);
6696 refname = got_worktree_get_head_ref_name(worktree);
6698 if (strncmp(refname, "refs/heads/", 11) == 0)
6699 refname += 11;
6700 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6701 refname += 18;
6703 printf("%s\n", refname);
6705 return NULL;
6708 static const struct got_error *
6709 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6710 int sort_by_time)
6712 static const struct got_error *err = NULL;
6713 struct got_reflist_head refs;
6714 struct got_reflist_entry *re;
6715 struct got_reference *temp_ref = NULL;
6716 int rebase_in_progress, histedit_in_progress;
6718 TAILQ_INIT(&refs);
6720 if (worktree) {
6721 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6722 worktree);
6723 if (err)
6724 return err;
6726 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6727 worktree);
6728 if (err)
6729 return err;
6731 if (rebase_in_progress || histedit_in_progress) {
6732 err = got_ref_open(&temp_ref, repo,
6733 got_worktree_get_head_ref_name(worktree), 0);
6734 if (err)
6735 return err;
6736 list_branch(repo, worktree, temp_ref);
6737 got_ref_close(temp_ref);
6741 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6742 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6743 repo);
6744 if (err)
6745 return err;
6747 TAILQ_FOREACH(re, &refs, entry)
6748 list_branch(repo, worktree, re->ref);
6750 got_ref_list_free(&refs);
6752 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6753 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6754 repo);
6755 if (err)
6756 return err;
6758 TAILQ_FOREACH(re, &refs, entry)
6759 list_branch(repo, worktree, re->ref);
6761 got_ref_list_free(&refs);
6763 return NULL;
6766 static const struct got_error *
6767 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6768 const char *branch_name)
6770 const struct got_error *err = NULL;
6771 struct got_reference *ref = NULL;
6772 char *refname, *remote_refname = NULL;
6774 if (strncmp(branch_name, "refs/", 5) == 0)
6775 branch_name += 5;
6776 if (strncmp(branch_name, "heads/", 6) == 0)
6777 branch_name += 6;
6778 else if (strncmp(branch_name, "remotes/", 8) == 0)
6779 branch_name += 8;
6781 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6782 return got_error_from_errno("asprintf");
6784 if (asprintf(&remote_refname, "refs/remotes/%s",
6785 branch_name) == -1) {
6786 err = got_error_from_errno("asprintf");
6787 goto done;
6790 err = got_ref_open(&ref, repo, refname, 0);
6791 if (err) {
6792 const struct got_error *err2;
6793 if (err->code != GOT_ERR_NOT_REF)
6794 goto done;
6796 * Keep 'err' intact such that if neither branch exists
6797 * we report "refs/heads" rather than "refs/remotes" in
6798 * our error message.
6800 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6801 if (err2)
6802 goto done;
6803 err = NULL;
6806 if (worktree &&
6807 strcmp(got_worktree_get_head_ref_name(worktree),
6808 got_ref_get_name(ref)) == 0) {
6809 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6810 "will not delete this work tree's current branch");
6811 goto done;
6814 err = delete_ref(repo, ref);
6815 done:
6816 if (ref)
6817 got_ref_close(ref);
6818 free(refname);
6819 free(remote_refname);
6820 return err;
6823 static const struct got_error *
6824 add_branch(struct got_repository *repo, const char *branch_name,
6825 struct got_object_id *base_commit_id)
6827 const struct got_error *err = NULL;
6828 struct got_reference *ref = NULL;
6829 char *refname = NULL;
6832 * Don't let the user create a branch name with a leading '-'.
6833 * While technically a valid reference name, this case is usually
6834 * an unintended typo.
6836 if (branch_name[0] == '-')
6837 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6839 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6840 branch_name += 11;
6842 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6843 err = got_error_from_errno("asprintf");
6844 goto done;
6847 err = got_ref_open(&ref, repo, refname, 0);
6848 if (err == NULL) {
6849 err = got_error(GOT_ERR_BRANCH_EXISTS);
6850 goto done;
6851 } else if (err->code != GOT_ERR_NOT_REF)
6852 goto done;
6854 err = got_ref_alloc(&ref, refname, base_commit_id);
6855 if (err)
6856 goto done;
6858 err = got_ref_write(ref, repo);
6859 done:
6860 if (ref)
6861 got_ref_close(ref);
6862 free(refname);
6863 return err;
6866 static const struct got_error *
6867 cmd_branch(int argc, char *argv[])
6869 const struct got_error *error = NULL;
6870 struct got_repository *repo = NULL;
6871 struct got_worktree *worktree = NULL;
6872 char *cwd = NULL, *repo_path = NULL;
6873 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6874 const char *delref = NULL, *commit_id_arg = NULL;
6875 struct got_reference *ref = NULL;
6876 struct got_pathlist_head paths;
6877 struct got_object_id *commit_id = NULL;
6878 char *commit_id_str = NULL;
6879 int *pack_fds = NULL;
6881 TAILQ_INIT(&paths);
6883 #ifndef PROFILE
6884 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6885 "sendfd unveil", NULL) == -1)
6886 err(1, "pledge");
6887 #endif
6889 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6890 switch (ch) {
6891 case 'c':
6892 commit_id_arg = optarg;
6893 break;
6894 case 'd':
6895 delref = optarg;
6896 break;
6897 case 'l':
6898 do_list = 1;
6899 break;
6900 case 'n':
6901 do_update = 0;
6902 break;
6903 case 'r':
6904 repo_path = realpath(optarg, NULL);
6905 if (repo_path == NULL)
6906 return got_error_from_errno2("realpath",
6907 optarg);
6908 got_path_strip_trailing_slashes(repo_path);
6909 break;
6910 case 't':
6911 sort_by_time = 1;
6912 break;
6913 default:
6914 usage_branch();
6915 /* NOTREACHED */
6919 if (do_list && delref)
6920 option_conflict('l', 'd');
6921 if (sort_by_time && !do_list)
6922 errx(1, "-t option requires -l option");
6924 argc -= optind;
6925 argv += optind;
6927 if (!do_list && !delref && argc == 0)
6928 do_show = 1;
6930 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6931 errx(1, "-c option can only be used when creating a branch");
6933 if (do_list || delref) {
6934 if (argc > 0)
6935 usage_branch();
6936 } else if (!do_show && argc != 1)
6937 usage_branch();
6939 cwd = getcwd(NULL, 0);
6940 if (cwd == NULL) {
6941 error = got_error_from_errno("getcwd");
6942 goto done;
6945 error = got_repo_pack_fds_open(&pack_fds);
6946 if (error != NULL)
6947 goto done;
6949 if (repo_path == NULL) {
6950 error = got_worktree_open(&worktree, cwd);
6951 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6952 goto done;
6953 else
6954 error = NULL;
6955 if (worktree) {
6956 repo_path =
6957 strdup(got_worktree_get_repo_path(worktree));
6958 if (repo_path == NULL)
6959 error = got_error_from_errno("strdup");
6960 if (error)
6961 goto done;
6962 } else {
6963 repo_path = strdup(cwd);
6964 if (repo_path == NULL) {
6965 error = got_error_from_errno("strdup");
6966 goto done;
6971 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6972 if (error != NULL)
6973 goto done;
6975 #ifndef PROFILE
6976 if (do_list || do_show) {
6977 /* Remove "cpath" promise. */
6978 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6979 NULL) == -1)
6980 err(1, "pledge");
6982 #endif
6984 error = apply_unveil(got_repo_get_path(repo), do_list,
6985 worktree ? got_worktree_get_root_path(worktree) : NULL);
6986 if (error)
6987 goto done;
6989 if (do_show)
6990 error = show_current_branch(repo, worktree);
6991 else if (do_list)
6992 error = list_branches(repo, worktree, sort_by_time);
6993 else if (delref)
6994 error = delete_branch(repo, worktree, delref);
6995 else {
6996 struct got_reflist_head refs;
6997 TAILQ_INIT(&refs);
6998 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6999 NULL);
7000 if (error)
7001 goto done;
7002 if (commit_id_arg == NULL)
7003 commit_id_arg = worktree ?
7004 got_worktree_get_head_ref_name(worktree) :
7005 GOT_REF_HEAD;
7006 error = got_repo_match_object_id(&commit_id, NULL,
7007 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7008 got_ref_list_free(&refs);
7009 if (error)
7010 goto done;
7011 error = add_branch(repo, argv[0], commit_id);
7012 if (error)
7013 goto done;
7014 if (worktree && do_update) {
7015 struct got_update_progress_arg upa;
7016 char *branch_refname = NULL;
7018 error = got_object_id_str(&commit_id_str, commit_id);
7019 if (error)
7020 goto done;
7021 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7022 worktree);
7023 if (error)
7024 goto done;
7025 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7026 == -1) {
7027 error = got_error_from_errno("asprintf");
7028 goto done;
7030 error = got_ref_open(&ref, repo, branch_refname, 0);
7031 free(branch_refname);
7032 if (error)
7033 goto done;
7034 error = switch_head_ref(ref, commit_id, worktree,
7035 repo);
7036 if (error)
7037 goto done;
7038 error = got_worktree_set_base_commit_id(worktree, repo,
7039 commit_id);
7040 if (error)
7041 goto done;
7042 memset(&upa, 0, sizeof(upa));
7043 error = got_worktree_checkout_files(worktree, &paths,
7044 repo, update_progress, &upa, check_cancelled,
7045 NULL);
7046 if (error)
7047 goto done;
7048 if (upa.did_something) {
7049 printf("Updated to %s: %s\n",
7050 got_worktree_get_head_ref_name(worktree),
7051 commit_id_str);
7053 print_update_progress_stats(&upa);
7056 done:
7057 if (ref)
7058 got_ref_close(ref);
7059 if (repo) {
7060 const struct got_error *close_err = got_repo_close(repo);
7061 if (error == NULL)
7062 error = close_err;
7064 if (worktree)
7065 got_worktree_close(worktree);
7066 if (pack_fds) {
7067 const struct got_error *pack_err =
7068 got_repo_pack_fds_close(pack_fds);
7069 if (error == NULL)
7070 error = pack_err;
7072 free(cwd);
7073 free(repo_path);
7074 free(commit_id);
7075 free(commit_id_str);
7076 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7077 return error;
7081 __dead static void
7082 usage_tag(void)
7084 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7085 "[-r repository-path] [-s signer-id] name\n", getprogname());
7086 exit(1);
7089 #if 0
7090 static const struct got_error *
7091 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7093 const struct got_error *err = NULL;
7094 struct got_reflist_entry *re, *se, *new;
7095 struct got_object_id *re_id, *se_id;
7096 struct got_tag_object *re_tag, *se_tag;
7097 time_t re_time, se_time;
7099 STAILQ_FOREACH(re, tags, entry) {
7100 se = STAILQ_FIRST(sorted);
7101 if (se == NULL) {
7102 err = got_reflist_entry_dup(&new, re);
7103 if (err)
7104 return err;
7105 STAILQ_INSERT_HEAD(sorted, new, entry);
7106 continue;
7107 } else {
7108 err = got_ref_resolve(&re_id, repo, re->ref);
7109 if (err)
7110 break;
7111 err = got_object_open_as_tag(&re_tag, repo, re_id);
7112 free(re_id);
7113 if (err)
7114 break;
7115 re_time = got_object_tag_get_tagger_time(re_tag);
7116 got_object_tag_close(re_tag);
7119 while (se) {
7120 err = got_ref_resolve(&se_id, repo, re->ref);
7121 if (err)
7122 break;
7123 err = got_object_open_as_tag(&se_tag, repo, se_id);
7124 free(se_id);
7125 if (err)
7126 break;
7127 se_time = got_object_tag_get_tagger_time(se_tag);
7128 got_object_tag_close(se_tag);
7130 if (se_time > re_time) {
7131 err = got_reflist_entry_dup(&new, re);
7132 if (err)
7133 return err;
7134 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7135 break;
7137 se = STAILQ_NEXT(se, entry);
7138 continue;
7141 done:
7142 return err;
7144 #endif
7146 static const struct got_error *
7147 get_tag_refname(char **refname, const char *tag_name)
7149 const struct got_error *err;
7151 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7152 *refname = strdup(tag_name);
7153 if (*refname == NULL)
7154 return got_error_from_errno("strdup");
7155 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7156 err = got_error_from_errno("asprintf");
7157 *refname = NULL;
7158 return err;
7161 return NULL;
7164 static const struct got_error *
7165 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7166 const char *allowed_signers, const char *revoked_signers, int verbosity)
7168 static const struct got_error *err = NULL;
7169 struct got_reflist_head refs;
7170 struct got_reflist_entry *re;
7171 char *wanted_refname = NULL;
7172 int bad_sigs = 0;
7174 TAILQ_INIT(&refs);
7176 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7177 if (err)
7178 return err;
7180 if (tag_name) {
7181 struct got_reference *ref;
7182 err = get_tag_refname(&wanted_refname, tag_name);
7183 if (err)
7184 goto done;
7185 /* Wanted tag reference should exist. */
7186 err = got_ref_open(&ref, repo, wanted_refname, 0);
7187 if (err)
7188 goto done;
7189 got_ref_close(ref);
7192 TAILQ_FOREACH(re, &refs, entry) {
7193 const char *refname;
7194 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7195 char datebuf[26];
7196 const char *tagger, *ssh_sig = NULL;
7197 char *sig_msg = NULL;
7198 time_t tagger_time;
7199 struct got_object_id *id;
7200 struct got_tag_object *tag;
7201 struct got_commit_object *commit = NULL;
7203 refname = got_ref_get_name(re->ref);
7204 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7205 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7206 continue;
7207 refname += 10;
7208 refstr = got_ref_to_str(re->ref);
7209 if (refstr == NULL) {
7210 err = got_error_from_errno("got_ref_to_str");
7211 break;
7214 err = got_ref_resolve(&id, repo, re->ref);
7215 if (err)
7216 break;
7217 err = got_object_open_as_tag(&tag, repo, id);
7218 if (err) {
7219 if (err->code != GOT_ERR_OBJ_TYPE) {
7220 free(id);
7221 break;
7223 /* "lightweight" tag */
7224 err = got_object_open_as_commit(&commit, repo, id);
7225 if (err) {
7226 free(id);
7227 break;
7229 tagger = got_object_commit_get_committer(commit);
7230 tagger_time =
7231 got_object_commit_get_committer_time(commit);
7232 err = got_object_id_str(&id_str, id);
7233 free(id);
7234 if (err)
7235 break;
7236 } else {
7237 free(id);
7238 tagger = got_object_tag_get_tagger(tag);
7239 tagger_time = got_object_tag_get_tagger_time(tag);
7240 err = got_object_id_str(&id_str,
7241 got_object_tag_get_object_id(tag));
7242 if (err)
7243 break;
7246 if (tag && verify_tags) {
7247 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7248 got_object_tag_get_message(tag));
7249 if (ssh_sig && allowed_signers == NULL) {
7250 err = got_error_msg(
7251 GOT_ERR_VERIFY_TAG_SIGNATURE,
7252 "SSH signature verification requires "
7253 "setting allowed_signers in "
7254 "got.conf(5)");
7255 break;
7259 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7260 free(refstr);
7261 printf("from: %s\n", tagger);
7262 datestr = get_datestr(&tagger_time, datebuf);
7263 if (datestr)
7264 printf("date: %s UTC\n", datestr);
7265 if (commit)
7266 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7267 else {
7268 switch (got_object_tag_get_object_type(tag)) {
7269 case GOT_OBJ_TYPE_BLOB:
7270 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7271 id_str);
7272 break;
7273 case GOT_OBJ_TYPE_TREE:
7274 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7275 id_str);
7276 break;
7277 case GOT_OBJ_TYPE_COMMIT:
7278 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7279 id_str);
7280 break;
7281 case GOT_OBJ_TYPE_TAG:
7282 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7283 id_str);
7284 break;
7285 default:
7286 break;
7289 free(id_str);
7291 if (ssh_sig) {
7292 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7293 allowed_signers, revoked_signers, verbosity);
7294 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7295 bad_sigs = 1;
7296 else if (err)
7297 break;
7298 printf("signature: %s", sig_msg);
7299 free(sig_msg);
7300 sig_msg = NULL;
7303 if (commit) {
7304 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7305 if (err)
7306 break;
7307 got_object_commit_close(commit);
7308 } else {
7309 tagmsg0 = strdup(got_object_tag_get_message(tag));
7310 got_object_tag_close(tag);
7311 if (tagmsg0 == NULL) {
7312 err = got_error_from_errno("strdup");
7313 break;
7317 tagmsg = tagmsg0;
7318 do {
7319 line = strsep(&tagmsg, "\n");
7320 if (line)
7321 printf(" %s\n", line);
7322 } while (line);
7323 free(tagmsg0);
7325 done:
7326 got_ref_list_free(&refs);
7327 free(wanted_refname);
7329 if (err == NULL && bad_sigs)
7330 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7331 return err;
7334 static const struct got_error *
7335 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7336 const char *tag_name, const char *repo_path)
7338 const struct got_error *err = NULL;
7339 char *template = NULL, *initial_content = NULL;
7340 char *editor = NULL;
7341 int initial_content_len;
7342 int fd = -1;
7344 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7345 err = got_error_from_errno("asprintf");
7346 goto done;
7349 initial_content_len = asprintf(&initial_content,
7350 "\n# tagging commit %s as %s\n",
7351 commit_id_str, tag_name);
7352 if (initial_content_len == -1) {
7353 err = got_error_from_errno("asprintf");
7354 goto done;
7357 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7358 if (err)
7359 goto done;
7361 if (write(fd, initial_content, initial_content_len) == -1) {
7362 err = got_error_from_errno2("write", *tagmsg_path);
7363 goto done;
7366 err = get_editor(&editor);
7367 if (err)
7368 goto done;
7369 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7370 initial_content_len, 1);
7371 done:
7372 free(initial_content);
7373 free(template);
7374 free(editor);
7376 if (fd != -1 && close(fd) == -1 && err == NULL)
7377 err = got_error_from_errno2("close", *tagmsg_path);
7379 if (err) {
7380 free(*tagmsg);
7381 *tagmsg = NULL;
7383 return err;
7386 static const struct got_error *
7387 add_tag(struct got_repository *repo, const char *tagger,
7388 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7389 const char *signer_id, int verbosity)
7391 const struct got_error *err = NULL;
7392 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7393 char *label = NULL, *commit_id_str = NULL;
7394 struct got_reference *ref = NULL;
7395 char *refname = NULL, *tagmsg = NULL;
7396 char *tagmsg_path = NULL, *tag_id_str = NULL;
7397 int preserve_tagmsg = 0;
7398 struct got_reflist_head refs;
7400 TAILQ_INIT(&refs);
7403 * Don't let the user create a tag name with a leading '-'.
7404 * While technically a valid reference name, this case is usually
7405 * an unintended typo.
7407 if (tag_name[0] == '-')
7408 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7410 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7411 if (err)
7412 goto done;
7414 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7415 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7416 if (err)
7417 goto done;
7419 err = got_object_id_str(&commit_id_str, commit_id);
7420 if (err)
7421 goto done;
7423 err = get_tag_refname(&refname, tag_name);
7424 if (err)
7425 goto done;
7426 if (strncmp("refs/tags/", tag_name, 10) == 0)
7427 tag_name += 10;
7429 err = got_ref_open(&ref, repo, refname, 0);
7430 if (err == NULL) {
7431 err = got_error(GOT_ERR_TAG_EXISTS);
7432 goto done;
7433 } else if (err->code != GOT_ERR_NOT_REF)
7434 goto done;
7436 if (tagmsg_arg == NULL) {
7437 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7438 tag_name, got_repo_get_path(repo));
7439 if (err) {
7440 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7441 tagmsg_path != NULL)
7442 preserve_tagmsg = 1;
7443 goto done;
7445 /* Editor is done; we can now apply unveil(2) */
7446 err = got_sigs_apply_unveil();
7447 if (err)
7448 goto done;
7449 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7450 if (err)
7451 goto done;
7454 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7455 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7456 verbosity);
7457 if (err) {
7458 if (tagmsg_path)
7459 preserve_tagmsg = 1;
7460 goto done;
7463 err = got_ref_alloc(&ref, refname, tag_id);
7464 if (err) {
7465 if (tagmsg_path)
7466 preserve_tagmsg = 1;
7467 goto done;
7470 err = got_ref_write(ref, repo);
7471 if (err) {
7472 if (tagmsg_path)
7473 preserve_tagmsg = 1;
7474 goto done;
7477 err = got_object_id_str(&tag_id_str, tag_id);
7478 if (err) {
7479 if (tagmsg_path)
7480 preserve_tagmsg = 1;
7481 goto done;
7483 printf("Created tag %s\n", tag_id_str);
7484 done:
7485 if (preserve_tagmsg) {
7486 fprintf(stderr, "%s: tag message preserved in %s\n",
7487 getprogname(), tagmsg_path);
7488 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7489 err = got_error_from_errno2("unlink", tagmsg_path);
7490 free(tag_id_str);
7491 if (ref)
7492 got_ref_close(ref);
7493 free(commit_id);
7494 free(commit_id_str);
7495 free(refname);
7496 free(tagmsg);
7497 free(tagmsg_path);
7498 got_ref_list_free(&refs);
7499 return err;
7502 static const struct got_error *
7503 cmd_tag(int argc, char *argv[])
7505 const struct got_error *error = NULL;
7506 struct got_repository *repo = NULL;
7507 struct got_worktree *worktree = NULL;
7508 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7509 char *gitconfig_path = NULL, *tagger = NULL;
7510 char *allowed_signers = NULL, *revoked_signers = NULL;
7511 const char *signer_id = NULL;
7512 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7513 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7514 int *pack_fds = NULL;
7516 #ifndef PROFILE
7517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7518 "sendfd unveil", NULL) == -1)
7519 err(1, "pledge");
7520 #endif
7522 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7523 switch (ch) {
7524 case 'c':
7525 commit_id_arg = optarg;
7526 break;
7527 case 'l':
7528 do_list = 1;
7529 break;
7530 case 'm':
7531 tagmsg = optarg;
7532 break;
7533 case 'r':
7534 repo_path = realpath(optarg, NULL);
7535 if (repo_path == NULL) {
7536 error = got_error_from_errno2("realpath",
7537 optarg);
7538 goto done;
7540 got_path_strip_trailing_slashes(repo_path);
7541 break;
7542 case 's':
7543 signer_id = optarg;
7544 break;
7545 case 'V':
7546 verify_tags = 1;
7547 break;
7548 case 'v':
7549 if (verbosity < 0)
7550 verbosity = 0;
7551 else if (verbosity < 3)
7552 verbosity++;
7553 break;
7554 default:
7555 usage_tag();
7556 /* NOTREACHED */
7560 argc -= optind;
7561 argv += optind;
7563 if (do_list || verify_tags) {
7564 if (commit_id_arg != NULL)
7565 errx(1,
7566 "-c option can only be used when creating a tag");
7567 if (tagmsg) {
7568 if (do_list)
7569 option_conflict('l', 'm');
7570 else
7571 option_conflict('V', 'm');
7573 if (signer_id) {
7574 if (do_list)
7575 option_conflict('l', 's');
7576 else
7577 option_conflict('V', 's');
7579 if (argc > 1)
7580 usage_tag();
7581 } else if (argc != 1)
7582 usage_tag();
7584 if (argc == 1)
7585 tag_name = argv[0];
7587 cwd = getcwd(NULL, 0);
7588 if (cwd == NULL) {
7589 error = got_error_from_errno("getcwd");
7590 goto done;
7593 error = got_repo_pack_fds_open(&pack_fds);
7594 if (error != NULL)
7595 goto done;
7597 if (repo_path == NULL) {
7598 error = got_worktree_open(&worktree, cwd);
7599 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7600 goto done;
7601 else
7602 error = NULL;
7603 if (worktree) {
7604 repo_path =
7605 strdup(got_worktree_get_repo_path(worktree));
7606 if (repo_path == NULL)
7607 error = got_error_from_errno("strdup");
7608 if (error)
7609 goto done;
7610 } else {
7611 repo_path = strdup(cwd);
7612 if (repo_path == NULL) {
7613 error = got_error_from_errno("strdup");
7614 goto done;
7619 if (do_list || verify_tags) {
7620 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7621 if (error != NULL)
7622 goto done;
7623 error = get_allowed_signers(&allowed_signers, repo, worktree);
7624 if (error)
7625 goto done;
7626 error = get_revoked_signers(&revoked_signers, repo, worktree);
7627 if (error)
7628 goto done;
7629 if (worktree) {
7630 /* Release work tree lock. */
7631 got_worktree_close(worktree);
7632 worktree = NULL;
7636 * Remove "cpath" promise unless needed for signature tmpfile
7637 * creation.
7639 if (verify_tags)
7640 got_sigs_apply_unveil();
7641 else {
7642 #ifndef PROFILE
7643 if (pledge("stdio rpath wpath flock proc exec sendfd "
7644 "unveil", NULL) == -1)
7645 err(1, "pledge");
7646 #endif
7648 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7649 if (error)
7650 goto done;
7651 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7652 revoked_signers, verbosity);
7653 } else {
7654 error = get_gitconfig_path(&gitconfig_path);
7655 if (error)
7656 goto done;
7657 error = got_repo_open(&repo, repo_path, gitconfig_path,
7658 pack_fds);
7659 if (error != NULL)
7660 goto done;
7662 error = get_author(&tagger, repo, worktree);
7663 if (error)
7664 goto done;
7665 if (signer_id == NULL)
7666 signer_id = get_signer_id(repo, worktree);
7668 if (tagmsg) {
7669 if (signer_id) {
7670 error = got_sigs_apply_unveil();
7671 if (error)
7672 goto done;
7674 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7675 if (error)
7676 goto done;
7679 if (commit_id_arg == NULL) {
7680 struct got_reference *head_ref;
7681 struct got_object_id *commit_id;
7682 error = got_ref_open(&head_ref, repo,
7683 worktree ? got_worktree_get_head_ref_name(worktree)
7684 : GOT_REF_HEAD, 0);
7685 if (error)
7686 goto done;
7687 error = got_ref_resolve(&commit_id, repo, head_ref);
7688 got_ref_close(head_ref);
7689 if (error)
7690 goto done;
7691 error = got_object_id_str(&commit_id_str, commit_id);
7692 free(commit_id);
7693 if (error)
7694 goto done;
7697 if (worktree) {
7698 /* Release work tree lock. */
7699 got_worktree_close(worktree);
7700 worktree = NULL;
7703 error = add_tag(repo, tagger, tag_name,
7704 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7705 signer_id, verbosity);
7707 done:
7708 if (repo) {
7709 const struct got_error *close_err = got_repo_close(repo);
7710 if (error == NULL)
7711 error = close_err;
7713 if (worktree)
7714 got_worktree_close(worktree);
7715 if (pack_fds) {
7716 const struct got_error *pack_err =
7717 got_repo_pack_fds_close(pack_fds);
7718 if (error == NULL)
7719 error = pack_err;
7721 free(cwd);
7722 free(repo_path);
7723 free(gitconfig_path);
7724 free(commit_id_str);
7725 free(tagger);
7726 free(allowed_signers);
7727 free(revoked_signers);
7728 return error;
7731 __dead static void
7732 usage_add(void)
7734 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7735 exit(1);
7738 static const struct got_error *
7739 add_progress(void *arg, unsigned char status, const char *path)
7741 while (path[0] == '/')
7742 path++;
7743 printf("%c %s\n", status, path);
7744 return NULL;
7747 static const struct got_error *
7748 cmd_add(int argc, char *argv[])
7750 const struct got_error *error = NULL;
7751 struct got_repository *repo = NULL;
7752 struct got_worktree *worktree = NULL;
7753 char *cwd = NULL;
7754 struct got_pathlist_head paths;
7755 struct got_pathlist_entry *pe;
7756 int ch, can_recurse = 0, no_ignores = 0;
7757 int *pack_fds = NULL;
7759 TAILQ_INIT(&paths);
7761 #ifndef PROFILE
7762 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7763 NULL) == -1)
7764 err(1, "pledge");
7765 #endif
7767 while ((ch = getopt(argc, argv, "IR")) != -1) {
7768 switch (ch) {
7769 case 'I':
7770 no_ignores = 1;
7771 break;
7772 case 'R':
7773 can_recurse = 1;
7774 break;
7775 default:
7776 usage_add();
7777 /* NOTREACHED */
7781 argc -= optind;
7782 argv += optind;
7784 if (argc < 1)
7785 usage_add();
7787 cwd = getcwd(NULL, 0);
7788 if (cwd == NULL) {
7789 error = got_error_from_errno("getcwd");
7790 goto done;
7793 error = got_repo_pack_fds_open(&pack_fds);
7794 if (error != NULL)
7795 goto done;
7797 error = got_worktree_open(&worktree, cwd);
7798 if (error) {
7799 if (error->code == GOT_ERR_NOT_WORKTREE)
7800 error = wrap_not_worktree_error(error, "add", cwd);
7801 goto done;
7804 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7805 NULL, pack_fds);
7806 if (error != NULL)
7807 goto done;
7809 error = apply_unveil(got_repo_get_path(repo), 1,
7810 got_worktree_get_root_path(worktree));
7811 if (error)
7812 goto done;
7814 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7815 if (error)
7816 goto done;
7818 if (!can_recurse) {
7819 char *ondisk_path;
7820 struct stat sb;
7821 TAILQ_FOREACH(pe, &paths, entry) {
7822 if (asprintf(&ondisk_path, "%s/%s",
7823 got_worktree_get_root_path(worktree),
7824 pe->path) == -1) {
7825 error = got_error_from_errno("asprintf");
7826 goto done;
7828 if (lstat(ondisk_path, &sb) == -1) {
7829 if (errno == ENOENT) {
7830 free(ondisk_path);
7831 continue;
7833 error = got_error_from_errno2("lstat",
7834 ondisk_path);
7835 free(ondisk_path);
7836 goto done;
7838 free(ondisk_path);
7839 if (S_ISDIR(sb.st_mode)) {
7840 error = got_error_msg(GOT_ERR_BAD_PATH,
7841 "adding directories requires -R option");
7842 goto done;
7847 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7848 NULL, repo, no_ignores);
7849 done:
7850 if (repo) {
7851 const struct got_error *close_err = got_repo_close(repo);
7852 if (error == NULL)
7853 error = close_err;
7855 if (worktree)
7856 got_worktree_close(worktree);
7857 if (pack_fds) {
7858 const struct got_error *pack_err =
7859 got_repo_pack_fds_close(pack_fds);
7860 if (error == NULL)
7861 error = pack_err;
7863 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7864 free(cwd);
7865 return error;
7868 __dead static void
7869 usage_remove(void)
7871 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7872 getprogname());
7873 exit(1);
7876 static const struct got_error *
7877 print_remove_status(void *arg, unsigned char status,
7878 unsigned char staged_status, const char *path)
7880 while (path[0] == '/')
7881 path++;
7882 if (status == GOT_STATUS_NONEXISTENT)
7883 return NULL;
7884 if (status == staged_status && (status == GOT_STATUS_DELETE))
7885 status = GOT_STATUS_NO_CHANGE;
7886 printf("%c%c %s\n", status, staged_status, path);
7887 return NULL;
7890 static const struct got_error *
7891 cmd_remove(int argc, char *argv[])
7893 const struct got_error *error = NULL;
7894 struct got_worktree *worktree = NULL;
7895 struct got_repository *repo = NULL;
7896 const char *status_codes = NULL;
7897 char *cwd = NULL;
7898 struct got_pathlist_head paths;
7899 struct got_pathlist_entry *pe;
7900 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7901 int ignore_missing_paths = 0;
7902 int *pack_fds = NULL;
7904 TAILQ_INIT(&paths);
7906 #ifndef PROFILE
7907 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7908 NULL) == -1)
7909 err(1, "pledge");
7910 #endif
7912 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7913 switch (ch) {
7914 case 'f':
7915 delete_local_mods = 1;
7916 ignore_missing_paths = 1;
7917 break;
7918 case 'k':
7919 keep_on_disk = 1;
7920 break;
7921 case 'R':
7922 can_recurse = 1;
7923 break;
7924 case 's':
7925 for (i = 0; i < strlen(optarg); i++) {
7926 switch (optarg[i]) {
7927 case GOT_STATUS_MODIFY:
7928 delete_local_mods = 1;
7929 break;
7930 case GOT_STATUS_MISSING:
7931 ignore_missing_paths = 1;
7932 break;
7933 default:
7934 errx(1, "invalid status code '%c'",
7935 optarg[i]);
7938 status_codes = optarg;
7939 break;
7940 default:
7941 usage_remove();
7942 /* NOTREACHED */
7946 argc -= optind;
7947 argv += optind;
7949 if (argc < 1)
7950 usage_remove();
7952 cwd = getcwd(NULL, 0);
7953 if (cwd == NULL) {
7954 error = got_error_from_errno("getcwd");
7955 goto done;
7958 error = got_repo_pack_fds_open(&pack_fds);
7959 if (error != NULL)
7960 goto done;
7962 error = got_worktree_open(&worktree, cwd);
7963 if (error) {
7964 if (error->code == GOT_ERR_NOT_WORKTREE)
7965 error = wrap_not_worktree_error(error, "remove", cwd);
7966 goto done;
7969 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7970 NULL, pack_fds);
7971 if (error)
7972 goto done;
7974 error = apply_unveil(got_repo_get_path(repo), 1,
7975 got_worktree_get_root_path(worktree));
7976 if (error)
7977 goto done;
7979 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7980 if (error)
7981 goto done;
7983 if (!can_recurse) {
7984 char *ondisk_path;
7985 struct stat sb;
7986 TAILQ_FOREACH(pe, &paths, entry) {
7987 if (asprintf(&ondisk_path, "%s/%s",
7988 got_worktree_get_root_path(worktree),
7989 pe->path) == -1) {
7990 error = got_error_from_errno("asprintf");
7991 goto done;
7993 if (lstat(ondisk_path, &sb) == -1) {
7994 if (errno == ENOENT) {
7995 free(ondisk_path);
7996 continue;
7998 error = got_error_from_errno2("lstat",
7999 ondisk_path);
8000 free(ondisk_path);
8001 goto done;
8003 free(ondisk_path);
8004 if (S_ISDIR(sb.st_mode)) {
8005 error = got_error_msg(GOT_ERR_BAD_PATH,
8006 "removing directories requires -R option");
8007 goto done;
8012 error = got_worktree_schedule_delete(worktree, &paths,
8013 delete_local_mods, status_codes, print_remove_status, NULL,
8014 repo, keep_on_disk, ignore_missing_paths);
8015 done:
8016 if (repo) {
8017 const struct got_error *close_err = got_repo_close(repo);
8018 if (error == NULL)
8019 error = close_err;
8021 if (worktree)
8022 got_worktree_close(worktree);
8023 if (pack_fds) {
8024 const struct got_error *pack_err =
8025 got_repo_pack_fds_close(pack_fds);
8026 if (error == NULL)
8027 error = pack_err;
8029 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8030 free(cwd);
8031 return error;
8034 __dead static void
8035 usage_patch(void)
8037 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8038 "[patchfile]\n", getprogname());
8039 exit(1);
8042 static const struct got_error *
8043 patch_from_stdin(int *patchfd)
8045 const struct got_error *err = NULL;
8046 ssize_t r;
8047 char buf[BUFSIZ];
8048 sig_t sighup, sigint, sigquit;
8050 *patchfd = got_opentempfd();
8051 if (*patchfd == -1)
8052 return got_error_from_errno("got_opentempfd");
8054 sighup = signal(SIGHUP, SIG_DFL);
8055 sigint = signal(SIGINT, SIG_DFL);
8056 sigquit = signal(SIGQUIT, SIG_DFL);
8058 for (;;) {
8059 r = read(0, buf, sizeof(buf));
8060 if (r == -1) {
8061 err = got_error_from_errno("read");
8062 break;
8064 if (r == 0)
8065 break;
8066 if (write(*patchfd, buf, r) == -1) {
8067 err = got_error_from_errno("write");
8068 break;
8072 signal(SIGHUP, sighup);
8073 signal(SIGINT, sigint);
8074 signal(SIGQUIT, sigquit);
8076 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8077 err = got_error_from_errno("lseek");
8079 if (err != NULL) {
8080 close(*patchfd);
8081 *patchfd = -1;
8084 return err;
8087 static const struct got_error *
8088 patch_progress(void *arg, const char *old, const char *new,
8089 unsigned char status, const struct got_error *error, int old_from,
8090 int old_lines, int new_from, int new_lines, int offset,
8091 int ws_mangled, const struct got_error *hunk_err)
8093 const char *path = new == NULL ? old : new;
8095 while (*path == '/')
8096 path++;
8098 if (status != 0)
8099 printf("%c %s\n", status, path);
8101 if (error != NULL)
8102 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8104 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8105 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8106 old_lines, new_from, new_lines);
8107 if (hunk_err != NULL)
8108 printf("%s\n", hunk_err->msg);
8109 else if (offset != 0)
8110 printf("applied with offset %d\n", offset);
8111 else
8112 printf("hunk contains mangled whitespace\n");
8115 return NULL;
8118 static const struct got_error *
8119 cmd_patch(int argc, char *argv[])
8121 const struct got_error *error = NULL, *close_error = NULL;
8122 struct got_worktree *worktree = NULL;
8123 struct got_repository *repo = NULL;
8124 struct got_reflist_head refs;
8125 struct got_object_id *commit_id = NULL;
8126 const char *commit_id_str = NULL;
8127 struct stat sb;
8128 const char *errstr;
8129 char *cwd = NULL;
8130 int ch, nop = 0, strip = -1, reverse = 0;
8131 int patchfd;
8132 int *pack_fds = NULL;
8134 TAILQ_INIT(&refs);
8136 #ifndef PROFILE
8137 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8138 "unveil", NULL) == -1)
8139 err(1, "pledge");
8140 #endif
8142 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8143 switch (ch) {
8144 case 'c':
8145 commit_id_str = optarg;
8146 break;
8147 case 'n':
8148 nop = 1;
8149 break;
8150 case 'p':
8151 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8152 if (errstr != NULL)
8153 errx(1, "pathname strip count is %s: %s",
8154 errstr, optarg);
8155 break;
8156 case 'R':
8157 reverse = 1;
8158 break;
8159 default:
8160 usage_patch();
8161 /* NOTREACHED */
8165 argc -= optind;
8166 argv += optind;
8168 if (argc == 0) {
8169 error = patch_from_stdin(&patchfd);
8170 if (error)
8171 return error;
8172 } else if (argc == 1) {
8173 patchfd = open(argv[0], O_RDONLY);
8174 if (patchfd == -1) {
8175 error = got_error_from_errno2("open", argv[0]);
8176 return error;
8178 if (fstat(patchfd, &sb) == -1) {
8179 error = got_error_from_errno2("fstat", argv[0]);
8180 goto done;
8182 if (!S_ISREG(sb.st_mode)) {
8183 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8184 goto done;
8186 } else
8187 usage_patch();
8189 if ((cwd = getcwd(NULL, 0)) == NULL) {
8190 error = got_error_from_errno("getcwd");
8191 goto done;
8194 error = got_repo_pack_fds_open(&pack_fds);
8195 if (error != NULL)
8196 goto done;
8198 error = got_worktree_open(&worktree, cwd);
8199 if (error != NULL)
8200 goto done;
8202 const char *repo_path = got_worktree_get_repo_path(worktree);
8203 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8204 if (error != NULL)
8205 goto done;
8207 error = apply_unveil(got_repo_get_path(repo), 0,
8208 got_worktree_get_root_path(worktree));
8209 if (error != NULL)
8210 goto done;
8212 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8213 if (error)
8214 goto done;
8216 if (commit_id_str != NULL) {
8217 error = got_repo_match_object_id(&commit_id, NULL,
8218 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8219 if (error)
8220 goto done;
8223 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8224 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8226 done:
8227 got_ref_list_free(&refs);
8228 free(commit_id);
8229 if (repo) {
8230 close_error = got_repo_close(repo);
8231 if (error == NULL)
8232 error = close_error;
8234 if (worktree != NULL) {
8235 close_error = got_worktree_close(worktree);
8236 if (error == NULL)
8237 error = close_error;
8239 if (pack_fds) {
8240 const struct got_error *pack_err =
8241 got_repo_pack_fds_close(pack_fds);
8242 if (error == NULL)
8243 error = pack_err;
8245 free(cwd);
8246 return error;
8249 __dead static void
8250 usage_revert(void)
8252 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8253 getprogname());
8254 exit(1);
8257 static const struct got_error *
8258 revert_progress(void *arg, unsigned char status, const char *path)
8260 if (status == GOT_STATUS_UNVERSIONED)
8261 return NULL;
8263 while (path[0] == '/')
8264 path++;
8265 printf("%c %s\n", status, path);
8266 return NULL;
8269 struct choose_patch_arg {
8270 FILE *patch_script_file;
8271 const char *action;
8274 static const struct got_error *
8275 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8276 int nchanges, const char *action)
8278 const struct got_error *err;
8279 char *line = NULL;
8280 size_t linesize = 0;
8281 ssize_t linelen;
8283 switch (status) {
8284 case GOT_STATUS_ADD:
8285 printf("A %s\n%s this addition? [y/n] ", path, action);
8286 break;
8287 case GOT_STATUS_DELETE:
8288 printf("D %s\n%s this deletion? [y/n] ", path, action);
8289 break;
8290 case GOT_STATUS_MODIFY:
8291 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8292 return got_error_from_errno("fseek");
8293 printf(GOT_COMMIT_SEP_STR);
8294 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8295 printf("%s", line);
8296 if (linelen == -1 && ferror(patch_file)) {
8297 err = got_error_from_errno("getline");
8298 free(line);
8299 return err;
8301 free(line);
8302 printf(GOT_COMMIT_SEP_STR);
8303 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8304 path, n, nchanges, action);
8305 break;
8306 default:
8307 return got_error_path(path, GOT_ERR_FILE_STATUS);
8310 fflush(stdout);
8311 return NULL;
8314 static const struct got_error *
8315 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8316 FILE *patch_file, int n, int nchanges)
8318 const struct got_error *err = NULL;
8319 char *line = NULL;
8320 size_t linesize = 0;
8321 ssize_t linelen;
8322 int resp = ' ';
8323 struct choose_patch_arg *a = arg;
8325 *choice = GOT_PATCH_CHOICE_NONE;
8327 if (a->patch_script_file) {
8328 char *nl;
8329 err = show_change(status, path, patch_file, n, nchanges,
8330 a->action);
8331 if (err)
8332 return err;
8333 linelen = getline(&line, &linesize, a->patch_script_file);
8334 if (linelen == -1) {
8335 if (ferror(a->patch_script_file))
8336 return got_error_from_errno("getline");
8337 return NULL;
8339 nl = strchr(line, '\n');
8340 if (nl)
8341 *nl = '\0';
8342 if (strcmp(line, "y") == 0) {
8343 *choice = GOT_PATCH_CHOICE_YES;
8344 printf("y\n");
8345 } else if (strcmp(line, "n") == 0) {
8346 *choice = GOT_PATCH_CHOICE_NO;
8347 printf("n\n");
8348 } else if (strcmp(line, "q") == 0 &&
8349 status == GOT_STATUS_MODIFY) {
8350 *choice = GOT_PATCH_CHOICE_QUIT;
8351 printf("q\n");
8352 } else
8353 printf("invalid response '%s'\n", line);
8354 free(line);
8355 return NULL;
8358 while (resp != 'y' && resp != 'n' && resp != 'q') {
8359 err = show_change(status, path, patch_file, n, nchanges,
8360 a->action);
8361 if (err)
8362 return err;
8363 resp = getchar();
8364 if (resp == '\n')
8365 resp = getchar();
8366 if (status == GOT_STATUS_MODIFY) {
8367 if (resp != 'y' && resp != 'n' && resp != 'q') {
8368 printf("invalid response '%c'\n", resp);
8369 resp = ' ';
8371 } else if (resp != 'y' && resp != 'n') {
8372 printf("invalid response '%c'\n", resp);
8373 resp = ' ';
8377 if (resp == 'y')
8378 *choice = GOT_PATCH_CHOICE_YES;
8379 else if (resp == 'n')
8380 *choice = GOT_PATCH_CHOICE_NO;
8381 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8382 *choice = GOT_PATCH_CHOICE_QUIT;
8384 return NULL;
8387 struct wt_commitable_path_arg {
8388 struct got_pathlist_head *commit_paths;
8389 int *has_changes;
8393 * Shortcut work tree status callback to determine if the set of paths scanned
8394 * has at least one versioned path that is being modified and, if not NULL, is
8395 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8396 * soon as a path is passed with a status that satisfies this criteria.
8398 static const struct got_error *
8399 worktree_has_commitable_path(void *arg, unsigned char status,
8400 unsigned char staged_status, const char *path,
8401 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8402 struct got_object_id *commit_id, int dirfd, const char *de_name)
8404 struct wt_commitable_path_arg *a = arg;
8406 if (status == staged_status && (status == GOT_STATUS_DELETE))
8407 status = GOT_STATUS_NO_CHANGE;
8409 if (!(status == GOT_STATUS_NO_CHANGE ||
8410 status == GOT_STATUS_UNVERSIONED) ||
8411 staged_status != GOT_STATUS_NO_CHANGE) {
8412 if (a->commit_paths != NULL) {
8413 struct got_pathlist_entry *pe;
8415 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8416 if (strncmp(path, pe->path,
8417 pe->path_len) == 0) {
8418 *a->has_changes = 1;
8419 break;
8422 } else
8423 *a->has_changes = 1;
8425 if (*a->has_changes)
8426 return got_error(GOT_ERR_FILE_MODIFIED);
8429 return NULL;
8433 * Check that the changeset of the commit identified by id is
8434 * comprised of at least one modified path that is being committed.
8436 static const struct got_error *
8437 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8438 struct got_object_id *id, struct got_worktree *worktree,
8439 struct got_repository *repo)
8441 const struct got_error *err;
8442 struct got_pathlist_head paths;
8443 struct got_commit_object *commit = NULL, *pcommit = NULL;
8444 struct got_tree_object *tree = NULL, *ptree = NULL;
8445 struct got_object_qid *pid;
8447 TAILQ_INIT(&paths);
8449 err = got_object_open_as_commit(&commit, repo, id);
8450 if (err)
8451 goto done;
8453 err = got_object_open_as_tree(&tree, repo,
8454 got_object_commit_get_tree_id(commit));
8455 if (err)
8456 goto done;
8458 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8459 if (pid != NULL) {
8460 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8461 if (err)
8462 goto done;
8464 err = got_object_open_as_tree(&ptree, repo,
8465 got_object_commit_get_tree_id(pcommit));
8466 if (err)
8467 goto done;
8470 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8471 got_diff_tree_collect_changed_paths, &paths, 0);
8472 if (err)
8473 goto done;
8475 err = got_worktree_status(worktree, &paths, repo, 0,
8476 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8477 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8479 * At least one changed path in the referenced commit is
8480 * modified in the work tree, that's all we need to know!
8482 err = NULL;
8485 done:
8486 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8487 if (commit)
8488 got_object_commit_close(commit);
8489 if (pcommit)
8490 got_object_commit_close(pcommit);
8491 if (tree)
8492 got_object_tree_close(tree);
8493 if (ptree)
8494 got_object_tree_close(ptree);
8495 return err;
8499 * Remove any "logmsg" reference comprised entirely of paths that have
8500 * been reverted in this work tree. If any path in the logmsg ref changeset
8501 * remains in a changed state in the worktree, do not remove the reference.
8503 static const struct got_error *
8504 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8506 const struct got_error *err;
8507 struct got_reflist_head refs;
8508 struct got_reflist_entry *re;
8509 struct got_commit_object *commit = NULL;
8510 struct got_object_id *commit_id = NULL;
8511 struct wt_commitable_path_arg wcpa;
8512 char *uuidstr = NULL;
8514 TAILQ_INIT(&refs);
8516 err = got_worktree_get_uuid(&uuidstr, worktree);
8517 if (err)
8518 goto done;
8520 err = got_ref_list(&refs, repo, "refs/got/worktree",
8521 got_ref_cmp_by_name, repo);
8522 if (err)
8523 goto done;
8525 TAILQ_FOREACH(re, &refs, entry) {
8526 const char *refname;
8527 int has_changes = 0;
8529 refname = got_ref_get_name(re->ref);
8531 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8532 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8533 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8534 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8535 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8536 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8537 else
8538 continue;
8540 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8541 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8542 else
8543 continue;
8545 err = got_repo_match_object_id(&commit_id, NULL, refname,
8546 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8547 if (err)
8548 goto done;
8550 err = got_object_open_as_commit(&commit, repo, commit_id);
8551 if (err)
8552 goto done;
8554 wcpa.commit_paths = NULL;
8555 wcpa.has_changes = &has_changes;
8557 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8558 worktree, repo);
8559 if (err)
8560 goto done;
8562 if (!has_changes) {
8563 err = got_ref_delete(re->ref, repo);
8564 if (err)
8565 goto done;
8568 got_object_commit_close(commit);
8569 commit = NULL;
8570 free(commit_id);
8571 commit_id = NULL;
8574 done:
8575 free(uuidstr);
8576 free(commit_id);
8577 got_ref_list_free(&refs);
8578 if (commit)
8579 got_object_commit_close(commit);
8580 return err;
8583 static const struct got_error *
8584 cmd_revert(int argc, char *argv[])
8586 const struct got_error *error = NULL;
8587 struct got_worktree *worktree = NULL;
8588 struct got_repository *repo = NULL;
8589 char *cwd = NULL, *path = NULL;
8590 struct got_pathlist_head paths;
8591 struct got_pathlist_entry *pe;
8592 int ch, can_recurse = 0, pflag = 0;
8593 FILE *patch_script_file = NULL;
8594 const char *patch_script_path = NULL;
8595 struct choose_patch_arg cpa;
8596 int *pack_fds = NULL;
8598 TAILQ_INIT(&paths);
8600 #ifndef PROFILE
8601 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8602 "unveil", NULL) == -1)
8603 err(1, "pledge");
8604 #endif
8606 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8607 switch (ch) {
8608 case 'F':
8609 patch_script_path = optarg;
8610 break;
8611 case 'p':
8612 pflag = 1;
8613 break;
8614 case 'R':
8615 can_recurse = 1;
8616 break;
8617 default:
8618 usage_revert();
8619 /* NOTREACHED */
8623 argc -= optind;
8624 argv += optind;
8626 if (argc < 1)
8627 usage_revert();
8628 if (patch_script_path && !pflag)
8629 errx(1, "-F option can only be used together with -p option");
8631 cwd = getcwd(NULL, 0);
8632 if (cwd == NULL) {
8633 error = got_error_from_errno("getcwd");
8634 goto done;
8637 error = got_repo_pack_fds_open(&pack_fds);
8638 if (error != NULL)
8639 goto done;
8641 error = got_worktree_open(&worktree, cwd);
8642 if (error) {
8643 if (error->code == GOT_ERR_NOT_WORKTREE)
8644 error = wrap_not_worktree_error(error, "revert", cwd);
8645 goto done;
8648 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8649 NULL, pack_fds);
8650 if (error != NULL)
8651 goto done;
8653 if (patch_script_path) {
8654 patch_script_file = fopen(patch_script_path, "re");
8655 if (patch_script_file == NULL) {
8656 error = got_error_from_errno2("fopen",
8657 patch_script_path);
8658 goto done;
8663 * XXX "c" perm needed on repo dir to delete merge references.
8665 error = apply_unveil(got_repo_get_path(repo), 0,
8666 got_worktree_get_root_path(worktree));
8667 if (error)
8668 goto done;
8670 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8671 if (error)
8672 goto done;
8674 if (!can_recurse) {
8675 char *ondisk_path;
8676 struct stat sb;
8677 TAILQ_FOREACH(pe, &paths, entry) {
8678 if (asprintf(&ondisk_path, "%s/%s",
8679 got_worktree_get_root_path(worktree),
8680 pe->path) == -1) {
8681 error = got_error_from_errno("asprintf");
8682 goto done;
8684 if (lstat(ondisk_path, &sb) == -1) {
8685 if (errno == ENOENT) {
8686 free(ondisk_path);
8687 continue;
8689 error = got_error_from_errno2("lstat",
8690 ondisk_path);
8691 free(ondisk_path);
8692 goto done;
8694 free(ondisk_path);
8695 if (S_ISDIR(sb.st_mode)) {
8696 error = got_error_msg(GOT_ERR_BAD_PATH,
8697 "reverting directories requires -R option");
8698 goto done;
8703 cpa.patch_script_file = patch_script_file;
8704 cpa.action = "revert";
8705 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8706 pflag ? choose_patch : NULL, &cpa, repo);
8708 error = rm_logmsg_ref(worktree, repo);
8709 done:
8710 if (patch_script_file && fclose(patch_script_file) == EOF &&
8711 error == NULL)
8712 error = got_error_from_errno2("fclose", patch_script_path);
8713 if (repo) {
8714 const struct got_error *close_err = got_repo_close(repo);
8715 if (error == NULL)
8716 error = close_err;
8718 if (worktree)
8719 got_worktree_close(worktree);
8720 if (pack_fds) {
8721 const struct got_error *pack_err =
8722 got_repo_pack_fds_close(pack_fds);
8723 if (error == NULL)
8724 error = pack_err;
8726 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8727 free(path);
8728 free(cwd);
8729 return error;
8732 __dead static void
8733 usage_commit(void)
8735 fprintf(stderr, "usage: %s commit [-NnS] [-A author] [-F path] "
8736 "[-m message] [path ...]\n", getprogname());
8737 exit(1);
8740 struct collect_commit_logmsg_arg {
8741 const char *cmdline_log;
8742 const char *prepared_log;
8743 const char *merged_log;
8744 int non_interactive;
8745 const char *editor;
8746 const char *worktree_path;
8747 const char *branch_name;
8748 const char *repo_path;
8749 char *logmsg_path;
8753 static const struct got_error *
8754 read_prepared_logmsg(char **logmsg, const char *path)
8756 const struct got_error *err = NULL;
8757 FILE *f = NULL;
8758 struct stat sb;
8759 size_t r;
8761 *logmsg = NULL;
8762 memset(&sb, 0, sizeof(sb));
8764 f = fopen(path, "re");
8765 if (f == NULL)
8766 return got_error_from_errno2("fopen", path);
8768 if (fstat(fileno(f), &sb) == -1) {
8769 err = got_error_from_errno2("fstat", path);
8770 goto done;
8772 if (sb.st_size == 0) {
8773 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8774 goto done;
8777 *logmsg = malloc(sb.st_size + 1);
8778 if (*logmsg == NULL) {
8779 err = got_error_from_errno("malloc");
8780 goto done;
8783 r = fread(*logmsg, 1, sb.st_size, f);
8784 if (r != sb.st_size) {
8785 if (ferror(f))
8786 err = got_error_from_errno2("fread", path);
8787 else
8788 err = got_error(GOT_ERR_IO);
8789 goto done;
8791 (*logmsg)[sb.st_size] = '\0';
8792 done:
8793 if (fclose(f) == EOF && err == NULL)
8794 err = got_error_from_errno2("fclose", path);
8795 if (err) {
8796 free(*logmsg);
8797 *logmsg = NULL;
8799 return err;
8802 static const struct got_error *
8803 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8804 const char *diff_path, char **logmsg, void *arg)
8806 char *initial_content = NULL;
8807 struct got_pathlist_entry *pe;
8808 const struct got_error *err = NULL;
8809 char *template = NULL;
8810 char *prepared_msg = NULL, *merged_msg = NULL;
8811 struct collect_commit_logmsg_arg *a = arg;
8812 int initial_content_len;
8813 int fd = -1;
8814 size_t len;
8816 /* if a message was specified on the command line, just use it */
8817 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8818 len = strlen(a->cmdline_log) + 1;
8819 *logmsg = malloc(len + 1);
8820 if (*logmsg == NULL)
8821 return got_error_from_errno("malloc");
8822 strlcpy(*logmsg, a->cmdline_log, len);
8823 return NULL;
8824 } else if (a->prepared_log != NULL && a->non_interactive)
8825 return read_prepared_logmsg(logmsg, a->prepared_log);
8827 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8828 return got_error_from_errno("asprintf");
8830 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8831 if (err)
8832 goto done;
8834 if (a->prepared_log) {
8835 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8836 if (err)
8837 goto done;
8838 } else if (a->merged_log) {
8839 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8840 if (err)
8841 goto done;
8844 initial_content_len = asprintf(&initial_content,
8845 "%s%s\n# changes to be committed on branch %s:\n",
8846 prepared_msg ? prepared_msg : "",
8847 merged_msg ? merged_msg : "", a->branch_name);
8848 if (initial_content_len == -1) {
8849 err = got_error_from_errno("asprintf");
8850 goto done;
8853 if (write(fd, initial_content, initial_content_len) == -1) {
8854 err = got_error_from_errno2("write", a->logmsg_path);
8855 goto done;
8858 TAILQ_FOREACH(pe, commitable_paths, entry) {
8859 struct got_commitable *ct = pe->data;
8860 dprintf(fd, "# %c %s\n",
8861 got_commitable_get_status(ct),
8862 got_commitable_get_path(ct));
8865 if (diff_path) {
8866 dprintf(fd, "# detailed changes can be viewed in %s\n",
8867 diff_path);
8870 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8871 initial_content_len, a->prepared_log ? 0 : 1);
8872 done:
8873 free(initial_content);
8874 free(template);
8875 free(prepared_msg);
8876 free(merged_msg);
8878 if (fd != -1 && close(fd) == -1 && err == NULL)
8879 err = got_error_from_errno2("close", a->logmsg_path);
8881 /* Editor is done; we can now apply unveil(2) */
8882 if (err == NULL)
8883 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8884 if (err) {
8885 free(*logmsg);
8886 *logmsg = NULL;
8888 return err;
8891 static const struct got_error *
8892 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8893 const char *type, int has_content)
8895 const struct got_error *err = NULL;
8896 char *logmsg = NULL;
8898 err = got_object_commit_get_logmsg(&logmsg, commit);
8899 if (err)
8900 return err;
8902 if (fprintf(f, "%s# log message of %s commit %s:%s",
8903 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8904 err = got_ferror(f, GOT_ERR_IO);
8906 free(logmsg);
8907 return err;
8911 * Lookup "logmsg" references of backed-out and cherrypicked commits
8912 * belonging to the current work tree. If found, and the worktree has
8913 * at least one modified file that was changed in the referenced commit,
8914 * add its log message to a new temporary file at *logmsg_path.
8915 * Add all refs found to matched_refs to be scheduled for removal on
8916 * successful commit.
8918 static const struct got_error *
8919 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8920 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8921 struct got_repository *repo)
8923 const struct got_error *err;
8924 struct got_commit_object *commit = NULL;
8925 struct got_object_id *id = NULL;
8926 struct got_reflist_head refs;
8927 struct got_reflist_entry *re, *re_match;
8928 FILE *f = NULL;
8929 char *uuidstr = NULL;
8930 int added_logmsg = 0;
8932 TAILQ_INIT(&refs);
8934 *logmsg_path = NULL;
8936 err = got_worktree_get_uuid(&uuidstr, worktree);
8937 if (err)
8938 goto done;
8940 err = got_ref_list(&refs, repo, "refs/got/worktree",
8941 got_ref_cmp_by_name, repo);
8942 if (err)
8943 goto done;
8945 TAILQ_FOREACH(re, &refs, entry) {
8946 const char *refname, *type;
8947 struct wt_commitable_path_arg wcpa;
8948 int add_logmsg = 0;
8950 refname = got_ref_get_name(re->ref);
8952 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8953 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8954 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8955 type = "cherrypicked";
8956 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8957 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8958 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8959 type = "backed-out";
8960 } else
8961 continue;
8963 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8964 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8965 else
8966 continue;
8968 err = got_repo_match_object_id(&id, NULL, refname,
8969 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8970 if (err)
8971 goto done;
8973 err = got_object_open_as_commit(&commit, repo, id);
8974 if (err)
8975 goto done;
8977 wcpa.commit_paths = paths;
8978 wcpa.has_changes = &add_logmsg;
8980 err = commit_path_changed_in_worktree(&wcpa, id,
8981 worktree, repo);
8982 if (err)
8983 goto done;
8985 if (add_logmsg) {
8986 if (f == NULL) {
8987 err = got_opentemp_named(logmsg_path, &f,
8988 "got-commit-logmsg", "");
8989 if (err)
8990 goto done;
8992 err = cat_logmsg(f, commit, refname, type,
8993 added_logmsg);
8994 if (err)
8995 goto done;
8996 if (!added_logmsg)
8997 ++added_logmsg;
8999 err = got_reflist_entry_dup(&re_match, re);
9000 if (err)
9001 goto done;
9002 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9005 got_object_commit_close(commit);
9006 commit = NULL;
9007 free(id);
9008 id = NULL;
9011 done:
9012 free(id);
9013 free(uuidstr);
9014 got_ref_list_free(&refs);
9015 if (commit)
9016 got_object_commit_close(commit);
9017 if (f && fclose(f) == EOF && err == NULL)
9018 err = got_error_from_errno("fclose");
9019 if (!added_logmsg) {
9020 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9021 err = got_error_from_errno2("unlink", *logmsg_path);
9022 *logmsg_path = NULL;
9024 return err;
9027 static const struct got_error *
9028 cmd_commit(int argc, char *argv[])
9030 const struct got_error *error = NULL;
9031 struct got_worktree *worktree = NULL;
9032 struct got_repository *repo = NULL;
9033 char *cwd = NULL, *id_str = NULL;
9034 struct got_object_id *id = NULL;
9035 const char *logmsg = NULL;
9036 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9037 struct collect_commit_logmsg_arg cl_arg;
9038 const char *author = NULL;
9039 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9040 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9041 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9042 int show_diff = 1;
9043 struct got_pathlist_head paths;
9044 struct got_reflist_head refs;
9045 struct got_reflist_entry *re;
9046 int *pack_fds = NULL;
9048 TAILQ_INIT(&refs);
9049 TAILQ_INIT(&paths);
9050 cl_arg.logmsg_path = NULL;
9052 #ifndef PROFILE
9053 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9054 "unveil", NULL) == -1)
9055 err(1, "pledge");
9056 #endif
9058 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9059 switch (ch) {
9060 case 'A':
9061 author = optarg;
9062 error = valid_author(author);
9063 if (error)
9064 return error;
9065 break;
9066 case 'F':
9067 if (logmsg != NULL)
9068 option_conflict('F', 'm');
9069 prepared_logmsg = realpath(optarg, NULL);
9070 if (prepared_logmsg == NULL)
9071 return got_error_from_errno2("realpath",
9072 optarg);
9073 break;
9074 case 'm':
9075 if (prepared_logmsg)
9076 option_conflict('m', 'F');
9077 logmsg = optarg;
9078 break;
9079 case 'N':
9080 non_interactive = 1;
9081 break;
9082 case 'n':
9083 show_diff = 0;
9084 break;
9085 case 'S':
9086 allow_bad_symlinks = 1;
9087 break;
9088 default:
9089 usage_commit();
9090 /* NOTREACHED */
9094 argc -= optind;
9095 argv += optind;
9097 cwd = getcwd(NULL, 0);
9098 if (cwd == NULL) {
9099 error = got_error_from_errno("getcwd");
9100 goto done;
9103 error = got_repo_pack_fds_open(&pack_fds);
9104 if (error != NULL)
9105 goto done;
9107 error = got_worktree_open(&worktree, cwd);
9108 if (error) {
9109 if (error->code == GOT_ERR_NOT_WORKTREE)
9110 error = wrap_not_worktree_error(error, "commit", cwd);
9111 goto done;
9114 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9115 if (error)
9116 goto done;
9117 if (rebase_in_progress) {
9118 error = got_error(GOT_ERR_REBASING);
9119 goto done;
9122 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9123 worktree);
9124 if (error)
9125 goto done;
9127 error = get_gitconfig_path(&gitconfig_path);
9128 if (error)
9129 goto done;
9130 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9131 gitconfig_path, pack_fds);
9132 if (error != NULL)
9133 goto done;
9135 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9136 if (error)
9137 goto done;
9138 if (merge_in_progress) {
9139 error = got_error(GOT_ERR_MERGE_BUSY);
9140 goto done;
9143 error = get_author(&committer, repo, worktree);
9144 if (error)
9145 goto done;
9147 if (author == NULL)
9148 author = committer;
9151 * unveil(2) traverses exec(2); if an editor is used we have
9152 * to apply unveil after the log message has been written.
9154 if (logmsg == NULL || strlen(logmsg) == 0)
9155 error = get_editor(&editor);
9156 else
9157 error = apply_unveil(got_repo_get_path(repo), 0,
9158 got_worktree_get_root_path(worktree));
9159 if (error)
9160 goto done;
9162 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9163 if (error)
9164 goto done;
9166 if (prepared_logmsg == NULL) {
9167 error = lookup_logmsg_ref(&merged_logmsg,
9168 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9169 if (error)
9170 goto done;
9173 cl_arg.editor = editor;
9174 cl_arg.cmdline_log = logmsg;
9175 cl_arg.prepared_log = prepared_logmsg;
9176 cl_arg.merged_log = merged_logmsg;
9177 cl_arg.non_interactive = non_interactive;
9178 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9179 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9180 if (!histedit_in_progress) {
9181 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9182 error = got_error(GOT_ERR_COMMIT_BRANCH);
9183 goto done;
9185 cl_arg.branch_name += 11;
9187 cl_arg.repo_path = got_repo_get_path(repo);
9188 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9189 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9190 print_status, NULL, repo);
9191 if (error) {
9192 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9193 cl_arg.logmsg_path != NULL)
9194 preserve_logmsg = 1;
9195 goto done;
9198 error = got_object_id_str(&id_str, id);
9199 if (error)
9200 goto done;
9201 printf("Created commit %s\n", id_str);
9203 TAILQ_FOREACH(re, &refs, entry) {
9204 error = got_ref_delete(re->ref, repo);
9205 if (error)
9206 goto done;
9209 done:
9210 if (preserve_logmsg) {
9211 fprintf(stderr, "%s: log message preserved in %s\n",
9212 getprogname(), cl_arg.logmsg_path);
9213 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9214 error == NULL)
9215 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9216 free(cl_arg.logmsg_path);
9217 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9218 error = got_error_from_errno2("unlink", merged_logmsg);
9219 free(merged_logmsg);
9220 if (repo) {
9221 const struct got_error *close_err = got_repo_close(repo);
9222 if (error == NULL)
9223 error = close_err;
9225 if (worktree)
9226 got_worktree_close(worktree);
9227 if (pack_fds) {
9228 const struct got_error *pack_err =
9229 got_repo_pack_fds_close(pack_fds);
9230 if (error == NULL)
9231 error = pack_err;
9233 got_ref_list_free(&refs);
9234 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9235 free(cwd);
9236 free(id_str);
9237 free(gitconfig_path);
9238 free(editor);
9239 free(committer);
9240 free(prepared_logmsg);
9241 return error;
9244 __dead static void
9245 usage_send(void)
9247 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9248 "[-r repository-path] [-t tag] [remote-repository]\n",
9249 getprogname());
9250 exit(1);
9253 static void
9254 print_load_info(int print_colored, int print_found, int print_trees,
9255 int ncolored, int nfound, int ntrees)
9257 if (print_colored) {
9258 printf("%d commit%s colored", ncolored,
9259 ncolored == 1 ? "" : "s");
9261 if (print_found) {
9262 printf("%s%d object%s found",
9263 ncolored > 0 ? "; " : "",
9264 nfound, nfound == 1 ? "" : "s");
9266 if (print_trees) {
9267 printf("; %d tree%s scanned", ntrees,
9268 ntrees == 1 ? "" : "s");
9272 struct got_send_progress_arg {
9273 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9274 int verbosity;
9275 int last_ncolored;
9276 int last_nfound;
9277 int last_ntrees;
9278 int loading_done;
9279 int last_ncommits;
9280 int last_nobj_total;
9281 int last_p_deltify;
9282 int last_p_written;
9283 int last_p_sent;
9284 int printed_something;
9285 int sent_something;
9286 struct got_pathlist_head *delete_branches;
9289 static const struct got_error *
9290 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9291 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9292 int nobj_written, off_t bytes_sent, const char *refname,
9293 const char *errmsg, int success)
9295 struct got_send_progress_arg *a = arg;
9296 char scaled_packsize[FMT_SCALED_STRSIZE];
9297 char scaled_sent[FMT_SCALED_STRSIZE];
9298 int p_deltify = 0, p_written = 0, p_sent = 0;
9299 int print_colored = 0, print_found = 0, print_trees = 0;
9300 int print_searching = 0, print_total = 0;
9301 int print_deltify = 0, print_written = 0, print_sent = 0;
9303 if (a->verbosity < 0)
9304 return NULL;
9306 if (refname) {
9307 const char *status = success ? "accepted" : "rejected";
9309 if (success) {
9310 struct got_pathlist_entry *pe;
9311 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9312 const char *branchname = pe->path;
9313 if (got_path_cmp(branchname, refname,
9314 strlen(branchname), strlen(refname)) == 0) {
9315 status = "deleted";
9316 a->sent_something = 1;
9317 break;
9322 if (a->printed_something)
9323 putchar('\n');
9324 printf("Server has %s %s", status, refname);
9325 if (errmsg)
9326 printf(": %s", errmsg);
9327 a->printed_something = 1;
9328 return NULL;
9331 if (a->last_ncolored != ncolored) {
9332 print_colored = 1;
9333 a->last_ncolored = ncolored;
9336 if (a->last_nfound != nfound) {
9337 print_colored = 1;
9338 print_found = 1;
9339 a->last_nfound = nfound;
9342 if (a->last_ntrees != ntrees) {
9343 print_colored = 1;
9344 print_found = 1;
9345 print_trees = 1;
9346 a->last_ntrees = ntrees;
9349 if ((print_colored || print_found || print_trees) &&
9350 !a->loading_done) {
9351 printf("\r");
9352 print_load_info(print_colored, print_found, print_trees,
9353 ncolored, nfound, ntrees);
9354 a->printed_something = 1;
9355 fflush(stdout);
9356 return NULL;
9357 } else if (!a->loading_done) {
9358 printf("\r");
9359 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9360 printf("\n");
9361 a->loading_done = 1;
9364 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9365 return got_error_from_errno("fmt_scaled");
9366 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9367 return got_error_from_errno("fmt_scaled");
9369 if (a->last_ncommits != ncommits) {
9370 print_searching = 1;
9371 a->last_ncommits = ncommits;
9374 if (a->last_nobj_total != nobj_total) {
9375 print_searching = 1;
9376 print_total = 1;
9377 a->last_nobj_total = nobj_total;
9380 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9381 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9382 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9383 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9384 return got_error(GOT_ERR_NO_SPACE);
9387 if (nobj_deltify > 0 || nobj_written > 0) {
9388 if (nobj_deltify > 0) {
9389 p_deltify = (nobj_deltify * 100) / nobj_total;
9390 if (p_deltify != a->last_p_deltify) {
9391 a->last_p_deltify = p_deltify;
9392 print_searching = 1;
9393 print_total = 1;
9394 print_deltify = 1;
9397 if (nobj_written > 0) {
9398 p_written = (nobj_written * 100) / nobj_total;
9399 if (p_written != a->last_p_written) {
9400 a->last_p_written = p_written;
9401 print_searching = 1;
9402 print_total = 1;
9403 print_deltify = 1;
9404 print_written = 1;
9409 if (bytes_sent > 0) {
9410 p_sent = (bytes_sent * 100) / packfile_size;
9411 if (p_sent != a->last_p_sent) {
9412 a->last_p_sent = p_sent;
9413 print_searching = 1;
9414 print_total = 1;
9415 print_deltify = 1;
9416 print_written = 1;
9417 print_sent = 1;
9419 a->sent_something = 1;
9422 if (print_searching || print_total || print_deltify || print_written ||
9423 print_sent)
9424 printf("\r");
9425 if (print_searching)
9426 printf("packing %d reference%s", ncommits,
9427 ncommits == 1 ? "" : "s");
9428 if (print_total)
9429 printf("; %d object%s", nobj_total,
9430 nobj_total == 1 ? "" : "s");
9431 if (print_deltify)
9432 printf("; deltify: %d%%", p_deltify);
9433 if (print_sent)
9434 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9435 scaled_packsize, p_sent);
9436 else if (print_written)
9437 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9438 scaled_packsize, p_written);
9439 if (print_searching || print_total || print_deltify ||
9440 print_written || print_sent) {
9441 a->printed_something = 1;
9442 fflush(stdout);
9444 return NULL;
9447 static const struct got_error *
9448 cmd_send(int argc, char *argv[])
9450 const struct got_error *error = NULL;
9451 char *cwd = NULL, *repo_path = NULL;
9452 const char *remote_name;
9453 char *proto = NULL, *host = NULL, *port = NULL;
9454 char *repo_name = NULL, *server_path = NULL;
9455 const struct got_remote_repo *remotes, *remote = NULL;
9456 int nremotes, nbranches = 0, ndelete_branches = 0;
9457 struct got_repository *repo = NULL;
9458 struct got_worktree *worktree = NULL;
9459 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9460 struct got_pathlist_head branches;
9461 struct got_pathlist_head tags;
9462 struct got_reflist_head all_branches;
9463 struct got_reflist_head all_tags;
9464 struct got_pathlist_head delete_args;
9465 struct got_pathlist_head delete_branches;
9466 struct got_reflist_entry *re;
9467 struct got_pathlist_entry *pe;
9468 int i, ch, sendfd = -1, sendstatus;
9469 pid_t sendpid = -1;
9470 struct got_send_progress_arg spa;
9471 int verbosity = 0, overwrite_refs = 0;
9472 int send_all_branches = 0, send_all_tags = 0;
9473 struct got_reference *ref = NULL;
9474 int *pack_fds = NULL;
9476 TAILQ_INIT(&branches);
9477 TAILQ_INIT(&tags);
9478 TAILQ_INIT(&all_branches);
9479 TAILQ_INIT(&all_tags);
9480 TAILQ_INIT(&delete_args);
9481 TAILQ_INIT(&delete_branches);
9483 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9484 switch (ch) {
9485 case 'a':
9486 send_all_branches = 1;
9487 break;
9488 case 'b':
9489 error = got_pathlist_append(&branches, optarg, NULL);
9490 if (error)
9491 return error;
9492 nbranches++;
9493 break;
9494 case 'd':
9495 error = got_pathlist_append(&delete_args, optarg, NULL);
9496 if (error)
9497 return error;
9498 break;
9499 case 'f':
9500 overwrite_refs = 1;
9501 break;
9502 case 'q':
9503 verbosity = -1;
9504 break;
9505 case 'r':
9506 repo_path = realpath(optarg, NULL);
9507 if (repo_path == NULL)
9508 return got_error_from_errno2("realpath",
9509 optarg);
9510 got_path_strip_trailing_slashes(repo_path);
9511 break;
9512 case 'T':
9513 send_all_tags = 1;
9514 break;
9515 case 't':
9516 error = got_pathlist_append(&tags, optarg, NULL);
9517 if (error)
9518 return error;
9519 break;
9520 case 'v':
9521 if (verbosity < 0)
9522 verbosity = 0;
9523 else if (verbosity < 3)
9524 verbosity++;
9525 break;
9526 default:
9527 usage_send();
9528 /* NOTREACHED */
9531 argc -= optind;
9532 argv += optind;
9534 if (send_all_branches && !TAILQ_EMPTY(&branches))
9535 option_conflict('a', 'b');
9536 if (send_all_tags && !TAILQ_EMPTY(&tags))
9537 option_conflict('T', 't');
9540 if (argc == 0)
9541 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9542 else if (argc == 1)
9543 remote_name = argv[0];
9544 else
9545 usage_send();
9547 cwd = getcwd(NULL, 0);
9548 if (cwd == NULL) {
9549 error = got_error_from_errno("getcwd");
9550 goto done;
9553 error = got_repo_pack_fds_open(&pack_fds);
9554 if (error != NULL)
9555 goto done;
9557 if (repo_path == NULL) {
9558 error = got_worktree_open(&worktree, cwd);
9559 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9560 goto done;
9561 else
9562 error = NULL;
9563 if (worktree) {
9564 repo_path =
9565 strdup(got_worktree_get_repo_path(worktree));
9566 if (repo_path == NULL)
9567 error = got_error_from_errno("strdup");
9568 if (error)
9569 goto done;
9570 } else {
9571 repo_path = strdup(cwd);
9572 if (repo_path == NULL) {
9573 error = got_error_from_errno("strdup");
9574 goto done;
9579 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9580 if (error)
9581 goto done;
9583 if (worktree) {
9584 worktree_conf = got_worktree_get_gotconfig(worktree);
9585 if (worktree_conf) {
9586 got_gotconfig_get_remotes(&nremotes, &remotes,
9587 worktree_conf);
9588 for (i = 0; i < nremotes; i++) {
9589 if (strcmp(remotes[i].name, remote_name) == 0) {
9590 remote = &remotes[i];
9591 break;
9596 if (remote == NULL) {
9597 repo_conf = got_repo_get_gotconfig(repo);
9598 if (repo_conf) {
9599 got_gotconfig_get_remotes(&nremotes, &remotes,
9600 repo_conf);
9601 for (i = 0; i < nremotes; i++) {
9602 if (strcmp(remotes[i].name, remote_name) == 0) {
9603 remote = &remotes[i];
9604 break;
9609 if (remote == NULL) {
9610 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9611 for (i = 0; i < nremotes; i++) {
9612 if (strcmp(remotes[i].name, remote_name) == 0) {
9613 remote = &remotes[i];
9614 break;
9618 if (remote == NULL) {
9619 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9620 goto done;
9623 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9624 &repo_name, remote->send_url);
9625 if (error)
9626 goto done;
9628 if (strcmp(proto, "git") == 0) {
9629 #ifndef PROFILE
9630 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9631 "sendfd dns inet unveil", NULL) == -1)
9632 err(1, "pledge");
9633 #endif
9634 } else if (strcmp(proto, "git+ssh") == 0 ||
9635 strcmp(proto, "ssh") == 0) {
9636 #ifndef PROFILE
9637 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9638 "sendfd unveil", NULL) == -1)
9639 err(1, "pledge");
9640 #endif
9641 } else if (strcmp(proto, "http") == 0 ||
9642 strcmp(proto, "git+http") == 0) {
9643 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9644 goto done;
9645 } else {
9646 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9647 goto done;
9650 error = got_dial_apply_unveil(proto);
9651 if (error)
9652 goto done;
9654 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9655 if (error)
9656 goto done;
9658 if (send_all_branches) {
9659 error = got_ref_list(&all_branches, repo, "refs/heads",
9660 got_ref_cmp_by_name, NULL);
9661 if (error)
9662 goto done;
9663 TAILQ_FOREACH(re, &all_branches, entry) {
9664 const char *branchname = got_ref_get_name(re->ref);
9665 error = got_pathlist_append(&branches,
9666 branchname, NULL);
9667 if (error)
9668 goto done;
9669 nbranches++;
9671 } else if (nbranches == 0) {
9672 for (i = 0; i < remote->nsend_branches; i++) {
9673 error = got_pathlist_append(&branches,
9674 remote->send_branches[i], NULL);
9675 if (error)
9676 goto done;
9680 if (send_all_tags) {
9681 error = got_ref_list(&all_tags, repo, "refs/tags",
9682 got_ref_cmp_by_name, NULL);
9683 if (error)
9684 goto done;
9685 TAILQ_FOREACH(re, &all_tags, entry) {
9686 const char *tagname = got_ref_get_name(re->ref);
9687 error = got_pathlist_append(&tags,
9688 tagname, NULL);
9689 if (error)
9690 goto done;
9695 * To prevent accidents only branches in refs/heads/ can be deleted
9696 * with 'got send -d'.
9697 * Deleting anything else requires local repository access or Git.
9699 TAILQ_FOREACH(pe, &delete_args, entry) {
9700 const char *branchname = pe->path;
9701 char *s;
9702 struct got_pathlist_entry *new;
9703 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9704 s = strdup(branchname);
9705 if (s == NULL) {
9706 error = got_error_from_errno("strdup");
9707 goto done;
9709 } else {
9710 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9711 error = got_error_from_errno("asprintf");
9712 goto done;
9715 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9716 if (error || new == NULL /* duplicate */)
9717 free(s);
9718 if (error)
9719 goto done;
9720 ndelete_branches++;
9723 if (nbranches == 0 && ndelete_branches == 0) {
9724 struct got_reference *head_ref;
9725 if (worktree)
9726 error = got_ref_open(&head_ref, repo,
9727 got_worktree_get_head_ref_name(worktree), 0);
9728 else
9729 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9730 if (error)
9731 goto done;
9732 if (got_ref_is_symbolic(head_ref)) {
9733 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9734 got_ref_close(head_ref);
9735 if (error)
9736 goto done;
9737 } else
9738 ref = head_ref;
9739 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9740 NULL);
9741 if (error)
9742 goto done;
9743 nbranches++;
9746 if (verbosity >= 0) {
9747 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9748 remote->name, proto, host,
9749 port ? ":" : "", port ? port : "",
9750 *server_path == '/' ? "" : "/", server_path);
9753 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9754 server_path, verbosity);
9755 if (error)
9756 goto done;
9758 memset(&spa, 0, sizeof(spa));
9759 spa.last_scaled_packsize[0] = '\0';
9760 spa.last_p_deltify = -1;
9761 spa.last_p_written = -1;
9762 spa.verbosity = verbosity;
9763 spa.delete_branches = &delete_branches;
9764 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9765 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9766 check_cancelled, NULL);
9767 if (spa.printed_something)
9768 putchar('\n');
9769 if (error)
9770 goto done;
9771 if (!spa.sent_something && verbosity >= 0)
9772 printf("Already up-to-date\n");
9773 done:
9774 if (sendpid > 0) {
9775 if (kill(sendpid, SIGTERM) == -1)
9776 error = got_error_from_errno("kill");
9777 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9778 error = got_error_from_errno("waitpid");
9780 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9781 error = got_error_from_errno("close");
9782 if (repo) {
9783 const struct got_error *close_err = got_repo_close(repo);
9784 if (error == NULL)
9785 error = close_err;
9787 if (worktree)
9788 got_worktree_close(worktree);
9789 if (pack_fds) {
9790 const struct got_error *pack_err =
9791 got_repo_pack_fds_close(pack_fds);
9792 if (error == NULL)
9793 error = pack_err;
9795 if (ref)
9796 got_ref_close(ref);
9797 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9798 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9799 got_ref_list_free(&all_branches);
9800 got_ref_list_free(&all_tags);
9801 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9802 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9803 free(cwd);
9804 free(repo_path);
9805 free(proto);
9806 free(host);
9807 free(port);
9808 free(server_path);
9809 free(repo_name);
9810 return error;
9814 * Print and if delete is set delete all ref_prefix references.
9815 * If wanted_ref is not NULL, only print or delete this reference.
9817 static const struct got_error *
9818 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9819 const char *wanted_ref, int delete, struct got_worktree *worktree,
9820 struct got_repository *repo)
9822 const struct got_error *err;
9823 struct got_pathlist_head paths;
9824 struct got_reflist_head refs;
9825 struct got_reflist_entry *re;
9826 struct got_reflist_object_id_map *refs_idmap = NULL;
9827 struct got_commit_object *commit = NULL;
9828 struct got_object_id *id = NULL;
9829 const char *header_prefix;
9830 char *uuidstr = NULL;
9831 int found = 0;
9833 TAILQ_INIT(&refs);
9834 TAILQ_INIT(&paths);
9836 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9837 if (err)
9838 goto done;
9840 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9841 if (err)
9842 goto done;
9844 if (worktree != NULL) {
9845 err = got_worktree_get_uuid(&uuidstr, worktree);
9846 if (err)
9847 goto done;
9850 if (wanted_ref) {
9851 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9852 wanted_ref += 11;
9855 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9856 header_prefix = "backout";
9857 else
9858 header_prefix = "cherrypick";
9860 TAILQ_FOREACH(re, &refs, entry) {
9861 const char *refname, *wt;
9863 refname = got_ref_get_name(re->ref);
9865 err = check_cancelled(NULL);
9866 if (err)
9867 goto done;
9869 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9870 refname += prefix_len + 1; /* skip '-' delimiter */
9871 else
9872 continue;
9874 wt = refname;
9876 if (worktree == NULL || strncmp(refname, uuidstr,
9877 GOT_WORKTREE_UUID_STRLEN) == 0)
9878 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9879 else
9880 continue;
9882 err = got_repo_match_object_id(&id, NULL, refname,
9883 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9884 if (err)
9885 goto done;
9887 err = got_object_open_as_commit(&commit, repo, id);
9888 if (err)
9889 goto done;
9891 if (wanted_ref)
9892 found = strncmp(wanted_ref, refname,
9893 strlen(wanted_ref)) == 0;
9894 if (wanted_ref && !found) {
9895 struct got_reflist_head *ci_refs;
9897 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9898 id);
9900 if (ci_refs) {
9901 char *refs_str = NULL;
9902 char const *r = NULL;
9904 err = build_refs_str(&refs_str, ci_refs, id,
9905 repo, 1);
9906 if (err)
9907 goto done;
9909 r = refs_str;
9910 while (r) {
9911 if (strncmp(r, wanted_ref,
9912 strlen(wanted_ref)) == 0) {
9913 found = 1;
9914 break;
9916 r = strchr(r, ' ');
9917 if (r)
9918 ++r;
9920 free(refs_str);
9924 if (wanted_ref == NULL || found) {
9925 if (delete) {
9926 err = got_ref_delete(re->ref, repo);
9927 if (err)
9928 goto done;
9929 printf("Deleted: ");
9930 err = print_commit_oneline(commit, id, repo,
9931 refs_idmap);
9932 } else {
9934 * Print paths modified by commit to help
9935 * associate commits with worktree changes.
9937 err = get_changed_paths(&paths, commit,
9938 repo, NULL);
9939 if (err)
9940 goto done;
9942 err = print_commit(commit, id, repo, NULL,
9943 &paths, NULL, 0, 0, refs_idmap, NULL,
9944 header_prefix);
9945 got_pathlist_free(&paths,
9946 GOT_PATHLIST_FREE_ALL);
9948 if (worktree == NULL)
9949 printf("work tree: %.*s\n\n",
9950 GOT_WORKTREE_UUID_STRLEN, wt);
9952 if (err || found)
9953 goto done;
9956 got_object_commit_close(commit);
9957 commit = NULL;
9958 free(id);
9959 id = NULL;
9962 if (wanted_ref != NULL && !found)
9963 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9965 done:
9966 free(id);
9967 free(uuidstr);
9968 got_ref_list_free(&refs);
9969 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9970 if (refs_idmap)
9971 got_reflist_object_id_map_free(refs_idmap);
9972 if (commit)
9973 got_object_commit_close(commit);
9974 return err;
9978 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9979 * identified by id for log messages to prepopulate the editor on commit.
9981 static const struct got_error *
9982 logmsg_ref(struct got_object_id *id, const char *prefix,
9983 struct got_worktree *worktree, struct got_repository *repo)
9985 const struct got_error *err = NULL;
9986 char *idstr, *ref = NULL, *refname = NULL;
9987 int histedit_in_progress;
9988 int rebase_in_progress, merge_in_progress;
9991 * Silenty refuse to create merge reference if any histedit, merge,
9992 * or rebase operation is in progress.
9994 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9995 worktree);
9996 if (err)
9997 return err;
9998 if (histedit_in_progress)
9999 return NULL;
10001 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10002 if (err)
10003 return err;
10004 if (rebase_in_progress)
10005 return NULL;
10007 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10008 repo);
10009 if (err)
10010 return err;
10011 if (merge_in_progress)
10012 return NULL;
10014 err = got_object_id_str(&idstr, id);
10015 if (err)
10016 return err;
10018 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10019 if (err)
10020 goto done;
10022 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10023 err = got_error_from_errno("asprintf");
10024 goto done;
10027 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10028 -1, repo);
10029 done:
10030 free(ref);
10031 free(idstr);
10032 free(refname);
10033 return err;
10036 __dead static void
10037 usage_cherrypick(void)
10039 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10040 getprogname());
10041 exit(1);
10044 static const struct got_error *
10045 cmd_cherrypick(int argc, char *argv[])
10047 const struct got_error *error = NULL;
10048 struct got_worktree *worktree = NULL;
10049 struct got_repository *repo = NULL;
10050 char *cwd = NULL, *commit_id_str = NULL;
10051 struct got_object_id *commit_id = NULL;
10052 struct got_commit_object *commit = NULL;
10053 struct got_object_qid *pid;
10054 int ch, list_refs = 0, remove_refs = 0;
10055 struct got_update_progress_arg upa;
10056 int *pack_fds = NULL;
10058 #ifndef PROFILE
10059 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10060 "unveil", NULL) == -1)
10061 err(1, "pledge");
10062 #endif
10064 while ((ch = getopt(argc, argv, "lX")) != -1) {
10065 switch (ch) {
10066 case 'l':
10067 list_refs = 1;
10068 break;
10069 case 'X':
10070 remove_refs = 1;
10071 break;
10072 default:
10073 usage_cherrypick();
10074 /* NOTREACHED */
10078 argc -= optind;
10079 argv += optind;
10081 if (list_refs || remove_refs) {
10082 if (argc != 0 && argc != 1)
10083 usage_cherrypick();
10084 } else if (argc != 1)
10085 usage_cherrypick();
10086 if (list_refs && remove_refs)
10087 option_conflict('l', 'X');
10089 cwd = getcwd(NULL, 0);
10090 if (cwd == NULL) {
10091 error = got_error_from_errno("getcwd");
10092 goto done;
10095 error = got_repo_pack_fds_open(&pack_fds);
10096 if (error != NULL)
10097 goto done;
10099 error = got_worktree_open(&worktree, cwd);
10100 if (error) {
10101 if (list_refs || remove_refs) {
10102 if (error->code != GOT_ERR_NOT_WORKTREE)
10103 goto done;
10104 } else {
10105 if (error->code == GOT_ERR_NOT_WORKTREE)
10106 error = wrap_not_worktree_error(error,
10107 "cherrypick", cwd);
10108 goto done;
10112 error = got_repo_open(&repo,
10113 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10114 NULL, pack_fds);
10115 if (error != NULL)
10116 goto done;
10118 error = apply_unveil(got_repo_get_path(repo), 0,
10119 worktree ? got_worktree_get_root_path(worktree) : NULL);
10120 if (error)
10121 goto done;
10123 if (list_refs || remove_refs) {
10124 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10125 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10126 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10127 goto done;
10130 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10131 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10132 if (error)
10133 goto done;
10134 error = got_object_id_str(&commit_id_str, commit_id);
10135 if (error)
10136 goto done;
10138 error = got_object_open_as_commit(&commit, repo, commit_id);
10139 if (error)
10140 goto done;
10141 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10142 memset(&upa, 0, sizeof(upa));
10143 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10144 commit_id, repo, update_progress, &upa, check_cancelled,
10145 NULL);
10146 if (error != NULL)
10147 goto done;
10149 if (upa.did_something) {
10150 error = logmsg_ref(commit_id,
10151 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10152 if (error)
10153 goto done;
10154 printf("Merged commit %s\n", commit_id_str);
10156 print_merge_progress_stats(&upa);
10157 done:
10158 free(cwd);
10159 if (commit)
10160 got_object_commit_close(commit);
10161 free(commit_id_str);
10162 if (worktree)
10163 got_worktree_close(worktree);
10164 if (repo) {
10165 const struct got_error *close_err = got_repo_close(repo);
10166 if (error == NULL)
10167 error = close_err;
10169 if (pack_fds) {
10170 const struct got_error *pack_err =
10171 got_repo_pack_fds_close(pack_fds);
10172 if (error == NULL)
10173 error = pack_err;
10176 return error;
10179 __dead static void
10180 usage_backout(void)
10182 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10183 exit(1);
10186 static const struct got_error *
10187 cmd_backout(int argc, char *argv[])
10189 const struct got_error *error = NULL;
10190 struct got_worktree *worktree = NULL;
10191 struct got_repository *repo = NULL;
10192 char *cwd = NULL, *commit_id_str = NULL;
10193 struct got_object_id *commit_id = NULL;
10194 struct got_commit_object *commit = NULL;
10195 struct got_object_qid *pid;
10196 int ch, list_refs = 0, remove_refs = 0;
10197 struct got_update_progress_arg upa;
10198 int *pack_fds = NULL;
10200 #ifndef PROFILE
10201 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10202 "unveil", NULL) == -1)
10203 err(1, "pledge");
10204 #endif
10206 while ((ch = getopt(argc, argv, "lX")) != -1) {
10207 switch (ch) {
10208 case 'l':
10209 list_refs = 1;
10210 break;
10211 case 'X':
10212 remove_refs = 1;
10213 break;
10214 default:
10215 usage_backout();
10216 /* NOTREACHED */
10220 argc -= optind;
10221 argv += optind;
10223 if (list_refs || remove_refs) {
10224 if (argc != 0 && argc != 1)
10225 usage_backout();
10226 } else if (argc != 1)
10227 usage_backout();
10228 if (list_refs && remove_refs)
10229 option_conflict('l', 'X');
10231 cwd = getcwd(NULL, 0);
10232 if (cwd == NULL) {
10233 error = got_error_from_errno("getcwd");
10234 goto done;
10237 error = got_repo_pack_fds_open(&pack_fds);
10238 if (error != NULL)
10239 goto done;
10241 error = got_worktree_open(&worktree, cwd);
10242 if (error) {
10243 if (list_refs || remove_refs) {
10244 if (error->code != GOT_ERR_NOT_WORKTREE)
10245 goto done;
10246 } else {
10247 if (error->code == GOT_ERR_NOT_WORKTREE)
10248 error = wrap_not_worktree_error(error,
10249 "backout", cwd);
10250 goto done;
10254 error = got_repo_open(&repo,
10255 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10256 NULL, pack_fds);
10257 if (error != NULL)
10258 goto done;
10260 error = apply_unveil(got_repo_get_path(repo), 0,
10261 worktree ? got_worktree_get_root_path(worktree) : NULL);
10262 if (error)
10263 goto done;
10265 if (list_refs || remove_refs) {
10266 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10267 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10268 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10269 goto done;
10272 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10273 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10274 if (error)
10275 goto done;
10276 error = got_object_id_str(&commit_id_str, commit_id);
10277 if (error)
10278 goto done;
10280 error = got_object_open_as_commit(&commit, repo, commit_id);
10281 if (error)
10282 goto done;
10283 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10284 if (pid == NULL) {
10285 error = got_error(GOT_ERR_ROOT_COMMIT);
10286 goto done;
10289 memset(&upa, 0, sizeof(upa));
10290 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10291 repo, update_progress, &upa, check_cancelled, NULL);
10292 if (error != NULL)
10293 goto done;
10295 if (upa.did_something) {
10296 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10297 worktree, repo);
10298 if (error)
10299 goto done;
10300 printf("Backed out commit %s\n", commit_id_str);
10302 print_merge_progress_stats(&upa);
10303 done:
10304 free(cwd);
10305 if (commit)
10306 got_object_commit_close(commit);
10307 free(commit_id_str);
10308 if (worktree)
10309 got_worktree_close(worktree);
10310 if (repo) {
10311 const struct got_error *close_err = got_repo_close(repo);
10312 if (error == NULL)
10313 error = close_err;
10315 if (pack_fds) {
10316 const struct got_error *pack_err =
10317 got_repo_pack_fds_close(pack_fds);
10318 if (error == NULL)
10319 error = pack_err;
10321 return error;
10324 __dead static void
10325 usage_rebase(void)
10327 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10328 exit(1);
10331 static void
10332 trim_logmsg(char *logmsg, int limit)
10334 char *nl;
10335 size_t len;
10337 len = strlen(logmsg);
10338 if (len > limit)
10339 len = limit;
10340 logmsg[len] = '\0';
10341 nl = strchr(logmsg, '\n');
10342 if (nl)
10343 *nl = '\0';
10346 static const struct got_error *
10347 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10349 const struct got_error *err;
10350 char *logmsg0 = NULL;
10351 const char *s;
10353 err = got_object_commit_get_logmsg(&logmsg0, commit);
10354 if (err)
10355 return err;
10357 s = logmsg0;
10358 while (isspace((unsigned char)s[0]))
10359 s++;
10361 *logmsg = strdup(s);
10362 if (*logmsg == NULL) {
10363 err = got_error_from_errno("strdup");
10364 goto done;
10367 trim_logmsg(*logmsg, limit);
10368 done:
10369 free(logmsg0);
10370 return err;
10373 static const struct got_error *
10374 show_rebase_merge_conflict(struct got_object_id *id,
10375 struct got_repository *repo)
10377 const struct got_error *err;
10378 struct got_commit_object *commit = NULL;
10379 char *id_str = NULL, *logmsg = NULL;
10381 err = got_object_open_as_commit(&commit, repo, id);
10382 if (err)
10383 return err;
10385 err = got_object_id_str(&id_str, id);
10386 if (err)
10387 goto done;
10389 id_str[12] = '\0';
10391 err = get_short_logmsg(&logmsg, 42, commit);
10392 if (err)
10393 goto done;
10395 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10396 done:
10397 free(id_str);
10398 got_object_commit_close(commit);
10399 free(logmsg);
10400 return err;
10403 static const struct got_error *
10404 show_rebase_progress(struct got_commit_object *commit,
10405 struct got_object_id *old_id, struct got_object_id *new_id)
10407 const struct got_error *err;
10408 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10410 err = got_object_id_str(&old_id_str, old_id);
10411 if (err)
10412 goto done;
10414 if (new_id) {
10415 err = got_object_id_str(&new_id_str, new_id);
10416 if (err)
10417 goto done;
10420 old_id_str[12] = '\0';
10421 if (new_id_str)
10422 new_id_str[12] = '\0';
10424 err = get_short_logmsg(&logmsg, 42, commit);
10425 if (err)
10426 goto done;
10428 printf("%s -> %s: %s\n", old_id_str,
10429 new_id_str ? new_id_str : "no-op change", logmsg);
10430 done:
10431 free(old_id_str);
10432 free(new_id_str);
10433 free(logmsg);
10434 return err;
10437 static const struct got_error *
10438 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10439 struct got_reference *branch, struct got_reference *tmp_branch,
10440 struct got_repository *repo, int create_backup)
10442 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10443 return got_worktree_rebase_complete(worktree, fileindex,
10444 tmp_branch, branch, repo, create_backup);
10447 static const struct got_error *
10448 rebase_commit(struct got_pathlist_head *merged_paths,
10449 struct got_worktree *worktree, struct got_fileindex *fileindex,
10450 struct got_reference *tmp_branch, const char *committer,
10451 struct got_object_id *commit_id, struct got_repository *repo)
10453 const struct got_error *error;
10454 struct got_commit_object *commit;
10455 struct got_object_id *new_commit_id;
10457 error = got_object_open_as_commit(&commit, repo, commit_id);
10458 if (error)
10459 return error;
10461 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10462 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10463 repo);
10464 if (error) {
10465 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10466 goto done;
10467 error = show_rebase_progress(commit, commit_id, NULL);
10468 } else {
10469 error = show_rebase_progress(commit, commit_id, new_commit_id);
10470 free(new_commit_id);
10472 done:
10473 got_object_commit_close(commit);
10474 return error;
10477 struct check_path_prefix_arg {
10478 const char *path_prefix;
10479 size_t len;
10480 int errcode;
10483 static const struct got_error *
10484 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10485 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10486 struct got_object_id *id1, struct got_object_id *id2,
10487 const char *path1, const char *path2,
10488 mode_t mode1, mode_t mode2, struct got_repository *repo)
10490 struct check_path_prefix_arg *a = arg;
10492 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10493 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10494 return got_error(a->errcode);
10496 return NULL;
10499 static const struct got_error *
10500 check_path_prefix(struct got_object_id *parent_id,
10501 struct got_object_id *commit_id, const char *path_prefix,
10502 int errcode, struct got_repository *repo)
10504 const struct got_error *err;
10505 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10506 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10507 struct check_path_prefix_arg cpp_arg;
10509 if (got_path_is_root_dir(path_prefix))
10510 return NULL;
10512 err = got_object_open_as_commit(&commit, repo, commit_id);
10513 if (err)
10514 goto done;
10516 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10517 if (err)
10518 goto done;
10520 err = got_object_open_as_tree(&tree1, repo,
10521 got_object_commit_get_tree_id(parent_commit));
10522 if (err)
10523 goto done;
10525 err = got_object_open_as_tree(&tree2, repo,
10526 got_object_commit_get_tree_id(commit));
10527 if (err)
10528 goto done;
10530 cpp_arg.path_prefix = path_prefix;
10531 while (cpp_arg.path_prefix[0] == '/')
10532 cpp_arg.path_prefix++;
10533 cpp_arg.len = strlen(cpp_arg.path_prefix);
10534 cpp_arg.errcode = errcode;
10535 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10536 check_path_prefix_in_diff, &cpp_arg, 0);
10537 done:
10538 if (tree1)
10539 got_object_tree_close(tree1);
10540 if (tree2)
10541 got_object_tree_close(tree2);
10542 if (commit)
10543 got_object_commit_close(commit);
10544 if (parent_commit)
10545 got_object_commit_close(parent_commit);
10546 return err;
10549 static const struct got_error *
10550 collect_commits(struct got_object_id_queue *commits,
10551 struct got_object_id *initial_commit_id,
10552 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10553 const char *path_prefix, int path_prefix_errcode,
10554 struct got_repository *repo)
10556 const struct got_error *err = NULL;
10557 struct got_commit_graph *graph = NULL;
10558 struct got_object_id parent_id, commit_id;
10559 struct got_object_qid *qid;
10561 err = got_commit_graph_open(&graph, "/", 1);
10562 if (err)
10563 return err;
10565 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10566 check_cancelled, NULL);
10567 if (err)
10568 goto done;
10570 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10571 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10572 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10573 check_cancelled, NULL);
10574 if (err) {
10575 if (err->code == GOT_ERR_ITER_COMPLETED) {
10576 err = got_error_msg(GOT_ERR_ANCESTRY,
10577 "ran out of commits to rebase before "
10578 "youngest common ancestor commit has "
10579 "been reached?!?");
10581 goto done;
10582 } else {
10583 err = check_path_prefix(&parent_id, &commit_id,
10584 path_prefix, path_prefix_errcode, repo);
10585 if (err)
10586 goto done;
10588 err = got_object_qid_alloc(&qid, &commit_id);
10589 if (err)
10590 goto done;
10591 STAILQ_INSERT_HEAD(commits, qid, entry);
10593 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10596 done:
10597 got_commit_graph_close(graph);
10598 return err;
10601 static const struct got_error *
10602 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10604 const struct got_error *err = NULL;
10605 time_t committer_time;
10606 struct tm tm;
10607 char datebuf[11]; /* YYYY-MM-DD + NUL */
10608 char *author0 = NULL, *author, *smallerthan;
10609 char *logmsg0 = NULL, *logmsg, *newline;
10611 committer_time = got_object_commit_get_committer_time(commit);
10612 if (gmtime_r(&committer_time, &tm) == NULL)
10613 return got_error_from_errno("gmtime_r");
10614 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10615 return got_error(GOT_ERR_NO_SPACE);
10617 author0 = strdup(got_object_commit_get_author(commit));
10618 if (author0 == NULL)
10619 return got_error_from_errno("strdup");
10620 author = author0;
10621 smallerthan = strchr(author, '<');
10622 if (smallerthan && smallerthan[1] != '\0')
10623 author = smallerthan + 1;
10624 author[strcspn(author, "@>")] = '\0';
10626 err = got_object_commit_get_logmsg(&logmsg0, commit);
10627 if (err)
10628 goto done;
10629 logmsg = logmsg0;
10630 while (*logmsg == '\n')
10631 logmsg++;
10632 newline = strchr(logmsg, '\n');
10633 if (newline)
10634 *newline = '\0';
10636 if (asprintf(brief_str, "%s %s %s",
10637 datebuf, author, logmsg) == -1)
10638 err = got_error_from_errno("asprintf");
10639 done:
10640 free(author0);
10641 free(logmsg0);
10642 return err;
10645 static const struct got_error *
10646 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10647 struct got_repository *repo)
10649 const struct got_error *err;
10650 char *id_str;
10652 err = got_object_id_str(&id_str, id);
10653 if (err)
10654 return err;
10656 err = got_ref_delete(ref, repo);
10657 if (err)
10658 goto done;
10660 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10661 done:
10662 free(id_str);
10663 return err;
10666 static const struct got_error *
10667 print_backup_ref(const char *branch_name, const char *new_id_str,
10668 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10669 struct got_reflist_object_id_map *refs_idmap,
10670 struct got_repository *repo)
10672 const struct got_error *err = NULL;
10673 struct got_reflist_head *refs;
10674 char *refs_str = NULL;
10675 struct got_object_id *new_commit_id = NULL;
10676 struct got_commit_object *new_commit = NULL;
10677 char *new_commit_brief_str = NULL;
10678 struct got_object_id *yca_id = NULL;
10679 struct got_commit_object *yca_commit = NULL;
10680 char *yca_id_str = NULL, *yca_brief_str = NULL;
10681 char *custom_refs_str;
10683 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10684 return got_error_from_errno("asprintf");
10686 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10687 0, 0, refs_idmap, custom_refs_str, NULL);
10688 if (err)
10689 goto done;
10691 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10692 if (err)
10693 goto done;
10695 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10696 if (refs) {
10697 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10698 if (err)
10699 goto done;
10702 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10703 if (err)
10704 goto done;
10706 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10707 if (err)
10708 goto done;
10710 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10711 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10712 if (err)
10713 goto done;
10715 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10716 refs_str ? " (" : "", refs_str ? refs_str : "",
10717 refs_str ? ")" : "", new_commit_brief_str);
10718 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10719 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10720 free(refs_str);
10721 refs_str = NULL;
10723 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10724 if (err)
10725 goto done;
10727 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10728 if (err)
10729 goto done;
10731 err = got_object_id_str(&yca_id_str, yca_id);
10732 if (err)
10733 goto done;
10735 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10736 if (refs) {
10737 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10738 if (err)
10739 goto done;
10741 printf("history forked at %s%s%s%s\n %s\n",
10742 yca_id_str,
10743 refs_str ? " (" : "", refs_str ? refs_str : "",
10744 refs_str ? ")" : "", yca_brief_str);
10746 done:
10747 free(custom_refs_str);
10748 free(new_commit_id);
10749 free(refs_str);
10750 free(yca_id);
10751 free(yca_id_str);
10752 free(yca_brief_str);
10753 if (new_commit)
10754 got_object_commit_close(new_commit);
10755 if (yca_commit)
10756 got_object_commit_close(yca_commit);
10758 return err;
10761 static const struct got_error *
10762 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10763 struct got_repository *repo)
10765 const struct got_error *err;
10766 struct got_reflist_head refs;
10767 struct got_reflist_entry *re;
10768 char *uuidstr = NULL;
10769 static char msg[160];
10771 TAILQ_INIT(&refs);
10773 err = got_worktree_get_uuid(&uuidstr, worktree);
10774 if (err)
10775 goto done;
10777 err = got_ref_list(&refs, repo, "refs/got/worktree",
10778 got_ref_cmp_by_name, repo);
10779 if (err)
10780 goto done;
10782 TAILQ_FOREACH(re, &refs, entry) {
10783 const char *cmd, *refname, *type;
10785 refname = got_ref_get_name(re->ref);
10787 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10788 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10789 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10790 cmd = "cherrypick";
10791 type = "cherrypicked";
10792 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10793 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10794 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10795 cmd = "backout";
10796 type = "backed-out";
10797 } else
10798 continue;
10800 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10801 continue;
10803 snprintf(msg, sizeof(msg),
10804 "work tree has references created by %s commits which "
10805 "must be removed with 'got %s -X' before running the %s "
10806 "command", type, cmd, caller);
10807 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10808 goto done;
10811 done:
10812 free(uuidstr);
10813 got_ref_list_free(&refs);
10814 return err;
10817 static const struct got_error *
10818 process_backup_refs(const char *backup_ref_prefix,
10819 const char *wanted_branch_name,
10820 int delete, struct got_repository *repo)
10822 const struct got_error *err;
10823 struct got_reflist_head refs, backup_refs;
10824 struct got_reflist_entry *re;
10825 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10826 struct got_object_id *old_commit_id = NULL;
10827 char *branch_name = NULL;
10828 struct got_commit_object *old_commit = NULL;
10829 struct got_reflist_object_id_map *refs_idmap = NULL;
10830 int wanted_branch_found = 0;
10832 TAILQ_INIT(&refs);
10833 TAILQ_INIT(&backup_refs);
10835 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10836 if (err)
10837 return err;
10839 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10840 if (err)
10841 goto done;
10843 if (wanted_branch_name) {
10844 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10845 wanted_branch_name += 11;
10848 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10849 got_ref_cmp_by_commit_timestamp_descending, repo);
10850 if (err)
10851 goto done;
10853 TAILQ_FOREACH(re, &backup_refs, entry) {
10854 const char *refname = got_ref_get_name(re->ref);
10855 char *slash;
10857 err = check_cancelled(NULL);
10858 if (err)
10859 break;
10861 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10862 if (err)
10863 break;
10865 err = got_object_open_as_commit(&old_commit, repo,
10866 old_commit_id);
10867 if (err)
10868 break;
10870 if (strncmp(backup_ref_prefix, refname,
10871 backup_ref_prefix_len) == 0)
10872 refname += backup_ref_prefix_len;
10874 while (refname[0] == '/')
10875 refname++;
10877 branch_name = strdup(refname);
10878 if (branch_name == NULL) {
10879 err = got_error_from_errno("strdup");
10880 break;
10882 slash = strrchr(branch_name, '/');
10883 if (slash) {
10884 *slash = '\0';
10885 refname += strlen(branch_name) + 1;
10888 if (wanted_branch_name == NULL ||
10889 strcmp(wanted_branch_name, branch_name) == 0) {
10890 wanted_branch_found = 1;
10891 if (delete) {
10892 err = delete_backup_ref(re->ref,
10893 old_commit_id, repo);
10894 } else {
10895 err = print_backup_ref(branch_name, refname,
10896 old_commit_id, old_commit, refs_idmap,
10897 repo);
10899 if (err)
10900 break;
10903 free(old_commit_id);
10904 old_commit_id = NULL;
10905 free(branch_name);
10906 branch_name = NULL;
10907 got_object_commit_close(old_commit);
10908 old_commit = NULL;
10911 if (wanted_branch_name && !wanted_branch_found) {
10912 err = got_error_fmt(GOT_ERR_NOT_REF,
10913 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10915 done:
10916 if (refs_idmap)
10917 got_reflist_object_id_map_free(refs_idmap);
10918 got_ref_list_free(&refs);
10919 got_ref_list_free(&backup_refs);
10920 free(old_commit_id);
10921 free(branch_name);
10922 if (old_commit)
10923 got_object_commit_close(old_commit);
10924 return err;
10927 static const struct got_error *
10928 abort_progress(void *arg, unsigned char status, const char *path)
10931 * Unversioned files should not clutter progress output when
10932 * an operation is aborted.
10934 if (status == GOT_STATUS_UNVERSIONED)
10935 return NULL;
10937 return update_progress(arg, status, path);
10940 static const struct got_error *
10941 cmd_rebase(int argc, char *argv[])
10943 const struct got_error *error = NULL;
10944 struct got_worktree *worktree = NULL;
10945 struct got_repository *repo = NULL;
10946 struct got_fileindex *fileindex = NULL;
10947 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10948 struct got_reference *branch = NULL;
10949 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10950 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10951 struct got_object_id *resume_commit_id = NULL;
10952 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10953 struct got_object_id *head_commit_id = NULL;
10954 struct got_reference *head_ref = NULL;
10955 struct got_commit_object *commit = NULL;
10956 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10957 int histedit_in_progress = 0, merge_in_progress = 0;
10958 int create_backup = 1, list_backups = 0, delete_backups = 0;
10959 struct got_object_id_queue commits;
10960 struct got_pathlist_head merged_paths;
10961 const struct got_object_id_queue *parent_ids;
10962 struct got_object_qid *qid, *pid;
10963 struct got_update_progress_arg upa;
10964 int *pack_fds = NULL;
10966 STAILQ_INIT(&commits);
10967 TAILQ_INIT(&merged_paths);
10968 memset(&upa, 0, sizeof(upa));
10970 #ifndef PROFILE
10971 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10972 "unveil", NULL) == -1)
10973 err(1, "pledge");
10974 #endif
10976 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10977 switch (ch) {
10978 case 'a':
10979 abort_rebase = 1;
10980 break;
10981 case 'c':
10982 continue_rebase = 1;
10983 break;
10984 case 'l':
10985 list_backups = 1;
10986 break;
10987 case 'X':
10988 delete_backups = 1;
10989 break;
10990 default:
10991 usage_rebase();
10992 /* NOTREACHED */
10996 argc -= optind;
10997 argv += optind;
10999 if (list_backups) {
11000 if (abort_rebase)
11001 option_conflict('l', 'a');
11002 if (continue_rebase)
11003 option_conflict('l', 'c');
11004 if (delete_backups)
11005 option_conflict('l', 'X');
11006 if (argc != 0 && argc != 1)
11007 usage_rebase();
11008 } else if (delete_backups) {
11009 if (abort_rebase)
11010 option_conflict('X', 'a');
11011 if (continue_rebase)
11012 option_conflict('X', 'c');
11013 if (list_backups)
11014 option_conflict('l', 'X');
11015 if (argc != 0 && argc != 1)
11016 usage_rebase();
11017 } else {
11018 if (abort_rebase && continue_rebase)
11019 usage_rebase();
11020 else if (abort_rebase || continue_rebase) {
11021 if (argc != 0)
11022 usage_rebase();
11023 } else if (argc != 1)
11024 usage_rebase();
11027 cwd = getcwd(NULL, 0);
11028 if (cwd == NULL) {
11029 error = got_error_from_errno("getcwd");
11030 goto done;
11033 error = got_repo_pack_fds_open(&pack_fds);
11034 if (error != NULL)
11035 goto done;
11037 error = got_worktree_open(&worktree, cwd);
11038 if (error) {
11039 if (list_backups || delete_backups) {
11040 if (error->code != GOT_ERR_NOT_WORKTREE)
11041 goto done;
11042 } else {
11043 if (error->code == GOT_ERR_NOT_WORKTREE)
11044 error = wrap_not_worktree_error(error,
11045 "rebase", cwd);
11046 goto done;
11050 error = get_gitconfig_path(&gitconfig_path);
11051 if (error)
11052 goto done;
11053 error = got_repo_open(&repo,
11054 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11055 gitconfig_path, pack_fds);
11056 if (error != NULL)
11057 goto done;
11059 if (worktree != NULL && !list_backups && !delete_backups) {
11060 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11061 if (error)
11062 goto done;
11065 error = get_author(&committer, repo, worktree);
11066 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11067 goto done;
11069 error = apply_unveil(got_repo_get_path(repo), 0,
11070 worktree ? got_worktree_get_root_path(worktree) : NULL);
11071 if (error)
11072 goto done;
11074 if (list_backups || delete_backups) {
11075 error = process_backup_refs(
11076 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11077 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11078 goto done; /* nothing else to do */
11081 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11082 worktree);
11083 if (error)
11084 goto done;
11085 if (histedit_in_progress) {
11086 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11087 goto done;
11090 error = got_worktree_merge_in_progress(&merge_in_progress,
11091 worktree, repo);
11092 if (error)
11093 goto done;
11094 if (merge_in_progress) {
11095 error = got_error(GOT_ERR_MERGE_BUSY);
11096 goto done;
11099 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11100 if (error)
11101 goto done;
11103 if (abort_rebase) {
11104 if (!rebase_in_progress) {
11105 error = got_error(GOT_ERR_NOT_REBASING);
11106 goto done;
11108 error = got_worktree_rebase_continue(&resume_commit_id,
11109 &new_base_branch, &tmp_branch, &branch, &fileindex,
11110 worktree, repo);
11111 if (error)
11112 goto done;
11113 printf("Switching work tree to %s\n",
11114 got_ref_get_symref_target(new_base_branch));
11115 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11116 new_base_branch, abort_progress, &upa);
11117 if (error)
11118 goto done;
11119 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11120 print_merge_progress_stats(&upa);
11121 goto done; /* nothing else to do */
11124 if (continue_rebase) {
11125 if (!rebase_in_progress) {
11126 error = got_error(GOT_ERR_NOT_REBASING);
11127 goto done;
11129 error = got_worktree_rebase_continue(&resume_commit_id,
11130 &new_base_branch, &tmp_branch, &branch, &fileindex,
11131 worktree, repo);
11132 if (error)
11133 goto done;
11135 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11136 committer, resume_commit_id, repo);
11137 if (error)
11138 goto done;
11140 yca_id = got_object_id_dup(resume_commit_id);
11141 if (yca_id == NULL) {
11142 error = got_error_from_errno("got_object_id_dup");
11143 goto done;
11145 } else {
11146 error = got_ref_open(&branch, repo, argv[0], 0);
11147 if (error != NULL)
11148 goto done;
11149 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11150 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11151 "will not rebase a branch which lives outside "
11152 "the \"refs/heads/\" reference namespace");
11153 goto done;
11157 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11158 if (error)
11159 goto done;
11161 if (!continue_rebase) {
11162 struct got_object_id *base_commit_id;
11164 error = got_ref_open(&head_ref, repo,
11165 got_worktree_get_head_ref_name(worktree), 0);
11166 if (error)
11167 goto done;
11168 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11169 if (error)
11170 goto done;
11171 base_commit_id = got_worktree_get_base_commit_id(worktree);
11172 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11173 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11174 goto done;
11177 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11178 base_commit_id, branch_head_commit_id, 1, repo,
11179 check_cancelled, NULL);
11180 if (error) {
11181 if (error->code == GOT_ERR_ANCESTRY) {
11182 error = got_error_msg(GOT_ERR_ANCESTRY,
11183 "specified branch shares no common "
11184 "ancestry with work tree's branch");
11186 goto done;
11189 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11190 if (error) {
11191 if (error->code != GOT_ERR_ANCESTRY)
11192 goto done;
11193 error = NULL;
11194 } else {
11195 struct got_pathlist_head paths;
11196 printf("%s is already based on %s\n",
11197 got_ref_get_name(branch),
11198 got_worktree_get_head_ref_name(worktree));
11199 error = switch_head_ref(branch, branch_head_commit_id,
11200 worktree, repo);
11201 if (error)
11202 goto done;
11203 error = got_worktree_set_base_commit_id(worktree, repo,
11204 branch_head_commit_id);
11205 if (error)
11206 goto done;
11207 TAILQ_INIT(&paths);
11208 error = got_pathlist_append(&paths, "", NULL);
11209 if (error)
11210 goto done;
11211 error = got_worktree_checkout_files(worktree,
11212 &paths, repo, update_progress, &upa,
11213 check_cancelled, NULL);
11214 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11215 if (error)
11216 goto done;
11217 if (upa.did_something) {
11218 char *id_str;
11219 error = got_object_id_str(&id_str,
11220 branch_head_commit_id);
11221 if (error)
11222 goto done;
11223 printf("Updated to %s: %s\n",
11224 got_worktree_get_head_ref_name(worktree),
11225 id_str);
11226 free(id_str);
11227 } else
11228 printf("Already up-to-date\n");
11229 print_update_progress_stats(&upa);
11230 goto done;
11234 commit_id = branch_head_commit_id;
11235 error = got_object_open_as_commit(&commit, repo, commit_id);
11236 if (error)
11237 goto done;
11239 parent_ids = got_object_commit_get_parent_ids(commit);
11240 pid = STAILQ_FIRST(parent_ids);
11241 if (pid) {
11242 error = collect_commits(&commits, commit_id, &pid->id,
11243 yca_id, got_worktree_get_path_prefix(worktree),
11244 GOT_ERR_REBASE_PATH, repo);
11245 if (error)
11246 goto done;
11249 got_object_commit_close(commit);
11250 commit = NULL;
11252 if (!continue_rebase) {
11253 error = got_worktree_rebase_prepare(&new_base_branch,
11254 &tmp_branch, &fileindex, worktree, branch, repo);
11255 if (error)
11256 goto done;
11259 if (STAILQ_EMPTY(&commits)) {
11260 if (continue_rebase) {
11261 error = rebase_complete(worktree, fileindex,
11262 branch, tmp_branch, repo, create_backup);
11263 goto done;
11264 } else {
11265 /* Fast-forward the reference of the branch. */
11266 struct got_object_id *new_head_commit_id;
11267 char *id_str;
11268 error = got_ref_resolve(&new_head_commit_id, repo,
11269 new_base_branch);
11270 if (error)
11271 goto done;
11272 error = got_object_id_str(&id_str, new_head_commit_id);
11273 if (error)
11274 goto done;
11275 printf("Forwarding %s to commit %s\n",
11276 got_ref_get_name(branch), id_str);
11277 free(id_str);
11278 error = got_ref_change_ref(branch,
11279 new_head_commit_id);
11280 if (error)
11281 goto done;
11282 /* No backup needed since objects did not change. */
11283 create_backup = 0;
11287 pid = NULL;
11288 STAILQ_FOREACH(qid, &commits, entry) {
11290 commit_id = &qid->id;
11291 parent_id = pid ? &pid->id : yca_id;
11292 pid = qid;
11294 memset(&upa, 0, sizeof(upa));
11295 error = got_worktree_rebase_merge_files(&merged_paths,
11296 worktree, fileindex, parent_id, commit_id, repo,
11297 update_progress, &upa, check_cancelled, NULL);
11298 if (error)
11299 goto done;
11301 print_merge_progress_stats(&upa);
11302 if (upa.conflicts > 0 || upa.missing > 0 ||
11303 upa.not_deleted > 0 || upa.unversioned > 0) {
11304 if (upa.conflicts > 0) {
11305 error = show_rebase_merge_conflict(&qid->id,
11306 repo);
11307 if (error)
11308 goto done;
11310 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11311 break;
11314 error = rebase_commit(&merged_paths, worktree, fileindex,
11315 tmp_branch, committer, commit_id, repo);
11316 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11317 if (error)
11318 goto done;
11321 if (upa.conflicts > 0 || upa.missing > 0 ||
11322 upa.not_deleted > 0 || upa.unversioned > 0) {
11323 error = got_worktree_rebase_postpone(worktree, fileindex);
11324 if (error)
11325 goto done;
11326 if (upa.conflicts > 0 && upa.missing == 0 &&
11327 upa.not_deleted == 0 && upa.unversioned == 0) {
11328 error = got_error_msg(GOT_ERR_CONFLICTS,
11329 "conflicts must be resolved before rebasing "
11330 "can continue");
11331 } else if (upa.conflicts > 0) {
11332 error = got_error_msg(GOT_ERR_CONFLICTS,
11333 "conflicts must be resolved before rebasing "
11334 "can continue; changes destined for some "
11335 "files were not yet merged and should be "
11336 "merged manually if required before the "
11337 "rebase operation is continued");
11338 } else {
11339 error = got_error_msg(GOT_ERR_CONFLICTS,
11340 "changes destined for some files were not "
11341 "yet merged and should be merged manually "
11342 "if required before the rebase operation "
11343 "is continued");
11345 } else
11346 error = rebase_complete(worktree, fileindex, branch,
11347 tmp_branch, repo, create_backup);
11348 done:
11349 free(cwd);
11350 free(committer);
11351 free(gitconfig_path);
11352 got_object_id_queue_free(&commits);
11353 free(branch_head_commit_id);
11354 free(resume_commit_id);
11355 free(head_commit_id);
11356 free(yca_id);
11357 if (commit)
11358 got_object_commit_close(commit);
11359 if (branch)
11360 got_ref_close(branch);
11361 if (new_base_branch)
11362 got_ref_close(new_base_branch);
11363 if (tmp_branch)
11364 got_ref_close(tmp_branch);
11365 if (head_ref)
11366 got_ref_close(head_ref);
11367 if (worktree)
11368 got_worktree_close(worktree);
11369 if (repo) {
11370 const struct got_error *close_err = got_repo_close(repo);
11371 if (error == NULL)
11372 error = close_err;
11374 if (pack_fds) {
11375 const struct got_error *pack_err =
11376 got_repo_pack_fds_close(pack_fds);
11377 if (error == NULL)
11378 error = pack_err;
11380 return error;
11383 __dead static void
11384 usage_histedit(void)
11386 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11387 "[branch]\n", getprogname());
11388 exit(1);
11391 #define GOT_HISTEDIT_PICK 'p'
11392 #define GOT_HISTEDIT_EDIT 'e'
11393 #define GOT_HISTEDIT_FOLD 'f'
11394 #define GOT_HISTEDIT_DROP 'd'
11395 #define GOT_HISTEDIT_MESG 'm'
11397 static const struct got_histedit_cmd {
11398 unsigned char code;
11399 const char *name;
11400 const char *desc;
11401 } got_histedit_cmds[] = {
11402 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11403 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11404 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11405 "be used" },
11406 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11407 { GOT_HISTEDIT_MESG, "mesg",
11408 "single-line log message for commit above (open editor if empty)" },
11411 struct got_histedit_list_entry {
11412 TAILQ_ENTRY(got_histedit_list_entry) entry;
11413 struct got_object_id *commit_id;
11414 const struct got_histedit_cmd *cmd;
11415 char *logmsg;
11417 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11419 static const struct got_error *
11420 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11421 FILE *f, struct got_repository *repo)
11423 const struct got_error *err = NULL;
11424 char *logmsg = NULL, *id_str = NULL;
11425 struct got_commit_object *commit = NULL;
11426 int n;
11428 err = got_object_open_as_commit(&commit, repo, commit_id);
11429 if (err)
11430 goto done;
11432 err = get_short_logmsg(&logmsg, 34, commit);
11433 if (err)
11434 goto done;
11436 err = got_object_id_str(&id_str, commit_id);
11437 if (err)
11438 goto done;
11440 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11441 if (n < 0)
11442 err = got_ferror(f, GOT_ERR_IO);
11443 done:
11444 if (commit)
11445 got_object_commit_close(commit);
11446 free(id_str);
11447 free(logmsg);
11448 return err;
11451 static const struct got_error *
11452 histedit_write_commit_list(struct got_object_id_queue *commits,
11453 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11454 int edit_only, struct got_repository *repo)
11456 const struct got_error *err = NULL;
11457 struct got_object_qid *qid;
11458 const char *histedit_cmd = NULL;
11460 if (STAILQ_EMPTY(commits))
11461 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11463 STAILQ_FOREACH(qid, commits, entry) {
11464 histedit_cmd = got_histedit_cmds[0].name;
11465 if (drop_only)
11466 histedit_cmd = "drop";
11467 else if (edit_only)
11468 histedit_cmd = "edit";
11469 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11470 histedit_cmd = "fold";
11471 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11472 if (err)
11473 break;
11474 if (edit_logmsg_only) {
11475 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11476 if (n < 0) {
11477 err = got_ferror(f, GOT_ERR_IO);
11478 break;
11483 return err;
11486 static const struct got_error *
11487 write_cmd_list(FILE *f, const char *branch_name,
11488 struct got_object_id_queue *commits)
11490 const struct got_error *err = NULL;
11491 size_t i;
11492 int n;
11493 char *id_str;
11494 struct got_object_qid *qid;
11496 qid = STAILQ_FIRST(commits);
11497 err = got_object_id_str(&id_str, &qid->id);
11498 if (err)
11499 return err;
11501 n = fprintf(f,
11502 "# Editing the history of branch '%s' starting at\n"
11503 "# commit %s\n"
11504 "# Commits will be processed in order from top to "
11505 "bottom of this file.\n", branch_name, id_str);
11506 if (n < 0) {
11507 err = got_ferror(f, GOT_ERR_IO);
11508 goto done;
11511 n = fprintf(f, "# Available histedit commands:\n");
11512 if (n < 0) {
11513 err = got_ferror(f, GOT_ERR_IO);
11514 goto done;
11517 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11518 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11519 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11520 cmd->desc);
11521 if (n < 0) {
11522 err = got_ferror(f, GOT_ERR_IO);
11523 break;
11526 done:
11527 free(id_str);
11528 return err;
11531 static const struct got_error *
11532 histedit_syntax_error(int lineno)
11534 static char msg[42];
11535 int ret;
11537 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11538 lineno);
11539 if (ret < 0 || (size_t)ret >= sizeof(msg))
11540 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11542 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11545 static const struct got_error *
11546 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11547 char *logmsg, struct got_repository *repo)
11549 const struct got_error *err;
11550 struct got_commit_object *folded_commit = NULL;
11551 char *id_str, *folded_logmsg = NULL;
11553 err = got_object_id_str(&id_str, hle->commit_id);
11554 if (err)
11555 return err;
11557 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11558 if (err)
11559 goto done;
11561 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11562 if (err)
11563 goto done;
11564 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11565 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11566 folded_logmsg) == -1) {
11567 err = got_error_from_errno("asprintf");
11569 done:
11570 if (folded_commit)
11571 got_object_commit_close(folded_commit);
11572 free(id_str);
11573 free(folded_logmsg);
11574 return err;
11577 static struct got_histedit_list_entry *
11578 get_folded_commits(struct got_histedit_list_entry *hle)
11580 struct got_histedit_list_entry *prev, *folded = NULL;
11582 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11583 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11584 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11585 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11586 folded = prev;
11587 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11590 return folded;
11593 static const struct got_error *
11594 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11595 struct got_repository *repo)
11597 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11598 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11599 const struct got_error *err = NULL;
11600 struct got_commit_object *commit = NULL;
11601 int logmsg_len;
11602 int fd;
11603 struct got_histedit_list_entry *folded = NULL;
11605 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11606 if (err)
11607 return err;
11609 folded = get_folded_commits(hle);
11610 if (folded) {
11611 while (folded != hle) {
11612 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11613 folded = TAILQ_NEXT(folded, entry);
11614 continue;
11616 err = append_folded_commit_msg(&new_msg, folded,
11617 logmsg, repo);
11618 if (err)
11619 goto done;
11620 free(logmsg);
11621 logmsg = new_msg;
11622 folded = TAILQ_NEXT(folded, entry);
11626 err = got_object_id_str(&id_str, hle->commit_id);
11627 if (err)
11628 goto done;
11629 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11630 if (err)
11631 goto done;
11632 logmsg_len = asprintf(&new_msg,
11633 "%s\n# original log message of commit %s: %s",
11634 logmsg ? logmsg : "", id_str, orig_logmsg);
11635 if (logmsg_len == -1) {
11636 err = got_error_from_errno("asprintf");
11637 goto done;
11639 free(logmsg);
11640 logmsg = new_msg;
11642 err = got_object_id_str(&id_str, hle->commit_id);
11643 if (err)
11644 goto done;
11646 err = got_opentemp_named_fd(&logmsg_path, &fd,
11647 GOT_TMPDIR_STR "/got-logmsg", "");
11648 if (err)
11649 goto done;
11651 write(fd, logmsg, logmsg_len);
11652 close(fd);
11654 err = get_editor(&editor);
11655 if (err)
11656 goto done;
11658 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11659 logmsg_len, 0);
11660 if (err) {
11661 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11662 goto done;
11663 err = NULL;
11664 hle->logmsg = strdup(new_msg);
11665 if (hle->logmsg == NULL)
11666 err = got_error_from_errno("strdup");
11668 done:
11669 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11670 err = got_error_from_errno2("unlink", logmsg_path);
11671 free(logmsg_path);
11672 free(logmsg);
11673 free(orig_logmsg);
11674 free(editor);
11675 if (commit)
11676 got_object_commit_close(commit);
11677 return err;
11680 static const struct got_error *
11681 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11682 FILE *f, struct got_repository *repo)
11684 const struct got_error *err = NULL;
11685 char *line = NULL, *p, *end;
11686 size_t i, size;
11687 ssize_t len;
11688 int lineno = 0, lastcmd = -1;
11689 const struct got_histedit_cmd *cmd;
11690 struct got_object_id *commit_id = NULL;
11691 struct got_histedit_list_entry *hle = NULL;
11693 for (;;) {
11694 len = getline(&line, &size, f);
11695 if (len == -1) {
11696 const struct got_error *getline_err;
11697 if (feof(f))
11698 break;
11699 getline_err = got_error_from_errno("getline");
11700 err = got_ferror(f, getline_err->code);
11701 break;
11703 lineno++;
11704 p = line;
11705 while (isspace((unsigned char)p[0]))
11706 p++;
11707 if (p[0] == '#' || p[0] == '\0') {
11708 free(line);
11709 line = NULL;
11710 continue;
11712 cmd = NULL;
11713 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11714 cmd = &got_histedit_cmds[i];
11715 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11716 isspace((unsigned char)p[strlen(cmd->name)])) {
11717 p += strlen(cmd->name);
11718 break;
11720 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11721 p++;
11722 break;
11725 if (i == nitems(got_histedit_cmds)) {
11726 err = histedit_syntax_error(lineno);
11727 break;
11729 while (isspace((unsigned char)p[0]))
11730 p++;
11731 if (cmd->code == GOT_HISTEDIT_MESG) {
11732 if (lastcmd != GOT_HISTEDIT_PICK &&
11733 lastcmd != GOT_HISTEDIT_EDIT) {
11734 err = got_error(GOT_ERR_HISTEDIT_CMD);
11735 break;
11737 if (p[0] == '\0') {
11738 err = histedit_edit_logmsg(hle, repo);
11739 if (err)
11740 break;
11741 } else {
11742 hle->logmsg = strdup(p);
11743 if (hle->logmsg == NULL) {
11744 err = got_error_from_errno("strdup");
11745 break;
11748 free(line);
11749 line = NULL;
11750 lastcmd = cmd->code;
11751 continue;
11752 } else {
11753 end = p;
11754 while (end[0] && !isspace((unsigned char)end[0]))
11755 end++;
11756 *end = '\0';
11758 err = got_object_resolve_id_str(&commit_id, repo, p);
11759 if (err) {
11760 /* override error code */
11761 err = histedit_syntax_error(lineno);
11762 break;
11765 hle = malloc(sizeof(*hle));
11766 if (hle == NULL) {
11767 err = got_error_from_errno("malloc");
11768 break;
11770 hle->cmd = cmd;
11771 hle->commit_id = commit_id;
11772 hle->logmsg = NULL;
11773 commit_id = NULL;
11774 free(line);
11775 line = NULL;
11776 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11777 lastcmd = cmd->code;
11780 free(line);
11781 free(commit_id);
11782 return err;
11785 static const struct got_error *
11786 histedit_check_script(struct got_histedit_list *histedit_cmds,
11787 struct got_object_id_queue *commits, struct got_repository *repo)
11789 const struct got_error *err = NULL;
11790 struct got_object_qid *qid;
11791 struct got_histedit_list_entry *hle;
11792 static char msg[92];
11793 char *id_str;
11795 if (TAILQ_EMPTY(histedit_cmds))
11796 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11797 "histedit script contains no commands");
11798 if (STAILQ_EMPTY(commits))
11799 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11801 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11802 struct got_histedit_list_entry *hle2;
11803 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11804 if (hle == hle2)
11805 continue;
11806 if (got_object_id_cmp(hle->commit_id,
11807 hle2->commit_id) != 0)
11808 continue;
11809 err = got_object_id_str(&id_str, hle->commit_id);
11810 if (err)
11811 return err;
11812 snprintf(msg, sizeof(msg), "commit %s is listed "
11813 "more than once in histedit script", id_str);
11814 free(id_str);
11815 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11819 STAILQ_FOREACH(qid, commits, entry) {
11820 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11821 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11822 break;
11824 if (hle == NULL) {
11825 err = got_object_id_str(&id_str, &qid->id);
11826 if (err)
11827 return err;
11828 snprintf(msg, sizeof(msg),
11829 "commit %s missing from histedit script", id_str);
11830 free(id_str);
11831 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11835 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11836 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11837 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11838 "last commit in histedit script cannot be folded");
11840 return NULL;
11843 static const struct got_error *
11844 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11845 const char *path, struct got_object_id_queue *commits,
11846 struct got_repository *repo)
11848 const struct got_error *err = NULL;
11849 char *editor;
11850 FILE *f = NULL;
11852 err = get_editor(&editor);
11853 if (err)
11854 return err;
11856 if (spawn_editor(editor, path) == -1) {
11857 err = got_error_from_errno("failed spawning editor");
11858 goto done;
11861 f = fopen(path, "re");
11862 if (f == NULL) {
11863 err = got_error_from_errno("fopen");
11864 goto done;
11866 err = histedit_parse_list(histedit_cmds, f, repo);
11867 if (err)
11868 goto done;
11870 err = histedit_check_script(histedit_cmds, commits, repo);
11871 done:
11872 if (f && fclose(f) == EOF && err == NULL)
11873 err = got_error_from_errno("fclose");
11874 free(editor);
11875 return err;
11878 static const struct got_error *
11879 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11880 struct got_object_id_queue *, const char *, const char *,
11881 struct got_repository *);
11883 static const struct got_error *
11884 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11885 struct got_object_id_queue *commits, const char *branch_name,
11886 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11887 struct got_repository *repo)
11889 const struct got_error *err;
11890 FILE *f = NULL;
11891 char *path = NULL;
11893 err = got_opentemp_named(&path, &f, "got-histedit", "");
11894 if (err)
11895 return err;
11897 err = write_cmd_list(f, branch_name, commits);
11898 if (err)
11899 goto done;
11901 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11902 fold_only, drop_only, edit_only, repo);
11903 if (err)
11904 goto done;
11906 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11907 rewind(f);
11908 err = histedit_parse_list(histedit_cmds, f, repo);
11909 } else {
11910 if (fclose(f) == EOF) {
11911 err = got_error_from_errno("fclose");
11912 goto done;
11914 f = NULL;
11915 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11916 if (err) {
11917 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11918 err->code != GOT_ERR_HISTEDIT_CMD)
11919 goto done;
11920 err = histedit_edit_list_retry(histedit_cmds, err,
11921 commits, path, branch_name, repo);
11924 done:
11925 if (f && fclose(f) == EOF && err == NULL)
11926 err = got_error_from_errno("fclose");
11927 if (path && unlink(path) != 0 && err == NULL)
11928 err = got_error_from_errno2("unlink", path);
11929 free(path);
11930 return err;
11933 static const struct got_error *
11934 histedit_save_list(struct got_histedit_list *histedit_cmds,
11935 struct got_worktree *worktree, struct got_repository *repo)
11937 const struct got_error *err = NULL;
11938 char *path = NULL;
11939 FILE *f = NULL;
11940 struct got_histedit_list_entry *hle;
11941 struct got_commit_object *commit = NULL;
11943 err = got_worktree_get_histedit_script_path(&path, worktree);
11944 if (err)
11945 return err;
11947 f = fopen(path, "we");
11948 if (f == NULL) {
11949 err = got_error_from_errno2("fopen", path);
11950 goto done;
11952 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11953 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11954 repo);
11955 if (err)
11956 break;
11958 if (hle->logmsg) {
11959 int n = fprintf(f, "%c %s\n",
11960 GOT_HISTEDIT_MESG, hle->logmsg);
11961 if (n < 0) {
11962 err = got_ferror(f, GOT_ERR_IO);
11963 break;
11967 done:
11968 if (f && fclose(f) == EOF && err == NULL)
11969 err = got_error_from_errno("fclose");
11970 free(path);
11971 if (commit)
11972 got_object_commit_close(commit);
11973 return err;
11976 static void
11977 histedit_free_list(struct got_histedit_list *histedit_cmds)
11979 struct got_histedit_list_entry *hle;
11981 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11982 TAILQ_REMOVE(histedit_cmds, hle, entry);
11983 free(hle);
11987 static const struct got_error *
11988 histedit_load_list(struct got_histedit_list *histedit_cmds,
11989 const char *path, struct got_repository *repo)
11991 const struct got_error *err = NULL;
11992 FILE *f = NULL;
11994 f = fopen(path, "re");
11995 if (f == NULL) {
11996 err = got_error_from_errno2("fopen", path);
11997 goto done;
12000 err = histedit_parse_list(histedit_cmds, f, repo);
12001 done:
12002 if (f && fclose(f) == EOF && err == NULL)
12003 err = got_error_from_errno("fclose");
12004 return err;
12007 static const struct got_error *
12008 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12009 const struct got_error *edit_err, struct got_object_id_queue *commits,
12010 const char *path, const char *branch_name, struct got_repository *repo)
12012 const struct got_error *err = NULL, *prev_err = edit_err;
12013 int resp = ' ';
12015 while (resp != 'c' && resp != 'r' && resp != 'a') {
12016 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12017 "or (a)bort: ", getprogname(), prev_err->msg);
12018 resp = getchar();
12019 if (resp == '\n')
12020 resp = getchar();
12021 if (resp == 'c') {
12022 histedit_free_list(histedit_cmds);
12023 err = histedit_run_editor(histedit_cmds, path, commits,
12024 repo);
12025 if (err) {
12026 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12027 err->code != GOT_ERR_HISTEDIT_CMD)
12028 break;
12029 prev_err = err;
12030 resp = ' ';
12031 continue;
12033 break;
12034 } else if (resp == 'r') {
12035 histedit_free_list(histedit_cmds);
12036 err = histedit_edit_script(histedit_cmds,
12037 commits, branch_name, 0, 0, 0, 0, repo);
12038 if (err) {
12039 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12040 err->code != GOT_ERR_HISTEDIT_CMD)
12041 break;
12042 prev_err = err;
12043 resp = ' ';
12044 continue;
12046 break;
12047 } else if (resp == 'a') {
12048 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12049 break;
12050 } else
12051 printf("invalid response '%c'\n", resp);
12054 return err;
12057 static const struct got_error *
12058 histedit_complete(struct got_worktree *worktree,
12059 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12060 struct got_reference *branch, struct got_repository *repo)
12062 printf("Switching work tree to %s\n",
12063 got_ref_get_symref_target(branch));
12064 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12065 branch, repo);
12068 static const struct got_error *
12069 show_histedit_progress(struct got_commit_object *commit,
12070 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12072 const struct got_error *err;
12073 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12075 err = got_object_id_str(&old_id_str, hle->commit_id);
12076 if (err)
12077 goto done;
12079 if (new_id) {
12080 err = got_object_id_str(&new_id_str, new_id);
12081 if (err)
12082 goto done;
12085 old_id_str[12] = '\0';
12086 if (new_id_str)
12087 new_id_str[12] = '\0';
12089 if (hle->logmsg) {
12090 logmsg = strdup(hle->logmsg);
12091 if (logmsg == NULL) {
12092 err = got_error_from_errno("strdup");
12093 goto done;
12095 trim_logmsg(logmsg, 42);
12096 } else {
12097 err = get_short_logmsg(&logmsg, 42, commit);
12098 if (err)
12099 goto done;
12102 switch (hle->cmd->code) {
12103 case GOT_HISTEDIT_PICK:
12104 case GOT_HISTEDIT_EDIT:
12105 printf("%s -> %s: %s\n", old_id_str,
12106 new_id_str ? new_id_str : "no-op change", logmsg);
12107 break;
12108 case GOT_HISTEDIT_DROP:
12109 case GOT_HISTEDIT_FOLD:
12110 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12111 logmsg);
12112 break;
12113 default:
12114 break;
12116 done:
12117 free(old_id_str);
12118 free(new_id_str);
12119 return err;
12122 static const struct got_error *
12123 histedit_commit(struct got_pathlist_head *merged_paths,
12124 struct got_worktree *worktree, struct got_fileindex *fileindex,
12125 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12126 const char *committer, struct got_repository *repo)
12128 const struct got_error *err;
12129 struct got_commit_object *commit;
12130 struct got_object_id *new_commit_id;
12132 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12133 && hle->logmsg == NULL) {
12134 err = histedit_edit_logmsg(hle, repo);
12135 if (err)
12136 return err;
12139 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12140 if (err)
12141 return err;
12143 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12144 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12145 hle->logmsg, repo);
12146 if (err) {
12147 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12148 goto done;
12149 err = show_histedit_progress(commit, hle, NULL);
12150 } else {
12151 err = show_histedit_progress(commit, hle, new_commit_id);
12152 free(new_commit_id);
12154 done:
12155 got_object_commit_close(commit);
12156 return err;
12159 static const struct got_error *
12160 histedit_skip_commit(struct got_histedit_list_entry *hle,
12161 struct got_worktree *worktree, struct got_repository *repo)
12163 const struct got_error *error;
12164 struct got_commit_object *commit;
12166 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12167 repo);
12168 if (error)
12169 return error;
12171 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12172 if (error)
12173 return error;
12175 error = show_histedit_progress(commit, hle, NULL);
12176 got_object_commit_close(commit);
12177 return error;
12180 static const struct got_error *
12181 check_local_changes(void *arg, unsigned char status,
12182 unsigned char staged_status, const char *path,
12183 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12184 struct got_object_id *commit_id, int dirfd, const char *de_name)
12186 int *have_local_changes = arg;
12188 switch (status) {
12189 case GOT_STATUS_ADD:
12190 case GOT_STATUS_DELETE:
12191 case GOT_STATUS_MODIFY:
12192 case GOT_STATUS_CONFLICT:
12193 *have_local_changes = 1;
12194 return got_error(GOT_ERR_CANCELLED);
12195 default:
12196 break;
12199 switch (staged_status) {
12200 case GOT_STATUS_ADD:
12201 case GOT_STATUS_DELETE:
12202 case GOT_STATUS_MODIFY:
12203 *have_local_changes = 1;
12204 return got_error(GOT_ERR_CANCELLED);
12205 default:
12206 break;
12209 return NULL;
12212 static const struct got_error *
12213 cmd_histedit(int argc, char *argv[])
12215 const struct got_error *error = NULL;
12216 struct got_worktree *worktree = NULL;
12217 struct got_fileindex *fileindex = NULL;
12218 struct got_repository *repo = NULL;
12219 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12220 struct got_reference *branch = NULL;
12221 struct got_reference *tmp_branch = NULL;
12222 struct got_object_id *resume_commit_id = NULL;
12223 struct got_object_id *base_commit_id = NULL;
12224 struct got_object_id *head_commit_id = NULL;
12225 struct got_commit_object *commit = NULL;
12226 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12227 struct got_update_progress_arg upa;
12228 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12229 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12230 int list_backups = 0, delete_backups = 0;
12231 const char *edit_script_path = NULL;
12232 struct got_object_id_queue commits;
12233 struct got_pathlist_head merged_paths;
12234 const struct got_object_id_queue *parent_ids;
12235 struct got_object_qid *pid;
12236 struct got_histedit_list histedit_cmds;
12237 struct got_histedit_list_entry *hle;
12238 int *pack_fds = NULL;
12240 STAILQ_INIT(&commits);
12241 TAILQ_INIT(&histedit_cmds);
12242 TAILQ_INIT(&merged_paths);
12243 memset(&upa, 0, sizeof(upa));
12245 #ifndef PROFILE
12246 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12247 "unveil", NULL) == -1)
12248 err(1, "pledge");
12249 #endif
12251 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12252 switch (ch) {
12253 case 'a':
12254 abort_edit = 1;
12255 break;
12256 case 'c':
12257 continue_edit = 1;
12258 break;
12259 case 'd':
12260 drop_only = 1;
12261 break;
12262 case 'e':
12263 edit_only = 1;
12264 break;
12265 case 'F':
12266 edit_script_path = optarg;
12267 break;
12268 case 'f':
12269 fold_only = 1;
12270 break;
12271 case 'l':
12272 list_backups = 1;
12273 break;
12274 case 'm':
12275 edit_logmsg_only = 1;
12276 break;
12277 case 'X':
12278 delete_backups = 1;
12279 break;
12280 default:
12281 usage_histedit();
12282 /* NOTREACHED */
12286 argc -= optind;
12287 argv += optind;
12289 if (abort_edit && continue_edit)
12290 option_conflict('a', 'c');
12291 if (edit_script_path && edit_logmsg_only)
12292 option_conflict('F', 'm');
12293 if (abort_edit && edit_logmsg_only)
12294 option_conflict('a', 'm');
12295 if (continue_edit && edit_logmsg_only)
12296 option_conflict('c', 'm');
12297 if (abort_edit && fold_only)
12298 option_conflict('a', 'f');
12299 if (continue_edit && fold_only)
12300 option_conflict('c', 'f');
12301 if (fold_only && edit_logmsg_only)
12302 option_conflict('f', 'm');
12303 if (edit_script_path && fold_only)
12304 option_conflict('F', 'f');
12305 if (abort_edit && edit_only)
12306 option_conflict('a', 'e');
12307 if (continue_edit && edit_only)
12308 option_conflict('c', 'e');
12309 if (edit_only && edit_logmsg_only)
12310 option_conflict('e', 'm');
12311 if (edit_script_path && edit_only)
12312 option_conflict('F', 'e');
12313 if (fold_only && edit_only)
12314 option_conflict('f', 'e');
12315 if (drop_only && abort_edit)
12316 option_conflict('d', 'a');
12317 if (drop_only && continue_edit)
12318 option_conflict('d', 'c');
12319 if (drop_only && edit_logmsg_only)
12320 option_conflict('d', 'm');
12321 if (drop_only && edit_only)
12322 option_conflict('d', 'e');
12323 if (drop_only && edit_script_path)
12324 option_conflict('d', 'F');
12325 if (drop_only && fold_only)
12326 option_conflict('d', 'f');
12327 if (list_backups) {
12328 if (abort_edit)
12329 option_conflict('l', 'a');
12330 if (continue_edit)
12331 option_conflict('l', 'c');
12332 if (edit_script_path)
12333 option_conflict('l', 'F');
12334 if (edit_logmsg_only)
12335 option_conflict('l', 'm');
12336 if (drop_only)
12337 option_conflict('l', 'd');
12338 if (fold_only)
12339 option_conflict('l', 'f');
12340 if (edit_only)
12341 option_conflict('l', 'e');
12342 if (delete_backups)
12343 option_conflict('l', 'X');
12344 if (argc != 0 && argc != 1)
12345 usage_histedit();
12346 } else if (delete_backups) {
12347 if (abort_edit)
12348 option_conflict('X', 'a');
12349 if (continue_edit)
12350 option_conflict('X', 'c');
12351 if (drop_only)
12352 option_conflict('X', 'd');
12353 if (edit_script_path)
12354 option_conflict('X', 'F');
12355 if (edit_logmsg_only)
12356 option_conflict('X', 'm');
12357 if (fold_only)
12358 option_conflict('X', 'f');
12359 if (edit_only)
12360 option_conflict('X', 'e');
12361 if (list_backups)
12362 option_conflict('X', 'l');
12363 if (argc != 0 && argc != 1)
12364 usage_histedit();
12365 } else if (argc != 0)
12366 usage_histedit();
12369 * This command cannot apply unveil(2) in all cases because the
12370 * user may choose to run an editor to edit the histedit script
12371 * and to edit individual commit log messages.
12372 * unveil(2) traverses exec(2); if an editor is used we have to
12373 * apply unveil after edit script and log messages have been written.
12374 * XXX TODO: Make use of unveil(2) where possible.
12377 cwd = getcwd(NULL, 0);
12378 if (cwd == NULL) {
12379 error = got_error_from_errno("getcwd");
12380 goto done;
12383 error = got_repo_pack_fds_open(&pack_fds);
12384 if (error != NULL)
12385 goto done;
12387 error = got_worktree_open(&worktree, cwd);
12388 if (error) {
12389 if (list_backups || delete_backups) {
12390 if (error->code != GOT_ERR_NOT_WORKTREE)
12391 goto done;
12392 } else {
12393 if (error->code == GOT_ERR_NOT_WORKTREE)
12394 error = wrap_not_worktree_error(error,
12395 "histedit", cwd);
12396 goto done;
12400 if (list_backups || delete_backups) {
12401 error = got_repo_open(&repo,
12402 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12403 NULL, pack_fds);
12404 if (error != NULL)
12405 goto done;
12406 error = apply_unveil(got_repo_get_path(repo), 0,
12407 worktree ? got_worktree_get_root_path(worktree) : NULL);
12408 if (error)
12409 goto done;
12410 error = process_backup_refs(
12411 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12412 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12413 goto done; /* nothing else to do */
12416 error = get_gitconfig_path(&gitconfig_path);
12417 if (error)
12418 goto done;
12419 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12420 gitconfig_path, pack_fds);
12421 if (error != NULL)
12422 goto done;
12424 if (worktree != NULL && !list_backups && !delete_backups) {
12425 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12426 if (error)
12427 goto done;
12430 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12431 if (error)
12432 goto done;
12433 if (rebase_in_progress) {
12434 error = got_error(GOT_ERR_REBASING);
12435 goto done;
12438 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12439 repo);
12440 if (error)
12441 goto done;
12442 if (merge_in_progress) {
12443 error = got_error(GOT_ERR_MERGE_BUSY);
12444 goto done;
12447 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12448 if (error)
12449 goto done;
12451 if (edit_in_progress && edit_logmsg_only) {
12452 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12453 "histedit operation is in progress in this "
12454 "work tree and must be continued or aborted "
12455 "before the -m option can be used");
12456 goto done;
12458 if (edit_in_progress && drop_only) {
12459 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12460 "histedit operation is in progress in this "
12461 "work tree and must be continued or aborted "
12462 "before the -d option can be used");
12463 goto done;
12465 if (edit_in_progress && fold_only) {
12466 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12467 "histedit operation is in progress in this "
12468 "work tree and must be continued or aborted "
12469 "before the -f option can be used");
12470 goto done;
12472 if (edit_in_progress && edit_only) {
12473 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12474 "histedit operation is in progress in this "
12475 "work tree and must be continued or aborted "
12476 "before the -e option can be used");
12477 goto done;
12480 if (edit_in_progress && abort_edit) {
12481 error = got_worktree_histedit_continue(&resume_commit_id,
12482 &tmp_branch, &branch, &base_commit_id, &fileindex,
12483 worktree, repo);
12484 if (error)
12485 goto done;
12486 printf("Switching work tree to %s\n",
12487 got_ref_get_symref_target(branch));
12488 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12489 branch, base_commit_id, abort_progress, &upa);
12490 if (error)
12491 goto done;
12492 printf("Histedit of %s aborted\n",
12493 got_ref_get_symref_target(branch));
12494 print_merge_progress_stats(&upa);
12495 goto done; /* nothing else to do */
12496 } else if (abort_edit) {
12497 error = got_error(GOT_ERR_NOT_HISTEDIT);
12498 goto done;
12501 error = get_author(&committer, repo, worktree);
12502 if (error)
12503 goto done;
12505 if (continue_edit) {
12506 char *path;
12508 if (!edit_in_progress) {
12509 error = got_error(GOT_ERR_NOT_HISTEDIT);
12510 goto done;
12513 error = got_worktree_get_histedit_script_path(&path, worktree);
12514 if (error)
12515 goto done;
12517 error = histedit_load_list(&histedit_cmds, path, repo);
12518 free(path);
12519 if (error)
12520 goto done;
12522 error = got_worktree_histedit_continue(&resume_commit_id,
12523 &tmp_branch, &branch, &base_commit_id, &fileindex,
12524 worktree, repo);
12525 if (error)
12526 goto done;
12528 error = got_ref_resolve(&head_commit_id, repo, branch);
12529 if (error)
12530 goto done;
12532 error = got_object_open_as_commit(&commit, repo,
12533 head_commit_id);
12534 if (error)
12535 goto done;
12536 parent_ids = got_object_commit_get_parent_ids(commit);
12537 pid = STAILQ_FIRST(parent_ids);
12538 if (pid == NULL) {
12539 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12540 goto done;
12542 error = collect_commits(&commits, head_commit_id, &pid->id,
12543 base_commit_id, got_worktree_get_path_prefix(worktree),
12544 GOT_ERR_HISTEDIT_PATH, repo);
12545 got_object_commit_close(commit);
12546 commit = NULL;
12547 if (error)
12548 goto done;
12549 } else {
12550 if (edit_in_progress) {
12551 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12552 goto done;
12555 error = got_ref_open(&branch, repo,
12556 got_worktree_get_head_ref_name(worktree), 0);
12557 if (error != NULL)
12558 goto done;
12560 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12561 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12562 "will not edit commit history of a branch outside "
12563 "the \"refs/heads/\" reference namespace");
12564 goto done;
12567 error = got_ref_resolve(&head_commit_id, repo, branch);
12568 got_ref_close(branch);
12569 branch = NULL;
12570 if (error)
12571 goto done;
12573 error = got_object_open_as_commit(&commit, repo,
12574 head_commit_id);
12575 if (error)
12576 goto done;
12577 parent_ids = got_object_commit_get_parent_ids(commit);
12578 pid = STAILQ_FIRST(parent_ids);
12579 if (pid == NULL) {
12580 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12581 goto done;
12583 error = collect_commits(&commits, head_commit_id, &pid->id,
12584 got_worktree_get_base_commit_id(worktree),
12585 got_worktree_get_path_prefix(worktree),
12586 GOT_ERR_HISTEDIT_PATH, repo);
12587 got_object_commit_close(commit);
12588 commit = NULL;
12589 if (error)
12590 goto done;
12592 if (STAILQ_EMPTY(&commits)) {
12593 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12594 goto done;
12597 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12598 &base_commit_id, &fileindex, worktree, repo);
12599 if (error)
12600 goto done;
12602 if (edit_script_path) {
12603 error = histedit_load_list(&histedit_cmds,
12604 edit_script_path, repo);
12605 if (error) {
12606 got_worktree_histedit_abort(worktree, fileindex,
12607 repo, branch, base_commit_id,
12608 abort_progress, &upa);
12609 print_merge_progress_stats(&upa);
12610 goto done;
12612 } else {
12613 const char *branch_name;
12614 branch_name = got_ref_get_symref_target(branch);
12615 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12616 branch_name += 11;
12617 error = histedit_edit_script(&histedit_cmds, &commits,
12618 branch_name, edit_logmsg_only, fold_only,
12619 drop_only, edit_only, repo);
12620 if (error) {
12621 got_worktree_histedit_abort(worktree, fileindex,
12622 repo, branch, base_commit_id,
12623 abort_progress, &upa);
12624 print_merge_progress_stats(&upa);
12625 goto done;
12630 error = histedit_save_list(&histedit_cmds, worktree,
12631 repo);
12632 if (error) {
12633 got_worktree_histedit_abort(worktree, fileindex,
12634 repo, branch, base_commit_id,
12635 abort_progress, &upa);
12636 print_merge_progress_stats(&upa);
12637 goto done;
12642 error = histedit_check_script(&histedit_cmds, &commits, repo);
12643 if (error)
12644 goto done;
12646 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12647 if (resume_commit_id) {
12648 if (got_object_id_cmp(hle->commit_id,
12649 resume_commit_id) != 0)
12650 continue;
12652 resume_commit_id = NULL;
12653 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12654 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12655 error = histedit_skip_commit(hle, worktree,
12656 repo);
12657 if (error)
12658 goto done;
12659 } else {
12660 struct got_pathlist_head paths;
12661 int have_changes = 0;
12663 TAILQ_INIT(&paths);
12664 error = got_pathlist_append(&paths, "", NULL);
12665 if (error)
12666 goto done;
12667 error = got_worktree_status(worktree, &paths,
12668 repo, 0, check_local_changes, &have_changes,
12669 check_cancelled, NULL);
12670 got_pathlist_free(&paths,
12671 GOT_PATHLIST_FREE_NONE);
12672 if (error) {
12673 if (error->code != GOT_ERR_CANCELLED)
12674 goto done;
12675 if (sigint_received || sigpipe_received)
12676 goto done;
12678 if (have_changes) {
12679 error = histedit_commit(NULL, worktree,
12680 fileindex, tmp_branch, hle,
12681 committer, repo);
12682 if (error)
12683 goto done;
12684 } else {
12685 error = got_object_open_as_commit(
12686 &commit, repo, hle->commit_id);
12687 if (error)
12688 goto done;
12689 error = show_histedit_progress(commit,
12690 hle, NULL);
12691 got_object_commit_close(commit);
12692 commit = NULL;
12693 if (error)
12694 goto done;
12697 continue;
12700 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12701 error = histedit_skip_commit(hle, worktree, repo);
12702 if (error)
12703 goto done;
12704 continue;
12707 error = got_object_open_as_commit(&commit, repo,
12708 hle->commit_id);
12709 if (error)
12710 goto done;
12711 parent_ids = got_object_commit_get_parent_ids(commit);
12712 pid = STAILQ_FIRST(parent_ids);
12714 error = got_worktree_histedit_merge_files(&merged_paths,
12715 worktree, fileindex, &pid->id, hle->commit_id, repo,
12716 update_progress, &upa, check_cancelled, NULL);
12717 if (error)
12718 goto done;
12719 got_object_commit_close(commit);
12720 commit = NULL;
12722 print_merge_progress_stats(&upa);
12723 if (upa.conflicts > 0 || upa.missing > 0 ||
12724 upa.not_deleted > 0 || upa.unversioned > 0) {
12725 if (upa.conflicts > 0) {
12726 error = show_rebase_merge_conflict(
12727 hle->commit_id, repo);
12728 if (error)
12729 goto done;
12731 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12732 break;
12735 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12736 char *id_str;
12737 error = got_object_id_str(&id_str, hle->commit_id);
12738 if (error)
12739 goto done;
12740 printf("Stopping histedit for amending commit %s\n",
12741 id_str);
12742 free(id_str);
12743 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12744 error = got_worktree_histedit_postpone(worktree,
12745 fileindex);
12746 goto done;
12749 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12750 error = histedit_skip_commit(hle, worktree, repo);
12751 if (error)
12752 goto done;
12753 continue;
12756 error = histedit_commit(&merged_paths, worktree, fileindex,
12757 tmp_branch, hle, committer, repo);
12758 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12759 if (error)
12760 goto done;
12763 if (upa.conflicts > 0 || upa.missing > 0 ||
12764 upa.not_deleted > 0 || upa.unversioned > 0) {
12765 error = got_worktree_histedit_postpone(worktree, fileindex);
12766 if (error)
12767 goto done;
12768 if (upa.conflicts > 0 && upa.missing == 0 &&
12769 upa.not_deleted == 0 && upa.unversioned == 0) {
12770 error = got_error_msg(GOT_ERR_CONFLICTS,
12771 "conflicts must be resolved before histedit "
12772 "can continue");
12773 } else if (upa.conflicts > 0) {
12774 error = got_error_msg(GOT_ERR_CONFLICTS,
12775 "conflicts must be resolved before histedit "
12776 "can continue; changes destined for some "
12777 "files were not yet merged and should be "
12778 "merged manually if required before the "
12779 "histedit operation is continued");
12780 } else {
12781 error = got_error_msg(GOT_ERR_CONFLICTS,
12782 "changes destined for some files were not "
12783 "yet merged and should be merged manually "
12784 "if required before the histedit operation "
12785 "is continued");
12787 } else
12788 error = histedit_complete(worktree, fileindex, tmp_branch,
12789 branch, repo);
12790 done:
12791 free(cwd);
12792 free(committer);
12793 free(gitconfig_path);
12794 got_object_id_queue_free(&commits);
12795 histedit_free_list(&histedit_cmds);
12796 free(head_commit_id);
12797 free(base_commit_id);
12798 free(resume_commit_id);
12799 if (commit)
12800 got_object_commit_close(commit);
12801 if (branch)
12802 got_ref_close(branch);
12803 if (tmp_branch)
12804 got_ref_close(tmp_branch);
12805 if (worktree)
12806 got_worktree_close(worktree);
12807 if (repo) {
12808 const struct got_error *close_err = got_repo_close(repo);
12809 if (error == NULL)
12810 error = close_err;
12812 if (pack_fds) {
12813 const struct got_error *pack_err =
12814 got_repo_pack_fds_close(pack_fds);
12815 if (error == NULL)
12816 error = pack_err;
12818 return error;
12821 __dead static void
12822 usage_integrate(void)
12824 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12825 exit(1);
12828 static const struct got_error *
12829 cmd_integrate(int argc, char *argv[])
12831 const struct got_error *error = NULL;
12832 struct got_repository *repo = NULL;
12833 struct got_worktree *worktree = NULL;
12834 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12835 const char *branch_arg = NULL;
12836 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12837 struct got_fileindex *fileindex = NULL;
12838 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12839 int ch;
12840 struct got_update_progress_arg upa;
12841 int *pack_fds = NULL;
12843 #ifndef PROFILE
12844 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12845 "unveil", NULL) == -1)
12846 err(1, "pledge");
12847 #endif
12849 while ((ch = getopt(argc, argv, "")) != -1) {
12850 switch (ch) {
12851 default:
12852 usage_integrate();
12853 /* NOTREACHED */
12857 argc -= optind;
12858 argv += optind;
12860 if (argc != 1)
12861 usage_integrate();
12862 branch_arg = argv[0];
12864 cwd = getcwd(NULL, 0);
12865 if (cwd == NULL) {
12866 error = got_error_from_errno("getcwd");
12867 goto done;
12870 error = got_repo_pack_fds_open(&pack_fds);
12871 if (error != NULL)
12872 goto done;
12874 error = got_worktree_open(&worktree, cwd);
12875 if (error) {
12876 if (error->code == GOT_ERR_NOT_WORKTREE)
12877 error = wrap_not_worktree_error(error, "integrate",
12878 cwd);
12879 goto done;
12882 error = check_rebase_or_histedit_in_progress(worktree);
12883 if (error)
12884 goto done;
12886 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12887 NULL, pack_fds);
12888 if (error != NULL)
12889 goto done;
12891 error = apply_unveil(got_repo_get_path(repo), 0,
12892 got_worktree_get_root_path(worktree));
12893 if (error)
12894 goto done;
12896 error = check_merge_in_progress(worktree, repo);
12897 if (error)
12898 goto done;
12900 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12901 error = got_error_from_errno("asprintf");
12902 goto done;
12905 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12906 &base_branch_ref, worktree, refname, repo);
12907 if (error)
12908 goto done;
12910 refname = strdup(got_ref_get_name(branch_ref));
12911 if (refname == NULL) {
12912 error = got_error_from_errno("strdup");
12913 got_worktree_integrate_abort(worktree, fileindex, repo,
12914 branch_ref, base_branch_ref);
12915 goto done;
12917 base_refname = strdup(got_ref_get_name(base_branch_ref));
12918 if (base_refname == NULL) {
12919 error = got_error_from_errno("strdup");
12920 got_worktree_integrate_abort(worktree, fileindex, repo,
12921 branch_ref, base_branch_ref);
12922 goto done;
12924 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12925 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12926 got_worktree_integrate_abort(worktree, fileindex, repo,
12927 branch_ref, base_branch_ref);
12928 goto done;
12931 error = got_ref_resolve(&commit_id, repo, branch_ref);
12932 if (error)
12933 goto done;
12935 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12936 if (error)
12937 goto done;
12939 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12940 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12941 "specified branch has already been integrated");
12942 got_worktree_integrate_abort(worktree, fileindex, repo,
12943 branch_ref, base_branch_ref);
12944 goto done;
12947 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12948 if (error) {
12949 if (error->code == GOT_ERR_ANCESTRY)
12950 error = got_error(GOT_ERR_REBASE_REQUIRED);
12951 got_worktree_integrate_abort(worktree, fileindex, repo,
12952 branch_ref, base_branch_ref);
12953 goto done;
12956 memset(&upa, 0, sizeof(upa));
12957 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12958 branch_ref, base_branch_ref, update_progress, &upa,
12959 check_cancelled, NULL);
12960 if (error)
12961 goto done;
12963 printf("Integrated %s into %s\n", refname, base_refname);
12964 print_update_progress_stats(&upa);
12965 done:
12966 if (repo) {
12967 const struct got_error *close_err = got_repo_close(repo);
12968 if (error == NULL)
12969 error = close_err;
12971 if (worktree)
12972 got_worktree_close(worktree);
12973 if (pack_fds) {
12974 const struct got_error *pack_err =
12975 got_repo_pack_fds_close(pack_fds);
12976 if (error == NULL)
12977 error = pack_err;
12979 free(cwd);
12980 free(base_commit_id);
12981 free(commit_id);
12982 free(refname);
12983 free(base_refname);
12984 return error;
12987 __dead static void
12988 usage_merge(void)
12990 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12991 exit(1);
12994 static const struct got_error *
12995 cmd_merge(int argc, char *argv[])
12997 const struct got_error *error = NULL;
12998 struct got_worktree *worktree = NULL;
12999 struct got_repository *repo = NULL;
13000 struct got_fileindex *fileindex = NULL;
13001 char *cwd = NULL, *id_str = NULL, *author = NULL;
13002 struct got_reference *branch = NULL, *wt_branch = NULL;
13003 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13004 struct got_object_id *wt_branch_tip = NULL;
13005 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13006 int interrupt_merge = 0;
13007 struct got_update_progress_arg upa;
13008 struct got_object_id *merge_commit_id = NULL;
13009 char *branch_name = NULL;
13010 int *pack_fds = NULL;
13012 memset(&upa, 0, sizeof(upa));
13014 #ifndef PROFILE
13015 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13016 "unveil", NULL) == -1)
13017 err(1, "pledge");
13018 #endif
13020 while ((ch = getopt(argc, argv, "acn")) != -1) {
13021 switch (ch) {
13022 case 'a':
13023 abort_merge = 1;
13024 break;
13025 case 'c':
13026 continue_merge = 1;
13027 break;
13028 case 'n':
13029 interrupt_merge = 1;
13030 break;
13031 default:
13032 usage_merge();
13033 /* NOTREACHED */
13037 argc -= optind;
13038 argv += optind;
13040 if (abort_merge && continue_merge)
13041 option_conflict('a', 'c');
13042 if (abort_merge || continue_merge) {
13043 if (argc != 0)
13044 usage_merge();
13045 } else if (argc != 1)
13046 usage_merge();
13048 cwd = getcwd(NULL, 0);
13049 if (cwd == NULL) {
13050 error = got_error_from_errno("getcwd");
13051 goto done;
13054 error = got_repo_pack_fds_open(&pack_fds);
13055 if (error != NULL)
13056 goto done;
13058 error = got_worktree_open(&worktree, cwd);
13059 if (error) {
13060 if (error->code == GOT_ERR_NOT_WORKTREE)
13061 error = wrap_not_worktree_error(error,
13062 "merge", cwd);
13063 goto done;
13066 error = got_repo_open(&repo,
13067 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13068 pack_fds);
13069 if (error != NULL)
13070 goto done;
13072 if (worktree != NULL) {
13073 error = worktree_has_logmsg_ref("merge", worktree, repo);
13074 if (error)
13075 goto done;
13078 error = apply_unveil(got_repo_get_path(repo), 0,
13079 worktree ? got_worktree_get_root_path(worktree) : NULL);
13080 if (error)
13081 goto done;
13083 error = check_rebase_or_histedit_in_progress(worktree);
13084 if (error)
13085 goto done;
13087 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13088 repo);
13089 if (error)
13090 goto done;
13092 if (abort_merge) {
13093 if (!merge_in_progress) {
13094 error = got_error(GOT_ERR_NOT_MERGING);
13095 goto done;
13097 error = got_worktree_merge_continue(&branch_name,
13098 &branch_tip, &fileindex, worktree, repo);
13099 if (error)
13100 goto done;
13101 error = got_worktree_merge_abort(worktree, fileindex, repo,
13102 abort_progress, &upa);
13103 if (error)
13104 goto done;
13105 printf("Merge of %s aborted\n", branch_name);
13106 goto done; /* nothing else to do */
13109 error = get_author(&author, repo, worktree);
13110 if (error)
13111 goto done;
13113 if (continue_merge) {
13114 if (!merge_in_progress) {
13115 error = got_error(GOT_ERR_NOT_MERGING);
13116 goto done;
13118 error = got_worktree_merge_continue(&branch_name,
13119 &branch_tip, &fileindex, worktree, repo);
13120 if (error)
13121 goto done;
13122 } else {
13123 error = got_ref_open(&branch, repo, argv[0], 0);
13124 if (error != NULL)
13125 goto done;
13126 branch_name = strdup(got_ref_get_name(branch));
13127 if (branch_name == NULL) {
13128 error = got_error_from_errno("strdup");
13129 goto done;
13131 error = got_ref_resolve(&branch_tip, repo, branch);
13132 if (error)
13133 goto done;
13136 error = got_ref_open(&wt_branch, repo,
13137 got_worktree_get_head_ref_name(worktree), 0);
13138 if (error)
13139 goto done;
13140 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13141 if (error)
13142 goto done;
13143 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13144 wt_branch_tip, branch_tip, 0, repo,
13145 check_cancelled, NULL);
13146 if (error && error->code != GOT_ERR_ANCESTRY)
13147 goto done;
13149 if (!continue_merge) {
13150 error = check_path_prefix(wt_branch_tip, branch_tip,
13151 got_worktree_get_path_prefix(worktree),
13152 GOT_ERR_MERGE_PATH, repo);
13153 if (error)
13154 goto done;
13155 if (yca_id) {
13156 error = check_same_branch(wt_branch_tip, branch,
13157 yca_id, repo);
13158 if (error) {
13159 if (error->code != GOT_ERR_ANCESTRY)
13160 goto done;
13161 error = NULL;
13162 } else {
13163 static char msg[512];
13164 snprintf(msg, sizeof(msg),
13165 "cannot create a merge commit because "
13166 "%s is based on %s; %s can be integrated "
13167 "with 'got integrate' instead", branch_name,
13168 got_worktree_get_head_ref_name(worktree),
13169 branch_name);
13170 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13171 goto done;
13174 error = got_worktree_merge_prepare(&fileindex, worktree,
13175 branch, repo);
13176 if (error)
13177 goto done;
13179 error = got_worktree_merge_branch(worktree, fileindex,
13180 yca_id, branch_tip, repo, update_progress, &upa,
13181 check_cancelled, NULL);
13182 if (error)
13183 goto done;
13184 print_merge_progress_stats(&upa);
13185 if (!upa.did_something) {
13186 error = got_worktree_merge_abort(worktree, fileindex,
13187 repo, abort_progress, &upa);
13188 if (error)
13189 goto done;
13190 printf("Already up-to-date\n");
13191 goto done;
13195 if (interrupt_merge) {
13196 error = got_worktree_merge_postpone(worktree, fileindex);
13197 if (error)
13198 goto done;
13199 printf("Merge of %s interrupted on request\n", branch_name);
13200 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13201 upa.not_deleted > 0 || upa.unversioned > 0) {
13202 error = got_worktree_merge_postpone(worktree, fileindex);
13203 if (error)
13204 goto done;
13205 if (upa.conflicts > 0 && upa.missing == 0 &&
13206 upa.not_deleted == 0 && upa.unversioned == 0) {
13207 error = got_error_msg(GOT_ERR_CONFLICTS,
13208 "conflicts must be resolved before merging "
13209 "can continue");
13210 } else if (upa.conflicts > 0) {
13211 error = got_error_msg(GOT_ERR_CONFLICTS,
13212 "conflicts must be resolved before merging "
13213 "can continue; changes destined for some "
13214 "files were not yet merged and "
13215 "should be merged manually if required before the "
13216 "merge operation is continued");
13217 } else {
13218 error = got_error_msg(GOT_ERR_CONFLICTS,
13219 "changes destined for some "
13220 "files were not yet merged and should be "
13221 "merged manually if required before the "
13222 "merge operation is continued");
13224 goto done;
13225 } else {
13226 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13227 fileindex, author, NULL, 1, branch_tip, branch_name,
13228 repo, continue_merge ? print_status : NULL, NULL);
13229 if (error)
13230 goto done;
13231 error = got_worktree_merge_complete(worktree, fileindex, repo);
13232 if (error)
13233 goto done;
13234 error = got_object_id_str(&id_str, merge_commit_id);
13235 if (error)
13236 goto done;
13237 printf("Merged %s into %s: %s\n", branch_name,
13238 got_worktree_get_head_ref_name(worktree),
13239 id_str);
13242 done:
13243 free(id_str);
13244 free(merge_commit_id);
13245 free(author);
13246 free(branch_tip);
13247 free(branch_name);
13248 free(yca_id);
13249 if (branch)
13250 got_ref_close(branch);
13251 if (wt_branch)
13252 got_ref_close(wt_branch);
13253 if (worktree)
13254 got_worktree_close(worktree);
13255 if (repo) {
13256 const struct got_error *close_err = got_repo_close(repo);
13257 if (error == NULL)
13258 error = close_err;
13260 if (pack_fds) {
13261 const struct got_error *pack_err =
13262 got_repo_pack_fds_close(pack_fds);
13263 if (error == NULL)
13264 error = pack_err;
13266 return error;
13269 __dead static void
13270 usage_stage(void)
13272 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13273 "[path ...]\n", getprogname());
13274 exit(1);
13277 static const struct got_error *
13278 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13279 const char *path, struct got_object_id *blob_id,
13280 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13281 int dirfd, const char *de_name)
13283 const struct got_error *err = NULL;
13284 char *id_str = NULL;
13286 if (staged_status != GOT_STATUS_ADD &&
13287 staged_status != GOT_STATUS_MODIFY &&
13288 staged_status != GOT_STATUS_DELETE)
13289 return NULL;
13291 if (staged_status == GOT_STATUS_ADD ||
13292 staged_status == GOT_STATUS_MODIFY)
13293 err = got_object_id_str(&id_str, staged_blob_id);
13294 else
13295 err = got_object_id_str(&id_str, blob_id);
13296 if (err)
13297 return err;
13299 printf("%s %c %s\n", id_str, staged_status, path);
13300 free(id_str);
13301 return NULL;
13304 static const struct got_error *
13305 cmd_stage(int argc, char *argv[])
13307 const struct got_error *error = NULL;
13308 struct got_repository *repo = NULL;
13309 struct got_worktree *worktree = NULL;
13310 char *cwd = NULL;
13311 struct got_pathlist_head paths;
13312 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13313 FILE *patch_script_file = NULL;
13314 const char *patch_script_path = NULL;
13315 struct choose_patch_arg cpa;
13316 int *pack_fds = NULL;
13318 TAILQ_INIT(&paths);
13320 #ifndef PROFILE
13321 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13322 "unveil", NULL) == -1)
13323 err(1, "pledge");
13324 #endif
13326 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13327 switch (ch) {
13328 case 'F':
13329 patch_script_path = optarg;
13330 break;
13331 case 'l':
13332 list_stage = 1;
13333 break;
13334 case 'p':
13335 pflag = 1;
13336 break;
13337 case 'S':
13338 allow_bad_symlinks = 1;
13339 break;
13340 default:
13341 usage_stage();
13342 /* NOTREACHED */
13346 argc -= optind;
13347 argv += optind;
13349 if (list_stage && (pflag || patch_script_path))
13350 errx(1, "-l option cannot be used with other options");
13351 if (patch_script_path && !pflag)
13352 errx(1, "-F option can only be used together with -p option");
13354 cwd = getcwd(NULL, 0);
13355 if (cwd == NULL) {
13356 error = got_error_from_errno("getcwd");
13357 goto done;
13360 error = got_repo_pack_fds_open(&pack_fds);
13361 if (error != NULL)
13362 goto done;
13364 error = got_worktree_open(&worktree, cwd);
13365 if (error) {
13366 if (error->code == GOT_ERR_NOT_WORKTREE)
13367 error = wrap_not_worktree_error(error, "stage", cwd);
13368 goto done;
13371 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13372 NULL, pack_fds);
13373 if (error != NULL)
13374 goto done;
13376 if (patch_script_path) {
13377 patch_script_file = fopen(patch_script_path, "re");
13378 if (patch_script_file == NULL) {
13379 error = got_error_from_errno2("fopen",
13380 patch_script_path);
13381 goto done;
13384 error = apply_unveil(got_repo_get_path(repo), 0,
13385 got_worktree_get_root_path(worktree));
13386 if (error)
13387 goto done;
13389 error = check_merge_in_progress(worktree, repo);
13390 if (error)
13391 goto done;
13393 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13394 if (error)
13395 goto done;
13397 if (list_stage)
13398 error = got_worktree_status(worktree, &paths, repo, 0,
13399 print_stage, NULL, check_cancelled, NULL);
13400 else {
13401 cpa.patch_script_file = patch_script_file;
13402 cpa.action = "stage";
13403 error = got_worktree_stage(worktree, &paths,
13404 pflag ? NULL : print_status, NULL,
13405 pflag ? choose_patch : NULL, &cpa,
13406 allow_bad_symlinks, repo);
13408 done:
13409 if (patch_script_file && fclose(patch_script_file) == EOF &&
13410 error == NULL)
13411 error = got_error_from_errno2("fclose", patch_script_path);
13412 if (repo) {
13413 const struct got_error *close_err = got_repo_close(repo);
13414 if (error == NULL)
13415 error = close_err;
13417 if (worktree)
13418 got_worktree_close(worktree);
13419 if (pack_fds) {
13420 const struct got_error *pack_err =
13421 got_repo_pack_fds_close(pack_fds);
13422 if (error == NULL)
13423 error = pack_err;
13425 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13426 free(cwd);
13427 return error;
13430 __dead static void
13431 usage_unstage(void)
13433 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13434 "[path ...]\n", getprogname());
13435 exit(1);
13439 static const struct got_error *
13440 cmd_unstage(int argc, char *argv[])
13442 const struct got_error *error = NULL;
13443 struct got_repository *repo = NULL;
13444 struct got_worktree *worktree = NULL;
13445 char *cwd = NULL;
13446 struct got_pathlist_head paths;
13447 int ch, pflag = 0;
13448 struct got_update_progress_arg upa;
13449 FILE *patch_script_file = NULL;
13450 const char *patch_script_path = NULL;
13451 struct choose_patch_arg cpa;
13452 int *pack_fds = NULL;
13454 TAILQ_INIT(&paths);
13456 #ifndef PROFILE
13457 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13458 "unveil", NULL) == -1)
13459 err(1, "pledge");
13460 #endif
13462 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13463 switch (ch) {
13464 case 'F':
13465 patch_script_path = optarg;
13466 break;
13467 case 'p':
13468 pflag = 1;
13469 break;
13470 default:
13471 usage_unstage();
13472 /* NOTREACHED */
13476 argc -= optind;
13477 argv += optind;
13479 if (patch_script_path && !pflag)
13480 errx(1, "-F option can only be used together with -p option");
13482 cwd = getcwd(NULL, 0);
13483 if (cwd == NULL) {
13484 error = got_error_from_errno("getcwd");
13485 goto done;
13488 error = got_repo_pack_fds_open(&pack_fds);
13489 if (error != NULL)
13490 goto done;
13492 error = got_worktree_open(&worktree, cwd);
13493 if (error) {
13494 if (error->code == GOT_ERR_NOT_WORKTREE)
13495 error = wrap_not_worktree_error(error, "unstage", cwd);
13496 goto done;
13499 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13500 NULL, pack_fds);
13501 if (error != NULL)
13502 goto done;
13504 if (patch_script_path) {
13505 patch_script_file = fopen(patch_script_path, "re");
13506 if (patch_script_file == NULL) {
13507 error = got_error_from_errno2("fopen",
13508 patch_script_path);
13509 goto done;
13513 error = apply_unveil(got_repo_get_path(repo), 0,
13514 got_worktree_get_root_path(worktree));
13515 if (error)
13516 goto done;
13518 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13519 if (error)
13520 goto done;
13522 cpa.patch_script_file = patch_script_file;
13523 cpa.action = "unstage";
13524 memset(&upa, 0, sizeof(upa));
13525 error = got_worktree_unstage(worktree, &paths, update_progress,
13526 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13527 if (!error)
13528 print_merge_progress_stats(&upa);
13529 done:
13530 if (patch_script_file && fclose(patch_script_file) == EOF &&
13531 error == NULL)
13532 error = got_error_from_errno2("fclose", patch_script_path);
13533 if (repo) {
13534 const struct got_error *close_err = got_repo_close(repo);
13535 if (error == NULL)
13536 error = close_err;
13538 if (worktree)
13539 got_worktree_close(worktree);
13540 if (pack_fds) {
13541 const struct got_error *pack_err =
13542 got_repo_pack_fds_close(pack_fds);
13543 if (error == NULL)
13544 error = pack_err;
13546 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13547 free(cwd);
13548 return error;
13551 __dead static void
13552 usage_cat(void)
13554 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13555 "arg ...\n", getprogname());
13556 exit(1);
13559 static const struct got_error *
13560 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13562 const struct got_error *err;
13563 struct got_blob_object *blob;
13564 int fd = -1;
13566 fd = got_opentempfd();
13567 if (fd == -1)
13568 return got_error_from_errno("got_opentempfd");
13570 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13571 if (err)
13572 goto done;
13574 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13575 done:
13576 if (fd != -1 && close(fd) == -1 && err == NULL)
13577 err = got_error_from_errno("close");
13578 if (blob)
13579 got_object_blob_close(blob);
13580 return err;
13583 static const struct got_error *
13584 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13586 const struct got_error *err;
13587 struct got_tree_object *tree;
13588 int nentries, i;
13590 err = got_object_open_as_tree(&tree, repo, id);
13591 if (err)
13592 return err;
13594 nentries = got_object_tree_get_nentries(tree);
13595 for (i = 0; i < nentries; i++) {
13596 struct got_tree_entry *te;
13597 char *id_str;
13598 if (sigint_received || sigpipe_received)
13599 break;
13600 te = got_object_tree_get_entry(tree, i);
13601 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13602 if (err)
13603 break;
13604 fprintf(outfile, "%s %.7o %s\n", id_str,
13605 got_tree_entry_get_mode(te),
13606 got_tree_entry_get_name(te));
13607 free(id_str);
13610 got_object_tree_close(tree);
13611 return err;
13614 static const struct got_error *
13615 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13617 const struct got_error *err;
13618 struct got_commit_object *commit;
13619 const struct got_object_id_queue *parent_ids;
13620 struct got_object_qid *pid;
13621 char *id_str = NULL;
13622 const char *logmsg = NULL;
13623 char gmtoff[6];
13625 err = got_object_open_as_commit(&commit, repo, id);
13626 if (err)
13627 return err;
13629 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13630 if (err)
13631 goto done;
13633 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13634 parent_ids = got_object_commit_get_parent_ids(commit);
13635 fprintf(outfile, "numparents %d\n",
13636 got_object_commit_get_nparents(commit));
13637 STAILQ_FOREACH(pid, parent_ids, entry) {
13638 char *pid_str;
13639 err = got_object_id_str(&pid_str, &pid->id);
13640 if (err)
13641 goto done;
13642 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13643 free(pid_str);
13645 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13646 got_object_commit_get_author_gmtoff(commit));
13647 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13648 got_object_commit_get_author(commit),
13649 (long long)got_object_commit_get_author_time(commit),
13650 gmtoff);
13652 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13653 got_object_commit_get_committer_gmtoff(commit));
13654 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13655 got_object_commit_get_committer(commit),
13656 (long long)got_object_commit_get_committer_time(commit),
13657 gmtoff);
13659 logmsg = got_object_commit_get_logmsg_raw(commit);
13660 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13661 fprintf(outfile, "%s", logmsg);
13662 done:
13663 free(id_str);
13664 got_object_commit_close(commit);
13665 return err;
13668 static const struct got_error *
13669 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13671 const struct got_error *err;
13672 struct got_tag_object *tag;
13673 char *id_str = NULL;
13674 const char *tagmsg = NULL;
13675 char gmtoff[6];
13677 err = got_object_open_as_tag(&tag, repo, id);
13678 if (err)
13679 return err;
13681 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13682 if (err)
13683 goto done;
13685 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13687 switch (got_object_tag_get_object_type(tag)) {
13688 case GOT_OBJ_TYPE_BLOB:
13689 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13690 GOT_OBJ_LABEL_BLOB);
13691 break;
13692 case GOT_OBJ_TYPE_TREE:
13693 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13694 GOT_OBJ_LABEL_TREE);
13695 break;
13696 case GOT_OBJ_TYPE_COMMIT:
13697 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13698 GOT_OBJ_LABEL_COMMIT);
13699 break;
13700 case GOT_OBJ_TYPE_TAG:
13701 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13702 GOT_OBJ_LABEL_TAG);
13703 break;
13704 default:
13705 break;
13708 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13709 got_object_tag_get_name(tag));
13711 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13712 got_object_tag_get_tagger_gmtoff(tag));
13713 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13714 got_object_tag_get_tagger(tag),
13715 (long long)got_object_tag_get_tagger_time(tag),
13716 gmtoff);
13718 tagmsg = got_object_tag_get_message(tag);
13719 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13720 fprintf(outfile, "%s", tagmsg);
13721 done:
13722 free(id_str);
13723 got_object_tag_close(tag);
13724 return err;
13727 static const struct got_error *
13728 cmd_cat(int argc, char *argv[])
13730 const struct got_error *error;
13731 struct got_repository *repo = NULL;
13732 struct got_worktree *worktree = NULL;
13733 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13734 const char *commit_id_str = NULL;
13735 struct got_object_id *id = NULL, *commit_id = NULL;
13736 struct got_commit_object *commit = NULL;
13737 int ch, obj_type, i, force_path = 0;
13738 struct got_reflist_head refs;
13739 int *pack_fds = NULL;
13741 TAILQ_INIT(&refs);
13743 #ifndef PROFILE
13744 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13745 NULL) == -1)
13746 err(1, "pledge");
13747 #endif
13749 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13750 switch (ch) {
13751 case 'c':
13752 commit_id_str = optarg;
13753 break;
13754 case 'P':
13755 force_path = 1;
13756 break;
13757 case 'r':
13758 repo_path = realpath(optarg, NULL);
13759 if (repo_path == NULL)
13760 return got_error_from_errno2("realpath",
13761 optarg);
13762 got_path_strip_trailing_slashes(repo_path);
13763 break;
13764 default:
13765 usage_cat();
13766 /* NOTREACHED */
13770 argc -= optind;
13771 argv += optind;
13773 cwd = getcwd(NULL, 0);
13774 if (cwd == NULL) {
13775 error = got_error_from_errno("getcwd");
13776 goto done;
13779 error = got_repo_pack_fds_open(&pack_fds);
13780 if (error != NULL)
13781 goto done;
13783 if (repo_path == NULL) {
13784 error = got_worktree_open(&worktree, cwd);
13785 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13786 goto done;
13787 if (worktree) {
13788 repo_path = strdup(
13789 got_worktree_get_repo_path(worktree));
13790 if (repo_path == NULL) {
13791 error = got_error_from_errno("strdup");
13792 goto done;
13795 /* Release work tree lock. */
13796 got_worktree_close(worktree);
13797 worktree = NULL;
13801 if (repo_path == NULL) {
13802 repo_path = strdup(cwd);
13803 if (repo_path == NULL)
13804 return got_error_from_errno("strdup");
13807 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13808 free(repo_path);
13809 if (error != NULL)
13810 goto done;
13812 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13813 if (error)
13814 goto done;
13816 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13817 if (error)
13818 goto done;
13820 if (commit_id_str == NULL)
13821 commit_id_str = GOT_REF_HEAD;
13822 error = got_repo_match_object_id(&commit_id, NULL,
13823 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13824 if (error)
13825 goto done;
13827 error = got_object_open_as_commit(&commit, repo, commit_id);
13828 if (error)
13829 goto done;
13831 for (i = 0; i < argc; i++) {
13832 if (force_path) {
13833 error = got_object_id_by_path(&id, repo, commit,
13834 argv[i]);
13835 if (error)
13836 break;
13837 } else {
13838 error = got_repo_match_object_id(&id, &label, argv[i],
13839 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13840 repo);
13841 if (error) {
13842 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13843 error->code != GOT_ERR_NOT_REF)
13844 break;
13845 error = got_object_id_by_path(&id, repo,
13846 commit, argv[i]);
13847 if (error)
13848 break;
13852 error = got_object_get_type(&obj_type, repo, id);
13853 if (error)
13854 break;
13856 switch (obj_type) {
13857 case GOT_OBJ_TYPE_BLOB:
13858 error = cat_blob(id, repo, stdout);
13859 break;
13860 case GOT_OBJ_TYPE_TREE:
13861 error = cat_tree(id, repo, stdout);
13862 break;
13863 case GOT_OBJ_TYPE_COMMIT:
13864 error = cat_commit(id, repo, stdout);
13865 break;
13866 case GOT_OBJ_TYPE_TAG:
13867 error = cat_tag(id, repo, stdout);
13868 break;
13869 default:
13870 error = got_error(GOT_ERR_OBJ_TYPE);
13871 break;
13873 if (error)
13874 break;
13875 free(label);
13876 label = NULL;
13877 free(id);
13878 id = NULL;
13880 done:
13881 free(label);
13882 free(id);
13883 free(commit_id);
13884 if (commit)
13885 got_object_commit_close(commit);
13886 if (worktree)
13887 got_worktree_close(worktree);
13888 if (repo) {
13889 const struct got_error *close_err = got_repo_close(repo);
13890 if (error == NULL)
13891 error = close_err;
13893 if (pack_fds) {
13894 const struct got_error *pack_err =
13895 got_repo_pack_fds_close(pack_fds);
13896 if (error == NULL)
13897 error = pack_err;
13900 got_ref_list_free(&refs);
13901 return error;
13904 __dead static void
13905 usage_info(void)
13907 fprintf(stderr, "usage: %s info [path ...]\n",
13908 getprogname());
13909 exit(1);
13912 static const struct got_error *
13913 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13914 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13915 struct got_object_id *commit_id)
13917 const struct got_error *err = NULL;
13918 char *id_str = NULL;
13919 char datebuf[128];
13920 struct tm mytm, *tm;
13921 struct got_pathlist_head *paths = arg;
13922 struct got_pathlist_entry *pe;
13925 * Clear error indication from any of the path arguments which
13926 * would cause this file index entry to be displayed.
13928 TAILQ_FOREACH(pe, paths, entry) {
13929 if (got_path_cmp(path, pe->path, strlen(path),
13930 pe->path_len) == 0 ||
13931 got_path_is_child(path, pe->path, pe->path_len))
13932 pe->data = NULL; /* no error */
13935 printf(GOT_COMMIT_SEP_STR);
13936 if (S_ISLNK(mode))
13937 printf("symlink: %s\n", path);
13938 else if (S_ISREG(mode)) {
13939 printf("file: %s\n", path);
13940 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13941 } else if (S_ISDIR(mode))
13942 printf("directory: %s\n", path);
13943 else
13944 printf("something: %s\n", path);
13946 tm = localtime_r(&mtime, &mytm);
13947 if (tm == NULL)
13948 return NULL;
13949 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13950 return got_error(GOT_ERR_NO_SPACE);
13951 printf("timestamp: %s\n", datebuf);
13953 if (blob_id) {
13954 err = got_object_id_str(&id_str, blob_id);
13955 if (err)
13956 return err;
13957 printf("based on blob: %s\n", id_str);
13958 free(id_str);
13961 if (staged_blob_id) {
13962 err = got_object_id_str(&id_str, staged_blob_id);
13963 if (err)
13964 return err;
13965 printf("based on staged blob: %s\n", id_str);
13966 free(id_str);
13969 if (commit_id) {
13970 err = got_object_id_str(&id_str, commit_id);
13971 if (err)
13972 return err;
13973 printf("based on commit: %s\n", id_str);
13974 free(id_str);
13977 return NULL;
13980 static const struct got_error *
13981 cmd_info(int argc, char *argv[])
13983 const struct got_error *error = NULL;
13984 struct got_worktree *worktree = NULL;
13985 char *cwd = NULL, *id_str = NULL;
13986 struct got_pathlist_head paths;
13987 char *uuidstr = NULL;
13988 int ch, show_files = 0;
13990 TAILQ_INIT(&paths);
13992 #ifndef PROFILE
13993 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13994 NULL) == -1)
13995 err(1, "pledge");
13996 #endif
13998 while ((ch = getopt(argc, argv, "")) != -1) {
13999 switch (ch) {
14000 default:
14001 usage_info();
14002 /* NOTREACHED */
14006 argc -= optind;
14007 argv += optind;
14009 cwd = getcwd(NULL, 0);
14010 if (cwd == NULL) {
14011 error = got_error_from_errno("getcwd");
14012 goto done;
14015 error = got_worktree_open(&worktree, cwd);
14016 if (error) {
14017 if (error->code == GOT_ERR_NOT_WORKTREE)
14018 error = wrap_not_worktree_error(error, "info", cwd);
14019 goto done;
14022 #ifndef PROFILE
14023 /* Remove "wpath cpath proc exec sendfd" promises. */
14024 if (pledge("stdio rpath flock unveil", NULL) == -1)
14025 err(1, "pledge");
14026 #endif
14027 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14028 if (error)
14029 goto done;
14031 if (argc >= 1) {
14032 error = get_worktree_paths_from_argv(&paths, argc, argv,
14033 worktree);
14034 if (error)
14035 goto done;
14036 show_files = 1;
14039 error = got_object_id_str(&id_str,
14040 got_worktree_get_base_commit_id(worktree));
14041 if (error)
14042 goto done;
14044 error = got_worktree_get_uuid(&uuidstr, worktree);
14045 if (error)
14046 goto done;
14048 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14049 printf("work tree base commit: %s\n", id_str);
14050 printf("work tree path prefix: %s\n",
14051 got_worktree_get_path_prefix(worktree));
14052 printf("work tree branch reference: %s\n",
14053 got_worktree_get_head_ref_name(worktree));
14054 printf("work tree UUID: %s\n", uuidstr);
14055 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14057 if (show_files) {
14058 struct got_pathlist_entry *pe;
14059 TAILQ_FOREACH(pe, &paths, entry) {
14060 if (pe->path_len == 0)
14061 continue;
14063 * Assume this path will fail. This will be corrected
14064 * in print_path_info() in case the path does suceeed.
14066 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14068 error = got_worktree_path_info(worktree, &paths,
14069 print_path_info, &paths, check_cancelled, NULL);
14070 if (error)
14071 goto done;
14072 TAILQ_FOREACH(pe, &paths, entry) {
14073 if (pe->data != NULL) {
14074 const struct got_error *perr;
14076 perr = pe->data;
14077 error = got_error_fmt(perr->code, "%s",
14078 pe->path);
14079 break;
14083 done:
14084 if (worktree)
14085 got_worktree_close(worktree);
14086 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14087 free(cwd);
14088 free(id_str);
14089 free(uuidstr);
14090 return error;