Blob


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