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 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
763 switch (ch) {
764 case 'b':
765 branch_name = optarg;
766 break;
767 case 'I':
768 if (optarg[0] == '\0')
769 break;
770 error = got_pathlist_insert(&pe, &ignores, optarg,
771 NULL);
772 if (error)
773 goto done;
774 break;
775 case 'm':
776 logmsg = strdup(optarg);
777 if (logmsg == NULL) {
778 error = got_error_from_errno("strdup");
779 goto done;
781 break;
782 case 'r':
783 repo_path = realpath(optarg, NULL);
784 if (repo_path == NULL) {
785 error = got_error_from_errno2("realpath",
786 optarg);
787 goto done;
789 break;
790 default:
791 usage_import();
792 /* NOTREACHED */
796 argc -= optind;
797 argv += optind;
799 #ifndef PROFILE
800 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
801 "unveil",
802 NULL) == -1)
803 err(1, "pledge");
804 #endif
805 if (argc != 1)
806 usage_import();
808 if (repo_path == NULL) {
809 repo_path = getcwd(NULL, 0);
810 if (repo_path == NULL)
811 return got_error_from_errno("getcwd");
813 got_path_strip_trailing_slashes(repo_path);
814 error = get_gitconfig_path(&gitconfig_path);
815 if (error)
816 goto done;
817 error = got_repo_pack_fds_open(&pack_fds);
818 if (error != NULL)
819 goto done;
820 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
821 if (error)
822 goto done;
824 error = get_author(&author, repo, NULL);
825 if (error)
826 return error;
828 /*
829 * Don't let the user create a branch name with a leading '-'.
830 * While technically a valid reference name, this case is usually
831 * an unintended typo.
832 */
833 if (branch_name && branch_name[0] == '-')
834 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
836 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
837 if (error && error->code != GOT_ERR_NOT_REF)
838 goto done;
840 if (branch_name)
841 n = strlcat(refname, branch_name, sizeof(refname));
842 else if (head_ref && got_ref_is_symbolic(head_ref))
843 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
844 sizeof(refname));
845 else
846 n = strlcat(refname, "main", sizeof(refname));
847 if (n >= sizeof(refname)) {
848 error = got_error(GOT_ERR_NO_SPACE);
849 goto done;
852 error = got_ref_open(&branch_ref, repo, refname, 0);
853 if (error) {
854 if (error->code != GOT_ERR_NOT_REF)
855 goto done;
856 } else {
857 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
858 "import target branch already exists");
859 goto done;
862 path_dir = realpath(argv[0], NULL);
863 if (path_dir == NULL) {
864 error = got_error_from_errno2("realpath", argv[0]);
865 goto done;
867 got_path_strip_trailing_slashes(path_dir);
869 /*
870 * unveil(2) traverses exec(2); if an editor is used we have
871 * to apply unveil after the log message has been written.
872 */
873 if (logmsg == NULL || strlen(logmsg) == 0) {
874 error = get_editor(&editor);
875 if (error)
876 goto done;
877 free(logmsg);
878 error = collect_import_msg(&logmsg, &logmsg_path, editor,
879 path_dir, refname);
880 if (error) {
881 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
882 logmsg_path != NULL)
883 preserve_logmsg = 1;
884 goto done;
888 if (unveil(path_dir, "r") != 0) {
889 error = got_error_from_errno2("unveil", path_dir);
890 if (logmsg_path)
891 preserve_logmsg = 1;
892 goto done;
895 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
896 if (error) {
897 if (logmsg_path)
898 preserve_logmsg = 1;
899 goto done;
902 error = got_repo_import(&new_commit_id, path_dir, logmsg,
903 author, &ignores, repo, import_progress, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
911 if (error) {
912 if (logmsg_path)
913 preserve_logmsg = 1;
914 goto done;
917 error = got_ref_write(branch_ref, repo);
918 if (error) {
919 if (logmsg_path)
920 preserve_logmsg = 1;
921 goto done;
924 error = got_object_id_str(&id_str, new_commit_id);
925 if (error) {
926 if (logmsg_path)
927 preserve_logmsg = 1;
928 goto done;
931 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
932 if (error) {
933 if (error->code != GOT_ERR_NOT_REF) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
940 branch_ref);
941 if (error) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_write(head_ref, repo);
948 if (error) {
949 if (logmsg_path)
950 preserve_logmsg = 1;
951 goto done;
955 printf("Created branch %s with commit %s\n",
956 got_ref_get_name(branch_ref), id_str);
957 done:
958 if (pack_fds) {
959 const struct got_error *pack_err =
960 got_repo_pack_fds_close(pack_fds);
961 if (error == NULL)
962 error = pack_err;
964 if (preserve_logmsg) {
965 fprintf(stderr, "%s: log message preserved in %s\n",
966 getprogname(), logmsg_path);
967 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
968 error = got_error_from_errno2("unlink", logmsg_path);
969 free(logmsg);
970 free(logmsg_path);
971 free(repo_path);
972 free(editor);
973 free(new_commit_id);
974 free(id_str);
975 free(author);
976 free(gitconfig_path);
977 if (branch_ref)
978 got_ref_close(branch_ref);
979 if (head_ref)
980 got_ref_close(head_ref);
981 return error;
984 __dead static void
985 usage_clone(void)
987 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
988 "repository-URL [directory]\n", getprogname());
989 exit(1);
992 struct got_fetch_progress_arg {
993 char last_scaled_size[FMT_SCALED_STRSIZE];
994 int last_p_indexed;
995 int last_p_resolved;
996 int verbosity;
998 struct got_repository *repo;
1000 int create_configs;
1001 int configs_created;
1002 struct {
1003 struct got_pathlist_head *symrefs;
1004 struct got_pathlist_head *wanted_branches;
1005 struct got_pathlist_head *wanted_refs;
1006 const char *proto;
1007 const char *host;
1008 const char *port;
1009 const char *remote_repo_path;
1010 const char *git_url;
1011 int fetch_all_branches;
1012 int mirror_references;
1013 } config_info;
1016 /* XXX forward declaration */
1017 static const struct got_error *
1018 create_config_files(const char *proto, const char *host, const char *port,
1019 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1020 int mirror_references, struct got_pathlist_head *symrefs,
1021 struct got_pathlist_head *wanted_branches,
1022 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1024 static const struct got_error *
1025 fetch_progress(void *arg, const char *message, off_t packfile_size,
1026 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1028 const struct got_error *err = NULL;
1029 struct got_fetch_progress_arg *a = arg;
1030 char scaled_size[FMT_SCALED_STRSIZE];
1031 int p_indexed, p_resolved;
1032 int print_size = 0, print_indexed = 0, print_resolved = 0;
1035 * In order to allow a failed clone to be resumed with 'got fetch'
1036 * we try to create configuration files as soon as possible.
1037 * Once the server has sent information about its default branch
1038 * we have all required information.
1040 if (a->create_configs && !a->configs_created &&
1041 !TAILQ_EMPTY(a->config_info.symrefs)) {
1042 err = create_config_files(a->config_info.proto,
1043 a->config_info.host, a->config_info.port,
1044 a->config_info.remote_repo_path,
1045 a->config_info.git_url,
1046 a->config_info.fetch_all_branches,
1047 a->config_info.mirror_references,
1048 a->config_info.symrefs,
1049 a->config_info.wanted_branches,
1050 a->config_info.wanted_refs, a->repo);
1051 if (err)
1052 return err;
1053 a->configs_created = 1;
1056 if (a->verbosity < 0)
1057 return NULL;
1059 if (message && message[0] != '\0') {
1060 printf("\rserver: %s", message);
1061 fflush(stdout);
1062 return NULL;
1065 if (packfile_size > 0 || nobj_indexed > 0) {
1066 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1067 (a->last_scaled_size[0] == '\0' ||
1068 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1069 print_size = 1;
1070 if (strlcpy(a->last_scaled_size, scaled_size,
1071 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1072 return got_error(GOT_ERR_NO_SPACE);
1074 if (nobj_indexed > 0) {
1075 p_indexed = (nobj_indexed * 100) / nobj_total;
1076 if (p_indexed != a->last_p_indexed) {
1077 a->last_p_indexed = p_indexed;
1078 print_indexed = 1;
1079 print_size = 1;
1082 if (nobj_resolved > 0) {
1083 p_resolved = (nobj_resolved * 100) /
1084 (nobj_total - nobj_loose);
1085 if (p_resolved != a->last_p_resolved) {
1086 a->last_p_resolved = p_resolved;
1087 print_resolved = 1;
1088 print_indexed = 1;
1089 print_size = 1;
1094 if (print_size || print_indexed || print_resolved)
1095 printf("\r");
1096 if (print_size)
1097 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1098 if (print_indexed)
1099 printf("; indexing %d%%", p_indexed);
1100 if (print_resolved)
1101 printf("; resolving deltas %d%%", p_resolved);
1102 if (print_size || print_indexed || print_resolved)
1103 fflush(stdout);
1105 return NULL;
1108 static const struct got_error *
1109 create_symref(const char *refname, struct got_reference *target_ref,
1110 int verbosity, struct got_repository *repo)
1112 const struct got_error *err;
1113 struct got_reference *head_symref;
1115 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1116 if (err)
1117 return err;
1119 err = got_ref_write(head_symref, repo);
1120 if (err == NULL && verbosity > 0) {
1121 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1122 got_ref_get_name(target_ref));
1124 got_ref_close(head_symref);
1125 return err;
1128 static const struct got_error *
1129 list_remote_refs(struct got_pathlist_head *symrefs,
1130 struct got_pathlist_head *refs)
1132 const struct got_error *err;
1133 struct got_pathlist_entry *pe;
1135 TAILQ_FOREACH(pe, symrefs, entry) {
1136 const char *refname = pe->path;
1137 const char *targetref = pe->data;
1139 printf("%s: %s\n", refname, targetref);
1142 TAILQ_FOREACH(pe, refs, entry) {
1143 const char *refname = pe->path;
1144 struct got_object_id *id = pe->data;
1145 char *id_str;
1147 err = got_object_id_str(&id_str, id);
1148 if (err)
1149 return err;
1150 printf("%s: %s\n", refname, id_str);
1151 free(id_str);
1154 return NULL;
1157 static const struct got_error *
1158 create_ref(const char *refname, struct got_object_id *id,
1159 int verbosity, struct got_repository *repo)
1161 const struct got_error *err = NULL;
1162 struct got_reference *ref;
1163 char *id_str;
1165 err = got_object_id_str(&id_str, id);
1166 if (err)
1167 return err;
1169 err = got_ref_alloc(&ref, refname, id);
1170 if (err)
1171 goto done;
1173 err = got_ref_write(ref, repo);
1174 got_ref_close(ref);
1176 if (err == NULL && verbosity >= 0)
1177 printf("Created reference %s: %s\n", refname, id_str);
1178 done:
1179 free(id_str);
1180 return err;
1183 static int
1184 match_wanted_ref(const char *refname, const char *wanted_ref)
1186 if (strncmp(refname, "refs/", 5) != 0)
1187 return 0;
1188 refname += 5;
1191 * Prevent fetching of references that won't make any
1192 * sense outside of the remote repository's context.
1194 if (strncmp(refname, "got/", 4) == 0)
1195 return 0;
1196 if (strncmp(refname, "remotes/", 8) == 0)
1197 return 0;
1199 if (strncmp(wanted_ref, "refs/", 5) == 0)
1200 wanted_ref += 5;
1202 /* Allow prefix match. */
1203 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1204 return 1;
1206 /* Allow exact match. */
1207 return (strcmp(refname, wanted_ref) == 0);
1210 static int
1211 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1213 struct got_pathlist_entry *pe;
1215 TAILQ_FOREACH(pe, wanted_refs, entry) {
1216 if (match_wanted_ref(refname, pe->path))
1217 return 1;
1220 return 0;
1223 static const struct got_error *
1224 create_wanted_ref(const char *refname, struct got_object_id *id,
1225 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1227 const struct got_error *err;
1228 char *remote_refname;
1230 if (strncmp("refs/", refname, 5) == 0)
1231 refname += 5;
1233 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1234 remote_repo_name, refname) == -1)
1235 return got_error_from_errno("asprintf");
1237 err = create_ref(remote_refname, id, verbosity, repo);
1238 free(remote_refname);
1239 return err;
1242 static const struct got_error *
1243 create_gotconfig(const char *proto, const char *host, const char *port,
1244 const char *remote_repo_path, const char *default_branch,
1245 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1246 struct got_pathlist_head *wanted_refs, int mirror_references,
1247 struct got_repository *repo)
1249 const struct got_error *err = NULL;
1250 char *gotconfig_path = NULL;
1251 char *gotconfig = NULL;
1252 FILE *gotconfig_file = NULL;
1253 const char *branchname = NULL;
1254 char *branches = NULL, *refs = NULL;
1255 ssize_t n;
1257 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1258 struct got_pathlist_entry *pe;
1259 TAILQ_FOREACH(pe, wanted_branches, entry) {
1260 char *s;
1261 branchname = pe->path;
1262 if (strncmp(branchname, "refs/heads/", 11) == 0)
1263 branchname += 11;
1264 if (asprintf(&s, "%s\"%s\" ",
1265 branches ? branches : "", branchname) == -1) {
1266 err = got_error_from_errno("asprintf");
1267 goto done;
1269 free(branches);
1270 branches = s;
1272 } else if (!fetch_all_branches && default_branch) {
1273 branchname = default_branch;
1274 if (strncmp(branchname, "refs/heads/", 11) == 0)
1275 branchname += 11;
1276 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1277 err = got_error_from_errno("asprintf");
1278 goto done;
1281 if (!TAILQ_EMPTY(wanted_refs)) {
1282 struct got_pathlist_entry *pe;
1283 TAILQ_FOREACH(pe, wanted_refs, entry) {
1284 char *s;
1285 const char *refname = pe->path;
1286 if (strncmp(refname, "refs/", 5) == 0)
1287 branchname += 5;
1288 if (asprintf(&s, "%s\"%s\" ",
1289 refs ? refs : "", refname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1293 free(refs);
1294 refs = s;
1298 /* Create got.conf(5). */
1299 gotconfig_path = got_repo_get_path_gotconfig(repo);
1300 if (gotconfig_path == NULL) {
1301 err = got_error_from_errno("got_repo_get_path_gotconfig");
1302 goto done;
1304 gotconfig_file = fopen(gotconfig_path, "ae");
1305 if (gotconfig_file == NULL) {
1306 err = got_error_from_errno2("fopen", gotconfig_path);
1307 goto done;
1309 if (asprintf(&gotconfig,
1310 "remote \"%s\" {\n"
1311 "\tserver %s\n"
1312 "\tprotocol %s\n"
1313 "%s%s%s"
1314 "\trepository \"%s\"\n"
1315 "%s%s%s"
1316 "%s%s%s"
1317 "%s"
1318 "%s"
1319 "}\n",
1320 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1321 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1322 remote_repo_path, branches ? "\tbranch { " : "",
1323 branches ? branches : "", branches ? "}\n" : "",
1324 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1325 mirror_references ? "\tmirror_references yes\n" : "",
1326 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1327 err = got_error_from_errno("asprintf");
1328 goto done;
1330 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1331 if (n != strlen(gotconfig)) {
1332 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1333 goto done;
1336 done:
1337 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1338 err = got_error_from_errno2("fclose", gotconfig_path);
1339 free(gotconfig_path);
1340 free(branches);
1341 return err;
1344 static const struct got_error *
1345 create_gitconfig(const char *git_url, const char *default_branch,
1346 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1347 struct got_pathlist_head *wanted_refs, int mirror_references,
1348 struct got_repository *repo)
1350 const struct got_error *err = NULL;
1351 char *gitconfig_path = NULL;
1352 char *gitconfig = NULL;
1353 FILE *gitconfig_file = NULL;
1354 char *branches = NULL, *refs = NULL;
1355 const char *branchname;
1356 ssize_t n;
1358 /* Create a config file Git can understand. */
1359 gitconfig_path = got_repo_get_path_gitconfig(repo);
1360 if (gitconfig_path == NULL) {
1361 err = got_error_from_errno("got_repo_get_path_gitconfig");
1362 goto done;
1364 gitconfig_file = fopen(gitconfig_path, "ae");
1365 if (gitconfig_file == NULL) {
1366 err = got_error_from_errno2("fopen", gitconfig_path);
1367 goto done;
1369 if (fetch_all_branches) {
1370 if (mirror_references) {
1371 if (asprintf(&branches,
1372 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1373 err = got_error_from_errno("asprintf");
1374 goto done;
1376 } else if (asprintf(&branches,
1377 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1378 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1379 err = got_error_from_errno("asprintf");
1380 goto done;
1382 } else if (!TAILQ_EMPTY(wanted_branches)) {
1383 struct got_pathlist_entry *pe;
1384 TAILQ_FOREACH(pe, wanted_branches, entry) {
1385 char *s;
1386 branchname = pe->path;
1387 if (strncmp(branchname, "refs/heads/", 11) == 0)
1388 branchname += 11;
1389 if (mirror_references) {
1390 if (asprintf(&s,
1391 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1392 branches ? branches : "",
1393 branchname, branchname) == -1) {
1394 err = got_error_from_errno("asprintf");
1395 goto done;
1397 } else if (asprintf(&s,
1398 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1399 branches ? branches : "",
1400 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1401 branchname) == -1) {
1402 err = got_error_from_errno("asprintf");
1403 goto done;
1405 free(branches);
1406 branches = s;
1408 } else {
1410 * If the server specified a default branch, use just that one.
1411 * Otherwise fall back to fetching all branches on next fetch.
1413 if (default_branch) {
1414 branchname = default_branch;
1415 if (strncmp(branchname, "refs/heads/", 11) == 0)
1416 branchname += 11;
1417 } else
1418 branchname = "*"; /* fall back to all branches */
1419 if (mirror_references) {
1420 if (asprintf(&branches,
1421 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1422 branchname, branchname) == -1) {
1423 err = got_error_from_errno("asprintf");
1424 goto done;
1426 } else if (asprintf(&branches,
1427 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1428 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1429 branchname) == -1) {
1430 err = got_error_from_errno("asprintf");
1431 goto done;
1434 if (!TAILQ_EMPTY(wanted_refs)) {
1435 struct got_pathlist_entry *pe;
1436 TAILQ_FOREACH(pe, wanted_refs, entry) {
1437 char *s;
1438 const char *refname = pe->path;
1439 if (strncmp(refname, "refs/", 5) == 0)
1440 refname += 5;
1441 if (mirror_references) {
1442 if (asprintf(&s,
1443 "%s\tfetch = refs/%s:refs/%s\n",
1444 refs ? refs : "", refname, refname) == -1) {
1445 err = got_error_from_errno("asprintf");
1446 goto done;
1448 } else if (asprintf(&s,
1449 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1450 refs ? refs : "",
1451 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1452 refname) == -1) {
1453 err = got_error_from_errno("asprintf");
1454 goto done;
1456 free(refs);
1457 refs = s;
1461 if (asprintf(&gitconfig,
1462 "[remote \"%s\"]\n"
1463 "\turl = %s\n"
1464 "%s"
1465 "%s"
1466 "\tfetch = refs/tags/*:refs/tags/*\n",
1467 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1468 refs ? refs : "") == -1) {
1469 err = got_error_from_errno("asprintf");
1470 goto done;
1472 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1473 if (n != strlen(gitconfig)) {
1474 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1475 goto done;
1477 done:
1478 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1479 err = got_error_from_errno2("fclose", gitconfig_path);
1480 free(gitconfig_path);
1481 free(branches);
1482 return err;
1485 static const struct got_error *
1486 create_config_files(const char *proto, const char *host, const char *port,
1487 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1488 int mirror_references, struct got_pathlist_head *symrefs,
1489 struct got_pathlist_head *wanted_branches,
1490 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1492 const struct got_error *err = NULL;
1493 const char *default_branch = NULL;
1494 struct got_pathlist_entry *pe;
1497 * If we asked for a set of wanted branches then use the first
1498 * one of those.
1500 if (!TAILQ_EMPTY(wanted_branches)) {
1501 pe = TAILQ_FIRST(wanted_branches);
1502 default_branch = pe->path;
1503 } else {
1504 /* First HEAD ref listed by server is the default branch. */
1505 TAILQ_FOREACH(pe, symrefs, entry) {
1506 const char *refname = pe->path;
1507 const char *target = pe->data;
1509 if (strcmp(refname, GOT_REF_HEAD) != 0)
1510 continue;
1512 default_branch = target;
1513 break;
1517 /* Create got.conf(5). */
1518 err = create_gotconfig(proto, host, port, remote_repo_path,
1519 default_branch, fetch_all_branches, wanted_branches,
1520 wanted_refs, mirror_references, repo);
1521 if (err)
1522 return err;
1524 /* Create a config file Git can understand. */
1525 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1526 wanted_branches, wanted_refs, mirror_references, repo);
1529 static const struct got_error *
1530 cmd_clone(int argc, char *argv[])
1532 const struct got_error *error = NULL;
1533 const char *uri, *dirname;
1534 char *proto, *host, *port, *repo_name, *server_path;
1535 char *default_destdir = NULL, *id_str = NULL;
1536 const char *repo_path;
1537 struct got_repository *repo = NULL;
1538 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1539 struct got_pathlist_entry *pe;
1540 struct got_object_id *pack_hash = NULL;
1541 int ch, fetchfd = -1, fetchstatus;
1542 pid_t fetchpid = -1;
1543 struct got_fetch_progress_arg fpa;
1544 char *git_url = NULL;
1545 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1546 int list_refs_only = 0;
1547 int *pack_fds = NULL;
1549 TAILQ_INIT(&refs);
1550 TAILQ_INIT(&symrefs);
1551 TAILQ_INIT(&wanted_branches);
1552 TAILQ_INIT(&wanted_refs);
1554 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1555 switch (ch) {
1556 case 'a':
1557 fetch_all_branches = 1;
1558 break;
1559 case 'b':
1560 error = got_pathlist_append(&wanted_branches,
1561 optarg, NULL);
1562 if (error)
1563 return error;
1564 break;
1565 case 'l':
1566 list_refs_only = 1;
1567 break;
1568 case 'm':
1569 mirror_references = 1;
1570 break;
1571 case 'q':
1572 verbosity = -1;
1573 break;
1574 case 'R':
1575 error = got_pathlist_append(&wanted_refs,
1576 optarg, NULL);
1577 if (error)
1578 return error;
1579 break;
1580 case 'v':
1581 if (verbosity < 0)
1582 verbosity = 0;
1583 else if (verbosity < 3)
1584 verbosity++;
1585 break;
1586 default:
1587 usage_clone();
1588 break;
1591 argc -= optind;
1592 argv += optind;
1594 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1595 option_conflict('a', 'b');
1596 if (list_refs_only) {
1597 if (!TAILQ_EMPTY(&wanted_branches))
1598 option_conflict('l', 'b');
1599 if (fetch_all_branches)
1600 option_conflict('l', 'a');
1601 if (mirror_references)
1602 option_conflict('l', 'm');
1603 if (!TAILQ_EMPTY(&wanted_refs))
1604 option_conflict('l', 'R');
1607 uri = argv[0];
1609 if (argc == 1)
1610 dirname = NULL;
1611 else if (argc == 2)
1612 dirname = argv[1];
1613 else
1614 usage_clone();
1616 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1617 &repo_name, uri);
1618 if (error)
1619 goto done;
1621 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1622 host, port ? ":" : "", port ? port : "",
1623 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1624 error = got_error_from_errno("asprintf");
1625 goto done;
1628 if (strcmp(proto, "git") == 0) {
1629 #ifndef PROFILE
1630 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1631 "sendfd dns inet unveil", NULL) == -1)
1632 err(1, "pledge");
1633 #endif
1634 } else if (strcmp(proto, "git+ssh") == 0 ||
1635 strcmp(proto, "ssh") == 0) {
1636 #ifndef PROFILE
1637 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1638 "sendfd unveil", NULL) == -1)
1639 err(1, "pledge");
1640 #endif
1641 } else if (strcmp(proto, "http") == 0 ||
1642 strcmp(proto, "git+http") == 0) {
1643 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1644 goto done;
1645 } else {
1646 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1647 goto done;
1649 if (dirname == NULL) {
1650 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1651 error = got_error_from_errno("asprintf");
1652 goto done;
1654 repo_path = default_destdir;
1655 } else
1656 repo_path = dirname;
1658 if (!list_refs_only) {
1659 error = got_path_mkdir(repo_path);
1660 if (error &&
1661 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1662 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1663 goto done;
1664 if (!got_path_dir_is_empty(repo_path)) {
1665 error = got_error_path(repo_path,
1666 GOT_ERR_DIR_NOT_EMPTY);
1667 goto done;
1671 error = got_dial_apply_unveil(proto);
1672 if (error)
1673 goto done;
1675 error = apply_unveil(repo_path, 0, NULL);
1676 if (error)
1677 goto done;
1679 if (verbosity >= 0)
1680 printf("Connecting to %s\n", git_url);
1682 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1683 server_path, verbosity);
1684 if (error)
1685 goto done;
1687 if (!list_refs_only) {
1688 error = got_repo_init(repo_path, NULL);
1689 if (error)
1690 goto done;
1691 error = got_repo_pack_fds_open(&pack_fds);
1692 if (error != NULL)
1693 goto done;
1694 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1695 if (error)
1696 goto done;
1699 fpa.last_scaled_size[0] = '\0';
1700 fpa.last_p_indexed = -1;
1701 fpa.last_p_resolved = -1;
1702 fpa.verbosity = verbosity;
1703 fpa.create_configs = 1;
1704 fpa.configs_created = 0;
1705 fpa.repo = repo;
1706 fpa.config_info.symrefs = &symrefs;
1707 fpa.config_info.wanted_branches = &wanted_branches;
1708 fpa.config_info.wanted_refs = &wanted_refs;
1709 fpa.config_info.proto = proto;
1710 fpa.config_info.host = host;
1711 fpa.config_info.port = port;
1712 fpa.config_info.remote_repo_path = server_path;
1713 fpa.config_info.git_url = git_url;
1714 fpa.config_info.fetch_all_branches = fetch_all_branches;
1715 fpa.config_info.mirror_references = mirror_references;
1716 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1717 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1718 fetch_all_branches, &wanted_branches, &wanted_refs,
1719 list_refs_only, verbosity, fetchfd, repo, NULL,
1720 fetch_progress, &fpa);
1721 if (error)
1722 goto done;
1724 if (list_refs_only) {
1725 error = list_remote_refs(&symrefs, &refs);
1726 goto done;
1729 if (pack_hash == NULL) {
1730 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1731 "server sent an empty pack file");
1732 goto done;
1734 error = got_object_id_str(&id_str, pack_hash);
1735 if (error)
1736 goto done;
1737 if (verbosity >= 0)
1738 printf("\nFetched %s.pack\n", id_str);
1739 free(id_str);
1741 /* Set up references provided with the pack file. */
1742 TAILQ_FOREACH(pe, &refs, entry) {
1743 const char *refname = pe->path;
1744 struct got_object_id *id = pe->data;
1745 char *remote_refname;
1747 if (is_wanted_ref(&wanted_refs, refname) &&
1748 !mirror_references) {
1749 error = create_wanted_ref(refname, id,
1750 GOT_FETCH_DEFAULT_REMOTE_NAME,
1751 verbosity - 1, repo);
1752 if (error)
1753 goto done;
1754 continue;
1757 error = create_ref(refname, id, verbosity - 1, repo);
1758 if (error)
1759 goto done;
1761 if (mirror_references)
1762 continue;
1764 if (strncmp("refs/heads/", refname, 11) != 0)
1765 continue;
1767 if (asprintf(&remote_refname,
1768 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 refname + 11) == -1) {
1770 error = got_error_from_errno("asprintf");
1771 goto done;
1773 error = create_ref(remote_refname, id, verbosity - 1, repo);
1774 free(remote_refname);
1775 if (error)
1776 goto done;
1779 /* Set the HEAD reference if the server provided one. */
1780 TAILQ_FOREACH(pe, &symrefs, entry) {
1781 struct got_reference *target_ref;
1782 const char *refname = pe->path;
1783 const char *target = pe->data;
1784 char *remote_refname = NULL, *remote_target = NULL;
1786 if (strcmp(refname, GOT_REF_HEAD) != 0)
1787 continue;
1789 error = got_ref_open(&target_ref, repo, target, 0);
1790 if (error) {
1791 if (error->code == GOT_ERR_NOT_REF) {
1792 error = NULL;
1793 continue;
1795 goto done;
1798 error = create_symref(refname, target_ref, verbosity, repo);
1799 got_ref_close(target_ref);
1800 if (error)
1801 goto done;
1803 if (mirror_references)
1804 continue;
1806 if (strncmp("refs/heads/", target, 11) != 0)
1807 continue;
1809 if (asprintf(&remote_refname,
1810 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1811 refname) == -1) {
1812 error = got_error_from_errno("asprintf");
1813 goto done;
1815 if (asprintf(&remote_target,
1816 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1817 target + 11) == -1) {
1818 error = got_error_from_errno("asprintf");
1819 free(remote_refname);
1820 goto done;
1822 error = got_ref_open(&target_ref, repo, remote_target, 0);
1823 if (error) {
1824 free(remote_refname);
1825 free(remote_target);
1826 if (error->code == GOT_ERR_NOT_REF) {
1827 error = NULL;
1828 continue;
1830 goto done;
1832 error = create_symref(remote_refname, target_ref,
1833 verbosity - 1, repo);
1834 free(remote_refname);
1835 free(remote_target);
1836 got_ref_close(target_ref);
1837 if (error)
1838 goto done;
1840 if (pe == NULL) {
1842 * We failed to set the HEAD reference. If we asked for
1843 * a set of wanted branches use the first of one of those
1844 * which could be fetched instead.
1846 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1847 const char *target = pe->path;
1848 struct got_reference *target_ref;
1850 error = got_ref_open(&target_ref, repo, target, 0);
1851 if (error) {
1852 if (error->code == GOT_ERR_NOT_REF) {
1853 error = NULL;
1854 continue;
1856 goto done;
1859 error = create_symref(GOT_REF_HEAD, target_ref,
1860 verbosity, repo);
1861 got_ref_close(target_ref);
1862 if (error)
1863 goto done;
1864 break;
1867 if (!fpa.configs_created && pe != NULL) {
1868 error = create_config_files(fpa.config_info.proto,
1869 fpa.config_info.host, fpa.config_info.port,
1870 fpa.config_info.remote_repo_path,
1871 fpa.config_info.git_url,
1872 fpa.config_info.fetch_all_branches,
1873 fpa.config_info.mirror_references,
1874 fpa.config_info.symrefs,
1875 fpa.config_info.wanted_branches,
1876 fpa.config_info.wanted_refs, fpa.repo);
1877 if (error)
1878 goto done;
1882 if (verbosity >= 0)
1883 printf("Created %s repository '%s'\n",
1884 mirror_references ? "mirrored" : "cloned", repo_path);
1885 done:
1886 if (pack_fds) {
1887 const struct got_error *pack_err =
1888 got_repo_pack_fds_close(pack_fds);
1889 if (error == NULL)
1890 error = pack_err;
1892 if (fetchpid > 0) {
1893 if (kill(fetchpid, SIGTERM) == -1)
1894 error = got_error_from_errno("kill");
1895 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1896 error = got_error_from_errno("waitpid");
1898 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1899 error = got_error_from_errno("close");
1900 if (repo) {
1901 const struct got_error *close_err = got_repo_close(repo);
1902 if (error == NULL)
1903 error = close_err;
1905 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1906 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1907 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1908 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1909 free(pack_hash);
1910 free(proto);
1911 free(host);
1912 free(port);
1913 free(server_path);
1914 free(repo_name);
1915 free(default_destdir);
1916 free(git_url);
1917 return error;
1920 static const struct got_error *
1921 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1922 int replace_tags, int verbosity, struct got_repository *repo)
1924 const struct got_error *err = NULL;
1925 char *new_id_str = NULL;
1926 struct got_object_id *old_id = NULL;
1928 err = got_object_id_str(&new_id_str, new_id);
1929 if (err)
1930 goto done;
1932 if (!replace_tags &&
1933 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1934 err = got_ref_resolve(&old_id, repo, ref);
1935 if (err)
1936 goto done;
1937 if (got_object_id_cmp(old_id, new_id) == 0)
1938 goto done;
1939 if (verbosity >= 0) {
1940 printf("Rejecting update of existing tag %s: %s\n",
1941 got_ref_get_name(ref), new_id_str);
1943 goto done;
1946 if (got_ref_is_symbolic(ref)) {
1947 if (verbosity >= 0) {
1948 printf("Replacing reference %s: %s\n",
1949 got_ref_get_name(ref),
1950 got_ref_get_symref_target(ref));
1952 err = got_ref_change_symref_to_ref(ref, new_id);
1953 if (err)
1954 goto done;
1955 err = got_ref_write(ref, repo);
1956 if (err)
1957 goto done;
1958 } else {
1959 err = got_ref_resolve(&old_id, repo, ref);
1960 if (err)
1961 goto done;
1962 if (got_object_id_cmp(old_id, new_id) == 0)
1963 goto done;
1965 err = got_ref_change_ref(ref, new_id);
1966 if (err)
1967 goto done;
1968 err = got_ref_write(ref, repo);
1969 if (err)
1970 goto done;
1973 if (verbosity >= 0)
1974 printf("Updated %s: %s\n", got_ref_get_name(ref),
1975 new_id_str);
1976 done:
1977 free(old_id);
1978 free(new_id_str);
1979 return err;
1982 static const struct got_error *
1983 update_symref(const char *refname, struct got_reference *target_ref,
1984 int verbosity, struct got_repository *repo)
1986 const struct got_error *err = NULL, *unlock_err;
1987 struct got_reference *symref;
1988 int symref_is_locked = 0;
1990 err = got_ref_open(&symref, repo, refname, 1);
1991 if (err) {
1992 if (err->code != GOT_ERR_NOT_REF)
1993 return err;
1994 err = got_ref_alloc_symref(&symref, refname, target_ref);
1995 if (err)
1996 goto done;
1998 err = got_ref_write(symref, repo);
1999 if (err)
2000 goto done;
2002 if (verbosity >= 0)
2003 printf("Created reference %s: %s\n",
2004 got_ref_get_name(symref),
2005 got_ref_get_symref_target(symref));
2006 } else {
2007 symref_is_locked = 1;
2009 if (strcmp(got_ref_get_symref_target(symref),
2010 got_ref_get_name(target_ref)) == 0)
2011 goto done;
2013 err = got_ref_change_symref(symref,
2014 got_ref_get_name(target_ref));
2015 if (err)
2016 goto done;
2018 err = got_ref_write(symref, repo);
2019 if (err)
2020 goto done;
2022 if (verbosity >= 0)
2023 printf("Updated %s: %s\n", got_ref_get_name(symref),
2024 got_ref_get_symref_target(symref));
2027 done:
2028 if (symref_is_locked) {
2029 unlock_err = got_ref_unlock(symref);
2030 if (unlock_err && err == NULL)
2031 err = unlock_err;
2033 got_ref_close(symref);
2034 return err;
2037 __dead static void
2038 usage_fetch(void)
2040 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2041 "[-R reference] [-r repository-path] [remote-repository]\n",
2042 getprogname());
2043 exit(1);
2046 static const struct got_error *
2047 delete_missing_ref(struct got_reference *ref,
2048 int verbosity, struct got_repository *repo)
2050 const struct got_error *err = NULL;
2051 struct got_object_id *id = NULL;
2052 char *id_str = NULL;
2054 if (got_ref_is_symbolic(ref)) {
2055 err = got_ref_delete(ref, repo);
2056 if (err)
2057 return err;
2058 if (verbosity >= 0) {
2059 printf("Deleted %s: %s\n",
2060 got_ref_get_name(ref),
2061 got_ref_get_symref_target(ref));
2063 } else {
2064 err = got_ref_resolve(&id, repo, ref);
2065 if (err)
2066 return err;
2067 err = got_object_id_str(&id_str, id);
2068 if (err)
2069 goto done;
2071 err = got_ref_delete(ref, repo);
2072 if (err)
2073 goto done;
2074 if (verbosity >= 0) {
2075 printf("Deleted %s: %s\n",
2076 got_ref_get_name(ref), id_str);
2079 done:
2080 free(id);
2081 free(id_str);
2082 return err;
2085 static const struct got_error *
2086 delete_missing_refs(struct got_pathlist_head *their_refs,
2087 struct got_pathlist_head *their_symrefs,
2088 const struct got_remote_repo *remote,
2089 int verbosity, struct got_repository *repo)
2091 const struct got_error *err = NULL, *unlock_err;
2092 struct got_reflist_head my_refs;
2093 struct got_reflist_entry *re;
2094 struct got_pathlist_entry *pe;
2095 char *remote_namespace = NULL;
2096 char *local_refname = NULL;
2098 TAILQ_INIT(&my_refs);
2100 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2101 == -1)
2102 return got_error_from_errno("asprintf");
2104 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2105 if (err)
2106 goto done;
2108 TAILQ_FOREACH(re, &my_refs, entry) {
2109 const char *refname = got_ref_get_name(re->ref);
2110 const char *their_refname;
2112 if (remote->mirror_references) {
2113 their_refname = refname;
2114 } else {
2115 if (strncmp(refname, remote_namespace,
2116 strlen(remote_namespace)) == 0) {
2117 if (strcmp(refname + strlen(remote_namespace),
2118 GOT_REF_HEAD) == 0)
2119 continue;
2120 if (asprintf(&local_refname, "refs/heads/%s",
2121 refname + strlen(remote_namespace)) == -1) {
2122 err = got_error_from_errno("asprintf");
2123 goto done;
2125 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2126 continue;
2128 their_refname = local_refname;
2131 TAILQ_FOREACH(pe, their_refs, entry) {
2132 if (strcmp(their_refname, pe->path) == 0)
2133 break;
2135 if (pe != NULL)
2136 continue;
2138 TAILQ_FOREACH(pe, their_symrefs, entry) {
2139 if (strcmp(their_refname, pe->path) == 0)
2140 break;
2142 if (pe != NULL)
2143 continue;
2145 err = delete_missing_ref(re->ref, verbosity, repo);
2146 if (err)
2147 break;
2149 if (local_refname) {
2150 struct got_reference *ref;
2151 err = got_ref_open(&ref, repo, local_refname, 1);
2152 if (err) {
2153 if (err->code != GOT_ERR_NOT_REF)
2154 break;
2155 free(local_refname);
2156 local_refname = NULL;
2157 continue;
2159 err = delete_missing_ref(ref, verbosity, repo);
2160 if (err)
2161 break;
2162 unlock_err = got_ref_unlock(ref);
2163 got_ref_close(ref);
2164 if (unlock_err && err == NULL) {
2165 err = unlock_err;
2166 break;
2169 free(local_refname);
2170 local_refname = NULL;
2173 done:
2174 got_ref_list_free(&my_refs);
2175 free(remote_namespace);
2176 free(local_refname);
2177 return err;
2180 static const struct got_error *
2181 update_wanted_ref(const char *refname, struct got_object_id *id,
2182 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2184 const struct got_error *err, *unlock_err;
2185 char *remote_refname;
2186 struct got_reference *ref;
2188 if (strncmp("refs/", refname, 5) == 0)
2189 refname += 5;
2191 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2192 remote_repo_name, refname) == -1)
2193 return got_error_from_errno("asprintf");
2195 err = got_ref_open(&ref, repo, remote_refname, 1);
2196 if (err) {
2197 if (err->code != GOT_ERR_NOT_REF)
2198 goto done;
2199 err = create_ref(remote_refname, id, verbosity, repo);
2200 } else {
2201 err = update_ref(ref, id, 0, verbosity, repo);
2202 unlock_err = got_ref_unlock(ref);
2203 if (unlock_err && err == NULL)
2204 err = unlock_err;
2205 got_ref_close(ref);
2207 done:
2208 free(remote_refname);
2209 return err;
2212 static const struct got_error *
2213 delete_ref(struct got_repository *repo, struct got_reference *ref)
2215 const struct got_error *err = NULL;
2216 struct got_object_id *id = NULL;
2217 char *id_str = NULL;
2218 const char *target;
2220 if (got_ref_is_symbolic(ref)) {
2221 target = got_ref_get_symref_target(ref);
2222 } else {
2223 err = got_ref_resolve(&id, repo, ref);
2224 if (err)
2225 goto done;
2226 err = got_object_id_str(&id_str, id);
2227 if (err)
2228 goto done;
2229 target = id_str;
2232 err = got_ref_delete(ref, repo);
2233 if (err)
2234 goto done;
2236 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2237 done:
2238 free(id);
2239 free(id_str);
2240 return err;
2243 static const struct got_error *
2244 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2246 const struct got_error *err = NULL;
2247 struct got_reflist_head refs;
2248 struct got_reflist_entry *re;
2249 char *prefix;
2251 TAILQ_INIT(&refs);
2253 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2254 err = got_error_from_errno("asprintf");
2255 goto done;
2257 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2258 if (err)
2259 goto done;
2261 TAILQ_FOREACH(re, &refs, entry)
2262 delete_ref(repo, re->ref);
2263 done:
2264 got_ref_list_free(&refs);
2265 return err;
2268 static const struct got_error *
2269 cmd_fetch(int argc, char *argv[])
2271 const struct got_error *error = NULL, *unlock_err;
2272 char *cwd = NULL, *repo_path = NULL;
2273 const char *remote_name;
2274 char *proto = NULL, *host = NULL, *port = NULL;
2275 char *repo_name = NULL, *server_path = NULL;
2276 const struct got_remote_repo *remotes, *remote = NULL;
2277 int nremotes;
2278 char *id_str = NULL;
2279 struct got_repository *repo = NULL;
2280 struct got_worktree *worktree = NULL;
2281 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2282 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2283 struct got_pathlist_entry *pe;
2284 struct got_object_id *pack_hash = NULL;
2285 int i, ch, fetchfd = -1, fetchstatus;
2286 pid_t fetchpid = -1;
2287 struct got_fetch_progress_arg fpa;
2288 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2289 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2290 int *pack_fds = NULL, have_bflag = 0;
2291 const char *worktree_branch = NULL;
2293 TAILQ_INIT(&refs);
2294 TAILQ_INIT(&symrefs);
2295 TAILQ_INIT(&wanted_branches);
2296 TAILQ_INIT(&wanted_refs);
2298 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2299 switch (ch) {
2300 case 'a':
2301 fetch_all_branches = 1;
2302 break;
2303 case 'b':
2304 error = got_pathlist_append(&wanted_branches,
2305 optarg, NULL);
2306 if (error)
2307 return error;
2308 have_bflag = 1;
2309 break;
2310 case 'd':
2311 delete_refs = 1;
2312 break;
2313 case 'l':
2314 list_refs_only = 1;
2315 break;
2316 case 'q':
2317 verbosity = -1;
2318 break;
2319 case 'R':
2320 error = got_pathlist_append(&wanted_refs,
2321 optarg, NULL);
2322 if (error)
2323 return error;
2324 break;
2325 case 'r':
2326 repo_path = realpath(optarg, NULL);
2327 if (repo_path == NULL)
2328 return got_error_from_errno2("realpath",
2329 optarg);
2330 got_path_strip_trailing_slashes(repo_path);
2331 break;
2332 case 't':
2333 replace_tags = 1;
2334 break;
2335 case 'v':
2336 if (verbosity < 0)
2337 verbosity = 0;
2338 else if (verbosity < 3)
2339 verbosity++;
2340 break;
2341 case 'X':
2342 delete_remote = 1;
2343 break;
2344 default:
2345 usage_fetch();
2346 break;
2349 argc -= optind;
2350 argv += optind;
2352 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2353 option_conflict('a', 'b');
2354 if (list_refs_only) {
2355 if (!TAILQ_EMPTY(&wanted_branches))
2356 option_conflict('l', 'b');
2357 if (fetch_all_branches)
2358 option_conflict('l', 'a');
2359 if (delete_refs)
2360 option_conflict('l', 'd');
2361 if (delete_remote)
2362 option_conflict('l', 'X');
2364 if (delete_remote) {
2365 if (fetch_all_branches)
2366 option_conflict('X', 'a');
2367 if (!TAILQ_EMPTY(&wanted_branches))
2368 option_conflict('X', 'b');
2369 if (delete_refs)
2370 option_conflict('X', 'd');
2371 if (replace_tags)
2372 option_conflict('X', 't');
2373 if (!TAILQ_EMPTY(&wanted_refs))
2374 option_conflict('X', 'R');
2377 if (argc == 0) {
2378 if (delete_remote)
2379 errx(1, "-X option requires a remote name");
2380 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2381 } else if (argc == 1)
2382 remote_name = argv[0];
2383 else
2384 usage_fetch();
2386 cwd = getcwd(NULL, 0);
2387 if (cwd == NULL) {
2388 error = got_error_from_errno("getcwd");
2389 goto done;
2392 error = got_repo_pack_fds_open(&pack_fds);
2393 if (error != NULL)
2394 goto done;
2396 if (repo_path == NULL) {
2397 error = got_worktree_open(&worktree, cwd);
2398 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2399 goto done;
2400 else
2401 error = NULL;
2402 if (worktree) {
2403 repo_path =
2404 strdup(got_worktree_get_repo_path(worktree));
2405 if (repo_path == NULL)
2406 error = got_error_from_errno("strdup");
2407 if (error)
2408 goto done;
2409 } else {
2410 repo_path = strdup(cwd);
2411 if (repo_path == NULL) {
2412 error = got_error_from_errno("strdup");
2413 goto done;
2418 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2419 if (error)
2420 goto done;
2422 if (delete_remote) {
2423 error = delete_refs_for_remote(repo, remote_name);
2424 goto done; /* nothing else to do */
2427 if (worktree) {
2428 worktree_conf = got_worktree_get_gotconfig(worktree);
2429 if (worktree_conf) {
2430 got_gotconfig_get_remotes(&nremotes, &remotes,
2431 worktree_conf);
2432 for (i = 0; i < nremotes; i++) {
2433 if (strcmp(remotes[i].name, remote_name) == 0) {
2434 remote = &remotes[i];
2435 break;
2440 if (remote == NULL) {
2441 repo_conf = got_repo_get_gotconfig(repo);
2442 if (repo_conf) {
2443 got_gotconfig_get_remotes(&nremotes, &remotes,
2444 repo_conf);
2445 for (i = 0; i < nremotes; i++) {
2446 if (strcmp(remotes[i].name, remote_name) == 0) {
2447 remote = &remotes[i];
2448 break;
2453 if (remote == NULL) {
2454 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 remote = &remotes[i];
2458 break;
2462 if (remote == NULL) {
2463 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2464 goto done;
2467 if (TAILQ_EMPTY(&wanted_branches)) {
2468 if (!fetch_all_branches)
2469 fetch_all_branches = remote->fetch_all_branches;
2470 for (i = 0; i < remote->nfetch_branches; i++) {
2471 error = got_pathlist_append(&wanted_branches,
2472 remote->fetch_branches[i], NULL);
2473 if (error)
2474 goto done;
2477 if (TAILQ_EMPTY(&wanted_refs)) {
2478 for (i = 0; i < remote->nfetch_refs; i++) {
2479 error = got_pathlist_append(&wanted_refs,
2480 remote->fetch_refs[i], NULL);
2481 if (error)
2482 goto done;
2486 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2487 &repo_name, remote->fetch_url);
2488 if (error)
2489 goto done;
2491 if (strcmp(proto, "git") == 0) {
2492 #ifndef PROFILE
2493 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2494 "sendfd dns inet unveil", NULL) == -1)
2495 err(1, "pledge");
2496 #endif
2497 } else if (strcmp(proto, "git+ssh") == 0 ||
2498 strcmp(proto, "ssh") == 0) {
2499 #ifndef PROFILE
2500 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2501 "sendfd unveil", NULL) == -1)
2502 err(1, "pledge");
2503 #endif
2504 } else if (strcmp(proto, "http") == 0 ||
2505 strcmp(proto, "git+http") == 0) {
2506 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2507 goto done;
2508 } else {
2509 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2510 goto done;
2513 error = got_dial_apply_unveil(proto);
2514 if (error)
2515 goto done;
2517 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2518 if (error)
2519 goto done;
2521 if (verbosity >= 0) {
2522 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2523 remote->name, proto, host,
2524 port ? ":" : "", port ? port : "",
2525 *server_path == '/' ? "" : "/", server_path);
2528 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2529 server_path, verbosity);
2530 if (error)
2531 goto done;
2533 if (worktree && !have_bflag) {
2534 const char *refname;
2536 refname = got_worktree_get_head_ref_name(worktree);
2537 if (strncmp(refname, "refs/heads/", 11) == 0)
2538 worktree_branch = refname;
2541 fpa.last_scaled_size[0] = '\0';
2542 fpa.last_p_indexed = -1;
2543 fpa.last_p_resolved = -1;
2544 fpa.verbosity = verbosity;
2545 fpa.repo = repo;
2546 fpa.create_configs = 0;
2547 fpa.configs_created = 0;
2548 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2549 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2550 remote->mirror_references, fetch_all_branches, &wanted_branches,
2551 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2552 worktree_branch, fetch_progress, &fpa);
2553 if (error)
2554 goto done;
2556 if (list_refs_only) {
2557 error = list_remote_refs(&symrefs, &refs);
2558 goto done;
2561 if (pack_hash == NULL) {
2562 if (verbosity >= 0)
2563 printf("Already up-to-date\n");
2564 } else if (verbosity >= 0) {
2565 error = got_object_id_str(&id_str, pack_hash);
2566 if (error)
2567 goto done;
2568 printf("\nFetched %s.pack\n", id_str);
2569 free(id_str);
2570 id_str = NULL;
2573 /* Update references provided with the pack file. */
2574 TAILQ_FOREACH(pe, &refs, entry) {
2575 const char *refname = pe->path;
2576 struct got_object_id *id = pe->data;
2577 struct got_reference *ref;
2578 char *remote_refname;
2580 if (is_wanted_ref(&wanted_refs, refname) &&
2581 !remote->mirror_references) {
2582 error = update_wanted_ref(refname, id,
2583 remote->name, verbosity, repo);
2584 if (error)
2585 goto done;
2586 continue;
2589 if (remote->mirror_references ||
2590 strncmp("refs/tags/", refname, 10) == 0) {
2591 error = got_ref_open(&ref, repo, refname, 1);
2592 if (error) {
2593 if (error->code != GOT_ERR_NOT_REF)
2594 goto done;
2595 error = create_ref(refname, id, verbosity,
2596 repo);
2597 if (error)
2598 goto done;
2599 } else {
2600 error = update_ref(ref, id, replace_tags,
2601 verbosity, repo);
2602 unlock_err = got_ref_unlock(ref);
2603 if (unlock_err && error == NULL)
2604 error = unlock_err;
2605 got_ref_close(ref);
2606 if (error)
2607 goto done;
2609 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2610 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2611 remote_name, refname + 11) == -1) {
2612 error = got_error_from_errno("asprintf");
2613 goto done;
2616 error = got_ref_open(&ref, repo, remote_refname, 1);
2617 if (error) {
2618 if (error->code != GOT_ERR_NOT_REF)
2619 goto done;
2620 error = create_ref(remote_refname, id,
2621 verbosity, repo);
2622 if (error)
2623 goto done;
2624 } else {
2625 error = update_ref(ref, id, replace_tags,
2626 verbosity, repo);
2627 unlock_err = got_ref_unlock(ref);
2628 if (unlock_err && error == NULL)
2629 error = unlock_err;
2630 got_ref_close(ref);
2631 if (error)
2632 goto done;
2635 /* Also create a local branch if none exists yet. */
2636 error = got_ref_open(&ref, repo, refname, 1);
2637 if (error) {
2638 if (error->code != GOT_ERR_NOT_REF)
2639 goto done;
2640 error = create_ref(refname, id, verbosity,
2641 repo);
2642 if (error)
2643 goto done;
2644 } else {
2645 unlock_err = got_ref_unlock(ref);
2646 if (unlock_err && error == NULL)
2647 error = unlock_err;
2648 got_ref_close(ref);
2652 if (delete_refs) {
2653 error = delete_missing_refs(&refs, &symrefs, remote,
2654 verbosity, repo);
2655 if (error)
2656 goto done;
2659 if (!remote->mirror_references) {
2660 /* Update remote HEAD reference if the server provided one. */
2661 TAILQ_FOREACH(pe, &symrefs, entry) {
2662 struct got_reference *target_ref;
2663 const char *refname = pe->path;
2664 const char *target = pe->data;
2665 char *remote_refname = NULL, *remote_target = NULL;
2667 if (strcmp(refname, GOT_REF_HEAD) != 0)
2668 continue;
2670 if (strncmp("refs/heads/", target, 11) != 0)
2671 continue;
2673 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2674 remote->name, refname) == -1) {
2675 error = got_error_from_errno("asprintf");
2676 goto done;
2678 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2679 remote->name, target + 11) == -1) {
2680 error = got_error_from_errno("asprintf");
2681 free(remote_refname);
2682 goto done;
2685 error = got_ref_open(&target_ref, repo, remote_target,
2686 0);
2687 if (error) {
2688 free(remote_refname);
2689 free(remote_target);
2690 if (error->code == GOT_ERR_NOT_REF) {
2691 error = NULL;
2692 continue;
2694 goto done;
2696 error = update_symref(remote_refname, target_ref,
2697 verbosity, repo);
2698 free(remote_refname);
2699 free(remote_target);
2700 got_ref_close(target_ref);
2701 if (error)
2702 goto done;
2705 done:
2706 if (fetchpid > 0) {
2707 if (kill(fetchpid, SIGTERM) == -1)
2708 error = got_error_from_errno("kill");
2709 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2710 error = got_error_from_errno("waitpid");
2712 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2713 error = got_error_from_errno("close");
2714 if (repo) {
2715 const struct got_error *close_err = got_repo_close(repo);
2716 if (error == NULL)
2717 error = close_err;
2719 if (worktree)
2720 got_worktree_close(worktree);
2721 if (pack_fds) {
2722 const struct got_error *pack_err =
2723 got_repo_pack_fds_close(pack_fds);
2724 if (error == NULL)
2725 error = pack_err;
2727 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2728 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2729 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2730 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2731 free(id_str);
2732 free(cwd);
2733 free(repo_path);
2734 free(pack_hash);
2735 free(proto);
2736 free(host);
2737 free(port);
2738 free(server_path);
2739 free(repo_name);
2740 return error;
2744 __dead static void
2745 usage_checkout(void)
2747 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2748 "[-p path-prefix] repository-path [work-tree-path]\n",
2749 getprogname());
2750 exit(1);
2753 static void
2754 show_worktree_base_ref_warning(void)
2756 fprintf(stderr, "%s: warning: could not create a reference "
2757 "to the work tree's base commit; the commit could be "
2758 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2759 "repository writable and running 'got update' will prevent this\n",
2760 getprogname());
2763 struct got_checkout_progress_arg {
2764 const char *worktree_path;
2765 int had_base_commit_ref_error;
2766 int verbosity;
2769 static const struct got_error *
2770 checkout_progress(void *arg, unsigned char status, const char *path)
2772 struct got_checkout_progress_arg *a = arg;
2774 /* Base commit bump happens silently. */
2775 if (status == GOT_STATUS_BUMP_BASE)
2776 return NULL;
2778 if (status == GOT_STATUS_BASE_REF_ERR) {
2779 a->had_base_commit_ref_error = 1;
2780 return NULL;
2783 while (path[0] == '/')
2784 path++;
2786 if (a->verbosity >= 0)
2787 printf("%c %s/%s\n", status, a->worktree_path, path);
2789 return NULL;
2792 static const struct got_error *
2793 check_cancelled(void *arg)
2795 if (sigint_received || sigpipe_received)
2796 return got_error(GOT_ERR_CANCELLED);
2797 return NULL;
2800 static const struct got_error *
2801 check_linear_ancestry(struct got_object_id *commit_id,
2802 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2803 struct got_repository *repo)
2805 const struct got_error *err = NULL;
2806 struct got_object_id *yca_id;
2808 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2809 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2810 if (err)
2811 return err;
2813 if (yca_id == NULL)
2814 return got_error(GOT_ERR_ANCESTRY);
2817 * Require a straight line of history between the target commit
2818 * and the work tree's base commit.
2820 * Non-linear situations such as this require a rebase:
2822 * (commit) D F (base_commit)
2823 * \ /
2824 * C E
2825 * \ /
2826 * B (yca)
2827 * |
2828 * A
2830 * 'got update' only handles linear cases:
2831 * Update forwards in time: A (base/yca) - B - C - D (commit)
2832 * Update backwards in time: D (base) - C - B - A (commit/yca)
2834 if (allow_forwards_in_time_only) {
2835 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2836 return got_error(GOT_ERR_ANCESTRY);
2837 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2838 got_object_id_cmp(base_commit_id, yca_id) != 0)
2839 return got_error(GOT_ERR_ANCESTRY);
2841 free(yca_id);
2842 return NULL;
2845 static const struct got_error *
2846 check_same_branch(struct got_object_id *commit_id,
2847 struct got_reference *head_ref, struct got_object_id *yca_id,
2848 struct got_repository *repo)
2850 const struct got_error *err = NULL;
2851 struct got_commit_graph *graph = NULL;
2852 struct got_object_id *head_commit_id = NULL;
2853 int is_same_branch = 0;
2855 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2856 if (err)
2857 goto done;
2859 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2860 is_same_branch = 1;
2861 goto done;
2863 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2864 is_same_branch = 1;
2865 goto done;
2868 err = got_commit_graph_open(&graph, "/", 1);
2869 if (err)
2870 goto done;
2872 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2873 check_cancelled, NULL);
2874 if (err)
2875 goto done;
2877 for (;;) {
2878 struct got_object_id id;
2880 err = got_commit_graph_iter_next(&id, graph, repo,
2881 check_cancelled, NULL);
2882 if (err) {
2883 if (err->code == GOT_ERR_ITER_COMPLETED)
2884 err = NULL;
2885 break;
2888 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2889 break;
2890 if (got_object_id_cmp(&id, commit_id) == 0) {
2891 is_same_branch = 1;
2892 break;
2895 done:
2896 if (graph)
2897 got_commit_graph_close(graph);
2898 free(head_commit_id);
2899 if (!err && !is_same_branch)
2900 err = got_error(GOT_ERR_ANCESTRY);
2901 return err;
2904 static const struct got_error *
2905 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2907 static char msg[512];
2908 const char *branch_name;
2910 if (got_ref_is_symbolic(ref))
2911 branch_name = got_ref_get_symref_target(ref);
2912 else
2913 branch_name = got_ref_get_name(ref);
2915 if (strncmp("refs/heads/", branch_name, 11) == 0)
2916 branch_name += 11;
2918 snprintf(msg, sizeof(msg),
2919 "target commit is not contained in branch '%s'; "
2920 "the branch to use must be specified with -b; "
2921 "if necessary a new branch can be created for "
2922 "this commit with 'got branch -c %s BRANCH_NAME'",
2923 branch_name, commit_id_str);
2925 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2928 static const struct got_error *
2929 cmd_checkout(int argc, char *argv[])
2931 const struct got_error *error = NULL;
2932 struct got_repository *repo = NULL;
2933 struct got_reference *head_ref = NULL, *ref = NULL;
2934 struct got_worktree *worktree = NULL;
2935 char *repo_path = NULL;
2936 char *worktree_path = NULL;
2937 const char *path_prefix = "";
2938 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2939 char *commit_id_str = NULL;
2940 struct got_object_id *commit_id = NULL;
2941 char *cwd = NULL;
2942 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2943 struct got_pathlist_head paths;
2944 struct got_checkout_progress_arg cpa;
2945 int *pack_fds = NULL;
2947 TAILQ_INIT(&paths);
2949 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2950 switch (ch) {
2951 case 'b':
2952 branch_name = optarg;
2953 break;
2954 case 'c':
2955 commit_id_str = strdup(optarg);
2956 if (commit_id_str == NULL)
2957 return got_error_from_errno("strdup");
2958 break;
2959 case 'E':
2960 allow_nonempty = 1;
2961 break;
2962 case 'p':
2963 path_prefix = optarg;
2964 break;
2965 case 'q':
2966 verbosity = -1;
2967 break;
2968 default:
2969 usage_checkout();
2970 /* NOTREACHED */
2974 argc -= optind;
2975 argv += optind;
2977 #ifndef PROFILE
2978 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2979 "unveil", NULL) == -1)
2980 err(1, "pledge");
2981 #endif
2982 if (argc == 1) {
2983 char *base, *dotgit;
2984 const char *path;
2985 repo_path = realpath(argv[0], NULL);
2986 if (repo_path == NULL)
2987 return got_error_from_errno2("realpath", argv[0]);
2988 cwd = getcwd(NULL, 0);
2989 if (cwd == NULL) {
2990 error = got_error_from_errno("getcwd");
2991 goto done;
2993 if (path_prefix[0])
2994 path = path_prefix;
2995 else
2996 path = repo_path;
2997 error = got_path_basename(&base, path);
2998 if (error)
2999 goto done;
3000 dotgit = strstr(base, ".git");
3001 if (dotgit)
3002 *dotgit = '\0';
3003 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3004 error = got_error_from_errno("asprintf");
3005 free(base);
3006 goto done;
3008 free(base);
3009 } else if (argc == 2) {
3010 repo_path = realpath(argv[0], NULL);
3011 if (repo_path == NULL) {
3012 error = got_error_from_errno2("realpath", argv[0]);
3013 goto done;
3015 worktree_path = realpath(argv[1], NULL);
3016 if (worktree_path == NULL) {
3017 if (errno != ENOENT) {
3018 error = got_error_from_errno2("realpath",
3019 argv[1]);
3020 goto done;
3022 worktree_path = strdup(argv[1]);
3023 if (worktree_path == NULL) {
3024 error = got_error_from_errno("strdup");
3025 goto done;
3028 } else
3029 usage_checkout();
3031 got_path_strip_trailing_slashes(repo_path);
3032 got_path_strip_trailing_slashes(worktree_path);
3034 error = got_repo_pack_fds_open(&pack_fds);
3035 if (error != NULL)
3036 goto done;
3038 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3039 if (error != NULL)
3040 goto done;
3042 /* Pre-create work tree path for unveil(2) */
3043 error = got_path_mkdir(worktree_path);
3044 if (error) {
3045 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3046 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3047 goto done;
3048 if (!allow_nonempty &&
3049 !got_path_dir_is_empty(worktree_path)) {
3050 error = got_error_path(worktree_path,
3051 GOT_ERR_DIR_NOT_EMPTY);
3052 goto done;
3056 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3057 if (error)
3058 goto done;
3060 error = got_ref_open(&head_ref, repo, branch_name, 0);
3061 if (error != NULL)
3062 goto done;
3064 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3065 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3066 goto done;
3068 error = got_worktree_open(&worktree, worktree_path);
3069 if (error != NULL)
3070 goto done;
3072 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3073 path_prefix);
3074 if (error != NULL)
3075 goto done;
3076 if (!same_path_prefix) {
3077 error = got_error(GOT_ERR_PATH_PREFIX);
3078 goto done;
3081 if (commit_id_str) {
3082 struct got_reflist_head refs;
3083 TAILQ_INIT(&refs);
3084 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3085 NULL);
3086 if (error)
3087 goto done;
3088 error = got_repo_match_object_id(&commit_id, NULL,
3089 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3090 got_ref_list_free(&refs);
3091 if (error)
3092 goto done;
3093 error = check_linear_ancestry(commit_id,
3094 got_worktree_get_base_commit_id(worktree), 0, repo);
3095 if (error != NULL) {
3096 if (error->code == GOT_ERR_ANCESTRY) {
3097 error = checkout_ancestry_error(
3098 head_ref, commit_id_str);
3100 goto done;
3102 error = check_same_branch(commit_id, head_ref, NULL, repo);
3103 if (error) {
3104 if (error->code == GOT_ERR_ANCESTRY) {
3105 error = checkout_ancestry_error(
3106 head_ref, commit_id_str);
3108 goto done;
3110 error = got_worktree_set_base_commit_id(worktree, repo,
3111 commit_id);
3112 if (error)
3113 goto done;
3114 /* Expand potentially abbreviated commit ID string. */
3115 free(commit_id_str);
3116 error = got_object_id_str(&commit_id_str, commit_id);
3117 if (error)
3118 goto done;
3119 } else {
3120 commit_id = got_object_id_dup(
3121 got_worktree_get_base_commit_id(worktree));
3122 if (commit_id == NULL) {
3123 error = got_error_from_errno("got_object_id_dup");
3124 goto done;
3126 error = got_object_id_str(&commit_id_str, commit_id);
3127 if (error)
3128 goto done;
3131 error = got_pathlist_append(&paths, "", NULL);
3132 if (error)
3133 goto done;
3134 cpa.worktree_path = worktree_path;
3135 cpa.had_base_commit_ref_error = 0;
3136 cpa.verbosity = verbosity;
3137 error = got_worktree_checkout_files(worktree, &paths, repo,
3138 checkout_progress, &cpa, check_cancelled, NULL);
3139 if (error != NULL)
3140 goto done;
3142 if (got_ref_is_symbolic(head_ref)) {
3143 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3144 if (error)
3145 goto done;
3146 refname = got_ref_get_name(ref);
3147 } else
3148 refname = got_ref_get_name(head_ref);
3149 printf("Checked out %s: %s\n", refname, commit_id_str);
3150 printf("Now shut up and hack\n");
3151 if (cpa.had_base_commit_ref_error)
3152 show_worktree_base_ref_warning();
3153 done:
3154 if (pack_fds) {
3155 const struct got_error *pack_err =
3156 got_repo_pack_fds_close(pack_fds);
3157 if (error == NULL)
3158 error = pack_err;
3160 if (head_ref)
3161 got_ref_close(head_ref);
3162 if (ref)
3163 got_ref_close(ref);
3164 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3165 free(commit_id_str);
3166 free(commit_id);
3167 free(repo_path);
3168 free(worktree_path);
3169 free(cwd);
3170 return error;
3173 struct got_update_progress_arg {
3174 int did_something;
3175 int conflicts;
3176 int obstructed;
3177 int not_updated;
3178 int missing;
3179 int not_deleted;
3180 int unversioned;
3181 int verbosity;
3184 static void
3185 print_update_progress_stats(struct got_update_progress_arg *upa)
3187 if (!upa->did_something)
3188 return;
3190 if (upa->conflicts > 0)
3191 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3192 if (upa->obstructed > 0)
3193 printf("File paths obstructed by a non-regular file: %d\n",
3194 upa->obstructed);
3195 if (upa->not_updated > 0)
3196 printf("Files not updated because of existing merge "
3197 "conflicts: %d\n", upa->not_updated);
3201 * The meaning of some status codes differs between merge-style operations and
3202 * update operations. For example, the ! status code means "file was missing"
3203 * if changes were merged into the work tree, and "missing file was restored"
3204 * if the work tree was updated. This function should be used by any operation
3205 * which merges changes into the work tree without updating the work tree.
3207 static void
3208 print_merge_progress_stats(struct got_update_progress_arg *upa)
3210 if (!upa->did_something)
3211 return;
3213 if (upa->conflicts > 0)
3214 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3215 if (upa->obstructed > 0)
3216 printf("File paths obstructed by a non-regular file: %d\n",
3217 upa->obstructed);
3218 if (upa->missing > 0)
3219 printf("Files which had incoming changes but could not be "
3220 "found in the work tree: %d\n", upa->missing);
3221 if (upa->not_deleted > 0)
3222 printf("Files not deleted due to differences in deleted "
3223 "content: %d\n", upa->not_deleted);
3224 if (upa->unversioned > 0)
3225 printf("Files not merged because an unversioned file was "
3226 "found in the work tree: %d\n", upa->unversioned);
3229 __dead static void
3230 usage_update(void)
3232 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3233 "[path ...]\n", getprogname());
3234 exit(1);
3237 static const struct got_error *
3238 update_progress(void *arg, unsigned char status, const char *path)
3240 struct got_update_progress_arg *upa = arg;
3242 if (status == GOT_STATUS_EXISTS ||
3243 status == GOT_STATUS_BASE_REF_ERR)
3244 return NULL;
3246 upa->did_something = 1;
3248 /* Base commit bump happens silently. */
3249 if (status == GOT_STATUS_BUMP_BASE)
3250 return NULL;
3252 if (status == GOT_STATUS_CONFLICT)
3253 upa->conflicts++;
3254 if (status == GOT_STATUS_OBSTRUCTED)
3255 upa->obstructed++;
3256 if (status == GOT_STATUS_CANNOT_UPDATE)
3257 upa->not_updated++;
3258 if (status == GOT_STATUS_MISSING)
3259 upa->missing++;
3260 if (status == GOT_STATUS_CANNOT_DELETE)
3261 upa->not_deleted++;
3262 if (status == GOT_STATUS_UNVERSIONED)
3263 upa->unversioned++;
3265 while (path[0] == '/')
3266 path++;
3267 if (upa->verbosity >= 0)
3268 printf("%c %s\n", status, path);
3270 return NULL;
3273 static const struct got_error *
3274 switch_head_ref(struct got_reference *head_ref,
3275 struct got_object_id *commit_id, struct got_worktree *worktree,
3276 struct got_repository *repo)
3278 const struct got_error *err = NULL;
3279 char *base_id_str;
3280 int ref_has_moved = 0;
3282 /* Trivial case: switching between two different references. */
3283 if (strcmp(got_ref_get_name(head_ref),
3284 got_worktree_get_head_ref_name(worktree)) != 0) {
3285 printf("Switching work tree from %s to %s\n",
3286 got_worktree_get_head_ref_name(worktree),
3287 got_ref_get_name(head_ref));
3288 return got_worktree_set_head_ref(worktree, head_ref);
3291 err = check_linear_ancestry(commit_id,
3292 got_worktree_get_base_commit_id(worktree), 0, repo);
3293 if (err) {
3294 if (err->code != GOT_ERR_ANCESTRY)
3295 return err;
3296 ref_has_moved = 1;
3298 if (!ref_has_moved)
3299 return NULL;
3301 /* Switching to a rebased branch with the same reference name. */
3302 err = got_object_id_str(&base_id_str,
3303 got_worktree_get_base_commit_id(worktree));
3304 if (err)
3305 return err;
3306 printf("Reference %s now points at a different branch\n",
3307 got_worktree_get_head_ref_name(worktree));
3308 printf("Switching work tree from %s to %s\n", base_id_str,
3309 got_worktree_get_head_ref_name(worktree));
3310 return NULL;
3313 static const struct got_error *
3314 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3316 const struct got_error *err;
3317 int in_progress;
3319 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3320 if (err)
3321 return err;
3322 if (in_progress)
3323 return got_error(GOT_ERR_REBASING);
3325 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3326 if (err)
3327 return err;
3328 if (in_progress)
3329 return got_error(GOT_ERR_HISTEDIT_BUSY);
3331 return NULL;
3334 static const struct got_error *
3335 check_merge_in_progress(struct got_worktree *worktree,
3336 struct got_repository *repo)
3338 const struct got_error *err;
3339 int in_progress;
3341 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3342 if (err)
3343 return err;
3344 if (in_progress)
3345 return got_error(GOT_ERR_MERGE_BUSY);
3347 return NULL;
3350 static const struct got_error *
3351 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3352 char *argv[], struct got_worktree *worktree)
3354 const struct got_error *err = NULL;
3355 char *path;
3356 struct got_pathlist_entry *new;
3357 int i;
3359 if (argc == 0) {
3360 path = strdup("");
3361 if (path == NULL)
3362 return got_error_from_errno("strdup");
3363 return got_pathlist_append(paths, path, NULL);
3366 for (i = 0; i < argc; i++) {
3367 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3368 if (err)
3369 break;
3370 err = got_pathlist_insert(&new, paths, path, NULL);
3371 if (err || new == NULL /* duplicate */) {
3372 free(path);
3373 if (err)
3374 break;
3378 return err;
3381 static const struct got_error *
3382 wrap_not_worktree_error(const struct got_error *orig_err,
3383 const char *cmdname, const char *path)
3385 const struct got_error *err;
3386 struct got_repository *repo;
3387 static char msg[512];
3388 int *pack_fds = NULL;
3390 err = got_repo_pack_fds_open(&pack_fds);
3391 if (err)
3392 return err;
3394 err = got_repo_open(&repo, path, NULL, pack_fds);
3395 if (err)
3396 return orig_err;
3398 snprintf(msg, sizeof(msg),
3399 "'got %s' needs a work tree in addition to a git repository\n"
3400 "Work trees can be checked out from this Git repository with "
3401 "'got checkout'.\n"
3402 "The got(1) manual page contains more information.", cmdname);
3403 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3404 got_repo_close(repo);
3405 if (pack_fds) {
3406 const struct got_error *pack_err =
3407 got_repo_pack_fds_close(pack_fds);
3408 if (err == NULL)
3409 err = pack_err;
3411 return err;
3414 static const struct got_error *
3415 cmd_update(int argc, char *argv[])
3417 const struct got_error *error = NULL;
3418 struct got_repository *repo = NULL;
3419 struct got_worktree *worktree = NULL;
3420 char *worktree_path = NULL;
3421 struct got_object_id *commit_id = NULL;
3422 char *commit_id_str = NULL;
3423 const char *branch_name = NULL;
3424 struct got_reference *head_ref = NULL;
3425 struct got_pathlist_head paths;
3426 struct got_pathlist_entry *pe;
3427 int ch, verbosity = 0;
3428 struct got_update_progress_arg upa;
3429 int *pack_fds = NULL;
3431 TAILQ_INIT(&paths);
3433 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3434 switch (ch) {
3435 case 'b':
3436 branch_name = optarg;
3437 break;
3438 case 'c':
3439 commit_id_str = strdup(optarg);
3440 if (commit_id_str == NULL)
3441 return got_error_from_errno("strdup");
3442 break;
3443 case 'q':
3444 verbosity = -1;
3445 break;
3446 default:
3447 usage_update();
3448 /* NOTREACHED */
3452 argc -= optind;
3453 argv += optind;
3455 #ifndef PROFILE
3456 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3457 "unveil", NULL) == -1)
3458 err(1, "pledge");
3459 #endif
3460 worktree_path = getcwd(NULL, 0);
3461 if (worktree_path == NULL) {
3462 error = got_error_from_errno("getcwd");
3463 goto done;
3466 error = got_repo_pack_fds_open(&pack_fds);
3467 if (error != NULL)
3468 goto done;
3470 error = got_worktree_open(&worktree, worktree_path);
3471 if (error) {
3472 if (error->code == GOT_ERR_NOT_WORKTREE)
3473 error = wrap_not_worktree_error(error, "update",
3474 worktree_path);
3475 goto done;
3478 error = check_rebase_or_histedit_in_progress(worktree);
3479 if (error)
3480 goto done;
3482 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3483 NULL, pack_fds);
3484 if (error != NULL)
3485 goto done;
3487 error = apply_unveil(got_repo_get_path(repo), 0,
3488 got_worktree_get_root_path(worktree));
3489 if (error)
3490 goto done;
3492 error = check_merge_in_progress(worktree, repo);
3493 if (error)
3494 goto done;
3496 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3497 if (error)
3498 goto done;
3500 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3501 got_worktree_get_head_ref_name(worktree), 0);
3502 if (error != NULL)
3503 goto done;
3504 if (commit_id_str == NULL) {
3505 error = got_ref_resolve(&commit_id, repo, head_ref);
3506 if (error != NULL)
3507 goto done;
3508 error = got_object_id_str(&commit_id_str, commit_id);
3509 if (error != NULL)
3510 goto done;
3511 } else {
3512 struct got_reflist_head refs;
3513 TAILQ_INIT(&refs);
3514 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3515 NULL);
3516 if (error)
3517 goto done;
3518 error = got_repo_match_object_id(&commit_id, NULL,
3519 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3520 got_ref_list_free(&refs);
3521 free(commit_id_str);
3522 commit_id_str = NULL;
3523 if (error)
3524 goto done;
3525 error = got_object_id_str(&commit_id_str, commit_id);
3526 if (error)
3527 goto done;
3530 if (branch_name) {
3531 struct got_object_id *head_commit_id;
3532 TAILQ_FOREACH(pe, &paths, entry) {
3533 if (pe->path_len == 0)
3534 continue;
3535 error = got_error_msg(GOT_ERR_BAD_PATH,
3536 "switching between branches requires that "
3537 "the entire work tree gets updated");
3538 goto done;
3540 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3541 if (error)
3542 goto done;
3543 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3544 repo);
3545 free(head_commit_id);
3546 if (error != NULL)
3547 goto done;
3548 error = check_same_branch(commit_id, head_ref, NULL, repo);
3549 if (error)
3550 goto done;
3551 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3552 if (error)
3553 goto done;
3554 } else {
3555 error = check_linear_ancestry(commit_id,
3556 got_worktree_get_base_commit_id(worktree), 0, repo);
3557 if (error != NULL) {
3558 if (error->code == GOT_ERR_ANCESTRY)
3559 error = got_error(GOT_ERR_BRANCH_MOVED);
3560 goto done;
3562 error = check_same_branch(commit_id, head_ref, NULL, repo);
3563 if (error)
3564 goto done;
3567 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3568 commit_id) != 0) {
3569 error = got_worktree_set_base_commit_id(worktree, repo,
3570 commit_id);
3571 if (error)
3572 goto done;
3575 memset(&upa, 0, sizeof(upa));
3576 upa.verbosity = verbosity;
3577 error = got_worktree_checkout_files(worktree, &paths, repo,
3578 update_progress, &upa, check_cancelled, NULL);
3579 if (error != NULL)
3580 goto done;
3582 if (upa.did_something) {
3583 printf("Updated to %s: %s\n",
3584 got_worktree_get_head_ref_name(worktree), commit_id_str);
3585 } else
3586 printf("Already up-to-date\n");
3588 print_update_progress_stats(&upa);
3589 done:
3590 if (pack_fds) {
3591 const struct got_error *pack_err =
3592 got_repo_pack_fds_close(pack_fds);
3593 if (error == NULL)
3594 error = pack_err;
3596 free(worktree_path);
3597 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3598 free(commit_id);
3599 free(commit_id_str);
3600 return error;
3603 static const struct got_error *
3604 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3605 const char *path, int diff_context, int ignore_whitespace,
3606 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3607 struct got_repository *repo, FILE *outfile)
3609 const struct got_error *err = NULL;
3610 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3611 FILE *f1 = NULL, *f2 = NULL;
3612 int fd1 = -1, fd2 = -1;
3614 fd1 = got_opentempfd();
3615 if (fd1 == -1)
3616 return got_error_from_errno("got_opentempfd");
3617 fd2 = got_opentempfd();
3618 if (fd2 == -1) {
3619 err = got_error_from_errno("got_opentempfd");
3620 goto done;
3623 if (blob_id1) {
3624 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3625 fd1);
3626 if (err)
3627 goto done;
3630 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3631 if (err)
3632 goto done;
3634 f1 = got_opentemp();
3635 if (f1 == NULL) {
3636 err = got_error_from_errno("got_opentemp");
3637 goto done;
3639 f2 = got_opentemp();
3640 if (f2 == NULL) {
3641 err = got_error_from_errno("got_opentemp");
3642 goto done;
3645 while (path[0] == '/')
3646 path++;
3647 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3648 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3649 force_text_diff, dsa, outfile);
3650 done:
3651 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3652 err = got_error_from_errno("close");
3653 if (blob1)
3654 got_object_blob_close(blob1);
3655 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3656 err = got_error_from_errno("close");
3657 got_object_blob_close(blob2);
3658 if (f1 && fclose(f1) == EOF && err == NULL)
3659 err = got_error_from_errno("fclose");
3660 if (f2 && fclose(f2) == EOF && err == NULL)
3661 err = got_error_from_errno("fclose");
3662 return err;
3665 static const struct got_error *
3666 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3667 const char *path, int diff_context, int ignore_whitespace,
3668 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3669 struct got_repository *repo, FILE *outfile)
3671 const struct got_error *err = NULL;
3672 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3673 struct got_diff_blob_output_unidiff_arg arg;
3674 FILE *f1 = NULL, *f2 = NULL;
3675 int fd1 = -1, fd2 = -1;
3677 if (tree_id1) {
3678 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3679 if (err)
3680 goto done;
3681 fd1 = got_opentempfd();
3682 if (fd1 == -1) {
3683 err = got_error_from_errno("got_opentempfd");
3684 goto done;
3688 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3689 if (err)
3690 goto done;
3692 f1 = got_opentemp();
3693 if (f1 == NULL) {
3694 err = got_error_from_errno("got_opentemp");
3695 goto done;
3698 f2 = got_opentemp();
3699 if (f2 == NULL) {
3700 err = got_error_from_errno("got_opentemp");
3701 goto done;
3703 fd2 = got_opentempfd();
3704 if (fd2 == -1) {
3705 err = got_error_from_errno("got_opentempfd");
3706 goto done;
3708 arg.diff_context = diff_context;
3709 arg.ignore_whitespace = ignore_whitespace;
3710 arg.force_text_diff = force_text_diff;
3711 arg.diffstat = dsa;
3712 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3713 arg.outfile = outfile;
3714 arg.lines = NULL;
3715 arg.nlines = 0;
3716 while (path[0] == '/')
3717 path++;
3718 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3719 got_diff_blob_output_unidiff, &arg, 1);
3720 done:
3721 if (tree1)
3722 got_object_tree_close(tree1);
3723 if (tree2)
3724 got_object_tree_close(tree2);
3725 if (f1 && fclose(f1) == EOF && err == NULL)
3726 err = got_error_from_errno("fclose");
3727 if (f2 && fclose(f2) == EOF && err == NULL)
3728 err = got_error_from_errno("fclose");
3729 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3730 err = got_error_from_errno("close");
3731 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3732 err = got_error_from_errno("close");
3733 return err;
3736 static const struct got_error *
3737 get_changed_paths(struct got_pathlist_head *paths,
3738 struct got_commit_object *commit, struct got_repository *repo,
3739 struct got_diffstat_cb_arg *dsa)
3741 const struct got_error *err = NULL;
3742 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3743 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3744 struct got_object_qid *qid;
3745 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3746 FILE *f1 = NULL, *f2 = NULL;
3747 int fd1 = -1, fd2 = -1;
3749 if (dsa) {
3750 cb = got_diff_tree_compute_diffstat;
3752 f1 = got_opentemp();
3753 if (f1 == NULL) {
3754 err = got_error_from_errno("got_opentemp");
3755 goto done;
3757 f2 = got_opentemp();
3758 if (f2 == NULL) {
3759 err = got_error_from_errno("got_opentemp");
3760 goto done;
3762 fd1 = got_opentempfd();
3763 if (fd1 == -1) {
3764 err = got_error_from_errno("got_opentempfd");
3765 goto done;
3767 fd2 = got_opentempfd();
3768 if (fd2 == -1) {
3769 err = got_error_from_errno("got_opentempfd");
3770 goto done;
3774 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3775 if (qid != NULL) {
3776 struct got_commit_object *pcommit;
3777 err = got_object_open_as_commit(&pcommit, repo,
3778 &qid->id);
3779 if (err)
3780 return err;
3782 tree_id1 = got_object_id_dup(
3783 got_object_commit_get_tree_id(pcommit));
3784 if (tree_id1 == NULL) {
3785 got_object_commit_close(pcommit);
3786 return got_error_from_errno("got_object_id_dup");
3788 got_object_commit_close(pcommit);
3792 if (tree_id1) {
3793 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3794 if (err)
3795 goto done;
3798 tree_id2 = got_object_commit_get_tree_id(commit);
3799 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3800 if (err)
3801 goto done;
3803 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3804 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3805 done:
3806 if (tree1)
3807 got_object_tree_close(tree1);
3808 if (tree2)
3809 got_object_tree_close(tree2);
3810 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3811 err = got_error_from_errno("close");
3812 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3813 err = got_error_from_errno("close");
3814 if (f1 && fclose(f1) == EOF && err == NULL)
3815 err = got_error_from_errno("fclose");
3816 if (f2 && fclose(f2) == EOF && err == NULL)
3817 err = got_error_from_errno("fclose");
3818 free(tree_id1);
3819 return err;
3822 static const struct got_error *
3823 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3824 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3825 struct got_repository *repo, FILE *outfile)
3827 const struct got_error *err = NULL;
3828 struct got_commit_object *pcommit = NULL;
3829 char *id_str1 = NULL, *id_str2 = NULL;
3830 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3831 struct got_object_qid *qid;
3833 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3834 if (qid != NULL) {
3835 err = got_object_open_as_commit(&pcommit, repo,
3836 &qid->id);
3837 if (err)
3838 return err;
3839 err = got_object_id_str(&id_str1, &qid->id);
3840 if (err)
3841 goto done;
3844 err = got_object_id_str(&id_str2, id);
3845 if (err)
3846 goto done;
3848 if (path && path[0] != '\0') {
3849 int obj_type;
3850 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3851 if (err)
3852 goto done;
3853 if (pcommit) {
3854 err = got_object_id_by_path(&obj_id1, repo,
3855 pcommit, path);
3856 if (err) {
3857 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3858 free(obj_id2);
3859 goto done;
3863 err = got_object_get_type(&obj_type, repo, obj_id2);
3864 if (err) {
3865 free(obj_id2);
3866 goto done;
3868 fprintf(outfile,
3869 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3870 fprintf(outfile, "commit - %s\n",
3871 id_str1 ? id_str1 : "/dev/null");
3872 fprintf(outfile, "commit + %s\n", id_str2);
3873 switch (obj_type) {
3874 case GOT_OBJ_TYPE_BLOB:
3875 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3876 0, 0, dsa, repo, outfile);
3877 break;
3878 case GOT_OBJ_TYPE_TREE:
3879 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3880 0, 0, dsa, repo, outfile);
3881 break;
3882 default:
3883 err = got_error(GOT_ERR_OBJ_TYPE);
3884 break;
3886 free(obj_id1);
3887 free(obj_id2);
3888 } else {
3889 obj_id2 = got_object_commit_get_tree_id(commit);
3890 if (pcommit)
3891 obj_id1 = got_object_commit_get_tree_id(pcommit);
3892 fprintf(outfile,
3893 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3894 fprintf(outfile, "commit - %s\n",
3895 id_str1 ? id_str1 : "/dev/null");
3896 fprintf(outfile, "commit + %s\n", id_str2);
3897 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3898 dsa, repo, outfile);
3900 done:
3901 free(id_str1);
3902 free(id_str2);
3903 if (pcommit)
3904 got_object_commit_close(pcommit);
3905 return err;
3908 static char *
3909 get_datestr(time_t *time, char *datebuf)
3911 struct tm mytm, *tm;
3912 char *p, *s;
3914 tm = gmtime_r(time, &mytm);
3915 if (tm == NULL)
3916 return NULL;
3917 s = asctime_r(tm, datebuf);
3918 if (s == NULL)
3919 return NULL;
3920 p = strchr(s, '\n');
3921 if (p)
3922 *p = '\0';
3923 return s;
3926 static const struct got_error *
3927 match_commit(int *have_match, struct got_object_id *id,
3928 struct got_commit_object *commit, regex_t *regex)
3930 const struct got_error *err = NULL;
3931 regmatch_t regmatch;
3932 char *id_str = NULL, *logmsg = NULL;
3934 *have_match = 0;
3936 err = got_object_id_str(&id_str, id);
3937 if (err)
3938 return err;
3940 err = got_object_commit_get_logmsg(&logmsg, commit);
3941 if (err)
3942 goto done;
3944 if (regexec(regex, got_object_commit_get_author(commit), 1,
3945 &regmatch, 0) == 0 ||
3946 regexec(regex, got_object_commit_get_committer(commit), 1,
3947 &regmatch, 0) == 0 ||
3948 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3949 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3950 *have_match = 1;
3951 done:
3952 free(id_str);
3953 free(logmsg);
3954 return err;
3957 static void
3958 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3959 regex_t *regex)
3961 regmatch_t regmatch;
3962 struct got_pathlist_entry *pe;
3964 *have_match = 0;
3966 TAILQ_FOREACH(pe, changed_paths, entry) {
3967 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3968 *have_match = 1;
3969 break;
3974 static const struct got_error *
3975 match_patch(int *have_match, struct got_commit_object *commit,
3976 struct got_object_id *id, const char *path, int diff_context,
3977 struct got_repository *repo, regex_t *regex, FILE *f)
3979 const struct got_error *err = NULL;
3980 char *line = NULL;
3981 size_t linesize = 0;
3982 regmatch_t regmatch;
3984 *have_match = 0;
3986 err = got_opentemp_truncate(f);
3987 if (err)
3988 return err;
3990 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3991 if (err)
3992 goto done;
3994 if (fseeko(f, 0L, SEEK_SET) == -1) {
3995 err = got_error_from_errno("fseeko");
3996 goto done;
3999 while (getline(&line, &linesize, f) != -1) {
4000 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4001 *have_match = 1;
4002 break;
4005 done:
4006 free(line);
4007 return err;
4010 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4012 static const struct got_error*
4013 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4014 struct got_object_id *id, struct got_repository *repo,
4015 int local_only)
4017 static const struct got_error *err = NULL;
4018 struct got_reflist_entry *re;
4019 char *s;
4020 const char *name;
4022 *refs_str = NULL;
4024 TAILQ_FOREACH(re, refs, entry) {
4025 struct got_tag_object *tag = NULL;
4026 struct got_object_id *ref_id;
4027 int cmp;
4029 name = got_ref_get_name(re->ref);
4030 if (strcmp(name, GOT_REF_HEAD) == 0)
4031 continue;
4032 if (strncmp(name, "refs/", 5) == 0)
4033 name += 5;
4034 if (strncmp(name, "got/", 4) == 0)
4035 continue;
4036 if (strncmp(name, "heads/", 6) == 0)
4037 name += 6;
4038 if (strncmp(name, "remotes/", 8) == 0) {
4039 if (local_only)
4040 continue;
4041 name += 8;
4042 s = strstr(name, "/" GOT_REF_HEAD);
4043 if (s != NULL && s[strlen(s)] == '\0')
4044 continue;
4046 err = got_ref_resolve(&ref_id, repo, re->ref);
4047 if (err)
4048 break;
4049 if (strncmp(name, "tags/", 5) == 0) {
4050 err = got_object_open_as_tag(&tag, repo, ref_id);
4051 if (err) {
4052 if (err->code != GOT_ERR_OBJ_TYPE) {
4053 free(ref_id);
4054 break;
4056 /* Ref points at something other than a tag. */
4057 err = NULL;
4058 tag = NULL;
4061 cmp = got_object_id_cmp(tag ?
4062 got_object_tag_get_object_id(tag) : ref_id, id);
4063 free(ref_id);
4064 if (tag)
4065 got_object_tag_close(tag);
4066 if (cmp != 0)
4067 continue;
4068 s = *refs_str;
4069 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4070 s ? ", " : "", name) == -1) {
4071 err = got_error_from_errno("asprintf");
4072 free(s);
4073 *refs_str = NULL;
4074 break;
4076 free(s);
4079 return err;
4082 static const struct got_error *
4083 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4084 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4086 const struct got_error *err = NULL;
4087 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4088 char *comma, *s, *nl;
4089 struct got_reflist_head *refs;
4090 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4091 struct tm tm;
4092 time_t committer_time;
4094 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4095 if (refs) {
4096 err = build_refs_str(&ref_str, refs, id, repo, 1);
4097 if (err)
4098 return err;
4100 /* Display the first matching ref only. */
4101 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4102 *comma = '\0';
4105 if (ref_str == NULL) {
4106 err = got_object_id_str(&id_str, id);
4107 if (err)
4108 return err;
4111 committer_time = got_object_commit_get_committer_time(commit);
4112 if (gmtime_r(&committer_time, &tm) == NULL) {
4113 err = got_error_from_errno("gmtime_r");
4114 goto done;
4116 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4117 err = got_error(GOT_ERR_NO_SPACE);
4118 goto done;
4121 err = got_object_commit_get_logmsg(&logmsg0, commit);
4122 if (err)
4123 goto done;
4125 s = logmsg0;
4126 while (isspace((unsigned char)s[0]))
4127 s++;
4129 nl = strchr(s, '\n');
4130 if (nl) {
4131 *nl = '\0';
4134 if (ref_str)
4135 printf("%s%-7s %s\n", datebuf, ref_str, s);
4136 else
4137 printf("%s%.7s %s\n", datebuf, id_str, s);
4139 if (fflush(stdout) != 0 && err == NULL)
4140 err = got_error_from_errno("fflush");
4141 done:
4142 free(id_str);
4143 free(ref_str);
4144 free(logmsg0);
4145 return err;
4148 static const struct got_error *
4149 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4151 struct got_pathlist_entry *pe;
4153 if (header != NULL)
4154 printf("%s\n", header);
4156 TAILQ_FOREACH(pe, dsa->paths, entry) {
4157 struct got_diff_changed_path *cp = pe->data;
4158 int pad = dsa->max_path_len - pe->path_len + 1;
4160 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4161 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4163 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4164 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4165 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4167 if (fflush(stdout) != 0)
4168 return got_error_from_errno("fflush");
4170 return NULL;
4173 static const struct got_error *
4174 printfile(FILE *f)
4176 char buf[8192];
4177 size_t r;
4179 if (fseeko(f, 0L, SEEK_SET) == -1)
4180 return got_error_from_errno("fseek");
4182 for (;;) {
4183 r = fread(buf, 1, sizeof(buf), f);
4184 if (r == 0) {
4185 if (ferror(f))
4186 return got_error_from_errno("fread");
4187 if (feof(f))
4188 break;
4190 if (fwrite(buf, 1, r, stdout) != r)
4191 return got_ferror(stdout, GOT_ERR_IO);
4194 return NULL;
4197 static const struct got_error *
4198 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4199 struct got_repository *repo, const char *path,
4200 struct got_pathlist_head *changed_paths,
4201 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4202 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4203 const char *prefix)
4205 const struct got_error *err = NULL;
4206 FILE *f = NULL;
4207 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4208 char datebuf[26];
4209 time_t committer_time;
4210 const char *author, *committer;
4211 char *refs_str = NULL;
4213 err = got_object_id_str(&id_str, id);
4214 if (err)
4215 return err;
4217 if (custom_refs_str == NULL) {
4218 struct got_reflist_head *refs;
4219 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4220 if (refs) {
4221 err = build_refs_str(&refs_str, refs, id, repo, 0);
4222 if (err)
4223 goto done;
4227 printf(GOT_COMMIT_SEP_STR);
4228 if (custom_refs_str)
4229 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4230 custom_refs_str);
4231 else
4232 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4233 refs_str ? " (" : "", refs_str ? refs_str : "",
4234 refs_str ? ")" : "");
4235 free(id_str);
4236 id_str = NULL;
4237 free(refs_str);
4238 refs_str = NULL;
4239 printf("from: %s\n", got_object_commit_get_author(commit));
4240 author = got_object_commit_get_author(commit);
4241 committer = got_object_commit_get_committer(commit);
4242 if (strcmp(author, committer) != 0)
4243 printf("via: %s\n", committer);
4244 committer_time = got_object_commit_get_committer_time(commit);
4245 datestr = get_datestr(&committer_time, datebuf);
4246 if (datestr)
4247 printf("date: %s UTC\n", datestr);
4248 if (got_object_commit_get_nparents(commit) > 1) {
4249 const struct got_object_id_queue *parent_ids;
4250 struct got_object_qid *qid;
4251 int n = 1;
4252 parent_ids = got_object_commit_get_parent_ids(commit);
4253 STAILQ_FOREACH(qid, parent_ids, entry) {
4254 err = got_object_id_str(&id_str, &qid->id);
4255 if (err)
4256 goto done;
4257 printf("parent %d: %s\n", n++, id_str);
4258 free(id_str);
4259 id_str = NULL;
4263 err = got_object_commit_get_logmsg(&logmsg0, commit);
4264 if (err)
4265 goto done;
4267 logmsg = logmsg0;
4268 do {
4269 line = strsep(&logmsg, "\n");
4270 if (line)
4271 printf(" %s\n", line);
4272 } while (line);
4273 free(logmsg0);
4275 if (changed_paths && diffstat == NULL) {
4276 struct got_pathlist_entry *pe;
4278 TAILQ_FOREACH(pe, changed_paths, entry) {
4279 struct got_diff_changed_path *cp = pe->data;
4281 printf(" %c %s\n", cp->status, pe->path);
4283 printf("\n");
4285 if (show_patch) {
4286 if (diffstat) {
4287 f = got_opentemp();
4288 if (f == NULL) {
4289 err = got_error_from_errno("got_opentemp");
4290 goto done;
4294 err = print_patch(commit, id, path, diff_context, diffstat,
4295 repo, diffstat == NULL ? stdout : f);
4296 if (err)
4297 goto done;
4299 if (diffstat) {
4300 err = print_diffstat(diffstat, NULL);
4301 if (err)
4302 goto done;
4303 if (show_patch) {
4304 err = printfile(f);
4305 if (err)
4306 goto done;
4309 if (show_patch)
4310 printf("\n");
4312 if (fflush(stdout) != 0 && err == NULL)
4313 err = got_error_from_errno("fflush");
4314 done:
4315 if (f && fclose(f) == EOF && err == NULL)
4316 err = got_error_from_errno("fclose");
4317 free(id_str);
4318 free(refs_str);
4319 return err;
4322 static const struct got_error *
4323 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4324 struct got_repository *repo, const char *path, int show_changed_paths,
4325 int show_diffstat, int show_patch, const char *search_pattern,
4326 int diff_context, int limit, int log_branches, int reverse_display_order,
4327 struct got_reflist_object_id_map *refs_idmap, int one_line,
4328 FILE *tmpfile)
4330 const struct got_error *err;
4331 struct got_commit_graph *graph;
4332 regex_t regex;
4333 int have_match;
4334 struct got_object_id_queue reversed_commits;
4335 struct got_object_qid *qid;
4336 struct got_commit_object *commit;
4337 struct got_pathlist_head changed_paths;
4339 STAILQ_INIT(&reversed_commits);
4340 TAILQ_INIT(&changed_paths);
4342 if (search_pattern && regcomp(&regex, search_pattern,
4343 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4344 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4346 err = got_commit_graph_open(&graph, path, !log_branches);
4347 if (err)
4348 return err;
4349 err = got_commit_graph_iter_start(graph, root_id, repo,
4350 check_cancelled, NULL);
4351 if (err)
4352 goto done;
4353 for (;;) {
4354 struct got_object_id id;
4355 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4356 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4358 if (sigint_received || sigpipe_received)
4359 break;
4361 err = got_commit_graph_iter_next(&id, graph, repo,
4362 check_cancelled, NULL);
4363 if (err) {
4364 if (err->code == GOT_ERR_ITER_COMPLETED)
4365 err = NULL;
4366 break;
4369 err = got_object_open_as_commit(&commit, repo, &id);
4370 if (err)
4371 break;
4373 if ((show_changed_paths || (show_diffstat && !show_patch))
4374 && !reverse_display_order) {
4375 err = get_changed_paths(&changed_paths, commit, repo,
4376 show_diffstat ? &dsa : NULL);
4377 if (err)
4378 break;
4381 if (search_pattern) {
4382 err = match_commit(&have_match, &id, commit, &regex);
4383 if (err) {
4384 got_object_commit_close(commit);
4385 break;
4387 if (have_match == 0 && show_changed_paths)
4388 match_changed_paths(&have_match,
4389 &changed_paths, &regex);
4390 if (have_match == 0 && show_patch) {
4391 err = match_patch(&have_match, commit, &id,
4392 path, diff_context, repo, &regex, tmpfile);
4393 if (err)
4394 break;
4396 if (have_match == 0) {
4397 got_object_commit_close(commit);
4398 got_pathlist_free(&changed_paths,
4399 GOT_PATHLIST_FREE_ALL);
4400 continue;
4404 if (reverse_display_order) {
4405 err = got_object_qid_alloc(&qid, &id);
4406 if (err)
4407 break;
4408 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4409 got_object_commit_close(commit);
4410 } else {
4411 if (one_line)
4412 err = print_commit_oneline(commit, &id,
4413 repo, refs_idmap);
4414 else
4415 err = print_commit(commit, &id, repo, path,
4416 (show_changed_paths || show_diffstat) ?
4417 &changed_paths : NULL,
4418 show_diffstat ? &dsa : NULL, show_patch,
4419 diff_context, refs_idmap, NULL, NULL);
4420 got_object_commit_close(commit);
4421 if (err)
4422 break;
4424 if ((limit && --limit == 0) ||
4425 (end_id && got_object_id_cmp(&id, end_id) == 0))
4426 break;
4428 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4430 if (reverse_display_order) {
4431 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4432 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4433 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4435 err = got_object_open_as_commit(&commit, repo,
4436 &qid->id);
4437 if (err)
4438 break;
4439 if (show_changed_paths ||
4440 (show_diffstat && !show_patch)) {
4441 err = get_changed_paths(&changed_paths, commit,
4442 repo, show_diffstat ? &dsa : NULL);
4443 if (err)
4444 break;
4446 if (one_line)
4447 err = print_commit_oneline(commit, &qid->id,
4448 repo, refs_idmap);
4449 else
4450 err = print_commit(commit, &qid->id, repo, path,
4451 (show_changed_paths || show_diffstat) ?
4452 &changed_paths : NULL,
4453 show_diffstat ? &dsa : NULL, show_patch,
4454 diff_context, refs_idmap, NULL, NULL);
4455 got_object_commit_close(commit);
4456 if (err)
4457 break;
4458 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4461 done:
4462 while (!STAILQ_EMPTY(&reversed_commits)) {
4463 qid = STAILQ_FIRST(&reversed_commits);
4464 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4465 got_object_qid_free(qid);
4467 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4468 if (search_pattern)
4469 regfree(&regex);
4470 got_commit_graph_close(graph);
4471 return err;
4474 __dead static void
4475 usage_log(void)
4477 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4478 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4479 "[path]\n", getprogname());
4480 exit(1);
4483 static int
4484 get_default_log_limit(void)
4486 const char *got_default_log_limit;
4487 long long n;
4488 const char *errstr;
4490 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4491 if (got_default_log_limit == NULL)
4492 return 0;
4493 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4494 if (errstr != NULL)
4495 return 0;
4496 return n;
4499 static const struct got_error *
4500 cmd_log(int argc, char *argv[])
4502 const struct got_error *error;
4503 struct got_repository *repo = NULL;
4504 struct got_worktree *worktree = NULL;
4505 struct got_object_id *start_id = NULL, *end_id = NULL;
4506 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4507 const char *start_commit = NULL, *end_commit = NULL;
4508 const char *search_pattern = NULL;
4509 int diff_context = -1, ch;
4510 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4511 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4512 const char *errstr;
4513 struct got_reflist_head refs;
4514 struct got_reflist_object_id_map *refs_idmap = NULL;
4515 FILE *tmpfile = NULL;
4516 int *pack_fds = NULL;
4518 TAILQ_INIT(&refs);
4520 #ifndef PROFILE
4521 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4522 NULL)
4523 == -1)
4524 err(1, "pledge");
4525 #endif
4527 limit = get_default_log_limit();
4529 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4530 switch (ch) {
4531 case 'b':
4532 log_branches = 1;
4533 break;
4534 case 'C':
4535 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4536 &errstr);
4537 if (errstr != NULL)
4538 errx(1, "number of context lines is %s: %s",
4539 errstr, optarg);
4540 break;
4541 case 'c':
4542 start_commit = optarg;
4543 break;
4544 case 'd':
4545 show_diffstat = 1;
4546 break;
4547 case 'l':
4548 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4549 if (errstr != NULL)
4550 errx(1, "number of commits is %s: %s",
4551 errstr, optarg);
4552 break;
4553 case 'P':
4554 show_changed_paths = 1;
4555 break;
4556 case 'p':
4557 show_patch = 1;
4558 break;
4559 case 'R':
4560 reverse_display_order = 1;
4561 break;
4562 case 'r':
4563 repo_path = realpath(optarg, NULL);
4564 if (repo_path == NULL)
4565 return got_error_from_errno2("realpath",
4566 optarg);
4567 got_path_strip_trailing_slashes(repo_path);
4568 break;
4569 case 'S':
4570 search_pattern = optarg;
4571 break;
4572 case 's':
4573 one_line = 1;
4574 break;
4575 case 'x':
4576 end_commit = optarg;
4577 break;
4578 default:
4579 usage_log();
4580 /* NOTREACHED */
4584 argc -= optind;
4585 argv += optind;
4587 if (diff_context == -1)
4588 diff_context = 3;
4589 else if (!show_patch)
4590 errx(1, "-C requires -p");
4592 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4593 errx(1, "cannot use -s with -d, -p or -P");
4595 cwd = getcwd(NULL, 0);
4596 if (cwd == NULL) {
4597 error = got_error_from_errno("getcwd");
4598 goto done;
4601 error = got_repo_pack_fds_open(&pack_fds);
4602 if (error != NULL)
4603 goto done;
4605 if (repo_path == NULL) {
4606 error = got_worktree_open(&worktree, cwd);
4607 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4608 goto done;
4609 error = NULL;
4612 if (argc == 1) {
4613 if (worktree) {
4614 error = got_worktree_resolve_path(&path, worktree,
4615 argv[0]);
4616 if (error)
4617 goto done;
4618 } else {
4619 path = strdup(argv[0]);
4620 if (path == NULL) {
4621 error = got_error_from_errno("strdup");
4622 goto done;
4625 } else if (argc != 0)
4626 usage_log();
4628 if (repo_path == NULL) {
4629 repo_path = worktree ?
4630 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4632 if (repo_path == NULL) {
4633 error = got_error_from_errno("strdup");
4634 goto done;
4637 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4638 if (error != NULL)
4639 goto done;
4641 error = apply_unveil(got_repo_get_path(repo), 1,
4642 worktree ? got_worktree_get_root_path(worktree) : NULL);
4643 if (error)
4644 goto done;
4646 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4647 if (error)
4648 goto done;
4650 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4651 if (error)
4652 goto done;
4654 if (start_commit == NULL) {
4655 struct got_reference *head_ref;
4656 struct got_commit_object *commit = NULL;
4657 error = got_ref_open(&head_ref, repo,
4658 worktree ? got_worktree_get_head_ref_name(worktree)
4659 : GOT_REF_HEAD, 0);
4660 if (error != NULL)
4661 goto done;
4662 error = got_ref_resolve(&start_id, repo, head_ref);
4663 got_ref_close(head_ref);
4664 if (error != NULL)
4665 goto done;
4666 error = got_object_open_as_commit(&commit, repo,
4667 start_id);
4668 if (error != NULL)
4669 goto done;
4670 got_object_commit_close(commit);
4671 } else {
4672 error = got_repo_match_object_id(&start_id, NULL,
4673 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4674 if (error != NULL)
4675 goto done;
4677 if (end_commit != NULL) {
4678 error = got_repo_match_object_id(&end_id, NULL,
4679 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4680 if (error != NULL)
4681 goto done;
4684 if (worktree) {
4686 * If a path was specified on the command line it was resolved
4687 * to a path in the work tree above. Prepend the work tree's
4688 * path prefix to obtain the corresponding in-repository path.
4690 if (path) {
4691 const char *prefix;
4692 prefix = got_worktree_get_path_prefix(worktree);
4693 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4694 (path[0] != '\0') ? "/" : "", path) == -1) {
4695 error = got_error_from_errno("asprintf");
4696 goto done;
4699 } else
4700 error = got_repo_map_path(&in_repo_path, repo,
4701 path ? path : "");
4702 if (error != NULL)
4703 goto done;
4704 if (in_repo_path) {
4705 free(path);
4706 path = in_repo_path;
4709 if (worktree) {
4710 /* Release work tree lock. */
4711 got_worktree_close(worktree);
4712 worktree = NULL;
4715 if (search_pattern && show_patch) {
4716 tmpfile = got_opentemp();
4717 if (tmpfile == NULL) {
4718 error = got_error_from_errno("got_opentemp");
4719 goto done;
4723 error = print_commits(start_id, end_id, repo, path ? path : "",
4724 show_changed_paths, show_diffstat, show_patch, search_pattern,
4725 diff_context, limit, log_branches, reverse_display_order,
4726 refs_idmap, one_line, tmpfile);
4727 done:
4728 free(path);
4729 free(repo_path);
4730 free(cwd);
4731 if (worktree)
4732 got_worktree_close(worktree);
4733 if (repo) {
4734 const struct got_error *close_err = got_repo_close(repo);
4735 if (error == NULL)
4736 error = close_err;
4738 if (pack_fds) {
4739 const struct got_error *pack_err =
4740 got_repo_pack_fds_close(pack_fds);
4741 if (error == NULL)
4742 error = pack_err;
4744 if (refs_idmap)
4745 got_reflist_object_id_map_free(refs_idmap);
4746 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4747 error = got_error_from_errno("fclose");
4748 got_ref_list_free(&refs);
4749 return error;
4752 __dead static void
4753 usage_diff(void)
4755 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4756 "[-r repository-path] [object1 object2 | path ...]\n",
4757 getprogname());
4758 exit(1);
4761 struct print_diff_arg {
4762 struct got_repository *repo;
4763 struct got_worktree *worktree;
4764 struct got_diffstat_cb_arg *diffstat;
4765 int diff_context;
4766 const char *id_str;
4767 int header_shown;
4768 int diff_staged;
4769 enum got_diff_algorithm diff_algo;
4770 int ignore_whitespace;
4771 int force_text_diff;
4772 FILE *f1;
4773 FILE *f2;
4774 FILE *outfile;
4778 * Create a file which contains the target path of a symlink so we can feed
4779 * it as content to the diff engine.
4781 static const struct got_error *
4782 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4783 const char *abspath)
4785 const struct got_error *err = NULL;
4786 char target_path[PATH_MAX];
4787 ssize_t target_len, outlen;
4789 *fd = -1;
4791 if (dirfd != -1) {
4792 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4793 if (target_len == -1)
4794 return got_error_from_errno2("readlinkat", abspath);
4795 } else {
4796 target_len = readlink(abspath, target_path, PATH_MAX);
4797 if (target_len == -1)
4798 return got_error_from_errno2("readlink", abspath);
4801 *fd = got_opentempfd();
4802 if (*fd == -1)
4803 return got_error_from_errno("got_opentempfd");
4805 outlen = write(*fd, target_path, target_len);
4806 if (outlen == -1) {
4807 err = got_error_from_errno("got_opentempfd");
4808 goto done;
4811 if (lseek(*fd, 0, SEEK_SET) == -1) {
4812 err = got_error_from_errno2("lseek", abspath);
4813 goto done;
4815 done:
4816 if (err) {
4817 close(*fd);
4818 *fd = -1;
4820 return err;
4823 static const struct got_error *
4824 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4825 const char *path, struct got_object_id *blob_id,
4826 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4827 int dirfd, const char *de_name)
4829 struct print_diff_arg *a = arg;
4830 const struct got_error *err = NULL;
4831 struct got_blob_object *blob1 = NULL;
4832 int fd = -1, fd1 = -1, fd2 = -1;
4833 FILE *f2 = NULL;
4834 char *abspath = NULL, *label1 = NULL;
4835 struct stat sb;
4836 off_t size1 = 0;
4837 int f2_exists = 0;
4839 memset(&sb, 0, sizeof(sb));
4841 if (a->diff_staged) {
4842 if (staged_status != GOT_STATUS_MODIFY &&
4843 staged_status != GOT_STATUS_ADD &&
4844 staged_status != GOT_STATUS_DELETE)
4845 return NULL;
4846 } else {
4847 if (staged_status == GOT_STATUS_DELETE)
4848 return NULL;
4849 if (status == GOT_STATUS_NONEXISTENT)
4850 return got_error_set_errno(ENOENT, path);
4851 if (status != GOT_STATUS_MODIFY &&
4852 status != GOT_STATUS_ADD &&
4853 status != GOT_STATUS_DELETE &&
4854 status != GOT_STATUS_CONFLICT)
4855 return NULL;
4858 err = got_opentemp_truncate(a->f1);
4859 if (err)
4860 return got_error_from_errno("got_opentemp_truncate");
4861 err = got_opentemp_truncate(a->f2);
4862 if (err)
4863 return got_error_from_errno("got_opentemp_truncate");
4865 if (!a->header_shown) {
4866 if (fprintf(a->outfile, "diff %s%s\n",
4867 a->diff_staged ? "-s " : "",
4868 got_worktree_get_root_path(a->worktree)) < 0) {
4869 err = got_error_from_errno("fprintf");
4870 goto done;
4872 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4873 err = got_error_from_errno("fprintf");
4874 goto done;
4876 if (fprintf(a->outfile, "path + %s%s\n",
4877 got_worktree_get_root_path(a->worktree),
4878 a->diff_staged ? " (staged changes)" : "") < 0) {
4879 err = got_error_from_errno("fprintf");
4880 goto done;
4882 a->header_shown = 1;
4885 if (a->diff_staged) {
4886 const char *label1 = NULL, *label2 = NULL;
4887 switch (staged_status) {
4888 case GOT_STATUS_MODIFY:
4889 label1 = path;
4890 label2 = path;
4891 break;
4892 case GOT_STATUS_ADD:
4893 label2 = path;
4894 break;
4895 case GOT_STATUS_DELETE:
4896 label1 = path;
4897 break;
4898 default:
4899 return got_error(GOT_ERR_FILE_STATUS);
4901 fd1 = got_opentempfd();
4902 if (fd1 == -1) {
4903 err = got_error_from_errno("got_opentempfd");
4904 goto done;
4906 fd2 = got_opentempfd();
4907 if (fd2 == -1) {
4908 err = got_error_from_errno("got_opentempfd");
4909 goto done;
4911 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4912 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4913 a->diff_algo, a->diff_context, a->ignore_whitespace,
4914 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4915 goto done;
4918 fd1 = got_opentempfd();
4919 if (fd1 == -1) {
4920 err = got_error_from_errno("got_opentempfd");
4921 goto done;
4924 if (staged_status == GOT_STATUS_ADD ||
4925 staged_status == GOT_STATUS_MODIFY) {
4926 char *id_str;
4927 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4928 8192, fd1);
4929 if (err)
4930 goto done;
4931 err = got_object_id_str(&id_str, staged_blob_id);
4932 if (err)
4933 goto done;
4934 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4935 err = got_error_from_errno("asprintf");
4936 free(id_str);
4937 goto done;
4939 free(id_str);
4940 } else if (status != GOT_STATUS_ADD) {
4941 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4942 fd1);
4943 if (err)
4944 goto done;
4947 if (status != GOT_STATUS_DELETE) {
4948 if (asprintf(&abspath, "%s/%s",
4949 got_worktree_get_root_path(a->worktree), path) == -1) {
4950 err = got_error_from_errno("asprintf");
4951 goto done;
4954 if (dirfd != -1) {
4955 fd = openat(dirfd, de_name,
4956 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4957 if (fd == -1) {
4958 if (!got_err_open_nofollow_on_symlink()) {
4959 err = got_error_from_errno2("openat",
4960 abspath);
4961 goto done;
4963 err = get_symlink_target_file(&fd, dirfd,
4964 de_name, abspath);
4965 if (err)
4966 goto done;
4968 } else {
4969 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4970 if (fd == -1) {
4971 if (!got_err_open_nofollow_on_symlink()) {
4972 err = got_error_from_errno2("open",
4973 abspath);
4974 goto done;
4976 err = get_symlink_target_file(&fd, dirfd,
4977 de_name, abspath);
4978 if (err)
4979 goto done;
4982 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4983 err = got_error_from_errno2("fstatat", abspath);
4984 goto done;
4986 f2 = fdopen(fd, "r");
4987 if (f2 == NULL) {
4988 err = got_error_from_errno2("fdopen", abspath);
4989 goto done;
4991 fd = -1;
4992 f2_exists = 1;
4995 if (blob1) {
4996 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4997 a->f1, blob1);
4998 if (err)
4999 goto done;
5002 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5003 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5004 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5005 done:
5006 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5007 err = got_error_from_errno("close");
5008 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5009 err = got_error_from_errno("close");
5010 if (blob1)
5011 got_object_blob_close(blob1);
5012 if (fd != -1 && close(fd) == -1 && err == NULL)
5013 err = got_error_from_errno("close");
5014 if (f2 && fclose(f2) == EOF && err == NULL)
5015 err = got_error_from_errno("fclose");
5016 free(abspath);
5017 return err;
5020 static const struct got_error *
5021 cmd_diff(int argc, char *argv[])
5023 const struct got_error *error;
5024 struct got_repository *repo = NULL;
5025 struct got_worktree *worktree = NULL;
5026 char *cwd = NULL, *repo_path = NULL;
5027 const char *commit_args[2] = { NULL, NULL };
5028 int ncommit_args = 0;
5029 struct got_object_id *ids[2] = { NULL, NULL };
5030 char *labels[2] = { NULL, NULL };
5031 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5032 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5033 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5034 const char *errstr;
5035 struct got_reflist_head refs;
5036 struct got_pathlist_head diffstat_paths, paths;
5037 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5038 int fd1 = -1, fd2 = -1;
5039 int *pack_fds = NULL;
5040 struct got_diffstat_cb_arg dsa;
5042 memset(&dsa, 0, sizeof(dsa));
5044 TAILQ_INIT(&refs);
5045 TAILQ_INIT(&paths);
5046 TAILQ_INIT(&diffstat_paths);
5048 #ifndef PROFILE
5049 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5050 NULL) == -1)
5051 err(1, "pledge");
5052 #endif
5054 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5055 switch (ch) {
5056 case 'a':
5057 force_text_diff = 1;
5058 break;
5059 case 'C':
5060 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5061 &errstr);
5062 if (errstr != NULL)
5063 errx(1, "number of context lines is %s: %s",
5064 errstr, optarg);
5065 break;
5066 case 'c':
5067 if (ncommit_args >= 2)
5068 errx(1, "too many -c options used");
5069 commit_args[ncommit_args++] = optarg;
5070 break;
5071 case 'd':
5072 show_diffstat = 1;
5073 break;
5074 case 'P':
5075 force_path = 1;
5076 break;
5077 case 'r':
5078 repo_path = realpath(optarg, NULL);
5079 if (repo_path == NULL)
5080 return got_error_from_errno2("realpath",
5081 optarg);
5082 got_path_strip_trailing_slashes(repo_path);
5083 rflag = 1;
5084 break;
5085 case 's':
5086 diff_staged = 1;
5087 break;
5088 case 'w':
5089 ignore_whitespace = 1;
5090 break;
5091 default:
5092 usage_diff();
5093 /* NOTREACHED */
5097 argc -= optind;
5098 argv += optind;
5100 cwd = getcwd(NULL, 0);
5101 if (cwd == NULL) {
5102 error = got_error_from_errno("getcwd");
5103 goto done;
5106 error = got_repo_pack_fds_open(&pack_fds);
5107 if (error != NULL)
5108 goto done;
5110 if (repo_path == NULL) {
5111 error = got_worktree_open(&worktree, cwd);
5112 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5113 goto done;
5114 else
5115 error = NULL;
5116 if (worktree) {
5117 repo_path =
5118 strdup(got_worktree_get_repo_path(worktree));
5119 if (repo_path == NULL) {
5120 error = got_error_from_errno("strdup");
5121 goto done;
5123 } else {
5124 repo_path = strdup(cwd);
5125 if (repo_path == NULL) {
5126 error = got_error_from_errno("strdup");
5127 goto done;
5132 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5133 free(repo_path);
5134 if (error != NULL)
5135 goto done;
5137 if (show_diffstat) {
5138 dsa.paths = &diffstat_paths;
5139 dsa.force_text = force_text_diff;
5140 dsa.ignore_ws = ignore_whitespace;
5141 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5144 if (rflag || worktree == NULL || ncommit_args > 0) {
5145 if (force_path) {
5146 error = got_error_msg(GOT_ERR_NOT_IMPL,
5147 "-P option can only be used when diffing "
5148 "a work tree");
5149 goto done;
5151 if (diff_staged) {
5152 error = got_error_msg(GOT_ERR_NOT_IMPL,
5153 "-s option can only be used when diffing "
5154 "a work tree");
5155 goto done;
5159 error = apply_unveil(got_repo_get_path(repo), 1,
5160 worktree ? got_worktree_get_root_path(worktree) : NULL);
5161 if (error)
5162 goto done;
5164 if ((!force_path && argc == 2) || ncommit_args > 0) {
5165 int obj_type = (ncommit_args > 0 ?
5166 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5167 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5168 NULL);
5169 if (error)
5170 goto done;
5171 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5172 const char *arg;
5173 if (ncommit_args > 0)
5174 arg = commit_args[i];
5175 else
5176 arg = argv[i];
5177 error = got_repo_match_object_id(&ids[i], &labels[i],
5178 arg, obj_type, &refs, repo);
5179 if (error) {
5180 if (error->code != GOT_ERR_NOT_REF &&
5181 error->code != GOT_ERR_NO_OBJ)
5182 goto done;
5183 if (ncommit_args > 0)
5184 goto done;
5185 error = NULL;
5186 break;
5191 f1 = got_opentemp();
5192 if (f1 == NULL) {
5193 error = got_error_from_errno("got_opentemp");
5194 goto done;
5197 f2 = got_opentemp();
5198 if (f2 == NULL) {
5199 error = got_error_from_errno("got_opentemp");
5200 goto done;
5203 outfile = got_opentemp();
5204 if (outfile == NULL) {
5205 error = got_error_from_errno("got_opentemp");
5206 goto done;
5209 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5210 struct print_diff_arg arg;
5211 char *id_str;
5213 if (worktree == NULL) {
5214 if (argc == 2 && ids[0] == NULL) {
5215 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5216 goto done;
5217 } else if (argc == 2 && ids[1] == NULL) {
5218 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5219 goto done;
5220 } else if (argc > 0) {
5221 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5222 "%s", "specified paths cannot be resolved");
5223 goto done;
5224 } else {
5225 error = got_error(GOT_ERR_NOT_WORKTREE);
5226 goto done;
5230 error = get_worktree_paths_from_argv(&paths, argc, argv,
5231 worktree);
5232 if (error)
5233 goto done;
5235 error = got_object_id_str(&id_str,
5236 got_worktree_get_base_commit_id(worktree));
5237 if (error)
5238 goto done;
5239 arg.repo = repo;
5240 arg.worktree = worktree;
5241 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5242 arg.diff_context = diff_context;
5243 arg.id_str = id_str;
5244 arg.header_shown = 0;
5245 arg.diff_staged = diff_staged;
5246 arg.ignore_whitespace = ignore_whitespace;
5247 arg.force_text_diff = force_text_diff;
5248 arg.diffstat = show_diffstat ? &dsa : NULL;
5249 arg.f1 = f1;
5250 arg.f2 = f2;
5251 arg.outfile = outfile;
5253 error = got_worktree_status(worktree, &paths, repo, 0,
5254 print_diff, &arg, check_cancelled, NULL);
5255 free(id_str);
5256 if (error)
5257 goto done;
5259 if (show_diffstat && dsa.nfiles > 0) {
5260 char *header;
5262 if (asprintf(&header, "diffstat %s%s",
5263 diff_staged ? "-s " : "",
5264 got_worktree_get_root_path(worktree)) == -1) {
5265 error = got_error_from_errno("asprintf");
5266 goto done;
5269 error = print_diffstat(&dsa, header);
5270 free(header);
5271 if (error)
5272 goto done;
5275 error = printfile(outfile);
5276 goto done;
5279 if (ncommit_args == 1) {
5280 struct got_commit_object *commit;
5281 error = got_object_open_as_commit(&commit, repo, ids[0]);
5282 if (error)
5283 goto done;
5285 labels[1] = labels[0];
5286 ids[1] = ids[0];
5287 if (got_object_commit_get_nparents(commit) > 0) {
5288 const struct got_object_id_queue *pids;
5289 struct got_object_qid *pid;
5290 pids = got_object_commit_get_parent_ids(commit);
5291 pid = STAILQ_FIRST(pids);
5292 ids[0] = got_object_id_dup(&pid->id);
5293 if (ids[0] == NULL) {
5294 error = got_error_from_errno(
5295 "got_object_id_dup");
5296 got_object_commit_close(commit);
5297 goto done;
5299 error = got_object_id_str(&labels[0], ids[0]);
5300 if (error) {
5301 got_object_commit_close(commit);
5302 goto done;
5304 } else {
5305 ids[0] = NULL;
5306 labels[0] = strdup("/dev/null");
5307 if (labels[0] == NULL) {
5308 error = got_error_from_errno("strdup");
5309 got_object_commit_close(commit);
5310 goto done;
5314 got_object_commit_close(commit);
5317 if (ncommit_args == 0 && argc > 2) {
5318 error = got_error_msg(GOT_ERR_BAD_PATH,
5319 "path arguments cannot be used when diffing two objects");
5320 goto done;
5323 if (ids[0]) {
5324 error = got_object_get_type(&type1, repo, ids[0]);
5325 if (error)
5326 goto done;
5329 error = got_object_get_type(&type2, repo, ids[1]);
5330 if (error)
5331 goto done;
5332 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5333 error = got_error(GOT_ERR_OBJ_TYPE);
5334 goto done;
5336 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5337 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5338 "path arguments cannot be used when diffing blobs");
5339 goto done;
5342 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5343 char *in_repo_path;
5344 struct got_pathlist_entry *new;
5345 if (worktree) {
5346 const char *prefix;
5347 char *p;
5348 error = got_worktree_resolve_path(&p, worktree,
5349 argv[i]);
5350 if (error)
5351 goto done;
5352 prefix = got_worktree_get_path_prefix(worktree);
5353 while (prefix[0] == '/')
5354 prefix++;
5355 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5356 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5357 p) == -1) {
5358 error = got_error_from_errno("asprintf");
5359 free(p);
5360 goto done;
5362 free(p);
5363 } else {
5364 char *mapped_path, *s;
5365 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5366 if (error)
5367 goto done;
5368 s = mapped_path;
5369 while (s[0] == '/')
5370 s++;
5371 in_repo_path = strdup(s);
5372 if (in_repo_path == NULL) {
5373 error = got_error_from_errno("asprintf");
5374 free(mapped_path);
5375 goto done;
5377 free(mapped_path);
5380 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5381 if (error || new == NULL /* duplicate */)
5382 free(in_repo_path);
5383 if (error)
5384 goto done;
5387 if (worktree) {
5388 /* Release work tree lock. */
5389 got_worktree_close(worktree);
5390 worktree = NULL;
5393 fd1 = got_opentempfd();
5394 if (fd1 == -1) {
5395 error = got_error_from_errno("got_opentempfd");
5396 goto done;
5399 fd2 = got_opentempfd();
5400 if (fd2 == -1) {
5401 error = got_error_from_errno("got_opentempfd");
5402 goto done;
5405 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5406 case GOT_OBJ_TYPE_BLOB:
5407 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5408 fd1, fd2, ids[0], ids[1], NULL, NULL,
5409 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5410 ignore_whitespace, force_text_diff,
5411 show_diffstat ? &dsa : NULL, repo, outfile);
5412 break;
5413 case GOT_OBJ_TYPE_TREE:
5414 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5415 ids[0], ids[1], &paths, "", "",
5416 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5417 ignore_whitespace, force_text_diff,
5418 show_diffstat ? &dsa : NULL, repo, outfile);
5419 break;
5420 case GOT_OBJ_TYPE_COMMIT:
5421 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5422 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5423 fd1, fd2, ids[0], ids[1], &paths,
5424 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5425 ignore_whitespace, force_text_diff,
5426 show_diffstat ? &dsa : NULL, repo, outfile);
5427 break;
5428 default:
5429 error = got_error(GOT_ERR_OBJ_TYPE);
5431 if (error)
5432 goto done;
5434 if (show_diffstat && dsa.nfiles > 0) {
5435 char *header = NULL;
5437 if (asprintf(&header, "diffstat %s %s",
5438 labels[0], labels[1]) == -1) {
5439 error = got_error_from_errno("asprintf");
5440 goto done;
5443 error = print_diffstat(&dsa, header);
5444 free(header);
5445 if (error)
5446 goto done;
5449 error = printfile(outfile);
5451 done:
5452 free(labels[0]);
5453 free(labels[1]);
5454 free(ids[0]);
5455 free(ids[1]);
5456 if (worktree)
5457 got_worktree_close(worktree);
5458 if (repo) {
5459 const struct got_error *close_err = got_repo_close(repo);
5460 if (error == NULL)
5461 error = close_err;
5463 if (pack_fds) {
5464 const struct got_error *pack_err =
5465 got_repo_pack_fds_close(pack_fds);
5466 if (error == NULL)
5467 error = pack_err;
5469 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5470 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5471 got_ref_list_free(&refs);
5472 if (outfile && fclose(outfile) == EOF && error == NULL)
5473 error = got_error_from_errno("fclose");
5474 if (f1 && fclose(f1) == EOF && error == NULL)
5475 error = got_error_from_errno("fclose");
5476 if (f2 && fclose(f2) == EOF && error == NULL)
5477 error = got_error_from_errno("fclose");
5478 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5479 error = got_error_from_errno("close");
5480 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5481 error = got_error_from_errno("close");
5482 return error;
5485 __dead static void
5486 usage_blame(void)
5488 fprintf(stderr,
5489 "usage: %s blame [-c commit] [-r repository-path] path\n",
5490 getprogname());
5491 exit(1);
5494 struct blame_line {
5495 int annotated;
5496 char *id_str;
5497 char *committer;
5498 char datebuf[11]; /* YYYY-MM-DD + NUL */
5501 struct blame_cb_args {
5502 struct blame_line *lines;
5503 int nlines;
5504 int nlines_prec;
5505 int lineno_cur;
5506 off_t *line_offsets;
5507 FILE *f;
5508 struct got_repository *repo;
5511 static const struct got_error *
5512 blame_cb(void *arg, int nlines, int lineno,
5513 struct got_commit_object *commit, struct got_object_id *id)
5515 const struct got_error *err = NULL;
5516 struct blame_cb_args *a = arg;
5517 struct blame_line *bline;
5518 char *line = NULL;
5519 size_t linesize = 0;
5520 off_t offset;
5521 struct tm tm;
5522 time_t committer_time;
5524 if (nlines != a->nlines ||
5525 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5526 return got_error(GOT_ERR_RANGE);
5528 if (sigint_received)
5529 return got_error(GOT_ERR_ITER_COMPLETED);
5531 if (lineno == -1)
5532 return NULL; /* no change in this commit */
5534 /* Annotate this line. */
5535 bline = &a->lines[lineno - 1];
5536 if (bline->annotated)
5537 return NULL;
5538 err = got_object_id_str(&bline->id_str, id);
5539 if (err)
5540 return err;
5542 bline->committer = strdup(got_object_commit_get_committer(commit));
5543 if (bline->committer == NULL) {
5544 err = got_error_from_errno("strdup");
5545 goto done;
5548 committer_time = got_object_commit_get_committer_time(commit);
5549 if (gmtime_r(&committer_time, &tm) == NULL)
5550 return got_error_from_errno("gmtime_r");
5551 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5552 &tm) == 0) {
5553 err = got_error(GOT_ERR_NO_SPACE);
5554 goto done;
5556 bline->annotated = 1;
5558 /* Print lines annotated so far. */
5559 bline = &a->lines[a->lineno_cur - 1];
5560 if (!bline->annotated)
5561 goto done;
5563 offset = a->line_offsets[a->lineno_cur - 1];
5564 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5565 err = got_error_from_errno("fseeko");
5566 goto done;
5569 while (a->lineno_cur <= a->nlines && bline->annotated) {
5570 char *smallerthan, *at, *nl, *committer;
5571 size_t len;
5573 if (getline(&line, &linesize, a->f) == -1) {
5574 if (ferror(a->f))
5575 err = got_error_from_errno("getline");
5576 break;
5579 committer = bline->committer;
5580 smallerthan = strchr(committer, '<');
5581 if (smallerthan && smallerthan[1] != '\0')
5582 committer = smallerthan + 1;
5583 at = strchr(committer, '@');
5584 if (at)
5585 *at = '\0';
5586 len = strlen(committer);
5587 if (len >= 9)
5588 committer[8] = '\0';
5590 nl = strchr(line, '\n');
5591 if (nl)
5592 *nl = '\0';
5593 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5594 bline->id_str, bline->datebuf, committer, line);
5596 a->lineno_cur++;
5597 bline = &a->lines[a->lineno_cur - 1];
5599 done:
5600 free(line);
5601 return err;
5604 static const struct got_error *
5605 cmd_blame(int argc, char *argv[])
5607 const struct got_error *error;
5608 struct got_repository *repo = NULL;
5609 struct got_worktree *worktree = NULL;
5610 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5611 char *link_target = NULL;
5612 struct got_object_id *obj_id = NULL;
5613 struct got_object_id *commit_id = NULL;
5614 struct got_commit_object *commit = NULL;
5615 struct got_blob_object *blob = NULL;
5616 char *commit_id_str = NULL;
5617 struct blame_cb_args bca;
5618 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5619 off_t filesize;
5620 int *pack_fds = NULL;
5621 FILE *f1 = NULL, *f2 = NULL;
5623 fd1 = got_opentempfd();
5624 if (fd1 == -1)
5625 return got_error_from_errno("got_opentempfd");
5627 memset(&bca, 0, sizeof(bca));
5629 #ifndef PROFILE
5630 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5631 NULL) == -1)
5632 err(1, "pledge");
5633 #endif
5635 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5636 switch (ch) {
5637 case 'c':
5638 commit_id_str = optarg;
5639 break;
5640 case 'r':
5641 repo_path = realpath(optarg, NULL);
5642 if (repo_path == NULL)
5643 return got_error_from_errno2("realpath",
5644 optarg);
5645 got_path_strip_trailing_slashes(repo_path);
5646 break;
5647 default:
5648 usage_blame();
5649 /* NOTREACHED */
5653 argc -= optind;
5654 argv += optind;
5656 if (argc == 1)
5657 path = argv[0];
5658 else
5659 usage_blame();
5661 cwd = getcwd(NULL, 0);
5662 if (cwd == NULL) {
5663 error = got_error_from_errno("getcwd");
5664 goto done;
5667 error = got_repo_pack_fds_open(&pack_fds);
5668 if (error != NULL)
5669 goto done;
5671 if (repo_path == NULL) {
5672 error = got_worktree_open(&worktree, cwd);
5673 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5674 goto done;
5675 else
5676 error = NULL;
5677 if (worktree) {
5678 repo_path =
5679 strdup(got_worktree_get_repo_path(worktree));
5680 if (repo_path == NULL) {
5681 error = got_error_from_errno("strdup");
5682 if (error)
5683 goto done;
5685 } else {
5686 repo_path = strdup(cwd);
5687 if (repo_path == NULL) {
5688 error = got_error_from_errno("strdup");
5689 goto done;
5694 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5695 if (error != NULL)
5696 goto done;
5698 if (worktree) {
5699 const char *prefix = got_worktree_get_path_prefix(worktree);
5700 char *p;
5702 error = got_worktree_resolve_path(&p, worktree, path);
5703 if (error)
5704 goto done;
5705 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5706 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5707 p) == -1) {
5708 error = got_error_from_errno("asprintf");
5709 free(p);
5710 goto done;
5712 free(p);
5713 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5714 } else {
5715 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5716 if (error)
5717 goto done;
5718 error = got_repo_map_path(&in_repo_path, repo, path);
5720 if (error)
5721 goto done;
5723 if (commit_id_str == NULL) {
5724 struct got_reference *head_ref;
5725 error = got_ref_open(&head_ref, repo, worktree ?
5726 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5727 if (error != NULL)
5728 goto done;
5729 error = got_ref_resolve(&commit_id, repo, head_ref);
5730 got_ref_close(head_ref);
5731 if (error != NULL)
5732 goto done;
5733 } else {
5734 struct got_reflist_head refs;
5735 TAILQ_INIT(&refs);
5736 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5737 NULL);
5738 if (error)
5739 goto done;
5740 error = got_repo_match_object_id(&commit_id, NULL,
5741 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5742 got_ref_list_free(&refs);
5743 if (error)
5744 goto done;
5747 if (worktree) {
5748 /* Release work tree lock. */
5749 got_worktree_close(worktree);
5750 worktree = NULL;
5753 error = got_object_open_as_commit(&commit, repo, commit_id);
5754 if (error)
5755 goto done;
5757 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5758 commit, repo);
5759 if (error)
5760 goto done;
5762 error = got_object_id_by_path(&obj_id, repo, commit,
5763 link_target ? link_target : in_repo_path);
5764 if (error)
5765 goto done;
5767 error = got_object_get_type(&obj_type, repo, obj_id);
5768 if (error)
5769 goto done;
5771 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5772 error = got_error_path(link_target ? link_target : in_repo_path,
5773 GOT_ERR_OBJ_TYPE);
5774 goto done;
5777 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5778 if (error)
5779 goto done;
5780 bca.f = got_opentemp();
5781 if (bca.f == NULL) {
5782 error = got_error_from_errno("got_opentemp");
5783 goto done;
5785 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5786 &bca.line_offsets, bca.f, blob);
5787 if (error || bca.nlines == 0)
5788 goto done;
5790 /* Don't include \n at EOF in the blame line count. */
5791 if (bca.line_offsets[bca.nlines - 1] == filesize)
5792 bca.nlines--;
5794 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5795 if (bca.lines == NULL) {
5796 error = got_error_from_errno("calloc");
5797 goto done;
5799 bca.lineno_cur = 1;
5800 bca.nlines_prec = 0;
5801 i = bca.nlines;
5802 while (i > 0) {
5803 i /= 10;
5804 bca.nlines_prec++;
5806 bca.repo = repo;
5808 fd2 = got_opentempfd();
5809 if (fd2 == -1) {
5810 error = got_error_from_errno("got_opentempfd");
5811 goto done;
5813 fd3 = got_opentempfd();
5814 if (fd3 == -1) {
5815 error = got_error_from_errno("got_opentempfd");
5816 goto done;
5818 f1 = got_opentemp();
5819 if (f1 == NULL) {
5820 error = got_error_from_errno("got_opentemp");
5821 goto done;
5823 f2 = got_opentemp();
5824 if (f2 == NULL) {
5825 error = got_error_from_errno("got_opentemp");
5826 goto done;
5828 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5829 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5830 check_cancelled, NULL, fd2, fd3, f1, f2);
5831 done:
5832 free(in_repo_path);
5833 free(link_target);
5834 free(repo_path);
5835 free(cwd);
5836 free(commit_id);
5837 free(obj_id);
5838 if (commit)
5839 got_object_commit_close(commit);
5841 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5842 error = got_error_from_errno("close");
5843 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5844 error = got_error_from_errno("close");
5845 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5846 error = got_error_from_errno("close");
5847 if (f1 && fclose(f1) == EOF && error == NULL)
5848 error = got_error_from_errno("fclose");
5849 if (f2 && fclose(f2) == EOF && error == NULL)
5850 error = got_error_from_errno("fclose");
5852 if (blob)
5853 got_object_blob_close(blob);
5854 if (worktree)
5855 got_worktree_close(worktree);
5856 if (repo) {
5857 const struct got_error *close_err = got_repo_close(repo);
5858 if (error == NULL)
5859 error = close_err;
5861 if (pack_fds) {
5862 const struct got_error *pack_err =
5863 got_repo_pack_fds_close(pack_fds);
5864 if (error == NULL)
5865 error = pack_err;
5867 if (bca.lines) {
5868 for (i = 0; i < bca.nlines; i++) {
5869 struct blame_line *bline = &bca.lines[i];
5870 free(bline->id_str);
5871 free(bline->committer);
5873 free(bca.lines);
5875 free(bca.line_offsets);
5876 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5877 error = got_error_from_errno("fclose");
5878 return error;
5881 __dead static void
5882 usage_tree(void)
5884 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5885 "[path]\n", getprogname());
5886 exit(1);
5889 static const struct got_error *
5890 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5891 const char *root_path, struct got_repository *repo)
5893 const struct got_error *err = NULL;
5894 int is_root_path = (strcmp(path, root_path) == 0);
5895 const char *modestr = "";
5896 mode_t mode = got_tree_entry_get_mode(te);
5897 char *link_target = NULL;
5899 path += strlen(root_path);
5900 while (path[0] == '/')
5901 path++;
5903 if (got_object_tree_entry_is_submodule(te))
5904 modestr = "$";
5905 else if (S_ISLNK(mode)) {
5906 int i;
5908 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5909 if (err)
5910 return err;
5911 for (i = 0; i < strlen(link_target); i++) {
5912 if (!isprint((unsigned char)link_target[i]))
5913 link_target[i] = '?';
5916 modestr = "@";
5918 else if (S_ISDIR(mode))
5919 modestr = "/";
5920 else if (mode & S_IXUSR)
5921 modestr = "*";
5923 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5924 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5925 link_target ? " -> ": "", link_target ? link_target : "");
5927 free(link_target);
5928 return NULL;
5931 static const struct got_error *
5932 print_tree(const char *path, struct got_commit_object *commit,
5933 int show_ids, int recurse, const char *root_path,
5934 struct got_repository *repo)
5936 const struct got_error *err = NULL;
5937 struct got_object_id *tree_id = NULL;
5938 struct got_tree_object *tree = NULL;
5939 int nentries, i;
5941 err = got_object_id_by_path(&tree_id, repo, commit, path);
5942 if (err)
5943 goto done;
5945 err = got_object_open_as_tree(&tree, repo, tree_id);
5946 if (err)
5947 goto done;
5948 nentries = got_object_tree_get_nentries(tree);
5949 for (i = 0; i < nentries; i++) {
5950 struct got_tree_entry *te;
5951 char *id = NULL;
5953 if (sigint_received || sigpipe_received)
5954 break;
5956 te = got_object_tree_get_entry(tree, i);
5957 if (show_ids) {
5958 char *id_str;
5959 err = got_object_id_str(&id_str,
5960 got_tree_entry_get_id(te));
5961 if (err)
5962 goto done;
5963 if (asprintf(&id, "%s ", id_str) == -1) {
5964 err = got_error_from_errno("asprintf");
5965 free(id_str);
5966 goto done;
5968 free(id_str);
5970 err = print_entry(te, id, path, root_path, repo);
5971 free(id);
5972 if (err)
5973 goto done;
5975 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5976 char *child_path;
5977 if (asprintf(&child_path, "%s%s%s", path,
5978 path[0] == '/' && path[1] == '\0' ? "" : "/",
5979 got_tree_entry_get_name(te)) == -1) {
5980 err = got_error_from_errno("asprintf");
5981 goto done;
5983 err = print_tree(child_path, commit, show_ids, 1,
5984 root_path, repo);
5985 free(child_path);
5986 if (err)
5987 goto done;
5990 done:
5991 if (tree)
5992 got_object_tree_close(tree);
5993 free(tree_id);
5994 return err;
5997 static const struct got_error *
5998 cmd_tree(int argc, char *argv[])
6000 const struct got_error *error;
6001 struct got_repository *repo = NULL;
6002 struct got_worktree *worktree = NULL;
6003 const char *path, *refname = NULL;
6004 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6005 struct got_object_id *commit_id = NULL;
6006 struct got_commit_object *commit = NULL;
6007 char *commit_id_str = NULL;
6008 int show_ids = 0, recurse = 0;
6009 int ch;
6010 int *pack_fds = NULL;
6012 #ifndef PROFILE
6013 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6014 NULL) == -1)
6015 err(1, "pledge");
6016 #endif
6018 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6019 switch (ch) {
6020 case 'c':
6021 commit_id_str = optarg;
6022 break;
6023 case 'i':
6024 show_ids = 1;
6025 break;
6026 case 'R':
6027 recurse = 1;
6028 break;
6029 case 'r':
6030 repo_path = realpath(optarg, NULL);
6031 if (repo_path == NULL)
6032 return got_error_from_errno2("realpath",
6033 optarg);
6034 got_path_strip_trailing_slashes(repo_path);
6035 break;
6036 default:
6037 usage_tree();
6038 /* NOTREACHED */
6042 argc -= optind;
6043 argv += optind;
6045 if (argc == 1)
6046 path = argv[0];
6047 else if (argc > 1)
6048 usage_tree();
6049 else
6050 path = NULL;
6052 cwd = getcwd(NULL, 0);
6053 if (cwd == NULL) {
6054 error = got_error_from_errno("getcwd");
6055 goto done;
6058 error = got_repo_pack_fds_open(&pack_fds);
6059 if (error != NULL)
6060 goto done;
6062 if (repo_path == NULL) {
6063 error = got_worktree_open(&worktree, cwd);
6064 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6065 goto done;
6066 else
6067 error = NULL;
6068 if (worktree) {
6069 repo_path =
6070 strdup(got_worktree_get_repo_path(worktree));
6071 if (repo_path == NULL)
6072 error = got_error_from_errno("strdup");
6073 if (error)
6074 goto done;
6075 } else {
6076 repo_path = strdup(cwd);
6077 if (repo_path == NULL) {
6078 error = got_error_from_errno("strdup");
6079 goto done;
6084 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6085 if (error != NULL)
6086 goto done;
6088 if (worktree) {
6089 const char *prefix = got_worktree_get_path_prefix(worktree);
6090 char *p;
6092 if (path == NULL)
6093 path = "";
6094 error = got_worktree_resolve_path(&p, worktree, path);
6095 if (error)
6096 goto done;
6097 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6098 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6099 p) == -1) {
6100 error = got_error_from_errno("asprintf");
6101 free(p);
6102 goto done;
6104 free(p);
6105 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6106 if (error)
6107 goto done;
6108 } else {
6109 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6110 if (error)
6111 goto done;
6112 if (path == NULL)
6113 path = "/";
6114 error = got_repo_map_path(&in_repo_path, repo, path);
6115 if (error != NULL)
6116 goto done;
6119 if (commit_id_str == NULL) {
6120 struct got_reference *head_ref;
6121 if (worktree)
6122 refname = got_worktree_get_head_ref_name(worktree);
6123 else
6124 refname = GOT_REF_HEAD;
6125 error = got_ref_open(&head_ref, repo, refname, 0);
6126 if (error != NULL)
6127 goto done;
6128 error = got_ref_resolve(&commit_id, repo, head_ref);
6129 got_ref_close(head_ref);
6130 if (error != NULL)
6131 goto done;
6132 } else {
6133 struct got_reflist_head refs;
6134 TAILQ_INIT(&refs);
6135 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6136 NULL);
6137 if (error)
6138 goto done;
6139 error = got_repo_match_object_id(&commit_id, NULL,
6140 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6141 got_ref_list_free(&refs);
6142 if (error)
6143 goto done;
6146 if (worktree) {
6147 /* Release work tree lock. */
6148 got_worktree_close(worktree);
6149 worktree = NULL;
6152 error = got_object_open_as_commit(&commit, repo, commit_id);
6153 if (error)
6154 goto done;
6156 error = print_tree(in_repo_path, commit, show_ids, recurse,
6157 in_repo_path, repo);
6158 done:
6159 free(in_repo_path);
6160 free(repo_path);
6161 free(cwd);
6162 free(commit_id);
6163 if (commit)
6164 got_object_commit_close(commit);
6165 if (worktree)
6166 got_worktree_close(worktree);
6167 if (repo) {
6168 const struct got_error *close_err = got_repo_close(repo);
6169 if (error == NULL)
6170 error = close_err;
6172 if (pack_fds) {
6173 const struct got_error *pack_err =
6174 got_repo_pack_fds_close(pack_fds);
6175 if (error == NULL)
6176 error = pack_err;
6178 return error;
6181 __dead static void
6182 usage_status(void)
6184 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6185 "[-s status-codes] [path ...]\n", getprogname());
6186 exit(1);
6189 struct got_status_arg {
6190 char *status_codes;
6191 int suppress;
6194 static const struct got_error *
6195 print_status(void *arg, unsigned char status, unsigned char staged_status,
6196 const char *path, struct got_object_id *blob_id,
6197 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6198 int dirfd, const char *de_name)
6200 struct got_status_arg *st = arg;
6202 if (status == staged_status && (status == GOT_STATUS_DELETE))
6203 status = GOT_STATUS_NO_CHANGE;
6204 if (st != NULL && st->status_codes) {
6205 size_t ncodes = strlen(st->status_codes);
6206 int i, j = 0;
6208 for (i = 0; i < ncodes ; i++) {
6209 if (st->suppress) {
6210 if (status == st->status_codes[i] ||
6211 staged_status == st->status_codes[i]) {
6212 j++;
6213 continue;
6215 } else {
6216 if (status == st->status_codes[i] ||
6217 staged_status == st->status_codes[i])
6218 break;
6222 if (st->suppress && j == 0)
6223 goto print;
6225 if (i == ncodes)
6226 return NULL;
6228 print:
6229 printf("%c%c %s\n", status, staged_status, path);
6230 return NULL;
6233 static const struct got_error *
6234 cmd_status(int argc, char *argv[])
6236 const struct got_error *error = NULL;
6237 struct got_repository *repo = NULL;
6238 struct got_worktree *worktree = NULL;
6239 struct got_status_arg st;
6240 char *cwd = NULL;
6241 struct got_pathlist_head paths;
6242 int ch, i, no_ignores = 0;
6243 int *pack_fds = NULL;
6245 TAILQ_INIT(&paths);
6247 memset(&st, 0, sizeof(st));
6248 st.status_codes = NULL;
6249 st.suppress = 0;
6251 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6252 switch (ch) {
6253 case 'I':
6254 no_ignores = 1;
6255 break;
6256 case 'S':
6257 if (st.status_codes != NULL && st.suppress == 0)
6258 option_conflict('S', 's');
6259 st.suppress = 1;
6260 /* fallthrough */
6261 case 's':
6262 for (i = 0; i < strlen(optarg); i++) {
6263 switch (optarg[i]) {
6264 case GOT_STATUS_MODIFY:
6265 case GOT_STATUS_ADD:
6266 case GOT_STATUS_DELETE:
6267 case GOT_STATUS_CONFLICT:
6268 case GOT_STATUS_MISSING:
6269 case GOT_STATUS_OBSTRUCTED:
6270 case GOT_STATUS_UNVERSIONED:
6271 case GOT_STATUS_MODE_CHANGE:
6272 case GOT_STATUS_NONEXISTENT:
6273 break;
6274 default:
6275 errx(1, "invalid status code '%c'",
6276 optarg[i]);
6279 if (ch == 's' && st.suppress)
6280 option_conflict('s', 'S');
6281 st.status_codes = optarg;
6282 break;
6283 default:
6284 usage_status();
6285 /* NOTREACHED */
6289 argc -= optind;
6290 argv += optind;
6292 #ifndef PROFILE
6293 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6294 NULL) == -1)
6295 err(1, "pledge");
6296 #endif
6297 cwd = getcwd(NULL, 0);
6298 if (cwd == NULL) {
6299 error = got_error_from_errno("getcwd");
6300 goto done;
6303 error = got_repo_pack_fds_open(&pack_fds);
6304 if (error != NULL)
6305 goto done;
6307 error = got_worktree_open(&worktree, cwd);
6308 if (error) {
6309 if (error->code == GOT_ERR_NOT_WORKTREE)
6310 error = wrap_not_worktree_error(error, "status", cwd);
6311 goto done;
6314 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6315 NULL, pack_fds);
6316 if (error != NULL)
6317 goto done;
6319 error = apply_unveil(got_repo_get_path(repo), 1,
6320 got_worktree_get_root_path(worktree));
6321 if (error)
6322 goto done;
6324 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6325 if (error)
6326 goto done;
6328 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6329 print_status, &st, check_cancelled, NULL);
6330 done:
6331 if (pack_fds) {
6332 const struct got_error *pack_err =
6333 got_repo_pack_fds_close(pack_fds);
6334 if (error == NULL)
6335 error = pack_err;
6338 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6339 free(cwd);
6340 return error;
6343 __dead static void
6344 usage_ref(void)
6346 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6347 "[-s reference] [name]\n", getprogname());
6348 exit(1);
6351 static const struct got_error *
6352 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6354 static const struct got_error *err = NULL;
6355 struct got_reflist_head refs;
6356 struct got_reflist_entry *re;
6358 TAILQ_INIT(&refs);
6359 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6360 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6361 repo);
6362 if (err)
6363 return err;
6365 TAILQ_FOREACH(re, &refs, entry) {
6366 char *refstr;
6367 refstr = got_ref_to_str(re->ref);
6368 if (refstr == NULL) {
6369 err = got_error_from_errno("got_ref_to_str");
6370 break;
6372 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6373 free(refstr);
6376 got_ref_list_free(&refs);
6377 return err;
6380 static const struct got_error *
6381 delete_ref_by_name(struct got_repository *repo, const char *refname)
6383 const struct got_error *err;
6384 struct got_reference *ref;
6386 err = got_ref_open(&ref, repo, refname, 0);
6387 if (err)
6388 return err;
6390 err = delete_ref(repo, ref);
6391 got_ref_close(ref);
6392 return err;
6395 static const struct got_error *
6396 add_ref(struct got_repository *repo, const char *refname, const char *target)
6398 const struct got_error *err = NULL;
6399 struct got_object_id *id = NULL;
6400 struct got_reference *ref = NULL;
6401 struct got_reflist_head refs;
6404 * Don't let the user create a reference name with a leading '-'.
6405 * While technically a valid reference name, this case is usually
6406 * an unintended typo.
6408 if (refname[0] == '-')
6409 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6411 TAILQ_INIT(&refs);
6412 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6413 if (err)
6414 goto done;
6415 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6416 &refs, repo);
6417 got_ref_list_free(&refs);
6418 if (err)
6419 goto done;
6421 err = got_ref_alloc(&ref, refname, id);
6422 if (err)
6423 goto done;
6425 err = got_ref_write(ref, repo);
6426 done:
6427 if (ref)
6428 got_ref_close(ref);
6429 free(id);
6430 return err;
6433 static const struct got_error *
6434 add_symref(struct got_repository *repo, const char *refname, const char *target)
6436 const struct got_error *err = NULL;
6437 struct got_reference *ref = NULL;
6438 struct got_reference *target_ref = NULL;
6441 * Don't let the user create a reference name with a leading '-'.
6442 * While technically a valid reference name, this case is usually
6443 * an unintended typo.
6445 if (refname[0] == '-')
6446 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6448 err = got_ref_open(&target_ref, repo, target, 0);
6449 if (err)
6450 return err;
6452 err = got_ref_alloc_symref(&ref, refname, target_ref);
6453 if (err)
6454 goto done;
6456 err = got_ref_write(ref, repo);
6457 done:
6458 if (target_ref)
6459 got_ref_close(target_ref);
6460 if (ref)
6461 got_ref_close(ref);
6462 return err;
6465 static const struct got_error *
6466 cmd_ref(int argc, char *argv[])
6468 const struct got_error *error = NULL;
6469 struct got_repository *repo = NULL;
6470 struct got_worktree *worktree = NULL;
6471 char *cwd = NULL, *repo_path = NULL;
6472 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6473 const char *obj_arg = NULL, *symref_target= NULL;
6474 char *refname = NULL;
6475 int *pack_fds = NULL;
6477 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6478 switch (ch) {
6479 case 'c':
6480 obj_arg = optarg;
6481 break;
6482 case 'd':
6483 do_delete = 1;
6484 break;
6485 case 'l':
6486 do_list = 1;
6487 break;
6488 case 'r':
6489 repo_path = realpath(optarg, NULL);
6490 if (repo_path == NULL)
6491 return got_error_from_errno2("realpath",
6492 optarg);
6493 got_path_strip_trailing_slashes(repo_path);
6494 break;
6495 case 's':
6496 symref_target = optarg;
6497 break;
6498 case 't':
6499 sort_by_time = 1;
6500 break;
6501 default:
6502 usage_ref();
6503 /* NOTREACHED */
6507 if (obj_arg && do_list)
6508 option_conflict('c', 'l');
6509 if (obj_arg && do_delete)
6510 option_conflict('c', 'd');
6511 if (obj_arg && symref_target)
6512 option_conflict('c', 's');
6513 if (symref_target && do_delete)
6514 option_conflict('s', 'd');
6515 if (symref_target && do_list)
6516 option_conflict('s', 'l');
6517 if (do_delete && do_list)
6518 option_conflict('d', 'l');
6519 if (sort_by_time && !do_list)
6520 errx(1, "-t option requires -l option");
6522 argc -= optind;
6523 argv += optind;
6525 if (do_list) {
6526 if (argc != 0 && argc != 1)
6527 usage_ref();
6528 if (argc == 1) {
6529 refname = strdup(argv[0]);
6530 if (refname == NULL) {
6531 error = got_error_from_errno("strdup");
6532 goto done;
6535 } else {
6536 if (argc != 1)
6537 usage_ref();
6538 refname = strdup(argv[0]);
6539 if (refname == NULL) {
6540 error = got_error_from_errno("strdup");
6541 goto done;
6545 if (refname)
6546 got_path_strip_trailing_slashes(refname);
6548 #ifndef PROFILE
6549 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6550 "sendfd unveil", NULL) == -1)
6551 err(1, "pledge");
6552 #endif
6553 cwd = getcwd(NULL, 0);
6554 if (cwd == NULL) {
6555 error = got_error_from_errno("getcwd");
6556 goto done;
6559 error = got_repo_pack_fds_open(&pack_fds);
6560 if (error != NULL)
6561 goto done;
6563 if (repo_path == NULL) {
6564 error = got_worktree_open(&worktree, cwd);
6565 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6566 goto done;
6567 else
6568 error = NULL;
6569 if (worktree) {
6570 repo_path =
6571 strdup(got_worktree_get_repo_path(worktree));
6572 if (repo_path == NULL)
6573 error = got_error_from_errno("strdup");
6574 if (error)
6575 goto done;
6576 } else {
6577 repo_path = strdup(cwd);
6578 if (repo_path == NULL) {
6579 error = got_error_from_errno("strdup");
6580 goto done;
6585 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6586 if (error != NULL)
6587 goto done;
6589 #ifndef PROFILE
6590 if (do_list) {
6591 /* Remove "cpath" promise. */
6592 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6593 NULL) == -1)
6594 err(1, "pledge");
6596 #endif
6598 error = apply_unveil(got_repo_get_path(repo), do_list,
6599 worktree ? got_worktree_get_root_path(worktree) : NULL);
6600 if (error)
6601 goto done;
6603 if (do_list)
6604 error = list_refs(repo, refname, sort_by_time);
6605 else if (do_delete)
6606 error = delete_ref_by_name(repo, refname);
6607 else if (symref_target)
6608 error = add_symref(repo, refname, symref_target);
6609 else {
6610 if (obj_arg == NULL)
6611 usage_ref();
6612 error = add_ref(repo, refname, obj_arg);
6614 done:
6615 free(refname);
6616 if (repo) {
6617 const struct got_error *close_err = got_repo_close(repo);
6618 if (error == NULL)
6619 error = close_err;
6621 if (worktree)
6622 got_worktree_close(worktree);
6623 if (pack_fds) {
6624 const struct got_error *pack_err =
6625 got_repo_pack_fds_close(pack_fds);
6626 if (error == NULL)
6627 error = pack_err;
6629 free(cwd);
6630 free(repo_path);
6631 return error;
6634 __dead static void
6635 usage_branch(void)
6637 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6638 "[-r repository-path] [name]\n", getprogname());
6639 exit(1);
6642 static const struct got_error *
6643 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6644 struct got_reference *ref)
6646 const struct got_error *err = NULL;
6647 const char *refname, *marker = " ";
6648 char *refstr;
6650 refname = got_ref_get_name(ref);
6651 if (worktree && strcmp(refname,
6652 got_worktree_get_head_ref_name(worktree)) == 0) {
6653 struct got_object_id *id = NULL;
6655 err = got_ref_resolve(&id, repo, ref);
6656 if (err)
6657 return err;
6658 if (got_object_id_cmp(id,
6659 got_worktree_get_base_commit_id(worktree)) == 0)
6660 marker = "* ";
6661 else
6662 marker = "~ ";
6663 free(id);
6666 if (strncmp(refname, "refs/heads/", 11) == 0)
6667 refname += 11;
6668 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6669 refname += 18;
6670 if (strncmp(refname, "refs/remotes/", 13) == 0)
6671 refname += 13;
6673 refstr = got_ref_to_str(ref);
6674 if (refstr == NULL)
6675 return got_error_from_errno("got_ref_to_str");
6677 printf("%s%s: %s\n", marker, refname, refstr);
6678 free(refstr);
6679 return NULL;
6682 static const struct got_error *
6683 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6685 const char *refname;
6687 if (worktree == NULL)
6688 return got_error(GOT_ERR_NOT_WORKTREE);
6690 refname = got_worktree_get_head_ref_name(worktree);
6692 if (strncmp(refname, "refs/heads/", 11) == 0)
6693 refname += 11;
6694 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6695 refname += 18;
6697 printf("%s\n", refname);
6699 return NULL;
6702 static const struct got_error *
6703 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6704 int sort_by_time)
6706 static const struct got_error *err = NULL;
6707 struct got_reflist_head refs;
6708 struct got_reflist_entry *re;
6709 struct got_reference *temp_ref = NULL;
6710 int rebase_in_progress, histedit_in_progress;
6712 TAILQ_INIT(&refs);
6714 if (worktree) {
6715 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6716 worktree);
6717 if (err)
6718 return err;
6720 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6721 worktree);
6722 if (err)
6723 return err;
6725 if (rebase_in_progress || histedit_in_progress) {
6726 err = got_ref_open(&temp_ref, repo,
6727 got_worktree_get_head_ref_name(worktree), 0);
6728 if (err)
6729 return err;
6730 list_branch(repo, worktree, temp_ref);
6731 got_ref_close(temp_ref);
6735 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6736 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6737 repo);
6738 if (err)
6739 return err;
6741 TAILQ_FOREACH(re, &refs, entry)
6742 list_branch(repo, worktree, re->ref);
6744 got_ref_list_free(&refs);
6746 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6747 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6748 repo);
6749 if (err)
6750 return err;
6752 TAILQ_FOREACH(re, &refs, entry)
6753 list_branch(repo, worktree, re->ref);
6755 got_ref_list_free(&refs);
6757 return NULL;
6760 static const struct got_error *
6761 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6762 const char *branch_name)
6764 const struct got_error *err = NULL;
6765 struct got_reference *ref = NULL;
6766 char *refname, *remote_refname = NULL;
6768 if (strncmp(branch_name, "refs/", 5) == 0)
6769 branch_name += 5;
6770 if (strncmp(branch_name, "heads/", 6) == 0)
6771 branch_name += 6;
6772 else if (strncmp(branch_name, "remotes/", 8) == 0)
6773 branch_name += 8;
6775 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6776 return got_error_from_errno("asprintf");
6778 if (asprintf(&remote_refname, "refs/remotes/%s",
6779 branch_name) == -1) {
6780 err = got_error_from_errno("asprintf");
6781 goto done;
6784 err = got_ref_open(&ref, repo, refname, 0);
6785 if (err) {
6786 const struct got_error *err2;
6787 if (err->code != GOT_ERR_NOT_REF)
6788 goto done;
6790 * Keep 'err' intact such that if neither branch exists
6791 * we report "refs/heads" rather than "refs/remotes" in
6792 * our error message.
6794 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6795 if (err2)
6796 goto done;
6797 err = NULL;
6800 if (worktree &&
6801 strcmp(got_worktree_get_head_ref_name(worktree),
6802 got_ref_get_name(ref)) == 0) {
6803 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6804 "will not delete this work tree's current branch");
6805 goto done;
6808 err = delete_ref(repo, ref);
6809 done:
6810 if (ref)
6811 got_ref_close(ref);
6812 free(refname);
6813 free(remote_refname);
6814 return err;
6817 static const struct got_error *
6818 add_branch(struct got_repository *repo, const char *branch_name,
6819 struct got_object_id *base_commit_id)
6821 const struct got_error *err = NULL;
6822 struct got_reference *ref = NULL;
6823 char *refname = NULL;
6826 * Don't let the user create a branch name with a leading '-'.
6827 * While technically a valid reference name, this case is usually
6828 * an unintended typo.
6830 if (branch_name[0] == '-')
6831 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6833 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6834 branch_name += 11;
6836 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6837 err = got_error_from_errno("asprintf");
6838 goto done;
6841 err = got_ref_open(&ref, repo, refname, 0);
6842 if (err == NULL) {
6843 err = got_error(GOT_ERR_BRANCH_EXISTS);
6844 goto done;
6845 } else if (err->code != GOT_ERR_NOT_REF)
6846 goto done;
6848 err = got_ref_alloc(&ref, refname, base_commit_id);
6849 if (err)
6850 goto done;
6852 err = got_ref_write(ref, repo);
6853 done:
6854 if (ref)
6855 got_ref_close(ref);
6856 free(refname);
6857 return err;
6860 static const struct got_error *
6861 cmd_branch(int argc, char *argv[])
6863 const struct got_error *error = NULL;
6864 struct got_repository *repo = NULL;
6865 struct got_worktree *worktree = NULL;
6866 char *cwd = NULL, *repo_path = NULL;
6867 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6868 const char *delref = NULL, *commit_id_arg = NULL;
6869 struct got_reference *ref = NULL;
6870 struct got_pathlist_head paths;
6871 struct got_object_id *commit_id = NULL;
6872 char *commit_id_str = NULL;
6873 int *pack_fds = NULL;
6875 TAILQ_INIT(&paths);
6877 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6878 switch (ch) {
6879 case 'c':
6880 commit_id_arg = optarg;
6881 break;
6882 case 'd':
6883 delref = optarg;
6884 break;
6885 case 'l':
6886 do_list = 1;
6887 break;
6888 case 'n':
6889 do_update = 0;
6890 break;
6891 case 'r':
6892 repo_path = realpath(optarg, NULL);
6893 if (repo_path == NULL)
6894 return got_error_from_errno2("realpath",
6895 optarg);
6896 got_path_strip_trailing_slashes(repo_path);
6897 break;
6898 case 't':
6899 sort_by_time = 1;
6900 break;
6901 default:
6902 usage_branch();
6903 /* NOTREACHED */
6907 if (do_list && delref)
6908 option_conflict('l', 'd');
6909 if (sort_by_time && !do_list)
6910 errx(1, "-t option requires -l option");
6912 argc -= optind;
6913 argv += optind;
6915 if (!do_list && !delref && argc == 0)
6916 do_show = 1;
6918 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6919 errx(1, "-c option can only be used when creating a branch");
6921 if (do_list || delref) {
6922 if (argc > 0)
6923 usage_branch();
6924 } else if (!do_show && argc != 1)
6925 usage_branch();
6927 #ifndef PROFILE
6928 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6929 "sendfd unveil", NULL) == -1)
6930 err(1, "pledge");
6931 #endif
6932 cwd = getcwd(NULL, 0);
6933 if (cwd == NULL) {
6934 error = got_error_from_errno("getcwd");
6935 goto done;
6938 error = got_repo_pack_fds_open(&pack_fds);
6939 if (error != NULL)
6940 goto done;
6942 if (repo_path == NULL) {
6943 error = got_worktree_open(&worktree, cwd);
6944 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6945 goto done;
6946 else
6947 error = NULL;
6948 if (worktree) {
6949 repo_path =
6950 strdup(got_worktree_get_repo_path(worktree));
6951 if (repo_path == NULL)
6952 error = got_error_from_errno("strdup");
6953 if (error)
6954 goto done;
6955 } else {
6956 repo_path = strdup(cwd);
6957 if (repo_path == NULL) {
6958 error = got_error_from_errno("strdup");
6959 goto done;
6964 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6965 if (error != NULL)
6966 goto done;
6968 #ifndef PROFILE
6969 if (do_list || do_show) {
6970 /* Remove "cpath" promise. */
6971 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6972 NULL) == -1)
6973 err(1, "pledge");
6975 #endif
6977 error = apply_unveil(got_repo_get_path(repo), do_list,
6978 worktree ? got_worktree_get_root_path(worktree) : NULL);
6979 if (error)
6980 goto done;
6982 if (do_show)
6983 error = show_current_branch(repo, worktree);
6984 else if (do_list)
6985 error = list_branches(repo, worktree, sort_by_time);
6986 else if (delref)
6987 error = delete_branch(repo, worktree, delref);
6988 else {
6989 struct got_reflist_head refs;
6990 TAILQ_INIT(&refs);
6991 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6992 NULL);
6993 if (error)
6994 goto done;
6995 if (commit_id_arg == NULL)
6996 commit_id_arg = worktree ?
6997 got_worktree_get_head_ref_name(worktree) :
6998 GOT_REF_HEAD;
6999 error = got_repo_match_object_id(&commit_id, NULL,
7000 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7001 got_ref_list_free(&refs);
7002 if (error)
7003 goto done;
7004 error = add_branch(repo, argv[0], commit_id);
7005 if (error)
7006 goto done;
7007 if (worktree && do_update) {
7008 struct got_update_progress_arg upa;
7009 char *branch_refname = NULL;
7011 error = got_object_id_str(&commit_id_str, commit_id);
7012 if (error)
7013 goto done;
7014 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7015 worktree);
7016 if (error)
7017 goto done;
7018 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7019 == -1) {
7020 error = got_error_from_errno("asprintf");
7021 goto done;
7023 error = got_ref_open(&ref, repo, branch_refname, 0);
7024 free(branch_refname);
7025 if (error)
7026 goto done;
7027 error = switch_head_ref(ref, commit_id, worktree,
7028 repo);
7029 if (error)
7030 goto done;
7031 error = got_worktree_set_base_commit_id(worktree, repo,
7032 commit_id);
7033 if (error)
7034 goto done;
7035 memset(&upa, 0, sizeof(upa));
7036 error = got_worktree_checkout_files(worktree, &paths,
7037 repo, update_progress, &upa, check_cancelled,
7038 NULL);
7039 if (error)
7040 goto done;
7041 if (upa.did_something) {
7042 printf("Updated to %s: %s\n",
7043 got_worktree_get_head_ref_name(worktree),
7044 commit_id_str);
7046 print_update_progress_stats(&upa);
7049 done:
7050 if (ref)
7051 got_ref_close(ref);
7052 if (repo) {
7053 const struct got_error *close_err = got_repo_close(repo);
7054 if (error == NULL)
7055 error = close_err;
7057 if (worktree)
7058 got_worktree_close(worktree);
7059 if (pack_fds) {
7060 const struct got_error *pack_err =
7061 got_repo_pack_fds_close(pack_fds);
7062 if (error == NULL)
7063 error = pack_err;
7065 free(cwd);
7066 free(repo_path);
7067 free(commit_id);
7068 free(commit_id_str);
7069 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7070 return error;
7074 __dead static void
7075 usage_tag(void)
7077 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7078 "[-r repository-path] [-s signer-id] name\n", getprogname());
7079 exit(1);
7082 #if 0
7083 static const struct got_error *
7084 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7086 const struct got_error *err = NULL;
7087 struct got_reflist_entry *re, *se, *new;
7088 struct got_object_id *re_id, *se_id;
7089 struct got_tag_object *re_tag, *se_tag;
7090 time_t re_time, se_time;
7092 STAILQ_FOREACH(re, tags, entry) {
7093 se = STAILQ_FIRST(sorted);
7094 if (se == NULL) {
7095 err = got_reflist_entry_dup(&new, re);
7096 if (err)
7097 return err;
7098 STAILQ_INSERT_HEAD(sorted, new, entry);
7099 continue;
7100 } else {
7101 err = got_ref_resolve(&re_id, repo, re->ref);
7102 if (err)
7103 break;
7104 err = got_object_open_as_tag(&re_tag, repo, re_id);
7105 free(re_id);
7106 if (err)
7107 break;
7108 re_time = got_object_tag_get_tagger_time(re_tag);
7109 got_object_tag_close(re_tag);
7112 while (se) {
7113 err = got_ref_resolve(&se_id, repo, re->ref);
7114 if (err)
7115 break;
7116 err = got_object_open_as_tag(&se_tag, repo, se_id);
7117 free(se_id);
7118 if (err)
7119 break;
7120 se_time = got_object_tag_get_tagger_time(se_tag);
7121 got_object_tag_close(se_tag);
7123 if (se_time > re_time) {
7124 err = got_reflist_entry_dup(&new, re);
7125 if (err)
7126 return err;
7127 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7128 break;
7130 se = STAILQ_NEXT(se, entry);
7131 continue;
7134 done:
7135 return err;
7137 #endif
7139 static const struct got_error *
7140 get_tag_refname(char **refname, const char *tag_name)
7142 const struct got_error *err;
7144 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7145 *refname = strdup(tag_name);
7146 if (*refname == NULL)
7147 return got_error_from_errno("strdup");
7148 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7149 err = got_error_from_errno("asprintf");
7150 *refname = NULL;
7151 return err;
7154 return NULL;
7157 static const struct got_error *
7158 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7159 const char *allowed_signers, const char *revoked_signers, int verbosity)
7161 static const struct got_error *err = NULL;
7162 struct got_reflist_head refs;
7163 struct got_reflist_entry *re;
7164 char *wanted_refname = NULL;
7165 int bad_sigs = 0;
7167 TAILQ_INIT(&refs);
7169 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7170 if (err)
7171 return err;
7173 if (tag_name) {
7174 struct got_reference *ref;
7175 err = get_tag_refname(&wanted_refname, tag_name);
7176 if (err)
7177 goto done;
7178 /* Wanted tag reference should exist. */
7179 err = got_ref_open(&ref, repo, wanted_refname, 0);
7180 if (err)
7181 goto done;
7182 got_ref_close(ref);
7185 TAILQ_FOREACH(re, &refs, entry) {
7186 const char *refname;
7187 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7188 char datebuf[26];
7189 const char *tagger, *ssh_sig = NULL;
7190 char *sig_msg = NULL;
7191 time_t tagger_time;
7192 struct got_object_id *id;
7193 struct got_tag_object *tag;
7194 struct got_commit_object *commit = NULL;
7196 refname = got_ref_get_name(re->ref);
7197 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7198 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7199 continue;
7200 refname += 10;
7201 refstr = got_ref_to_str(re->ref);
7202 if (refstr == NULL) {
7203 err = got_error_from_errno("got_ref_to_str");
7204 break;
7207 err = got_ref_resolve(&id, repo, re->ref);
7208 if (err)
7209 break;
7210 err = got_object_open_as_tag(&tag, repo, id);
7211 if (err) {
7212 if (err->code != GOT_ERR_OBJ_TYPE) {
7213 free(id);
7214 break;
7216 /* "lightweight" tag */
7217 err = got_object_open_as_commit(&commit, repo, id);
7218 if (err) {
7219 free(id);
7220 break;
7222 tagger = got_object_commit_get_committer(commit);
7223 tagger_time =
7224 got_object_commit_get_committer_time(commit);
7225 err = got_object_id_str(&id_str, id);
7226 free(id);
7227 if (err)
7228 break;
7229 } else {
7230 free(id);
7231 tagger = got_object_tag_get_tagger(tag);
7232 tagger_time = got_object_tag_get_tagger_time(tag);
7233 err = got_object_id_str(&id_str,
7234 got_object_tag_get_object_id(tag));
7235 if (err)
7236 break;
7239 if (tag && verify_tags) {
7240 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7241 got_object_tag_get_message(tag));
7242 if (ssh_sig && allowed_signers == NULL) {
7243 err = got_error_msg(
7244 GOT_ERR_VERIFY_TAG_SIGNATURE,
7245 "SSH signature verification requires "
7246 "setting allowed_signers in "
7247 "got.conf(5)");
7248 break;
7252 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7253 free(refstr);
7254 printf("from: %s\n", tagger);
7255 datestr = get_datestr(&tagger_time, datebuf);
7256 if (datestr)
7257 printf("date: %s UTC\n", datestr);
7258 if (commit)
7259 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7260 else {
7261 switch (got_object_tag_get_object_type(tag)) {
7262 case GOT_OBJ_TYPE_BLOB:
7263 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7264 id_str);
7265 break;
7266 case GOT_OBJ_TYPE_TREE:
7267 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7268 id_str);
7269 break;
7270 case GOT_OBJ_TYPE_COMMIT:
7271 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7272 id_str);
7273 break;
7274 case GOT_OBJ_TYPE_TAG:
7275 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7276 id_str);
7277 break;
7278 default:
7279 break;
7282 free(id_str);
7284 if (ssh_sig) {
7285 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7286 allowed_signers, revoked_signers, verbosity);
7287 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7288 bad_sigs = 1;
7289 else if (err)
7290 break;
7291 printf("signature: %s", sig_msg);
7292 free(sig_msg);
7293 sig_msg = NULL;
7296 if (commit) {
7297 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7298 if (err)
7299 break;
7300 got_object_commit_close(commit);
7301 } else {
7302 tagmsg0 = strdup(got_object_tag_get_message(tag));
7303 got_object_tag_close(tag);
7304 if (tagmsg0 == NULL) {
7305 err = got_error_from_errno("strdup");
7306 break;
7310 tagmsg = tagmsg0;
7311 do {
7312 line = strsep(&tagmsg, "\n");
7313 if (line)
7314 printf(" %s\n", line);
7315 } while (line);
7316 free(tagmsg0);
7318 done:
7319 got_ref_list_free(&refs);
7320 free(wanted_refname);
7322 if (err == NULL && bad_sigs)
7323 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7324 return err;
7327 static const struct got_error *
7328 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7329 const char *tag_name, const char *repo_path)
7331 const struct got_error *err = NULL;
7332 char *template = NULL, *initial_content = NULL;
7333 char *editor = NULL;
7334 int initial_content_len;
7335 int fd = -1;
7337 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7338 err = got_error_from_errno("asprintf");
7339 goto done;
7342 initial_content_len = asprintf(&initial_content,
7343 "\n# tagging commit %s as %s\n",
7344 commit_id_str, tag_name);
7345 if (initial_content_len == -1) {
7346 err = got_error_from_errno("asprintf");
7347 goto done;
7350 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7351 if (err)
7352 goto done;
7354 if (write(fd, initial_content, initial_content_len) == -1) {
7355 err = got_error_from_errno2("write", *tagmsg_path);
7356 goto done;
7359 err = get_editor(&editor);
7360 if (err)
7361 goto done;
7362 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7363 initial_content_len, 1);
7364 done:
7365 free(initial_content);
7366 free(template);
7367 free(editor);
7369 if (fd != -1 && close(fd) == -1 && err == NULL)
7370 err = got_error_from_errno2("close", *tagmsg_path);
7372 if (err) {
7373 free(*tagmsg);
7374 *tagmsg = NULL;
7376 return err;
7379 static const struct got_error *
7380 add_tag(struct got_repository *repo, const char *tagger,
7381 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7382 const char *signer_id, int verbosity)
7384 const struct got_error *err = NULL;
7385 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7386 char *label = NULL, *commit_id_str = NULL;
7387 struct got_reference *ref = NULL;
7388 char *refname = NULL, *tagmsg = NULL;
7389 char *tagmsg_path = NULL, *tag_id_str = NULL;
7390 int preserve_tagmsg = 0;
7391 struct got_reflist_head refs;
7393 TAILQ_INIT(&refs);
7396 * Don't let the user create a tag name with a leading '-'.
7397 * While technically a valid reference name, this case is usually
7398 * an unintended typo.
7400 if (tag_name[0] == '-')
7401 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7403 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7404 if (err)
7405 goto done;
7407 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7408 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7409 if (err)
7410 goto done;
7412 err = got_object_id_str(&commit_id_str, commit_id);
7413 if (err)
7414 goto done;
7416 err = get_tag_refname(&refname, tag_name);
7417 if (err)
7418 goto done;
7419 if (strncmp("refs/tags/", tag_name, 10) == 0)
7420 tag_name += 10;
7422 err = got_ref_open(&ref, repo, refname, 0);
7423 if (err == NULL) {
7424 err = got_error(GOT_ERR_TAG_EXISTS);
7425 goto done;
7426 } else if (err->code != GOT_ERR_NOT_REF)
7427 goto done;
7429 if (tagmsg_arg == NULL) {
7430 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7431 tag_name, got_repo_get_path(repo));
7432 if (err) {
7433 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7434 tagmsg_path != NULL)
7435 preserve_tagmsg = 1;
7436 goto done;
7438 /* Editor is done; we can now apply unveil(2) */
7439 err = got_sigs_apply_unveil();
7440 if (err)
7441 goto done;
7442 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7443 if (err)
7444 goto done;
7447 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7448 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7449 verbosity);
7450 if (err) {
7451 if (tagmsg_path)
7452 preserve_tagmsg = 1;
7453 goto done;
7456 err = got_ref_alloc(&ref, refname, tag_id);
7457 if (err) {
7458 if (tagmsg_path)
7459 preserve_tagmsg = 1;
7460 goto done;
7463 err = got_ref_write(ref, repo);
7464 if (err) {
7465 if (tagmsg_path)
7466 preserve_tagmsg = 1;
7467 goto done;
7470 err = got_object_id_str(&tag_id_str, tag_id);
7471 if (err) {
7472 if (tagmsg_path)
7473 preserve_tagmsg = 1;
7474 goto done;
7476 printf("Created tag %s\n", tag_id_str);
7477 done:
7478 if (preserve_tagmsg) {
7479 fprintf(stderr, "%s: tag message preserved in %s\n",
7480 getprogname(), tagmsg_path);
7481 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7482 err = got_error_from_errno2("unlink", tagmsg_path);
7483 free(tag_id_str);
7484 if (ref)
7485 got_ref_close(ref);
7486 free(commit_id);
7487 free(commit_id_str);
7488 free(refname);
7489 free(tagmsg);
7490 free(tagmsg_path);
7491 got_ref_list_free(&refs);
7492 return err;
7495 static const struct got_error *
7496 cmd_tag(int argc, char *argv[])
7498 const struct got_error *error = NULL;
7499 struct got_repository *repo = NULL;
7500 struct got_worktree *worktree = NULL;
7501 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7502 char *gitconfig_path = NULL, *tagger = NULL;
7503 char *allowed_signers = NULL, *revoked_signers = NULL;
7504 const char *signer_id = NULL;
7505 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7506 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7507 int *pack_fds = NULL;
7509 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7510 switch (ch) {
7511 case 'c':
7512 commit_id_arg = optarg;
7513 break;
7514 case 'l':
7515 do_list = 1;
7516 break;
7517 case 'm':
7518 tagmsg = optarg;
7519 break;
7520 case 'r':
7521 repo_path = realpath(optarg, NULL);
7522 if (repo_path == NULL) {
7523 error = got_error_from_errno2("realpath",
7524 optarg);
7525 goto done;
7527 got_path_strip_trailing_slashes(repo_path);
7528 break;
7529 case 's':
7530 signer_id = optarg;
7531 break;
7532 case 'V':
7533 verify_tags = 1;
7534 break;
7535 case 'v':
7536 if (verbosity < 0)
7537 verbosity = 0;
7538 else if (verbosity < 3)
7539 verbosity++;
7540 break;
7541 default:
7542 usage_tag();
7543 /* NOTREACHED */
7547 argc -= optind;
7548 argv += optind;
7550 if (do_list || verify_tags) {
7551 if (commit_id_arg != NULL)
7552 errx(1,
7553 "-c option can only be used when creating a tag");
7554 if (tagmsg) {
7555 if (do_list)
7556 option_conflict('l', 'm');
7557 else
7558 option_conflict('V', 'm');
7560 if (signer_id) {
7561 if (do_list)
7562 option_conflict('l', 's');
7563 else
7564 option_conflict('V', 's');
7566 if (argc > 1)
7567 usage_tag();
7568 } else if (argc != 1)
7569 usage_tag();
7571 if (argc == 1)
7572 tag_name = argv[0];
7574 #ifndef PROFILE
7575 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7576 "sendfd unveil", NULL) == -1)
7577 err(1, "pledge");
7578 #endif
7579 cwd = getcwd(NULL, 0);
7580 if (cwd == NULL) {
7581 error = got_error_from_errno("getcwd");
7582 goto done;
7585 error = got_repo_pack_fds_open(&pack_fds);
7586 if (error != NULL)
7587 goto done;
7589 if (repo_path == NULL) {
7590 error = got_worktree_open(&worktree, cwd);
7591 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7592 goto done;
7593 else
7594 error = NULL;
7595 if (worktree) {
7596 repo_path =
7597 strdup(got_worktree_get_repo_path(worktree));
7598 if (repo_path == NULL)
7599 error = got_error_from_errno("strdup");
7600 if (error)
7601 goto done;
7602 } else {
7603 repo_path = strdup(cwd);
7604 if (repo_path == NULL) {
7605 error = got_error_from_errno("strdup");
7606 goto done;
7611 if (do_list || verify_tags) {
7612 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7613 if (error != NULL)
7614 goto done;
7615 error = get_allowed_signers(&allowed_signers, repo, worktree);
7616 if (error)
7617 goto done;
7618 error = get_revoked_signers(&revoked_signers, repo, worktree);
7619 if (error)
7620 goto done;
7621 if (worktree) {
7622 /* Release work tree lock. */
7623 got_worktree_close(worktree);
7624 worktree = NULL;
7628 * Remove "cpath" promise unless needed for signature tmpfile
7629 * creation.
7631 if (verify_tags)
7632 got_sigs_apply_unveil();
7633 else {
7634 #ifndef PROFILE
7635 if (pledge("stdio rpath wpath flock proc exec sendfd "
7636 "unveil", NULL) == -1)
7637 err(1, "pledge");
7638 #endif
7640 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7641 if (error)
7642 goto done;
7643 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7644 revoked_signers, verbosity);
7645 } else {
7646 error = get_gitconfig_path(&gitconfig_path);
7647 if (error)
7648 goto done;
7649 error = got_repo_open(&repo, repo_path, gitconfig_path,
7650 pack_fds);
7651 if (error != NULL)
7652 goto done;
7654 error = get_author(&tagger, repo, worktree);
7655 if (error)
7656 goto done;
7657 if (signer_id == NULL)
7658 signer_id = get_signer_id(repo, worktree);
7660 if (tagmsg) {
7661 if (signer_id) {
7662 error = got_sigs_apply_unveil();
7663 if (error)
7664 goto done;
7666 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7667 if (error)
7668 goto done;
7671 if (commit_id_arg == NULL) {
7672 struct got_reference *head_ref;
7673 struct got_object_id *commit_id;
7674 error = got_ref_open(&head_ref, repo,
7675 worktree ? got_worktree_get_head_ref_name(worktree)
7676 : GOT_REF_HEAD, 0);
7677 if (error)
7678 goto done;
7679 error = got_ref_resolve(&commit_id, repo, head_ref);
7680 got_ref_close(head_ref);
7681 if (error)
7682 goto done;
7683 error = got_object_id_str(&commit_id_str, commit_id);
7684 free(commit_id);
7685 if (error)
7686 goto done;
7689 if (worktree) {
7690 /* Release work tree lock. */
7691 got_worktree_close(worktree);
7692 worktree = NULL;
7695 error = add_tag(repo, tagger, tag_name,
7696 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7697 signer_id, verbosity);
7699 done:
7700 if (repo) {
7701 const struct got_error *close_err = got_repo_close(repo);
7702 if (error == NULL)
7703 error = close_err;
7705 if (worktree)
7706 got_worktree_close(worktree);
7707 if (pack_fds) {
7708 const struct got_error *pack_err =
7709 got_repo_pack_fds_close(pack_fds);
7710 if (error == NULL)
7711 error = pack_err;
7713 free(cwd);
7714 free(repo_path);
7715 free(gitconfig_path);
7716 free(commit_id_str);
7717 free(tagger);
7718 free(allowed_signers);
7719 free(revoked_signers);
7720 return error;
7723 __dead static void
7724 usage_add(void)
7726 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7727 exit(1);
7730 static const struct got_error *
7731 add_progress(void *arg, unsigned char status, const char *path)
7733 while (path[0] == '/')
7734 path++;
7735 printf("%c %s\n", status, path);
7736 return NULL;
7739 static const struct got_error *
7740 cmd_add(int argc, char *argv[])
7742 const struct got_error *error = NULL;
7743 struct got_repository *repo = NULL;
7744 struct got_worktree *worktree = NULL;
7745 char *cwd = NULL;
7746 struct got_pathlist_head paths;
7747 struct got_pathlist_entry *pe;
7748 int ch, can_recurse = 0, no_ignores = 0;
7749 int *pack_fds = NULL;
7751 TAILQ_INIT(&paths);
7753 while ((ch = getopt(argc, argv, "IR")) != -1) {
7754 switch (ch) {
7755 case 'I':
7756 no_ignores = 1;
7757 break;
7758 case 'R':
7759 can_recurse = 1;
7760 break;
7761 default:
7762 usage_add();
7763 /* NOTREACHED */
7767 argc -= optind;
7768 argv += optind;
7770 #ifndef PROFILE
7771 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7772 NULL) == -1)
7773 err(1, "pledge");
7774 #endif
7775 if (argc < 1)
7776 usage_add();
7778 cwd = getcwd(NULL, 0);
7779 if (cwd == NULL) {
7780 error = got_error_from_errno("getcwd");
7781 goto done;
7784 error = got_repo_pack_fds_open(&pack_fds);
7785 if (error != NULL)
7786 goto done;
7788 error = got_worktree_open(&worktree, cwd);
7789 if (error) {
7790 if (error->code == GOT_ERR_NOT_WORKTREE)
7791 error = wrap_not_worktree_error(error, "add", cwd);
7792 goto done;
7795 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7796 NULL, pack_fds);
7797 if (error != NULL)
7798 goto done;
7800 error = apply_unveil(got_repo_get_path(repo), 1,
7801 got_worktree_get_root_path(worktree));
7802 if (error)
7803 goto done;
7805 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7806 if (error)
7807 goto done;
7809 if (!can_recurse) {
7810 char *ondisk_path;
7811 struct stat sb;
7812 TAILQ_FOREACH(pe, &paths, entry) {
7813 if (asprintf(&ondisk_path, "%s/%s",
7814 got_worktree_get_root_path(worktree),
7815 pe->path) == -1) {
7816 error = got_error_from_errno("asprintf");
7817 goto done;
7819 if (lstat(ondisk_path, &sb) == -1) {
7820 if (errno == ENOENT) {
7821 free(ondisk_path);
7822 continue;
7824 error = got_error_from_errno2("lstat",
7825 ondisk_path);
7826 free(ondisk_path);
7827 goto done;
7829 free(ondisk_path);
7830 if (S_ISDIR(sb.st_mode)) {
7831 error = got_error_msg(GOT_ERR_BAD_PATH,
7832 "adding directories requires -R option");
7833 goto done;
7838 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7839 NULL, repo, no_ignores);
7840 done:
7841 if (repo) {
7842 const struct got_error *close_err = got_repo_close(repo);
7843 if (error == NULL)
7844 error = close_err;
7846 if (worktree)
7847 got_worktree_close(worktree);
7848 if (pack_fds) {
7849 const struct got_error *pack_err =
7850 got_repo_pack_fds_close(pack_fds);
7851 if (error == NULL)
7852 error = pack_err;
7854 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7855 free(cwd);
7856 return error;
7859 __dead static void
7860 usage_remove(void)
7862 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7863 getprogname());
7864 exit(1);
7867 static const struct got_error *
7868 print_remove_status(void *arg, unsigned char status,
7869 unsigned char staged_status, const char *path)
7871 while (path[0] == '/')
7872 path++;
7873 if (status == GOT_STATUS_NONEXISTENT)
7874 return NULL;
7875 if (status == staged_status && (status == GOT_STATUS_DELETE))
7876 status = GOT_STATUS_NO_CHANGE;
7877 printf("%c%c %s\n", status, staged_status, path);
7878 return NULL;
7881 static const struct got_error *
7882 cmd_remove(int argc, char *argv[])
7884 const struct got_error *error = NULL;
7885 struct got_worktree *worktree = NULL;
7886 struct got_repository *repo = NULL;
7887 const char *status_codes = NULL;
7888 char *cwd = NULL;
7889 struct got_pathlist_head paths;
7890 struct got_pathlist_entry *pe;
7891 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7892 int ignore_missing_paths = 0;
7893 int *pack_fds = NULL;
7895 TAILQ_INIT(&paths);
7897 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7898 switch (ch) {
7899 case 'f':
7900 delete_local_mods = 1;
7901 ignore_missing_paths = 1;
7902 break;
7903 case 'k':
7904 keep_on_disk = 1;
7905 break;
7906 case 'R':
7907 can_recurse = 1;
7908 break;
7909 case 's':
7910 for (i = 0; i < strlen(optarg); i++) {
7911 switch (optarg[i]) {
7912 case GOT_STATUS_MODIFY:
7913 delete_local_mods = 1;
7914 break;
7915 case GOT_STATUS_MISSING:
7916 ignore_missing_paths = 1;
7917 break;
7918 default:
7919 errx(1, "invalid status code '%c'",
7920 optarg[i]);
7923 status_codes = optarg;
7924 break;
7925 default:
7926 usage_remove();
7927 /* NOTREACHED */
7931 argc -= optind;
7932 argv += optind;
7934 #ifndef PROFILE
7935 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7936 NULL) == -1)
7937 err(1, "pledge");
7938 #endif
7939 if (argc < 1)
7940 usage_remove();
7942 cwd = getcwd(NULL, 0);
7943 if (cwd == NULL) {
7944 error = got_error_from_errno("getcwd");
7945 goto done;
7948 error = got_repo_pack_fds_open(&pack_fds);
7949 if (error != NULL)
7950 goto done;
7952 error = got_worktree_open(&worktree, cwd);
7953 if (error) {
7954 if (error->code == GOT_ERR_NOT_WORKTREE)
7955 error = wrap_not_worktree_error(error, "remove", cwd);
7956 goto done;
7959 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7960 NULL, pack_fds);
7961 if (error)
7962 goto done;
7964 error = apply_unveil(got_repo_get_path(repo), 1,
7965 got_worktree_get_root_path(worktree));
7966 if (error)
7967 goto done;
7969 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7970 if (error)
7971 goto done;
7973 if (!can_recurse) {
7974 char *ondisk_path;
7975 struct stat sb;
7976 TAILQ_FOREACH(pe, &paths, entry) {
7977 if (asprintf(&ondisk_path, "%s/%s",
7978 got_worktree_get_root_path(worktree),
7979 pe->path) == -1) {
7980 error = got_error_from_errno("asprintf");
7981 goto done;
7983 if (lstat(ondisk_path, &sb) == -1) {
7984 if (errno == ENOENT) {
7985 free(ondisk_path);
7986 continue;
7988 error = got_error_from_errno2("lstat",
7989 ondisk_path);
7990 free(ondisk_path);
7991 goto done;
7993 free(ondisk_path);
7994 if (S_ISDIR(sb.st_mode)) {
7995 error = got_error_msg(GOT_ERR_BAD_PATH,
7996 "removing directories requires -R option");
7997 goto done;
8002 error = got_worktree_schedule_delete(worktree, &paths,
8003 delete_local_mods, status_codes, print_remove_status, NULL,
8004 repo, keep_on_disk, ignore_missing_paths);
8005 done:
8006 if (repo) {
8007 const struct got_error *close_err = got_repo_close(repo);
8008 if (error == NULL)
8009 error = close_err;
8011 if (worktree)
8012 got_worktree_close(worktree);
8013 if (pack_fds) {
8014 const struct got_error *pack_err =
8015 got_repo_pack_fds_close(pack_fds);
8016 if (error == NULL)
8017 error = pack_err;
8019 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8020 free(cwd);
8021 return error;
8024 __dead static void
8025 usage_patch(void)
8027 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8028 "[patchfile]\n", getprogname());
8029 exit(1);
8032 static const struct got_error *
8033 patch_from_stdin(int *patchfd)
8035 const struct got_error *err = NULL;
8036 ssize_t r;
8037 char buf[BUFSIZ];
8038 sig_t sighup, sigint, sigquit;
8040 *patchfd = got_opentempfd();
8041 if (*patchfd == -1)
8042 return got_error_from_errno("got_opentempfd");
8044 sighup = signal(SIGHUP, SIG_DFL);
8045 sigint = signal(SIGINT, SIG_DFL);
8046 sigquit = signal(SIGQUIT, SIG_DFL);
8048 for (;;) {
8049 r = read(0, buf, sizeof(buf));
8050 if (r == -1) {
8051 err = got_error_from_errno("read");
8052 break;
8054 if (r == 0)
8055 break;
8056 if (write(*patchfd, buf, r) == -1) {
8057 err = got_error_from_errno("write");
8058 break;
8062 signal(SIGHUP, sighup);
8063 signal(SIGINT, sigint);
8064 signal(SIGQUIT, sigquit);
8066 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8067 err = got_error_from_errno("lseek");
8069 if (err != NULL) {
8070 close(*patchfd);
8071 *patchfd = -1;
8074 return err;
8077 static const struct got_error *
8078 patch_progress(void *arg, const char *old, const char *new,
8079 unsigned char status, const struct got_error *error, int old_from,
8080 int old_lines, int new_from, int new_lines, int offset,
8081 int ws_mangled, const struct got_error *hunk_err)
8083 const char *path = new == NULL ? old : new;
8085 while (*path == '/')
8086 path++;
8088 if (status != 0)
8089 printf("%c %s\n", status, path);
8091 if (error != NULL)
8092 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8094 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8095 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8096 old_lines, new_from, new_lines);
8097 if (hunk_err != NULL)
8098 printf("%s\n", hunk_err->msg);
8099 else if (offset != 0)
8100 printf("applied with offset %d\n", offset);
8101 else
8102 printf("hunk contains mangled whitespace\n");
8105 return NULL;
8108 static const struct got_error *
8109 cmd_patch(int argc, char *argv[])
8111 const struct got_error *error = NULL, *close_error = NULL;
8112 struct got_worktree *worktree = NULL;
8113 struct got_repository *repo = NULL;
8114 struct got_reflist_head refs;
8115 struct got_object_id *commit_id = NULL;
8116 const char *commit_id_str = NULL;
8117 struct stat sb;
8118 const char *errstr;
8119 char *cwd = NULL;
8120 int ch, nop = 0, strip = -1, reverse = 0;
8121 int patchfd;
8122 int *pack_fds = NULL;
8124 TAILQ_INIT(&refs);
8126 #ifndef PROFILE
8127 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8128 "unveil", NULL) == -1)
8129 err(1, "pledge");
8130 #endif
8132 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8133 switch (ch) {
8134 case 'c':
8135 commit_id_str = optarg;
8136 break;
8137 case 'n':
8138 nop = 1;
8139 break;
8140 case 'p':
8141 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8142 if (errstr != NULL)
8143 errx(1, "pathname strip count is %s: %s",
8144 errstr, optarg);
8145 break;
8146 case 'R':
8147 reverse = 1;
8148 break;
8149 default:
8150 usage_patch();
8151 /* NOTREACHED */
8155 argc -= optind;
8156 argv += optind;
8158 if (argc == 0) {
8159 error = patch_from_stdin(&patchfd);
8160 if (error)
8161 return error;
8162 } else if (argc == 1) {
8163 patchfd = open(argv[0], O_RDONLY);
8164 if (patchfd == -1) {
8165 error = got_error_from_errno2("open", argv[0]);
8166 return error;
8168 if (fstat(patchfd, &sb) == -1) {
8169 error = got_error_from_errno2("fstat", argv[0]);
8170 goto done;
8172 if (!S_ISREG(sb.st_mode)) {
8173 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8174 goto done;
8176 } else
8177 usage_patch();
8179 if ((cwd = getcwd(NULL, 0)) == NULL) {
8180 error = got_error_from_errno("getcwd");
8181 goto done;
8184 error = got_repo_pack_fds_open(&pack_fds);
8185 if (error != NULL)
8186 goto done;
8188 error = got_worktree_open(&worktree, cwd);
8189 if (error != NULL)
8190 goto done;
8192 const char *repo_path = got_worktree_get_repo_path(worktree);
8193 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8194 if (error != NULL)
8195 goto done;
8197 error = apply_unveil(got_repo_get_path(repo), 0,
8198 got_worktree_get_root_path(worktree));
8199 if (error != NULL)
8200 goto done;
8202 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8203 if (error)
8204 goto done;
8206 if (commit_id_str != NULL) {
8207 error = got_repo_match_object_id(&commit_id, NULL,
8208 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8209 if (error)
8210 goto done;
8213 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8214 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8216 done:
8217 got_ref_list_free(&refs);
8218 free(commit_id);
8219 if (repo) {
8220 close_error = got_repo_close(repo);
8221 if (error == NULL)
8222 error = close_error;
8224 if (worktree != NULL) {
8225 close_error = got_worktree_close(worktree);
8226 if (error == NULL)
8227 error = close_error;
8229 if (pack_fds) {
8230 const struct got_error *pack_err =
8231 got_repo_pack_fds_close(pack_fds);
8232 if (error == NULL)
8233 error = pack_err;
8235 free(cwd);
8236 return error;
8239 __dead static void
8240 usage_revert(void)
8242 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8243 getprogname());
8244 exit(1);
8247 static const struct got_error *
8248 revert_progress(void *arg, unsigned char status, const char *path)
8250 if (status == GOT_STATUS_UNVERSIONED)
8251 return NULL;
8253 while (path[0] == '/')
8254 path++;
8255 printf("%c %s\n", status, path);
8256 return NULL;
8259 struct choose_patch_arg {
8260 FILE *patch_script_file;
8261 const char *action;
8264 static const struct got_error *
8265 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8266 int nchanges, const char *action)
8268 const struct got_error *err;
8269 char *line = NULL;
8270 size_t linesize = 0;
8271 ssize_t linelen;
8273 switch (status) {
8274 case GOT_STATUS_ADD:
8275 printf("A %s\n%s this addition? [y/n] ", path, action);
8276 break;
8277 case GOT_STATUS_DELETE:
8278 printf("D %s\n%s this deletion? [y/n] ", path, action);
8279 break;
8280 case GOT_STATUS_MODIFY:
8281 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8282 return got_error_from_errno("fseek");
8283 printf(GOT_COMMIT_SEP_STR);
8284 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8285 printf("%s", line);
8286 if (linelen == -1 && ferror(patch_file)) {
8287 err = got_error_from_errno("getline");
8288 free(line);
8289 return err;
8291 free(line);
8292 printf(GOT_COMMIT_SEP_STR);
8293 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8294 path, n, nchanges, action);
8295 break;
8296 default:
8297 return got_error_path(path, GOT_ERR_FILE_STATUS);
8300 fflush(stdout);
8301 return NULL;
8304 static const struct got_error *
8305 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8306 FILE *patch_file, int n, int nchanges)
8308 const struct got_error *err = NULL;
8309 char *line = NULL;
8310 size_t linesize = 0;
8311 ssize_t linelen;
8312 int resp = ' ';
8313 struct choose_patch_arg *a = arg;
8315 *choice = GOT_PATCH_CHOICE_NONE;
8317 if (a->patch_script_file) {
8318 char *nl;
8319 err = show_change(status, path, patch_file, n, nchanges,
8320 a->action);
8321 if (err)
8322 return err;
8323 linelen = getline(&line, &linesize, a->patch_script_file);
8324 if (linelen == -1) {
8325 if (ferror(a->patch_script_file))
8326 return got_error_from_errno("getline");
8327 return NULL;
8329 nl = strchr(line, '\n');
8330 if (nl)
8331 *nl = '\0';
8332 if (strcmp(line, "y") == 0) {
8333 *choice = GOT_PATCH_CHOICE_YES;
8334 printf("y\n");
8335 } else if (strcmp(line, "n") == 0) {
8336 *choice = GOT_PATCH_CHOICE_NO;
8337 printf("n\n");
8338 } else if (strcmp(line, "q") == 0 &&
8339 status == GOT_STATUS_MODIFY) {
8340 *choice = GOT_PATCH_CHOICE_QUIT;
8341 printf("q\n");
8342 } else
8343 printf("invalid response '%s'\n", line);
8344 free(line);
8345 return NULL;
8348 while (resp != 'y' && resp != 'n' && resp != 'q') {
8349 err = show_change(status, path, patch_file, n, nchanges,
8350 a->action);
8351 if (err)
8352 return err;
8353 resp = getchar();
8354 if (resp == '\n')
8355 resp = getchar();
8356 if (status == GOT_STATUS_MODIFY) {
8357 if (resp != 'y' && resp != 'n' && resp != 'q') {
8358 printf("invalid response '%c'\n", resp);
8359 resp = ' ';
8361 } else if (resp != 'y' && resp != 'n') {
8362 printf("invalid response '%c'\n", resp);
8363 resp = ' ';
8367 if (resp == 'y')
8368 *choice = GOT_PATCH_CHOICE_YES;
8369 else if (resp == 'n')
8370 *choice = GOT_PATCH_CHOICE_NO;
8371 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8372 *choice = GOT_PATCH_CHOICE_QUIT;
8374 return NULL;
8377 struct wt_commitable_path_arg {
8378 struct got_pathlist_head *commit_paths;
8379 int *has_changes;
8383 * Shortcut work tree status callback to determine if the set of paths scanned
8384 * has at least one versioned path that is being modified and, if not NULL, is
8385 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8386 * soon as a path is passed with a status that satisfies this criteria.
8388 static const struct got_error *
8389 worktree_has_commitable_path(void *arg, unsigned char status,
8390 unsigned char staged_status, const char *path,
8391 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8392 struct got_object_id *commit_id, int dirfd, const char *de_name)
8394 struct wt_commitable_path_arg *a = arg;
8396 if (status == staged_status && (status == GOT_STATUS_DELETE))
8397 status = GOT_STATUS_NO_CHANGE;
8399 if (!(status == GOT_STATUS_NO_CHANGE ||
8400 status == GOT_STATUS_UNVERSIONED) ||
8401 staged_status != GOT_STATUS_NO_CHANGE) {
8402 if (a->commit_paths != NULL) {
8403 struct got_pathlist_entry *pe;
8405 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8406 if (strncmp(path, pe->path,
8407 pe->path_len) == 0) {
8408 *a->has_changes = 1;
8409 break;
8412 } else
8413 *a->has_changes = 1;
8415 if (*a->has_changes)
8416 return got_error(GOT_ERR_FILE_MODIFIED);
8419 return NULL;
8423 * Check that the changeset of the commit identified by id is
8424 * comprised of at least one modified path that is being committed.
8426 static const struct got_error *
8427 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8428 struct got_object_id *id, struct got_worktree *worktree,
8429 struct got_repository *repo)
8431 const struct got_error *err;
8432 struct got_pathlist_head paths;
8433 struct got_commit_object *commit = NULL, *pcommit = NULL;
8434 struct got_tree_object *tree = NULL, *ptree = NULL;
8435 struct got_object_qid *pid;
8437 TAILQ_INIT(&paths);
8439 err = got_object_open_as_commit(&commit, repo, id);
8440 if (err)
8441 goto done;
8443 err = got_object_open_as_tree(&tree, repo,
8444 got_object_commit_get_tree_id(commit));
8445 if (err)
8446 goto done;
8448 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8449 if (pid != NULL) {
8450 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8451 if (err)
8452 goto done;
8454 err = got_object_open_as_tree(&ptree, repo,
8455 got_object_commit_get_tree_id(pcommit));
8456 if (err)
8457 goto done;
8460 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8461 got_diff_tree_collect_changed_paths, &paths, 0);
8462 if (err)
8463 goto done;
8465 err = got_worktree_status(worktree, &paths, repo, 0,
8466 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8467 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8469 * At least one changed path in the referenced commit is
8470 * modified in the work tree, that's all we need to know!
8472 err = NULL;
8475 done:
8476 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8477 if (commit)
8478 got_object_commit_close(commit);
8479 if (pcommit)
8480 got_object_commit_close(pcommit);
8481 if (tree)
8482 got_object_tree_close(tree);
8483 if (ptree)
8484 got_object_tree_close(ptree);
8485 return err;
8489 * Remove any "logmsg" reference comprised entirely of paths that have
8490 * been reverted in this work tree. If any path in the logmsg ref changeset
8491 * remains in a changed state in the worktree, do not remove the reference.
8493 static const struct got_error *
8494 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8496 const struct got_error *err;
8497 struct got_reflist_head refs;
8498 struct got_reflist_entry *re;
8499 struct got_commit_object *commit = NULL;
8500 struct got_object_id *commit_id = NULL;
8501 struct wt_commitable_path_arg wcpa;
8502 char *uuidstr = NULL;
8504 TAILQ_INIT(&refs);
8506 err = got_worktree_get_uuid(&uuidstr, worktree);
8507 if (err)
8508 goto done;
8510 err = got_ref_list(&refs, repo, "refs/got/worktree",
8511 got_ref_cmp_by_name, repo);
8512 if (err)
8513 goto done;
8515 TAILQ_FOREACH(re, &refs, entry) {
8516 const char *refname;
8517 int has_changes = 0;
8519 refname = got_ref_get_name(re->ref);
8521 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8522 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8523 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8524 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8525 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8526 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8527 else
8528 continue;
8530 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8531 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8532 else
8533 continue;
8535 err = got_repo_match_object_id(&commit_id, NULL, refname,
8536 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8537 if (err)
8538 goto done;
8540 err = got_object_open_as_commit(&commit, repo, commit_id);
8541 if (err)
8542 goto done;
8544 wcpa.commit_paths = NULL;
8545 wcpa.has_changes = &has_changes;
8547 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8548 worktree, repo);
8549 if (err)
8550 goto done;
8552 if (!has_changes) {
8553 err = got_ref_delete(re->ref, repo);
8554 if (err)
8555 goto done;
8558 got_object_commit_close(commit);
8559 commit = NULL;
8560 free(commit_id);
8561 commit_id = NULL;
8564 done:
8565 free(uuidstr);
8566 free(commit_id);
8567 got_ref_list_free(&refs);
8568 if (commit)
8569 got_object_commit_close(commit);
8570 return err;
8573 static const struct got_error *
8574 cmd_revert(int argc, char *argv[])
8576 const struct got_error *error = NULL;
8577 struct got_worktree *worktree = NULL;
8578 struct got_repository *repo = NULL;
8579 char *cwd = NULL, *path = NULL;
8580 struct got_pathlist_head paths;
8581 struct got_pathlist_entry *pe;
8582 int ch, can_recurse = 0, pflag = 0;
8583 FILE *patch_script_file = NULL;
8584 const char *patch_script_path = NULL;
8585 struct choose_patch_arg cpa;
8586 int *pack_fds = NULL;
8588 TAILQ_INIT(&paths);
8590 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8591 switch (ch) {
8592 case 'F':
8593 patch_script_path = optarg;
8594 break;
8595 case 'p':
8596 pflag = 1;
8597 break;
8598 case 'R':
8599 can_recurse = 1;
8600 break;
8601 default:
8602 usage_revert();
8603 /* NOTREACHED */
8607 argc -= optind;
8608 argv += optind;
8610 #ifndef PROFILE
8611 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8612 "unveil", NULL) == -1)
8613 err(1, "pledge");
8614 #endif
8615 if (argc < 1)
8616 usage_revert();
8617 if (patch_script_path && !pflag)
8618 errx(1, "-F option can only be used together with -p option");
8620 cwd = getcwd(NULL, 0);
8621 if (cwd == NULL) {
8622 error = got_error_from_errno("getcwd");
8623 goto done;
8626 error = got_repo_pack_fds_open(&pack_fds);
8627 if (error != NULL)
8628 goto done;
8630 error = got_worktree_open(&worktree, cwd);
8631 if (error) {
8632 if (error->code == GOT_ERR_NOT_WORKTREE)
8633 error = wrap_not_worktree_error(error, "revert", cwd);
8634 goto done;
8637 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8638 NULL, pack_fds);
8639 if (error != NULL)
8640 goto done;
8642 if (patch_script_path) {
8643 patch_script_file = fopen(patch_script_path, "re");
8644 if (patch_script_file == NULL) {
8645 error = got_error_from_errno2("fopen",
8646 patch_script_path);
8647 goto done;
8652 * XXX "c" perm needed on repo dir to delete merge references.
8654 error = apply_unveil(got_repo_get_path(repo), 0,
8655 got_worktree_get_root_path(worktree));
8656 if (error)
8657 goto done;
8659 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8660 if (error)
8661 goto done;
8663 if (!can_recurse) {
8664 char *ondisk_path;
8665 struct stat sb;
8666 TAILQ_FOREACH(pe, &paths, entry) {
8667 if (asprintf(&ondisk_path, "%s/%s",
8668 got_worktree_get_root_path(worktree),
8669 pe->path) == -1) {
8670 error = got_error_from_errno("asprintf");
8671 goto done;
8673 if (lstat(ondisk_path, &sb) == -1) {
8674 if (errno == ENOENT) {
8675 free(ondisk_path);
8676 continue;
8678 error = got_error_from_errno2("lstat",
8679 ondisk_path);
8680 free(ondisk_path);
8681 goto done;
8683 free(ondisk_path);
8684 if (S_ISDIR(sb.st_mode)) {
8685 error = got_error_msg(GOT_ERR_BAD_PATH,
8686 "reverting directories requires -R option");
8687 goto done;
8692 cpa.patch_script_file = patch_script_file;
8693 cpa.action = "revert";
8694 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8695 pflag ? choose_patch : NULL, &cpa, repo);
8697 error = rm_logmsg_ref(worktree, repo);
8698 done:
8699 if (patch_script_file && fclose(patch_script_file) == EOF &&
8700 error == NULL)
8701 error = got_error_from_errno2("fclose", patch_script_path);
8702 if (repo) {
8703 const struct got_error *close_err = got_repo_close(repo);
8704 if (error == NULL)
8705 error = close_err;
8707 if (worktree)
8708 got_worktree_close(worktree);
8709 if (pack_fds) {
8710 const struct got_error *pack_err =
8711 got_repo_pack_fds_close(pack_fds);
8712 if (error == NULL)
8713 error = pack_err;
8715 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8716 free(path);
8717 free(cwd);
8718 return error;
8721 __dead static void
8722 usage_commit(void)
8724 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8725 "[-m message] [path ...]\n", getprogname());
8726 exit(1);
8729 struct collect_commit_logmsg_arg {
8730 const char *cmdline_log;
8731 const char *prepared_log;
8732 const char *merged_log;
8733 int non_interactive;
8734 const char *editor;
8735 const char *worktree_path;
8736 const char *branch_name;
8737 const char *repo_path;
8738 char *logmsg_path;
8742 static const struct got_error *
8743 read_prepared_logmsg(char **logmsg, const char *path)
8745 const struct got_error *err = NULL;
8746 FILE *f = NULL;
8747 struct stat sb;
8748 size_t r;
8750 *logmsg = NULL;
8751 memset(&sb, 0, sizeof(sb));
8753 f = fopen(path, "re");
8754 if (f == NULL)
8755 return got_error_from_errno2("fopen", path);
8757 if (fstat(fileno(f), &sb) == -1) {
8758 err = got_error_from_errno2("fstat", path);
8759 goto done;
8761 if (sb.st_size == 0) {
8762 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8763 goto done;
8766 *logmsg = malloc(sb.st_size + 1);
8767 if (*logmsg == NULL) {
8768 err = got_error_from_errno("malloc");
8769 goto done;
8772 r = fread(*logmsg, 1, sb.st_size, f);
8773 if (r != sb.st_size) {
8774 if (ferror(f))
8775 err = got_error_from_errno2("fread", path);
8776 else
8777 err = got_error(GOT_ERR_IO);
8778 goto done;
8780 (*logmsg)[sb.st_size] = '\0';
8781 done:
8782 if (fclose(f) == EOF && err == NULL)
8783 err = got_error_from_errno2("fclose", path);
8784 if (err) {
8785 free(*logmsg);
8786 *logmsg = NULL;
8788 return err;
8791 static const struct got_error *
8792 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8793 const char *diff_path, char **logmsg, void *arg)
8795 char *initial_content = NULL;
8796 struct got_pathlist_entry *pe;
8797 const struct got_error *err = NULL;
8798 char *template = NULL;
8799 char *prepared_msg = NULL, *merged_msg = NULL;
8800 struct collect_commit_logmsg_arg *a = arg;
8801 int initial_content_len;
8802 int fd = -1;
8803 size_t len;
8805 /* if a message was specified on the command line, just use it */
8806 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8807 len = strlen(a->cmdline_log) + 1;
8808 *logmsg = malloc(len + 1);
8809 if (*logmsg == NULL)
8810 return got_error_from_errno("malloc");
8811 strlcpy(*logmsg, a->cmdline_log, len);
8812 return NULL;
8813 } else if (a->prepared_log != NULL && a->non_interactive)
8814 return read_prepared_logmsg(logmsg, a->prepared_log);
8816 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8817 return got_error_from_errno("asprintf");
8819 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8820 if (err)
8821 goto done;
8823 if (a->prepared_log) {
8824 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8825 if (err)
8826 goto done;
8827 } else if (a->merged_log) {
8828 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8829 if (err)
8830 goto done;
8833 initial_content_len = asprintf(&initial_content,
8834 "%s%s\n# changes to be committed on branch %s:\n",
8835 prepared_msg ? prepared_msg : "",
8836 merged_msg ? merged_msg : "", a->branch_name);
8837 if (initial_content_len == -1) {
8838 err = got_error_from_errno("asprintf");
8839 goto done;
8842 if (write(fd, initial_content, initial_content_len) == -1) {
8843 err = got_error_from_errno2("write", a->logmsg_path);
8844 goto done;
8847 TAILQ_FOREACH(pe, commitable_paths, entry) {
8848 struct got_commitable *ct = pe->data;
8849 dprintf(fd, "# %c %s\n",
8850 got_commitable_get_status(ct),
8851 got_commitable_get_path(ct));
8854 if (diff_path) {
8855 dprintf(fd, "# detailed changes can be viewed in %s\n",
8856 diff_path);
8859 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8860 initial_content_len, a->prepared_log ? 0 : 1);
8861 done:
8862 free(initial_content);
8863 free(template);
8864 free(prepared_msg);
8865 free(merged_msg);
8867 if (fd != -1 && close(fd) == -1 && err == NULL)
8868 err = got_error_from_errno2("close", a->logmsg_path);
8870 /* Editor is done; we can now apply unveil(2) */
8871 if (err == NULL)
8872 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8873 if (err) {
8874 free(*logmsg);
8875 *logmsg = NULL;
8877 return err;
8880 static const struct got_error *
8881 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8882 const char *type, int has_content)
8884 const struct got_error *err = NULL;
8885 char *logmsg = NULL;
8887 err = got_object_commit_get_logmsg(&logmsg, commit);
8888 if (err)
8889 return err;
8891 if (fprintf(f, "%s# log message of %s commit %s:%s",
8892 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8893 err = got_ferror(f, GOT_ERR_IO);
8895 free(logmsg);
8896 return err;
8900 * Lookup "logmsg" references of backed-out and cherrypicked commits
8901 * belonging to the current work tree. If found, and the worktree has
8902 * at least one modified file that was changed in the referenced commit,
8903 * add its log message to a new temporary file at *logmsg_path.
8904 * Add all refs found to matched_refs to be scheduled for removal on
8905 * successful commit.
8907 static const struct got_error *
8908 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8909 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8910 struct got_repository *repo)
8912 const struct got_error *err;
8913 struct got_commit_object *commit = NULL;
8914 struct got_object_id *id = NULL;
8915 struct got_reflist_head refs;
8916 struct got_reflist_entry *re, *re_match;
8917 FILE *f = NULL;
8918 char *uuidstr = NULL;
8919 int added_logmsg = 0;
8921 TAILQ_INIT(&refs);
8923 *logmsg_path = NULL;
8925 err = got_worktree_get_uuid(&uuidstr, worktree);
8926 if (err)
8927 goto done;
8929 err = got_ref_list(&refs, repo, "refs/got/worktree",
8930 got_ref_cmp_by_name, repo);
8931 if (err)
8932 goto done;
8934 TAILQ_FOREACH(re, &refs, entry) {
8935 const char *refname, *type;
8936 struct wt_commitable_path_arg wcpa;
8937 int add_logmsg = 0;
8939 refname = got_ref_get_name(re->ref);
8941 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8942 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8943 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8944 type = "cherrypicked";
8945 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8946 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8947 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8948 type = "backed-out";
8949 } else
8950 continue;
8952 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8953 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8954 else
8955 continue;
8957 err = got_repo_match_object_id(&id, NULL, refname,
8958 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8959 if (err)
8960 goto done;
8962 err = got_object_open_as_commit(&commit, repo, id);
8963 if (err)
8964 goto done;
8966 wcpa.commit_paths = paths;
8967 wcpa.has_changes = &add_logmsg;
8969 err = commit_path_changed_in_worktree(&wcpa, id,
8970 worktree, repo);
8971 if (err)
8972 goto done;
8974 if (add_logmsg) {
8975 if (f == NULL) {
8976 err = got_opentemp_named(logmsg_path, &f,
8977 "got-commit-logmsg", "");
8978 if (err)
8979 goto done;
8981 err = cat_logmsg(f, commit, refname, type,
8982 added_logmsg);
8983 if (err)
8984 goto done;
8985 if (!added_logmsg)
8986 ++added_logmsg;
8988 err = got_reflist_entry_dup(&re_match, re);
8989 if (err)
8990 goto done;
8991 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
8994 got_object_commit_close(commit);
8995 commit = NULL;
8996 free(id);
8997 id = NULL;
9000 done:
9001 free(id);
9002 free(uuidstr);
9003 got_ref_list_free(&refs);
9004 if (commit)
9005 got_object_commit_close(commit);
9006 if (f && fclose(f) == EOF && err == NULL)
9007 err = got_error_from_errno("fclose");
9008 if (!added_logmsg) {
9009 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9010 err = got_error_from_errno2("unlink", *logmsg_path);
9011 *logmsg_path = NULL;
9013 return err;
9016 static const struct got_error *
9017 cmd_commit(int argc, char *argv[])
9019 const struct got_error *error = NULL;
9020 struct got_worktree *worktree = NULL;
9021 struct got_repository *repo = NULL;
9022 char *cwd = NULL, *id_str = NULL;
9023 struct got_object_id *id = NULL;
9024 const char *logmsg = NULL;
9025 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9026 struct collect_commit_logmsg_arg cl_arg;
9027 const char *author = NULL;
9028 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9029 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9030 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9031 int show_diff = 1;
9032 struct got_pathlist_head paths;
9033 struct got_reflist_head refs;
9034 struct got_reflist_entry *re;
9035 int *pack_fds = NULL;
9037 TAILQ_INIT(&refs);
9038 TAILQ_INIT(&paths);
9039 cl_arg.logmsg_path = NULL;
9041 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9042 switch (ch) {
9043 case 'A':
9044 author = optarg;
9045 error = valid_author(author);
9046 if (error)
9047 return error;
9048 break;
9049 case 'F':
9050 if (logmsg != NULL)
9051 option_conflict('F', 'm');
9052 prepared_logmsg = realpath(optarg, NULL);
9053 if (prepared_logmsg == NULL)
9054 return got_error_from_errno2("realpath",
9055 optarg);
9056 break;
9057 case 'm':
9058 if (prepared_logmsg)
9059 option_conflict('m', 'F');
9060 logmsg = optarg;
9061 break;
9062 case 'N':
9063 non_interactive = 1;
9064 break;
9065 case 'n':
9066 show_diff = 0;
9067 break;
9068 case 'S':
9069 allow_bad_symlinks = 1;
9070 break;
9071 default:
9072 usage_commit();
9073 /* NOTREACHED */
9077 argc -= optind;
9078 argv += optind;
9080 #ifndef PROFILE
9081 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9082 "unveil", NULL) == -1)
9083 err(1, "pledge");
9084 #endif
9085 cwd = getcwd(NULL, 0);
9086 if (cwd == NULL) {
9087 error = got_error_from_errno("getcwd");
9088 goto done;
9091 error = got_repo_pack_fds_open(&pack_fds);
9092 if (error != NULL)
9093 goto done;
9095 error = got_worktree_open(&worktree, cwd);
9096 if (error) {
9097 if (error->code == GOT_ERR_NOT_WORKTREE)
9098 error = wrap_not_worktree_error(error, "commit", cwd);
9099 goto done;
9102 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9103 if (error)
9104 goto done;
9105 if (rebase_in_progress) {
9106 error = got_error(GOT_ERR_REBASING);
9107 goto done;
9110 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9111 worktree);
9112 if (error)
9113 goto done;
9115 error = get_gitconfig_path(&gitconfig_path);
9116 if (error)
9117 goto done;
9118 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9119 gitconfig_path, pack_fds);
9120 if (error != NULL)
9121 goto done;
9123 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9124 if (error)
9125 goto done;
9126 if (merge_in_progress) {
9127 error = got_error(GOT_ERR_MERGE_BUSY);
9128 goto done;
9131 error = get_author(&committer, repo, worktree);
9132 if (error)
9133 goto done;
9135 if (author != NULL && !strcmp(committer, author)) {
9136 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9137 goto done;
9140 if (author == NULL)
9141 author = committer;
9144 * unveil(2) traverses exec(2); if an editor is used we have
9145 * to apply unveil after the log message has been written.
9147 if (logmsg == NULL || strlen(logmsg) == 0)
9148 error = get_editor(&editor);
9149 else
9150 error = apply_unveil(got_repo_get_path(repo), 0,
9151 got_worktree_get_root_path(worktree));
9152 if (error)
9153 goto done;
9155 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9156 if (error)
9157 goto done;
9159 if (prepared_logmsg == NULL) {
9160 error = lookup_logmsg_ref(&merged_logmsg,
9161 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9162 if (error)
9163 goto done;
9166 cl_arg.editor = editor;
9167 cl_arg.cmdline_log = logmsg;
9168 cl_arg.prepared_log = prepared_logmsg;
9169 cl_arg.merged_log = merged_logmsg;
9170 cl_arg.non_interactive = non_interactive;
9171 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9172 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9173 if (!histedit_in_progress) {
9174 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9175 error = got_error(GOT_ERR_COMMIT_BRANCH);
9176 goto done;
9178 cl_arg.branch_name += 11;
9180 cl_arg.repo_path = got_repo_get_path(repo);
9181 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9182 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9183 print_status, NULL, repo);
9184 if (error) {
9185 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9186 cl_arg.logmsg_path != NULL)
9187 preserve_logmsg = 1;
9188 goto done;
9191 error = got_object_id_str(&id_str, id);
9192 if (error)
9193 goto done;
9194 printf("Created commit %s\n", id_str);
9196 TAILQ_FOREACH(re, &refs, entry) {
9197 error = got_ref_delete(re->ref, repo);
9198 if (error)
9199 goto done;
9202 done:
9203 if (preserve_logmsg) {
9204 fprintf(stderr, "%s: log message preserved in %s\n",
9205 getprogname(), cl_arg.logmsg_path);
9206 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9207 error == NULL)
9208 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9209 free(cl_arg.logmsg_path);
9210 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9211 error = got_error_from_errno2("unlink", merged_logmsg);
9212 free(merged_logmsg);
9213 if (repo) {
9214 const struct got_error *close_err = got_repo_close(repo);
9215 if (error == NULL)
9216 error = close_err;
9218 if (worktree)
9219 got_worktree_close(worktree);
9220 if (pack_fds) {
9221 const struct got_error *pack_err =
9222 got_repo_pack_fds_close(pack_fds);
9223 if (error == NULL)
9224 error = pack_err;
9226 got_ref_list_free(&refs);
9227 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9228 free(cwd);
9229 free(id_str);
9230 free(gitconfig_path);
9231 free(editor);
9232 free(committer);
9233 free(prepared_logmsg);
9234 return error;
9237 __dead static void
9238 usage_send(void)
9240 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9241 "[-r repository-path] [-t tag] [remote-repository]\n",
9242 getprogname());
9243 exit(1);
9246 static void
9247 print_load_info(int print_colored, int print_found, int print_trees,
9248 int ncolored, int nfound, int ntrees)
9250 if (print_colored) {
9251 printf("%d commit%s colored", ncolored,
9252 ncolored == 1 ? "" : "s");
9254 if (print_found) {
9255 printf("%s%d object%s found",
9256 ncolored > 0 ? "; " : "",
9257 nfound, nfound == 1 ? "" : "s");
9259 if (print_trees) {
9260 printf("; %d tree%s scanned", ntrees,
9261 ntrees == 1 ? "" : "s");
9265 struct got_send_progress_arg {
9266 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9267 int verbosity;
9268 int last_ncolored;
9269 int last_nfound;
9270 int last_ntrees;
9271 int loading_done;
9272 int last_ncommits;
9273 int last_nobj_total;
9274 int last_p_deltify;
9275 int last_p_written;
9276 int last_p_sent;
9277 int printed_something;
9278 int sent_something;
9279 struct got_pathlist_head *delete_branches;
9282 static const struct got_error *
9283 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9284 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9285 int nobj_written, off_t bytes_sent, const char *refname,
9286 const char *errmsg, int success)
9288 struct got_send_progress_arg *a = arg;
9289 char scaled_packsize[FMT_SCALED_STRSIZE];
9290 char scaled_sent[FMT_SCALED_STRSIZE];
9291 int p_deltify = 0, p_written = 0, p_sent = 0;
9292 int print_colored = 0, print_found = 0, print_trees = 0;
9293 int print_searching = 0, print_total = 0;
9294 int print_deltify = 0, print_written = 0, print_sent = 0;
9296 if (a->verbosity < 0)
9297 return NULL;
9299 if (refname) {
9300 const char *status = success ? "accepted" : "rejected";
9302 if (success) {
9303 struct got_pathlist_entry *pe;
9304 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9305 const char *branchname = pe->path;
9306 if (got_path_cmp(branchname, refname,
9307 strlen(branchname), strlen(refname)) == 0) {
9308 status = "deleted";
9309 a->sent_something = 1;
9310 break;
9315 if (a->printed_something)
9316 putchar('\n');
9317 printf("Server has %s %s", status, refname);
9318 if (errmsg)
9319 printf(": %s", errmsg);
9320 a->printed_something = 1;
9321 return NULL;
9324 if (a->last_ncolored != ncolored) {
9325 print_colored = 1;
9326 a->last_ncolored = ncolored;
9329 if (a->last_nfound != nfound) {
9330 print_colored = 1;
9331 print_found = 1;
9332 a->last_nfound = nfound;
9335 if (a->last_ntrees != ntrees) {
9336 print_colored = 1;
9337 print_found = 1;
9338 print_trees = 1;
9339 a->last_ntrees = ntrees;
9342 if ((print_colored || print_found || print_trees) &&
9343 !a->loading_done) {
9344 printf("\r");
9345 print_load_info(print_colored, print_found, print_trees,
9346 ncolored, nfound, ntrees);
9347 a->printed_something = 1;
9348 fflush(stdout);
9349 return NULL;
9350 } else if (!a->loading_done) {
9351 printf("\r");
9352 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9353 printf("\n");
9354 a->loading_done = 1;
9357 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9358 return got_error_from_errno("fmt_scaled");
9359 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9360 return got_error_from_errno("fmt_scaled");
9362 if (a->last_ncommits != ncommits) {
9363 print_searching = 1;
9364 a->last_ncommits = ncommits;
9367 if (a->last_nobj_total != nobj_total) {
9368 print_searching = 1;
9369 print_total = 1;
9370 a->last_nobj_total = nobj_total;
9373 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9374 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9375 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9376 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9377 return got_error(GOT_ERR_NO_SPACE);
9380 if (nobj_deltify > 0 || nobj_written > 0) {
9381 if (nobj_deltify > 0) {
9382 p_deltify = (nobj_deltify * 100) / nobj_total;
9383 if (p_deltify != a->last_p_deltify) {
9384 a->last_p_deltify = p_deltify;
9385 print_searching = 1;
9386 print_total = 1;
9387 print_deltify = 1;
9390 if (nobj_written > 0) {
9391 p_written = (nobj_written * 100) / nobj_total;
9392 if (p_written != a->last_p_written) {
9393 a->last_p_written = p_written;
9394 print_searching = 1;
9395 print_total = 1;
9396 print_deltify = 1;
9397 print_written = 1;
9402 if (bytes_sent > 0) {
9403 p_sent = (bytes_sent * 100) / packfile_size;
9404 if (p_sent != a->last_p_sent) {
9405 a->last_p_sent = p_sent;
9406 print_searching = 1;
9407 print_total = 1;
9408 print_deltify = 1;
9409 print_written = 1;
9410 print_sent = 1;
9412 a->sent_something = 1;
9415 if (print_searching || print_total || print_deltify || print_written ||
9416 print_sent)
9417 printf("\r");
9418 if (print_searching)
9419 printf("packing %d reference%s", ncommits,
9420 ncommits == 1 ? "" : "s");
9421 if (print_total)
9422 printf("; %d object%s", nobj_total,
9423 nobj_total == 1 ? "" : "s");
9424 if (print_deltify)
9425 printf("; deltify: %d%%", p_deltify);
9426 if (print_sent)
9427 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9428 scaled_packsize, p_sent);
9429 else if (print_written)
9430 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9431 scaled_packsize, p_written);
9432 if (print_searching || print_total || print_deltify ||
9433 print_written || print_sent) {
9434 a->printed_something = 1;
9435 fflush(stdout);
9437 return NULL;
9440 static const struct got_error *
9441 cmd_send(int argc, char *argv[])
9443 const struct got_error *error = NULL;
9444 char *cwd = NULL, *repo_path = NULL;
9445 const char *remote_name;
9446 char *proto = NULL, *host = NULL, *port = NULL;
9447 char *repo_name = NULL, *server_path = NULL;
9448 const struct got_remote_repo *remotes, *remote = NULL;
9449 int nremotes, nbranches = 0, ndelete_branches = 0;
9450 struct got_repository *repo = NULL;
9451 struct got_worktree *worktree = NULL;
9452 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9453 struct got_pathlist_head branches;
9454 struct got_pathlist_head tags;
9455 struct got_reflist_head all_branches;
9456 struct got_reflist_head all_tags;
9457 struct got_pathlist_head delete_args;
9458 struct got_pathlist_head delete_branches;
9459 struct got_reflist_entry *re;
9460 struct got_pathlist_entry *pe;
9461 int i, ch, sendfd = -1, sendstatus;
9462 pid_t sendpid = -1;
9463 struct got_send_progress_arg spa;
9464 int verbosity = 0, overwrite_refs = 0;
9465 int send_all_branches = 0, send_all_tags = 0;
9466 struct got_reference *ref = NULL;
9467 int *pack_fds = NULL;
9469 TAILQ_INIT(&branches);
9470 TAILQ_INIT(&tags);
9471 TAILQ_INIT(&all_branches);
9472 TAILQ_INIT(&all_tags);
9473 TAILQ_INIT(&delete_args);
9474 TAILQ_INIT(&delete_branches);
9476 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9477 switch (ch) {
9478 case 'a':
9479 send_all_branches = 1;
9480 break;
9481 case 'b':
9482 error = got_pathlist_append(&branches, optarg, NULL);
9483 if (error)
9484 return error;
9485 nbranches++;
9486 break;
9487 case 'd':
9488 error = got_pathlist_append(&delete_args, optarg, NULL);
9489 if (error)
9490 return error;
9491 break;
9492 case 'f':
9493 overwrite_refs = 1;
9494 break;
9495 case 'q':
9496 verbosity = -1;
9497 break;
9498 case 'r':
9499 repo_path = realpath(optarg, NULL);
9500 if (repo_path == NULL)
9501 return got_error_from_errno2("realpath",
9502 optarg);
9503 got_path_strip_trailing_slashes(repo_path);
9504 break;
9505 case 'T':
9506 send_all_tags = 1;
9507 break;
9508 case 't':
9509 error = got_pathlist_append(&tags, optarg, NULL);
9510 if (error)
9511 return error;
9512 break;
9513 case 'v':
9514 if (verbosity < 0)
9515 verbosity = 0;
9516 else if (verbosity < 3)
9517 verbosity++;
9518 break;
9519 default:
9520 usage_send();
9521 /* NOTREACHED */
9524 argc -= optind;
9525 argv += optind;
9527 if (send_all_branches && !TAILQ_EMPTY(&branches))
9528 option_conflict('a', 'b');
9529 if (send_all_tags && !TAILQ_EMPTY(&tags))
9530 option_conflict('T', 't');
9533 if (argc == 0)
9534 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9535 else if (argc == 1)
9536 remote_name = argv[0];
9537 else
9538 usage_send();
9540 cwd = getcwd(NULL, 0);
9541 if (cwd == NULL) {
9542 error = got_error_from_errno("getcwd");
9543 goto done;
9546 error = got_repo_pack_fds_open(&pack_fds);
9547 if (error != NULL)
9548 goto done;
9550 if (repo_path == NULL) {
9551 error = got_worktree_open(&worktree, cwd);
9552 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9553 goto done;
9554 else
9555 error = NULL;
9556 if (worktree) {
9557 repo_path =
9558 strdup(got_worktree_get_repo_path(worktree));
9559 if (repo_path == NULL)
9560 error = got_error_from_errno("strdup");
9561 if (error)
9562 goto done;
9563 } else {
9564 repo_path = strdup(cwd);
9565 if (repo_path == NULL) {
9566 error = got_error_from_errno("strdup");
9567 goto done;
9572 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9573 if (error)
9574 goto done;
9576 if (worktree) {
9577 worktree_conf = got_worktree_get_gotconfig(worktree);
9578 if (worktree_conf) {
9579 got_gotconfig_get_remotes(&nremotes, &remotes,
9580 worktree_conf);
9581 for (i = 0; i < nremotes; i++) {
9582 if (strcmp(remotes[i].name, remote_name) == 0) {
9583 remote = &remotes[i];
9584 break;
9589 if (remote == NULL) {
9590 repo_conf = got_repo_get_gotconfig(repo);
9591 if (repo_conf) {
9592 got_gotconfig_get_remotes(&nremotes, &remotes,
9593 repo_conf);
9594 for (i = 0; i < nremotes; i++) {
9595 if (strcmp(remotes[i].name, remote_name) == 0) {
9596 remote = &remotes[i];
9597 break;
9602 if (remote == NULL) {
9603 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9604 for (i = 0; i < nremotes; i++) {
9605 if (strcmp(remotes[i].name, remote_name) == 0) {
9606 remote = &remotes[i];
9607 break;
9611 if (remote == NULL) {
9612 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9613 goto done;
9616 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9617 &repo_name, remote->send_url);
9618 if (error)
9619 goto done;
9621 if (strcmp(proto, "git") == 0) {
9622 #ifndef PROFILE
9623 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9624 "sendfd dns inet unveil", NULL) == -1)
9625 err(1, "pledge");
9626 #endif
9627 } else if (strcmp(proto, "git+ssh") == 0 ||
9628 strcmp(proto, "ssh") == 0) {
9629 #ifndef PROFILE
9630 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9631 "sendfd unveil", NULL) == -1)
9632 err(1, "pledge");
9633 #endif
9634 } else if (strcmp(proto, "http") == 0 ||
9635 strcmp(proto, "git+http") == 0) {
9636 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9637 goto done;
9638 } else {
9639 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9640 goto done;
9643 error = got_dial_apply_unveil(proto);
9644 if (error)
9645 goto done;
9647 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9648 if (error)
9649 goto done;
9651 if (send_all_branches) {
9652 error = got_ref_list(&all_branches, repo, "refs/heads",
9653 got_ref_cmp_by_name, NULL);
9654 if (error)
9655 goto done;
9656 TAILQ_FOREACH(re, &all_branches, entry) {
9657 const char *branchname = got_ref_get_name(re->ref);
9658 error = got_pathlist_append(&branches,
9659 branchname, NULL);
9660 if (error)
9661 goto done;
9662 nbranches++;
9664 } else if (nbranches == 0) {
9665 for (i = 0; i < remote->nsend_branches; i++) {
9666 error = got_pathlist_append(&branches,
9667 remote->send_branches[i], NULL);
9668 if (error)
9669 goto done;
9673 if (send_all_tags) {
9674 error = got_ref_list(&all_tags, repo, "refs/tags",
9675 got_ref_cmp_by_name, NULL);
9676 if (error)
9677 goto done;
9678 TAILQ_FOREACH(re, &all_tags, entry) {
9679 const char *tagname = got_ref_get_name(re->ref);
9680 error = got_pathlist_append(&tags,
9681 tagname, NULL);
9682 if (error)
9683 goto done;
9688 * To prevent accidents only branches in refs/heads/ can be deleted
9689 * with 'got send -d'.
9690 * Deleting anything else requires local repository access or Git.
9692 TAILQ_FOREACH(pe, &delete_args, entry) {
9693 const char *branchname = pe->path;
9694 char *s;
9695 struct got_pathlist_entry *new;
9696 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9697 s = strdup(branchname);
9698 if (s == NULL) {
9699 error = got_error_from_errno("strdup");
9700 goto done;
9702 } else {
9703 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9704 error = got_error_from_errno("asprintf");
9705 goto done;
9708 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9709 if (error || new == NULL /* duplicate */)
9710 free(s);
9711 if (error)
9712 goto done;
9713 ndelete_branches++;
9716 if (nbranches == 0 && ndelete_branches == 0) {
9717 struct got_reference *head_ref;
9718 if (worktree)
9719 error = got_ref_open(&head_ref, repo,
9720 got_worktree_get_head_ref_name(worktree), 0);
9721 else
9722 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9723 if (error)
9724 goto done;
9725 if (got_ref_is_symbolic(head_ref)) {
9726 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9727 got_ref_close(head_ref);
9728 if (error)
9729 goto done;
9730 } else
9731 ref = head_ref;
9732 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9733 NULL);
9734 if (error)
9735 goto done;
9736 nbranches++;
9739 if (verbosity >= 0) {
9740 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9741 remote->name, proto, host,
9742 port ? ":" : "", port ? port : "",
9743 *server_path == '/' ? "" : "/", server_path);
9746 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9747 server_path, verbosity);
9748 if (error)
9749 goto done;
9751 memset(&spa, 0, sizeof(spa));
9752 spa.last_scaled_packsize[0] = '\0';
9753 spa.last_p_deltify = -1;
9754 spa.last_p_written = -1;
9755 spa.verbosity = verbosity;
9756 spa.delete_branches = &delete_branches;
9757 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9758 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9759 check_cancelled, NULL);
9760 if (spa.printed_something)
9761 putchar('\n');
9762 if (error)
9763 goto done;
9764 if (!spa.sent_something && verbosity >= 0)
9765 printf("Already up-to-date\n");
9766 done:
9767 if (sendpid > 0) {
9768 if (kill(sendpid, SIGTERM) == -1)
9769 error = got_error_from_errno("kill");
9770 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9771 error = got_error_from_errno("waitpid");
9773 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9774 error = got_error_from_errno("close");
9775 if (repo) {
9776 const struct got_error *close_err = got_repo_close(repo);
9777 if (error == NULL)
9778 error = close_err;
9780 if (worktree)
9781 got_worktree_close(worktree);
9782 if (pack_fds) {
9783 const struct got_error *pack_err =
9784 got_repo_pack_fds_close(pack_fds);
9785 if (error == NULL)
9786 error = pack_err;
9788 if (ref)
9789 got_ref_close(ref);
9790 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9791 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9792 got_ref_list_free(&all_branches);
9793 got_ref_list_free(&all_tags);
9794 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9795 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9796 free(cwd);
9797 free(repo_path);
9798 free(proto);
9799 free(host);
9800 free(port);
9801 free(server_path);
9802 free(repo_name);
9803 return error;
9807 * Print and if delete is set delete all ref_prefix references.
9808 * If wanted_ref is not NULL, only print or delete this reference.
9810 static const struct got_error *
9811 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9812 const char *wanted_ref, int delete, struct got_worktree *worktree,
9813 struct got_repository *repo)
9815 const struct got_error *err;
9816 struct got_pathlist_head paths;
9817 struct got_reflist_head refs;
9818 struct got_reflist_entry *re;
9819 struct got_reflist_object_id_map *refs_idmap = NULL;
9820 struct got_commit_object *commit = NULL;
9821 struct got_object_id *id = NULL;
9822 const char *header_prefix;
9823 char *uuidstr = NULL;
9824 int found = 0;
9826 TAILQ_INIT(&refs);
9827 TAILQ_INIT(&paths);
9829 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9830 if (err)
9831 goto done;
9833 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9834 if (err)
9835 goto done;
9837 if (worktree != NULL) {
9838 err = got_worktree_get_uuid(&uuidstr, worktree);
9839 if (err)
9840 goto done;
9843 if (wanted_ref) {
9844 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9845 wanted_ref += 11;
9848 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9849 header_prefix = "backout";
9850 else
9851 header_prefix = "cherrypick";
9853 TAILQ_FOREACH(re, &refs, entry) {
9854 const char *refname, *wt;
9856 refname = got_ref_get_name(re->ref);
9858 err = check_cancelled(NULL);
9859 if (err)
9860 goto done;
9862 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9863 refname += prefix_len + 1; /* skip '-' delimiter */
9864 else
9865 continue;
9867 wt = refname;
9869 if (worktree == NULL || strncmp(refname, uuidstr,
9870 GOT_WORKTREE_UUID_STRLEN) == 0)
9871 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9872 else
9873 continue;
9875 err = got_repo_match_object_id(&id, NULL, refname,
9876 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9877 if (err)
9878 goto done;
9880 err = got_object_open_as_commit(&commit, repo, id);
9881 if (err)
9882 goto done;
9884 if (wanted_ref)
9885 found = strncmp(wanted_ref, refname,
9886 strlen(wanted_ref)) == 0;
9887 if (wanted_ref && !found) {
9888 struct got_reflist_head *ci_refs;
9890 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9891 id);
9893 if (ci_refs) {
9894 char *refs_str = NULL;
9895 char const *r = NULL;
9897 err = build_refs_str(&refs_str, ci_refs, id,
9898 repo, 1);
9899 if (err)
9900 goto done;
9902 r = refs_str;
9903 while (r) {
9904 if (strncmp(r, wanted_ref,
9905 strlen(wanted_ref)) == 0) {
9906 found = 1;
9907 break;
9909 r = strchr(r, ' ');
9910 if (r)
9911 ++r;
9913 free(refs_str);
9917 if (wanted_ref == NULL || found) {
9918 if (delete) {
9919 err = got_ref_delete(re->ref, repo);
9920 if (err)
9921 goto done;
9922 printf("Deleted: ");
9923 err = print_commit_oneline(commit, id, repo,
9924 refs_idmap);
9925 } else {
9927 * Print paths modified by commit to help
9928 * associate commits with worktree changes.
9930 err = get_changed_paths(&paths, commit,
9931 repo, NULL);
9932 if (err)
9933 goto done;
9935 err = print_commit(commit, id, repo, NULL,
9936 &paths, NULL, 0, 0, refs_idmap, NULL,
9937 header_prefix);
9938 got_pathlist_free(&paths,
9939 GOT_PATHLIST_FREE_ALL);
9941 if (worktree == NULL)
9942 printf("work tree: %.*s\n\n",
9943 GOT_WORKTREE_UUID_STRLEN, wt);
9945 if (err || found)
9946 goto done;
9949 got_object_commit_close(commit);
9950 commit = NULL;
9951 free(id);
9952 id = NULL;
9955 if (wanted_ref != NULL && !found)
9956 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9958 done:
9959 free(id);
9960 free(uuidstr);
9961 got_ref_list_free(&refs);
9962 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9963 if (refs_idmap)
9964 got_reflist_object_id_map_free(refs_idmap);
9965 if (commit)
9966 got_object_commit_close(commit);
9967 return err;
9971 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9972 * identified by id for log messages to prepopulate the editor on commit.
9974 static const struct got_error *
9975 logmsg_ref(struct got_object_id *id, const char *prefix,
9976 struct got_worktree *worktree, struct got_repository *repo)
9978 const struct got_error *err = NULL;
9979 char *idstr, *ref = NULL, *refname = NULL;
9980 int histedit_in_progress;
9981 int rebase_in_progress, merge_in_progress;
9984 * Silenty refuse to create merge reference if any histedit, merge,
9985 * or rebase operation is in progress.
9987 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9988 worktree);
9989 if (err)
9990 return err;
9991 if (histedit_in_progress)
9992 return NULL;
9994 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9995 if (err)
9996 return err;
9997 if (rebase_in_progress)
9998 return NULL;
10000 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10001 repo);
10002 if (err)
10003 return err;
10004 if (merge_in_progress)
10005 return NULL;
10007 err = got_object_id_str(&idstr, id);
10008 if (err)
10009 return err;
10011 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10012 if (err)
10013 goto done;
10015 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10016 err = got_error_from_errno("asprintf");
10017 goto done;
10020 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10021 -1, repo);
10022 done:
10023 free(ref);
10024 free(idstr);
10025 free(refname);
10026 return err;
10029 __dead static void
10030 usage_cherrypick(void)
10032 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10033 getprogname());
10034 exit(1);
10037 static const struct got_error *
10038 cmd_cherrypick(int argc, char *argv[])
10040 const struct got_error *error = NULL;
10041 struct got_worktree *worktree = NULL;
10042 struct got_repository *repo = NULL;
10043 char *cwd = NULL, *commit_id_str = NULL;
10044 struct got_object_id *commit_id = NULL;
10045 struct got_commit_object *commit = NULL;
10046 struct got_object_qid *pid;
10047 int ch, list_refs = 0, remove_refs = 0;
10048 struct got_update_progress_arg upa;
10049 int *pack_fds = NULL;
10051 while ((ch = getopt(argc, argv, "lX")) != -1) {
10052 switch (ch) {
10053 case 'l':
10054 list_refs = 1;
10055 break;
10056 case 'X':
10057 remove_refs = 1;
10058 break;
10059 default:
10060 usage_cherrypick();
10061 /* NOTREACHED */
10065 argc -= optind;
10066 argv += optind;
10068 #ifndef PROFILE
10069 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10070 "unveil", NULL) == -1)
10071 err(1, "pledge");
10072 #endif
10073 if (list_refs || remove_refs) {
10074 if (argc != 0 && argc != 1)
10075 usage_cherrypick();
10076 } else if (argc != 1)
10077 usage_cherrypick();
10078 if (list_refs && remove_refs)
10079 option_conflict('l', 'X');
10081 cwd = getcwd(NULL, 0);
10082 if (cwd == NULL) {
10083 error = got_error_from_errno("getcwd");
10084 goto done;
10087 error = got_repo_pack_fds_open(&pack_fds);
10088 if (error != NULL)
10089 goto done;
10091 error = got_worktree_open(&worktree, cwd);
10092 if (error) {
10093 if (list_refs || remove_refs) {
10094 if (error->code != GOT_ERR_NOT_WORKTREE)
10095 goto done;
10096 } else {
10097 if (error->code == GOT_ERR_NOT_WORKTREE)
10098 error = wrap_not_worktree_error(error,
10099 "cherrypick", cwd);
10100 goto done;
10104 error = got_repo_open(&repo,
10105 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10106 NULL, pack_fds);
10107 if (error != NULL)
10108 goto done;
10110 error = apply_unveil(got_repo_get_path(repo), 0,
10111 worktree ? got_worktree_get_root_path(worktree) : NULL);
10112 if (error)
10113 goto done;
10115 if (list_refs || remove_refs) {
10116 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10117 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10118 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10119 goto done;
10122 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10123 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10124 if (error)
10125 goto done;
10126 error = got_object_id_str(&commit_id_str, commit_id);
10127 if (error)
10128 goto done;
10130 error = got_object_open_as_commit(&commit, repo, commit_id);
10131 if (error)
10132 goto done;
10133 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10134 memset(&upa, 0, sizeof(upa));
10135 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10136 commit_id, repo, update_progress, &upa, check_cancelled,
10137 NULL);
10138 if (error != NULL)
10139 goto done;
10141 if (upa.did_something) {
10142 error = logmsg_ref(commit_id,
10143 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10144 if (error)
10145 goto done;
10146 printf("Merged commit %s\n", commit_id_str);
10148 print_merge_progress_stats(&upa);
10149 done:
10150 free(cwd);
10151 if (commit)
10152 got_object_commit_close(commit);
10153 free(commit_id_str);
10154 if (worktree)
10155 got_worktree_close(worktree);
10156 if (repo) {
10157 const struct got_error *close_err = got_repo_close(repo);
10158 if (error == NULL)
10159 error = close_err;
10161 if (pack_fds) {
10162 const struct got_error *pack_err =
10163 got_repo_pack_fds_close(pack_fds);
10164 if (error == NULL)
10165 error = pack_err;
10168 return error;
10171 __dead static void
10172 usage_backout(void)
10174 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10175 exit(1);
10178 static const struct got_error *
10179 cmd_backout(int argc, char *argv[])
10181 const struct got_error *error = NULL;
10182 struct got_worktree *worktree = NULL;
10183 struct got_repository *repo = NULL;
10184 char *cwd = NULL, *commit_id_str = NULL;
10185 struct got_object_id *commit_id = NULL;
10186 struct got_commit_object *commit = NULL;
10187 struct got_object_qid *pid;
10188 int ch, list_refs = 0, remove_refs = 0;
10189 struct got_update_progress_arg upa;
10190 int *pack_fds = NULL;
10192 while ((ch = getopt(argc, argv, "lX")) != -1) {
10193 switch (ch) {
10194 case 'l':
10195 list_refs = 1;
10196 break;
10197 case 'X':
10198 remove_refs = 1;
10199 break;
10200 default:
10201 usage_backout();
10202 /* NOTREACHED */
10206 argc -= optind;
10207 argv += optind;
10209 #ifndef PROFILE
10210 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10211 "unveil", NULL) == -1)
10212 err(1, "pledge");
10213 #endif
10214 if (list_refs || remove_refs) {
10215 if (argc != 0 && argc != 1)
10216 usage_backout();
10217 } else if (argc != 1)
10218 usage_backout();
10219 if (list_refs && remove_refs)
10220 option_conflict('l', 'X');
10222 cwd = getcwd(NULL, 0);
10223 if (cwd == NULL) {
10224 error = got_error_from_errno("getcwd");
10225 goto done;
10228 error = got_repo_pack_fds_open(&pack_fds);
10229 if (error != NULL)
10230 goto done;
10232 error = got_worktree_open(&worktree, cwd);
10233 if (error) {
10234 if (list_refs || remove_refs) {
10235 if (error->code != GOT_ERR_NOT_WORKTREE)
10236 goto done;
10237 } else {
10238 if (error->code == GOT_ERR_NOT_WORKTREE)
10239 error = wrap_not_worktree_error(error,
10240 "backout", cwd);
10241 goto done;
10245 error = got_repo_open(&repo,
10246 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10247 NULL, pack_fds);
10248 if (error != NULL)
10249 goto done;
10251 error = apply_unveil(got_repo_get_path(repo), 0,
10252 worktree ? got_worktree_get_root_path(worktree) : NULL);
10253 if (error)
10254 goto done;
10256 if (list_refs || remove_refs) {
10257 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10258 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10259 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10260 goto done;
10263 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10264 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10265 if (error)
10266 goto done;
10267 error = got_object_id_str(&commit_id_str, commit_id);
10268 if (error)
10269 goto done;
10271 error = got_object_open_as_commit(&commit, repo, commit_id);
10272 if (error)
10273 goto done;
10274 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10275 if (pid == NULL) {
10276 error = got_error(GOT_ERR_ROOT_COMMIT);
10277 goto done;
10280 memset(&upa, 0, sizeof(upa));
10281 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10282 repo, update_progress, &upa, check_cancelled, NULL);
10283 if (error != NULL)
10284 goto done;
10286 if (upa.did_something) {
10287 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10288 worktree, repo);
10289 if (error)
10290 goto done;
10291 printf("Backed out commit %s\n", commit_id_str);
10293 print_merge_progress_stats(&upa);
10294 done:
10295 free(cwd);
10296 if (commit)
10297 got_object_commit_close(commit);
10298 free(commit_id_str);
10299 if (worktree)
10300 got_worktree_close(worktree);
10301 if (repo) {
10302 const struct got_error *close_err = got_repo_close(repo);
10303 if (error == NULL)
10304 error = close_err;
10306 if (pack_fds) {
10307 const struct got_error *pack_err =
10308 got_repo_pack_fds_close(pack_fds);
10309 if (error == NULL)
10310 error = pack_err;
10312 return error;
10315 __dead static void
10316 usage_rebase(void)
10318 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10319 exit(1);
10322 static void
10323 trim_logmsg(char *logmsg, int limit)
10325 char *nl;
10326 size_t len;
10328 len = strlen(logmsg);
10329 if (len > limit)
10330 len = limit;
10331 logmsg[len] = '\0';
10332 nl = strchr(logmsg, '\n');
10333 if (nl)
10334 *nl = '\0';
10337 static const struct got_error *
10338 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10340 const struct got_error *err;
10341 char *logmsg0 = NULL;
10342 const char *s;
10344 err = got_object_commit_get_logmsg(&logmsg0, commit);
10345 if (err)
10346 return err;
10348 s = logmsg0;
10349 while (isspace((unsigned char)s[0]))
10350 s++;
10352 *logmsg = strdup(s);
10353 if (*logmsg == NULL) {
10354 err = got_error_from_errno("strdup");
10355 goto done;
10358 trim_logmsg(*logmsg, limit);
10359 done:
10360 free(logmsg0);
10361 return err;
10364 static const struct got_error *
10365 show_rebase_merge_conflict(struct got_object_id *id,
10366 struct got_repository *repo)
10368 const struct got_error *err;
10369 struct got_commit_object *commit = NULL;
10370 char *id_str = NULL, *logmsg = NULL;
10372 err = got_object_open_as_commit(&commit, repo, id);
10373 if (err)
10374 return err;
10376 err = got_object_id_str(&id_str, id);
10377 if (err)
10378 goto done;
10380 id_str[12] = '\0';
10382 err = get_short_logmsg(&logmsg, 42, commit);
10383 if (err)
10384 goto done;
10386 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10387 done:
10388 free(id_str);
10389 got_object_commit_close(commit);
10390 free(logmsg);
10391 return err;
10394 static const struct got_error *
10395 show_rebase_progress(struct got_commit_object *commit,
10396 struct got_object_id *old_id, struct got_object_id *new_id)
10398 const struct got_error *err;
10399 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10401 err = got_object_id_str(&old_id_str, old_id);
10402 if (err)
10403 goto done;
10405 if (new_id) {
10406 err = got_object_id_str(&new_id_str, new_id);
10407 if (err)
10408 goto done;
10411 old_id_str[12] = '\0';
10412 if (new_id_str)
10413 new_id_str[12] = '\0';
10415 err = get_short_logmsg(&logmsg, 42, commit);
10416 if (err)
10417 goto done;
10419 printf("%s -> %s: %s\n", old_id_str,
10420 new_id_str ? new_id_str : "no-op change", logmsg);
10421 done:
10422 free(old_id_str);
10423 free(new_id_str);
10424 free(logmsg);
10425 return err;
10428 static const struct got_error *
10429 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10430 struct got_reference *branch, struct got_reference *tmp_branch,
10431 struct got_repository *repo, int create_backup)
10433 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10434 return got_worktree_rebase_complete(worktree, fileindex,
10435 tmp_branch, branch, repo, create_backup);
10438 static const struct got_error *
10439 rebase_commit(struct got_pathlist_head *merged_paths,
10440 struct got_worktree *worktree, struct got_fileindex *fileindex,
10441 struct got_reference *tmp_branch, const char *committer,
10442 struct got_object_id *commit_id, struct got_repository *repo)
10444 const struct got_error *error;
10445 struct got_commit_object *commit;
10446 struct got_object_id *new_commit_id;
10448 error = got_object_open_as_commit(&commit, repo, commit_id);
10449 if (error)
10450 return error;
10452 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10453 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10454 repo);
10455 if (error) {
10456 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10457 goto done;
10458 error = show_rebase_progress(commit, commit_id, NULL);
10459 } else {
10460 error = show_rebase_progress(commit, commit_id, new_commit_id);
10461 free(new_commit_id);
10463 done:
10464 got_object_commit_close(commit);
10465 return error;
10468 struct check_path_prefix_arg {
10469 const char *path_prefix;
10470 size_t len;
10471 int errcode;
10474 static const struct got_error *
10475 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10476 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10477 struct got_object_id *id1, struct got_object_id *id2,
10478 const char *path1, const char *path2,
10479 mode_t mode1, mode_t mode2, struct got_repository *repo)
10481 struct check_path_prefix_arg *a = arg;
10483 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10484 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10485 return got_error(a->errcode);
10487 return NULL;
10490 static const struct got_error *
10491 check_path_prefix(struct got_object_id *parent_id,
10492 struct got_object_id *commit_id, const char *path_prefix,
10493 int errcode, struct got_repository *repo)
10495 const struct got_error *err;
10496 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10497 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10498 struct check_path_prefix_arg cpp_arg;
10500 if (got_path_is_root_dir(path_prefix))
10501 return NULL;
10503 err = got_object_open_as_commit(&commit, repo, commit_id);
10504 if (err)
10505 goto done;
10507 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10508 if (err)
10509 goto done;
10511 err = got_object_open_as_tree(&tree1, repo,
10512 got_object_commit_get_tree_id(parent_commit));
10513 if (err)
10514 goto done;
10516 err = got_object_open_as_tree(&tree2, repo,
10517 got_object_commit_get_tree_id(commit));
10518 if (err)
10519 goto done;
10521 cpp_arg.path_prefix = path_prefix;
10522 while (cpp_arg.path_prefix[0] == '/')
10523 cpp_arg.path_prefix++;
10524 cpp_arg.len = strlen(cpp_arg.path_prefix);
10525 cpp_arg.errcode = errcode;
10526 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10527 check_path_prefix_in_diff, &cpp_arg, 0);
10528 done:
10529 if (tree1)
10530 got_object_tree_close(tree1);
10531 if (tree2)
10532 got_object_tree_close(tree2);
10533 if (commit)
10534 got_object_commit_close(commit);
10535 if (parent_commit)
10536 got_object_commit_close(parent_commit);
10537 return err;
10540 static const struct got_error *
10541 collect_commits(struct got_object_id_queue *commits,
10542 struct got_object_id *initial_commit_id,
10543 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10544 const char *path_prefix, int path_prefix_errcode,
10545 struct got_repository *repo)
10547 const struct got_error *err = NULL;
10548 struct got_commit_graph *graph = NULL;
10549 struct got_object_id parent_id, commit_id;
10550 struct got_object_qid *qid;
10552 err = got_commit_graph_open(&graph, "/", 1);
10553 if (err)
10554 return err;
10556 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10557 check_cancelled, NULL);
10558 if (err)
10559 goto done;
10561 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10562 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10563 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10564 check_cancelled, NULL);
10565 if (err) {
10566 if (err->code == GOT_ERR_ITER_COMPLETED) {
10567 err = got_error_msg(GOT_ERR_ANCESTRY,
10568 "ran out of commits to rebase before "
10569 "youngest common ancestor commit has "
10570 "been reached?!?");
10572 goto done;
10573 } else {
10574 err = check_path_prefix(&parent_id, &commit_id,
10575 path_prefix, path_prefix_errcode, repo);
10576 if (err)
10577 goto done;
10579 err = got_object_qid_alloc(&qid, &commit_id);
10580 if (err)
10581 goto done;
10582 STAILQ_INSERT_HEAD(commits, qid, entry);
10584 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10587 done:
10588 got_commit_graph_close(graph);
10589 return err;
10592 static const struct got_error *
10593 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10595 const struct got_error *err = NULL;
10596 time_t committer_time;
10597 struct tm tm;
10598 char datebuf[11]; /* YYYY-MM-DD + NUL */
10599 char *author0 = NULL, *author, *smallerthan;
10600 char *logmsg0 = NULL, *logmsg, *newline;
10602 committer_time = got_object_commit_get_committer_time(commit);
10603 if (gmtime_r(&committer_time, &tm) == NULL)
10604 return got_error_from_errno("gmtime_r");
10605 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10606 return got_error(GOT_ERR_NO_SPACE);
10608 author0 = strdup(got_object_commit_get_author(commit));
10609 if (author0 == NULL)
10610 return got_error_from_errno("strdup");
10611 author = author0;
10612 smallerthan = strchr(author, '<');
10613 if (smallerthan && smallerthan[1] != '\0')
10614 author = smallerthan + 1;
10615 author[strcspn(author, "@>")] = '\0';
10617 err = got_object_commit_get_logmsg(&logmsg0, commit);
10618 if (err)
10619 goto done;
10620 logmsg = logmsg0;
10621 while (*logmsg == '\n')
10622 logmsg++;
10623 newline = strchr(logmsg, '\n');
10624 if (newline)
10625 *newline = '\0';
10627 if (asprintf(brief_str, "%s %s %s",
10628 datebuf, author, logmsg) == -1)
10629 err = got_error_from_errno("asprintf");
10630 done:
10631 free(author0);
10632 free(logmsg0);
10633 return err;
10636 static const struct got_error *
10637 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10638 struct got_repository *repo)
10640 const struct got_error *err;
10641 char *id_str;
10643 err = got_object_id_str(&id_str, id);
10644 if (err)
10645 return err;
10647 err = got_ref_delete(ref, repo);
10648 if (err)
10649 goto done;
10651 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10652 done:
10653 free(id_str);
10654 return err;
10657 static const struct got_error *
10658 print_backup_ref(const char *branch_name, const char *new_id_str,
10659 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10660 struct got_reflist_object_id_map *refs_idmap,
10661 struct got_repository *repo)
10663 const struct got_error *err = NULL;
10664 struct got_reflist_head *refs;
10665 char *refs_str = NULL;
10666 struct got_object_id *new_commit_id = NULL;
10667 struct got_commit_object *new_commit = NULL;
10668 char *new_commit_brief_str = NULL;
10669 struct got_object_id *yca_id = NULL;
10670 struct got_commit_object *yca_commit = NULL;
10671 char *yca_id_str = NULL, *yca_brief_str = NULL;
10672 char *custom_refs_str;
10674 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10675 return got_error_from_errno("asprintf");
10677 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10678 0, 0, refs_idmap, custom_refs_str, NULL);
10679 if (err)
10680 goto done;
10682 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10683 if (err)
10684 goto done;
10686 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10687 if (refs) {
10688 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10689 if (err)
10690 goto done;
10693 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10694 if (err)
10695 goto done;
10697 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10698 if (err)
10699 goto done;
10701 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10702 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10703 if (err)
10704 goto done;
10706 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10707 refs_str ? " (" : "", refs_str ? refs_str : "",
10708 refs_str ? ")" : "", new_commit_brief_str);
10709 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10710 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10711 free(refs_str);
10712 refs_str = NULL;
10714 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10715 if (err)
10716 goto done;
10718 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10719 if (err)
10720 goto done;
10722 err = got_object_id_str(&yca_id_str, yca_id);
10723 if (err)
10724 goto done;
10726 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10727 if (refs) {
10728 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10729 if (err)
10730 goto done;
10732 printf("history forked at %s%s%s%s\n %s\n",
10733 yca_id_str,
10734 refs_str ? " (" : "", refs_str ? refs_str : "",
10735 refs_str ? ")" : "", yca_brief_str);
10737 done:
10738 free(custom_refs_str);
10739 free(new_commit_id);
10740 free(refs_str);
10741 free(yca_id);
10742 free(yca_id_str);
10743 free(yca_brief_str);
10744 if (new_commit)
10745 got_object_commit_close(new_commit);
10746 if (yca_commit)
10747 got_object_commit_close(yca_commit);
10749 return err;
10752 static const struct got_error *
10753 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10754 struct got_repository *repo)
10756 const struct got_error *err;
10757 struct got_reflist_head refs;
10758 struct got_reflist_entry *re;
10759 char *uuidstr = NULL;
10760 static char msg[160];
10762 TAILQ_INIT(&refs);
10764 err = got_worktree_get_uuid(&uuidstr, worktree);
10765 if (err)
10766 goto done;
10768 err = got_ref_list(&refs, repo, "refs/got/worktree",
10769 got_ref_cmp_by_name, repo);
10770 if (err)
10771 goto done;
10773 TAILQ_FOREACH(re, &refs, entry) {
10774 const char *cmd, *refname, *type;
10776 refname = got_ref_get_name(re->ref);
10778 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10779 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10780 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10781 cmd = "cherrypick";
10782 type = "cherrypicked";
10783 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10784 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10785 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10786 cmd = "backout";
10787 type = "backed-out";
10788 } else
10789 continue;
10791 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10792 continue;
10794 snprintf(msg, sizeof(msg),
10795 "work tree has references created by %s commits which "
10796 "must be removed with 'got %s -X' before running the %s "
10797 "command", type, cmd, caller);
10798 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10799 goto done;
10802 done:
10803 free(uuidstr);
10804 got_ref_list_free(&refs);
10805 return err;
10808 static const struct got_error *
10809 process_backup_refs(const char *backup_ref_prefix,
10810 const char *wanted_branch_name,
10811 int delete, struct got_repository *repo)
10813 const struct got_error *err;
10814 struct got_reflist_head refs, backup_refs;
10815 struct got_reflist_entry *re;
10816 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10817 struct got_object_id *old_commit_id = NULL;
10818 char *branch_name = NULL;
10819 struct got_commit_object *old_commit = NULL;
10820 struct got_reflist_object_id_map *refs_idmap = NULL;
10821 int wanted_branch_found = 0;
10823 TAILQ_INIT(&refs);
10824 TAILQ_INIT(&backup_refs);
10826 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10827 if (err)
10828 return err;
10830 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10831 if (err)
10832 goto done;
10834 if (wanted_branch_name) {
10835 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10836 wanted_branch_name += 11;
10839 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10840 got_ref_cmp_by_commit_timestamp_descending, repo);
10841 if (err)
10842 goto done;
10844 TAILQ_FOREACH(re, &backup_refs, entry) {
10845 const char *refname = got_ref_get_name(re->ref);
10846 char *slash;
10848 err = check_cancelled(NULL);
10849 if (err)
10850 break;
10852 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10853 if (err)
10854 break;
10856 err = got_object_open_as_commit(&old_commit, repo,
10857 old_commit_id);
10858 if (err)
10859 break;
10861 if (strncmp(backup_ref_prefix, refname,
10862 backup_ref_prefix_len) == 0)
10863 refname += backup_ref_prefix_len;
10865 while (refname[0] == '/')
10866 refname++;
10868 branch_name = strdup(refname);
10869 if (branch_name == NULL) {
10870 err = got_error_from_errno("strdup");
10871 break;
10873 slash = strrchr(branch_name, '/');
10874 if (slash) {
10875 *slash = '\0';
10876 refname += strlen(branch_name) + 1;
10879 if (wanted_branch_name == NULL ||
10880 strcmp(wanted_branch_name, branch_name) == 0) {
10881 wanted_branch_found = 1;
10882 if (delete) {
10883 err = delete_backup_ref(re->ref,
10884 old_commit_id, repo);
10885 } else {
10886 err = print_backup_ref(branch_name, refname,
10887 old_commit_id, old_commit, refs_idmap,
10888 repo);
10890 if (err)
10891 break;
10894 free(old_commit_id);
10895 old_commit_id = NULL;
10896 free(branch_name);
10897 branch_name = NULL;
10898 got_object_commit_close(old_commit);
10899 old_commit = NULL;
10902 if (wanted_branch_name && !wanted_branch_found) {
10903 err = got_error_fmt(GOT_ERR_NOT_REF,
10904 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10906 done:
10907 if (refs_idmap)
10908 got_reflist_object_id_map_free(refs_idmap);
10909 got_ref_list_free(&refs);
10910 got_ref_list_free(&backup_refs);
10911 free(old_commit_id);
10912 free(branch_name);
10913 if (old_commit)
10914 got_object_commit_close(old_commit);
10915 return err;
10918 static const struct got_error *
10919 abort_progress(void *arg, unsigned char status, const char *path)
10922 * Unversioned files should not clutter progress output when
10923 * an operation is aborted.
10925 if (status == GOT_STATUS_UNVERSIONED)
10926 return NULL;
10928 return update_progress(arg, status, path);
10931 static const struct got_error *
10932 cmd_rebase(int argc, char *argv[])
10934 const struct got_error *error = NULL;
10935 struct got_worktree *worktree = NULL;
10936 struct got_repository *repo = NULL;
10937 struct got_fileindex *fileindex = NULL;
10938 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10939 struct got_reference *branch = NULL;
10940 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10941 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10942 struct got_object_id *resume_commit_id = NULL;
10943 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10944 struct got_object_id *head_commit_id = NULL;
10945 struct got_reference *head_ref = NULL;
10946 struct got_commit_object *commit = NULL;
10947 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10948 int histedit_in_progress = 0, merge_in_progress = 0;
10949 int create_backup = 1, list_backups = 0, delete_backups = 0;
10950 struct got_object_id_queue commits;
10951 struct got_pathlist_head merged_paths;
10952 const struct got_object_id_queue *parent_ids;
10953 struct got_object_qid *qid, *pid;
10954 struct got_update_progress_arg upa;
10955 int *pack_fds = NULL;
10957 STAILQ_INIT(&commits);
10958 TAILQ_INIT(&merged_paths);
10959 memset(&upa, 0, sizeof(upa));
10961 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10962 switch (ch) {
10963 case 'a':
10964 abort_rebase = 1;
10965 break;
10966 case 'c':
10967 continue_rebase = 1;
10968 break;
10969 case 'l':
10970 list_backups = 1;
10971 break;
10972 case 'X':
10973 delete_backups = 1;
10974 break;
10975 default:
10976 usage_rebase();
10977 /* NOTREACHED */
10981 argc -= optind;
10982 argv += optind;
10984 #ifndef PROFILE
10985 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10986 "unveil", NULL) == -1)
10987 err(1, "pledge");
10988 #endif
10989 if (list_backups) {
10990 if (abort_rebase)
10991 option_conflict('l', 'a');
10992 if (continue_rebase)
10993 option_conflict('l', 'c');
10994 if (delete_backups)
10995 option_conflict('l', 'X');
10996 if (argc != 0 && argc != 1)
10997 usage_rebase();
10998 } else if (delete_backups) {
10999 if (abort_rebase)
11000 option_conflict('X', 'a');
11001 if (continue_rebase)
11002 option_conflict('X', 'c');
11003 if (list_backups)
11004 option_conflict('l', 'X');
11005 if (argc != 0 && argc != 1)
11006 usage_rebase();
11007 } else {
11008 if (abort_rebase && continue_rebase)
11009 usage_rebase();
11010 else if (abort_rebase || continue_rebase) {
11011 if (argc != 0)
11012 usage_rebase();
11013 } else if (argc != 1)
11014 usage_rebase();
11017 cwd = getcwd(NULL, 0);
11018 if (cwd == NULL) {
11019 error = got_error_from_errno("getcwd");
11020 goto done;
11023 error = got_repo_pack_fds_open(&pack_fds);
11024 if (error != NULL)
11025 goto done;
11027 error = got_worktree_open(&worktree, cwd);
11028 if (error) {
11029 if (list_backups || delete_backups) {
11030 if (error->code != GOT_ERR_NOT_WORKTREE)
11031 goto done;
11032 } else {
11033 if (error->code == GOT_ERR_NOT_WORKTREE)
11034 error = wrap_not_worktree_error(error,
11035 "rebase", cwd);
11036 goto done;
11040 error = get_gitconfig_path(&gitconfig_path);
11041 if (error)
11042 goto done;
11043 error = got_repo_open(&repo,
11044 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11045 gitconfig_path, pack_fds);
11046 if (error != NULL)
11047 goto done;
11049 if (worktree != NULL && !list_backups && !delete_backups) {
11050 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11051 if (error)
11052 goto done;
11055 error = get_author(&committer, repo, worktree);
11056 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11057 goto done;
11059 error = apply_unveil(got_repo_get_path(repo), 0,
11060 worktree ? got_worktree_get_root_path(worktree) : NULL);
11061 if (error)
11062 goto done;
11064 if (list_backups || delete_backups) {
11065 error = process_backup_refs(
11066 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11067 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11068 goto done; /* nothing else to do */
11071 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11072 worktree);
11073 if (error)
11074 goto done;
11075 if (histedit_in_progress) {
11076 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11077 goto done;
11080 error = got_worktree_merge_in_progress(&merge_in_progress,
11081 worktree, repo);
11082 if (error)
11083 goto done;
11084 if (merge_in_progress) {
11085 error = got_error(GOT_ERR_MERGE_BUSY);
11086 goto done;
11089 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11090 if (error)
11091 goto done;
11093 if (abort_rebase) {
11094 if (!rebase_in_progress) {
11095 error = got_error(GOT_ERR_NOT_REBASING);
11096 goto done;
11098 error = got_worktree_rebase_continue(&resume_commit_id,
11099 &new_base_branch, &tmp_branch, &branch, &fileindex,
11100 worktree, repo);
11101 if (error)
11102 goto done;
11103 printf("Switching work tree to %s\n",
11104 got_ref_get_symref_target(new_base_branch));
11105 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11106 new_base_branch, abort_progress, &upa);
11107 if (error)
11108 goto done;
11109 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11110 print_merge_progress_stats(&upa);
11111 goto done; /* nothing else to do */
11114 if (continue_rebase) {
11115 if (!rebase_in_progress) {
11116 error = got_error(GOT_ERR_NOT_REBASING);
11117 goto done;
11119 error = got_worktree_rebase_continue(&resume_commit_id,
11120 &new_base_branch, &tmp_branch, &branch, &fileindex,
11121 worktree, repo);
11122 if (error)
11123 goto done;
11125 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11126 committer, resume_commit_id, repo);
11127 if (error)
11128 goto done;
11130 yca_id = got_object_id_dup(resume_commit_id);
11131 if (yca_id == NULL) {
11132 error = got_error_from_errno("got_object_id_dup");
11133 goto done;
11135 } else {
11136 error = got_ref_open(&branch, repo, argv[0], 0);
11137 if (error != NULL)
11138 goto done;
11139 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11140 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11141 "will not rebase a branch which lives outside "
11142 "the \"refs/heads/\" reference namespace");
11143 goto done;
11147 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11148 if (error)
11149 goto done;
11151 if (!continue_rebase) {
11152 struct got_object_id *base_commit_id;
11154 error = got_ref_open(&head_ref, repo,
11155 got_worktree_get_head_ref_name(worktree), 0);
11156 if (error)
11157 goto done;
11158 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11159 if (error)
11160 goto done;
11161 base_commit_id = got_worktree_get_base_commit_id(worktree);
11162 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11163 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11164 goto done;
11167 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11168 base_commit_id, branch_head_commit_id, 1, repo,
11169 check_cancelled, NULL);
11170 if (error) {
11171 if (error->code == GOT_ERR_ANCESTRY) {
11172 error = got_error_msg(GOT_ERR_ANCESTRY,
11173 "specified branch shares no common "
11174 "ancestry with work tree's branch");
11176 goto done;
11179 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11180 if (error) {
11181 if (error->code != GOT_ERR_ANCESTRY)
11182 goto done;
11183 error = NULL;
11184 } else {
11185 struct got_pathlist_head paths;
11186 printf("%s is already based on %s\n",
11187 got_ref_get_name(branch),
11188 got_worktree_get_head_ref_name(worktree));
11189 error = switch_head_ref(branch, branch_head_commit_id,
11190 worktree, repo);
11191 if (error)
11192 goto done;
11193 error = got_worktree_set_base_commit_id(worktree, repo,
11194 branch_head_commit_id);
11195 if (error)
11196 goto done;
11197 TAILQ_INIT(&paths);
11198 error = got_pathlist_append(&paths, "", NULL);
11199 if (error)
11200 goto done;
11201 error = got_worktree_checkout_files(worktree,
11202 &paths, repo, update_progress, &upa,
11203 check_cancelled, NULL);
11204 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11205 if (error)
11206 goto done;
11207 if (upa.did_something) {
11208 char *id_str;
11209 error = got_object_id_str(&id_str,
11210 branch_head_commit_id);
11211 if (error)
11212 goto done;
11213 printf("Updated to %s: %s\n",
11214 got_worktree_get_head_ref_name(worktree),
11215 id_str);
11216 free(id_str);
11217 } else
11218 printf("Already up-to-date\n");
11219 print_update_progress_stats(&upa);
11220 goto done;
11224 commit_id = branch_head_commit_id;
11225 error = got_object_open_as_commit(&commit, repo, commit_id);
11226 if (error)
11227 goto done;
11229 parent_ids = got_object_commit_get_parent_ids(commit);
11230 pid = STAILQ_FIRST(parent_ids);
11231 if (pid) {
11232 error = collect_commits(&commits, commit_id, &pid->id,
11233 yca_id, got_worktree_get_path_prefix(worktree),
11234 GOT_ERR_REBASE_PATH, repo);
11235 if (error)
11236 goto done;
11239 got_object_commit_close(commit);
11240 commit = NULL;
11242 if (!continue_rebase) {
11243 error = got_worktree_rebase_prepare(&new_base_branch,
11244 &tmp_branch, &fileindex, worktree, branch, repo);
11245 if (error)
11246 goto done;
11249 if (STAILQ_EMPTY(&commits)) {
11250 if (continue_rebase) {
11251 error = rebase_complete(worktree, fileindex,
11252 branch, tmp_branch, repo, create_backup);
11253 goto done;
11254 } else {
11255 /* Fast-forward the reference of the branch. */
11256 struct got_object_id *new_head_commit_id;
11257 char *id_str;
11258 error = got_ref_resolve(&new_head_commit_id, repo,
11259 new_base_branch);
11260 if (error)
11261 goto done;
11262 error = got_object_id_str(&id_str, new_head_commit_id);
11263 if (error)
11264 goto done;
11265 printf("Forwarding %s to commit %s\n",
11266 got_ref_get_name(branch), id_str);
11267 free(id_str);
11268 error = got_ref_change_ref(branch,
11269 new_head_commit_id);
11270 if (error)
11271 goto done;
11272 /* No backup needed since objects did not change. */
11273 create_backup = 0;
11277 pid = NULL;
11278 STAILQ_FOREACH(qid, &commits, entry) {
11280 commit_id = &qid->id;
11281 parent_id = pid ? &pid->id : yca_id;
11282 pid = qid;
11284 memset(&upa, 0, sizeof(upa));
11285 error = got_worktree_rebase_merge_files(&merged_paths,
11286 worktree, fileindex, parent_id, commit_id, repo,
11287 update_progress, &upa, check_cancelled, NULL);
11288 if (error)
11289 goto done;
11291 print_merge_progress_stats(&upa);
11292 if (upa.conflicts > 0 || upa.missing > 0 ||
11293 upa.not_deleted > 0 || upa.unversioned > 0) {
11294 if (upa.conflicts > 0) {
11295 error = show_rebase_merge_conflict(&qid->id,
11296 repo);
11297 if (error)
11298 goto done;
11300 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11301 break;
11304 error = rebase_commit(&merged_paths, worktree, fileindex,
11305 tmp_branch, committer, commit_id, repo);
11306 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11307 if (error)
11308 goto done;
11311 if (upa.conflicts > 0 || upa.missing > 0 ||
11312 upa.not_deleted > 0 || upa.unversioned > 0) {
11313 error = got_worktree_rebase_postpone(worktree, fileindex);
11314 if (error)
11315 goto done;
11316 if (upa.conflicts > 0 && upa.missing == 0 &&
11317 upa.not_deleted == 0 && upa.unversioned == 0) {
11318 error = got_error_msg(GOT_ERR_CONFLICTS,
11319 "conflicts must be resolved before rebasing "
11320 "can continue");
11321 } else if (upa.conflicts > 0) {
11322 error = got_error_msg(GOT_ERR_CONFLICTS,
11323 "conflicts must be resolved before rebasing "
11324 "can continue; changes destined for some "
11325 "files were not yet merged and should be "
11326 "merged manually if required before the "
11327 "rebase operation is continued");
11328 } else {
11329 error = got_error_msg(GOT_ERR_CONFLICTS,
11330 "changes destined for some files were not "
11331 "yet merged and should be merged manually "
11332 "if required before the rebase operation "
11333 "is continued");
11335 } else
11336 error = rebase_complete(worktree, fileindex, branch,
11337 tmp_branch, repo, create_backup);
11338 done:
11339 free(cwd);
11340 free(committer);
11341 free(gitconfig_path);
11342 got_object_id_queue_free(&commits);
11343 free(branch_head_commit_id);
11344 free(resume_commit_id);
11345 free(head_commit_id);
11346 free(yca_id);
11347 if (commit)
11348 got_object_commit_close(commit);
11349 if (branch)
11350 got_ref_close(branch);
11351 if (new_base_branch)
11352 got_ref_close(new_base_branch);
11353 if (tmp_branch)
11354 got_ref_close(tmp_branch);
11355 if (head_ref)
11356 got_ref_close(head_ref);
11357 if (worktree)
11358 got_worktree_close(worktree);
11359 if (repo) {
11360 const struct got_error *close_err = got_repo_close(repo);
11361 if (error == NULL)
11362 error = close_err;
11364 if (pack_fds) {
11365 const struct got_error *pack_err =
11366 got_repo_pack_fds_close(pack_fds);
11367 if (error == NULL)
11368 error = pack_err;
11370 return error;
11373 __dead static void
11374 usage_histedit(void)
11376 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11377 "[branch]\n", getprogname());
11378 exit(1);
11381 #define GOT_HISTEDIT_PICK 'p'
11382 #define GOT_HISTEDIT_EDIT 'e'
11383 #define GOT_HISTEDIT_FOLD 'f'
11384 #define GOT_HISTEDIT_DROP 'd'
11385 #define GOT_HISTEDIT_MESG 'm'
11387 static const struct got_histedit_cmd {
11388 unsigned char code;
11389 const char *name;
11390 const char *desc;
11391 } got_histedit_cmds[] = {
11392 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11393 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11394 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11395 "be used" },
11396 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11397 { GOT_HISTEDIT_MESG, "mesg",
11398 "single-line log message for commit above (open editor if empty)" },
11401 struct got_histedit_list_entry {
11402 TAILQ_ENTRY(got_histedit_list_entry) entry;
11403 struct got_object_id *commit_id;
11404 const struct got_histedit_cmd *cmd;
11405 char *logmsg;
11407 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11409 static const struct got_error *
11410 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11411 FILE *f, struct got_repository *repo)
11413 const struct got_error *err = NULL;
11414 char *logmsg = NULL, *id_str = NULL;
11415 struct got_commit_object *commit = NULL;
11416 int n;
11418 err = got_object_open_as_commit(&commit, repo, commit_id);
11419 if (err)
11420 goto done;
11422 err = get_short_logmsg(&logmsg, 34, commit);
11423 if (err)
11424 goto done;
11426 err = got_object_id_str(&id_str, commit_id);
11427 if (err)
11428 goto done;
11430 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11431 if (n < 0)
11432 err = got_ferror(f, GOT_ERR_IO);
11433 done:
11434 if (commit)
11435 got_object_commit_close(commit);
11436 free(id_str);
11437 free(logmsg);
11438 return err;
11441 static const struct got_error *
11442 histedit_write_commit_list(struct got_object_id_queue *commits,
11443 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11444 int edit_only, struct got_repository *repo)
11446 const struct got_error *err = NULL;
11447 struct got_object_qid *qid;
11448 const char *histedit_cmd = NULL;
11450 if (STAILQ_EMPTY(commits))
11451 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11453 STAILQ_FOREACH(qid, commits, entry) {
11454 histedit_cmd = got_histedit_cmds[0].name;
11455 if (drop_only)
11456 histedit_cmd = "drop";
11457 else if (edit_only)
11458 histedit_cmd = "edit";
11459 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11460 histedit_cmd = "fold";
11461 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11462 if (err)
11463 break;
11464 if (edit_logmsg_only) {
11465 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11466 if (n < 0) {
11467 err = got_ferror(f, GOT_ERR_IO);
11468 break;
11473 return err;
11476 static const struct got_error *
11477 write_cmd_list(FILE *f, const char *branch_name,
11478 struct got_object_id_queue *commits)
11480 const struct got_error *err = NULL;
11481 size_t i;
11482 int n;
11483 char *id_str;
11484 struct got_object_qid *qid;
11486 qid = STAILQ_FIRST(commits);
11487 err = got_object_id_str(&id_str, &qid->id);
11488 if (err)
11489 return err;
11491 n = fprintf(f,
11492 "# Editing the history of branch '%s' starting at\n"
11493 "# commit %s\n"
11494 "# Commits will be processed in order from top to "
11495 "bottom of this file.\n", branch_name, id_str);
11496 if (n < 0) {
11497 err = got_ferror(f, GOT_ERR_IO);
11498 goto done;
11501 n = fprintf(f, "# Available histedit commands:\n");
11502 if (n < 0) {
11503 err = got_ferror(f, GOT_ERR_IO);
11504 goto done;
11507 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11508 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11509 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11510 cmd->desc);
11511 if (n < 0) {
11512 err = got_ferror(f, GOT_ERR_IO);
11513 break;
11516 done:
11517 free(id_str);
11518 return err;
11521 static const struct got_error *
11522 histedit_syntax_error(int lineno)
11524 static char msg[42];
11525 int ret;
11527 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11528 lineno);
11529 if (ret < 0 || (size_t)ret >= sizeof(msg))
11530 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11532 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11535 static const struct got_error *
11536 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11537 char *logmsg, struct got_repository *repo)
11539 const struct got_error *err;
11540 struct got_commit_object *folded_commit = NULL;
11541 char *id_str, *folded_logmsg = NULL;
11543 err = got_object_id_str(&id_str, hle->commit_id);
11544 if (err)
11545 return err;
11547 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11548 if (err)
11549 goto done;
11551 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11552 if (err)
11553 goto done;
11554 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11555 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11556 folded_logmsg) == -1) {
11557 err = got_error_from_errno("asprintf");
11559 done:
11560 if (folded_commit)
11561 got_object_commit_close(folded_commit);
11562 free(id_str);
11563 free(folded_logmsg);
11564 return err;
11567 static struct got_histedit_list_entry *
11568 get_folded_commits(struct got_histedit_list_entry *hle)
11570 struct got_histedit_list_entry *prev, *folded = NULL;
11572 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11573 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11574 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11575 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11576 folded = prev;
11577 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11580 return folded;
11583 static const struct got_error *
11584 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11585 struct got_repository *repo)
11587 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11588 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11589 const struct got_error *err = NULL;
11590 struct got_commit_object *commit = NULL;
11591 int logmsg_len;
11592 int fd;
11593 struct got_histedit_list_entry *folded = NULL;
11595 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11596 if (err)
11597 return err;
11599 folded = get_folded_commits(hle);
11600 if (folded) {
11601 while (folded != hle) {
11602 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11603 folded = TAILQ_NEXT(folded, entry);
11604 continue;
11606 err = append_folded_commit_msg(&new_msg, folded,
11607 logmsg, repo);
11608 if (err)
11609 goto done;
11610 free(logmsg);
11611 logmsg = new_msg;
11612 folded = TAILQ_NEXT(folded, entry);
11616 err = got_object_id_str(&id_str, hle->commit_id);
11617 if (err)
11618 goto done;
11619 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11620 if (err)
11621 goto done;
11622 logmsg_len = asprintf(&new_msg,
11623 "%s\n# original log message of commit %s: %s",
11624 logmsg ? logmsg : "", id_str, orig_logmsg);
11625 if (logmsg_len == -1) {
11626 err = got_error_from_errno("asprintf");
11627 goto done;
11629 free(logmsg);
11630 logmsg = new_msg;
11632 err = got_object_id_str(&id_str, hle->commit_id);
11633 if (err)
11634 goto done;
11636 err = got_opentemp_named_fd(&logmsg_path, &fd,
11637 GOT_TMPDIR_STR "/got-logmsg", "");
11638 if (err)
11639 goto done;
11641 write(fd, logmsg, logmsg_len);
11642 close(fd);
11644 err = get_editor(&editor);
11645 if (err)
11646 goto done;
11648 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11649 logmsg_len, 0);
11650 if (err) {
11651 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11652 goto done;
11653 err = NULL;
11654 hle->logmsg = strdup(new_msg);
11655 if (hle->logmsg == NULL)
11656 err = got_error_from_errno("strdup");
11658 done:
11659 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11660 err = got_error_from_errno2("unlink", logmsg_path);
11661 free(logmsg_path);
11662 free(logmsg);
11663 free(orig_logmsg);
11664 free(editor);
11665 if (commit)
11666 got_object_commit_close(commit);
11667 return err;
11670 static const struct got_error *
11671 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11672 FILE *f, struct got_repository *repo)
11674 const struct got_error *err = NULL;
11675 char *line = NULL, *p, *end;
11676 size_t i, size;
11677 ssize_t len;
11678 int lineno = 0, lastcmd = -1;
11679 const struct got_histedit_cmd *cmd;
11680 struct got_object_id *commit_id = NULL;
11681 struct got_histedit_list_entry *hle = NULL;
11683 for (;;) {
11684 len = getline(&line, &size, f);
11685 if (len == -1) {
11686 const struct got_error *getline_err;
11687 if (feof(f))
11688 break;
11689 getline_err = got_error_from_errno("getline");
11690 err = got_ferror(f, getline_err->code);
11691 break;
11693 lineno++;
11694 p = line;
11695 while (isspace((unsigned char)p[0]))
11696 p++;
11697 if (p[0] == '#' || p[0] == '\0') {
11698 free(line);
11699 line = NULL;
11700 continue;
11702 cmd = NULL;
11703 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11704 cmd = &got_histedit_cmds[i];
11705 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11706 isspace((unsigned char)p[strlen(cmd->name)])) {
11707 p += strlen(cmd->name);
11708 break;
11710 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11711 p++;
11712 break;
11715 if (i == nitems(got_histedit_cmds)) {
11716 err = histedit_syntax_error(lineno);
11717 break;
11719 while (isspace((unsigned char)p[0]))
11720 p++;
11721 if (cmd->code == GOT_HISTEDIT_MESG) {
11722 if (lastcmd != GOT_HISTEDIT_PICK &&
11723 lastcmd != GOT_HISTEDIT_EDIT) {
11724 err = got_error(GOT_ERR_HISTEDIT_CMD);
11725 break;
11727 if (p[0] == '\0') {
11728 err = histedit_edit_logmsg(hle, repo);
11729 if (err)
11730 break;
11731 } else {
11732 hle->logmsg = strdup(p);
11733 if (hle->logmsg == NULL) {
11734 err = got_error_from_errno("strdup");
11735 break;
11738 free(line);
11739 line = NULL;
11740 lastcmd = cmd->code;
11741 continue;
11742 } else {
11743 end = p;
11744 while (end[0] && !isspace((unsigned char)end[0]))
11745 end++;
11746 *end = '\0';
11748 err = got_object_resolve_id_str(&commit_id, repo, p);
11749 if (err) {
11750 /* override error code */
11751 err = histedit_syntax_error(lineno);
11752 break;
11755 hle = malloc(sizeof(*hle));
11756 if (hle == NULL) {
11757 err = got_error_from_errno("malloc");
11758 break;
11760 hle->cmd = cmd;
11761 hle->commit_id = commit_id;
11762 hle->logmsg = NULL;
11763 commit_id = NULL;
11764 free(line);
11765 line = NULL;
11766 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11767 lastcmd = cmd->code;
11770 free(line);
11771 free(commit_id);
11772 return err;
11775 static const struct got_error *
11776 histedit_check_script(struct got_histedit_list *histedit_cmds,
11777 struct got_object_id_queue *commits, struct got_repository *repo)
11779 const struct got_error *err = NULL;
11780 struct got_object_qid *qid;
11781 struct got_histedit_list_entry *hle;
11782 static char msg[92];
11783 char *id_str;
11785 if (TAILQ_EMPTY(histedit_cmds))
11786 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11787 "histedit script contains no commands");
11788 if (STAILQ_EMPTY(commits))
11789 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11791 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11792 struct got_histedit_list_entry *hle2;
11793 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11794 if (hle == hle2)
11795 continue;
11796 if (got_object_id_cmp(hle->commit_id,
11797 hle2->commit_id) != 0)
11798 continue;
11799 err = got_object_id_str(&id_str, hle->commit_id);
11800 if (err)
11801 return err;
11802 snprintf(msg, sizeof(msg), "commit %s is listed "
11803 "more than once in histedit script", id_str);
11804 free(id_str);
11805 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11809 STAILQ_FOREACH(qid, commits, entry) {
11810 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11811 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11812 break;
11814 if (hle == NULL) {
11815 err = got_object_id_str(&id_str, &qid->id);
11816 if (err)
11817 return err;
11818 snprintf(msg, sizeof(msg),
11819 "commit %s missing from histedit script", id_str);
11820 free(id_str);
11821 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11825 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11826 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11827 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11828 "last commit in histedit script cannot be folded");
11830 return NULL;
11833 static const struct got_error *
11834 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11835 const char *path, struct got_object_id_queue *commits,
11836 struct got_repository *repo)
11838 const struct got_error *err = NULL;
11839 char *editor;
11840 FILE *f = NULL;
11842 err = get_editor(&editor);
11843 if (err)
11844 return err;
11846 if (spawn_editor(editor, path) == -1) {
11847 err = got_error_from_errno("failed spawning editor");
11848 goto done;
11851 f = fopen(path, "re");
11852 if (f == NULL) {
11853 err = got_error_from_errno("fopen");
11854 goto done;
11856 err = histedit_parse_list(histedit_cmds, f, repo);
11857 if (err)
11858 goto done;
11860 err = histedit_check_script(histedit_cmds, commits, repo);
11861 done:
11862 if (f && fclose(f) == EOF && err == NULL)
11863 err = got_error_from_errno("fclose");
11864 free(editor);
11865 return err;
11868 static const struct got_error *
11869 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11870 struct got_object_id_queue *, const char *, const char *,
11871 struct got_repository *);
11873 static const struct got_error *
11874 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11875 struct got_object_id_queue *commits, const char *branch_name,
11876 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11877 struct got_repository *repo)
11879 const struct got_error *err;
11880 FILE *f = NULL;
11881 char *path = NULL;
11883 err = got_opentemp_named(&path, &f, "got-histedit", "");
11884 if (err)
11885 return err;
11887 err = write_cmd_list(f, branch_name, commits);
11888 if (err)
11889 goto done;
11891 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11892 fold_only, drop_only, edit_only, repo);
11893 if (err)
11894 goto done;
11896 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11897 rewind(f);
11898 err = histedit_parse_list(histedit_cmds, f, repo);
11899 } else {
11900 if (fclose(f) == EOF) {
11901 err = got_error_from_errno("fclose");
11902 goto done;
11904 f = NULL;
11905 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11906 if (err) {
11907 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11908 err->code != GOT_ERR_HISTEDIT_CMD)
11909 goto done;
11910 err = histedit_edit_list_retry(histedit_cmds, err,
11911 commits, path, branch_name, repo);
11914 done:
11915 if (f && fclose(f) == EOF && err == NULL)
11916 err = got_error_from_errno("fclose");
11917 if (path && unlink(path) != 0 && err == NULL)
11918 err = got_error_from_errno2("unlink", path);
11919 free(path);
11920 return err;
11923 static const struct got_error *
11924 histedit_save_list(struct got_histedit_list *histedit_cmds,
11925 struct got_worktree *worktree, struct got_repository *repo)
11927 const struct got_error *err = NULL;
11928 char *path = NULL;
11929 FILE *f = NULL;
11930 struct got_histedit_list_entry *hle;
11931 struct got_commit_object *commit = NULL;
11933 err = got_worktree_get_histedit_script_path(&path, worktree);
11934 if (err)
11935 return err;
11937 f = fopen(path, "we");
11938 if (f == NULL) {
11939 err = got_error_from_errno2("fopen", path);
11940 goto done;
11942 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11943 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11944 repo);
11945 if (err)
11946 break;
11948 if (hle->logmsg) {
11949 int n = fprintf(f, "%c %s\n",
11950 GOT_HISTEDIT_MESG, hle->logmsg);
11951 if (n < 0) {
11952 err = got_ferror(f, GOT_ERR_IO);
11953 break;
11957 done:
11958 if (f && fclose(f) == EOF && err == NULL)
11959 err = got_error_from_errno("fclose");
11960 free(path);
11961 if (commit)
11962 got_object_commit_close(commit);
11963 return err;
11966 static void
11967 histedit_free_list(struct got_histedit_list *histedit_cmds)
11969 struct got_histedit_list_entry *hle;
11971 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11972 TAILQ_REMOVE(histedit_cmds, hle, entry);
11973 free(hle);
11977 static const struct got_error *
11978 histedit_load_list(struct got_histedit_list *histedit_cmds,
11979 const char *path, struct got_repository *repo)
11981 const struct got_error *err = NULL;
11982 FILE *f = NULL;
11984 f = fopen(path, "re");
11985 if (f == NULL) {
11986 err = got_error_from_errno2("fopen", path);
11987 goto done;
11990 err = histedit_parse_list(histedit_cmds, f, repo);
11991 done:
11992 if (f && fclose(f) == EOF && err == NULL)
11993 err = got_error_from_errno("fclose");
11994 return err;
11997 static const struct got_error *
11998 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11999 const struct got_error *edit_err, struct got_object_id_queue *commits,
12000 const char *path, const char *branch_name, struct got_repository *repo)
12002 const struct got_error *err = NULL, *prev_err = edit_err;
12003 int resp = ' ';
12005 while (resp != 'c' && resp != 'r' && resp != 'a') {
12006 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12007 "or (a)bort: ", getprogname(), prev_err->msg);
12008 resp = getchar();
12009 if (resp == '\n')
12010 resp = getchar();
12011 if (resp == 'c') {
12012 histedit_free_list(histedit_cmds);
12013 err = histedit_run_editor(histedit_cmds, path, commits,
12014 repo);
12015 if (err) {
12016 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12017 err->code != GOT_ERR_HISTEDIT_CMD)
12018 break;
12019 prev_err = err;
12020 resp = ' ';
12021 continue;
12023 break;
12024 } else if (resp == 'r') {
12025 histedit_free_list(histedit_cmds);
12026 err = histedit_edit_script(histedit_cmds,
12027 commits, branch_name, 0, 0, 0, 0, repo);
12028 if (err) {
12029 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12030 err->code != GOT_ERR_HISTEDIT_CMD)
12031 break;
12032 prev_err = err;
12033 resp = ' ';
12034 continue;
12036 break;
12037 } else if (resp == 'a') {
12038 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12039 break;
12040 } else
12041 printf("invalid response '%c'\n", resp);
12044 return err;
12047 static const struct got_error *
12048 histedit_complete(struct got_worktree *worktree,
12049 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12050 struct got_reference *branch, struct got_repository *repo)
12052 printf("Switching work tree to %s\n",
12053 got_ref_get_symref_target(branch));
12054 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12055 branch, repo);
12058 static const struct got_error *
12059 show_histedit_progress(struct got_commit_object *commit,
12060 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12062 const struct got_error *err;
12063 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12065 err = got_object_id_str(&old_id_str, hle->commit_id);
12066 if (err)
12067 goto done;
12069 if (new_id) {
12070 err = got_object_id_str(&new_id_str, new_id);
12071 if (err)
12072 goto done;
12075 old_id_str[12] = '\0';
12076 if (new_id_str)
12077 new_id_str[12] = '\0';
12079 if (hle->logmsg) {
12080 logmsg = strdup(hle->logmsg);
12081 if (logmsg == NULL) {
12082 err = got_error_from_errno("strdup");
12083 goto done;
12085 trim_logmsg(logmsg, 42);
12086 } else {
12087 err = get_short_logmsg(&logmsg, 42, commit);
12088 if (err)
12089 goto done;
12092 switch (hle->cmd->code) {
12093 case GOT_HISTEDIT_PICK:
12094 case GOT_HISTEDIT_EDIT:
12095 printf("%s -> %s: %s\n", old_id_str,
12096 new_id_str ? new_id_str : "no-op change", logmsg);
12097 break;
12098 case GOT_HISTEDIT_DROP:
12099 case GOT_HISTEDIT_FOLD:
12100 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12101 logmsg);
12102 break;
12103 default:
12104 break;
12106 done:
12107 free(old_id_str);
12108 free(new_id_str);
12109 return err;
12112 static const struct got_error *
12113 histedit_commit(struct got_pathlist_head *merged_paths,
12114 struct got_worktree *worktree, struct got_fileindex *fileindex,
12115 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12116 const char *committer, struct got_repository *repo)
12118 const struct got_error *err;
12119 struct got_commit_object *commit;
12120 struct got_object_id *new_commit_id;
12122 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12123 && hle->logmsg == NULL) {
12124 err = histedit_edit_logmsg(hle, repo);
12125 if (err)
12126 return err;
12129 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12130 if (err)
12131 return err;
12133 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12134 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12135 hle->logmsg, repo);
12136 if (err) {
12137 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12138 goto done;
12139 err = show_histedit_progress(commit, hle, NULL);
12140 } else {
12141 err = show_histedit_progress(commit, hle, new_commit_id);
12142 free(new_commit_id);
12144 done:
12145 got_object_commit_close(commit);
12146 return err;
12149 static const struct got_error *
12150 histedit_skip_commit(struct got_histedit_list_entry *hle,
12151 struct got_worktree *worktree, struct got_repository *repo)
12153 const struct got_error *error;
12154 struct got_commit_object *commit;
12156 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12157 repo);
12158 if (error)
12159 return error;
12161 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12162 if (error)
12163 return error;
12165 error = show_histedit_progress(commit, hle, NULL);
12166 got_object_commit_close(commit);
12167 return error;
12170 static const struct got_error *
12171 check_local_changes(void *arg, unsigned char status,
12172 unsigned char staged_status, const char *path,
12173 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12174 struct got_object_id *commit_id, int dirfd, const char *de_name)
12176 int *have_local_changes = arg;
12178 switch (status) {
12179 case GOT_STATUS_ADD:
12180 case GOT_STATUS_DELETE:
12181 case GOT_STATUS_MODIFY:
12182 case GOT_STATUS_CONFLICT:
12183 *have_local_changes = 1;
12184 return got_error(GOT_ERR_CANCELLED);
12185 default:
12186 break;
12189 switch (staged_status) {
12190 case GOT_STATUS_ADD:
12191 case GOT_STATUS_DELETE:
12192 case GOT_STATUS_MODIFY:
12193 *have_local_changes = 1;
12194 return got_error(GOT_ERR_CANCELLED);
12195 default:
12196 break;
12199 return NULL;
12202 static const struct got_error *
12203 cmd_histedit(int argc, char *argv[])
12205 const struct got_error *error = NULL;
12206 struct got_worktree *worktree = NULL;
12207 struct got_fileindex *fileindex = NULL;
12208 struct got_repository *repo = NULL;
12209 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12210 struct got_reference *branch = NULL;
12211 struct got_reference *tmp_branch = NULL;
12212 struct got_object_id *resume_commit_id = NULL;
12213 struct got_object_id *base_commit_id = NULL;
12214 struct got_object_id *head_commit_id = NULL;
12215 struct got_commit_object *commit = NULL;
12216 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12217 struct got_update_progress_arg upa;
12218 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12219 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12220 int list_backups = 0, delete_backups = 0;
12221 const char *edit_script_path = NULL;
12222 struct got_object_id_queue commits;
12223 struct got_pathlist_head merged_paths;
12224 const struct got_object_id_queue *parent_ids;
12225 struct got_object_qid *pid;
12226 struct got_histedit_list histedit_cmds;
12227 struct got_histedit_list_entry *hle;
12228 int *pack_fds = NULL;
12230 STAILQ_INIT(&commits);
12231 TAILQ_INIT(&histedit_cmds);
12232 TAILQ_INIT(&merged_paths);
12233 memset(&upa, 0, sizeof(upa));
12235 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12236 switch (ch) {
12237 case 'a':
12238 abort_edit = 1;
12239 break;
12240 case 'c':
12241 continue_edit = 1;
12242 break;
12243 case 'd':
12244 drop_only = 1;
12245 break;
12246 case 'e':
12247 edit_only = 1;
12248 break;
12249 case 'F':
12250 edit_script_path = optarg;
12251 break;
12252 case 'f':
12253 fold_only = 1;
12254 break;
12255 case 'l':
12256 list_backups = 1;
12257 break;
12258 case 'm':
12259 edit_logmsg_only = 1;
12260 break;
12261 case 'X':
12262 delete_backups = 1;
12263 break;
12264 default:
12265 usage_histedit();
12266 /* NOTREACHED */
12270 argc -= optind;
12271 argv += optind;
12273 #ifndef PROFILE
12274 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12275 "unveil", NULL) == -1)
12276 err(1, "pledge");
12277 #endif
12278 if (abort_edit && continue_edit)
12279 option_conflict('a', 'c');
12280 if (edit_script_path && edit_logmsg_only)
12281 option_conflict('F', 'm');
12282 if (abort_edit && edit_logmsg_only)
12283 option_conflict('a', 'm');
12284 if (continue_edit && edit_logmsg_only)
12285 option_conflict('c', 'm');
12286 if (abort_edit && fold_only)
12287 option_conflict('a', 'f');
12288 if (continue_edit && fold_only)
12289 option_conflict('c', 'f');
12290 if (fold_only && edit_logmsg_only)
12291 option_conflict('f', 'm');
12292 if (edit_script_path && fold_only)
12293 option_conflict('F', 'f');
12294 if (abort_edit && edit_only)
12295 option_conflict('a', 'e');
12296 if (continue_edit && edit_only)
12297 option_conflict('c', 'e');
12298 if (edit_only && edit_logmsg_only)
12299 option_conflict('e', 'm');
12300 if (edit_script_path && edit_only)
12301 option_conflict('F', 'e');
12302 if (fold_only && edit_only)
12303 option_conflict('f', 'e');
12304 if (drop_only && abort_edit)
12305 option_conflict('d', 'a');
12306 if (drop_only && continue_edit)
12307 option_conflict('d', 'c');
12308 if (drop_only && edit_logmsg_only)
12309 option_conflict('d', 'm');
12310 if (drop_only && edit_only)
12311 option_conflict('d', 'e');
12312 if (drop_only && edit_script_path)
12313 option_conflict('d', 'F');
12314 if (drop_only && fold_only)
12315 option_conflict('d', 'f');
12316 if (list_backups) {
12317 if (abort_edit)
12318 option_conflict('l', 'a');
12319 if (continue_edit)
12320 option_conflict('l', 'c');
12321 if (edit_script_path)
12322 option_conflict('l', 'F');
12323 if (edit_logmsg_only)
12324 option_conflict('l', 'm');
12325 if (drop_only)
12326 option_conflict('l', 'd');
12327 if (fold_only)
12328 option_conflict('l', 'f');
12329 if (edit_only)
12330 option_conflict('l', 'e');
12331 if (delete_backups)
12332 option_conflict('l', 'X');
12333 if (argc != 0 && argc != 1)
12334 usage_histedit();
12335 } else if (delete_backups) {
12336 if (abort_edit)
12337 option_conflict('X', 'a');
12338 if (continue_edit)
12339 option_conflict('X', 'c');
12340 if (drop_only)
12341 option_conflict('X', 'd');
12342 if (edit_script_path)
12343 option_conflict('X', 'F');
12344 if (edit_logmsg_only)
12345 option_conflict('X', 'm');
12346 if (fold_only)
12347 option_conflict('X', 'f');
12348 if (edit_only)
12349 option_conflict('X', 'e');
12350 if (list_backups)
12351 option_conflict('X', 'l');
12352 if (argc != 0 && argc != 1)
12353 usage_histedit();
12354 } else if (argc != 0)
12355 usage_histedit();
12358 * This command cannot apply unveil(2) in all cases because the
12359 * user may choose to run an editor to edit the histedit script
12360 * and to edit individual commit log messages.
12361 * unveil(2) traverses exec(2); if an editor is used we have to
12362 * apply unveil after edit script and log messages have been written.
12363 * XXX TODO: Make use of unveil(2) where possible.
12366 cwd = getcwd(NULL, 0);
12367 if (cwd == NULL) {
12368 error = got_error_from_errno("getcwd");
12369 goto done;
12372 error = got_repo_pack_fds_open(&pack_fds);
12373 if (error != NULL)
12374 goto done;
12376 error = got_worktree_open(&worktree, cwd);
12377 if (error) {
12378 if (list_backups || delete_backups) {
12379 if (error->code != GOT_ERR_NOT_WORKTREE)
12380 goto done;
12381 } else {
12382 if (error->code == GOT_ERR_NOT_WORKTREE)
12383 error = wrap_not_worktree_error(error,
12384 "histedit", cwd);
12385 goto done;
12389 if (list_backups || delete_backups) {
12390 error = got_repo_open(&repo,
12391 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12392 NULL, pack_fds);
12393 if (error != NULL)
12394 goto done;
12395 error = apply_unveil(got_repo_get_path(repo), 0,
12396 worktree ? got_worktree_get_root_path(worktree) : NULL);
12397 if (error)
12398 goto done;
12399 error = process_backup_refs(
12400 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12401 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12402 goto done; /* nothing else to do */
12405 error = get_gitconfig_path(&gitconfig_path);
12406 if (error)
12407 goto done;
12408 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12409 gitconfig_path, pack_fds);
12410 if (error != NULL)
12411 goto done;
12413 if (worktree != NULL && !list_backups && !delete_backups) {
12414 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12415 if (error)
12416 goto done;
12419 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12420 if (error)
12421 goto done;
12422 if (rebase_in_progress) {
12423 error = got_error(GOT_ERR_REBASING);
12424 goto done;
12427 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12428 repo);
12429 if (error)
12430 goto done;
12431 if (merge_in_progress) {
12432 error = got_error(GOT_ERR_MERGE_BUSY);
12433 goto done;
12436 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12437 if (error)
12438 goto done;
12440 if (edit_in_progress && edit_logmsg_only) {
12441 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12442 "histedit operation is in progress in this "
12443 "work tree and must be continued or aborted "
12444 "before the -m option can be used");
12445 goto done;
12447 if (edit_in_progress && drop_only) {
12448 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12449 "histedit operation is in progress in this "
12450 "work tree and must be continued or aborted "
12451 "before the -d option can be used");
12452 goto done;
12454 if (edit_in_progress && fold_only) {
12455 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12456 "histedit operation is in progress in this "
12457 "work tree and must be continued or aborted "
12458 "before the -f option can be used");
12459 goto done;
12461 if (edit_in_progress && edit_only) {
12462 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12463 "histedit operation is in progress in this "
12464 "work tree and must be continued or aborted "
12465 "before the -e option can be used");
12466 goto done;
12469 if (edit_in_progress && abort_edit) {
12470 error = got_worktree_histedit_continue(&resume_commit_id,
12471 &tmp_branch, &branch, &base_commit_id, &fileindex,
12472 worktree, repo);
12473 if (error)
12474 goto done;
12475 printf("Switching work tree to %s\n",
12476 got_ref_get_symref_target(branch));
12477 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12478 branch, base_commit_id, abort_progress, &upa);
12479 if (error)
12480 goto done;
12481 printf("Histedit of %s aborted\n",
12482 got_ref_get_symref_target(branch));
12483 print_merge_progress_stats(&upa);
12484 goto done; /* nothing else to do */
12485 } else if (abort_edit) {
12486 error = got_error(GOT_ERR_NOT_HISTEDIT);
12487 goto done;
12490 error = get_author(&committer, repo, worktree);
12491 if (error)
12492 goto done;
12494 if (continue_edit) {
12495 char *path;
12497 if (!edit_in_progress) {
12498 error = got_error(GOT_ERR_NOT_HISTEDIT);
12499 goto done;
12502 error = got_worktree_get_histedit_script_path(&path, worktree);
12503 if (error)
12504 goto done;
12506 error = histedit_load_list(&histedit_cmds, path, repo);
12507 free(path);
12508 if (error)
12509 goto done;
12511 error = got_worktree_histedit_continue(&resume_commit_id,
12512 &tmp_branch, &branch, &base_commit_id, &fileindex,
12513 worktree, repo);
12514 if (error)
12515 goto done;
12517 error = got_ref_resolve(&head_commit_id, repo, branch);
12518 if (error)
12519 goto done;
12521 error = got_object_open_as_commit(&commit, repo,
12522 head_commit_id);
12523 if (error)
12524 goto done;
12525 parent_ids = got_object_commit_get_parent_ids(commit);
12526 pid = STAILQ_FIRST(parent_ids);
12527 if (pid == NULL) {
12528 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12529 goto done;
12531 error = collect_commits(&commits, head_commit_id, &pid->id,
12532 base_commit_id, got_worktree_get_path_prefix(worktree),
12533 GOT_ERR_HISTEDIT_PATH, repo);
12534 got_object_commit_close(commit);
12535 commit = NULL;
12536 if (error)
12537 goto done;
12538 } else {
12539 if (edit_in_progress) {
12540 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12541 goto done;
12544 error = got_ref_open(&branch, repo,
12545 got_worktree_get_head_ref_name(worktree), 0);
12546 if (error != NULL)
12547 goto done;
12549 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12550 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12551 "will not edit commit history of a branch outside "
12552 "the \"refs/heads/\" reference namespace");
12553 goto done;
12556 error = got_ref_resolve(&head_commit_id, repo, branch);
12557 got_ref_close(branch);
12558 branch = NULL;
12559 if (error)
12560 goto done;
12562 error = got_object_open_as_commit(&commit, repo,
12563 head_commit_id);
12564 if (error)
12565 goto done;
12566 parent_ids = got_object_commit_get_parent_ids(commit);
12567 pid = STAILQ_FIRST(parent_ids);
12568 if (pid == NULL) {
12569 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12570 goto done;
12572 error = collect_commits(&commits, head_commit_id, &pid->id,
12573 got_worktree_get_base_commit_id(worktree),
12574 got_worktree_get_path_prefix(worktree),
12575 GOT_ERR_HISTEDIT_PATH, repo);
12576 got_object_commit_close(commit);
12577 commit = NULL;
12578 if (error)
12579 goto done;
12581 if (STAILQ_EMPTY(&commits)) {
12582 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12583 goto done;
12586 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12587 &base_commit_id, &fileindex, worktree, repo);
12588 if (error)
12589 goto done;
12591 if (edit_script_path) {
12592 error = histedit_load_list(&histedit_cmds,
12593 edit_script_path, repo);
12594 if (error) {
12595 got_worktree_histedit_abort(worktree, fileindex,
12596 repo, branch, base_commit_id,
12597 abort_progress, &upa);
12598 print_merge_progress_stats(&upa);
12599 goto done;
12601 } else {
12602 const char *branch_name;
12603 branch_name = got_ref_get_symref_target(branch);
12604 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12605 branch_name += 11;
12606 error = histedit_edit_script(&histedit_cmds, &commits,
12607 branch_name, edit_logmsg_only, fold_only,
12608 drop_only, edit_only, repo);
12609 if (error) {
12610 got_worktree_histedit_abort(worktree, fileindex,
12611 repo, branch, base_commit_id,
12612 abort_progress, &upa);
12613 print_merge_progress_stats(&upa);
12614 goto done;
12619 error = histedit_save_list(&histedit_cmds, worktree,
12620 repo);
12621 if (error) {
12622 got_worktree_histedit_abort(worktree, fileindex,
12623 repo, branch, base_commit_id,
12624 abort_progress, &upa);
12625 print_merge_progress_stats(&upa);
12626 goto done;
12631 error = histedit_check_script(&histedit_cmds, &commits, repo);
12632 if (error)
12633 goto done;
12635 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12636 if (resume_commit_id) {
12637 if (got_object_id_cmp(hle->commit_id,
12638 resume_commit_id) != 0)
12639 continue;
12641 resume_commit_id = NULL;
12642 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12643 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12644 error = histedit_skip_commit(hle, worktree,
12645 repo);
12646 if (error)
12647 goto done;
12648 } else {
12649 struct got_pathlist_head paths;
12650 int have_changes = 0;
12652 TAILQ_INIT(&paths);
12653 error = got_pathlist_append(&paths, "", NULL);
12654 if (error)
12655 goto done;
12656 error = got_worktree_status(worktree, &paths,
12657 repo, 0, check_local_changes, &have_changes,
12658 check_cancelled, NULL);
12659 got_pathlist_free(&paths,
12660 GOT_PATHLIST_FREE_NONE);
12661 if (error) {
12662 if (error->code != GOT_ERR_CANCELLED)
12663 goto done;
12664 if (sigint_received || sigpipe_received)
12665 goto done;
12667 if (have_changes) {
12668 error = histedit_commit(NULL, worktree,
12669 fileindex, tmp_branch, hle,
12670 committer, repo);
12671 if (error)
12672 goto done;
12673 } else {
12674 error = got_object_open_as_commit(
12675 &commit, repo, hle->commit_id);
12676 if (error)
12677 goto done;
12678 error = show_histedit_progress(commit,
12679 hle, NULL);
12680 got_object_commit_close(commit);
12681 commit = NULL;
12682 if (error)
12683 goto done;
12686 continue;
12689 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12690 error = histedit_skip_commit(hle, worktree, repo);
12691 if (error)
12692 goto done;
12693 continue;
12696 error = got_object_open_as_commit(&commit, repo,
12697 hle->commit_id);
12698 if (error)
12699 goto done;
12700 parent_ids = got_object_commit_get_parent_ids(commit);
12701 pid = STAILQ_FIRST(parent_ids);
12703 error = got_worktree_histedit_merge_files(&merged_paths,
12704 worktree, fileindex, &pid->id, hle->commit_id, repo,
12705 update_progress, &upa, check_cancelled, NULL);
12706 if (error)
12707 goto done;
12708 got_object_commit_close(commit);
12709 commit = NULL;
12711 print_merge_progress_stats(&upa);
12712 if (upa.conflicts > 0 || upa.missing > 0 ||
12713 upa.not_deleted > 0 || upa.unversioned > 0) {
12714 if (upa.conflicts > 0) {
12715 error = show_rebase_merge_conflict(
12716 hle->commit_id, repo);
12717 if (error)
12718 goto done;
12720 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12721 break;
12724 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12725 char *id_str;
12726 error = got_object_id_str(&id_str, hle->commit_id);
12727 if (error)
12728 goto done;
12729 printf("Stopping histedit for amending commit %s\n",
12730 id_str);
12731 free(id_str);
12732 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12733 error = got_worktree_histedit_postpone(worktree,
12734 fileindex);
12735 goto done;
12738 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12739 error = histedit_skip_commit(hle, worktree, repo);
12740 if (error)
12741 goto done;
12742 continue;
12745 error = histedit_commit(&merged_paths, worktree, fileindex,
12746 tmp_branch, hle, committer, repo);
12747 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12748 if (error)
12749 goto done;
12752 if (upa.conflicts > 0 || upa.missing > 0 ||
12753 upa.not_deleted > 0 || upa.unversioned > 0) {
12754 error = got_worktree_histedit_postpone(worktree, fileindex);
12755 if (error)
12756 goto done;
12757 if (upa.conflicts > 0 && upa.missing == 0 &&
12758 upa.not_deleted == 0 && upa.unversioned == 0) {
12759 error = got_error_msg(GOT_ERR_CONFLICTS,
12760 "conflicts must be resolved before histedit "
12761 "can continue");
12762 } else if (upa.conflicts > 0) {
12763 error = got_error_msg(GOT_ERR_CONFLICTS,
12764 "conflicts must be resolved before histedit "
12765 "can continue; changes destined for some "
12766 "files were not yet merged and should be "
12767 "merged manually if required before the "
12768 "histedit operation is continued");
12769 } else {
12770 error = got_error_msg(GOT_ERR_CONFLICTS,
12771 "changes destined for some files were not "
12772 "yet merged and should be merged manually "
12773 "if required before the histedit operation "
12774 "is continued");
12776 } else
12777 error = histedit_complete(worktree, fileindex, tmp_branch,
12778 branch, repo);
12779 done:
12780 free(cwd);
12781 free(committer);
12782 free(gitconfig_path);
12783 got_object_id_queue_free(&commits);
12784 histedit_free_list(&histedit_cmds);
12785 free(head_commit_id);
12786 free(base_commit_id);
12787 free(resume_commit_id);
12788 if (commit)
12789 got_object_commit_close(commit);
12790 if (branch)
12791 got_ref_close(branch);
12792 if (tmp_branch)
12793 got_ref_close(tmp_branch);
12794 if (worktree)
12795 got_worktree_close(worktree);
12796 if (repo) {
12797 const struct got_error *close_err = got_repo_close(repo);
12798 if (error == NULL)
12799 error = close_err;
12801 if (pack_fds) {
12802 const struct got_error *pack_err =
12803 got_repo_pack_fds_close(pack_fds);
12804 if (error == NULL)
12805 error = pack_err;
12807 return error;
12810 __dead static void
12811 usage_integrate(void)
12813 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12814 exit(1);
12817 static const struct got_error *
12818 cmd_integrate(int argc, char *argv[])
12820 const struct got_error *error = NULL;
12821 struct got_repository *repo = NULL;
12822 struct got_worktree *worktree = NULL;
12823 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12824 const char *branch_arg = NULL;
12825 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12826 struct got_fileindex *fileindex = NULL;
12827 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12828 int ch;
12829 struct got_update_progress_arg upa;
12830 int *pack_fds = NULL;
12832 while ((ch = getopt(argc, argv, "")) != -1) {
12833 switch (ch) {
12834 default:
12835 usage_integrate();
12836 /* NOTREACHED */
12840 argc -= optind;
12841 argv += optind;
12843 if (argc != 1)
12844 usage_integrate();
12845 branch_arg = argv[0];
12846 #ifndef PROFILE
12847 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12848 "unveil", NULL) == -1)
12849 err(1, "pledge");
12850 #endif
12851 cwd = getcwd(NULL, 0);
12852 if (cwd == NULL) {
12853 error = got_error_from_errno("getcwd");
12854 goto done;
12857 error = got_repo_pack_fds_open(&pack_fds);
12858 if (error != NULL)
12859 goto done;
12861 error = got_worktree_open(&worktree, cwd);
12862 if (error) {
12863 if (error->code == GOT_ERR_NOT_WORKTREE)
12864 error = wrap_not_worktree_error(error, "integrate",
12865 cwd);
12866 goto done;
12869 error = check_rebase_or_histedit_in_progress(worktree);
12870 if (error)
12871 goto done;
12873 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12874 NULL, pack_fds);
12875 if (error != NULL)
12876 goto done;
12878 error = apply_unveil(got_repo_get_path(repo), 0,
12879 got_worktree_get_root_path(worktree));
12880 if (error)
12881 goto done;
12883 error = check_merge_in_progress(worktree, repo);
12884 if (error)
12885 goto done;
12887 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12888 error = got_error_from_errno("asprintf");
12889 goto done;
12892 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12893 &base_branch_ref, worktree, refname, repo);
12894 if (error)
12895 goto done;
12897 refname = strdup(got_ref_get_name(branch_ref));
12898 if (refname == NULL) {
12899 error = got_error_from_errno("strdup");
12900 got_worktree_integrate_abort(worktree, fileindex, repo,
12901 branch_ref, base_branch_ref);
12902 goto done;
12904 base_refname = strdup(got_ref_get_name(base_branch_ref));
12905 if (base_refname == NULL) {
12906 error = got_error_from_errno("strdup");
12907 got_worktree_integrate_abort(worktree, fileindex, repo,
12908 branch_ref, base_branch_ref);
12909 goto done;
12911 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12912 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12913 got_worktree_integrate_abort(worktree, fileindex, repo,
12914 branch_ref, base_branch_ref);
12915 goto done;
12918 error = got_ref_resolve(&commit_id, repo, branch_ref);
12919 if (error)
12920 goto done;
12922 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12923 if (error)
12924 goto done;
12926 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12927 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12928 "specified branch has already been integrated");
12929 got_worktree_integrate_abort(worktree, fileindex, repo,
12930 branch_ref, base_branch_ref);
12931 goto done;
12934 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12935 if (error) {
12936 if (error->code == GOT_ERR_ANCESTRY)
12937 error = got_error(GOT_ERR_REBASE_REQUIRED);
12938 got_worktree_integrate_abort(worktree, fileindex, repo,
12939 branch_ref, base_branch_ref);
12940 goto done;
12943 memset(&upa, 0, sizeof(upa));
12944 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12945 branch_ref, base_branch_ref, update_progress, &upa,
12946 check_cancelled, NULL);
12947 if (error)
12948 goto done;
12950 printf("Integrated %s into %s\n", refname, base_refname);
12951 print_update_progress_stats(&upa);
12952 done:
12953 if (repo) {
12954 const struct got_error *close_err = got_repo_close(repo);
12955 if (error == NULL)
12956 error = close_err;
12958 if (worktree)
12959 got_worktree_close(worktree);
12960 if (pack_fds) {
12961 const struct got_error *pack_err =
12962 got_repo_pack_fds_close(pack_fds);
12963 if (error == NULL)
12964 error = pack_err;
12966 free(cwd);
12967 free(base_commit_id);
12968 free(commit_id);
12969 free(refname);
12970 free(base_refname);
12971 return error;
12974 __dead static void
12975 usage_merge(void)
12977 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12978 exit(1);
12981 static const struct got_error *
12982 cmd_merge(int argc, char *argv[])
12984 const struct got_error *error = NULL;
12985 struct got_worktree *worktree = NULL;
12986 struct got_repository *repo = NULL;
12987 struct got_fileindex *fileindex = NULL;
12988 char *cwd = NULL, *id_str = NULL, *author = NULL;
12989 struct got_reference *branch = NULL, *wt_branch = NULL;
12990 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12991 struct got_object_id *wt_branch_tip = NULL;
12992 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12993 int interrupt_merge = 0;
12994 struct got_update_progress_arg upa;
12995 struct got_object_id *merge_commit_id = NULL;
12996 char *branch_name = NULL;
12997 int *pack_fds = NULL;
12999 memset(&upa, 0, sizeof(upa));
13001 while ((ch = getopt(argc, argv, "acn")) != -1) {
13002 switch (ch) {
13003 case 'a':
13004 abort_merge = 1;
13005 break;
13006 case 'c':
13007 continue_merge = 1;
13008 break;
13009 case 'n':
13010 interrupt_merge = 1;
13011 break;
13012 default:
13013 usage_merge();
13014 /* NOTREACHED */
13018 argc -= optind;
13019 argv += optind;
13021 #ifndef PROFILE
13022 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13023 "unveil", NULL) == -1)
13024 err(1, "pledge");
13025 #endif
13027 if (abort_merge && continue_merge)
13028 option_conflict('a', 'c');
13029 if (abort_merge || continue_merge) {
13030 if (argc != 0)
13031 usage_merge();
13032 } else if (argc != 1)
13033 usage_merge();
13035 cwd = getcwd(NULL, 0);
13036 if (cwd == NULL) {
13037 error = got_error_from_errno("getcwd");
13038 goto done;
13041 error = got_repo_pack_fds_open(&pack_fds);
13042 if (error != NULL)
13043 goto done;
13045 error = got_worktree_open(&worktree, cwd);
13046 if (error) {
13047 if (error->code == GOT_ERR_NOT_WORKTREE)
13048 error = wrap_not_worktree_error(error,
13049 "merge", cwd);
13050 goto done;
13053 error = got_repo_open(&repo,
13054 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13055 pack_fds);
13056 if (error != NULL)
13057 goto done;
13059 if (worktree != NULL) {
13060 error = worktree_has_logmsg_ref("merge", worktree, repo);
13061 if (error)
13062 goto done;
13065 error = apply_unveil(got_repo_get_path(repo), 0,
13066 worktree ? got_worktree_get_root_path(worktree) : NULL);
13067 if (error)
13068 goto done;
13070 error = check_rebase_or_histedit_in_progress(worktree);
13071 if (error)
13072 goto done;
13074 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13075 repo);
13076 if (error)
13077 goto done;
13079 if (abort_merge) {
13080 if (!merge_in_progress) {
13081 error = got_error(GOT_ERR_NOT_MERGING);
13082 goto done;
13084 error = got_worktree_merge_continue(&branch_name,
13085 &branch_tip, &fileindex, worktree, repo);
13086 if (error)
13087 goto done;
13088 error = got_worktree_merge_abort(worktree, fileindex, repo,
13089 abort_progress, &upa);
13090 if (error)
13091 goto done;
13092 printf("Merge of %s aborted\n", branch_name);
13093 goto done; /* nothing else to do */
13096 error = get_author(&author, repo, worktree);
13097 if (error)
13098 goto done;
13100 if (continue_merge) {
13101 if (!merge_in_progress) {
13102 error = got_error(GOT_ERR_NOT_MERGING);
13103 goto done;
13105 error = got_worktree_merge_continue(&branch_name,
13106 &branch_tip, &fileindex, worktree, repo);
13107 if (error)
13108 goto done;
13109 } else {
13110 error = got_ref_open(&branch, repo, argv[0], 0);
13111 if (error != NULL)
13112 goto done;
13113 branch_name = strdup(got_ref_get_name(branch));
13114 if (branch_name == NULL) {
13115 error = got_error_from_errno("strdup");
13116 goto done;
13118 error = got_ref_resolve(&branch_tip, repo, branch);
13119 if (error)
13120 goto done;
13123 error = got_ref_open(&wt_branch, repo,
13124 got_worktree_get_head_ref_name(worktree), 0);
13125 if (error)
13126 goto done;
13127 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13128 if (error)
13129 goto done;
13130 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13131 wt_branch_tip, branch_tip, 0, repo,
13132 check_cancelled, NULL);
13133 if (error && error->code != GOT_ERR_ANCESTRY)
13134 goto done;
13136 if (!continue_merge) {
13137 error = check_path_prefix(wt_branch_tip, branch_tip,
13138 got_worktree_get_path_prefix(worktree),
13139 GOT_ERR_MERGE_PATH, repo);
13140 if (error)
13141 goto done;
13142 if (yca_id) {
13143 error = check_same_branch(wt_branch_tip, branch,
13144 yca_id, repo);
13145 if (error) {
13146 if (error->code != GOT_ERR_ANCESTRY)
13147 goto done;
13148 error = NULL;
13149 } else {
13150 static char msg[512];
13151 snprintf(msg, sizeof(msg),
13152 "cannot create a merge commit because "
13153 "%s is based on %s; %s can be integrated "
13154 "with 'got integrate' instead", branch_name,
13155 got_worktree_get_head_ref_name(worktree),
13156 branch_name);
13157 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13158 goto done;
13161 error = got_worktree_merge_prepare(&fileindex, worktree,
13162 branch, repo);
13163 if (error)
13164 goto done;
13166 error = got_worktree_merge_branch(worktree, fileindex,
13167 yca_id, branch_tip, repo, update_progress, &upa,
13168 check_cancelled, NULL);
13169 if (error)
13170 goto done;
13171 print_merge_progress_stats(&upa);
13172 if (!upa.did_something) {
13173 error = got_worktree_merge_abort(worktree, fileindex,
13174 repo, abort_progress, &upa);
13175 if (error)
13176 goto done;
13177 printf("Already up-to-date\n");
13178 goto done;
13182 if (interrupt_merge) {
13183 error = got_worktree_merge_postpone(worktree, fileindex);
13184 if (error)
13185 goto done;
13186 printf("Merge of %s interrupted on request\n", branch_name);
13187 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13188 upa.not_deleted > 0 || upa.unversioned > 0) {
13189 error = got_worktree_merge_postpone(worktree, fileindex);
13190 if (error)
13191 goto done;
13192 if (upa.conflicts > 0 && upa.missing == 0 &&
13193 upa.not_deleted == 0 && upa.unversioned == 0) {
13194 error = got_error_msg(GOT_ERR_CONFLICTS,
13195 "conflicts must be resolved before merging "
13196 "can continue");
13197 } else if (upa.conflicts > 0) {
13198 error = got_error_msg(GOT_ERR_CONFLICTS,
13199 "conflicts must be resolved before merging "
13200 "can continue; changes destined for some "
13201 "files were not yet merged and "
13202 "should be merged manually if required before the "
13203 "merge operation is continued");
13204 } else {
13205 error = got_error_msg(GOT_ERR_CONFLICTS,
13206 "changes destined for some "
13207 "files were not yet merged and should be "
13208 "merged manually if required before the "
13209 "merge operation is continued");
13211 goto done;
13212 } else {
13213 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13214 fileindex, author, NULL, 1, branch_tip, branch_name,
13215 repo, continue_merge ? print_status : NULL, NULL);
13216 if (error)
13217 goto done;
13218 error = got_worktree_merge_complete(worktree, fileindex, repo);
13219 if (error)
13220 goto done;
13221 error = got_object_id_str(&id_str, merge_commit_id);
13222 if (error)
13223 goto done;
13224 printf("Merged %s into %s: %s\n", branch_name,
13225 got_worktree_get_head_ref_name(worktree),
13226 id_str);
13229 done:
13230 free(id_str);
13231 free(merge_commit_id);
13232 free(author);
13233 free(branch_tip);
13234 free(branch_name);
13235 free(yca_id);
13236 if (branch)
13237 got_ref_close(branch);
13238 if (wt_branch)
13239 got_ref_close(wt_branch);
13240 if (worktree)
13241 got_worktree_close(worktree);
13242 if (repo) {
13243 const struct got_error *close_err = got_repo_close(repo);
13244 if (error == NULL)
13245 error = close_err;
13247 if (pack_fds) {
13248 const struct got_error *pack_err =
13249 got_repo_pack_fds_close(pack_fds);
13250 if (error == NULL)
13251 error = pack_err;
13253 return error;
13256 __dead static void
13257 usage_stage(void)
13259 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13260 "[path ...]\n", getprogname());
13261 exit(1);
13264 static const struct got_error *
13265 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13266 const char *path, struct got_object_id *blob_id,
13267 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13268 int dirfd, const char *de_name)
13270 const struct got_error *err = NULL;
13271 char *id_str = NULL;
13273 if (staged_status != GOT_STATUS_ADD &&
13274 staged_status != GOT_STATUS_MODIFY &&
13275 staged_status != GOT_STATUS_DELETE)
13276 return NULL;
13278 if (staged_status == GOT_STATUS_ADD ||
13279 staged_status == GOT_STATUS_MODIFY)
13280 err = got_object_id_str(&id_str, staged_blob_id);
13281 else
13282 err = got_object_id_str(&id_str, blob_id);
13283 if (err)
13284 return err;
13286 printf("%s %c %s\n", id_str, staged_status, path);
13287 free(id_str);
13288 return NULL;
13291 static const struct got_error *
13292 cmd_stage(int argc, char *argv[])
13294 const struct got_error *error = NULL;
13295 struct got_repository *repo = NULL;
13296 struct got_worktree *worktree = NULL;
13297 char *cwd = NULL;
13298 struct got_pathlist_head paths;
13299 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13300 FILE *patch_script_file = NULL;
13301 const char *patch_script_path = NULL;
13302 struct choose_patch_arg cpa;
13303 int *pack_fds = NULL;
13305 TAILQ_INIT(&paths);
13307 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13308 switch (ch) {
13309 case 'F':
13310 patch_script_path = optarg;
13311 break;
13312 case 'l':
13313 list_stage = 1;
13314 break;
13315 case 'p':
13316 pflag = 1;
13317 break;
13318 case 'S':
13319 allow_bad_symlinks = 1;
13320 break;
13321 default:
13322 usage_stage();
13323 /* NOTREACHED */
13327 argc -= optind;
13328 argv += optind;
13330 #ifndef PROFILE
13331 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13332 "unveil", NULL) == -1)
13333 err(1, "pledge");
13334 #endif
13335 if (list_stage && (pflag || patch_script_path))
13336 errx(1, "-l option cannot be used with other options");
13337 if (patch_script_path && !pflag)
13338 errx(1, "-F option can only be used together with -p option");
13340 cwd = getcwd(NULL, 0);
13341 if (cwd == NULL) {
13342 error = got_error_from_errno("getcwd");
13343 goto done;
13346 error = got_repo_pack_fds_open(&pack_fds);
13347 if (error != NULL)
13348 goto done;
13350 error = got_worktree_open(&worktree, cwd);
13351 if (error) {
13352 if (error->code == GOT_ERR_NOT_WORKTREE)
13353 error = wrap_not_worktree_error(error, "stage", cwd);
13354 goto done;
13357 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13358 NULL, pack_fds);
13359 if (error != NULL)
13360 goto done;
13362 if (patch_script_path) {
13363 patch_script_file = fopen(patch_script_path, "re");
13364 if (patch_script_file == NULL) {
13365 error = got_error_from_errno2("fopen",
13366 patch_script_path);
13367 goto done;
13370 error = apply_unveil(got_repo_get_path(repo), 0,
13371 got_worktree_get_root_path(worktree));
13372 if (error)
13373 goto done;
13375 error = check_merge_in_progress(worktree, repo);
13376 if (error)
13377 goto done;
13379 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13380 if (error)
13381 goto done;
13383 if (list_stage)
13384 error = got_worktree_status(worktree, &paths, repo, 0,
13385 print_stage, NULL, check_cancelled, NULL);
13386 else {
13387 cpa.patch_script_file = patch_script_file;
13388 cpa.action = "stage";
13389 error = got_worktree_stage(worktree, &paths,
13390 pflag ? NULL : print_status, NULL,
13391 pflag ? choose_patch : NULL, &cpa,
13392 allow_bad_symlinks, repo);
13394 done:
13395 if (patch_script_file && fclose(patch_script_file) == EOF &&
13396 error == NULL)
13397 error = got_error_from_errno2("fclose", patch_script_path);
13398 if (repo) {
13399 const struct got_error *close_err = got_repo_close(repo);
13400 if (error == NULL)
13401 error = close_err;
13403 if (worktree)
13404 got_worktree_close(worktree);
13405 if (pack_fds) {
13406 const struct got_error *pack_err =
13407 got_repo_pack_fds_close(pack_fds);
13408 if (error == NULL)
13409 error = pack_err;
13411 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13412 free(cwd);
13413 return error;
13416 __dead static void
13417 usage_unstage(void)
13419 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13420 "[path ...]\n", getprogname());
13421 exit(1);
13425 static const struct got_error *
13426 cmd_unstage(int argc, char *argv[])
13428 const struct got_error *error = NULL;
13429 struct got_repository *repo = NULL;
13430 struct got_worktree *worktree = NULL;
13431 char *cwd = NULL;
13432 struct got_pathlist_head paths;
13433 int ch, pflag = 0;
13434 struct got_update_progress_arg upa;
13435 FILE *patch_script_file = NULL;
13436 const char *patch_script_path = NULL;
13437 struct choose_patch_arg cpa;
13438 int *pack_fds = NULL;
13440 TAILQ_INIT(&paths);
13442 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13443 switch (ch) {
13444 case 'F':
13445 patch_script_path = optarg;
13446 break;
13447 case 'p':
13448 pflag = 1;
13449 break;
13450 default:
13451 usage_unstage();
13452 /* NOTREACHED */
13456 argc -= optind;
13457 argv += optind;
13459 #ifndef PROFILE
13460 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13461 "unveil", NULL) == -1)
13462 err(1, "pledge");
13463 #endif
13464 if (patch_script_path && !pflag)
13465 errx(1, "-F option can only be used together with -p option");
13467 cwd = getcwd(NULL, 0);
13468 if (cwd == NULL) {
13469 error = got_error_from_errno("getcwd");
13470 goto done;
13473 error = got_repo_pack_fds_open(&pack_fds);
13474 if (error != NULL)
13475 goto done;
13477 error = got_worktree_open(&worktree, cwd);
13478 if (error) {
13479 if (error->code == GOT_ERR_NOT_WORKTREE)
13480 error = wrap_not_worktree_error(error, "unstage", cwd);
13481 goto done;
13484 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13485 NULL, pack_fds);
13486 if (error != NULL)
13487 goto done;
13489 if (patch_script_path) {
13490 patch_script_file = fopen(patch_script_path, "re");
13491 if (patch_script_file == NULL) {
13492 error = got_error_from_errno2("fopen",
13493 patch_script_path);
13494 goto done;
13498 error = apply_unveil(got_repo_get_path(repo), 0,
13499 got_worktree_get_root_path(worktree));
13500 if (error)
13501 goto done;
13503 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13504 if (error)
13505 goto done;
13507 cpa.patch_script_file = patch_script_file;
13508 cpa.action = "unstage";
13509 memset(&upa, 0, sizeof(upa));
13510 error = got_worktree_unstage(worktree, &paths, update_progress,
13511 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13512 if (!error)
13513 print_merge_progress_stats(&upa);
13514 done:
13515 if (patch_script_file && fclose(patch_script_file) == EOF &&
13516 error == NULL)
13517 error = got_error_from_errno2("fclose", patch_script_path);
13518 if (repo) {
13519 const struct got_error *close_err = got_repo_close(repo);
13520 if (error == NULL)
13521 error = close_err;
13523 if (worktree)
13524 got_worktree_close(worktree);
13525 if (pack_fds) {
13526 const struct got_error *pack_err =
13527 got_repo_pack_fds_close(pack_fds);
13528 if (error == NULL)
13529 error = pack_err;
13531 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13532 free(cwd);
13533 return error;
13536 __dead static void
13537 usage_cat(void)
13539 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13540 "arg ...\n", getprogname());
13541 exit(1);
13544 static const struct got_error *
13545 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13547 const struct got_error *err;
13548 struct got_blob_object *blob;
13549 int fd = -1;
13551 fd = got_opentempfd();
13552 if (fd == -1)
13553 return got_error_from_errno("got_opentempfd");
13555 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13556 if (err)
13557 goto done;
13559 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13560 done:
13561 if (fd != -1 && close(fd) == -1 && err == NULL)
13562 err = got_error_from_errno("close");
13563 if (blob)
13564 got_object_blob_close(blob);
13565 return err;
13568 static const struct got_error *
13569 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13571 const struct got_error *err;
13572 struct got_tree_object *tree;
13573 int nentries, i;
13575 err = got_object_open_as_tree(&tree, repo, id);
13576 if (err)
13577 return err;
13579 nentries = got_object_tree_get_nentries(tree);
13580 for (i = 0; i < nentries; i++) {
13581 struct got_tree_entry *te;
13582 char *id_str;
13583 if (sigint_received || sigpipe_received)
13584 break;
13585 te = got_object_tree_get_entry(tree, i);
13586 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13587 if (err)
13588 break;
13589 fprintf(outfile, "%s %.7o %s\n", id_str,
13590 got_tree_entry_get_mode(te),
13591 got_tree_entry_get_name(te));
13592 free(id_str);
13595 got_object_tree_close(tree);
13596 return err;
13599 static const struct got_error *
13600 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13602 const struct got_error *err;
13603 struct got_commit_object *commit;
13604 const struct got_object_id_queue *parent_ids;
13605 struct got_object_qid *pid;
13606 char *id_str = NULL;
13607 const char *logmsg = NULL;
13608 char gmtoff[6];
13610 err = got_object_open_as_commit(&commit, repo, id);
13611 if (err)
13612 return err;
13614 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13615 if (err)
13616 goto done;
13618 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13619 parent_ids = got_object_commit_get_parent_ids(commit);
13620 fprintf(outfile, "numparents %d\n",
13621 got_object_commit_get_nparents(commit));
13622 STAILQ_FOREACH(pid, parent_ids, entry) {
13623 char *pid_str;
13624 err = got_object_id_str(&pid_str, &pid->id);
13625 if (err)
13626 goto done;
13627 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13628 free(pid_str);
13630 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13631 got_object_commit_get_author_gmtoff(commit));
13632 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13633 got_object_commit_get_author(commit),
13634 (long long)got_object_commit_get_author_time(commit),
13635 gmtoff);
13637 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13638 got_object_commit_get_committer_gmtoff(commit));
13639 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13640 got_object_commit_get_committer(commit),
13641 (long long)got_object_commit_get_committer_time(commit),
13642 gmtoff);
13644 logmsg = got_object_commit_get_logmsg_raw(commit);
13645 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13646 fprintf(outfile, "%s", logmsg);
13647 done:
13648 free(id_str);
13649 got_object_commit_close(commit);
13650 return err;
13653 static const struct got_error *
13654 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13656 const struct got_error *err;
13657 struct got_tag_object *tag;
13658 char *id_str = NULL;
13659 const char *tagmsg = NULL;
13660 char gmtoff[6];
13662 err = got_object_open_as_tag(&tag, repo, id);
13663 if (err)
13664 return err;
13666 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13667 if (err)
13668 goto done;
13670 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13672 switch (got_object_tag_get_object_type(tag)) {
13673 case GOT_OBJ_TYPE_BLOB:
13674 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13675 GOT_OBJ_LABEL_BLOB);
13676 break;
13677 case GOT_OBJ_TYPE_TREE:
13678 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13679 GOT_OBJ_LABEL_TREE);
13680 break;
13681 case GOT_OBJ_TYPE_COMMIT:
13682 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13683 GOT_OBJ_LABEL_COMMIT);
13684 break;
13685 case GOT_OBJ_TYPE_TAG:
13686 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13687 GOT_OBJ_LABEL_TAG);
13688 break;
13689 default:
13690 break;
13693 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13694 got_object_tag_get_name(tag));
13696 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13697 got_object_tag_get_tagger_gmtoff(tag));
13698 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13699 got_object_tag_get_tagger(tag),
13700 (long long)got_object_tag_get_tagger_time(tag),
13701 gmtoff);
13703 tagmsg = got_object_tag_get_message(tag);
13704 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13705 fprintf(outfile, "%s", tagmsg);
13706 done:
13707 free(id_str);
13708 got_object_tag_close(tag);
13709 return err;
13712 static const struct got_error *
13713 cmd_cat(int argc, char *argv[])
13715 const struct got_error *error;
13716 struct got_repository *repo = NULL;
13717 struct got_worktree *worktree = NULL;
13718 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13719 const char *commit_id_str = NULL;
13720 struct got_object_id *id = NULL, *commit_id = NULL;
13721 struct got_commit_object *commit = NULL;
13722 int ch, obj_type, i, force_path = 0;
13723 struct got_reflist_head refs;
13724 int *pack_fds = NULL;
13726 TAILQ_INIT(&refs);
13728 #ifndef PROFILE
13729 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13730 NULL) == -1)
13731 err(1, "pledge");
13732 #endif
13734 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13735 switch (ch) {
13736 case 'c':
13737 commit_id_str = optarg;
13738 break;
13739 case 'P':
13740 force_path = 1;
13741 break;
13742 case 'r':
13743 repo_path = realpath(optarg, NULL);
13744 if (repo_path == NULL)
13745 return got_error_from_errno2("realpath",
13746 optarg);
13747 got_path_strip_trailing_slashes(repo_path);
13748 break;
13749 default:
13750 usage_cat();
13751 /* NOTREACHED */
13755 argc -= optind;
13756 argv += optind;
13758 cwd = getcwd(NULL, 0);
13759 if (cwd == NULL) {
13760 error = got_error_from_errno("getcwd");
13761 goto done;
13764 error = got_repo_pack_fds_open(&pack_fds);
13765 if (error != NULL)
13766 goto done;
13768 if (repo_path == NULL) {
13769 error = got_worktree_open(&worktree, cwd);
13770 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13771 goto done;
13772 if (worktree) {
13773 repo_path = strdup(
13774 got_worktree_get_repo_path(worktree));
13775 if (repo_path == NULL) {
13776 error = got_error_from_errno("strdup");
13777 goto done;
13780 /* Release work tree lock. */
13781 got_worktree_close(worktree);
13782 worktree = NULL;
13786 if (repo_path == NULL) {
13787 repo_path = strdup(cwd);
13788 if (repo_path == NULL)
13789 return got_error_from_errno("strdup");
13792 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13793 free(repo_path);
13794 if (error != NULL)
13795 goto done;
13797 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13798 if (error)
13799 goto done;
13801 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13802 if (error)
13803 goto done;
13805 if (commit_id_str == NULL)
13806 commit_id_str = GOT_REF_HEAD;
13807 error = got_repo_match_object_id(&commit_id, NULL,
13808 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13809 if (error)
13810 goto done;
13812 error = got_object_open_as_commit(&commit, repo, commit_id);
13813 if (error)
13814 goto done;
13816 for (i = 0; i < argc; i++) {
13817 if (force_path) {
13818 error = got_object_id_by_path(&id, repo, commit,
13819 argv[i]);
13820 if (error)
13821 break;
13822 } else {
13823 error = got_repo_match_object_id(&id, &label, argv[i],
13824 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13825 repo);
13826 if (error) {
13827 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13828 error->code != GOT_ERR_NOT_REF)
13829 break;
13830 error = got_object_id_by_path(&id, repo,
13831 commit, argv[i]);
13832 if (error)
13833 break;
13837 error = got_object_get_type(&obj_type, repo, id);
13838 if (error)
13839 break;
13841 switch (obj_type) {
13842 case GOT_OBJ_TYPE_BLOB:
13843 error = cat_blob(id, repo, stdout);
13844 break;
13845 case GOT_OBJ_TYPE_TREE:
13846 error = cat_tree(id, repo, stdout);
13847 break;
13848 case GOT_OBJ_TYPE_COMMIT:
13849 error = cat_commit(id, repo, stdout);
13850 break;
13851 case GOT_OBJ_TYPE_TAG:
13852 error = cat_tag(id, repo, stdout);
13853 break;
13854 default:
13855 error = got_error(GOT_ERR_OBJ_TYPE);
13856 break;
13858 if (error)
13859 break;
13860 free(label);
13861 label = NULL;
13862 free(id);
13863 id = NULL;
13865 done:
13866 free(label);
13867 free(id);
13868 free(commit_id);
13869 if (commit)
13870 got_object_commit_close(commit);
13871 if (worktree)
13872 got_worktree_close(worktree);
13873 if (repo) {
13874 const struct got_error *close_err = got_repo_close(repo);
13875 if (error == NULL)
13876 error = close_err;
13878 if (pack_fds) {
13879 const struct got_error *pack_err =
13880 got_repo_pack_fds_close(pack_fds);
13881 if (error == NULL)
13882 error = pack_err;
13885 got_ref_list_free(&refs);
13886 return error;
13889 __dead static void
13890 usage_info(void)
13892 fprintf(stderr, "usage: %s info [path ...]\n",
13893 getprogname());
13894 exit(1);
13897 static const struct got_error *
13898 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13899 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13900 struct got_object_id *commit_id)
13902 const struct got_error *err = NULL;
13903 char *id_str = NULL;
13904 char datebuf[128];
13905 struct tm mytm, *tm;
13906 struct got_pathlist_head *paths = arg;
13907 struct got_pathlist_entry *pe;
13910 * Clear error indication from any of the path arguments which
13911 * would cause this file index entry to be displayed.
13913 TAILQ_FOREACH(pe, paths, entry) {
13914 if (got_path_cmp(path, pe->path, strlen(path),
13915 pe->path_len) == 0 ||
13916 got_path_is_child(path, pe->path, pe->path_len))
13917 pe->data = NULL; /* no error */
13920 printf(GOT_COMMIT_SEP_STR);
13921 if (S_ISLNK(mode))
13922 printf("symlink: %s\n", path);
13923 else if (S_ISREG(mode)) {
13924 printf("file: %s\n", path);
13925 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13926 } else if (S_ISDIR(mode))
13927 printf("directory: %s\n", path);
13928 else
13929 printf("something: %s\n", path);
13931 tm = localtime_r(&mtime, &mytm);
13932 if (tm == NULL)
13933 return NULL;
13934 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13935 return got_error(GOT_ERR_NO_SPACE);
13936 printf("timestamp: %s\n", datebuf);
13938 if (blob_id) {
13939 err = got_object_id_str(&id_str, blob_id);
13940 if (err)
13941 return err;
13942 printf("based on blob: %s\n", id_str);
13943 free(id_str);
13946 if (staged_blob_id) {
13947 err = got_object_id_str(&id_str, staged_blob_id);
13948 if (err)
13949 return err;
13950 printf("based on staged blob: %s\n", id_str);
13951 free(id_str);
13954 if (commit_id) {
13955 err = got_object_id_str(&id_str, commit_id);
13956 if (err)
13957 return err;
13958 printf("based on commit: %s\n", id_str);
13959 free(id_str);
13962 return NULL;
13965 static const struct got_error *
13966 cmd_info(int argc, char *argv[])
13968 const struct got_error *error = NULL;
13969 struct got_worktree *worktree = NULL;
13970 char *cwd = NULL, *id_str = NULL;
13971 struct got_pathlist_head paths;
13972 char *uuidstr = NULL;
13973 int ch, show_files = 0;
13975 TAILQ_INIT(&paths);
13977 while ((ch = getopt(argc, argv, "")) != -1) {
13978 switch (ch) {
13979 default:
13980 usage_info();
13981 /* NOTREACHED */
13985 argc -= optind;
13986 argv += optind;
13988 #ifndef PROFILE
13989 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13990 NULL) == -1)
13991 err(1, "pledge");
13992 #endif
13993 cwd = getcwd(NULL, 0);
13994 if (cwd == NULL) {
13995 error = got_error_from_errno("getcwd");
13996 goto done;
13999 error = got_worktree_open(&worktree, cwd);
14000 if (error) {
14001 if (error->code == GOT_ERR_NOT_WORKTREE)
14002 error = wrap_not_worktree_error(error, "info", cwd);
14003 goto done;
14006 #ifndef PROFILE
14007 /* Remove "wpath cpath proc exec sendfd" promises. */
14008 if (pledge("stdio rpath flock unveil", NULL) == -1)
14009 err(1, "pledge");
14010 #endif
14011 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14012 if (error)
14013 goto done;
14015 if (argc >= 1) {
14016 error = get_worktree_paths_from_argv(&paths, argc, argv,
14017 worktree);
14018 if (error)
14019 goto done;
14020 show_files = 1;
14023 error = got_object_id_str(&id_str,
14024 got_worktree_get_base_commit_id(worktree));
14025 if (error)
14026 goto done;
14028 error = got_worktree_get_uuid(&uuidstr, worktree);
14029 if (error)
14030 goto done;
14032 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14033 printf("work tree base commit: %s\n", id_str);
14034 printf("work tree path prefix: %s\n",
14035 got_worktree_get_path_prefix(worktree));
14036 printf("work tree branch reference: %s\n",
14037 got_worktree_get_head_ref_name(worktree));
14038 printf("work tree UUID: %s\n", uuidstr);
14039 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14041 if (show_files) {
14042 struct got_pathlist_entry *pe;
14043 TAILQ_FOREACH(pe, &paths, entry) {
14044 if (pe->path_len == 0)
14045 continue;
14047 * Assume this path will fail. This will be corrected
14048 * in print_path_info() in case the path does suceeed.
14050 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14052 error = got_worktree_path_info(worktree, &paths,
14053 print_path_info, &paths, check_cancelled, NULL);
14054 if (error)
14055 goto done;
14056 TAILQ_FOREACH(pe, &paths, entry) {
14057 if (pe->data != NULL) {
14058 const struct got_error *perr;
14060 perr = pe->data;
14061 error = got_error_fmt(perr->code, "%s",
14062 pe->path);
14063 break;
14067 done:
14068 if (worktree)
14069 got_worktree_close(worktree);
14070 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14071 free(cwd);
14072 free(id_str);
14073 free(uuidstr);
14074 return error;