update EWAH todo item
[got-portable.git] / got / got.c
blob3aca3e0b5f7a8d30881ea65469302f533306ea60
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>
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.
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.
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 #ifndef GOT_DEFAULT_EDITOR
71 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
72 #endif
74 static volatile sig_atomic_t sigint_received;
75 static volatile sig_atomic_t sigpipe_received;
77 static void
78 catch_sigint(int signo)
80 sigint_received = 1;
83 static void
84 catch_sigpipe(int signo)
86 sigpipe_received = 1;
90 struct got_cmd {
91 const char *cmd_name;
92 const struct got_error *(*cmd_main)(int, char *[]);
93 void (*cmd_usage)(void);
94 const char *cmd_alias;
97 __dead static void usage(int, int);
98 __dead static void usage_init(void);
99 __dead static void usage_import(void);
100 __dead static void usage_clone(void);
101 __dead static void usage_fetch(void);
102 __dead static void usage_checkout(void);
103 __dead static void usage_update(void);
104 __dead static void usage_log(void);
105 __dead static void usage_diff(void);
106 __dead static void usage_blame(void);
107 __dead static void usage_tree(void);
108 __dead static void usage_status(void);
109 __dead static void usage_ref(void);
110 __dead static void usage_branch(void);
111 __dead static void usage_tag(void);
112 __dead static void usage_add(void);
113 __dead static void usage_remove(void);
114 __dead static void usage_patch(void);
115 __dead static void usage_revert(void);
116 __dead static void usage_commit(void);
117 __dead static void usage_send(void);
118 __dead static void usage_cherrypick(void);
119 __dead static void usage_backout(void);
120 __dead static void usage_rebase(void);
121 __dead static void usage_histedit(void);
122 __dead static void usage_integrate(void);
123 __dead static void usage_merge(void);
124 __dead static void usage_stage(void);
125 __dead static void usage_unstage(void);
126 __dead static void usage_cat(void);
127 __dead static void usage_info(void);
129 static const struct got_error* cmd_init(int, char *[]);
130 static const struct got_error* cmd_import(int, char *[]);
131 static const struct got_error* cmd_clone(int, char *[]);
132 static const struct got_error* cmd_fetch(int, char *[]);
133 static const struct got_error* cmd_checkout(int, char *[]);
134 static const struct got_error* cmd_update(int, char *[]);
135 static const struct got_error* cmd_log(int, char *[]);
136 static const struct got_error* cmd_diff(int, char *[]);
137 static const struct got_error* cmd_blame(int, char *[]);
138 static const struct got_error* cmd_tree(int, char *[]);
139 static const struct got_error* cmd_status(int, char *[]);
140 static const struct got_error* cmd_ref(int, char *[]);
141 static const struct got_error* cmd_branch(int, char *[]);
142 static const struct got_error* cmd_tag(int, char *[]);
143 static const struct got_error* cmd_add(int, char *[]);
144 static const struct got_error* cmd_remove(int, char *[]);
145 static const struct got_error* cmd_patch(int, char *[]);
146 static const struct got_error* cmd_revert(int, char *[]);
147 static const struct got_error* cmd_commit(int, char *[]);
148 static const struct got_error* cmd_send(int, char *[]);
149 static const struct got_error* cmd_cherrypick(int, char *[]);
150 static const struct got_error* cmd_backout(int, char *[]);
151 static const struct got_error* cmd_rebase(int, char *[]);
152 static const struct got_error* cmd_histedit(int, char *[]);
153 static const struct got_error* cmd_integrate(int, char *[]);
154 static const struct got_error* cmd_merge(int, char *[]);
155 static const struct got_error* cmd_stage(int, char *[]);
156 static const struct got_error* cmd_unstage(int, char *[]);
157 static const struct got_error* cmd_cat(int, char *[]);
158 static const struct got_error* cmd_info(int, char *[]);
160 static const struct got_cmd got_commands[] = {
161 { "init", cmd_init, usage_init, "" },
162 { "import", cmd_import, usage_import, "im" },
163 { "clone", cmd_clone, usage_clone, "cl" },
164 { "fetch", cmd_fetch, usage_fetch, "fe" },
165 { "checkout", cmd_checkout, usage_checkout, "co" },
166 { "update", cmd_update, usage_update, "up" },
167 { "log", cmd_log, usage_log, "" },
168 { "diff", cmd_diff, usage_diff, "di" },
169 { "blame", cmd_blame, usage_blame, "bl" },
170 { "tree", cmd_tree, usage_tree, "tr" },
171 { "status", cmd_status, usage_status, "st" },
172 { "ref", cmd_ref, usage_ref, "" },
173 { "branch", cmd_branch, usage_branch, "br" },
174 { "tag", cmd_tag, usage_tag, "" },
175 { "add", cmd_add, usage_add, "" },
176 { "remove", cmd_remove, usage_remove, "rm" },
177 { "patch", cmd_patch, usage_patch, "pa" },
178 { "revert", cmd_revert, usage_revert, "rv" },
179 { "commit", cmd_commit, usage_commit, "ci" },
180 { "send", cmd_send, usage_send, "se" },
181 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
182 { "backout", cmd_backout, usage_backout, "bo" },
183 { "rebase", cmd_rebase, usage_rebase, "rb" },
184 { "histedit", cmd_histedit, usage_histedit, "he" },
185 { "integrate", cmd_integrate, usage_integrate,"ig" },
186 { "merge", cmd_merge, usage_merge, "mg" },
187 { "stage", cmd_stage, usage_stage, "sg" },
188 { "unstage", cmd_unstage, usage_unstage, "ug" },
189 { "cat", cmd_cat, usage_cat, "" },
190 { "info", cmd_info, usage_info, "" },
193 static void
194 list_commands(FILE *fp)
196 size_t i;
198 fprintf(fp, "commands:");
199 for (i = 0; i < nitems(got_commands); i++) {
200 const struct got_cmd *cmd = &got_commands[i];
201 fprintf(fp, " %s", cmd->cmd_name);
203 fputc('\n', fp);
206 __dead static void
207 option_conflict(char a, char b)
209 errx(1, "-%c and -%c options are mutually exclusive", a, b);
213 main(int argc, char *argv[])
215 const struct got_cmd *cmd;
216 size_t i;
217 int ch;
218 int hflag = 0, Vflag = 0;
219 static const struct option longopts[] = {
220 { "version", no_argument, NULL, 'V' },
221 { NULL, 0, NULL, 0 }
224 setlocale(LC_CTYPE, "");
226 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
227 switch (ch) {
228 case 'h':
229 hflag = 1;
230 break;
231 case 'V':
232 Vflag = 1;
233 break;
234 default:
235 usage(hflag, 1);
236 /* NOTREACHED */
240 argc -= optind;
241 argv += optind;
242 optind = 1;
243 optreset = 1;
245 if (Vflag) {
246 got_version_print_str();
247 return 0;
250 if (argc <= 0)
251 usage(hflag, hflag ? 0 : 1);
253 signal(SIGINT, catch_sigint);
254 signal(SIGPIPE, catch_sigpipe);
256 for (i = 0; i < nitems(got_commands); i++) {
257 const struct got_error *error;
259 cmd = &got_commands[i];
261 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
262 strcmp(cmd->cmd_alias, argv[0]) != 0)
263 continue;
265 if (hflag)
266 cmd->cmd_usage();
268 error = cmd->cmd_main(argc, argv);
269 if (error && error->code != GOT_ERR_CANCELLED &&
270 error->code != GOT_ERR_PRIVSEP_EXIT &&
271 !(sigpipe_received &&
272 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
273 !(sigint_received &&
274 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
275 fflush(stdout);
276 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
277 return 1;
280 return 0;
283 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
284 list_commands(stderr);
285 return 1;
288 __dead static void
289 usage(int hflag, int status)
291 FILE *fp = (status == 0) ? stdout : stderr;
293 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
294 getprogname());
295 if (hflag)
296 list_commands(fp);
297 exit(status);
300 static const struct got_error *
301 get_editor(char **abspath)
303 const struct got_error *err = NULL;
304 const char *editor;
306 *abspath = NULL;
308 editor = getenv("VISUAL");
309 if (editor == NULL)
310 editor = getenv("EDITOR");
312 if (editor) {
313 err = got_path_find_prog(abspath, editor);
314 if (err)
315 return err;
318 if (*abspath == NULL) {
319 *abspath = strdup(GOT_DEFAULT_EDITOR);
320 if (*abspath == NULL)
321 return got_error_from_errno("strdup");
324 return NULL;
327 static const struct got_error *
328 apply_unveil(const char *repo_path, int repo_read_only,
329 const char *worktree_path)
331 const struct got_error *err;
333 #ifdef PROFILE
334 if (unveil("gmon.out", "rwc") != 0)
335 return got_error_from_errno2("unveil", "gmon.out");
336 #endif
337 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
338 return got_error_from_errno2("unveil", repo_path);
340 if (worktree_path && unveil(worktree_path, "rwc") != 0)
341 return got_error_from_errno2("unveil", worktree_path);
343 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
344 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
346 err = got_privsep_unveil_exec_helpers();
347 if (err != NULL)
348 return err;
350 if (unveil(NULL, NULL) != 0)
351 return got_error_from_errno("unveil");
353 return NULL;
356 __dead static void
357 usage_init(void)
359 fprintf(stderr, "usage: %s init [-A hashing-algorithm] [-b branch]"
360 " repository-path\n",
361 getprogname());
362 exit(1);
365 static const struct got_error *
366 cmd_init(int argc, char *argv[])
368 const struct got_error *error = NULL;
369 const char *head_name = NULL;
370 char *repo_path = NULL;
371 enum got_hash_algorithm algo = GOT_HASH_SHA1;
372 int ch;
374 while ((ch = getopt(argc, argv, "A:b:")) != -1) {
375 switch (ch) {
376 case 'A':
377 if (!strcmp(optarg, "sha1"))
378 algo = GOT_HASH_SHA1;
379 else if (!strcmp(optarg, "sha256"))
380 algo = GOT_HASH_SHA256;
381 else
382 return got_error_path(optarg,
383 GOT_ERR_OBJECT_FORMAT);
384 break;
385 case 'b':
386 head_name = optarg;
387 break;
388 default:
389 usage_init();
390 /* NOTREACHED */
394 argc -= optind;
395 argv += optind;
397 #ifndef PROFILE
398 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
399 err(1, "pledge");
400 #endif
401 if (argc != 1)
402 usage_init();
404 repo_path = strdup(argv[0]);
405 if (repo_path == NULL)
406 return got_error_from_errno("strdup");
408 got_path_strip_trailing_slashes(repo_path);
410 error = got_path_mkdir(repo_path);
411 if (error &&
412 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
413 goto done;
415 error = apply_unveil(repo_path, 0, NULL);
416 if (error)
417 goto done;
419 error = got_repo_init(repo_path, head_name, algo);
420 done:
421 free(repo_path);
422 return error;
425 __dead static void
426 usage_import(void)
428 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
429 "[-r repository-path] directory\n", getprogname());
430 exit(1);
433 static int
434 spawn_editor(const char *editor, const char *file)
436 pid_t pid;
437 sig_t sighup, sigint, sigquit;
438 int st = -1;
440 sighup = signal(SIGHUP, SIG_IGN);
441 sigint = signal(SIGINT, SIG_IGN);
442 sigquit = signal(SIGQUIT, SIG_IGN);
444 switch (pid = fork()) {
445 case -1:
446 goto doneediting;
447 case 0:
448 execl(editor, editor, file, (char *)NULL);
449 _exit(127);
452 while (waitpid(pid, &st, 0) == -1)
453 if (errno != EINTR)
454 break;
456 doneediting:
457 (void)signal(SIGHUP, sighup);
458 (void)signal(SIGINT, sigint);
459 (void)signal(SIGQUIT, sigquit);
461 if (!WIFEXITED(st)) {
462 errno = EINTR;
463 return -1;
466 return WEXITSTATUS(st);
469 static const struct got_error *
470 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
472 const struct got_error *err = NULL;
473 char *line = NULL;
474 size_t linesize = 0;
476 *logmsg = NULL;
477 *len = 0;
479 if (fseeko(fp, 0L, SEEK_SET) == -1)
480 return got_error_from_errno("fseeko");
482 *logmsg = malloc(filesize + 1);
483 if (*logmsg == NULL)
484 return got_error_from_errno("malloc");
485 (*logmsg)[0] = '\0';
487 while (getline(&line, &linesize, fp) != -1) {
488 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
489 continue; /* remove comments and leading empty lines */
490 *len = strlcat(*logmsg, line, filesize + 1);
491 if (*len >= filesize + 1) {
492 err = got_error(GOT_ERR_NO_SPACE);
493 goto done;
496 if (ferror(fp)) {
497 err = got_ferror(fp, GOT_ERR_IO);
498 goto done;
501 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
502 (*logmsg)[*len - 1] = '\0';
503 (*len)--;
505 done:
506 free(line);
507 if (err) {
508 free(*logmsg);
509 *logmsg = NULL;
510 *len = 0;
512 return err;
515 static const struct got_error *
516 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
517 const char *initial_content, size_t initial_content_len,
518 int require_modification)
520 const struct got_error *err = NULL;
521 struct stat st, st2;
522 FILE *fp = NULL;
523 size_t logmsg_len;
525 *logmsg = NULL;
527 if (stat(logmsg_path, &st) == -1)
528 return got_error_from_errno2("stat", logmsg_path);
530 if (spawn_editor(editor, logmsg_path) == -1)
531 return got_error_from_errno("failed spawning editor");
533 if (require_modification) {
534 struct timespec timeout;
536 timeout.tv_sec = 0;
537 timeout.tv_nsec = 1;
538 nanosleep(&timeout, NULL);
541 if (stat(logmsg_path, &st2) == -1)
542 return got_error_from_errno2("stat", logmsg_path);
544 if (require_modification && st.st_size == st2.st_size &&
545 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
546 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
547 "no changes made to commit message, aborting");
549 fp = fopen(logmsg_path, "re");
550 if (fp == NULL) {
551 err = got_error_from_errno("fopen");
552 goto done;
555 /* strip comments and leading/trailing newlines */
556 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
557 if (err)
558 goto done;
559 if (logmsg_len == 0) {
560 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
561 "commit message cannot be empty, aborting");
562 goto done;
564 done:
565 if (fp && fclose(fp) == EOF && err == NULL)
566 err = got_error_from_errno("fclose");
567 if (err) {
568 free(*logmsg);
569 *logmsg = NULL;
571 return err;
574 static const struct got_error *
575 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
576 const char *path_dir, const char *branch_name)
578 char *initial_content = NULL;
579 const struct got_error *err = NULL;
580 int initial_content_len;
581 int fd = -1;
583 initial_content_len = asprintf(&initial_content,
584 "\n# %s to be imported to branch %s\n", path_dir,
585 branch_name);
586 if (initial_content_len == -1)
587 return got_error_from_errno("asprintf");
589 err = got_opentemp_named_fd(logmsg_path, &fd,
590 GOT_TMPDIR_STR "/got-importmsg", "");
591 if (err)
592 goto done;
594 if (write(fd, initial_content, initial_content_len) == -1) {
595 err = got_error_from_errno2("write", *logmsg_path);
596 goto done;
598 if (close(fd) == -1) {
599 err = got_error_from_errno2("close", *logmsg_path);
600 goto done;
602 fd = -1;
604 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
605 initial_content_len, 1);
606 done:
607 if (fd != -1 && close(fd) == -1 && err == NULL)
608 err = got_error_from_errno2("close", *logmsg_path);
609 free(initial_content);
610 if (err) {
611 free(*logmsg_path);
612 *logmsg_path = NULL;
614 return err;
617 static const struct got_error *
618 import_progress(void *arg, const char *path)
620 printf("A %s\n", path);
621 return NULL;
624 static const struct got_error *
625 valid_author(const char *author)
627 const char *email = author;
630 * Git' expects the author (or committer) to be in the form
631 * "name <email>", which are mostly free form (see the
632 * "committer" description in git-fast-import(1)). We're only
633 * doing this to avoid git's object parser breaking on commits
634 * we create.
637 while (*author && *author != '\n' && *author != '<' && *author != '>')
638 author++;
639 if (author != email && *author == '<' && *(author - 1) != ' ')
640 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
641 "between author name and email required", email);
642 if (*author++ != '<')
643 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
644 while (*author && *author != '\n' && *author != '<' && *author != '>')
645 author++;
646 if (strcmp(author, ">") != 0)
647 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
648 return NULL;
651 static const struct got_error *
652 get_author(char **author, struct got_repository *repo,
653 struct got_worktree *worktree)
655 const struct got_error *err = NULL;
656 const char *got_author = NULL, *name, *email;
657 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
659 *author = NULL;
661 if (worktree)
662 worktree_conf = got_worktree_get_gotconfig(worktree);
663 repo_conf = got_repo_get_gotconfig(repo);
666 * Priority of potential author information sources, from most
667 * significant to least significant:
668 * 1) work tree's .got/got.conf file
669 * 2) repository's got.conf file
670 * 3) repository's git config file
671 * 4) environment variables
672 * 5) global git config files (in user's home directory or /etc)
675 if (worktree_conf)
676 got_author = got_gotconfig_get_author(worktree_conf);
677 if (got_author == NULL)
678 got_author = got_gotconfig_get_author(repo_conf);
679 if (got_author == NULL) {
680 name = got_repo_get_gitconfig_author_name(repo);
681 email = got_repo_get_gitconfig_author_email(repo);
682 if (name && email) {
683 if (asprintf(author, "%s <%s>", name, email) == -1)
684 return got_error_from_errno("asprintf");
685 return NULL;
688 got_author = getenv("GOT_AUTHOR");
689 if (got_author == NULL) {
690 name = got_repo_get_global_gitconfig_author_name(repo);
691 email = got_repo_get_global_gitconfig_author_email(
692 repo);
693 if (name && email) {
694 if (asprintf(author, "%s <%s>", name, email)
695 == -1)
696 return got_error_from_errno("asprintf");
697 return NULL;
699 /* TODO: Look up user in password database? */
700 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
704 *author = strdup(got_author);
705 if (*author == NULL)
706 return got_error_from_errno("strdup");
708 err = valid_author(*author);
709 if (err) {
710 free(*author);
711 *author = NULL;
713 return err;
716 static const struct got_error *
717 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
718 struct got_worktree *worktree)
720 const char *got_allowed_signers = NULL;
721 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
723 *allowed_signers = NULL;
725 if (worktree)
726 worktree_conf = got_worktree_get_gotconfig(worktree);
727 repo_conf = got_repo_get_gotconfig(repo);
730 * Priority of potential author information sources, from most
731 * significant to least significant:
732 * 1) work tree's .got/got.conf file
733 * 2) repository's got.conf file
736 if (worktree_conf)
737 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
738 worktree_conf);
739 if (got_allowed_signers == NULL)
740 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
741 repo_conf);
743 if (got_allowed_signers) {
744 *allowed_signers = strdup(got_allowed_signers);
745 if (*allowed_signers == NULL)
746 return got_error_from_errno("strdup");
748 return NULL;
751 static const struct got_error *
752 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
753 struct got_worktree *worktree)
755 const char *got_revoked_signers = NULL;
756 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
758 *revoked_signers = NULL;
760 if (worktree)
761 worktree_conf = got_worktree_get_gotconfig(worktree);
762 repo_conf = got_repo_get_gotconfig(repo);
765 * Priority of potential author information sources, from most
766 * significant to least significant:
767 * 1) work tree's .got/got.conf file
768 * 2) repository's got.conf file
771 if (worktree_conf)
772 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
773 worktree_conf);
774 if (got_revoked_signers == NULL)
775 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
776 repo_conf);
778 if (got_revoked_signers) {
779 *revoked_signers = strdup(got_revoked_signers);
780 if (*revoked_signers == NULL)
781 return got_error_from_errno("strdup");
783 return NULL;
786 static const char *
787 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
789 const char *got_signer_id = NULL;
790 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
792 if (worktree)
793 worktree_conf = got_worktree_get_gotconfig(worktree);
794 repo_conf = got_repo_get_gotconfig(repo);
797 * Priority of potential author information sources, from most
798 * significant to least significant:
799 * 1) work tree's .got/got.conf file
800 * 2) repository's got.conf file
803 if (worktree_conf)
804 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
805 if (got_signer_id == NULL)
806 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
808 return got_signer_id;
811 static const struct got_error *
812 get_gitconfig_path(char **gitconfig_path)
814 const char *homedir = getenv("HOME");
816 *gitconfig_path = NULL;
817 if (homedir) {
818 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
819 return got_error_from_errno("asprintf");
822 return NULL;
825 static const struct got_error *
826 cmd_import(int argc, char *argv[])
828 const struct got_error *error = NULL;
829 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
830 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
831 const char *branch_name = NULL;
832 char *id_str = NULL, *logmsg_path = NULL;
833 char refname[PATH_MAX] = "refs/heads/";
834 struct got_repository *repo = NULL;
835 struct got_reference *branch_ref = NULL, *head_ref = NULL;
836 struct got_object_id *new_commit_id = NULL;
837 int ch, n = 0;
838 struct got_pathlist_head ignores;
839 struct got_pathlist_entry *pe;
840 int preserve_logmsg = 0;
841 int *pack_fds = NULL;
843 TAILQ_INIT(&ignores);
845 #ifndef PROFILE
846 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
847 "unveil",
848 NULL) == -1)
849 err(1, "pledge");
850 #endif
852 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
853 switch (ch) {
854 case 'b':
855 branch_name = optarg;
856 break;
857 case 'I':
858 if (optarg[0] == '\0')
859 break;
860 error = got_pathlist_insert(&pe, &ignores, optarg,
861 NULL);
862 if (error)
863 goto done;
864 break;
865 case 'm':
866 logmsg = strdup(optarg);
867 if (logmsg == NULL) {
868 error = got_error_from_errno("strdup");
869 goto done;
871 break;
872 case 'r':
873 repo_path = realpath(optarg, NULL);
874 if (repo_path == NULL) {
875 error = got_error_from_errno2("realpath",
876 optarg);
877 goto done;
879 break;
880 default:
881 usage_import();
882 /* NOTREACHED */
886 argc -= optind;
887 argv += optind;
889 if (argc != 1)
890 usage_import();
892 if (repo_path == NULL) {
893 repo_path = getcwd(NULL, 0);
894 if (repo_path == NULL)
895 return got_error_from_errno("getcwd");
897 got_path_strip_trailing_slashes(repo_path);
898 error = get_gitconfig_path(&gitconfig_path);
899 if (error)
900 goto done;
901 error = got_repo_pack_fds_open(&pack_fds);
902 if (error != NULL)
903 goto done;
904 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
905 if (error)
906 goto done;
908 path_dir = realpath(argv[0], NULL);
909 if (path_dir == NULL) {
910 error = got_error_from_errno2("realpath", argv[0]);
911 goto done;
913 got_path_strip_trailing_slashes(path_dir);
915 error = get_editor(&editor);
916 if (error)
917 goto done;
919 if (unveil(path_dir, "r") != 0) {
920 error = got_error_from_errno2("unveil", path_dir);
921 goto done;
923 if (unveil(editor, "x") != 0) {
924 error = got_error_from_errno2("unveil", editor);
925 goto done;
927 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
928 if (error)
929 goto done;
931 error = get_author(&author, repo, NULL);
932 if (error)
933 return error;
936 * Don't let the user create a branch name with a leading '-'.
937 * While technically a valid reference name, this case is usually
938 * an unintended typo.
940 if (branch_name && branch_name[0] == '-')
941 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
943 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
944 if (error && error->code != GOT_ERR_NOT_REF)
945 goto done;
947 if (branch_name)
948 n = strlcat(refname, branch_name, sizeof(refname));
949 else if (head_ref && got_ref_is_symbolic(head_ref))
950 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
951 sizeof(refname));
952 else
953 n = strlcat(refname, "main", sizeof(refname));
954 if (n >= sizeof(refname)) {
955 error = got_error(GOT_ERR_NO_SPACE);
956 goto done;
959 error = got_ref_open(&branch_ref, repo, refname, 0);
960 if (error) {
961 if (error->code != GOT_ERR_NOT_REF)
962 goto done;
963 } else {
964 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
965 "import target branch already exists");
966 goto done;
969 if (logmsg == NULL || *logmsg == '\0') {
970 free(logmsg);
971 error = collect_import_msg(&logmsg, &logmsg_path, editor,
972 path_dir, refname);
973 if (error) {
974 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
975 logmsg_path != NULL)
976 preserve_logmsg = 1;
977 goto done;
981 error = got_repo_import(&new_commit_id, path_dir, logmsg,
982 author, &ignores, repo, import_progress, NULL);
983 if (error) {
984 if (logmsg_path)
985 preserve_logmsg = 1;
986 goto done;
989 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
990 if (error) {
991 if (logmsg_path)
992 preserve_logmsg = 1;
993 goto done;
996 error = got_ref_write(branch_ref, repo);
997 if (error) {
998 if (logmsg_path)
999 preserve_logmsg = 1;
1000 goto done;
1003 error = got_object_id_str(&id_str, new_commit_id);
1004 if (error) {
1005 if (logmsg_path)
1006 preserve_logmsg = 1;
1007 goto done;
1010 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
1011 if (error) {
1012 if (error->code != GOT_ERR_NOT_REF) {
1013 if (logmsg_path)
1014 preserve_logmsg = 1;
1015 goto done;
1018 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
1019 branch_ref);
1020 if (error) {
1021 if (logmsg_path)
1022 preserve_logmsg = 1;
1023 goto done;
1026 error = got_ref_write(head_ref, repo);
1027 if (error) {
1028 if (logmsg_path)
1029 preserve_logmsg = 1;
1030 goto done;
1034 printf("Created branch %s with commit %s\n",
1035 got_ref_get_name(branch_ref), id_str);
1036 done:
1037 if (pack_fds) {
1038 const struct got_error *pack_err =
1039 got_repo_pack_fds_close(pack_fds);
1040 if (error == NULL)
1041 error = pack_err;
1043 if (repo) {
1044 const struct got_error *close_err = got_repo_close(repo);
1045 if (error == NULL)
1046 error = close_err;
1048 if (preserve_logmsg) {
1049 fprintf(stderr, "%s: log message preserved in %s\n",
1050 getprogname(), logmsg_path);
1051 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
1052 error = got_error_from_errno2("unlink", logmsg_path);
1053 free(logmsg);
1054 free(logmsg_path);
1055 free(repo_path);
1056 free(editor);
1057 free(new_commit_id);
1058 free(id_str);
1059 free(author);
1060 free(gitconfig_path);
1061 if (branch_ref)
1062 got_ref_close(branch_ref);
1063 if (head_ref)
1064 got_ref_close(head_ref);
1065 return error;
1068 __dead static void
1069 usage_clone(void)
1071 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1072 "repository-URL [directory]\n", getprogname());
1073 exit(1);
1076 struct got_fetch_progress_arg {
1077 char last_scaled_size[FMT_SCALED_STRSIZE];
1078 int last_p_indexed;
1079 int last_p_resolved;
1080 int verbosity;
1082 struct got_repository *repo;
1084 int create_configs;
1085 int configs_created;
1086 struct {
1087 struct got_pathlist_head *symrefs;
1088 struct got_pathlist_head *wanted_branches;
1089 struct got_pathlist_head *wanted_refs;
1090 const char *proto;
1091 const char *host;
1092 const char *port;
1093 const char *remote_repo_path;
1094 const char *git_url;
1095 int fetch_all_branches;
1096 int mirror_references;
1097 } config_info;
1100 /* XXX forward declaration */
1101 static const struct got_error *
1102 create_config_files(const char *proto, const char *host, const char *port,
1103 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1104 int mirror_references, struct got_pathlist_head *symrefs,
1105 struct got_pathlist_head *wanted_branches,
1106 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1108 static const struct got_error *
1109 fetch_progress(void *arg, const char *message, off_t packfile_size,
1110 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1112 const struct got_error *err = NULL;
1113 struct got_fetch_progress_arg *a = arg;
1114 char scaled_size[FMT_SCALED_STRSIZE];
1115 int p_indexed, p_resolved;
1116 int print_size = 0, print_indexed = 0, print_resolved = 0;
1119 * In order to allow a failed clone to be resumed with 'got fetch'
1120 * we try to create configuration files as soon as possible.
1121 * Once the server has sent information about its default branch
1122 * we have all required information.
1124 if (a->create_configs && !a->configs_created &&
1125 !TAILQ_EMPTY(a->config_info.symrefs)) {
1126 err = create_config_files(a->config_info.proto,
1127 a->config_info.host, a->config_info.port,
1128 a->config_info.remote_repo_path,
1129 a->config_info.git_url,
1130 a->config_info.fetch_all_branches,
1131 a->config_info.mirror_references,
1132 a->config_info.symrefs,
1133 a->config_info.wanted_branches,
1134 a->config_info.wanted_refs, a->repo);
1135 if (err)
1136 return err;
1137 a->configs_created = 1;
1140 if (a->verbosity < 0)
1141 return NULL;
1143 if (message && message[0] != '\0') {
1144 printf("\rserver: %s", message);
1145 fflush(stdout);
1146 return NULL;
1149 if (packfile_size > 0 || nobj_indexed > 0) {
1150 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1151 (a->last_scaled_size[0] == '\0' ||
1152 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1153 print_size = 1;
1154 if (strlcpy(a->last_scaled_size, scaled_size,
1155 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1156 return got_error(GOT_ERR_NO_SPACE);
1158 if (nobj_indexed > 0) {
1159 p_indexed = (nobj_indexed * 100) / nobj_total;
1160 if (p_indexed != a->last_p_indexed) {
1161 a->last_p_indexed = p_indexed;
1162 print_indexed = 1;
1163 print_size = 1;
1166 if (nobj_resolved > 0) {
1167 p_resolved = (nobj_resolved * 100) /
1168 (nobj_total - nobj_loose);
1169 if (p_resolved != a->last_p_resolved) {
1170 a->last_p_resolved = p_resolved;
1171 print_resolved = 1;
1172 print_indexed = 1;
1173 print_size = 1;
1178 if (print_size || print_indexed || print_resolved)
1179 printf("\r");
1180 if (print_size)
1181 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1182 if (print_indexed)
1183 printf("; indexing %d%%", p_indexed);
1184 if (print_resolved)
1185 printf("; resolving deltas %d%%", p_resolved);
1186 if (print_size || print_indexed || print_resolved)
1187 fflush(stdout);
1189 return NULL;
1192 static const struct got_error *
1193 create_symref(const char *refname, struct got_reference *target_ref,
1194 int verbosity, struct got_repository *repo)
1196 const struct got_error *err;
1197 struct got_reference *head_symref;
1199 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1200 if (err)
1201 return err;
1203 err = got_ref_write(head_symref, repo);
1204 if (err == NULL && verbosity > 0) {
1205 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1206 got_ref_get_name(target_ref));
1208 got_ref_close(head_symref);
1209 return err;
1212 static const struct got_error *
1213 list_remote_refs(struct got_pathlist_head *symrefs,
1214 struct got_pathlist_head *refs)
1216 const struct got_error *err;
1217 struct got_pathlist_entry *pe;
1219 TAILQ_FOREACH(pe, symrefs, entry) {
1220 const char *refname = pe->path;
1221 const char *targetref = pe->data;
1223 printf("%s: %s\n", refname, targetref);
1226 TAILQ_FOREACH(pe, refs, entry) {
1227 const char *refname = pe->path;
1228 struct got_object_id *id = pe->data;
1229 char *id_str;
1231 err = got_object_id_str(&id_str, id);
1232 if (err)
1233 return err;
1234 printf("%s: %s\n", refname, id_str);
1235 free(id_str);
1238 return NULL;
1241 static const struct got_error *
1242 create_ref(const char *refname, struct got_object_id *id,
1243 int verbosity, struct got_repository *repo)
1245 const struct got_error *err = NULL;
1246 struct got_reference *ref;
1247 char *id_str;
1249 err = got_object_id_str(&id_str, id);
1250 if (err)
1251 return err;
1253 err = got_ref_alloc(&ref, refname, id);
1254 if (err)
1255 goto done;
1257 err = got_ref_write(ref, repo);
1258 got_ref_close(ref);
1260 if (err == NULL && verbosity >= 0)
1261 printf("Created reference %s: %s\n", refname, id_str);
1262 done:
1263 free(id_str);
1264 return err;
1267 static int
1268 match_wanted_ref(const char *refname, const char *wanted_ref)
1270 if (strncmp(refname, "refs/", 5) != 0)
1271 return 0;
1272 refname += 5;
1275 * Prevent fetching of references that won't make any
1276 * sense outside of the remote repository's context.
1278 if (strncmp(refname, "got/", 4) == 0)
1279 return 0;
1280 if (strncmp(refname, "remotes/", 8) == 0)
1281 return 0;
1283 if (strncmp(wanted_ref, "refs/", 5) == 0)
1284 wanted_ref += 5;
1286 /* Allow prefix match. */
1287 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1288 return 1;
1290 /* Allow exact match. */
1291 return (strcmp(refname, wanted_ref) == 0);
1294 static int
1295 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1297 struct got_pathlist_entry *pe;
1299 TAILQ_FOREACH(pe, wanted_refs, entry) {
1300 if (match_wanted_ref(refname, pe->path))
1301 return 1;
1304 return 0;
1307 static const struct got_error *
1308 create_wanted_ref(const char *refname, struct got_object_id *id,
1309 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1311 const struct got_error *err;
1312 char *remote_refname;
1314 if (strncmp("refs/", refname, 5) == 0)
1315 refname += 5;
1317 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1318 remote_repo_name, refname) == -1)
1319 return got_error_from_errno("asprintf");
1321 err = create_ref(remote_refname, id, verbosity, repo);
1322 free(remote_refname);
1323 return err;
1326 static const struct got_error *
1327 create_gotconfig(const char *proto, const char *host, const char *port,
1328 const char *remote_repo_path, const char *default_branch,
1329 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1330 struct got_pathlist_head *wanted_refs, int mirror_references,
1331 struct got_repository *repo)
1333 const struct got_error *err = NULL;
1334 char *gotconfig_path = NULL;
1335 char *gotconfig = NULL;
1336 FILE *gotconfig_file = NULL;
1337 const char *branchname = NULL;
1338 char *branches = NULL, *refs = NULL;
1339 ssize_t n;
1341 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1342 struct got_pathlist_entry *pe;
1343 TAILQ_FOREACH(pe, wanted_branches, entry) {
1344 char *s;
1345 branchname = pe->path;
1346 if (strncmp(branchname, "refs/heads/", 11) == 0)
1347 branchname += 11;
1348 if (asprintf(&s, "%s\"%s\" ",
1349 branches ? branches : "", branchname) == -1) {
1350 err = got_error_from_errno("asprintf");
1351 goto done;
1353 free(branches);
1354 branches = s;
1356 } else if (!fetch_all_branches && default_branch) {
1357 branchname = default_branch;
1358 if (strncmp(branchname, "refs/heads/", 11) == 0)
1359 branchname += 11;
1360 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1361 err = got_error_from_errno("asprintf");
1362 goto done;
1365 if (!TAILQ_EMPTY(wanted_refs)) {
1366 struct got_pathlist_entry *pe;
1367 TAILQ_FOREACH(pe, wanted_refs, entry) {
1368 char *s;
1369 const char *refname = pe->path;
1370 if (strncmp(refname, "refs/", 5) == 0)
1371 branchname += 5;
1372 if (asprintf(&s, "%s\"%s\" ",
1373 refs ? refs : "", refname) == -1) {
1374 err = got_error_from_errno("asprintf");
1375 goto done;
1377 free(refs);
1378 refs = s;
1382 /* Create got.conf(5). */
1383 gotconfig_path = got_repo_get_path_gotconfig(repo);
1384 if (gotconfig_path == NULL) {
1385 err = got_error_from_errno("got_repo_get_path_gotconfig");
1386 goto done;
1388 gotconfig_file = fopen(gotconfig_path, "ae");
1389 if (gotconfig_file == NULL) {
1390 err = got_error_from_errno2("fopen", gotconfig_path);
1391 goto done;
1393 if (asprintf(&gotconfig,
1394 "remote \"%s\" {\n"
1395 "\tserver %s\n"
1396 "\tprotocol %s\n"
1397 "%s%s%s"
1398 "\trepository \"%s\"\n"
1399 "%s%s%s"
1400 "%s%s%s"
1401 "%s"
1402 "%s"
1403 "}\n",
1404 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1405 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1406 remote_repo_path, branches ? "\tbranch { " : "",
1407 branches ? branches : "", branches ? "}\n" : "",
1408 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1409 mirror_references ? "\tmirror_references yes\n" : "",
1410 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1415 if (n != strlen(gotconfig)) {
1416 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1417 goto done;
1420 done:
1421 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1422 err = got_error_from_errno2("fclose", gotconfig_path);
1423 free(gotconfig_path);
1424 free(branches);
1425 return err;
1428 static const struct got_error *
1429 create_gitconfig(const char *git_url, const char *default_branch,
1430 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1431 struct got_pathlist_head *wanted_refs, int mirror_references,
1432 struct got_repository *repo)
1434 const struct got_error *err = NULL;
1435 char *gitconfig_path = NULL;
1436 char *gitconfig = NULL;
1437 FILE *gitconfig_file = NULL;
1438 char *branches = NULL, *refs = NULL;
1439 const char *branchname;
1440 ssize_t n;
1442 /* Create a config file Git can understand. */
1443 gitconfig_path = got_repo_get_path_gitconfig(repo);
1444 if (gitconfig_path == NULL) {
1445 err = got_error_from_errno("got_repo_get_path_gitconfig");
1446 goto done;
1448 gitconfig_file = fopen(gitconfig_path, "ae");
1449 if (gitconfig_file == NULL) {
1450 err = got_error_from_errno2("fopen", gitconfig_path);
1451 goto done;
1453 if (fetch_all_branches) {
1454 if (mirror_references) {
1455 if (asprintf(&branches,
1456 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1457 err = got_error_from_errno("asprintf");
1458 goto done;
1460 } else if (asprintf(&branches,
1461 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1462 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1463 err = got_error_from_errno("asprintf");
1464 goto done;
1466 } else if (!TAILQ_EMPTY(wanted_branches)) {
1467 struct got_pathlist_entry *pe;
1468 TAILQ_FOREACH(pe, wanted_branches, entry) {
1469 char *s;
1470 branchname = pe->path;
1471 if (strncmp(branchname, "refs/heads/", 11) == 0)
1472 branchname += 11;
1473 if (mirror_references) {
1474 if (asprintf(&s,
1475 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1476 branches ? branches : "",
1477 branchname, branchname) == -1) {
1478 err = got_error_from_errno("asprintf");
1479 goto done;
1481 } else if (asprintf(&s,
1482 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1483 branches ? branches : "",
1484 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1485 branchname) == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 free(branches);
1490 branches = s;
1492 } else {
1494 * If the server specified a default branch, use just that one.
1495 * Otherwise fall back to fetching all branches on next fetch.
1497 if (default_branch) {
1498 branchname = default_branch;
1499 if (strncmp(branchname, "refs/heads/", 11) == 0)
1500 branchname += 11;
1501 } else
1502 branchname = "*"; /* fall back to all branches */
1503 if (mirror_references) {
1504 if (asprintf(&branches,
1505 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1506 branchname, branchname) == -1) {
1507 err = got_error_from_errno("asprintf");
1508 goto done;
1510 } else if (asprintf(&branches,
1511 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1512 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1513 branchname) == -1) {
1514 err = got_error_from_errno("asprintf");
1515 goto done;
1518 if (!TAILQ_EMPTY(wanted_refs)) {
1519 struct got_pathlist_entry *pe;
1520 TAILQ_FOREACH(pe, wanted_refs, entry) {
1521 char *s;
1522 const char *refname = pe->path;
1523 if (strncmp(refname, "refs/", 5) == 0)
1524 refname += 5;
1525 if (mirror_references) {
1526 if (asprintf(&s,
1527 "%s\tfetch = refs/%s:refs/%s\n",
1528 refs ? refs : "", refname, refname) == -1) {
1529 err = got_error_from_errno("asprintf");
1530 goto done;
1532 } else if (asprintf(&s,
1533 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1534 refs ? refs : "",
1535 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1536 refname) == -1) {
1537 err = got_error_from_errno("asprintf");
1538 goto done;
1540 free(refs);
1541 refs = s;
1545 if (asprintf(&gitconfig,
1546 "[remote \"%s\"]\n"
1547 "\turl = %s\n"
1548 "%s"
1549 "%s"
1550 "\tfetch = refs/tags/*:refs/tags/*\n",
1551 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1552 refs ? refs : "") == -1) {
1553 err = got_error_from_errno("asprintf");
1554 goto done;
1556 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1557 if (n != strlen(gitconfig)) {
1558 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1559 goto done;
1561 done:
1562 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1563 err = got_error_from_errno2("fclose", gitconfig_path);
1564 free(gitconfig_path);
1565 free(branches);
1566 return err;
1569 static const struct got_error *
1570 create_config_files(const char *proto, const char *host, const char *port,
1571 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1572 int mirror_references, struct got_pathlist_head *symrefs,
1573 struct got_pathlist_head *wanted_branches,
1574 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1576 const struct got_error *err = NULL;
1577 const char *default_branch = NULL;
1578 struct got_pathlist_entry *pe;
1581 * If we asked for a set of wanted branches then use the first
1582 * one of those.
1584 if (!TAILQ_EMPTY(wanted_branches)) {
1585 pe = TAILQ_FIRST(wanted_branches);
1586 default_branch = pe->path;
1587 } else {
1588 /* First HEAD ref listed by server is the default branch. */
1589 TAILQ_FOREACH(pe, symrefs, entry) {
1590 const char *refname = pe->path;
1591 const char *target = pe->data;
1593 if (strcmp(refname, GOT_REF_HEAD) != 0)
1594 continue;
1596 default_branch = target;
1597 break;
1601 /* Create got.conf(5). */
1602 err = create_gotconfig(proto, host, port, remote_repo_path,
1603 default_branch, fetch_all_branches, wanted_branches,
1604 wanted_refs, mirror_references, repo);
1605 if (err)
1606 return err;
1608 /* Create a config file Git can understand. */
1609 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1610 wanted_branches, wanted_refs, mirror_references, repo);
1613 static const struct got_error *
1614 cmd_clone(int argc, char *argv[])
1616 const struct got_error *error = NULL;
1617 const char *uri, *dirname;
1618 char *proto, *host, *port, *repo_name, *server_path;
1619 char *default_destdir = NULL, *id_str = NULL;
1620 const char *repo_path;
1621 struct got_repository *repo = NULL;
1622 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1623 struct got_pathlist_entry *pe;
1624 struct got_object_id *pack_hash = NULL;
1625 int ch, fetchfd = -1, fetchstatus;
1626 pid_t fetchpid = -1;
1627 struct got_fetch_progress_arg fpa;
1628 char *git_url = NULL;
1629 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1630 int bflag = 0, list_refs_only = 0;
1631 int *pack_fds = NULL;
1633 TAILQ_INIT(&refs);
1634 TAILQ_INIT(&symrefs);
1635 TAILQ_INIT(&wanted_branches);
1636 TAILQ_INIT(&wanted_refs);
1638 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1639 switch (ch) {
1640 case 'a':
1641 fetch_all_branches = 1;
1642 break;
1643 case 'b':
1644 error = got_pathlist_append(&wanted_branches,
1645 optarg, NULL);
1646 if (error)
1647 return error;
1648 bflag = 1;
1649 break;
1650 case 'l':
1651 list_refs_only = 1;
1652 break;
1653 case 'm':
1654 mirror_references = 1;
1655 break;
1656 case 'q':
1657 verbosity = -1;
1658 break;
1659 case 'R':
1660 error = got_pathlist_append(&wanted_refs,
1661 optarg, NULL);
1662 if (error)
1663 return error;
1664 break;
1665 case 'v':
1666 if (verbosity < 0)
1667 verbosity = 0;
1668 else if (verbosity < 3)
1669 verbosity++;
1670 break;
1671 default:
1672 usage_clone();
1673 break;
1676 argc -= optind;
1677 argv += optind;
1679 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1680 option_conflict('a', 'b');
1681 if (list_refs_only) {
1682 if (!TAILQ_EMPTY(&wanted_branches))
1683 option_conflict('l', 'b');
1684 if (fetch_all_branches)
1685 option_conflict('l', 'a');
1686 if (mirror_references)
1687 option_conflict('l', 'm');
1688 if (!TAILQ_EMPTY(&wanted_refs))
1689 option_conflict('l', 'R');
1692 uri = argv[0];
1694 if (argc == 1)
1695 dirname = NULL;
1696 else if (argc == 2)
1697 dirname = argv[1];
1698 else
1699 usage_clone();
1701 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1702 &repo_name, uri);
1703 if (error)
1704 goto done;
1706 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1707 host, port ? ":" : "", port ? port : "",
1708 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1709 error = got_error_from_errno("asprintf");
1710 goto done;
1713 if (strcmp(proto, "git") == 0) {
1714 #ifndef PROFILE
1715 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1716 "sendfd dns inet unveil", NULL) == -1)
1717 err(1, "pledge");
1718 #endif
1719 } else if (strcmp(proto, "git+ssh") == 0 ||
1720 strcmp(proto, "ssh") == 0 ||
1721 strcmp(proto, "git+http") == 0 ||
1722 strcmp(proto, "http") == 0 ||
1723 strcmp(proto, "git+https") == 0 ||
1724 strcmp(proto, "https") == 0) {
1725 #ifndef PROFILE
1726 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1727 "sendfd unveil", NULL) == -1)
1728 err(1, "pledge");
1729 #endif
1730 } else {
1731 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1732 goto done;
1734 if (dirname == NULL) {
1735 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1736 error = got_error_from_errno("asprintf");
1737 goto done;
1739 repo_path = default_destdir;
1740 } else
1741 repo_path = dirname;
1743 if (!list_refs_only) {
1744 error = got_path_mkdir(repo_path);
1745 if (error &&
1746 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1747 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1748 goto done;
1749 if (!got_path_dir_is_empty(repo_path)) {
1750 error = got_error_path(repo_path,
1751 GOT_ERR_DIR_NOT_EMPTY);
1752 goto done;
1756 error = got_dial_apply_unveil(proto);
1757 if (error)
1758 goto done;
1760 error = apply_unveil(repo_path, 0, NULL);
1761 if (error)
1762 goto done;
1764 if (verbosity >= 0)
1765 printf("Connecting to %s\n", git_url);
1767 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1768 server_path, verbosity);
1769 if (error)
1770 goto done;
1772 #ifndef PROFILE
1773 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
1774 NULL) == -1)
1775 err(1, "pledge");
1776 #endif
1777 if (!list_refs_only) {
1778 error = got_repo_init(repo_path, NULL, GOT_HASH_SHA1);
1779 if (error)
1780 goto done;
1781 error = got_repo_pack_fds_open(&pack_fds);
1782 if (error != NULL)
1783 goto done;
1784 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1785 if (error)
1786 goto done;
1789 fpa.last_scaled_size[0] = '\0';
1790 fpa.last_p_indexed = -1;
1791 fpa.last_p_resolved = -1;
1792 fpa.verbosity = verbosity;
1793 fpa.create_configs = 1;
1794 fpa.configs_created = 0;
1795 fpa.repo = repo;
1796 fpa.config_info.symrefs = &symrefs;
1797 fpa.config_info.wanted_branches = &wanted_branches;
1798 fpa.config_info.wanted_refs = &wanted_refs;
1799 fpa.config_info.proto = proto;
1800 fpa.config_info.host = host;
1801 fpa.config_info.port = port;
1802 fpa.config_info.remote_repo_path = server_path;
1803 fpa.config_info.git_url = git_url;
1804 fpa.config_info.fetch_all_branches = fetch_all_branches;
1805 fpa.config_info.mirror_references = mirror_references;
1806 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1807 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1808 fetch_all_branches, &wanted_branches, &wanted_refs,
1809 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1810 fetch_progress, &fpa);
1811 if (error)
1812 goto done;
1814 if (list_refs_only) {
1815 error = list_remote_refs(&symrefs, &refs);
1816 goto done;
1819 if (pack_hash == NULL) {
1820 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1821 "server sent an empty pack file");
1822 goto done;
1824 error = got_object_id_str(&id_str, pack_hash);
1825 if (error)
1826 goto done;
1827 if (verbosity >= 0)
1828 printf("\nFetched %s.pack\n", id_str);
1829 free(id_str);
1831 /* Set up references provided with the pack file. */
1832 TAILQ_FOREACH(pe, &refs, entry) {
1833 const char *refname = pe->path;
1834 struct got_object_id *id = pe->data;
1835 char *remote_refname;
1837 if (is_wanted_ref(&wanted_refs, refname) &&
1838 !mirror_references) {
1839 error = create_wanted_ref(refname, id,
1840 GOT_FETCH_DEFAULT_REMOTE_NAME,
1841 verbosity - 1, repo);
1842 if (error)
1843 goto done;
1844 continue;
1847 error = create_ref(refname, id, verbosity - 1, repo);
1848 if (error)
1849 goto done;
1851 if (mirror_references)
1852 continue;
1854 if (strncmp("refs/heads/", refname, 11) != 0)
1855 continue;
1857 if (asprintf(&remote_refname,
1858 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1859 refname + 11) == -1) {
1860 error = got_error_from_errno("asprintf");
1861 goto done;
1863 error = create_ref(remote_refname, id, verbosity - 1, repo);
1864 free(remote_refname);
1865 if (error)
1866 goto done;
1869 /* Set the HEAD reference if the server provided one. */
1870 TAILQ_FOREACH(pe, &symrefs, entry) {
1871 struct got_reference *target_ref;
1872 const char *refname = pe->path;
1873 const char *target = pe->data;
1874 char *remote_refname = NULL, *remote_target = NULL;
1876 if (strcmp(refname, GOT_REF_HEAD) != 0)
1877 continue;
1879 error = got_ref_open(&target_ref, repo, target, 0);
1880 if (error) {
1881 if (error->code == GOT_ERR_NOT_REF) {
1882 error = NULL;
1883 continue;
1885 goto done;
1888 error = create_symref(refname, target_ref, verbosity, repo);
1889 got_ref_close(target_ref);
1890 if (error)
1891 goto done;
1893 if (mirror_references)
1894 continue;
1896 if (strncmp("refs/heads/", target, 11) != 0)
1897 continue;
1899 if (asprintf(&remote_refname,
1900 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1901 refname) == -1) {
1902 error = got_error_from_errno("asprintf");
1903 goto done;
1905 if (asprintf(&remote_target,
1906 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1907 target + 11) == -1) {
1908 error = got_error_from_errno("asprintf");
1909 free(remote_refname);
1910 goto done;
1912 error = got_ref_open(&target_ref, repo, remote_target, 0);
1913 if (error) {
1914 free(remote_refname);
1915 free(remote_target);
1916 if (error->code == GOT_ERR_NOT_REF) {
1917 error = NULL;
1918 continue;
1920 goto done;
1922 error = create_symref(remote_refname, target_ref,
1923 verbosity - 1, repo);
1924 free(remote_refname);
1925 free(remote_target);
1926 got_ref_close(target_ref);
1927 if (error)
1928 goto done;
1930 if (pe == NULL) {
1932 * We failed to set the HEAD reference. If we asked for
1933 * a set of wanted branches use the first of one of those
1934 * which could be fetched instead.
1936 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1937 const char *target = pe->path;
1938 struct got_reference *target_ref;
1940 error = got_ref_open(&target_ref, repo, target, 0);
1941 if (error) {
1942 if (error->code == GOT_ERR_NOT_REF) {
1943 error = NULL;
1944 continue;
1946 goto done;
1949 error = create_symref(GOT_REF_HEAD, target_ref,
1950 verbosity, repo);
1951 got_ref_close(target_ref);
1952 if (error)
1953 goto done;
1954 break;
1957 if (!fpa.configs_created && pe != NULL) {
1958 error = create_config_files(fpa.config_info.proto,
1959 fpa.config_info.host, fpa.config_info.port,
1960 fpa.config_info.remote_repo_path,
1961 fpa.config_info.git_url,
1962 fpa.config_info.fetch_all_branches,
1963 fpa.config_info.mirror_references,
1964 fpa.config_info.symrefs,
1965 fpa.config_info.wanted_branches,
1966 fpa.config_info.wanted_refs, fpa.repo);
1967 if (error)
1968 goto done;
1972 if (verbosity >= 0)
1973 printf("Created %s repository '%s'\n",
1974 mirror_references ? "mirrored" : "cloned", repo_path);
1975 done:
1976 if (pack_fds) {
1977 const struct got_error *pack_err =
1978 got_repo_pack_fds_close(pack_fds);
1979 if (error == NULL)
1980 error = pack_err;
1982 if (fetchpid > 0) {
1983 if (kill(fetchpid, SIGTERM) == -1)
1984 error = got_error_from_errno("kill");
1985 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1986 error = got_error_from_errno("waitpid");
1988 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1989 error = got_error_from_errno("close");
1990 if (repo) {
1991 const struct got_error *close_err = got_repo_close(repo);
1992 if (error == NULL)
1993 error = close_err;
1995 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1996 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1997 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1998 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1999 free(pack_hash);
2000 free(proto);
2001 free(host);
2002 free(port);
2003 free(server_path);
2004 free(repo_name);
2005 free(default_destdir);
2006 free(git_url);
2007 return error;
2010 static const struct got_error *
2011 update_ref(struct got_reference *ref, struct got_object_id *new_id,
2012 int replace_tags, int verbosity, struct got_repository *repo)
2014 const struct got_error *err = NULL;
2015 char *new_id_str = NULL;
2016 struct got_object_id *old_id = NULL;
2018 err = got_object_id_str(&new_id_str, new_id);
2019 if (err)
2020 goto done;
2022 if (!replace_tags &&
2023 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
2024 err = got_ref_resolve(&old_id, repo, ref);
2025 if (err)
2026 goto done;
2027 if (got_object_id_cmp(old_id, new_id) == 0)
2028 goto done;
2029 if (verbosity >= 0) {
2030 printf("Rejecting update of existing tag %s: %s\n",
2031 got_ref_get_name(ref), new_id_str);
2033 goto done;
2036 if (got_ref_is_symbolic(ref)) {
2037 if (verbosity >= 0) {
2038 printf("Replacing reference %s: %s\n",
2039 got_ref_get_name(ref),
2040 got_ref_get_symref_target(ref));
2042 err = got_ref_change_symref_to_ref(ref, new_id);
2043 if (err)
2044 goto done;
2045 err = got_ref_write(ref, repo);
2046 if (err)
2047 goto done;
2048 } else {
2049 err = got_ref_resolve(&old_id, repo, ref);
2050 if (err)
2051 goto done;
2052 if (got_object_id_cmp(old_id, new_id) == 0)
2053 goto done;
2055 err = got_ref_change_ref(ref, new_id);
2056 if (err)
2057 goto done;
2058 err = got_ref_write(ref, repo);
2059 if (err)
2060 goto done;
2063 if (verbosity >= 0)
2064 printf("Updated %s: %s\n", got_ref_get_name(ref),
2065 new_id_str);
2066 done:
2067 free(old_id);
2068 free(new_id_str);
2069 return err;
2072 static const struct got_error *
2073 update_symref(const char *refname, struct got_reference *target_ref,
2074 int verbosity, struct got_repository *repo)
2076 const struct got_error *err = NULL, *unlock_err;
2077 struct got_reference *symref;
2078 int symref_is_locked = 0;
2080 err = got_ref_open(&symref, repo, refname, 1);
2081 if (err) {
2082 if (err->code != GOT_ERR_NOT_REF)
2083 return err;
2084 err = got_ref_alloc_symref(&symref, refname, target_ref);
2085 if (err)
2086 goto done;
2088 err = got_ref_write(symref, repo);
2089 if (err)
2090 goto done;
2092 if (verbosity >= 0)
2093 printf("Created reference %s: %s\n",
2094 got_ref_get_name(symref),
2095 got_ref_get_symref_target(symref));
2096 } else {
2097 symref_is_locked = 1;
2099 if (strcmp(got_ref_get_symref_target(symref),
2100 got_ref_get_name(target_ref)) == 0)
2101 goto done;
2103 err = got_ref_change_symref(symref,
2104 got_ref_get_name(target_ref));
2105 if (err)
2106 goto done;
2108 err = got_ref_write(symref, repo);
2109 if (err)
2110 goto done;
2112 if (verbosity >= 0)
2113 printf("Updated %s: %s\n", got_ref_get_name(symref),
2114 got_ref_get_symref_target(symref));
2117 done:
2118 if (symref_is_locked) {
2119 unlock_err = got_ref_unlock(symref);
2120 if (unlock_err && err == NULL)
2121 err = unlock_err;
2123 got_ref_close(symref);
2124 return err;
2127 __dead static void
2128 usage_fetch(void)
2130 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2131 "[-R reference] [-r repository-path] [remote-repository]\n",
2132 getprogname());
2133 exit(1);
2136 static const struct got_error *
2137 delete_missing_ref(struct got_reference *ref,
2138 int verbosity, struct got_repository *repo)
2140 const struct got_error *err = NULL;
2141 struct got_object_id *id = NULL;
2142 char *id_str = NULL;
2144 if (got_ref_is_symbolic(ref)) {
2145 err = got_ref_delete(ref, repo);
2146 if (err)
2147 return err;
2148 if (verbosity >= 0) {
2149 printf("Deleted %s: %s\n",
2150 got_ref_get_name(ref),
2151 got_ref_get_symref_target(ref));
2153 } else {
2154 err = got_ref_resolve(&id, repo, ref);
2155 if (err)
2156 return err;
2157 err = got_object_id_str(&id_str, id);
2158 if (err)
2159 goto done;
2161 err = got_ref_delete(ref, repo);
2162 if (err)
2163 goto done;
2164 if (verbosity >= 0) {
2165 printf("Deleted %s: %s\n",
2166 got_ref_get_name(ref), id_str);
2169 done:
2170 free(id);
2171 free(id_str);
2172 return err;
2175 static const struct got_error *
2176 delete_missing_refs(struct got_pathlist_head *their_refs,
2177 struct got_pathlist_head *their_symrefs,
2178 const struct got_remote_repo *remote,
2179 int verbosity, struct got_repository *repo)
2181 const struct got_error *err = NULL, *unlock_err;
2182 struct got_reflist_head my_refs;
2183 struct got_reflist_entry *re;
2184 struct got_pathlist_entry *pe;
2185 char *remote_namespace = NULL;
2186 char *local_refname = NULL;
2188 TAILQ_INIT(&my_refs);
2190 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2191 == -1)
2192 return got_error_from_errno("asprintf");
2194 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2195 if (err)
2196 goto done;
2198 TAILQ_FOREACH(re, &my_refs, entry) {
2199 const char *refname = got_ref_get_name(re->ref);
2200 const char *their_refname;
2202 if (remote->mirror_references) {
2203 their_refname = refname;
2204 } else {
2205 if (strncmp(refname, remote_namespace,
2206 strlen(remote_namespace)) == 0) {
2207 if (strcmp(refname + strlen(remote_namespace),
2208 GOT_REF_HEAD) == 0)
2209 continue;
2210 if (asprintf(&local_refname, "refs/heads/%s",
2211 refname + strlen(remote_namespace)) == -1) {
2212 err = got_error_from_errno("asprintf");
2213 goto done;
2215 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2216 continue;
2218 their_refname = local_refname;
2221 TAILQ_FOREACH(pe, their_refs, entry) {
2222 if (strcmp(their_refname, pe->path) == 0)
2223 break;
2225 if (pe != NULL)
2226 continue;
2228 TAILQ_FOREACH(pe, their_symrefs, entry) {
2229 if (strcmp(their_refname, pe->path) == 0)
2230 break;
2232 if (pe != NULL)
2233 continue;
2235 err = delete_missing_ref(re->ref, verbosity, repo);
2236 if (err)
2237 break;
2239 if (local_refname) {
2240 struct got_reference *ref;
2241 err = got_ref_open(&ref, repo, local_refname, 1);
2242 if (err) {
2243 if (err->code != GOT_ERR_NOT_REF)
2244 break;
2245 free(local_refname);
2246 local_refname = NULL;
2247 continue;
2249 err = delete_missing_ref(ref, verbosity, repo);
2250 if (err)
2251 break;
2252 unlock_err = got_ref_unlock(ref);
2253 got_ref_close(ref);
2254 if (unlock_err && err == NULL) {
2255 err = unlock_err;
2256 break;
2259 free(local_refname);
2260 local_refname = NULL;
2263 done:
2264 got_ref_list_free(&my_refs);
2265 free(remote_namespace);
2266 free(local_refname);
2267 return err;
2270 static const struct got_error *
2271 update_wanted_ref(const char *refname, struct got_object_id *id,
2272 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2274 const struct got_error *err, *unlock_err;
2275 char *remote_refname;
2276 struct got_reference *ref;
2278 if (strncmp("refs/", refname, 5) == 0)
2279 refname += 5;
2281 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2282 remote_repo_name, refname) == -1)
2283 return got_error_from_errno("asprintf");
2285 err = got_ref_open(&ref, repo, remote_refname, 1);
2286 if (err) {
2287 if (err->code != GOT_ERR_NOT_REF)
2288 goto done;
2289 err = create_ref(remote_refname, id, verbosity, repo);
2290 } else {
2291 err = update_ref(ref, id, 0, verbosity, repo);
2292 unlock_err = got_ref_unlock(ref);
2293 if (unlock_err && err == NULL)
2294 err = unlock_err;
2295 got_ref_close(ref);
2297 done:
2298 free(remote_refname);
2299 return err;
2302 static const struct got_error *
2303 delete_ref(struct got_repository *repo, struct got_reference *ref)
2305 const struct got_error *err = NULL;
2306 struct got_object_id *id = NULL;
2307 char *id_str = NULL;
2308 const char *target;
2310 if (got_ref_is_symbolic(ref)) {
2311 target = got_ref_get_symref_target(ref);
2312 } else {
2313 err = got_ref_resolve(&id, repo, ref);
2314 if (err)
2315 goto done;
2316 err = got_object_id_str(&id_str, id);
2317 if (err)
2318 goto done;
2319 target = id_str;
2322 err = got_ref_delete(ref, repo);
2323 if (err)
2324 goto done;
2326 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2327 done:
2328 free(id);
2329 free(id_str);
2330 return err;
2333 static const struct got_error *
2334 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2336 const struct got_error *err = NULL;
2337 struct got_reflist_head refs;
2338 struct got_reflist_entry *re;
2339 char *prefix;
2341 TAILQ_INIT(&refs);
2343 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2344 err = got_error_from_errno("asprintf");
2345 goto done;
2347 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2348 if (err)
2349 goto done;
2351 TAILQ_FOREACH(re, &refs, entry)
2352 delete_ref(repo, re->ref);
2353 done:
2354 got_ref_list_free(&refs);
2355 return err;
2358 static const struct got_error *
2359 cmd_fetch(int argc, char *argv[])
2361 const struct got_error *error = NULL, *unlock_err;
2362 char *cwd = NULL, *repo_path = NULL;
2363 const char *remote_name;
2364 char *proto = NULL, *host = NULL, *port = NULL;
2365 char *repo_name = NULL, *server_path = NULL;
2366 const struct got_remote_repo *remotes;
2367 struct got_remote_repo *remote = NULL;
2368 int nremotes;
2369 char *id_str = NULL;
2370 struct got_repository *repo = NULL;
2371 struct got_worktree *worktree = NULL;
2372 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2373 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2374 char *head_refname = NULL;
2375 struct got_pathlist_entry *pe;
2376 struct got_reflist_head remote_refs;
2377 struct got_reflist_entry *re;
2378 struct got_object_id *pack_hash = NULL;
2379 int i, ch, fetchfd = -1, fetchstatus;
2380 pid_t fetchpid = -1;
2381 struct got_fetch_progress_arg fpa;
2382 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2383 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2384 int *pack_fds = NULL, have_bflag = 0;
2385 const char *remote_head = NULL, *worktree_branch = NULL;
2387 TAILQ_INIT(&refs);
2388 TAILQ_INIT(&symrefs);
2389 TAILQ_INIT(&remote_refs);
2390 TAILQ_INIT(&wanted_branches);
2391 TAILQ_INIT(&wanted_refs);
2393 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2394 switch (ch) {
2395 case 'a':
2396 fetch_all_branches = 1;
2397 break;
2398 case 'b':
2399 error = got_pathlist_append(&wanted_branches,
2400 optarg, NULL);
2401 if (error)
2402 return error;
2403 have_bflag = 1;
2404 break;
2405 case 'd':
2406 delete_refs = 1;
2407 break;
2408 case 'l':
2409 list_refs_only = 1;
2410 break;
2411 case 'q':
2412 verbosity = -1;
2413 break;
2414 case 'R':
2415 error = got_pathlist_append(&wanted_refs,
2416 optarg, NULL);
2417 if (error)
2418 return error;
2419 break;
2420 case 'r':
2421 repo_path = realpath(optarg, NULL);
2422 if (repo_path == NULL)
2423 return got_error_from_errno2("realpath",
2424 optarg);
2425 got_path_strip_trailing_slashes(repo_path);
2426 break;
2427 case 't':
2428 replace_tags = 1;
2429 break;
2430 case 'v':
2431 if (verbosity < 0)
2432 verbosity = 0;
2433 else if (verbosity < 3)
2434 verbosity++;
2435 break;
2436 case 'X':
2437 delete_remote = 1;
2438 break;
2439 default:
2440 usage_fetch();
2441 break;
2444 argc -= optind;
2445 argv += optind;
2447 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2448 option_conflict('a', 'b');
2449 if (list_refs_only) {
2450 if (!TAILQ_EMPTY(&wanted_branches))
2451 option_conflict('l', 'b');
2452 if (fetch_all_branches)
2453 option_conflict('l', 'a');
2454 if (delete_refs)
2455 option_conflict('l', 'd');
2456 if (delete_remote)
2457 option_conflict('l', 'X');
2459 if (delete_remote) {
2460 if (fetch_all_branches)
2461 option_conflict('X', 'a');
2462 if (!TAILQ_EMPTY(&wanted_branches))
2463 option_conflict('X', 'b');
2464 if (delete_refs)
2465 option_conflict('X', 'd');
2466 if (replace_tags)
2467 option_conflict('X', 't');
2468 if (!TAILQ_EMPTY(&wanted_refs))
2469 option_conflict('X', 'R');
2472 if (argc == 0) {
2473 if (delete_remote)
2474 errx(1, "-X option requires a remote name");
2475 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2476 } else if (argc == 1)
2477 remote_name = argv[0];
2478 else
2479 usage_fetch();
2481 cwd = getcwd(NULL, 0);
2482 if (cwd == NULL) {
2483 error = got_error_from_errno("getcwd");
2484 goto done;
2487 error = got_repo_pack_fds_open(&pack_fds);
2488 if (error != NULL)
2489 goto done;
2491 if (repo_path == NULL) {
2492 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2493 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2494 goto done;
2495 else
2496 error = NULL;
2497 if (worktree) {
2498 repo_path =
2499 strdup(got_worktree_get_repo_path(worktree));
2500 if (repo_path == NULL)
2501 error = got_error_from_errno("strdup");
2502 if (error)
2503 goto done;
2504 } else {
2505 repo_path = strdup(cwd);
2506 if (repo_path == NULL) {
2507 error = got_error_from_errno("strdup");
2508 goto done;
2513 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2514 if (error)
2515 goto done;
2517 if (delete_remote) {
2518 error = delete_refs_for_remote(repo, remote_name);
2519 goto done; /* nothing else to do */
2522 if (worktree) {
2523 worktree_conf = got_worktree_get_gotconfig(worktree);
2524 if (worktree_conf) {
2525 got_gotconfig_get_remotes(&nremotes, &remotes,
2526 worktree_conf);
2527 for (i = 0; i < nremotes; i++) {
2528 if (strcmp(remotes[i].name, remote_name) == 0) {
2529 error = got_repo_remote_repo_dup(&remote,
2530 &remotes[i]);
2531 if (error)
2532 goto done;
2533 break;
2538 if (remote == NULL) {
2539 repo_conf = got_repo_get_gotconfig(repo);
2540 if (repo_conf) {
2541 got_gotconfig_get_remotes(&nremotes, &remotes,
2542 repo_conf);
2543 for (i = 0; i < nremotes; i++) {
2544 if (strcmp(remotes[i].name, remote_name) == 0) {
2545 error = got_repo_remote_repo_dup(&remote,
2546 &remotes[i]);
2547 if (error)
2548 goto done;
2549 break;
2554 if (remote == NULL) {
2555 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2556 for (i = 0; i < nremotes; i++) {
2557 if (strcmp(remotes[i].name, remote_name) == 0) {
2558 error = got_repo_remote_repo_dup(&remote,
2559 &remotes[i]);
2560 if (error)
2561 goto done;
2562 break;
2566 if (remote == NULL) {
2567 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2568 goto done;
2571 if (TAILQ_EMPTY(&wanted_branches)) {
2572 if (!fetch_all_branches)
2573 fetch_all_branches = remote->fetch_all_branches;
2574 for (i = 0; i < remote->nfetch_branches; i++) {
2575 error = got_pathlist_append(&wanted_branches,
2576 remote->fetch_branches[i], NULL);
2577 if (error)
2578 goto done;
2581 if (TAILQ_EMPTY(&wanted_refs)) {
2582 for (i = 0; i < remote->nfetch_refs; i++) {
2583 error = got_pathlist_append(&wanted_refs,
2584 remote->fetch_refs[i], NULL);
2585 if (error)
2586 goto done;
2590 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2591 &repo_name, remote->fetch_url);
2592 if (error)
2593 goto done;
2595 if (strcmp(proto, "git") == 0) {
2596 #ifndef PROFILE
2597 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2598 "sendfd dns inet unveil", NULL) == -1)
2599 err(1, "pledge");
2600 #endif
2601 } else if (strcmp(proto, "git+ssh") == 0 ||
2602 strcmp(proto, "ssh") == 0 ||
2603 strcmp(proto, "git+http") == 0 ||
2604 strcmp(proto, "http") == 0 ||
2605 strcmp(proto, "git+https") == 0 ||
2606 strcmp(proto, "https") == 0) {
2607 #ifndef PROFILE
2608 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2609 "sendfd unveil", NULL) == -1)
2610 err(1, "pledge");
2611 #endif
2612 } else {
2613 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2614 goto done;
2617 error = got_dial_apply_unveil(proto);
2618 if (error)
2619 goto done;
2621 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2622 if (error)
2623 goto done;
2625 if (worktree) {
2626 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2627 if (head_refname == NULL) {
2628 error = got_error_from_errno("strdup");
2629 goto done;
2632 /* Release work tree lock. */
2633 got_worktree_close(worktree);
2634 worktree = NULL;
2637 if (verbosity >= 0) {
2638 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2639 remote->name, proto, host,
2640 port ? ":" : "", port ? port : "",
2641 *server_path == '/' ? "" : "/", server_path);
2644 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2645 server_path, verbosity);
2646 if (error)
2647 goto done;
2648 #ifndef PROFILE
2649 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
2650 NULL) == -1)
2651 err(1, "pledge");
2652 #endif
2653 if (!have_bflag) {
2655 * If set, get this remote's HEAD ref target so
2656 * if it has changed on the server we can fetch it.
2658 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2659 got_ref_cmp_by_name, repo);
2660 if (error)
2661 goto done;
2663 TAILQ_FOREACH(re, &remote_refs, entry) {
2664 const char *remote_refname, *remote_target;
2665 size_t remote_name_len;
2667 if (!got_ref_is_symbolic(re->ref))
2668 continue;
2670 remote_name_len = strlen(remote->name);
2671 remote_refname = got_ref_get_name(re->ref);
2673 /* we only want refs/remotes/$remote->name/HEAD */
2674 if (strncmp(remote_refname + 13, remote->name,
2675 remote_name_len) != 0)
2676 continue;
2678 if (strcmp(remote_refname + remote_name_len + 14,
2679 GOT_REF_HEAD) != 0)
2680 continue;
2683 * Take the name itself because we already
2684 * only match with refs/heads/ in fetch_pack().
2686 remote_target = got_ref_get_symref_target(re->ref);
2687 remote_head = remote_target + remote_name_len + 14;
2688 break;
2691 if (head_refname &&
2692 strncmp(head_refname, "refs/heads/", 11) == 0)
2693 worktree_branch = head_refname;
2696 fpa.last_scaled_size[0] = '\0';
2697 fpa.last_p_indexed = -1;
2698 fpa.last_p_resolved = -1;
2699 fpa.verbosity = verbosity;
2700 fpa.repo = repo;
2701 fpa.create_configs = 0;
2702 fpa.configs_created = 0;
2703 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2705 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2706 remote->mirror_references, fetch_all_branches, &wanted_branches,
2707 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2708 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2709 if (error)
2710 goto done;
2712 if (list_refs_only) {
2713 error = list_remote_refs(&symrefs, &refs);
2714 goto done;
2717 if (pack_hash == NULL) {
2718 if (verbosity >= 0)
2719 printf("Already up-to-date\n");
2720 } else if (verbosity >= 0) {
2721 error = got_object_id_str(&id_str, pack_hash);
2722 if (error)
2723 goto done;
2724 printf("\nFetched %s.pack\n", id_str);
2725 free(id_str);
2726 id_str = NULL;
2729 /* Update references provided with the pack file. */
2730 TAILQ_FOREACH(pe, &refs, entry) {
2731 const char *refname = pe->path;
2732 struct got_object_id *id = pe->data;
2733 struct got_reference *ref;
2734 char *remote_refname;
2736 if (is_wanted_ref(&wanted_refs, refname) &&
2737 !remote->mirror_references) {
2738 error = update_wanted_ref(refname, id,
2739 remote->name, verbosity, repo);
2740 if (error)
2741 goto done;
2742 continue;
2745 if (remote->mirror_references ||
2746 strncmp("refs/tags/", refname, 10) == 0) {
2747 error = got_ref_open(&ref, repo, refname, 1);
2748 if (error) {
2749 if (error->code != GOT_ERR_NOT_REF)
2750 goto done;
2751 error = create_ref(refname, id, verbosity,
2752 repo);
2753 if (error)
2754 goto done;
2755 } else {
2756 error = update_ref(ref, id, replace_tags,
2757 verbosity, repo);
2758 unlock_err = got_ref_unlock(ref);
2759 if (unlock_err && error == NULL)
2760 error = unlock_err;
2761 got_ref_close(ref);
2762 if (error)
2763 goto done;
2765 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2766 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2767 remote_name, refname + 11) == -1) {
2768 error = got_error_from_errno("asprintf");
2769 goto done;
2772 error = got_ref_open(&ref, repo, remote_refname, 1);
2773 if (error) {
2774 if (error->code != GOT_ERR_NOT_REF)
2775 goto done;
2776 error = create_ref(remote_refname, id,
2777 verbosity, repo);
2778 if (error)
2779 goto done;
2780 } else {
2781 error = update_ref(ref, id, replace_tags,
2782 verbosity, repo);
2783 unlock_err = got_ref_unlock(ref);
2784 if (unlock_err && error == NULL)
2785 error = unlock_err;
2786 got_ref_close(ref);
2787 if (error)
2788 goto done;
2791 /* Also create a local branch if none exists yet. */
2792 error = got_ref_open(&ref, repo, refname, 1);
2793 if (error) {
2794 if (error->code != GOT_ERR_NOT_REF)
2795 goto done;
2796 error = create_ref(refname, id, verbosity,
2797 repo);
2798 if (error)
2799 goto done;
2800 } else {
2801 unlock_err = got_ref_unlock(ref);
2802 if (unlock_err && error == NULL)
2803 error = unlock_err;
2804 got_ref_close(ref);
2808 if (delete_refs) {
2809 error = delete_missing_refs(&refs, &symrefs, remote,
2810 verbosity, repo);
2811 if (error)
2812 goto done;
2815 if (!remote->mirror_references) {
2816 /* Update remote HEAD reference if the server provided one. */
2817 TAILQ_FOREACH(pe, &symrefs, entry) {
2818 struct got_reference *target_ref;
2819 const char *refname = pe->path;
2820 const char *target = pe->data;
2821 char *remote_refname = NULL, *remote_target = NULL;
2823 if (strcmp(refname, GOT_REF_HEAD) != 0)
2824 continue;
2826 if (strncmp("refs/heads/", target, 11) != 0)
2827 continue;
2829 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2830 remote->name, refname) == -1) {
2831 error = got_error_from_errno("asprintf");
2832 goto done;
2834 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2835 remote->name, target + 11) == -1) {
2836 error = got_error_from_errno("asprintf");
2837 free(remote_refname);
2838 goto done;
2841 error = got_ref_open(&target_ref, repo, remote_target,
2843 if (error) {
2844 free(remote_refname);
2845 free(remote_target);
2846 if (error->code == GOT_ERR_NOT_REF) {
2847 error = NULL;
2848 continue;
2850 goto done;
2852 error = update_symref(remote_refname, target_ref,
2853 verbosity, repo);
2854 free(remote_refname);
2855 free(remote_target);
2856 got_ref_close(target_ref);
2857 if (error)
2858 goto done;
2861 done:
2862 if (fetchpid > 0) {
2863 if (kill(fetchpid, SIGTERM) == -1)
2864 error = got_error_from_errno("kill");
2865 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2866 error = got_error_from_errno("waitpid");
2868 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2869 error = got_error_from_errno("close");
2870 if (repo) {
2871 const struct got_error *close_err = got_repo_close(repo);
2872 if (error == NULL)
2873 error = close_err;
2875 if (worktree)
2876 got_worktree_close(worktree);
2877 if (pack_fds) {
2878 const struct got_error *pack_err =
2879 got_repo_pack_fds_close(pack_fds);
2880 if (error == NULL)
2881 error = pack_err;
2883 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2884 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2885 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2886 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2887 got_ref_list_free(&remote_refs);
2888 got_repo_free_remote_repo_data(remote);
2889 free(remote);
2890 free(head_refname);
2891 free(id_str);
2892 free(cwd);
2893 free(repo_path);
2894 free(pack_hash);
2895 free(proto);
2896 free(host);
2897 free(port);
2898 free(server_path);
2899 free(repo_name);
2900 return error;
2904 __dead static void
2905 usage_checkout(void)
2907 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2908 "[-p path-prefix] repository-path [work-tree-path]\n",
2909 getprogname());
2910 exit(1);
2913 static void
2914 show_worktree_base_ref_warning(void)
2916 fprintf(stderr, "%s: warning: could not create a reference "
2917 "to the work tree's base commit; the commit could be "
2918 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2919 "repository writable and running 'got update' will prevent this\n",
2920 getprogname());
2923 struct got_checkout_progress_arg {
2924 const char *worktree_path;
2925 int had_base_commit_ref_error;
2926 int verbosity;
2929 static const struct got_error *
2930 checkout_progress(void *arg, unsigned char status, const char *path)
2932 struct got_checkout_progress_arg *a = arg;
2934 /* Base commit bump happens silently. */
2935 if (status == GOT_STATUS_BUMP_BASE)
2936 return NULL;
2938 if (status == GOT_STATUS_BASE_REF_ERR) {
2939 a->had_base_commit_ref_error = 1;
2940 return NULL;
2943 while (path[0] == '/')
2944 path++;
2946 if (a->verbosity >= 0)
2947 printf("%c %s/%s\n", status, a->worktree_path, path);
2949 return NULL;
2952 static const struct got_error *
2953 check_cancelled(void *arg)
2955 if (sigint_received || sigpipe_received)
2956 return got_error(GOT_ERR_CANCELLED);
2957 return NULL;
2960 static const struct got_error *
2961 check_linear_ancestry(struct got_object_id *commit_id,
2962 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2963 struct got_repository *repo)
2965 const struct got_error *err = NULL;
2966 struct got_object_id *yca_id;
2968 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2969 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2970 if (err)
2971 return err;
2973 if (yca_id == NULL)
2974 return got_error(GOT_ERR_ANCESTRY);
2977 * Require a straight line of history between the target commit
2978 * and the work tree's base commit.
2980 * Non-linear situations such as this require a rebase:
2982 * (commit) D F (base_commit)
2983 * \ /
2984 * C E
2985 * \ /
2986 * B (yca)
2990 * 'got update' only handles linear cases:
2991 * Update forwards in time: A (base/yca) - B - C - D (commit)
2992 * Update backwards in time: D (base) - C - B - A (commit/yca)
2994 if (allow_forwards_in_time_only) {
2995 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2996 return got_error(GOT_ERR_ANCESTRY);
2997 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2998 got_object_id_cmp(base_commit_id, yca_id) != 0)
2999 return got_error(GOT_ERR_ANCESTRY);
3001 free(yca_id);
3002 return NULL;
3005 static const struct got_error *
3006 check_same_branch(struct got_object_id *commit_id,
3007 struct got_reference *head_ref, struct got_repository *repo)
3009 const struct got_error *err = NULL;
3010 struct got_commit_graph *graph = NULL;
3011 struct got_object_id *head_commit_id = NULL;
3013 err = got_ref_resolve(&head_commit_id, repo, head_ref);
3014 if (err)
3015 goto done;
3017 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
3018 goto done;
3020 err = got_commit_graph_open(&graph, "/", 1);
3021 if (err)
3022 goto done;
3024 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
3025 check_cancelled, NULL);
3026 if (err)
3027 goto done;
3029 for (;;) {
3030 struct got_object_id id;
3032 err = got_commit_graph_iter_next(&id, graph, repo,
3033 check_cancelled, NULL);
3034 if (err) {
3035 if (err->code == GOT_ERR_ITER_COMPLETED)
3036 err = got_error(GOT_ERR_ANCESTRY);
3037 break;
3040 if (got_object_id_cmp(&id, commit_id) == 0)
3041 break;
3043 done:
3044 if (graph)
3045 got_commit_graph_close(graph);
3046 free(head_commit_id);
3047 return err;
3050 static const struct got_error *
3051 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
3053 static char msg[512];
3054 const char *branch_name;
3056 if (got_ref_is_symbolic(ref))
3057 branch_name = got_ref_get_symref_target(ref);
3058 else
3059 branch_name = got_ref_get_name(ref);
3061 if (strncmp("refs/heads/", branch_name, 11) == 0)
3062 branch_name += 11;
3064 snprintf(msg, sizeof(msg),
3065 "target commit is not contained in branch '%s'; "
3066 "the branch to use must be specified with -b; "
3067 "if necessary a new branch can be created for "
3068 "this commit with 'got branch -c %s BRANCH_NAME'",
3069 branch_name, commit_id_str);
3071 return got_error_msg(GOT_ERR_ANCESTRY, msg);
3074 static const struct got_error *
3075 cmd_checkout(int argc, char *argv[])
3077 const struct got_error *close_err, *error = NULL;
3078 struct got_repository *repo = NULL;
3079 struct got_reference *head_ref = NULL, *ref = NULL;
3080 struct got_worktree *worktree = NULL;
3081 char *repo_path = NULL;
3082 char *worktree_path = NULL;
3083 const char *path_prefix = "";
3084 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3085 char *commit_id_str = NULL, *keyword_idstr = NULL;
3086 struct got_object_id *commit_id = NULL;
3087 char *cwd = NULL;
3088 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3089 struct got_pathlist_head paths;
3090 struct got_checkout_progress_arg cpa;
3091 int *pack_fds = NULL;
3093 TAILQ_INIT(&paths);
3095 #ifndef PROFILE
3096 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3097 "unveil", NULL) == -1)
3098 err(1, "pledge");
3099 #endif
3101 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3102 switch (ch) {
3103 case 'b':
3104 branch_name = optarg;
3105 break;
3106 case 'c':
3107 commit_id_str = strdup(optarg);
3108 if (commit_id_str == NULL)
3109 return got_error_from_errno("strdup");
3110 break;
3111 case 'E':
3112 allow_nonempty = 1;
3113 break;
3114 case 'p':
3115 path_prefix = optarg;
3116 break;
3117 case 'q':
3118 verbosity = -1;
3119 break;
3120 default:
3121 usage_checkout();
3122 /* NOTREACHED */
3126 argc -= optind;
3127 argv += optind;
3129 if (argc == 1) {
3130 char *base, *dotgit;
3131 const char *path;
3132 repo_path = realpath(argv[0], NULL);
3133 if (repo_path == NULL)
3134 return got_error_from_errno2("realpath", argv[0]);
3135 cwd = getcwd(NULL, 0);
3136 if (cwd == NULL) {
3137 error = got_error_from_errno("getcwd");
3138 goto done;
3140 if (path_prefix[0])
3141 path = path_prefix;
3142 else
3143 path = repo_path;
3144 error = got_path_basename(&base, path);
3145 if (error)
3146 goto done;
3147 dotgit = strstr(base, ".git");
3148 if (dotgit)
3149 *dotgit = '\0';
3150 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3151 error = got_error_from_errno("asprintf");
3152 free(base);
3153 goto done;
3155 free(base);
3156 } else if (argc == 2) {
3157 repo_path = realpath(argv[0], NULL);
3158 if (repo_path == NULL) {
3159 error = got_error_from_errno2("realpath", argv[0]);
3160 goto done;
3162 worktree_path = realpath(argv[1], NULL);
3163 if (worktree_path == NULL) {
3164 if (errno != ENOENT) {
3165 error = got_error_from_errno2("realpath",
3166 argv[1]);
3167 goto done;
3169 worktree_path = strdup(argv[1]);
3170 if (worktree_path == NULL) {
3171 error = got_error_from_errno("strdup");
3172 goto done;
3175 } else
3176 usage_checkout();
3178 got_path_strip_trailing_slashes(repo_path);
3179 got_path_strip_trailing_slashes(worktree_path);
3181 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3182 got_path_is_child(repo_path, worktree_path,
3183 strlen(worktree_path))) {
3184 error = got_error_fmt(GOT_ERR_BAD_PATH,
3185 "work tree and repository paths may not overlap: %s",
3186 worktree_path);
3187 goto done;
3190 error = got_repo_pack_fds_open(&pack_fds);
3191 if (error != NULL)
3192 goto done;
3194 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3195 if (error != NULL)
3196 goto done;
3198 /* Pre-create work tree path for unveil(2) */
3199 error = got_path_mkdir(worktree_path);
3200 if (error) {
3201 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3202 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3203 goto done;
3204 if (!allow_nonempty &&
3205 !got_path_dir_is_empty(worktree_path)) {
3206 error = got_error_path(worktree_path,
3207 GOT_ERR_DIR_NOT_EMPTY);
3208 goto done;
3212 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3213 if (error)
3214 goto done;
3216 error = got_ref_open(&head_ref, repo, branch_name, 0);
3217 if (error != NULL)
3218 goto done;
3220 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3221 GOT_WORKTREE_GOT_DIR, repo);
3222 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3223 goto done;
3225 error = got_worktree_open(&worktree, worktree_path,
3226 GOT_WORKTREE_GOT_DIR);
3227 if (error != NULL)
3228 goto done;
3230 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3231 path_prefix);
3232 if (error != NULL)
3233 goto done;
3234 if (!same_path_prefix) {
3235 error = got_error(GOT_ERR_PATH_PREFIX);
3236 goto done;
3239 if (commit_id_str) {
3240 struct got_reflist_head refs;
3241 TAILQ_INIT(&refs);
3242 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3243 NULL);
3244 if (error)
3245 goto done;
3247 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3248 repo, worktree);
3249 if (error != NULL)
3250 goto done;
3251 if (keyword_idstr != NULL) {
3252 free(commit_id_str);
3253 commit_id_str = keyword_idstr;
3256 error = got_repo_match_object_id(&commit_id, NULL,
3257 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3258 got_ref_list_free(&refs);
3259 if (error)
3260 goto done;
3261 error = check_linear_ancestry(commit_id,
3262 got_worktree_get_base_commit_id(worktree), 0, repo);
3263 if (error != NULL) {
3264 if (error->code == GOT_ERR_ANCESTRY) {
3265 error = checkout_ancestry_error(
3266 head_ref, commit_id_str);
3268 goto done;
3270 error = check_same_branch(commit_id, head_ref, repo);
3271 if (error) {
3272 if (error->code == GOT_ERR_ANCESTRY) {
3273 error = checkout_ancestry_error(
3274 head_ref, commit_id_str);
3276 goto done;
3278 error = got_worktree_set_base_commit_id(worktree, repo,
3279 commit_id);
3280 if (error)
3281 goto done;
3282 /* Expand potentially abbreviated commit ID string. */
3283 free(commit_id_str);
3284 error = got_object_id_str(&commit_id_str, commit_id);
3285 if (error)
3286 goto done;
3287 } else {
3288 commit_id = got_object_id_dup(
3289 got_worktree_get_base_commit_id(worktree));
3290 if (commit_id == NULL) {
3291 error = got_error_from_errno("got_object_id_dup");
3292 goto done;
3294 error = got_object_id_str(&commit_id_str, commit_id);
3295 if (error)
3296 goto done;
3299 error = got_pathlist_append(&paths, "", NULL);
3300 if (error)
3301 goto done;
3302 cpa.worktree_path = worktree_path;
3303 cpa.had_base_commit_ref_error = 0;
3304 cpa.verbosity = verbosity;
3305 error = got_worktree_checkout_files(worktree, &paths, repo,
3306 checkout_progress, &cpa, check_cancelled, NULL);
3307 if (error != NULL)
3308 goto done;
3310 if (got_ref_is_symbolic(head_ref)) {
3311 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3312 if (error)
3313 goto done;
3314 refname = got_ref_get_name(ref);
3315 } else
3316 refname = got_ref_get_name(head_ref);
3317 printf("Checked out %s: %s\n", refname, commit_id_str);
3318 printf("Now shut up and hack\n");
3319 if (cpa.had_base_commit_ref_error)
3320 show_worktree_base_ref_warning();
3321 done:
3322 if (pack_fds) {
3323 const struct got_error *pack_err =
3324 got_repo_pack_fds_close(pack_fds);
3325 if (error == NULL)
3326 error = pack_err;
3328 if (head_ref)
3329 got_ref_close(head_ref);
3330 if (ref)
3331 got_ref_close(ref);
3332 if (repo) {
3333 close_err = got_repo_close(repo);
3334 if (error == NULL)
3335 error = close_err;
3337 if (worktree != NULL) {
3338 close_err = got_worktree_close(worktree);
3339 if (error == NULL)
3340 error = close_err;
3342 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3343 free(commit_id_str);
3344 free(commit_id);
3345 free(repo_path);
3346 free(worktree_path);
3347 free(cwd);
3348 return error;
3351 struct got_update_progress_arg {
3352 int did_something;
3353 int conflicts;
3354 int obstructed;
3355 int not_updated;
3356 int missing;
3357 int not_deleted;
3358 int unversioned;
3359 int verbosity;
3362 static void
3363 print_update_progress_stats(struct got_update_progress_arg *upa)
3365 if (!upa->did_something)
3366 return;
3368 if (upa->conflicts > 0)
3369 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3370 if (upa->obstructed > 0)
3371 printf("File paths obstructed by a non-regular file: %d\n",
3372 upa->obstructed);
3373 if (upa->not_updated > 0)
3374 printf("Files not updated because of existing merge "
3375 "conflicts: %d\n", upa->not_updated);
3379 * The meaning of some status codes differs between merge-style operations and
3380 * update operations. For example, the ! status code means "file was missing"
3381 * if changes were merged into the work tree, and "missing file was restored"
3382 * if the work tree was updated. This function should be used by any operation
3383 * which merges changes into the work tree without updating the work tree.
3385 static void
3386 print_merge_progress_stats(struct got_update_progress_arg *upa)
3388 if (!upa->did_something)
3389 return;
3391 if (upa->conflicts > 0)
3392 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3393 if (upa->obstructed > 0)
3394 printf("File paths obstructed by a non-regular file: %d\n",
3395 upa->obstructed);
3396 if (upa->missing > 0)
3397 printf("Files which had incoming changes but could not be "
3398 "found in the work tree: %d\n", upa->missing);
3399 if (upa->not_deleted > 0)
3400 printf("Files not deleted due to differences in deleted "
3401 "content: %d\n", upa->not_deleted);
3402 if (upa->unversioned > 0)
3403 printf("Files not merged because an unversioned file was "
3404 "found in the work tree: %d\n", upa->unversioned);
3407 __dead static void
3408 usage_update(void)
3410 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3411 "[path ...]\n", getprogname());
3412 exit(1);
3415 static const struct got_error *
3416 update_progress(void *arg, unsigned char status, const char *path)
3418 struct got_update_progress_arg *upa = arg;
3420 if (status == GOT_STATUS_EXISTS ||
3421 status == GOT_STATUS_BASE_REF_ERR)
3422 return NULL;
3424 upa->did_something = 1;
3426 /* Base commit bump happens silently. */
3427 if (status == GOT_STATUS_BUMP_BASE)
3428 return NULL;
3430 if (status == GOT_STATUS_CONFLICT)
3431 upa->conflicts++;
3432 if (status == GOT_STATUS_OBSTRUCTED)
3433 upa->obstructed++;
3434 if (status == GOT_STATUS_CANNOT_UPDATE)
3435 upa->not_updated++;
3436 if (status == GOT_STATUS_MISSING)
3437 upa->missing++;
3438 if (status == GOT_STATUS_CANNOT_DELETE)
3439 upa->not_deleted++;
3440 if (status == GOT_STATUS_UNVERSIONED)
3441 upa->unversioned++;
3443 while (path[0] == '/')
3444 path++;
3445 if (upa->verbosity >= 0)
3446 printf("%c %s\n", status, path);
3448 return NULL;
3451 static const struct got_error *
3452 switch_head_ref(struct got_reference *head_ref,
3453 struct got_object_id *commit_id, struct got_worktree *worktree,
3454 struct got_repository *repo)
3456 const struct got_error *err = NULL;
3457 char *base_id_str;
3458 int ref_has_moved = 0;
3460 /* Trivial case: switching between two different references. */
3461 if (strcmp(got_ref_get_name(head_ref),
3462 got_worktree_get_head_ref_name(worktree)) != 0) {
3463 printf("Switching work tree from %s to %s\n",
3464 got_worktree_get_head_ref_name(worktree),
3465 got_ref_get_name(head_ref));
3466 return got_worktree_set_head_ref(worktree, head_ref);
3469 err = check_linear_ancestry(commit_id,
3470 got_worktree_get_base_commit_id(worktree), 0, repo);
3471 if (err) {
3472 if (err->code != GOT_ERR_ANCESTRY)
3473 return err;
3474 ref_has_moved = 1;
3476 if (!ref_has_moved)
3477 return NULL;
3479 /* Switching to a rebased branch with the same reference name. */
3480 err = got_object_id_str(&base_id_str,
3481 got_worktree_get_base_commit_id(worktree));
3482 if (err)
3483 return err;
3484 printf("Reference %s now points at a different branch\n",
3485 got_worktree_get_head_ref_name(worktree));
3486 printf("Switching work tree from %s to %s\n", base_id_str,
3487 got_worktree_get_head_ref_name(worktree));
3488 return NULL;
3491 static const struct got_error *
3492 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3494 const struct got_error *err;
3495 int in_progress;
3497 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3498 if (err)
3499 return err;
3500 if (in_progress)
3501 return got_error(GOT_ERR_REBASING);
3503 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3504 if (err)
3505 return err;
3506 if (in_progress)
3507 return got_error(GOT_ERR_HISTEDIT_BUSY);
3509 return NULL;
3512 static const struct got_error *
3513 check_merge_in_progress(struct got_worktree *worktree,
3514 struct got_repository *repo)
3516 const struct got_error *err;
3517 int in_progress;
3519 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3520 if (err)
3521 return err;
3522 if (in_progress)
3523 return got_error(GOT_ERR_MERGE_BUSY);
3525 return NULL;
3528 static const struct got_error *
3529 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3530 char *argv[], struct got_worktree *worktree)
3532 const struct got_error *err = NULL;
3533 char *path;
3534 struct got_pathlist_entry *new;
3535 int i;
3537 if (argc == 0) {
3538 path = strdup("");
3539 if (path == NULL)
3540 return got_error_from_errno("strdup");
3541 return got_pathlist_append(paths, path, NULL);
3544 for (i = 0; i < argc; i++) {
3545 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3546 if (err)
3547 break;
3548 err = got_pathlist_insert(&new, paths, path, NULL);
3549 if (err || new == NULL /* duplicate */) {
3550 free(path);
3551 if (err)
3552 break;
3556 return err;
3559 static const struct got_error *
3560 wrap_not_worktree_error(const struct got_error *orig_err,
3561 const char *cmdname, const char *path)
3563 const struct got_error *err;
3564 struct got_repository *repo;
3565 static char msg[512];
3566 int *pack_fds = NULL;
3568 err = got_repo_pack_fds_open(&pack_fds);
3569 if (err)
3570 return err;
3572 err = got_repo_open(&repo, path, NULL, pack_fds);
3573 if (err)
3574 return orig_err;
3576 snprintf(msg, sizeof(msg),
3577 "'got %s' needs a work tree in addition to a git repository\n"
3578 "Work trees can be checked out from this Git repository with "
3579 "'got checkout'.\n"
3580 "The got(1) manual page contains more information.", cmdname);
3581 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3582 if (repo) {
3583 const struct got_error *close_err = got_repo_close(repo);
3584 if (err == NULL)
3585 err = close_err;
3587 if (pack_fds) {
3588 const struct got_error *pack_err =
3589 got_repo_pack_fds_close(pack_fds);
3590 if (err == NULL)
3591 err = pack_err;
3593 return err;
3596 static const struct got_error *
3597 cmd_update(int argc, char *argv[])
3599 const struct got_error *close_err, *error = NULL;
3600 struct got_repository *repo = NULL;
3601 struct got_worktree *worktree = NULL;
3602 char *worktree_path = NULL;
3603 struct got_object_id *commit_id = NULL;
3604 char *commit_id_str = NULL;
3605 const char *branch_name = NULL;
3606 struct got_reference *head_ref = NULL;
3607 struct got_pathlist_head paths;
3608 struct got_pathlist_entry *pe;
3609 int ch, verbosity = 0;
3610 struct got_update_progress_arg upa;
3611 int *pack_fds = NULL;
3613 TAILQ_INIT(&paths);
3615 #ifndef PROFILE
3616 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3617 "unveil", NULL) == -1)
3618 err(1, "pledge");
3619 #endif
3621 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3622 switch (ch) {
3623 case 'b':
3624 branch_name = optarg;
3625 break;
3626 case 'c':
3627 commit_id_str = strdup(optarg);
3628 if (commit_id_str == NULL)
3629 return got_error_from_errno("strdup");
3630 break;
3631 case 'q':
3632 verbosity = -1;
3633 break;
3634 default:
3635 usage_update();
3636 /* NOTREACHED */
3640 argc -= optind;
3641 argv += optind;
3643 worktree_path = getcwd(NULL, 0);
3644 if (worktree_path == NULL) {
3645 error = got_error_from_errno("getcwd");
3646 goto done;
3649 error = got_repo_pack_fds_open(&pack_fds);
3650 if (error != NULL)
3651 goto done;
3653 error = got_worktree_open(&worktree, worktree_path,
3654 GOT_WORKTREE_GOT_DIR);
3655 if (error) {
3656 if (error->code == GOT_ERR_NOT_WORKTREE)
3657 error = wrap_not_worktree_error(error, "update",
3658 worktree_path);
3659 goto done;
3662 error = check_rebase_or_histedit_in_progress(worktree);
3663 if (error)
3664 goto done;
3666 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3667 NULL, pack_fds);
3668 if (error != NULL)
3669 goto done;
3671 error = apply_unveil(got_repo_get_path(repo), 0,
3672 got_worktree_get_root_path(worktree));
3673 if (error)
3674 goto done;
3676 error = check_merge_in_progress(worktree, repo);
3677 if (error)
3678 goto done;
3680 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3681 if (error)
3682 goto done;
3684 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3685 got_worktree_get_head_ref_name(worktree), 0);
3686 if (error != NULL)
3687 goto done;
3688 if (commit_id_str == NULL) {
3689 error = got_ref_resolve(&commit_id, repo, head_ref);
3690 if (error != NULL)
3691 goto done;
3692 error = got_object_id_str(&commit_id_str, commit_id);
3693 if (error != NULL)
3694 goto done;
3695 } else {
3696 struct got_reflist_head refs;
3697 char *keyword_idstr = NULL;
3699 TAILQ_INIT(&refs);
3701 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3702 NULL);
3703 if (error)
3704 goto done;
3706 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3707 repo, worktree);
3708 if (error != NULL)
3709 goto done;
3710 if (keyword_idstr != NULL) {
3711 free(commit_id_str);
3712 commit_id_str = keyword_idstr;
3715 error = got_repo_match_object_id(&commit_id, NULL,
3716 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3717 got_ref_list_free(&refs);
3718 free(commit_id_str);
3719 commit_id_str = NULL;
3720 if (error)
3721 goto done;
3722 error = got_object_id_str(&commit_id_str, commit_id);
3723 if (error)
3724 goto done;
3727 if (branch_name) {
3728 struct got_object_id *head_commit_id;
3729 TAILQ_FOREACH(pe, &paths, entry) {
3730 if (pe->path_len == 0)
3731 continue;
3732 error = got_error_msg(GOT_ERR_BAD_PATH,
3733 "switching between branches requires that "
3734 "the entire work tree gets updated");
3735 goto done;
3737 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3738 if (error)
3739 goto done;
3740 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3741 repo);
3742 free(head_commit_id);
3743 if (error != NULL)
3744 goto done;
3745 error = check_same_branch(commit_id, head_ref, repo);
3746 if (error)
3747 goto done;
3748 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3749 if (error)
3750 goto done;
3751 } else {
3752 error = check_linear_ancestry(commit_id,
3753 got_worktree_get_base_commit_id(worktree), 0, repo);
3754 if (error != NULL) {
3755 if (error->code == GOT_ERR_ANCESTRY)
3756 error = got_error(GOT_ERR_BRANCH_MOVED);
3757 goto done;
3759 error = check_same_branch(commit_id, head_ref, repo);
3760 if (error)
3761 goto done;
3764 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3765 commit_id) != 0) {
3766 error = got_worktree_set_base_commit_id(worktree, repo,
3767 commit_id);
3768 if (error)
3769 goto done;
3772 memset(&upa, 0, sizeof(upa));
3773 upa.verbosity = verbosity;
3774 error = got_worktree_checkout_files(worktree, &paths, repo,
3775 update_progress, &upa, check_cancelled, NULL);
3776 if (error != NULL)
3777 goto done;
3779 if (upa.did_something) {
3780 printf("Updated to %s: %s\n",
3781 got_worktree_get_head_ref_name(worktree), commit_id_str);
3782 } else
3783 printf("Already up-to-date\n");
3785 print_update_progress_stats(&upa);
3786 done:
3787 if (pack_fds) {
3788 const struct got_error *pack_err =
3789 got_repo_pack_fds_close(pack_fds);
3790 if (error == NULL)
3791 error = pack_err;
3793 if (repo) {
3794 close_err = got_repo_close(repo);
3795 if (error == NULL)
3796 error = close_err;
3798 if (worktree != NULL) {
3799 close_err = got_worktree_close(worktree);
3800 if (error == NULL)
3801 error = close_err;
3803 if (head_ref != NULL)
3804 got_ref_close(head_ref);
3805 free(worktree_path);
3806 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3807 free(commit_id);
3808 free(commit_id_str);
3809 return error;
3812 static const struct got_error *
3813 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3814 const char *path, int diff_context, int ignore_whitespace,
3815 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3816 struct got_repository *repo, FILE *outfile)
3818 const struct got_error *err = NULL;
3819 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3820 FILE *f1 = NULL, *f2 = NULL;
3821 int fd1 = -1, fd2 = -1;
3823 fd1 = got_opentempfd();
3824 if (fd1 == -1)
3825 return got_error_from_errno("got_opentempfd");
3826 fd2 = got_opentempfd();
3827 if (fd2 == -1) {
3828 err = got_error_from_errno("got_opentempfd");
3829 goto done;
3832 if (blob_id1) {
3833 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3834 fd1);
3835 if (err)
3836 goto done;
3839 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3840 if (err)
3841 goto done;
3843 f1 = got_opentemp();
3844 if (f1 == NULL) {
3845 err = got_error_from_errno("got_opentemp");
3846 goto done;
3848 f2 = got_opentemp();
3849 if (f2 == NULL) {
3850 err = got_error_from_errno("got_opentemp");
3851 goto done;
3854 while (path[0] == '/')
3855 path++;
3856 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3857 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3858 force_text_diff, dsa, outfile);
3859 done:
3860 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3861 err = got_error_from_errno("close");
3862 if (blob1)
3863 got_object_blob_close(blob1);
3864 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3865 err = got_error_from_errno("close");
3866 if (blob2)
3867 got_object_blob_close(blob2);
3868 if (f1 && fclose(f1) == EOF && err == NULL)
3869 err = got_error_from_errno("fclose");
3870 if (f2 && fclose(f2) == EOF && err == NULL)
3871 err = got_error_from_errno("fclose");
3872 return err;
3875 static const struct got_error *
3876 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3877 const char *path, int diff_context, int ignore_whitespace,
3878 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3879 struct got_repository *repo, FILE *outfile)
3881 const struct got_error *err = NULL;
3882 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3883 struct got_diff_blob_output_unidiff_arg arg;
3884 FILE *f1 = NULL, *f2 = NULL;
3885 int fd1 = -1, fd2 = -1;
3887 if (tree_id1) {
3888 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3889 if (err)
3890 goto done;
3891 fd1 = got_opentempfd();
3892 if (fd1 == -1) {
3893 err = got_error_from_errno("got_opentempfd");
3894 goto done;
3898 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3899 if (err)
3900 goto done;
3902 f1 = got_opentemp();
3903 if (f1 == NULL) {
3904 err = got_error_from_errno("got_opentemp");
3905 goto done;
3908 f2 = got_opentemp();
3909 if (f2 == NULL) {
3910 err = got_error_from_errno("got_opentemp");
3911 goto done;
3913 fd2 = got_opentempfd();
3914 if (fd2 == -1) {
3915 err = got_error_from_errno("got_opentempfd");
3916 goto done;
3918 arg.diff_context = diff_context;
3919 arg.ignore_whitespace = ignore_whitespace;
3920 arg.force_text_diff = force_text_diff;
3921 arg.diffstat = dsa;
3922 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3923 arg.outfile = outfile;
3924 arg.lines = NULL;
3925 arg.nlines = 0;
3926 while (path[0] == '/')
3927 path++;
3928 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3929 got_diff_blob_output_unidiff, &arg, 1);
3930 done:
3931 if (tree1)
3932 got_object_tree_close(tree1);
3933 if (tree2)
3934 got_object_tree_close(tree2);
3935 if (f1 && fclose(f1) == EOF && err == NULL)
3936 err = got_error_from_errno("fclose");
3937 if (f2 && fclose(f2) == EOF && err == NULL)
3938 err = got_error_from_errno("fclose");
3939 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3940 err = got_error_from_errno("close");
3941 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3942 err = got_error_from_errno("close");
3943 return err;
3946 static const struct got_error *
3947 get_changed_paths(struct got_pathlist_head *paths,
3948 struct got_commit_object *commit, struct got_repository *repo,
3949 struct got_diffstat_cb_arg *dsa)
3951 const struct got_error *err = NULL;
3952 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3953 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3954 struct got_object_qid *qid;
3955 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3956 FILE *f1 = NULL, *f2 = NULL;
3957 int fd1 = -1, fd2 = -1;
3959 if (dsa) {
3960 cb = got_diff_tree_compute_diffstat;
3962 f1 = got_opentemp();
3963 if (f1 == NULL) {
3964 err = got_error_from_errno("got_opentemp");
3965 goto done;
3967 f2 = got_opentemp();
3968 if (f2 == NULL) {
3969 err = got_error_from_errno("got_opentemp");
3970 goto done;
3972 fd1 = got_opentempfd();
3973 if (fd1 == -1) {
3974 err = got_error_from_errno("got_opentempfd");
3975 goto done;
3977 fd2 = got_opentempfd();
3978 if (fd2 == -1) {
3979 err = got_error_from_errno("got_opentempfd");
3980 goto done;
3984 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3985 if (qid != NULL) {
3986 struct got_commit_object *pcommit;
3987 err = got_object_open_as_commit(&pcommit, repo,
3988 &qid->id);
3989 if (err)
3990 return err;
3992 tree_id1 = got_object_id_dup(
3993 got_object_commit_get_tree_id(pcommit));
3994 if (tree_id1 == NULL) {
3995 got_object_commit_close(pcommit);
3996 return got_error_from_errno("got_object_id_dup");
3998 got_object_commit_close(pcommit);
4002 if (tree_id1) {
4003 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4004 if (err)
4005 goto done;
4008 tree_id2 = got_object_commit_get_tree_id(commit);
4009 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4010 if (err)
4011 goto done;
4013 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
4014 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
4015 done:
4016 if (tree1)
4017 got_object_tree_close(tree1);
4018 if (tree2)
4019 got_object_tree_close(tree2);
4020 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4021 err = got_error_from_errno("close");
4022 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4023 err = got_error_from_errno("close");
4024 if (f1 && fclose(f1) == EOF && err == NULL)
4025 err = got_error_from_errno("fclose");
4026 if (f2 && fclose(f2) == EOF && err == NULL)
4027 err = got_error_from_errno("fclose");
4028 free(tree_id1);
4029 return err;
4032 static const struct got_error *
4033 print_patch(struct got_commit_object *commit, struct got_object_id *id,
4034 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
4035 struct got_repository *repo, FILE *outfile)
4037 const struct got_error *err = NULL;
4038 struct got_commit_object *pcommit = NULL;
4039 char *id_str1 = NULL, *id_str2 = NULL;
4040 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
4041 struct got_object_qid *qid;
4043 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4044 if (qid != NULL) {
4045 err = got_object_open_as_commit(&pcommit, repo,
4046 &qid->id);
4047 if (err)
4048 return err;
4049 err = got_object_id_str(&id_str1, &qid->id);
4050 if (err)
4051 goto done;
4054 err = got_object_id_str(&id_str2, id);
4055 if (err)
4056 goto done;
4058 if (path && path[0] != '\0') {
4059 int obj_type;
4060 err = got_object_id_by_path(&obj_id2, repo, commit, path);
4061 if (err)
4062 goto done;
4063 if (pcommit) {
4064 err = got_object_id_by_path(&obj_id1, repo,
4065 pcommit, path);
4066 if (err) {
4067 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
4068 free(obj_id2);
4069 goto done;
4073 err = got_object_get_type(&obj_type, repo, obj_id2);
4074 if (err) {
4075 free(obj_id2);
4076 goto done;
4078 fprintf(outfile,
4079 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4080 fprintf(outfile, "commit - %s\n",
4081 id_str1 ? id_str1 : "/dev/null");
4082 fprintf(outfile, "commit + %s\n", id_str2);
4083 switch (obj_type) {
4084 case GOT_OBJ_TYPE_BLOB:
4085 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4086 0, 0, dsa, repo, outfile);
4087 break;
4088 case GOT_OBJ_TYPE_TREE:
4089 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4090 0, 0, dsa, repo, outfile);
4091 break;
4092 default:
4093 err = got_error(GOT_ERR_OBJ_TYPE);
4094 break;
4096 free(obj_id1);
4097 free(obj_id2);
4098 } else {
4099 obj_id2 = got_object_commit_get_tree_id(commit);
4100 if (pcommit)
4101 obj_id1 = got_object_commit_get_tree_id(pcommit);
4102 fprintf(outfile,
4103 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4104 fprintf(outfile, "commit - %s\n",
4105 id_str1 ? id_str1 : "/dev/null");
4106 fprintf(outfile, "commit + %s\n", id_str2);
4107 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4108 dsa, repo, outfile);
4110 done:
4111 free(id_str1);
4112 free(id_str2);
4113 if (pcommit)
4114 got_object_commit_close(pcommit);
4115 return err;
4118 static char *
4119 get_datestr(time_t *time, char *datebuf)
4121 struct tm mytm, *tm;
4122 char *p, *s;
4124 tm = gmtime_r(time, &mytm);
4125 if (tm == NULL)
4126 return NULL;
4127 s = asctime_r(tm, datebuf);
4128 if (s == NULL)
4129 return NULL;
4130 p = strchr(s, '\n');
4131 if (p)
4132 *p = '\0';
4133 return s;
4136 static const struct got_error *
4137 match_commit(int *have_match, struct got_object_id *id,
4138 struct got_commit_object *commit, regex_t *regex)
4140 const struct got_error *err = NULL;
4141 regmatch_t regmatch;
4142 char *id_str = NULL, *logmsg = NULL;
4144 *have_match = 0;
4146 err = got_object_id_str(&id_str, id);
4147 if (err)
4148 return err;
4150 err = got_object_commit_get_logmsg(&logmsg, commit);
4151 if (err)
4152 goto done;
4154 if (regexec(regex, got_object_commit_get_author(commit), 1,
4155 &regmatch, 0) == 0 ||
4156 regexec(regex, got_object_commit_get_committer(commit), 1,
4157 &regmatch, 0) == 0 ||
4158 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4159 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4160 *have_match = 1;
4161 done:
4162 free(id_str);
4163 free(logmsg);
4164 return err;
4167 static void
4168 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4169 regex_t *regex)
4171 regmatch_t regmatch;
4172 struct got_pathlist_entry *pe;
4174 *have_match = 0;
4176 TAILQ_FOREACH(pe, changed_paths, entry) {
4177 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4178 *have_match = 1;
4179 break;
4184 static const struct got_error *
4185 match_patch(int *have_match, struct got_commit_object *commit,
4186 struct got_object_id *id, const char *path, int diff_context,
4187 struct got_repository *repo, regex_t *regex, FILE *f)
4189 const struct got_error *err = NULL;
4190 char *line = NULL;
4191 size_t linesize = 0;
4192 regmatch_t regmatch;
4194 *have_match = 0;
4196 err = got_opentemp_truncate(f);
4197 if (err)
4198 return err;
4200 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4201 if (err)
4202 goto done;
4204 if (fseeko(f, 0L, SEEK_SET) == -1) {
4205 err = got_error_from_errno("fseeko");
4206 goto done;
4209 while (getline(&line, &linesize, f) != -1) {
4210 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4211 *have_match = 1;
4212 break;
4215 done:
4216 free(line);
4217 return err;
4220 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4222 static const struct got_error*
4223 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4224 struct got_object_id *id, struct got_repository *repo,
4225 int local_only)
4227 static const struct got_error *err = NULL;
4228 struct got_reflist_entry *re;
4229 char *s;
4230 const char *name;
4232 *refs_str = NULL;
4234 TAILQ_FOREACH(re, refs, entry) {
4235 struct got_tag_object *tag = NULL;
4236 struct got_object_id *ref_id;
4237 int cmp;
4239 name = got_ref_get_name(re->ref);
4240 if (strcmp(name, GOT_REF_HEAD) == 0)
4241 continue;
4242 if (strncmp(name, "refs/", 5) == 0)
4243 name += 5;
4244 if (strncmp(name, "got/", 4) == 0)
4245 continue;
4246 if (strncmp(name, "heads/", 6) == 0)
4247 name += 6;
4248 if (strncmp(name, "remotes/", 8) == 0) {
4249 if (local_only)
4250 continue;
4251 name += 8;
4252 s = strstr(name, "/" GOT_REF_HEAD);
4253 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4254 continue;
4256 err = got_ref_resolve(&ref_id, repo, re->ref);
4257 if (err)
4258 break;
4259 if (strncmp(name, "tags/", 5) == 0) {
4260 err = got_object_open_as_tag(&tag, repo, ref_id);
4261 if (err) {
4262 if (err->code != GOT_ERR_OBJ_TYPE) {
4263 free(ref_id);
4264 break;
4266 /* Ref points at something other than a tag. */
4267 err = NULL;
4268 tag = NULL;
4271 cmp = got_object_id_cmp(tag ?
4272 got_object_tag_get_object_id(tag) : ref_id, id);
4273 free(ref_id);
4274 if (tag)
4275 got_object_tag_close(tag);
4276 if (cmp != 0)
4277 continue;
4278 s = *refs_str;
4279 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4280 s ? ", " : "", name) == -1) {
4281 err = got_error_from_errno("asprintf");
4282 free(s);
4283 *refs_str = NULL;
4284 break;
4286 free(s);
4289 return err;
4292 static const struct got_error *
4293 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4294 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4296 const struct got_error *err = NULL;
4297 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4298 char *comma, *s, *nl;
4299 struct got_reflist_head *refs;
4300 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4301 struct tm tm;
4302 time_t committer_time;
4304 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4305 if (refs) {
4306 err = build_refs_str(&ref_str, refs, id, repo, 1);
4307 if (err)
4308 return err;
4310 /* Display the first matching ref only. */
4311 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4312 *comma = '\0';
4315 if (ref_str == NULL) {
4316 err = got_object_id_str(&id_str, id);
4317 if (err)
4318 return err;
4321 committer_time = got_object_commit_get_committer_time(commit);
4322 if (gmtime_r(&committer_time, &tm) == NULL) {
4323 err = got_error_from_errno("gmtime_r");
4324 goto done;
4326 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0) {
4327 err = got_error(GOT_ERR_NO_SPACE);
4328 goto done;
4331 err = got_object_commit_get_logmsg(&logmsg0, commit);
4332 if (err)
4333 goto done;
4335 s = logmsg0;
4336 while (isspace((unsigned char)s[0]))
4337 s++;
4339 nl = strchr(s, '\n');
4340 if (nl) {
4341 *nl = '\0';
4344 if (ref_str)
4345 printf("%s%-7s %s\n", datebuf, ref_str, s);
4346 else
4347 printf("%s%.7s %s\n", datebuf, id_str, s);
4349 if (fflush(stdout) != 0 && err == NULL)
4350 err = got_error_from_errno("fflush");
4351 done:
4352 free(id_str);
4353 free(ref_str);
4354 free(logmsg0);
4355 return err;
4358 static const struct got_error *
4359 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4361 struct got_pathlist_entry *pe;
4363 if (header != NULL)
4364 printf("%s\n", header);
4366 TAILQ_FOREACH(pe, dsa->paths, entry) {
4367 struct got_diff_changed_path *cp = pe->data;
4368 int pad = dsa->max_path_len - pe->path_len + 1;
4370 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4371 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4373 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4374 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4375 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4377 if (fflush(stdout) != 0)
4378 return got_error_from_errno("fflush");
4380 return NULL;
4383 static const struct got_error *
4384 printfile(FILE *f)
4386 char buf[8192];
4387 size_t r;
4389 if (fseeko(f, 0L, SEEK_SET) == -1)
4390 return got_error_from_errno("fseek");
4392 for (;;) {
4393 r = fread(buf, 1, sizeof(buf), f);
4394 if (r == 0) {
4395 if (ferror(f))
4396 return got_error_from_errno("fread");
4397 if (feof(f))
4398 break;
4400 if (fwrite(buf, 1, r, stdout) != r)
4401 return got_ferror(stdout, GOT_ERR_IO);
4404 return NULL;
4407 static const struct got_error *
4408 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4409 struct got_repository *repo, const char *path,
4410 struct got_pathlist_head *changed_paths,
4411 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4412 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4413 const char *prefix)
4415 const struct got_error *err = NULL;
4416 FILE *f = NULL;
4417 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4418 char datebuf[26];
4419 time_t committer_time;
4420 const char *author, *committer;
4421 char *refs_str = NULL;
4423 err = got_object_id_str(&id_str, id);
4424 if (err)
4425 return err;
4427 if (custom_refs_str == NULL) {
4428 struct got_reflist_head *refs;
4429 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4430 if (refs) {
4431 err = build_refs_str(&refs_str, refs, id, repo, 0);
4432 if (err)
4433 goto done;
4437 printf(GOT_COMMIT_SEP_STR);
4438 if (custom_refs_str)
4439 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4440 custom_refs_str);
4441 else
4442 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4443 refs_str ? " (" : "", refs_str ? refs_str : "",
4444 refs_str ? ")" : "");
4445 free(id_str);
4446 id_str = NULL;
4447 free(refs_str);
4448 refs_str = NULL;
4449 printf("from: %s\n", got_object_commit_get_author(commit));
4450 author = got_object_commit_get_author(commit);
4451 committer = got_object_commit_get_committer(commit);
4452 if (strcmp(author, committer) != 0)
4453 printf("via: %s\n", committer);
4454 committer_time = got_object_commit_get_committer_time(commit);
4455 datestr = get_datestr(&committer_time, datebuf);
4456 if (datestr)
4457 printf("date: %s UTC\n", datestr);
4458 if (got_object_commit_get_nparents(commit) > 1) {
4459 const struct got_object_id_queue *parent_ids;
4460 struct got_object_qid *qid;
4461 int n = 1;
4462 parent_ids = got_object_commit_get_parent_ids(commit);
4463 STAILQ_FOREACH(qid, parent_ids, entry) {
4464 err = got_object_id_str(&id_str, &qid->id);
4465 if (err)
4466 goto done;
4467 printf("parent %d: %s\n", n++, id_str);
4468 free(id_str);
4469 id_str = NULL;
4473 err = got_object_commit_get_logmsg(&logmsg0, commit);
4474 if (err)
4475 goto done;
4477 logmsg = logmsg0;
4478 do {
4479 line = strsep(&logmsg, "\n");
4480 if (line)
4481 printf(" %s\n", line);
4482 } while (line);
4483 free(logmsg0);
4485 if (changed_paths && diffstat == NULL) {
4486 struct got_pathlist_entry *pe;
4488 TAILQ_FOREACH(pe, changed_paths, entry) {
4489 struct got_diff_changed_path *cp = pe->data;
4491 printf(" %c %s\n", cp->status, pe->path);
4493 printf("\n");
4495 if (show_patch) {
4496 if (diffstat) {
4497 f = got_opentemp();
4498 if (f == NULL) {
4499 err = got_error_from_errno("got_opentemp");
4500 goto done;
4504 err = print_patch(commit, id, path, diff_context, diffstat,
4505 repo, diffstat == NULL ? stdout : f);
4506 if (err)
4507 goto done;
4509 if (diffstat) {
4510 err = print_diffstat(diffstat, NULL);
4511 if (err)
4512 goto done;
4513 if (show_patch) {
4514 err = printfile(f);
4515 if (err)
4516 goto done;
4519 if (show_patch)
4520 printf("\n");
4522 if (fflush(stdout) != 0 && err == NULL)
4523 err = got_error_from_errno("fflush");
4524 done:
4525 if (f && fclose(f) == EOF && err == NULL)
4526 err = got_error_from_errno("fclose");
4527 free(id_str);
4528 free(refs_str);
4529 return err;
4532 static const struct got_error *
4533 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4534 struct got_repository *repo, const char *path, int show_changed_paths,
4535 int show_diffstat, int show_patch, const char *search_pattern,
4536 int diff_context, int limit, int log_branches, int reverse_display_order,
4537 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4538 FILE *tmpfile)
4540 const struct got_error *err;
4541 struct got_commit_graph *graph;
4542 regex_t regex;
4543 int have_match;
4544 struct got_object_id_queue reversed_commits;
4545 struct got_object_qid *qid;
4546 struct got_commit_object *commit;
4547 struct got_pathlist_head changed_paths;
4549 STAILQ_INIT(&reversed_commits);
4550 TAILQ_INIT(&changed_paths);
4552 if (search_pattern && regcomp(&regex, search_pattern,
4553 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4554 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4556 err = got_commit_graph_open(&graph, path, !log_branches);
4557 if (err)
4558 return err;
4559 if (log_branches && toposort) {
4560 err = got_commit_graph_toposort(graph, root_id, repo,
4561 check_cancelled, NULL);
4562 } else {
4563 err = got_commit_graph_bfsort(graph, root_id, repo,
4564 check_cancelled, NULL);
4566 if (err)
4567 goto done;
4568 for (;;) {
4569 struct got_object_id id;
4570 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4571 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4573 if (sigint_received || sigpipe_received)
4574 break;
4576 err = got_commit_graph_iter_next(&id, graph, repo,
4577 check_cancelled, NULL);
4578 if (err) {
4579 if (err->code == GOT_ERR_ITER_COMPLETED)
4580 err = NULL;
4581 break;
4584 err = got_object_open_as_commit(&commit, repo, &id);
4585 if (err)
4586 break;
4588 if (((show_changed_paths && !show_diffstat) ||
4589 (show_diffstat && !show_patch))
4590 && !reverse_display_order) {
4591 err = get_changed_paths(&changed_paths, commit, repo,
4592 show_diffstat ? &dsa : NULL);
4593 if (err)
4594 break;
4597 if (search_pattern) {
4598 err = match_commit(&have_match, &id, commit, &regex);
4599 if (err) {
4600 got_object_commit_close(commit);
4601 break;
4603 if (have_match == 0 && show_changed_paths)
4604 match_changed_paths(&have_match,
4605 &changed_paths, &regex);
4606 if (have_match == 0 && show_patch) {
4607 err = match_patch(&have_match, commit, &id,
4608 path, diff_context, repo, &regex, tmpfile);
4609 if (err)
4610 break;
4612 if (have_match == 0) {
4613 got_object_commit_close(commit);
4614 got_pathlist_free(&changed_paths,
4615 GOT_PATHLIST_FREE_ALL);
4616 continue;
4620 if (reverse_display_order) {
4621 err = got_object_qid_alloc(&qid, &id);
4622 if (err)
4623 break;
4624 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4625 got_object_commit_close(commit);
4626 } else {
4627 if (one_line)
4628 err = print_commit_oneline(commit, &id,
4629 repo, refs_idmap);
4630 else
4631 err = print_commit(commit, &id, repo, path,
4632 (show_changed_paths || show_diffstat) ?
4633 &changed_paths : NULL,
4634 show_diffstat ? &dsa : NULL, show_patch,
4635 diff_context, refs_idmap, NULL, NULL);
4636 got_object_commit_close(commit);
4637 if (err)
4638 break;
4640 if ((limit && --limit == 0) ||
4641 (end_id && got_object_id_cmp(&id, end_id) == 0))
4642 break;
4644 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4646 if (reverse_display_order) {
4647 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4648 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4649 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4651 err = got_object_open_as_commit(&commit, repo,
4652 &qid->id);
4653 if (err)
4654 break;
4655 if ((show_changed_paths && !show_diffstat) ||
4656 (show_diffstat && !show_patch)) {
4657 err = get_changed_paths(&changed_paths, commit,
4658 repo, show_diffstat ? &dsa : NULL);
4659 if (err)
4660 break;
4662 if (one_line)
4663 err = print_commit_oneline(commit, &qid->id,
4664 repo, refs_idmap);
4665 else
4666 err = print_commit(commit, &qid->id, repo, path,
4667 (show_changed_paths || show_diffstat) ?
4668 &changed_paths : NULL,
4669 show_diffstat ? &dsa : NULL, show_patch,
4670 diff_context, refs_idmap, NULL, NULL);
4671 got_object_commit_close(commit);
4672 if (err)
4673 break;
4674 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4677 done:
4678 while (!STAILQ_EMPTY(&reversed_commits)) {
4679 qid = STAILQ_FIRST(&reversed_commits);
4680 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4681 got_object_qid_free(qid);
4683 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4684 if (search_pattern)
4685 regfree(&regex);
4686 got_commit_graph_close(graph);
4687 return err;
4690 __dead static void
4691 usage_log(void)
4693 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4694 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4695 "[path]\n", getprogname());
4696 exit(1);
4699 static int
4700 get_default_log_limit(void)
4702 const char *got_default_log_limit;
4703 long long n;
4704 const char *errstr;
4706 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4707 if (got_default_log_limit == NULL)
4708 return 0;
4709 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4710 if (errstr != NULL)
4711 return 0;
4712 return n;
4715 static const struct got_error *
4716 cmd_log(int argc, char *argv[])
4718 const struct got_error *error;
4719 struct got_repository *repo = NULL;
4720 struct got_worktree *worktree = NULL;
4721 struct got_object_id *start_id = NULL, *end_id = NULL;
4722 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4723 char *keyword_idstr = NULL;
4724 const char *start_commit = NULL, *end_commit = NULL;
4725 const char *search_pattern = NULL;
4726 int diff_context = -1, ch;
4727 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4728 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4729 int toposort = 0;
4730 const char *errstr;
4731 struct got_reflist_head refs;
4732 struct got_reflist_object_id_map *refs_idmap = NULL;
4733 FILE *tmpfile = NULL;
4734 int *pack_fds = NULL;
4736 TAILQ_INIT(&refs);
4738 #ifndef PROFILE
4739 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4740 NULL)
4741 == -1)
4742 err(1, "pledge");
4743 #endif
4745 limit = get_default_log_limit();
4747 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4748 switch (ch) {
4749 case 'b':
4750 log_branches = 1;
4751 break;
4752 case 'C':
4753 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4754 &errstr);
4755 if (errstr != NULL)
4756 errx(1, "number of context lines is %s: %s",
4757 errstr, optarg);
4758 break;
4759 case 'c':
4760 start_commit = optarg;
4761 break;
4762 case 'd':
4763 show_diffstat = 1;
4764 break;
4765 case 'l':
4766 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4767 if (errstr != NULL)
4768 errx(1, "number of commits is %s: %s",
4769 errstr, optarg);
4770 break;
4771 case 'P':
4772 show_changed_paths = 1;
4773 break;
4774 case 'p':
4775 show_patch = 1;
4776 break;
4777 case 'R':
4778 reverse_display_order = 1;
4779 break;
4780 case 'r':
4781 repo_path = realpath(optarg, NULL);
4782 if (repo_path == NULL)
4783 return got_error_from_errno2("realpath",
4784 optarg);
4785 got_path_strip_trailing_slashes(repo_path);
4786 break;
4787 case 'S':
4788 search_pattern = optarg;
4789 break;
4790 case 's':
4791 one_line = 1;
4792 break;
4793 case 't':
4794 toposort = 1;
4795 break;
4796 case 'x':
4797 end_commit = optarg;
4798 break;
4799 default:
4800 usage_log();
4801 /* NOTREACHED */
4805 argc -= optind;
4806 argv += optind;
4808 if (diff_context == -1)
4809 diff_context = 3;
4810 else if (!show_patch)
4811 errx(1, "-C requires -p");
4813 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4814 errx(1, "cannot use -s with -d, -p or -P");
4816 cwd = getcwd(NULL, 0);
4817 if (cwd == NULL) {
4818 error = got_error_from_errno("getcwd");
4819 goto done;
4822 error = got_repo_pack_fds_open(&pack_fds);
4823 if (error != NULL)
4824 goto done;
4826 if (repo_path == NULL) {
4827 error = got_worktree_open(&worktree, cwd,
4828 GOT_WORKTREE_GOT_DIR);
4829 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4830 goto done;
4831 error = NULL;
4834 if (argc == 1) {
4835 if (worktree) {
4836 error = got_worktree_resolve_path(&path, worktree,
4837 argv[0]);
4838 if (error)
4839 goto done;
4840 } else {
4841 path = strdup(argv[0]);
4842 if (path == NULL) {
4843 error = got_error_from_errno("strdup");
4844 goto done;
4847 } else if (argc != 0)
4848 usage_log();
4850 if (repo_path == NULL) {
4851 repo_path = worktree ?
4852 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4854 if (repo_path == NULL) {
4855 error = got_error_from_errno("strdup");
4856 goto done;
4859 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4860 if (error != NULL)
4861 goto done;
4863 error = apply_unveil(got_repo_get_path(repo), 1,
4864 worktree ? got_worktree_get_root_path(worktree) : NULL);
4865 if (error)
4866 goto done;
4868 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4869 if (error)
4870 goto done;
4872 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4873 if (error)
4874 goto done;
4876 if (start_commit == NULL) {
4877 struct got_reference *head_ref;
4878 struct got_commit_object *commit = NULL;
4879 error = got_ref_open(&head_ref, repo,
4880 worktree ? got_worktree_get_head_ref_name(worktree)
4881 : GOT_REF_HEAD, 0);
4882 if (error != NULL)
4883 goto done;
4884 error = got_ref_resolve(&start_id, repo, head_ref);
4885 got_ref_close(head_ref);
4886 if (error != NULL)
4887 goto done;
4888 error = got_object_open_as_commit(&commit, repo,
4889 start_id);
4890 if (error != NULL)
4891 goto done;
4892 got_object_commit_close(commit);
4893 } else {
4894 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4895 repo, worktree);
4896 if (error != NULL)
4897 goto done;
4898 if (keyword_idstr != NULL)
4899 start_commit = keyword_idstr;
4901 error = got_repo_match_object_id(&start_id, NULL,
4902 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4903 if (error != NULL)
4904 goto done;
4906 if (end_commit != NULL) {
4907 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4908 repo, worktree);
4909 if (error != NULL)
4910 goto done;
4911 if (keyword_idstr != NULL)
4912 end_commit = keyword_idstr;
4914 error = got_repo_match_object_id(&end_id, NULL,
4915 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4916 if (error != NULL)
4917 goto done;
4920 if (worktree) {
4922 * If a path was specified on the command line it was resolved
4923 * to a path in the work tree above. Prepend the work tree's
4924 * path prefix to obtain the corresponding in-repository path.
4926 if (path) {
4927 const char *prefix;
4928 prefix = got_worktree_get_path_prefix(worktree);
4929 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4930 (path[0] != '\0') ? "/" : "", path) == -1) {
4931 error = got_error_from_errno("asprintf");
4932 goto done;
4935 } else
4936 error = got_repo_map_path(&in_repo_path, repo,
4937 path ? path : "");
4938 if (error != NULL)
4939 goto done;
4940 if (in_repo_path) {
4941 free(path);
4942 path = in_repo_path;
4945 if (worktree) {
4946 /* Release work tree lock. */
4947 got_worktree_close(worktree);
4948 worktree = NULL;
4951 if (search_pattern && show_patch) {
4952 tmpfile = got_opentemp();
4953 if (tmpfile == NULL) {
4954 error = got_error_from_errno("got_opentemp");
4955 goto done;
4959 error = print_commits(start_id, end_id, repo, path ? path : "",
4960 show_changed_paths, show_diffstat, show_patch, search_pattern,
4961 diff_context, limit, log_branches, reverse_display_order,
4962 refs_idmap, one_line, toposort, tmpfile);
4963 done:
4964 free(path);
4965 free(repo_path);
4966 free(cwd);
4967 free(start_id);
4968 free(end_id);
4969 free(keyword_idstr);
4970 if (worktree)
4971 got_worktree_close(worktree);
4972 if (repo) {
4973 const struct got_error *close_err = got_repo_close(repo);
4974 if (error == NULL)
4975 error = close_err;
4977 if (pack_fds) {
4978 const struct got_error *pack_err =
4979 got_repo_pack_fds_close(pack_fds);
4980 if (error == NULL)
4981 error = pack_err;
4983 if (refs_idmap)
4984 got_reflist_object_id_map_free(refs_idmap);
4985 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4986 error = got_error_from_errno("fclose");
4987 got_ref_list_free(&refs);
4988 return error;
4991 __dead static void
4992 usage_diff(void)
4994 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4995 "[-r repository-path] [object1 object2 | path ...]\n",
4996 getprogname());
4997 exit(1);
5000 struct print_diff_arg {
5001 struct got_repository *repo;
5002 struct got_worktree *worktree;
5003 struct got_diffstat_cb_arg *diffstat;
5004 int diff_context;
5005 const char *id_str;
5006 int header_shown;
5007 int diff_staged;
5008 enum got_diff_algorithm diff_algo;
5009 int ignore_whitespace;
5010 int force_text_diff;
5011 FILE *f1;
5012 FILE *f2;
5013 FILE *outfile;
5017 * Create a file which contains the target path of a symlink so we can feed
5018 * it as content to the diff engine.
5020 static const struct got_error *
5021 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
5022 const char *abspath)
5024 const struct got_error *err = NULL;
5025 char target_path[PATH_MAX];
5026 ssize_t target_len, outlen;
5028 *fd = -1;
5030 if (dirfd != -1) {
5031 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
5032 if (target_len == -1)
5033 return got_error_from_errno2("readlinkat", abspath);
5034 } else {
5035 target_len = readlink(abspath, target_path, PATH_MAX);
5036 if (target_len == -1)
5037 return got_error_from_errno2("readlink", abspath);
5040 *fd = got_opentempfd();
5041 if (*fd == -1)
5042 return got_error_from_errno("got_opentempfd");
5044 outlen = write(*fd, target_path, target_len);
5045 if (outlen == -1) {
5046 err = got_error_from_errno("got_opentempfd");
5047 goto done;
5050 if (lseek(*fd, 0, SEEK_SET) == -1) {
5051 err = got_error_from_errno2("lseek", abspath);
5052 goto done;
5054 done:
5055 if (err) {
5056 close(*fd);
5057 *fd = -1;
5059 return err;
5062 static const struct got_error *
5063 print_diff(void *arg, unsigned char status, unsigned char staged_status,
5064 const char *path, struct got_object_id *blob_id,
5065 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5066 int dirfd, const char *de_name)
5068 struct print_diff_arg *a = arg;
5069 const struct got_error *err = NULL;
5070 struct got_blob_object *blob1 = NULL;
5071 int fd = -1, fd1 = -1, fd2 = -1;
5072 FILE *f2 = NULL;
5073 char *abspath = NULL, *label1 = NULL;
5074 struct stat sb;
5075 off_t size1 = 0;
5076 int f2_exists = 0;
5078 memset(&sb, 0, sizeof(sb));
5080 if (a->diff_staged) {
5081 if (staged_status != GOT_STATUS_MODIFY &&
5082 staged_status != GOT_STATUS_ADD &&
5083 staged_status != GOT_STATUS_DELETE)
5084 return NULL;
5085 } else {
5086 if (staged_status == GOT_STATUS_DELETE)
5087 return NULL;
5088 if (status == GOT_STATUS_NONEXISTENT)
5089 return got_error_set_errno(ENOENT, path);
5090 if (status != GOT_STATUS_MODIFY &&
5091 status != GOT_STATUS_ADD &&
5092 status != GOT_STATUS_DELETE &&
5093 status != GOT_STATUS_CONFLICT)
5094 return NULL;
5097 err = got_opentemp_truncate(a->f1);
5098 if (err)
5099 return got_error_from_errno("got_opentemp_truncate");
5100 err = got_opentemp_truncate(a->f2);
5101 if (err)
5102 return got_error_from_errno("got_opentemp_truncate");
5104 if (!a->header_shown) {
5105 if (fprintf(a->outfile, "diff %s%s\n",
5106 a->diff_staged ? "-s " : "",
5107 got_worktree_get_root_path(a->worktree)) < 0) {
5108 err = got_error_from_errno("fprintf");
5109 goto done;
5111 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5112 err = got_error_from_errno("fprintf");
5113 goto done;
5115 if (fprintf(a->outfile, "path + %s%s\n",
5116 got_worktree_get_root_path(a->worktree),
5117 a->diff_staged ? " (staged changes)" : "") < 0) {
5118 err = got_error_from_errno("fprintf");
5119 goto done;
5121 a->header_shown = 1;
5124 if (a->diff_staged) {
5125 const char *label1 = NULL, *label2 = NULL;
5126 switch (staged_status) {
5127 case GOT_STATUS_MODIFY:
5128 label1 = path;
5129 label2 = path;
5130 break;
5131 case GOT_STATUS_ADD:
5132 label2 = path;
5133 break;
5134 case GOT_STATUS_DELETE:
5135 label1 = path;
5136 break;
5137 default:
5138 return got_error(GOT_ERR_FILE_STATUS);
5140 fd1 = got_opentempfd();
5141 if (fd1 == -1) {
5142 err = got_error_from_errno("got_opentempfd");
5143 goto done;
5145 fd2 = got_opentempfd();
5146 if (fd2 == -1) {
5147 err = got_error_from_errno("got_opentempfd");
5148 goto done;
5150 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5151 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5152 a->diff_algo, a->diff_context, a->ignore_whitespace,
5153 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5154 goto done;
5157 fd1 = got_opentempfd();
5158 if (fd1 == -1) {
5159 err = got_error_from_errno("got_opentempfd");
5160 goto done;
5163 if (staged_status == GOT_STATUS_ADD ||
5164 staged_status == GOT_STATUS_MODIFY) {
5165 char *id_str;
5166 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5167 8192, fd1);
5168 if (err)
5169 goto done;
5170 err = got_object_id_str(&id_str, staged_blob_id);
5171 if (err)
5172 goto done;
5173 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5174 err = got_error_from_errno("asprintf");
5175 free(id_str);
5176 goto done;
5178 free(id_str);
5179 } else if (status != GOT_STATUS_ADD) {
5180 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5181 fd1);
5182 if (err)
5183 goto done;
5186 if (status != GOT_STATUS_DELETE) {
5187 if (asprintf(&abspath, "%s/%s",
5188 got_worktree_get_root_path(a->worktree), path) == -1) {
5189 err = got_error_from_errno("asprintf");
5190 goto done;
5193 if (dirfd != -1) {
5194 fd = openat(dirfd, de_name,
5195 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5196 if (fd == -1) {
5197 if (!got_err_open_nofollow_on_symlink()) {
5198 err = got_error_from_errno2("openat",
5199 abspath);
5200 goto done;
5202 err = get_symlink_target_file(&fd, dirfd,
5203 de_name, abspath);
5204 if (err)
5205 goto done;
5207 } else {
5208 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5209 if (fd == -1) {
5210 if (!got_err_open_nofollow_on_symlink()) {
5211 err = got_error_from_errno2("open",
5212 abspath);
5213 goto done;
5215 err = get_symlink_target_file(&fd, dirfd,
5216 de_name, abspath);
5217 if (err)
5218 goto done;
5221 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5222 err = got_error_from_errno2("fstatat", abspath);
5223 goto done;
5225 f2 = fdopen(fd, "r");
5226 if (f2 == NULL) {
5227 err = got_error_from_errno2("fdopen", abspath);
5228 goto done;
5230 fd = -1;
5231 f2_exists = 1;
5234 if (blob1) {
5235 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5236 a->f1, blob1);
5237 if (err)
5238 goto done;
5241 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5242 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5243 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5244 done:
5245 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5246 err = got_error_from_errno("close");
5247 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5248 err = got_error_from_errno("close");
5249 if (blob1)
5250 got_object_blob_close(blob1);
5251 if (fd != -1 && close(fd) == -1 && err == NULL)
5252 err = got_error_from_errno("close");
5253 if (f2 && fclose(f2) == EOF && err == NULL)
5254 err = got_error_from_errno("fclose");
5255 free(abspath);
5256 return err;
5259 static const struct got_error *
5260 cmd_diff(int argc, char *argv[])
5262 const struct got_error *error;
5263 struct got_repository *repo = NULL;
5264 struct got_worktree *worktree = NULL;
5265 char *cwd = NULL, *repo_path = NULL;
5266 const char *commit_args[2] = { NULL, NULL };
5267 int ncommit_args = 0;
5268 struct got_object_id *ids[2] = { NULL, NULL };
5269 char *labels[2] = { NULL, NULL };
5270 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5271 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5272 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5273 const char *errstr;
5274 struct got_reflist_head refs;
5275 struct got_pathlist_head diffstat_paths, paths;
5276 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5277 int fd1 = -1, fd2 = -1;
5278 int *pack_fds = NULL;
5279 struct got_diffstat_cb_arg dsa;
5281 memset(&dsa, 0, sizeof(dsa));
5283 TAILQ_INIT(&refs);
5284 TAILQ_INIT(&paths);
5285 TAILQ_INIT(&diffstat_paths);
5287 #ifndef PROFILE
5288 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5289 NULL) == -1)
5290 err(1, "pledge");
5291 #endif
5293 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5294 switch (ch) {
5295 case 'a':
5296 force_text_diff = 1;
5297 break;
5298 case 'C':
5299 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5300 &errstr);
5301 if (errstr != NULL)
5302 errx(1, "number of context lines is %s: %s",
5303 errstr, optarg);
5304 break;
5305 case 'c':
5306 if (ncommit_args >= 2)
5307 errx(1, "too many -c options used");
5308 commit_args[ncommit_args++] = optarg;
5309 break;
5310 case 'd':
5311 show_diffstat = 1;
5312 break;
5313 case 'P':
5314 force_path = 1;
5315 break;
5316 case 'r':
5317 repo_path = realpath(optarg, NULL);
5318 if (repo_path == NULL)
5319 return got_error_from_errno2("realpath",
5320 optarg);
5321 got_path_strip_trailing_slashes(repo_path);
5322 rflag = 1;
5323 break;
5324 case 's':
5325 diff_staged = 1;
5326 break;
5327 case 'w':
5328 ignore_whitespace = 1;
5329 break;
5330 default:
5331 usage_diff();
5332 /* NOTREACHED */
5336 argc -= optind;
5337 argv += optind;
5339 cwd = getcwd(NULL, 0);
5340 if (cwd == NULL) {
5341 error = got_error_from_errno("getcwd");
5342 goto done;
5345 error = got_repo_pack_fds_open(&pack_fds);
5346 if (error != NULL)
5347 goto done;
5349 if (repo_path == NULL) {
5350 error = got_worktree_open(&worktree, cwd,
5351 GOT_WORKTREE_GOT_DIR);
5352 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5353 goto done;
5354 else
5355 error = NULL;
5356 if (worktree) {
5357 repo_path =
5358 strdup(got_worktree_get_repo_path(worktree));
5359 if (repo_path == NULL) {
5360 error = got_error_from_errno("strdup");
5361 goto done;
5363 } else {
5364 repo_path = strdup(cwd);
5365 if (repo_path == NULL) {
5366 error = got_error_from_errno("strdup");
5367 goto done;
5372 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5373 free(repo_path);
5374 if (error != NULL)
5375 goto done;
5377 if (show_diffstat) {
5378 dsa.paths = &diffstat_paths;
5379 dsa.force_text = force_text_diff;
5380 dsa.ignore_ws = ignore_whitespace;
5381 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5384 if (rflag || worktree == NULL || ncommit_args > 0) {
5385 if (force_path) {
5386 error = got_error_msg(GOT_ERR_NOT_IMPL,
5387 "-P option can only be used when diffing "
5388 "a work tree");
5389 goto done;
5391 if (diff_staged) {
5392 error = got_error_msg(GOT_ERR_NOT_IMPL,
5393 "-s option can only be used when diffing "
5394 "a work tree");
5395 goto done;
5399 error = apply_unveil(got_repo_get_path(repo), 1,
5400 worktree ? got_worktree_get_root_path(worktree) : NULL);
5401 if (error)
5402 goto done;
5404 if ((!force_path && argc == 2) || ncommit_args > 0) {
5405 int obj_type = (ncommit_args > 0 ?
5406 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5407 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5408 NULL);
5409 if (error)
5410 goto done;
5411 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5412 const char *arg;
5413 char *keyword_idstr = NULL;
5415 if (ncommit_args > 0)
5416 arg = commit_args[i];
5417 else
5418 arg = argv[i];
5420 error = got_keyword_to_idstr(&keyword_idstr, arg,
5421 repo, worktree);
5422 if (error != NULL)
5423 goto done;
5424 if (keyword_idstr != NULL)
5425 arg = keyword_idstr;
5427 error = got_repo_match_object_id(&ids[i], &labels[i],
5428 arg, obj_type, &refs, repo);
5429 free(keyword_idstr);
5430 if (error) {
5431 if (error->code != GOT_ERR_NOT_REF &&
5432 error->code != GOT_ERR_NO_OBJ)
5433 goto done;
5434 if (ncommit_args > 0)
5435 goto done;
5436 error = NULL;
5437 break;
5442 f1 = got_opentemp();
5443 if (f1 == NULL) {
5444 error = got_error_from_errno("got_opentemp");
5445 goto done;
5448 f2 = got_opentemp();
5449 if (f2 == NULL) {
5450 error = got_error_from_errno("got_opentemp");
5451 goto done;
5454 outfile = got_opentemp();
5455 if (outfile == NULL) {
5456 error = got_error_from_errno("got_opentemp");
5457 goto done;
5460 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5461 struct print_diff_arg arg;
5462 char *id_str;
5464 if (worktree == NULL) {
5465 if (argc == 2 && ids[0] == NULL) {
5466 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5467 goto done;
5468 } else if (argc == 2 && ids[1] == NULL) {
5469 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5470 goto done;
5471 } else if (argc > 0) {
5472 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5473 "%s", "specified paths cannot be resolved");
5474 goto done;
5475 } else {
5476 error = got_error(GOT_ERR_NOT_WORKTREE);
5477 goto done;
5481 error = get_worktree_paths_from_argv(&paths, argc, argv,
5482 worktree);
5483 if (error)
5484 goto done;
5486 error = got_object_id_str(&id_str,
5487 got_worktree_get_base_commit_id(worktree));
5488 if (error)
5489 goto done;
5490 arg.repo = repo;
5491 arg.worktree = worktree;
5492 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5493 arg.diff_context = diff_context;
5494 arg.id_str = id_str;
5495 arg.header_shown = 0;
5496 arg.diff_staged = diff_staged;
5497 arg.ignore_whitespace = ignore_whitespace;
5498 arg.force_text_diff = force_text_diff;
5499 arg.diffstat = show_diffstat ? &dsa : NULL;
5500 arg.f1 = f1;
5501 arg.f2 = f2;
5502 arg.outfile = outfile;
5504 error = got_worktree_status(worktree, &paths, repo, 0,
5505 print_diff, &arg, check_cancelled, NULL);
5506 free(id_str);
5507 if (error)
5508 goto done;
5510 if (show_diffstat && dsa.nfiles > 0) {
5511 char *header;
5513 if (asprintf(&header, "diffstat %s%s",
5514 diff_staged ? "-s " : "",
5515 got_worktree_get_root_path(worktree)) == -1) {
5516 error = got_error_from_errno("asprintf");
5517 goto done;
5520 error = print_diffstat(&dsa, header);
5521 free(header);
5522 if (error)
5523 goto done;
5526 error = printfile(outfile);
5527 goto done;
5530 if (ncommit_args == 1) {
5531 struct got_commit_object *commit;
5532 error = got_object_open_as_commit(&commit, repo, ids[0]);
5533 if (error)
5534 goto done;
5536 labels[1] = labels[0];
5537 ids[1] = ids[0];
5538 if (got_object_commit_get_nparents(commit) > 0) {
5539 const struct got_object_id_queue *pids;
5540 struct got_object_qid *pid;
5541 pids = got_object_commit_get_parent_ids(commit);
5542 pid = STAILQ_FIRST(pids);
5543 ids[0] = got_object_id_dup(&pid->id);
5544 if (ids[0] == NULL) {
5545 error = got_error_from_errno(
5546 "got_object_id_dup");
5547 got_object_commit_close(commit);
5548 goto done;
5550 error = got_object_id_str(&labels[0], ids[0]);
5551 if (error) {
5552 got_object_commit_close(commit);
5553 goto done;
5555 } else {
5556 ids[0] = NULL;
5557 labels[0] = strdup("/dev/null");
5558 if (labels[0] == NULL) {
5559 error = got_error_from_errno("strdup");
5560 got_object_commit_close(commit);
5561 goto done;
5565 got_object_commit_close(commit);
5568 if (ncommit_args == 0 && argc > 2) {
5569 error = got_error_msg(GOT_ERR_BAD_PATH,
5570 "path arguments cannot be used when diffing two objects");
5571 goto done;
5574 if (ids[0]) {
5575 error = got_object_get_type(&type1, repo, ids[0]);
5576 if (error)
5577 goto done;
5580 error = got_object_get_type(&type2, repo, ids[1]);
5581 if (error)
5582 goto done;
5583 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5584 error = got_error(GOT_ERR_OBJ_TYPE);
5585 goto done;
5587 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5588 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5589 "path arguments cannot be used when diffing blobs");
5590 goto done;
5593 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5594 char *in_repo_path;
5595 struct got_pathlist_entry *new;
5596 if (worktree) {
5597 const char *prefix;
5598 char *p;
5599 error = got_worktree_resolve_path(&p, worktree,
5600 argv[i]);
5601 if (error)
5602 goto done;
5603 prefix = got_worktree_get_path_prefix(worktree);
5604 while (prefix[0] == '/')
5605 prefix++;
5606 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5607 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5608 p) == -1) {
5609 error = got_error_from_errno("asprintf");
5610 free(p);
5611 goto done;
5613 free(p);
5614 } else {
5615 char *mapped_path, *s;
5616 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5617 if (error)
5618 goto done;
5619 s = mapped_path;
5620 while (s[0] == '/')
5621 s++;
5622 in_repo_path = strdup(s);
5623 if (in_repo_path == NULL) {
5624 error = got_error_from_errno("asprintf");
5625 free(mapped_path);
5626 goto done;
5628 free(mapped_path);
5631 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5632 if (error || new == NULL /* duplicate */)
5633 free(in_repo_path);
5634 if (error)
5635 goto done;
5638 if (worktree) {
5639 /* Release work tree lock. */
5640 got_worktree_close(worktree);
5641 worktree = NULL;
5644 fd1 = got_opentempfd();
5645 if (fd1 == -1) {
5646 error = got_error_from_errno("got_opentempfd");
5647 goto done;
5650 fd2 = got_opentempfd();
5651 if (fd2 == -1) {
5652 error = got_error_from_errno("got_opentempfd");
5653 goto done;
5656 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5657 case GOT_OBJ_TYPE_BLOB:
5658 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5659 fd1, fd2, ids[0], ids[1], NULL, NULL,
5660 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5661 ignore_whitespace, force_text_diff,
5662 show_diffstat ? &dsa : NULL, repo, outfile);
5663 break;
5664 case GOT_OBJ_TYPE_TREE:
5665 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5666 ids[0], ids[1], &paths, "", "",
5667 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5668 ignore_whitespace, force_text_diff,
5669 show_diffstat ? &dsa : NULL, repo, outfile);
5670 break;
5671 case GOT_OBJ_TYPE_COMMIT:
5672 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5673 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5674 fd1, fd2, ids[0], ids[1], &paths,
5675 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5676 ignore_whitespace, force_text_diff,
5677 show_diffstat ? &dsa : NULL, repo, outfile);
5678 break;
5679 default:
5680 error = got_error(GOT_ERR_OBJ_TYPE);
5682 if (error)
5683 goto done;
5685 if (show_diffstat && dsa.nfiles > 0) {
5686 char *header = NULL;
5688 if (asprintf(&header, "diffstat %s %s",
5689 labels[0], labels[1]) == -1) {
5690 error = got_error_from_errno("asprintf");
5691 goto done;
5694 error = print_diffstat(&dsa, header);
5695 free(header);
5696 if (error)
5697 goto done;
5700 error = printfile(outfile);
5702 done:
5703 free(cwd);
5704 free(labels[0]);
5705 free(labels[1]);
5706 free(ids[0]);
5707 free(ids[1]);
5708 if (worktree)
5709 got_worktree_close(worktree);
5710 if (repo) {
5711 const struct got_error *close_err = got_repo_close(repo);
5712 if (error == NULL)
5713 error = close_err;
5715 if (pack_fds) {
5716 const struct got_error *pack_err =
5717 got_repo_pack_fds_close(pack_fds);
5718 if (error == NULL)
5719 error = pack_err;
5721 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5722 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5723 got_ref_list_free(&refs);
5724 if (outfile && fclose(outfile) == EOF && error == NULL)
5725 error = got_error_from_errno("fclose");
5726 if (f1 && fclose(f1) == EOF && error == NULL)
5727 error = got_error_from_errno("fclose");
5728 if (f2 && fclose(f2) == EOF && error == NULL)
5729 error = got_error_from_errno("fclose");
5730 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5731 error = got_error_from_errno("close");
5732 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5733 error = got_error_from_errno("close");
5734 return error;
5737 __dead static void
5738 usage_blame(void)
5740 fprintf(stderr,
5741 "usage: %s blame [-c commit] [-r repository-path] path\n",
5742 getprogname());
5743 exit(1);
5746 struct blame_line {
5747 int annotated;
5748 char *id_str;
5749 char *committer;
5750 char datebuf[11]; /* YYYY-MM-DD + NUL */
5753 struct blame_cb_args {
5754 struct blame_line *lines;
5755 int nlines;
5756 int nlines_prec;
5757 int lineno_cur;
5758 off_t *line_offsets;
5759 FILE *f;
5760 struct got_repository *repo;
5763 static const struct got_error *
5764 blame_cb(void *arg, int nlines, int lineno,
5765 struct got_commit_object *commit, struct got_object_id *id)
5767 const struct got_error *err = NULL;
5768 struct blame_cb_args *a = arg;
5769 struct blame_line *bline;
5770 char *line = NULL;
5771 size_t linesize = 0;
5772 off_t offset;
5773 struct tm tm;
5774 time_t committer_time;
5776 if (nlines != a->nlines ||
5777 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5778 return got_error(GOT_ERR_RANGE);
5780 if (sigint_received)
5781 return got_error(GOT_ERR_ITER_COMPLETED);
5783 if (lineno == -1)
5784 return NULL; /* no change in this commit */
5786 /* Annotate this line. */
5787 bline = &a->lines[lineno - 1];
5788 if (bline->annotated)
5789 return NULL;
5790 err = got_object_id_str(&bline->id_str, id);
5791 if (err)
5792 return err;
5794 bline->committer = strdup(got_object_commit_get_committer(commit));
5795 if (bline->committer == NULL) {
5796 err = got_error_from_errno("strdup");
5797 goto done;
5800 committer_time = got_object_commit_get_committer_time(commit);
5801 if (gmtime_r(&committer_time, &tm) == NULL)
5802 return got_error_from_errno("gmtime_r");
5803 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%F", &tm) == 0) {
5804 err = got_error(GOT_ERR_NO_SPACE);
5805 goto done;
5807 bline->annotated = 1;
5809 /* Print lines annotated so far. */
5810 bline = &a->lines[a->lineno_cur - 1];
5811 if (!bline->annotated)
5812 goto done;
5814 offset = a->line_offsets[a->lineno_cur - 1];
5815 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5816 err = got_error_from_errno("fseeko");
5817 goto done;
5820 while (a->lineno_cur <= a->nlines && bline->annotated) {
5821 char *smallerthan, *at, *nl, *committer;
5822 size_t len;
5824 if (getline(&line, &linesize, a->f) == -1) {
5825 if (ferror(a->f))
5826 err = got_error_from_errno("getline");
5827 break;
5830 committer = bline->committer;
5831 smallerthan = strchr(committer, '<');
5832 if (smallerthan && smallerthan[1] != '\0')
5833 committer = smallerthan + 1;
5834 at = strchr(committer, '@');
5835 if (at)
5836 *at = '\0';
5837 len = strlen(committer);
5838 if (len >= 9)
5839 committer[8] = '\0';
5841 nl = strchr(line, '\n');
5842 if (nl)
5843 *nl = '\0';
5844 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5845 bline->id_str, bline->datebuf, committer, line);
5847 a->lineno_cur++;
5848 bline = &a->lines[a->lineno_cur - 1];
5850 done:
5851 free(line);
5852 return err;
5855 static const struct got_error *
5856 cmd_blame(int argc, char *argv[])
5858 const struct got_error *error;
5859 struct got_repository *repo = NULL;
5860 struct got_worktree *worktree = NULL;
5861 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5862 char *link_target = NULL;
5863 struct got_object_id *obj_id = NULL;
5864 struct got_object_id *commit_id = NULL;
5865 struct got_commit_object *commit = NULL;
5866 struct got_blob_object *blob = NULL;
5867 char *commit_id_str = NULL, *keyword_idstr = NULL;
5868 struct blame_cb_args bca;
5869 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5870 off_t filesize;
5871 int *pack_fds = NULL;
5872 FILE *f1 = NULL, *f2 = NULL;
5874 fd1 = got_opentempfd();
5875 if (fd1 == -1)
5876 return got_error_from_errno("got_opentempfd");
5878 memset(&bca, 0, sizeof(bca));
5880 #ifndef PROFILE
5881 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5882 NULL) == -1)
5883 err(1, "pledge");
5884 #endif
5886 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5887 switch (ch) {
5888 case 'c':
5889 commit_id_str = optarg;
5890 break;
5891 case 'r':
5892 repo_path = realpath(optarg, NULL);
5893 if (repo_path == NULL)
5894 return got_error_from_errno2("realpath",
5895 optarg);
5896 got_path_strip_trailing_slashes(repo_path);
5897 break;
5898 default:
5899 usage_blame();
5900 /* NOTREACHED */
5904 argc -= optind;
5905 argv += optind;
5907 if (argc == 1)
5908 path = argv[0];
5909 else
5910 usage_blame();
5912 cwd = getcwd(NULL, 0);
5913 if (cwd == NULL) {
5914 error = got_error_from_errno("getcwd");
5915 goto done;
5918 error = got_repo_pack_fds_open(&pack_fds);
5919 if (error != NULL)
5920 goto done;
5922 if (repo_path == NULL) {
5923 error = got_worktree_open(&worktree, cwd,
5924 GOT_WORKTREE_GOT_DIR);
5925 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5926 goto done;
5927 else
5928 error = NULL;
5929 if (worktree) {
5930 repo_path =
5931 strdup(got_worktree_get_repo_path(worktree));
5932 if (repo_path == NULL) {
5933 error = got_error_from_errno("strdup");
5934 if (error)
5935 goto done;
5937 } else {
5938 repo_path = strdup(cwd);
5939 if (repo_path == NULL) {
5940 error = got_error_from_errno("strdup");
5941 goto done;
5946 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5947 if (error != NULL)
5948 goto done;
5950 if (worktree) {
5951 const char *prefix = got_worktree_get_path_prefix(worktree);
5952 char *p;
5954 error = got_worktree_resolve_path(&p, worktree, path);
5955 if (error)
5956 goto done;
5957 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5958 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5959 p) == -1) {
5960 error = got_error_from_errno("asprintf");
5961 free(p);
5962 goto done;
5964 free(p);
5965 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5966 } else {
5967 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5968 if (error)
5969 goto done;
5970 error = got_repo_map_path(&in_repo_path, repo, path);
5972 if (error)
5973 goto done;
5975 if (commit_id_str == NULL) {
5976 struct got_reference *head_ref;
5977 error = got_ref_open(&head_ref, repo, worktree ?
5978 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5979 if (error != NULL)
5980 goto done;
5981 error = got_ref_resolve(&commit_id, repo, head_ref);
5982 got_ref_close(head_ref);
5983 if (error != NULL)
5984 goto done;
5985 } else {
5986 struct got_reflist_head refs;
5988 TAILQ_INIT(&refs);
5989 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5990 NULL);
5991 if (error)
5992 goto done;
5994 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5995 repo, worktree);
5996 if (error != NULL)
5997 goto done;
5998 if (keyword_idstr != NULL)
5999 commit_id_str = keyword_idstr;
6001 error = got_repo_match_object_id(&commit_id, NULL,
6002 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6003 got_ref_list_free(&refs);
6004 if (error)
6005 goto done;
6008 if (worktree) {
6009 /* Release work tree lock. */
6010 got_worktree_close(worktree);
6011 worktree = NULL;
6014 error = got_object_open_as_commit(&commit, repo, commit_id);
6015 if (error)
6016 goto done;
6018 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6019 commit, repo);
6020 if (error)
6021 goto done;
6023 error = got_object_id_by_path(&obj_id, repo, commit,
6024 link_target ? link_target : in_repo_path);
6025 if (error)
6026 goto done;
6028 error = got_object_get_type(&obj_type, repo, obj_id);
6029 if (error)
6030 goto done;
6032 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6033 error = got_error_path(link_target ? link_target : in_repo_path,
6034 GOT_ERR_OBJ_TYPE);
6035 goto done;
6038 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
6039 if (error)
6040 goto done;
6041 bca.f = got_opentemp();
6042 if (bca.f == NULL) {
6043 error = got_error_from_errno("got_opentemp");
6044 goto done;
6046 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
6047 &bca.line_offsets, bca.f, blob);
6048 if (error || bca.nlines == 0)
6049 goto done;
6051 /* Don't include \n at EOF in the blame line count. */
6052 if (bca.line_offsets[bca.nlines - 1] == filesize)
6053 bca.nlines--;
6055 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
6056 if (bca.lines == NULL) {
6057 error = got_error_from_errno("calloc");
6058 goto done;
6060 bca.lineno_cur = 1;
6061 bca.nlines_prec = 0;
6062 i = bca.nlines;
6063 while (i > 0) {
6064 i /= 10;
6065 bca.nlines_prec++;
6067 bca.repo = repo;
6069 fd2 = got_opentempfd();
6070 if (fd2 == -1) {
6071 error = got_error_from_errno("got_opentempfd");
6072 goto done;
6074 fd3 = got_opentempfd();
6075 if (fd3 == -1) {
6076 error = got_error_from_errno("got_opentempfd");
6077 goto done;
6079 f1 = got_opentemp();
6080 if (f1 == NULL) {
6081 error = got_error_from_errno("got_opentemp");
6082 goto done;
6084 f2 = got_opentemp();
6085 if (f2 == NULL) {
6086 error = got_error_from_errno("got_opentemp");
6087 goto done;
6089 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6090 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6091 check_cancelled, NULL, fd2, fd3, f1, f2);
6092 done:
6093 free(keyword_idstr);
6094 free(in_repo_path);
6095 free(link_target);
6096 free(repo_path);
6097 free(cwd);
6098 free(commit_id);
6099 free(obj_id);
6100 if (commit)
6101 got_object_commit_close(commit);
6103 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6104 error = got_error_from_errno("close");
6105 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6106 error = got_error_from_errno("close");
6107 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6108 error = got_error_from_errno("close");
6109 if (f1 && fclose(f1) == EOF && error == NULL)
6110 error = got_error_from_errno("fclose");
6111 if (f2 && fclose(f2) == EOF && error == NULL)
6112 error = got_error_from_errno("fclose");
6114 if (blob)
6115 got_object_blob_close(blob);
6116 if (worktree)
6117 got_worktree_close(worktree);
6118 if (repo) {
6119 const struct got_error *close_err = got_repo_close(repo);
6120 if (error == NULL)
6121 error = close_err;
6123 if (pack_fds) {
6124 const struct got_error *pack_err =
6125 got_repo_pack_fds_close(pack_fds);
6126 if (error == NULL)
6127 error = pack_err;
6129 if (bca.lines) {
6130 for (i = 0; i < bca.nlines; i++) {
6131 struct blame_line *bline = &bca.lines[i];
6132 free(bline->id_str);
6133 free(bline->committer);
6135 free(bca.lines);
6137 free(bca.line_offsets);
6138 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6139 error = got_error_from_errno("fclose");
6140 return error;
6143 __dead static void
6144 usage_tree(void)
6146 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6147 "[path]\n", getprogname());
6148 exit(1);
6151 static const struct got_error *
6152 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6153 const char *root_path, struct got_repository *repo)
6155 const struct got_error *err = NULL;
6156 int is_root_path = (strcmp(path, root_path) == 0);
6157 const char *modestr = "";
6158 mode_t mode = got_tree_entry_get_mode(te);
6159 char *link_target = NULL;
6161 path += strlen(root_path);
6162 while (path[0] == '/')
6163 path++;
6165 if (got_object_tree_entry_is_submodule(te))
6166 modestr = "$";
6167 else if (S_ISLNK(mode)) {
6168 int i;
6170 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6171 if (err)
6172 return err;
6173 for (i = 0; link_target[i] != '\0'; i++) {
6174 if (!isprint((unsigned char)link_target[i]))
6175 link_target[i] = '?';
6178 modestr = "@";
6180 else if (S_ISDIR(mode))
6181 modestr = "/";
6182 else if (mode & S_IXUSR)
6183 modestr = "*";
6185 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6186 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6187 link_target ? " -> ": "", link_target ? link_target : "");
6189 free(link_target);
6190 return NULL;
6193 static const struct got_error *
6194 print_tree(const char *path, struct got_commit_object *commit,
6195 int show_ids, int recurse, const char *root_path,
6196 struct got_repository *repo)
6198 const struct got_error *err = NULL;
6199 struct got_object_id *tree_id = NULL;
6200 struct got_tree_object *tree = NULL;
6201 int nentries, i;
6203 err = got_object_id_by_path(&tree_id, repo, commit, path);
6204 if (err)
6205 goto done;
6207 err = got_object_open_as_tree(&tree, repo, tree_id);
6208 if (err)
6209 goto done;
6210 nentries = got_object_tree_get_nentries(tree);
6211 for (i = 0; i < nentries; i++) {
6212 struct got_tree_entry *te;
6213 char *id = NULL;
6215 if (sigint_received || sigpipe_received)
6216 break;
6218 te = got_object_tree_get_entry(tree, i);
6219 if (show_ids) {
6220 char *id_str;
6221 err = got_object_id_str(&id_str,
6222 got_tree_entry_get_id(te));
6223 if (err)
6224 goto done;
6225 if (asprintf(&id, "%s ", id_str) == -1) {
6226 err = got_error_from_errno("asprintf");
6227 free(id_str);
6228 goto done;
6230 free(id_str);
6232 err = print_entry(te, id, path, root_path, repo);
6233 free(id);
6234 if (err)
6235 goto done;
6237 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6238 char *child_path;
6239 if (asprintf(&child_path, "%s%s%s", path,
6240 path[0] == '/' && path[1] == '\0' ? "" : "/",
6241 got_tree_entry_get_name(te)) == -1) {
6242 err = got_error_from_errno("asprintf");
6243 goto done;
6245 err = print_tree(child_path, commit, show_ids, 1,
6246 root_path, repo);
6247 free(child_path);
6248 if (err)
6249 goto done;
6252 done:
6253 if (tree)
6254 got_object_tree_close(tree);
6255 free(tree_id);
6256 return err;
6259 static const struct got_error *
6260 cmd_tree(int argc, char *argv[])
6262 const struct got_error *error;
6263 struct got_repository *repo = NULL;
6264 struct got_worktree *worktree = NULL;
6265 const char *path, *refname = NULL;
6266 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6267 struct got_object_id *commit_id = NULL;
6268 struct got_commit_object *commit = NULL;
6269 char *commit_id_str = NULL, *keyword_idstr = NULL;
6270 int show_ids = 0, recurse = 0;
6271 int ch;
6272 int *pack_fds = NULL;
6274 #ifndef PROFILE
6275 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6276 NULL) == -1)
6277 err(1, "pledge");
6278 #endif
6280 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6281 switch (ch) {
6282 case 'c':
6283 commit_id_str = optarg;
6284 break;
6285 case 'i':
6286 show_ids = 1;
6287 break;
6288 case 'R':
6289 recurse = 1;
6290 break;
6291 case 'r':
6292 repo_path = realpath(optarg, NULL);
6293 if (repo_path == NULL)
6294 return got_error_from_errno2("realpath",
6295 optarg);
6296 got_path_strip_trailing_slashes(repo_path);
6297 break;
6298 default:
6299 usage_tree();
6300 /* NOTREACHED */
6304 argc -= optind;
6305 argv += optind;
6307 if (argc == 1)
6308 path = argv[0];
6309 else if (argc > 1)
6310 usage_tree();
6311 else
6312 path = NULL;
6314 cwd = getcwd(NULL, 0);
6315 if (cwd == NULL) {
6316 error = got_error_from_errno("getcwd");
6317 goto done;
6320 error = got_repo_pack_fds_open(&pack_fds);
6321 if (error != NULL)
6322 goto done;
6324 if (repo_path == NULL) {
6325 error = got_worktree_open(&worktree, cwd,
6326 GOT_WORKTREE_GOT_DIR);
6327 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6328 goto done;
6329 else
6330 error = NULL;
6331 if (worktree) {
6332 repo_path =
6333 strdup(got_worktree_get_repo_path(worktree));
6334 if (repo_path == NULL)
6335 error = got_error_from_errno("strdup");
6336 if (error)
6337 goto done;
6338 } else {
6339 repo_path = strdup(cwd);
6340 if (repo_path == NULL) {
6341 error = got_error_from_errno("strdup");
6342 goto done;
6347 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6348 if (error != NULL)
6349 goto done;
6351 if (worktree) {
6352 const char *prefix = got_worktree_get_path_prefix(worktree);
6353 char *p;
6355 if (path == NULL || got_path_is_root_dir(path))
6356 path = "";
6357 error = got_worktree_resolve_path(&p, worktree, path);
6358 if (error)
6359 goto done;
6360 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6361 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6362 p) == -1) {
6363 error = got_error_from_errno("asprintf");
6364 free(p);
6365 goto done;
6367 free(p);
6368 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6369 if (error)
6370 goto done;
6371 } else {
6372 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6373 if (error)
6374 goto done;
6375 if (path == NULL)
6376 path = "/";
6377 error = got_repo_map_path(&in_repo_path, repo, path);
6378 if (error != NULL)
6379 goto done;
6382 if (commit_id_str == NULL) {
6383 struct got_reference *head_ref;
6384 if (worktree)
6385 refname = got_worktree_get_head_ref_name(worktree);
6386 else
6387 refname = GOT_REF_HEAD;
6388 error = got_ref_open(&head_ref, repo, refname, 0);
6389 if (error != NULL)
6390 goto done;
6391 error = got_ref_resolve(&commit_id, repo, head_ref);
6392 got_ref_close(head_ref);
6393 if (error != NULL)
6394 goto done;
6395 } else {
6396 struct got_reflist_head refs;
6398 TAILQ_INIT(&refs);
6399 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6400 NULL);
6401 if (error)
6402 goto done;
6404 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6405 repo, worktree);
6406 if (error != NULL)
6407 goto done;
6408 if (keyword_idstr != NULL)
6409 commit_id_str = keyword_idstr;
6411 error = got_repo_match_object_id(&commit_id, NULL,
6412 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6413 got_ref_list_free(&refs);
6414 if (error)
6415 goto done;
6418 if (worktree) {
6419 /* Release work tree lock. */
6420 got_worktree_close(worktree);
6421 worktree = NULL;
6424 error = got_object_open_as_commit(&commit, repo, commit_id);
6425 if (error)
6426 goto done;
6428 error = print_tree(in_repo_path, commit, show_ids, recurse,
6429 in_repo_path, repo);
6430 done:
6431 free(keyword_idstr);
6432 free(in_repo_path);
6433 free(repo_path);
6434 free(cwd);
6435 free(commit_id);
6436 if (commit)
6437 got_object_commit_close(commit);
6438 if (worktree)
6439 got_worktree_close(worktree);
6440 if (repo) {
6441 const struct got_error *close_err = got_repo_close(repo);
6442 if (error == NULL)
6443 error = close_err;
6445 if (pack_fds) {
6446 const struct got_error *pack_err =
6447 got_repo_pack_fds_close(pack_fds);
6448 if (error == NULL)
6449 error = pack_err;
6451 return error;
6454 __dead static void
6455 usage_status(void)
6457 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6458 "[-s status-codes] [path ...]\n", getprogname());
6459 exit(1);
6462 struct got_status_arg {
6463 char *status_codes;
6464 int suppress;
6467 static const struct got_error *
6468 print_status(void *arg, unsigned char status, unsigned char staged_status,
6469 const char *path, struct got_object_id *blob_id,
6470 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6471 int dirfd, const char *de_name)
6473 struct got_status_arg *st = arg;
6475 if (status == staged_status && (status == GOT_STATUS_DELETE))
6476 status = GOT_STATUS_NO_CHANGE;
6477 if (st != NULL && st->status_codes) {
6478 size_t ncodes = strlen(st->status_codes);
6479 int i, j = 0;
6481 for (i = 0; i < ncodes ; i++) {
6482 if (st->suppress) {
6483 if (status == st->status_codes[i] ||
6484 staged_status == st->status_codes[i]) {
6485 j++;
6486 continue;
6488 } else {
6489 if (status == st->status_codes[i] ||
6490 staged_status == st->status_codes[i])
6491 break;
6495 if (st->suppress && j == 0)
6496 goto print;
6498 if (i == ncodes)
6499 return NULL;
6501 print:
6502 printf("%c%c %s\n", status, staged_status, path);
6503 return NULL;
6506 static const struct got_error *
6507 show_operation_in_progress(struct got_worktree *worktree,
6508 struct got_repository *repo)
6510 const struct got_error *err;
6511 char *new_base_branch_name = NULL;
6512 char *branch_name = NULL;
6513 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6515 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6516 if (err)
6517 return err;
6518 if (rebase_in_progress) {
6519 err = got_worktree_rebase_info(&new_base_branch_name,
6520 &branch_name, worktree, repo);
6521 if (err)
6522 return err;
6523 printf("Work tree is rebasing %s onto %s\n",
6524 branch_name, new_base_branch_name);
6527 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6528 worktree);
6529 if (err)
6530 return err;
6531 if (histedit_in_progress) {
6532 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6533 if (err)
6534 return err;
6535 printf("Work tree is editing the history of %s\n", branch_name);
6538 err = got_worktree_merge_in_progress(&merge_in_progress,
6539 worktree, repo);
6540 if (err)
6541 return err;
6542 if (merge_in_progress) {
6543 err = got_worktree_merge_info(&branch_name, worktree,
6544 repo);
6545 if (err)
6546 return err;
6547 printf("Work tree is merging %s into %s\n", branch_name,
6548 got_worktree_get_head_ref_name(worktree));
6551 free(new_base_branch_name);
6552 free(branch_name);
6553 return NULL;
6556 static const struct got_error *
6557 cmd_status(int argc, char *argv[])
6559 const struct got_error *close_err, *error = NULL;
6560 struct got_repository *repo = NULL;
6561 struct got_worktree *worktree = NULL;
6562 struct got_status_arg st;
6563 char *cwd = NULL;
6564 struct got_pathlist_head paths;
6565 int ch, i, no_ignores = 0;
6566 int *pack_fds = NULL;
6568 TAILQ_INIT(&paths);
6570 memset(&st, 0, sizeof(st));
6571 st.status_codes = NULL;
6572 st.suppress = 0;
6574 #ifndef PROFILE
6575 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6576 NULL) == -1)
6577 err(1, "pledge");
6578 #endif
6580 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6581 switch (ch) {
6582 case 'I':
6583 no_ignores = 1;
6584 break;
6585 case 'S':
6586 if (st.status_codes != NULL && st.suppress == 0)
6587 option_conflict('S', 's');
6588 st.suppress = 1;
6589 /* fallthrough */
6590 case 's':
6591 for (i = 0; optarg[i] != '\0'; i++) {
6592 switch (optarg[i]) {
6593 case GOT_STATUS_MODIFY:
6594 case GOT_STATUS_ADD:
6595 case GOT_STATUS_DELETE:
6596 case GOT_STATUS_CONFLICT:
6597 case GOT_STATUS_MISSING:
6598 case GOT_STATUS_OBSTRUCTED:
6599 case GOT_STATUS_UNVERSIONED:
6600 case GOT_STATUS_MODE_CHANGE:
6601 case GOT_STATUS_NONEXISTENT:
6602 break;
6603 default:
6604 errx(1, "invalid status code '%c'",
6605 optarg[i]);
6608 if (ch == 's' && st.suppress)
6609 option_conflict('s', 'S');
6610 st.status_codes = optarg;
6611 break;
6612 default:
6613 usage_status();
6614 /* NOTREACHED */
6618 argc -= optind;
6619 argv += optind;
6621 cwd = getcwd(NULL, 0);
6622 if (cwd == NULL) {
6623 error = got_error_from_errno("getcwd");
6624 goto done;
6627 error = got_repo_pack_fds_open(&pack_fds);
6628 if (error != NULL)
6629 goto done;
6631 error = got_worktree_open(&worktree, cwd,
6632 GOT_WORKTREE_GOT_DIR);
6633 if (error) {
6634 if (error->code == GOT_ERR_NOT_WORKTREE)
6635 error = wrap_not_worktree_error(error, "status", cwd);
6636 goto done;
6639 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6640 NULL, pack_fds);
6641 if (error != NULL)
6642 goto done;
6644 error = apply_unveil(got_repo_get_path(repo), 1,
6645 got_worktree_get_root_path(worktree));
6646 if (error)
6647 goto done;
6649 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6650 if (error)
6651 goto done;
6653 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6654 print_status, &st, check_cancelled, NULL);
6655 if (error)
6656 goto done;
6658 error = show_operation_in_progress(worktree, repo);
6659 done:
6660 if (pack_fds) {
6661 const struct got_error *pack_err =
6662 got_repo_pack_fds_close(pack_fds);
6663 if (error == NULL)
6664 error = pack_err;
6666 if (repo) {
6667 close_err = got_repo_close(repo);
6668 if (error == NULL)
6669 error = close_err;
6671 if (worktree != NULL) {
6672 close_err = got_worktree_close(worktree);
6673 if (error == NULL)
6674 error = close_err;
6677 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6678 free(cwd);
6679 return error;
6682 __dead static void
6683 usage_ref(void)
6685 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6686 "[-s reference] [name]\n", getprogname());
6687 exit(1);
6690 static const struct got_error *
6691 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6693 static const struct got_error *err = NULL;
6694 struct got_reflist_head refs;
6695 struct got_reflist_entry *re;
6697 TAILQ_INIT(&refs);
6698 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6699 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6700 repo);
6701 if (err)
6702 return err;
6704 TAILQ_FOREACH(re, &refs, entry) {
6705 char *refstr;
6706 refstr = got_ref_to_str(re->ref);
6707 if (refstr == NULL) {
6708 err = got_error_from_errno("got_ref_to_str");
6709 break;
6711 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6712 free(refstr);
6715 got_ref_list_free(&refs);
6716 return err;
6719 static const struct got_error *
6720 delete_ref_by_name(struct got_repository *repo, const char *refname)
6722 const struct got_error *err;
6723 struct got_reference *ref;
6725 err = got_ref_open(&ref, repo, refname, 0);
6726 if (err)
6727 return err;
6729 err = delete_ref(repo, ref);
6730 got_ref_close(ref);
6731 return err;
6734 static const struct got_error *
6735 add_ref(struct got_repository *repo, const char *refname, const char *target)
6737 const struct got_error *err = NULL;
6738 struct got_object_id *id = NULL;
6739 struct got_reference *ref = NULL;
6740 struct got_reflist_head refs;
6743 * Don't let the user create a reference name with a leading '-'.
6744 * While technically a valid reference name, this case is usually
6745 * an unintended typo.
6747 if (refname[0] == '-')
6748 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6750 TAILQ_INIT(&refs);
6751 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6752 if (err)
6753 goto done;
6754 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6755 &refs, repo);
6756 got_ref_list_free(&refs);
6757 if (err)
6758 goto done;
6760 err = got_ref_alloc(&ref, refname, id);
6761 if (err)
6762 goto done;
6764 err = got_ref_write(ref, repo);
6765 done:
6766 if (ref)
6767 got_ref_close(ref);
6768 free(id);
6769 return err;
6772 static const struct got_error *
6773 add_symref(struct got_repository *repo, const char *refname, const char *target)
6775 const struct got_error *err = NULL;
6776 struct got_reference *ref = NULL;
6777 struct got_reference *target_ref = NULL;
6780 * Don't let the user create a reference name with a leading '-'.
6781 * While technically a valid reference name, this case is usually
6782 * an unintended typo.
6784 if (refname[0] == '-')
6785 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6787 err = got_ref_open(&target_ref, repo, target, 0);
6788 if (err)
6789 return err;
6791 err = got_ref_alloc_symref(&ref, refname, target_ref);
6792 if (err)
6793 goto done;
6795 err = got_ref_write(ref, repo);
6796 done:
6797 if (target_ref)
6798 got_ref_close(target_ref);
6799 if (ref)
6800 got_ref_close(ref);
6801 return err;
6804 static const struct got_error *
6805 cmd_ref(int argc, char *argv[])
6807 const struct got_error *error = NULL;
6808 struct got_repository *repo = NULL;
6809 struct got_worktree *worktree = NULL;
6810 char *cwd = NULL, *repo_path = NULL;
6811 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6812 const char *obj_arg = NULL, *symref_target= NULL;
6813 char *refname = NULL, *keyword_idstr = NULL;
6814 int *pack_fds = NULL;
6816 #ifndef PROFILE
6817 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6818 "sendfd unveil", NULL) == -1)
6819 err(1, "pledge");
6820 #endif
6822 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6823 switch (ch) {
6824 case 'c':
6825 obj_arg = optarg;
6826 break;
6827 case 'd':
6828 do_delete = 1;
6829 break;
6830 case 'l':
6831 do_list = 1;
6832 break;
6833 case 'r':
6834 repo_path = realpath(optarg, NULL);
6835 if (repo_path == NULL)
6836 return got_error_from_errno2("realpath",
6837 optarg);
6838 got_path_strip_trailing_slashes(repo_path);
6839 break;
6840 case 's':
6841 symref_target = optarg;
6842 break;
6843 case 't':
6844 sort_by_time = 1;
6845 break;
6846 default:
6847 usage_ref();
6848 /* NOTREACHED */
6852 if (obj_arg && do_list)
6853 option_conflict('c', 'l');
6854 if (obj_arg && do_delete)
6855 option_conflict('c', 'd');
6856 if (obj_arg && symref_target)
6857 option_conflict('c', 's');
6858 if (symref_target && do_delete)
6859 option_conflict('s', 'd');
6860 if (symref_target && do_list)
6861 option_conflict('s', 'l');
6862 if (do_delete && do_list)
6863 option_conflict('d', 'l');
6864 if (sort_by_time && !do_list)
6865 errx(1, "-t option requires -l option");
6867 argc -= optind;
6868 argv += optind;
6870 if (do_list) {
6871 if (argc != 0 && argc != 1)
6872 usage_ref();
6873 if (argc == 1) {
6874 refname = strdup(argv[0]);
6875 if (refname == NULL) {
6876 error = got_error_from_errno("strdup");
6877 goto done;
6880 } else {
6881 if (argc != 1)
6882 usage_ref();
6883 refname = strdup(argv[0]);
6884 if (refname == NULL) {
6885 error = got_error_from_errno("strdup");
6886 goto done;
6890 if (refname)
6891 got_path_strip_trailing_slashes(refname);
6893 cwd = getcwd(NULL, 0);
6894 if (cwd == NULL) {
6895 error = got_error_from_errno("getcwd");
6896 goto done;
6899 error = got_repo_pack_fds_open(&pack_fds);
6900 if (error != NULL)
6901 goto done;
6903 if (repo_path == NULL) {
6904 error = got_worktree_open(&worktree, cwd,
6905 GOT_WORKTREE_GOT_DIR);
6906 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6907 goto done;
6908 else
6909 error = NULL;
6910 if (worktree) {
6911 repo_path =
6912 strdup(got_worktree_get_repo_path(worktree));
6913 if (repo_path == NULL)
6914 error = got_error_from_errno("strdup");
6915 if (error)
6916 goto done;
6917 } else {
6918 repo_path = strdup(cwd);
6919 if (repo_path == NULL) {
6920 error = got_error_from_errno("strdup");
6921 goto done;
6926 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6927 if (error != NULL)
6928 goto done;
6930 #ifndef PROFILE
6931 if (do_list) {
6932 /* Remove "cpath" promise. */
6933 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6934 NULL) == -1)
6935 err(1, "pledge");
6937 #endif
6939 error = apply_unveil(got_repo_get_path(repo), do_list,
6940 worktree ? got_worktree_get_root_path(worktree) : NULL);
6941 if (error)
6942 goto done;
6944 if (do_list)
6945 error = list_refs(repo, refname, sort_by_time);
6946 else if (do_delete)
6947 error = delete_ref_by_name(repo, refname);
6948 else if (symref_target)
6949 error = add_symref(repo, refname, symref_target);
6950 else {
6951 if (obj_arg == NULL)
6952 usage_ref();
6954 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6955 repo, worktree);
6956 if (error != NULL)
6957 goto done;
6958 if (keyword_idstr != NULL)
6959 obj_arg = keyword_idstr;
6961 error = add_ref(repo, refname, obj_arg);
6963 done:
6964 free(refname);
6965 if (repo) {
6966 const struct got_error *close_err = got_repo_close(repo);
6967 if (error == NULL)
6968 error = close_err;
6970 if (worktree)
6971 got_worktree_close(worktree);
6972 if (pack_fds) {
6973 const struct got_error *pack_err =
6974 got_repo_pack_fds_close(pack_fds);
6975 if (error == NULL)
6976 error = pack_err;
6978 free(cwd);
6979 free(repo_path);
6980 free(keyword_idstr);
6981 return error;
6984 __dead static void
6985 usage_branch(void)
6987 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6988 "[-r repository-path] [name]\n", getprogname());
6989 exit(1);
6992 static const struct got_error *
6993 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6994 struct got_reference *ref)
6996 const struct got_error *err = NULL;
6997 const char *refname;
6998 char *refstr;
6999 char marker = ' ';
7001 refname = got_ref_get_name(ref);
7002 if (worktree && strcmp(refname,
7003 got_worktree_get_head_ref_name(worktree)) == 0) {
7004 err = got_worktree_get_state(&marker, repo, worktree,
7005 check_cancelled, NULL);
7006 if (err != NULL)
7007 return err;
7010 if (strncmp(refname, "refs/heads/", 11) == 0)
7011 refname += 11;
7012 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7013 refname += 18;
7014 if (strncmp(refname, "refs/remotes/", 13) == 0)
7015 refname += 13;
7017 refstr = got_ref_to_str(ref);
7018 if (refstr == NULL)
7019 return got_error_from_errno("got_ref_to_str");
7021 printf("%c %s: %s\n", marker, refname, refstr);
7022 free(refstr);
7023 return NULL;
7026 static const struct got_error *
7027 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
7029 const char *refname;
7031 if (worktree == NULL)
7032 return got_error(GOT_ERR_NOT_WORKTREE);
7034 refname = got_worktree_get_head_ref_name(worktree);
7036 if (strncmp(refname, "refs/heads/", 11) == 0)
7037 refname += 11;
7038 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7039 refname += 18;
7041 printf("%s\n", refname);
7043 return NULL;
7046 static const struct got_error *
7047 list_branches(struct got_repository *repo, struct got_worktree *worktree,
7048 int sort_by_time)
7050 static const struct got_error *err = NULL;
7051 struct got_reflist_head refs;
7052 struct got_reflist_entry *re;
7053 struct got_reference *temp_ref = NULL;
7054 int rebase_in_progress, histedit_in_progress;
7056 TAILQ_INIT(&refs);
7058 if (worktree) {
7059 err = got_worktree_rebase_in_progress(&rebase_in_progress,
7060 worktree);
7061 if (err)
7062 return err;
7064 err = got_worktree_histedit_in_progress(&histedit_in_progress,
7065 worktree);
7066 if (err)
7067 return err;
7069 if (rebase_in_progress || histedit_in_progress) {
7070 err = got_ref_open(&temp_ref, repo,
7071 got_worktree_get_head_ref_name(worktree), 0);
7072 if (err)
7073 return err;
7074 list_branch(repo, worktree, temp_ref);
7075 got_ref_close(temp_ref);
7079 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7080 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7081 repo);
7082 if (err)
7083 return err;
7085 TAILQ_FOREACH(re, &refs, entry)
7086 list_branch(repo, worktree, re->ref);
7088 got_ref_list_free(&refs);
7090 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7091 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7092 repo);
7093 if (err)
7094 return err;
7096 TAILQ_FOREACH(re, &refs, entry)
7097 list_branch(repo, worktree, re->ref);
7099 got_ref_list_free(&refs);
7101 return NULL;
7104 static const struct got_error *
7105 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7106 const char *branch_name)
7108 const struct got_error *err = NULL;
7109 struct got_reference *ref = NULL;
7110 char *refname, *remote_refname = NULL;
7112 if (strncmp(branch_name, "refs/", 5) == 0)
7113 branch_name += 5;
7114 if (strncmp(branch_name, "heads/", 6) == 0)
7115 branch_name += 6;
7116 else if (strncmp(branch_name, "remotes/", 8) == 0)
7117 branch_name += 8;
7119 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7120 return got_error_from_errno("asprintf");
7122 if (asprintf(&remote_refname, "refs/remotes/%s",
7123 branch_name) == -1) {
7124 err = got_error_from_errno("asprintf");
7125 goto done;
7128 err = got_ref_open(&ref, repo, refname, 0);
7129 if (err) {
7130 const struct got_error *err2;
7131 if (err->code != GOT_ERR_NOT_REF)
7132 goto done;
7134 * Keep 'err' intact such that if neither branch exists
7135 * we report "refs/heads" rather than "refs/remotes" in
7136 * our error message.
7138 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7139 if (err2)
7140 goto done;
7141 err = NULL;
7144 if (worktree &&
7145 strcmp(got_worktree_get_head_ref_name(worktree),
7146 got_ref_get_name(ref)) == 0) {
7147 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7148 "will not delete this work tree's current branch");
7149 goto done;
7152 err = delete_ref(repo, ref);
7153 done:
7154 if (ref)
7155 got_ref_close(ref);
7156 free(refname);
7157 free(remote_refname);
7158 return err;
7161 static const struct got_error *
7162 add_branch(struct got_repository *repo, const char *branch_name,
7163 struct got_object_id *base_commit_id)
7165 const struct got_error *err = NULL;
7166 struct got_reference *ref = NULL;
7167 char *refname = NULL;
7170 * Don't let the user create a branch name with a leading '-'.
7171 * While technically a valid reference name, this case is usually
7172 * an unintended typo.
7174 if (branch_name[0] == '-')
7175 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7177 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7178 branch_name += 11;
7180 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7181 err = got_error_from_errno("asprintf");
7182 goto done;
7185 err = got_ref_open(&ref, repo, refname, 0);
7186 if (err == NULL) {
7187 err = got_error(GOT_ERR_BRANCH_EXISTS);
7188 goto done;
7189 } else if (err->code != GOT_ERR_NOT_REF)
7190 goto done;
7192 err = got_ref_alloc(&ref, refname, base_commit_id);
7193 if (err)
7194 goto done;
7196 err = got_ref_write(ref, repo);
7197 done:
7198 if (ref)
7199 got_ref_close(ref);
7200 free(refname);
7201 return err;
7204 static const struct got_error *
7205 cmd_branch(int argc, char *argv[])
7207 const struct got_error *error = NULL;
7208 struct got_repository *repo = NULL;
7209 struct got_worktree *worktree = NULL;
7210 char *cwd = NULL, *repo_path = NULL;
7211 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7212 const char *delref = NULL, *commit_id_arg = NULL;
7213 struct got_reference *ref = NULL;
7214 struct got_pathlist_head paths;
7215 struct got_object_id *commit_id = NULL;
7216 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7217 int *pack_fds = NULL;
7219 TAILQ_INIT(&paths);
7221 #ifndef PROFILE
7222 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7223 "sendfd unveil", NULL) == -1)
7224 err(1, "pledge");
7225 #endif
7227 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7228 switch (ch) {
7229 case 'c':
7230 commit_id_arg = optarg;
7231 break;
7232 case 'd':
7233 delref = optarg;
7234 break;
7235 case 'l':
7236 do_list = 1;
7237 break;
7238 case 'n':
7239 do_update = 0;
7240 break;
7241 case 'r':
7242 repo_path = realpath(optarg, NULL);
7243 if (repo_path == NULL)
7244 return got_error_from_errno2("realpath",
7245 optarg);
7246 got_path_strip_trailing_slashes(repo_path);
7247 break;
7248 case 't':
7249 sort_by_time = 1;
7250 break;
7251 default:
7252 usage_branch();
7253 /* NOTREACHED */
7257 if (do_list && delref)
7258 option_conflict('l', 'd');
7259 if (sort_by_time && !do_list)
7260 errx(1, "-t option requires -l option");
7262 argc -= optind;
7263 argv += optind;
7265 if (!do_list && !delref && argc == 0)
7266 do_show = 1;
7268 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7269 errx(1, "-c option can only be used when creating a branch");
7271 if (do_list || delref) {
7272 if (argc > 0)
7273 usage_branch();
7274 } else if (!do_show && argc != 1)
7275 usage_branch();
7277 cwd = getcwd(NULL, 0);
7278 if (cwd == NULL) {
7279 error = got_error_from_errno("getcwd");
7280 goto done;
7283 error = got_repo_pack_fds_open(&pack_fds);
7284 if (error != NULL)
7285 goto done;
7287 if (repo_path == NULL) {
7288 error = got_worktree_open(&worktree, cwd,
7289 GOT_WORKTREE_GOT_DIR);
7290 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7291 goto done;
7292 else
7293 error = NULL;
7294 if (worktree) {
7295 repo_path =
7296 strdup(got_worktree_get_repo_path(worktree));
7297 if (repo_path == NULL)
7298 error = got_error_from_errno("strdup");
7299 if (error)
7300 goto done;
7301 } else {
7302 repo_path = strdup(cwd);
7303 if (repo_path == NULL) {
7304 error = got_error_from_errno("strdup");
7305 goto done;
7310 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7311 if (error != NULL)
7312 goto done;
7314 #ifndef PROFILE
7315 if (do_list || do_show) {
7316 /* Remove "cpath" promise. */
7317 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7318 NULL) == -1)
7319 err(1, "pledge");
7321 #endif
7323 error = apply_unveil(got_repo_get_path(repo), do_list,
7324 worktree ? got_worktree_get_root_path(worktree) : NULL);
7325 if (error)
7326 goto done;
7328 if (do_show)
7329 error = show_current_branch(repo, worktree);
7330 else if (do_list)
7331 error = list_branches(repo, worktree, sort_by_time);
7332 else if (delref)
7333 error = delete_branch(repo, worktree, delref);
7334 else {
7335 struct got_reflist_head refs;
7336 TAILQ_INIT(&refs);
7337 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7338 NULL);
7339 if (error)
7340 goto done;
7341 if (commit_id_arg == NULL)
7342 commit_id_arg = worktree ?
7343 got_worktree_get_head_ref_name(worktree) :
7344 GOT_REF_HEAD;
7345 else {
7346 error = got_keyword_to_idstr(&keyword_idstr,
7347 commit_id_arg, repo, worktree);
7348 if (error != NULL)
7349 goto done;
7350 if (keyword_idstr != NULL)
7351 commit_id_arg = keyword_idstr;
7353 error = got_repo_match_object_id(&commit_id, NULL,
7354 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7355 got_ref_list_free(&refs);
7356 if (error)
7357 goto done;
7358 error = add_branch(repo, argv[0], commit_id);
7359 if (error)
7360 goto done;
7361 if (worktree && do_update) {
7362 struct got_update_progress_arg upa;
7363 char *branch_refname = NULL;
7365 error = got_object_id_str(&commit_id_str, commit_id);
7366 if (error)
7367 goto done;
7368 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7369 worktree);
7370 if (error)
7371 goto done;
7372 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7373 == -1) {
7374 error = got_error_from_errno("asprintf");
7375 goto done;
7377 error = got_ref_open(&ref, repo, branch_refname, 0);
7378 free(branch_refname);
7379 if (error)
7380 goto done;
7381 error = switch_head_ref(ref, commit_id, worktree,
7382 repo);
7383 if (error)
7384 goto done;
7385 error = got_worktree_set_base_commit_id(worktree, repo,
7386 commit_id);
7387 if (error)
7388 goto done;
7389 memset(&upa, 0, sizeof(upa));
7390 error = got_worktree_checkout_files(worktree, &paths,
7391 repo, update_progress, &upa, check_cancelled,
7392 NULL);
7393 if (error)
7394 goto done;
7395 if (upa.did_something) {
7396 printf("Updated to %s: %s\n",
7397 got_worktree_get_head_ref_name(worktree),
7398 commit_id_str);
7400 print_update_progress_stats(&upa);
7403 done:
7404 free(keyword_idstr);
7405 if (ref)
7406 got_ref_close(ref);
7407 if (repo) {
7408 const struct got_error *close_err = got_repo_close(repo);
7409 if (error == NULL)
7410 error = close_err;
7412 if (worktree)
7413 got_worktree_close(worktree);
7414 if (pack_fds) {
7415 const struct got_error *pack_err =
7416 got_repo_pack_fds_close(pack_fds);
7417 if (error == NULL)
7418 error = pack_err;
7420 free(cwd);
7421 free(repo_path);
7422 free(commit_id);
7423 free(commit_id_str);
7424 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7425 return error;
7429 __dead static void
7430 usage_tag(void)
7432 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7433 "[-r repository-path] [-s signer-id] name\n", getprogname());
7434 exit(1);
7437 #if 0
7438 static const struct got_error *
7439 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7441 const struct got_error *err = NULL;
7442 struct got_reflist_entry *re, *se, *new;
7443 struct got_object_id *re_id, *se_id;
7444 struct got_tag_object *re_tag, *se_tag;
7445 time_t re_time, se_time;
7447 STAILQ_FOREACH(re, tags, entry) {
7448 se = STAILQ_FIRST(sorted);
7449 if (se == NULL) {
7450 err = got_reflist_entry_dup(&new, re);
7451 if (err)
7452 return err;
7453 STAILQ_INSERT_HEAD(sorted, new, entry);
7454 continue;
7455 } else {
7456 err = got_ref_resolve(&re_id, repo, re->ref);
7457 if (err)
7458 break;
7459 err = got_object_open_as_tag(&re_tag, repo, re_id);
7460 free(re_id);
7461 if (err)
7462 break;
7463 re_time = got_object_tag_get_tagger_time(re_tag);
7464 got_object_tag_close(re_tag);
7467 while (se) {
7468 err = got_ref_resolve(&se_id, repo, re->ref);
7469 if (err)
7470 break;
7471 err = got_object_open_as_tag(&se_tag, repo, se_id);
7472 free(se_id);
7473 if (err)
7474 break;
7475 se_time = got_object_tag_get_tagger_time(se_tag);
7476 got_object_tag_close(se_tag);
7478 if (se_time > re_time) {
7479 err = got_reflist_entry_dup(&new, re);
7480 if (err)
7481 return err;
7482 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7483 break;
7485 se = STAILQ_NEXT(se, entry);
7486 continue;
7489 done:
7490 return err;
7492 #endif
7494 static const struct got_error *
7495 get_tag_refname(char **refname, const char *tag_name)
7497 const struct got_error *err;
7499 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7500 *refname = strdup(tag_name);
7501 if (*refname == NULL)
7502 return got_error_from_errno("strdup");
7503 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7504 err = got_error_from_errno("asprintf");
7505 *refname = NULL;
7506 return err;
7509 return NULL;
7512 static const struct got_error *
7513 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7514 const char *allowed_signers, const char *revoked_signers, int verbosity)
7516 static const struct got_error *err = NULL;
7517 struct got_reflist_head refs;
7518 struct got_reflist_entry *re;
7519 char *wanted_refname = NULL;
7520 int bad_sigs = 0;
7522 TAILQ_INIT(&refs);
7524 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7525 if (err)
7526 return err;
7528 if (tag_name) {
7529 struct got_reference *ref;
7530 err = get_tag_refname(&wanted_refname, tag_name);
7531 if (err)
7532 goto done;
7533 /* Wanted tag reference should exist. */
7534 err = got_ref_open(&ref, repo, wanted_refname, 0);
7535 if (err)
7536 goto done;
7537 got_ref_close(ref);
7540 TAILQ_FOREACH(re, &refs, entry) {
7541 const char *refname;
7542 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7543 char datebuf[26];
7544 const char *tagger, *ssh_sig = NULL;
7545 char *sig_msg = NULL;
7546 time_t tagger_time;
7547 struct got_object_id *id;
7548 struct got_tag_object *tag;
7549 struct got_commit_object *commit = NULL;
7551 refname = got_ref_get_name(re->ref);
7552 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7553 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7554 continue;
7555 refname += 10;
7556 refstr = got_ref_to_str(re->ref);
7557 if (refstr == NULL) {
7558 err = got_error_from_errno("got_ref_to_str");
7559 break;
7562 err = got_ref_resolve(&id, repo, re->ref);
7563 if (err)
7564 break;
7565 err = got_object_open_as_tag(&tag, repo, id);
7566 if (err) {
7567 if (err->code != GOT_ERR_OBJ_TYPE) {
7568 free(id);
7569 break;
7571 /* "lightweight" tag */
7572 err = got_object_open_as_commit(&commit, repo, id);
7573 if (err) {
7574 free(id);
7575 break;
7577 tagger = got_object_commit_get_committer(commit);
7578 tagger_time =
7579 got_object_commit_get_committer_time(commit);
7580 err = got_object_id_str(&id_str, id);
7581 free(id);
7582 if (err)
7583 break;
7584 } else {
7585 free(id);
7586 tagger = got_object_tag_get_tagger(tag);
7587 tagger_time = got_object_tag_get_tagger_time(tag);
7588 err = got_object_id_str(&id_str,
7589 got_object_tag_get_object_id(tag));
7590 if (err)
7591 break;
7594 if (tag && verify_tags) {
7595 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7596 got_object_tag_get_message(tag));
7597 if (ssh_sig && allowed_signers == NULL) {
7598 err = got_error_msg(
7599 GOT_ERR_VERIFY_TAG_SIGNATURE,
7600 "SSH signature verification requires "
7601 "setting allowed_signers in "
7602 "got.conf(5)");
7603 break;
7607 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7608 free(refstr);
7609 printf("from: %s\n", tagger);
7610 datestr = get_datestr(&tagger_time, datebuf);
7611 if (datestr)
7612 printf("date: %s UTC\n", datestr);
7613 if (commit)
7614 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7615 else {
7616 switch (got_object_tag_get_object_type(tag)) {
7617 case GOT_OBJ_TYPE_BLOB:
7618 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7619 id_str);
7620 break;
7621 case GOT_OBJ_TYPE_TREE:
7622 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7623 id_str);
7624 break;
7625 case GOT_OBJ_TYPE_COMMIT:
7626 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7627 id_str);
7628 break;
7629 case GOT_OBJ_TYPE_TAG:
7630 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7631 id_str);
7632 break;
7633 default:
7634 break;
7637 free(id_str);
7639 if (ssh_sig) {
7640 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7641 allowed_signers, revoked_signers, verbosity);
7642 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7643 bad_sigs = 1;
7644 else if (err)
7645 break;
7646 printf("signature: %s", sig_msg);
7647 free(sig_msg);
7648 sig_msg = NULL;
7651 if (commit) {
7652 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7653 if (err)
7654 break;
7655 got_object_commit_close(commit);
7656 } else {
7657 tagmsg0 = strdup(got_object_tag_get_message(tag));
7658 got_object_tag_close(tag);
7659 if (tagmsg0 == NULL) {
7660 err = got_error_from_errno("strdup");
7661 break;
7665 tagmsg = tagmsg0;
7666 do {
7667 line = strsep(&tagmsg, "\n");
7668 if (line)
7669 printf(" %s\n", line);
7670 } while (line);
7671 free(tagmsg0);
7673 done:
7674 got_ref_list_free(&refs);
7675 free(wanted_refname);
7677 if (err == NULL && bad_sigs)
7678 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7679 return err;
7682 static const struct got_error *
7683 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7684 const char *tag_name, const char *editor, const char *repo_path)
7686 const struct got_error *err = NULL;
7687 char *template = NULL, *initial_content = NULL;
7688 int initial_content_len;
7689 int fd = -1;
7691 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7692 err = got_error_from_errno("asprintf");
7693 goto done;
7696 initial_content_len = asprintf(&initial_content,
7697 "\n# tagging commit %s as %s\n",
7698 commit_id_str, tag_name);
7699 if (initial_content_len == -1) {
7700 err = got_error_from_errno("asprintf");
7701 goto done;
7704 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7705 if (err)
7706 goto done;
7708 if (write(fd, initial_content, initial_content_len) == -1) {
7709 err = got_error_from_errno2("write", *tagmsg_path);
7710 goto done;
7712 if (close(fd) == -1) {
7713 err = got_error_from_errno2("close", *tagmsg_path);
7714 goto done;
7716 fd = -1;
7718 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7719 initial_content_len, 1);
7720 done:
7721 free(initial_content);
7722 free(template);
7724 if (fd != -1 && close(fd) == -1 && err == NULL)
7725 err = got_error_from_errno2("close", *tagmsg_path);
7727 if (err) {
7728 free(*tagmsg);
7729 *tagmsg = NULL;
7731 return err;
7734 static const struct got_error *
7735 add_tag(struct got_repository *repo, const char *tagger,
7736 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7737 const char *signer_id, const char *editor, int verbosity)
7739 const struct got_error *err = NULL;
7740 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7741 char *label = NULL, *commit_id_str = NULL;
7742 struct got_reference *ref = NULL;
7743 char *refname = NULL, *tagmsg = NULL;
7744 char *tagmsg_path = NULL, *tag_id_str = NULL;
7745 int preserve_tagmsg = 0;
7746 struct got_reflist_head refs;
7748 TAILQ_INIT(&refs);
7751 * Don't let the user create a tag name with a leading '-'.
7752 * While technically a valid reference name, this case is usually
7753 * an unintended typo.
7755 if (tag_name[0] == '-')
7756 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7758 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7759 if (err)
7760 goto done;
7762 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7763 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7764 if (err)
7765 goto done;
7767 err = got_object_id_str(&commit_id_str, commit_id);
7768 if (err)
7769 goto done;
7771 err = get_tag_refname(&refname, tag_name);
7772 if (err)
7773 goto done;
7774 if (strncmp("refs/tags/", tag_name, 10) == 0)
7775 tag_name += 10;
7777 err = got_ref_open(&ref, repo, refname, 0);
7778 if (err == NULL) {
7779 err = got_error(GOT_ERR_TAG_EXISTS);
7780 goto done;
7781 } else if (err->code != GOT_ERR_NOT_REF)
7782 goto done;
7784 if (tagmsg_arg == NULL) {
7785 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7786 tag_name, editor, got_repo_get_path(repo));
7787 if (err) {
7788 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7789 tagmsg_path != NULL)
7790 preserve_tagmsg = 1;
7791 goto done;
7795 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7796 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7797 verbosity);
7798 if (err) {
7799 if (tagmsg_path)
7800 preserve_tagmsg = 1;
7801 goto done;
7804 err = got_ref_alloc(&ref, refname, tag_id);
7805 if (err) {
7806 if (tagmsg_path)
7807 preserve_tagmsg = 1;
7808 goto done;
7811 err = got_ref_write(ref, repo);
7812 if (err) {
7813 if (tagmsg_path)
7814 preserve_tagmsg = 1;
7815 goto done;
7818 err = got_object_id_str(&tag_id_str, tag_id);
7819 if (err) {
7820 if (tagmsg_path)
7821 preserve_tagmsg = 1;
7822 goto done;
7824 printf("Created tag %s\n", tag_id_str);
7825 done:
7826 if (preserve_tagmsg) {
7827 fprintf(stderr, "%s: tag message preserved in %s\n",
7828 getprogname(), tagmsg_path);
7829 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7830 err = got_error_from_errno2("unlink", tagmsg_path);
7831 free(tag_id_str);
7832 if (ref)
7833 got_ref_close(ref);
7834 free(commit_id);
7835 free(commit_id_str);
7836 free(refname);
7837 free(tagmsg);
7838 free(tagmsg_path);
7839 got_ref_list_free(&refs);
7840 return err;
7843 static const struct got_error *
7844 cmd_tag(int argc, char *argv[])
7846 const struct got_error *error = NULL;
7847 struct got_repository *repo = NULL;
7848 struct got_worktree *worktree = NULL;
7849 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7850 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7851 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7852 const char *signer_id = NULL;
7853 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7854 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7855 int *pack_fds = NULL;
7857 #ifndef PROFILE
7858 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7859 "sendfd unveil", NULL) == -1)
7860 err(1, "pledge");
7861 #endif
7863 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7864 switch (ch) {
7865 case 'c':
7866 commit_id_arg = optarg;
7867 break;
7868 case 'l':
7869 do_list = 1;
7870 break;
7871 case 'm':
7872 tagmsg = optarg;
7873 break;
7874 case 'r':
7875 repo_path = realpath(optarg, NULL);
7876 if (repo_path == NULL) {
7877 error = got_error_from_errno2("realpath",
7878 optarg);
7879 goto done;
7881 got_path_strip_trailing_slashes(repo_path);
7882 break;
7883 case 's':
7884 signer_id = optarg;
7885 break;
7886 case 'V':
7887 verify_tags = 1;
7888 break;
7889 case 'v':
7890 if (verbosity < 0)
7891 verbosity = 0;
7892 else if (verbosity < 3)
7893 verbosity++;
7894 break;
7895 default:
7896 usage_tag();
7897 /* NOTREACHED */
7901 argc -= optind;
7902 argv += optind;
7904 if (do_list || verify_tags) {
7905 if (commit_id_arg != NULL)
7906 errx(1,
7907 "-c option can only be used when creating a tag");
7908 if (tagmsg) {
7909 if (do_list)
7910 option_conflict('l', 'm');
7911 else
7912 option_conflict('V', 'm');
7914 if (signer_id) {
7915 if (do_list)
7916 option_conflict('l', 's');
7917 else
7918 option_conflict('V', 's');
7920 if (argc > 1)
7921 usage_tag();
7922 } else if (argc != 1)
7923 usage_tag();
7925 if (argc == 1)
7926 tag_name = argv[0];
7928 cwd = getcwd(NULL, 0);
7929 if (cwd == NULL) {
7930 error = got_error_from_errno("getcwd");
7931 goto done;
7934 error = got_repo_pack_fds_open(&pack_fds);
7935 if (error != NULL)
7936 goto done;
7938 if (repo_path == NULL) {
7939 error = got_worktree_open(&worktree, cwd,
7940 GOT_WORKTREE_GOT_DIR);
7941 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7942 goto done;
7943 else
7944 error = NULL;
7945 if (worktree) {
7946 repo_path =
7947 strdup(got_worktree_get_repo_path(worktree));
7948 if (repo_path == NULL)
7949 error = got_error_from_errno("strdup");
7950 if (error)
7951 goto done;
7952 } else {
7953 repo_path = strdup(cwd);
7954 if (repo_path == NULL) {
7955 error = got_error_from_errno("strdup");
7956 goto done;
7961 if (do_list || verify_tags) {
7962 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7963 if (error != NULL)
7964 goto done;
7965 error = get_allowed_signers(&allowed_signers, repo, worktree);
7966 if (error)
7967 goto done;
7968 error = get_revoked_signers(&revoked_signers, repo, worktree);
7969 if (error)
7970 goto done;
7971 if (worktree) {
7972 /* Release work tree lock. */
7973 got_worktree_close(worktree);
7974 worktree = NULL;
7978 * Remove "cpath" promise unless needed for signature tmpfile
7979 * creation.
7981 if (verify_tags)
7982 got_sigs_apply_unveil();
7983 else {
7984 #ifndef PROFILE
7985 if (pledge("stdio rpath wpath flock proc exec sendfd "
7986 "unveil", NULL) == -1)
7987 err(1, "pledge");
7988 #endif
7990 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7991 if (error)
7992 goto done;
7993 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7994 revoked_signers, verbosity);
7995 } else {
7996 error = get_gitconfig_path(&gitconfig_path);
7997 if (error)
7998 goto done;
7999 error = got_repo_open(&repo, repo_path, gitconfig_path,
8000 pack_fds);
8001 if (error != NULL)
8002 goto done;
8004 error = get_author(&tagger, repo, worktree);
8005 if (error)
8006 goto done;
8007 if (signer_id == NULL)
8008 signer_id = get_signer_id(repo, worktree);
8010 if (tagmsg == NULL) {
8011 error = get_editor(&editor);
8012 if (error)
8013 goto done;
8014 if (unveil(editor, "x") != 0) {
8015 error = got_error_from_errno2("unveil", editor);
8016 goto done;
8019 if (signer_id) {
8020 error = got_sigs_apply_unveil();
8021 if (error)
8022 goto done;
8024 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8025 if (error)
8026 goto done;
8028 if (commit_id_arg == NULL) {
8029 struct got_reference *head_ref;
8030 struct got_object_id *commit_id;
8031 error = got_ref_open(&head_ref, repo,
8032 worktree ? got_worktree_get_head_ref_name(worktree)
8033 : GOT_REF_HEAD, 0);
8034 if (error)
8035 goto done;
8036 error = got_ref_resolve(&commit_id, repo, head_ref);
8037 got_ref_close(head_ref);
8038 if (error)
8039 goto done;
8040 error = got_object_id_str(&commit_id_str, commit_id);
8041 free(commit_id);
8042 if (error)
8043 goto done;
8044 } else {
8045 error = got_keyword_to_idstr(&keyword_idstr,
8046 commit_id_arg, repo, worktree);
8047 if (error != NULL)
8048 goto done;
8049 commit_id_str = keyword_idstr;
8052 if (worktree) {
8053 /* Release work tree lock. */
8054 got_worktree_close(worktree);
8055 worktree = NULL;
8058 error = add_tag(repo, tagger, tag_name,
8059 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
8060 signer_id, editor, verbosity);
8062 done:
8063 if (repo) {
8064 const struct got_error *close_err = got_repo_close(repo);
8065 if (error == NULL)
8066 error = close_err;
8068 if (worktree)
8069 got_worktree_close(worktree);
8070 if (pack_fds) {
8071 const struct got_error *pack_err =
8072 got_repo_pack_fds_close(pack_fds);
8073 if (error == NULL)
8074 error = pack_err;
8076 free(cwd);
8077 free(editor);
8078 free(repo_path);
8079 free(gitconfig_path);
8080 free(commit_id_str);
8081 free(tagger);
8082 free(allowed_signers);
8083 free(revoked_signers);
8084 return error;
8087 __dead static void
8088 usage_add(void)
8090 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8091 exit(1);
8094 static const struct got_error *
8095 add_progress(void *arg, unsigned char status, const char *path)
8097 while (path[0] == '/')
8098 path++;
8099 printf("%c %s\n", status, path);
8100 return NULL;
8103 static const struct got_error *
8104 cmd_add(int argc, char *argv[])
8106 const struct got_error *error = NULL;
8107 struct got_repository *repo = NULL;
8108 struct got_worktree *worktree = NULL;
8109 char *cwd = NULL;
8110 struct got_pathlist_head paths;
8111 struct got_pathlist_entry *pe;
8112 int ch, can_recurse = 0, no_ignores = 0;
8113 int *pack_fds = NULL;
8115 TAILQ_INIT(&paths);
8117 #ifndef PROFILE
8118 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8119 NULL) == -1)
8120 err(1, "pledge");
8121 #endif
8123 while ((ch = getopt(argc, argv, "IR")) != -1) {
8124 switch (ch) {
8125 case 'I':
8126 no_ignores = 1;
8127 break;
8128 case 'R':
8129 can_recurse = 1;
8130 break;
8131 default:
8132 usage_add();
8133 /* NOTREACHED */
8137 argc -= optind;
8138 argv += optind;
8140 if (argc < 1)
8141 usage_add();
8143 cwd = getcwd(NULL, 0);
8144 if (cwd == NULL) {
8145 error = got_error_from_errno("getcwd");
8146 goto done;
8149 error = got_repo_pack_fds_open(&pack_fds);
8150 if (error != NULL)
8151 goto done;
8153 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8154 if (error) {
8155 if (error->code == GOT_ERR_NOT_WORKTREE)
8156 error = wrap_not_worktree_error(error, "add", cwd);
8157 goto done;
8160 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8161 NULL, pack_fds);
8162 if (error != NULL)
8163 goto done;
8165 error = apply_unveil(got_repo_get_path(repo), 1,
8166 got_worktree_get_root_path(worktree));
8167 if (error)
8168 goto done;
8170 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8171 if (error)
8172 goto done;
8174 if (!can_recurse) {
8175 char *ondisk_path;
8176 struct stat sb;
8177 TAILQ_FOREACH(pe, &paths, entry) {
8178 if (asprintf(&ondisk_path, "%s/%s",
8179 got_worktree_get_root_path(worktree),
8180 pe->path) == -1) {
8181 error = got_error_from_errno("asprintf");
8182 goto done;
8184 if (lstat(ondisk_path, &sb) == -1) {
8185 if (errno == ENOENT) {
8186 free(ondisk_path);
8187 continue;
8189 error = got_error_from_errno2("lstat",
8190 ondisk_path);
8191 free(ondisk_path);
8192 goto done;
8194 free(ondisk_path);
8195 if (S_ISDIR(sb.st_mode)) {
8196 error = got_error_msg(GOT_ERR_BAD_PATH,
8197 "adding directories requires -R option");
8198 goto done;
8203 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8204 NULL, repo, no_ignores);
8205 done:
8206 if (repo) {
8207 const struct got_error *close_err = got_repo_close(repo);
8208 if (error == NULL)
8209 error = close_err;
8211 if (worktree)
8212 got_worktree_close(worktree);
8213 if (pack_fds) {
8214 const struct got_error *pack_err =
8215 got_repo_pack_fds_close(pack_fds);
8216 if (error == NULL)
8217 error = pack_err;
8219 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8220 free(cwd);
8221 return error;
8224 __dead static void
8225 usage_remove(void)
8227 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8228 getprogname());
8229 exit(1);
8232 static const struct got_error *
8233 print_remove_status(void *arg, unsigned char status,
8234 unsigned char staged_status, const char *path)
8236 while (path[0] == '/')
8237 path++;
8238 if (status == GOT_STATUS_NONEXISTENT)
8239 return NULL;
8240 if (status == staged_status && (status == GOT_STATUS_DELETE))
8241 status = GOT_STATUS_NO_CHANGE;
8242 printf("%c%c %s\n", status, staged_status, path);
8243 return NULL;
8246 static const struct got_error *
8247 cmd_remove(int argc, char *argv[])
8249 const struct got_error *error = NULL;
8250 struct got_worktree *worktree = NULL;
8251 struct got_repository *repo = NULL;
8252 const char *status_codes = NULL;
8253 char *cwd = NULL;
8254 struct got_pathlist_head paths;
8255 struct got_pathlist_entry *pe;
8256 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8257 int ignore_missing_paths = 0;
8258 int *pack_fds = NULL;
8260 TAILQ_INIT(&paths);
8262 #ifndef PROFILE
8263 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8264 NULL) == -1)
8265 err(1, "pledge");
8266 #endif
8268 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8269 switch (ch) {
8270 case 'f':
8271 delete_local_mods = 1;
8272 ignore_missing_paths = 1;
8273 break;
8274 case 'k':
8275 keep_on_disk = 1;
8276 break;
8277 case 'R':
8278 can_recurse = 1;
8279 break;
8280 case 's':
8281 for (i = 0; optarg[i] != '\0'; i++) {
8282 switch (optarg[i]) {
8283 case GOT_STATUS_MODIFY:
8284 delete_local_mods = 1;
8285 break;
8286 case GOT_STATUS_MISSING:
8287 ignore_missing_paths = 1;
8288 break;
8289 default:
8290 errx(1, "invalid status code '%c'",
8291 optarg[i]);
8294 status_codes = optarg;
8295 break;
8296 default:
8297 usage_remove();
8298 /* NOTREACHED */
8302 argc -= optind;
8303 argv += optind;
8305 if (argc < 1)
8306 usage_remove();
8308 cwd = getcwd(NULL, 0);
8309 if (cwd == NULL) {
8310 error = got_error_from_errno("getcwd");
8311 goto done;
8314 error = got_repo_pack_fds_open(&pack_fds);
8315 if (error != NULL)
8316 goto done;
8318 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8319 if (error) {
8320 if (error->code == GOT_ERR_NOT_WORKTREE)
8321 error = wrap_not_worktree_error(error, "remove", cwd);
8322 goto done;
8325 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8326 NULL, pack_fds);
8327 if (error)
8328 goto done;
8330 error = apply_unveil(got_repo_get_path(repo), 1,
8331 got_worktree_get_root_path(worktree));
8332 if (error)
8333 goto done;
8335 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8336 if (error)
8337 goto done;
8339 if (!can_recurse) {
8340 char *ondisk_path;
8341 struct stat sb;
8342 TAILQ_FOREACH(pe, &paths, entry) {
8343 if (asprintf(&ondisk_path, "%s/%s",
8344 got_worktree_get_root_path(worktree),
8345 pe->path) == -1) {
8346 error = got_error_from_errno("asprintf");
8347 goto done;
8349 if (lstat(ondisk_path, &sb) == -1) {
8350 if (errno == ENOENT) {
8351 free(ondisk_path);
8352 continue;
8354 error = got_error_from_errno2("lstat",
8355 ondisk_path);
8356 free(ondisk_path);
8357 goto done;
8359 free(ondisk_path);
8360 if (S_ISDIR(sb.st_mode)) {
8361 error = got_error_msg(GOT_ERR_BAD_PATH,
8362 "removing directories requires -R option");
8363 goto done;
8368 error = got_worktree_schedule_delete(worktree, &paths,
8369 delete_local_mods, status_codes, print_remove_status, NULL,
8370 repo, keep_on_disk, ignore_missing_paths);
8371 done:
8372 if (repo) {
8373 const struct got_error *close_err = got_repo_close(repo);
8374 if (error == NULL)
8375 error = close_err;
8377 if (worktree)
8378 got_worktree_close(worktree);
8379 if (pack_fds) {
8380 const struct got_error *pack_err =
8381 got_repo_pack_fds_close(pack_fds);
8382 if (error == NULL)
8383 error = pack_err;
8385 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8386 free(cwd);
8387 return error;
8390 __dead static void
8391 usage_patch(void)
8393 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8394 "[patchfile]\n", getprogname());
8395 exit(1);
8398 static const struct got_error *
8399 patch_from_stdin(int *patchfd)
8401 const struct got_error *err = NULL;
8402 ssize_t r;
8403 char buf[BUFSIZ];
8404 sig_t sighup, sigint, sigquit;
8406 *patchfd = got_opentempfd();
8407 if (*patchfd == -1)
8408 return got_error_from_errno("got_opentempfd");
8410 sighup = signal(SIGHUP, SIG_DFL);
8411 sigint = signal(SIGINT, SIG_DFL);
8412 sigquit = signal(SIGQUIT, SIG_DFL);
8414 for (;;) {
8415 r = read(0, buf, sizeof(buf));
8416 if (r == -1) {
8417 err = got_error_from_errno("read");
8418 break;
8420 if (r == 0)
8421 break;
8422 if (write(*patchfd, buf, r) == -1) {
8423 err = got_error_from_errno("write");
8424 break;
8428 signal(SIGHUP, sighup);
8429 signal(SIGINT, sigint);
8430 signal(SIGQUIT, sigquit);
8432 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8433 err = got_error_from_errno("lseek");
8435 if (err != NULL) {
8436 close(*patchfd);
8437 *patchfd = -1;
8440 return err;
8443 struct got_patch_progress_arg {
8444 int did_something;
8445 int conflicts;
8446 int rejects;
8449 static const struct got_error *
8450 patch_progress(void *arg, const char *old, const char *new,
8451 unsigned char status, const struct got_error *error, int old_from,
8452 int old_lines, int new_from, int new_lines, int offset,
8453 int ws_mangled, const struct got_error *hunk_err)
8455 const char *path = new == NULL ? old : new;
8456 struct got_patch_progress_arg *a = arg;
8458 while (*path == '/')
8459 path++;
8461 if (status != GOT_STATUS_NO_CHANGE &&
8462 status != 0 /* per-hunk progress */) {
8463 printf("%c %s\n", status, path);
8464 a->did_something = 1;
8467 if (hunk_err == NULL) {
8468 if (status == GOT_STATUS_CANNOT_UPDATE)
8469 a->rejects++;
8470 else if (status == GOT_STATUS_CONFLICT)
8471 a->conflicts++;
8474 if (error != NULL)
8475 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8477 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8478 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8479 old_lines, new_from, new_lines);
8480 if (hunk_err != NULL)
8481 printf("%s\n", hunk_err->msg);
8482 else if (offset != 0)
8483 printf("applied with offset %d\n", offset);
8484 else
8485 printf("hunk contains mangled whitespace\n");
8488 return NULL;
8491 static void
8492 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8494 if (!ppa->did_something)
8495 return;
8497 if (ppa->conflicts > 0)
8498 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8500 if (ppa->rejects > 0) {
8501 printf("Files where patch failed to apply: %d\n",
8502 ppa->rejects);
8506 static const struct got_error *
8507 cmd_patch(int argc, char *argv[])
8509 const struct got_error *error = NULL, *close_error = NULL;
8510 struct got_worktree *worktree = NULL;
8511 struct got_repository *repo = NULL;
8512 struct got_reflist_head refs;
8513 struct got_object_id *commit_id = NULL;
8514 const char *commit_id_str = NULL;
8515 struct stat sb;
8516 const char *errstr;
8517 char *cwd = NULL, *keyword_idstr = NULL;
8518 int ch, nop = 0, strip = -1, reverse = 0;
8519 int patchfd;
8520 int *pack_fds = NULL;
8521 struct got_patch_progress_arg ppa;
8523 TAILQ_INIT(&refs);
8525 #ifndef PROFILE
8526 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8527 "unveil", NULL) == -1)
8528 err(1, "pledge");
8529 #endif
8531 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8532 switch (ch) {
8533 case 'c':
8534 commit_id_str = optarg;
8535 break;
8536 case 'n':
8537 nop = 1;
8538 break;
8539 case 'p':
8540 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8541 if (errstr != NULL)
8542 errx(1, "pathname strip count is %s: %s",
8543 errstr, optarg);
8544 break;
8545 case 'R':
8546 reverse = 1;
8547 break;
8548 default:
8549 usage_patch();
8550 /* NOTREACHED */
8554 argc -= optind;
8555 argv += optind;
8557 if (argc == 0) {
8558 error = patch_from_stdin(&patchfd);
8559 if (error)
8560 return error;
8561 } else if (argc == 1) {
8562 patchfd = open(argv[0], O_RDONLY);
8563 if (patchfd == -1)
8564 return got_error_from_errno2("open", argv[0]);
8565 if (fstat(patchfd, &sb) == -1) {
8566 error = got_error_from_errno2("fstat", argv[0]);
8567 goto done;
8569 if (!S_ISREG(sb.st_mode)) {
8570 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8571 goto done;
8573 } else
8574 usage_patch();
8576 if ((cwd = getcwd(NULL, 0)) == NULL) {
8577 error = got_error_from_errno("getcwd");
8578 goto done;
8581 error = got_repo_pack_fds_open(&pack_fds);
8582 if (error != NULL)
8583 goto done;
8585 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8586 if (error != NULL)
8587 goto done;
8589 const char *repo_path = got_worktree_get_repo_path(worktree);
8590 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8591 if (error != NULL)
8592 goto done;
8594 error = apply_unveil(got_repo_get_path(repo), 0,
8595 got_worktree_get_root_path(worktree));
8596 if (error != NULL)
8597 goto done;
8599 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8600 if (error)
8601 goto done;
8603 if (commit_id_str != NULL) {
8604 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8605 repo, worktree);
8606 if (error != NULL)
8607 goto done;
8609 error = got_repo_match_object_id(&commit_id, NULL,
8610 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8611 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8612 if (error)
8613 goto done;
8616 memset(&ppa, 0, sizeof(ppa));
8617 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8618 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8619 print_patch_progress_stats(&ppa);
8620 done:
8621 got_ref_list_free(&refs);
8622 free(keyword_idstr);
8623 free(commit_id);
8624 if (repo) {
8625 close_error = got_repo_close(repo);
8626 if (error == NULL)
8627 error = close_error;
8629 if (worktree != NULL) {
8630 close_error = got_worktree_close(worktree);
8631 if (error == NULL)
8632 error = close_error;
8634 if (pack_fds) {
8635 const struct got_error *pack_err =
8636 got_repo_pack_fds_close(pack_fds);
8637 if (error == NULL)
8638 error = pack_err;
8640 free(cwd);
8641 return error;
8644 __dead static void
8645 usage_revert(void)
8647 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8648 getprogname());
8649 exit(1);
8652 static const struct got_error *
8653 revert_progress(void *arg, unsigned char status, const char *path)
8655 if (status == GOT_STATUS_UNVERSIONED)
8656 return NULL;
8658 while (path[0] == '/')
8659 path++;
8660 printf("%c %s\n", status, path);
8661 return NULL;
8664 struct choose_patch_arg {
8665 FILE *patch_script_file;
8666 const char *action;
8669 static const struct got_error *
8670 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8671 int nchanges, const char *action)
8673 const struct got_error *err;
8674 char *line = NULL;
8675 size_t linesize = 0;
8676 ssize_t linelen;
8678 switch (status) {
8679 case GOT_STATUS_ADD:
8680 printf("A %s\n%s this addition? [y/n] ", path, action);
8681 break;
8682 case GOT_STATUS_DELETE:
8683 printf("D %s\n%s this deletion? [y/n] ", path, action);
8684 break;
8685 case GOT_STATUS_MODIFY:
8686 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8687 return got_error_from_errno("fseek");
8688 printf(GOT_COMMIT_SEP_STR);
8689 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8690 printf("%s", line);
8691 if (linelen == -1 && ferror(patch_file)) {
8692 err = got_error_from_errno("getline");
8693 free(line);
8694 return err;
8696 free(line);
8697 printf(GOT_COMMIT_SEP_STR);
8698 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8699 path, n, nchanges, action);
8700 break;
8701 default:
8702 return got_error_path(path, GOT_ERR_FILE_STATUS);
8705 fflush(stdout);
8706 return NULL;
8709 #define CHOOSE_PATCH_VALID_RESPONSES "ynq"
8711 static const struct got_error *
8712 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8713 FILE *patch_file, int n, int nchanges)
8715 const struct got_error *err = NULL;
8716 char *nl, *line = NULL;
8717 FILE *fp = stdin;
8718 size_t linesize = 0;
8719 ssize_t linelen;
8720 int interactive = 1;
8721 struct choose_patch_arg *a = arg;
8723 *choice = GOT_PATCH_CHOICE_NONE;
8725 if (a->patch_script_file) {
8726 interactive = 0;
8727 fp = a->patch_script_file;
8730 for (;;) {
8731 err = show_change(status, path, patch_file, n, nchanges,
8732 a->action);
8733 if (err)
8734 return err;
8736 linelen = getline(&line, &linesize, fp);
8737 if (linelen == -1) {
8738 free(line);
8739 if (ferror(fp))
8740 return got_error_from_errno("getline");
8741 if (feof(fp))
8742 return got_error(GOT_ERR_EOF);
8743 return NULL;
8746 nl = strchr(line, '\n');
8747 if (nl)
8748 *nl = '\0';
8749 if (strlen(line) != 1 ||
8750 !strchr(CHOOSE_PATCH_VALID_RESPONSES, line[0])) {
8751 printf("invalid response '%s'\n", line);
8752 if (interactive)
8753 continue;
8756 /* ADD and DELETE do not accept 'q' response currently. */
8757 if (status != GOT_STATUS_MODIFY && line[0] == 'q') {
8758 printf("invalid response '%s'\n", line);
8759 continue;
8762 break;
8765 switch (line[0]) {
8766 case 'y':
8767 *choice = GOT_PATCH_CHOICE_YES;
8768 break;
8769 case 'n':
8770 *choice = GOT_PATCH_CHOICE_NO;
8771 break;
8772 case 'q':
8773 if (status == GOT_STATUS_MODIFY)
8774 *choice = GOT_PATCH_CHOICE_QUIT;
8775 break;
8776 default:
8777 printf("invalid response '%s'\n", line);
8778 free(line);
8779 return NULL;
8782 if (!interactive)
8783 printf("%c\n", line[0]);
8785 free(line);
8786 return NULL;
8789 struct wt_commitable_path_arg {
8790 struct got_pathlist_head *commit_paths;
8791 int *has_changes;
8795 * Shortcut work tree status callback to determine if the set of paths scanned
8796 * has at least one versioned path that is being modified and, if not NULL, is
8797 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8798 * soon as a path is passed with a status that satisfies this criteria.
8800 static const struct got_error *
8801 worktree_has_commitable_path(void *arg, unsigned char status,
8802 unsigned char staged_status, const char *path,
8803 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8804 struct got_object_id *commit_id, int dirfd, const char *de_name)
8806 struct wt_commitable_path_arg *a = arg;
8808 if (status == staged_status && (status == GOT_STATUS_DELETE))
8809 status = GOT_STATUS_NO_CHANGE;
8811 if (!(status == GOT_STATUS_NO_CHANGE ||
8812 status == GOT_STATUS_UNVERSIONED) ||
8813 staged_status != GOT_STATUS_NO_CHANGE) {
8814 if (a->commit_paths != NULL) {
8815 struct got_pathlist_entry *pe;
8817 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8818 if (strncmp(path, pe->path,
8819 pe->path_len) == 0) {
8820 *a->has_changes = 1;
8821 break;
8824 } else
8825 *a->has_changes = 1;
8827 if (*a->has_changes)
8828 return got_error(GOT_ERR_FILE_MODIFIED);
8831 return NULL;
8835 * Check that the changeset of the commit identified by id is
8836 * comprised of at least one modified path that is being committed.
8838 static const struct got_error *
8839 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8840 struct got_object_id *id, struct got_worktree *worktree,
8841 struct got_repository *repo)
8843 const struct got_error *err;
8844 struct got_pathlist_head paths;
8845 struct got_commit_object *commit = NULL, *pcommit = NULL;
8846 struct got_tree_object *tree = NULL, *ptree = NULL;
8847 struct got_object_qid *pid;
8849 TAILQ_INIT(&paths);
8851 err = got_object_open_as_commit(&commit, repo, id);
8852 if (err)
8853 goto done;
8855 err = got_object_open_as_tree(&tree, repo,
8856 got_object_commit_get_tree_id(commit));
8857 if (err)
8858 goto done;
8860 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8861 if (pid != NULL) {
8862 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8863 if (err)
8864 goto done;
8866 err = got_object_open_as_tree(&ptree, repo,
8867 got_object_commit_get_tree_id(pcommit));
8868 if (err)
8869 goto done;
8872 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8873 got_diff_tree_collect_changed_paths, &paths, 0);
8874 if (err)
8875 goto done;
8877 err = got_worktree_status(worktree, &paths, repo, 0,
8878 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8879 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8881 * At least one changed path in the referenced commit is
8882 * modified in the work tree, that's all we need to know!
8884 err = NULL;
8887 done:
8888 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8889 if (commit)
8890 got_object_commit_close(commit);
8891 if (pcommit)
8892 got_object_commit_close(pcommit);
8893 if (tree)
8894 got_object_tree_close(tree);
8895 if (ptree)
8896 got_object_tree_close(ptree);
8897 return err;
8901 * Remove any "logmsg" reference comprised entirely of paths that have
8902 * been reverted in this work tree. If any path in the logmsg ref changeset
8903 * remains in a changed state in the worktree, do not remove the reference.
8905 static const struct got_error *
8906 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8908 const struct got_error *err;
8909 struct got_reflist_head refs;
8910 struct got_reflist_entry *re;
8911 struct got_commit_object *commit = NULL;
8912 struct got_object_id *commit_id = NULL;
8913 struct wt_commitable_path_arg wcpa;
8914 char *uuidstr = NULL;
8916 TAILQ_INIT(&refs);
8918 err = got_worktree_get_uuid(&uuidstr, worktree);
8919 if (err)
8920 goto done;
8922 err = got_ref_list(&refs, repo, "refs/got/worktree",
8923 got_ref_cmp_by_name, repo);
8924 if (err)
8925 goto done;
8927 TAILQ_FOREACH(re, &refs, entry) {
8928 const char *refname;
8929 int has_changes = 0;
8931 refname = got_ref_get_name(re->ref);
8933 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8934 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8935 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8936 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8937 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8938 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8939 else
8940 continue;
8942 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8943 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8944 else
8945 continue;
8947 err = got_repo_match_object_id(&commit_id, NULL, refname,
8948 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8949 if (err)
8950 goto done;
8952 err = got_object_open_as_commit(&commit, repo, commit_id);
8953 if (err)
8954 goto done;
8956 wcpa.commit_paths = NULL;
8957 wcpa.has_changes = &has_changes;
8959 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8960 worktree, repo);
8961 if (err)
8962 goto done;
8964 if (!has_changes) {
8965 err = got_ref_delete(re->ref, repo);
8966 if (err)
8967 goto done;
8970 got_object_commit_close(commit);
8971 commit = NULL;
8972 free(commit_id);
8973 commit_id = NULL;
8976 done:
8977 free(uuidstr);
8978 free(commit_id);
8979 got_ref_list_free(&refs);
8980 if (commit)
8981 got_object_commit_close(commit);
8982 return err;
8985 static const struct got_error *
8986 cmd_revert(int argc, char *argv[])
8988 const struct got_error *error = NULL;
8989 struct got_worktree *worktree = NULL;
8990 struct got_repository *repo = NULL;
8991 char *cwd = NULL, *path = NULL;
8992 struct got_pathlist_head paths;
8993 struct got_pathlist_entry *pe;
8994 int ch, can_recurse = 0, pflag = 0;
8995 FILE *patch_script_file = NULL;
8996 const char *patch_script_path = NULL;
8997 struct choose_patch_arg cpa;
8998 int *pack_fds = NULL;
9000 TAILQ_INIT(&paths);
9002 #ifndef PROFILE
9003 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9004 "unveil", NULL) == -1)
9005 err(1, "pledge");
9006 #endif
9008 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
9009 switch (ch) {
9010 case 'F':
9011 patch_script_path = optarg;
9012 break;
9013 case 'p':
9014 pflag = 1;
9015 break;
9016 case 'R':
9017 can_recurse = 1;
9018 break;
9019 default:
9020 usage_revert();
9021 /* NOTREACHED */
9025 argc -= optind;
9026 argv += optind;
9028 if (argc < 1)
9029 usage_revert();
9030 if (patch_script_path && !pflag)
9031 errx(1, "-F option can only be used together with -p option");
9033 cwd = getcwd(NULL, 0);
9034 if (cwd == NULL) {
9035 error = got_error_from_errno("getcwd");
9036 goto done;
9039 error = got_repo_pack_fds_open(&pack_fds);
9040 if (error != NULL)
9041 goto done;
9043 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9044 if (error) {
9045 if (error->code == GOT_ERR_NOT_WORKTREE)
9046 error = wrap_not_worktree_error(error, "revert", cwd);
9047 goto done;
9050 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9051 NULL, pack_fds);
9052 if (error != NULL)
9053 goto done;
9055 if (patch_script_path) {
9056 patch_script_file = fopen(patch_script_path, "re");
9057 if (patch_script_file == NULL) {
9058 error = got_error_from_errno2("fopen",
9059 patch_script_path);
9060 goto done;
9065 * XXX "c" perm needed on repo dir to delete merge references.
9067 error = apply_unveil(got_repo_get_path(repo), 0,
9068 got_worktree_get_root_path(worktree));
9069 if (error)
9070 goto done;
9072 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9073 if (error)
9074 goto done;
9076 if (!can_recurse) {
9077 char *ondisk_path;
9078 struct stat sb;
9079 TAILQ_FOREACH(pe, &paths, entry) {
9080 if (asprintf(&ondisk_path, "%s/%s",
9081 got_worktree_get_root_path(worktree),
9082 pe->path) == -1) {
9083 error = got_error_from_errno("asprintf");
9084 goto done;
9086 if (lstat(ondisk_path, &sb) == -1) {
9087 if (errno == ENOENT) {
9088 free(ondisk_path);
9089 continue;
9091 error = got_error_from_errno2("lstat",
9092 ondisk_path);
9093 free(ondisk_path);
9094 goto done;
9096 free(ondisk_path);
9097 if (S_ISDIR(sb.st_mode)) {
9098 error = got_error_msg(GOT_ERR_BAD_PATH,
9099 "reverting directories requires -R option");
9100 goto done;
9105 cpa.patch_script_file = patch_script_file;
9106 cpa.action = "revert";
9107 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
9108 pflag ? choose_patch : NULL, &cpa, repo);
9110 error = rm_logmsg_ref(worktree, repo);
9111 done:
9112 if (patch_script_file && fclose(patch_script_file) == EOF &&
9113 error == NULL)
9114 error = got_error_from_errno2("fclose", patch_script_path);
9115 if (repo) {
9116 const struct got_error *close_err = got_repo_close(repo);
9117 if (error == NULL)
9118 error = close_err;
9120 if (worktree)
9121 got_worktree_close(worktree);
9122 if (pack_fds) {
9123 const struct got_error *pack_err =
9124 got_repo_pack_fds_close(pack_fds);
9125 if (error == NULL)
9126 error = pack_err;
9128 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9129 free(path);
9130 free(cwd);
9131 return error;
9134 __dead static void
9135 usage_commit(void)
9137 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9138 "[-m message] [path ...]\n", getprogname());
9139 exit(1);
9142 struct collect_commit_logmsg_arg {
9143 const char *cmdline_log;
9144 const char *prepared_log;
9145 const char *merged_log;
9146 int non_interactive;
9147 const char *editor;
9148 const char *worktree_path;
9149 const char *branch_name;
9150 const char *repo_path;
9151 char *logmsg_path;
9155 static const struct got_error *
9156 read_prepared_logmsg(char **logmsg, const char *path)
9158 const struct got_error *err = NULL;
9159 FILE *f = NULL;
9160 struct stat sb;
9161 size_t r;
9163 *logmsg = NULL;
9164 memset(&sb, 0, sizeof(sb));
9166 f = fopen(path, "re");
9167 if (f == NULL)
9168 return got_error_from_errno2("fopen", path);
9170 if (fstat(fileno(f), &sb) == -1) {
9171 err = got_error_from_errno2("fstat", path);
9172 goto done;
9174 if (sb.st_size == 0) {
9175 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9176 goto done;
9179 *logmsg = malloc(sb.st_size + 1);
9180 if (*logmsg == NULL) {
9181 err = got_error_from_errno("malloc");
9182 goto done;
9185 r = fread(*logmsg, 1, sb.st_size, f);
9186 if (r != sb.st_size) {
9187 if (ferror(f))
9188 err = got_error_from_errno2("fread", path);
9189 else
9190 err = got_error(GOT_ERR_IO);
9191 goto done;
9193 (*logmsg)[sb.st_size] = '\0';
9194 done:
9195 if (fclose(f) == EOF && err == NULL)
9196 err = got_error_from_errno2("fclose", path);
9197 if (err) {
9198 free(*logmsg);
9199 *logmsg = NULL;
9201 return err;
9204 static const struct got_error *
9205 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9206 const char *diff_path, char **logmsg, void *arg)
9208 char *initial_content = NULL;
9209 struct got_pathlist_entry *pe;
9210 const struct got_error *err = NULL;
9211 char *template = NULL;
9212 char *prepared_msg = NULL, *merged_msg = NULL;
9213 struct collect_commit_logmsg_arg *a = arg;
9214 int initial_content_len;
9215 int fd = -1;
9216 size_t len;
9218 /* if a message was specified on the command line, just use it */
9219 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9220 len = strlen(a->cmdline_log) + 1;
9221 *logmsg = malloc(len + 1);
9222 if (*logmsg == NULL)
9223 return got_error_from_errno("malloc");
9224 strlcpy(*logmsg, a->cmdline_log, len);
9225 return NULL;
9226 } else if (a->prepared_log != NULL && a->non_interactive)
9227 return read_prepared_logmsg(logmsg, a->prepared_log);
9229 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9230 return got_error_from_errno("asprintf");
9232 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9233 if (err)
9234 goto done;
9236 if (a->prepared_log) {
9237 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9238 if (err)
9239 goto done;
9240 } else if (a->merged_log) {
9241 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9242 if (err)
9243 goto done;
9246 initial_content_len = asprintf(&initial_content,
9247 "%s%s\n# changes to be committed on branch %s:\n",
9248 prepared_msg ? prepared_msg : "",
9249 merged_msg ? merged_msg : "", a->branch_name);
9250 if (initial_content_len == -1) {
9251 err = got_error_from_errno("asprintf");
9252 goto done;
9255 if (write(fd, initial_content, initial_content_len) == -1) {
9256 err = got_error_from_errno2("write", a->logmsg_path);
9257 goto done;
9260 TAILQ_FOREACH(pe, commitable_paths, entry) {
9261 struct got_commitable *ct = pe->data;
9262 dprintf(fd, "# %c %s\n",
9263 got_commitable_get_status(ct),
9264 got_commitable_get_path(ct));
9267 if (diff_path) {
9268 dprintf(fd, "# detailed changes can be viewed in %s\n",
9269 diff_path);
9272 if (close(fd) == -1) {
9273 err = got_error_from_errno2("close", a->logmsg_path);
9274 goto done;
9276 fd = -1;
9278 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9279 initial_content_len, a->prepared_log ? 0 : 1);
9280 done:
9281 free(initial_content);
9282 free(template);
9283 free(prepared_msg);
9284 free(merged_msg);
9286 if (fd != -1 && close(fd) == -1 && err == NULL)
9287 err = got_error_from_errno2("close", a->logmsg_path);
9288 if (err) {
9289 free(*logmsg);
9290 *logmsg = NULL;
9292 return err;
9295 static const struct got_error *
9296 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9297 const char *type, int has_content)
9299 const struct got_error *err = NULL;
9300 char *logmsg = NULL;
9302 err = got_object_commit_get_logmsg(&logmsg, commit);
9303 if (err)
9304 return err;
9306 if (fprintf(f, "%s# log message of %s commit %s:%s",
9307 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9308 err = got_ferror(f, GOT_ERR_IO);
9310 free(logmsg);
9311 return err;
9315 * Lookup "logmsg" references of backed-out and cherrypicked commits
9316 * belonging to the current work tree. If found, and the worktree has
9317 * at least one modified file that was changed in the referenced commit,
9318 * add its log message to a new temporary file at *logmsg_path.
9319 * Add all refs found to matched_refs to be scheduled for removal on
9320 * successful commit.
9322 static const struct got_error *
9323 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9324 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9325 struct got_repository *repo)
9327 const struct got_error *err;
9328 struct got_commit_object *commit = NULL;
9329 struct got_object_id *id = NULL;
9330 struct got_reflist_head refs;
9331 struct got_reflist_entry *re, *re_match;
9332 FILE *f = NULL;
9333 char *uuidstr = NULL;
9334 int added_logmsg = 0;
9336 TAILQ_INIT(&refs);
9338 *logmsg_path = NULL;
9340 err = got_worktree_get_uuid(&uuidstr, worktree);
9341 if (err)
9342 goto done;
9344 err = got_ref_list(&refs, repo, "refs/got/worktree",
9345 got_ref_cmp_by_name, repo);
9346 if (err)
9347 goto done;
9349 TAILQ_FOREACH(re, &refs, entry) {
9350 const char *refname, *type;
9351 struct wt_commitable_path_arg wcpa;
9352 int add_logmsg = 0;
9354 refname = got_ref_get_name(re->ref);
9356 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9357 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9358 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9359 type = "cherrypicked";
9360 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9361 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9362 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9363 type = "backed-out";
9364 } else
9365 continue;
9367 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9368 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9369 else
9370 continue;
9372 err = got_repo_match_object_id(&id, NULL, refname,
9373 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9374 if (err)
9375 goto done;
9377 err = got_object_open_as_commit(&commit, repo, id);
9378 if (err)
9379 goto done;
9381 wcpa.commit_paths = paths;
9382 wcpa.has_changes = &add_logmsg;
9384 err = commit_path_changed_in_worktree(&wcpa, id,
9385 worktree, repo);
9386 if (err)
9387 goto done;
9389 if (add_logmsg) {
9390 if (f == NULL) {
9391 err = got_opentemp_named(logmsg_path, &f,
9392 "got-commit-logmsg", "");
9393 if (err)
9394 goto done;
9396 err = cat_logmsg(f, commit, refname, type,
9397 added_logmsg);
9398 if (err)
9399 goto done;
9400 if (!added_logmsg)
9401 ++added_logmsg;
9403 err = got_reflist_entry_dup(&re_match, re);
9404 if (err)
9405 goto done;
9406 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9409 got_object_commit_close(commit);
9410 commit = NULL;
9411 free(id);
9412 id = NULL;
9415 done:
9416 free(id);
9417 free(uuidstr);
9418 got_ref_list_free(&refs);
9419 if (commit)
9420 got_object_commit_close(commit);
9421 if (f && fclose(f) == EOF && err == NULL)
9422 err = got_error_from_errno("fclose");
9423 if (!added_logmsg) {
9424 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9425 err = got_error_from_errno2("unlink", *logmsg_path);
9426 *logmsg_path = NULL;
9428 return err;
9431 static const struct got_error *
9432 cmd_commit(int argc, char *argv[])
9434 const struct got_error *error = NULL;
9435 struct got_worktree *worktree = NULL;
9436 struct got_repository *repo = NULL;
9437 char *cwd = NULL, *id_str = NULL;
9438 struct got_object_id *id = NULL;
9439 const char *logmsg = NULL;
9440 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9441 struct collect_commit_logmsg_arg cl_arg;
9442 const char *author = NULL;
9443 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9444 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9445 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9446 int show_diff = 1, commit_conflicts = 0;
9447 struct got_pathlist_head paths;
9448 struct got_reflist_head refs;
9449 struct got_reflist_entry *re;
9450 int *pack_fds = NULL;
9452 TAILQ_INIT(&refs);
9453 TAILQ_INIT(&paths);
9454 cl_arg.logmsg_path = NULL;
9456 #ifndef PROFILE
9457 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9458 "unveil", NULL) == -1)
9459 err(1, "pledge");
9460 #endif
9462 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9463 switch (ch) {
9464 case 'A':
9465 author = optarg;
9466 error = valid_author(author);
9467 if (error)
9468 return error;
9469 break;
9470 case 'C':
9471 commit_conflicts = 1;
9472 break;
9473 case 'F':
9474 if (logmsg != NULL)
9475 option_conflict('F', 'm');
9476 prepared_logmsg = realpath(optarg, NULL);
9477 if (prepared_logmsg == NULL)
9478 return got_error_from_errno2("realpath",
9479 optarg);
9480 break;
9481 case 'm':
9482 if (prepared_logmsg)
9483 option_conflict('m', 'F');
9484 logmsg = optarg;
9485 break;
9486 case 'N':
9487 non_interactive = 1;
9488 break;
9489 case 'n':
9490 show_diff = 0;
9491 break;
9492 case 'S':
9493 allow_bad_symlinks = 1;
9494 break;
9495 default:
9496 usage_commit();
9497 /* NOTREACHED */
9501 argc -= optind;
9502 argv += optind;
9504 cwd = getcwd(NULL, 0);
9505 if (cwd == NULL) {
9506 error = got_error_from_errno("getcwd");
9507 goto done;
9510 error = got_repo_pack_fds_open(&pack_fds);
9511 if (error != NULL)
9512 goto done;
9514 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9515 if (error) {
9516 if (error->code == GOT_ERR_NOT_WORKTREE)
9517 error = wrap_not_worktree_error(error, "commit", cwd);
9518 goto done;
9521 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9522 if (error)
9523 goto done;
9524 if (rebase_in_progress) {
9525 error = got_error(GOT_ERR_REBASING);
9526 goto done;
9529 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9530 worktree);
9531 if (error)
9532 goto done;
9534 error = get_gitconfig_path(&gitconfig_path);
9535 if (error)
9536 goto done;
9537 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9538 gitconfig_path, pack_fds);
9539 if (error != NULL)
9540 goto done;
9542 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9543 if (error)
9544 goto done;
9545 if (merge_in_progress) {
9546 error = got_error(GOT_ERR_MERGE_BUSY);
9547 goto done;
9550 error = get_author(&committer, repo, worktree);
9551 if (error)
9552 goto done;
9554 if (author == NULL)
9555 author = committer;
9557 if (logmsg == NULL || strlen(logmsg) == 0) {
9558 error = get_editor(&editor);
9559 if (error)
9560 goto done;
9561 if (unveil(editor, "x") != 0) {
9562 error = got_error_from_errno2("unveil", editor);
9563 goto done;
9566 if (prepared_logmsg) {
9567 if (unveil(prepared_logmsg, "r") != 0) {
9568 error = got_error_from_errno2("unveil",
9569 prepared_logmsg);
9570 goto done;
9574 error = apply_unveil(got_repo_get_path(repo), 0,
9575 got_worktree_get_root_path(worktree));
9576 if (error)
9577 goto done;
9579 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9580 if (error)
9581 goto done;
9583 if (prepared_logmsg == NULL) {
9584 error = lookup_logmsg_ref(&merged_logmsg,
9585 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9586 if (error)
9587 goto done;
9590 cl_arg.editor = editor;
9591 cl_arg.cmdline_log = logmsg;
9592 cl_arg.prepared_log = prepared_logmsg;
9593 cl_arg.merged_log = merged_logmsg;
9594 cl_arg.non_interactive = non_interactive;
9595 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9596 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9597 if (!histedit_in_progress) {
9598 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9599 error = got_error(GOT_ERR_COMMIT_BRANCH);
9600 goto done;
9602 cl_arg.branch_name += 11;
9604 cl_arg.repo_path = got_repo_get_path(repo);
9605 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9606 allow_bad_symlinks, show_diff, commit_conflicts,
9607 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9608 if (error) {
9609 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9610 cl_arg.logmsg_path != NULL)
9611 preserve_logmsg = 1;
9612 goto done;
9615 error = got_object_id_str(&id_str, id);
9616 if (error)
9617 goto done;
9618 printf("Created commit %s\n", id_str);
9620 TAILQ_FOREACH(re, &refs, entry) {
9621 error = got_ref_delete(re->ref, repo);
9622 if (error)
9623 goto done;
9626 done:
9627 if (preserve_logmsg) {
9628 fprintf(stderr, "%s: log message preserved in %s\n",
9629 getprogname(), cl_arg.logmsg_path);
9630 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9631 error == NULL)
9632 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9633 free(cl_arg.logmsg_path);
9634 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9635 error = got_error_from_errno2("unlink", merged_logmsg);
9636 free(merged_logmsg);
9637 if (repo) {
9638 const struct got_error *close_err = got_repo_close(repo);
9639 if (error == NULL)
9640 error = close_err;
9642 if (worktree)
9643 got_worktree_close(worktree);
9644 if (pack_fds) {
9645 const struct got_error *pack_err =
9646 got_repo_pack_fds_close(pack_fds);
9647 if (error == NULL)
9648 error = pack_err;
9650 got_ref_list_free(&refs);
9651 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9652 free(cwd);
9653 free(id_str);
9654 free(gitconfig_path);
9655 free(editor);
9656 free(committer);
9657 free(prepared_logmsg);
9658 return error;
9661 __dead static void
9662 usage_send(void)
9664 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9665 "[-r repository-path] [-t tag] [remote-repository]\n",
9666 getprogname());
9667 exit(1);
9670 static void
9671 print_load_info(int print_colored, int print_found, int print_trees,
9672 int ncolored, int nfound, int ntrees)
9674 if (print_colored) {
9675 printf("%d commit%s colored", ncolored,
9676 ncolored == 1 ? "" : "s");
9678 if (print_found) {
9679 printf("%s%d object%s found",
9680 ncolored > 0 ? "; " : "",
9681 nfound, nfound == 1 ? "" : "s");
9683 if (print_trees) {
9684 printf("; %d tree%s scanned", ntrees,
9685 ntrees == 1 ? "" : "s");
9689 struct got_send_progress_arg {
9690 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9691 int verbosity;
9692 int last_ncolored;
9693 int last_nfound;
9694 int last_ntrees;
9695 int loading_done;
9696 int last_ncommits;
9697 int last_nobj_total;
9698 int last_p_deltify;
9699 int last_p_written;
9700 int last_p_sent;
9701 int printed_something;
9702 int sent_something;
9703 struct got_pathlist_head *delete_branches;
9706 static const struct got_error *
9707 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9708 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9709 int nobj_written, off_t bytes_sent, const char *refname,
9710 const char *errmsg, int success)
9712 struct got_send_progress_arg *a = arg;
9713 char scaled_packsize[FMT_SCALED_STRSIZE];
9714 char scaled_sent[FMT_SCALED_STRSIZE];
9715 int p_deltify = 0, p_written = 0, p_sent = 0;
9716 int print_colored = 0, print_found = 0, print_trees = 0;
9717 int print_searching = 0, print_total = 0;
9718 int print_deltify = 0, print_written = 0, print_sent = 0;
9720 if (a->verbosity < 0)
9721 return NULL;
9723 if (refname) {
9724 const char *status = success ? "accepted" : "rejected";
9726 if (success) {
9727 struct got_pathlist_entry *pe;
9728 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9729 const char *branchname = pe->path;
9730 if (got_path_cmp(branchname, refname,
9731 strlen(branchname), strlen(refname)) == 0) {
9732 status = "deleted";
9733 a->sent_something = 1;
9734 break;
9739 if (a->printed_something)
9740 putchar('\n');
9741 printf("Server has %s %s", status, refname);
9742 if (errmsg)
9743 printf(": %s", errmsg);
9744 a->printed_something = 1;
9745 return NULL;
9748 if (a->last_ncolored != ncolored) {
9749 print_colored = 1;
9750 a->last_ncolored = ncolored;
9753 if (a->last_nfound != nfound) {
9754 print_colored = 1;
9755 print_found = 1;
9756 a->last_nfound = nfound;
9759 if (a->last_ntrees != ntrees) {
9760 print_colored = 1;
9761 print_found = 1;
9762 print_trees = 1;
9763 a->last_ntrees = ntrees;
9766 if ((print_colored || print_found || print_trees) &&
9767 !a->loading_done) {
9768 printf("\r");
9769 print_load_info(print_colored, print_found, print_trees,
9770 ncolored, nfound, ntrees);
9771 a->printed_something = 1;
9772 fflush(stdout);
9773 return NULL;
9774 } else if (!a->loading_done) {
9775 printf("\r");
9776 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9777 printf("\n");
9778 a->loading_done = 1;
9781 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9782 return got_error_from_errno("fmt_scaled");
9783 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9784 return got_error_from_errno("fmt_scaled");
9786 if (a->last_ncommits != ncommits) {
9787 print_searching = 1;
9788 a->last_ncommits = ncommits;
9791 if (a->last_nobj_total != nobj_total) {
9792 print_searching = 1;
9793 print_total = 1;
9794 a->last_nobj_total = nobj_total;
9797 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9798 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9799 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9800 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9801 return got_error(GOT_ERR_NO_SPACE);
9804 if (nobj_deltify > 0 || nobj_written > 0) {
9805 if (nobj_deltify > 0) {
9806 p_deltify = (nobj_deltify * 100) / nobj_total;
9807 if (p_deltify != a->last_p_deltify) {
9808 a->last_p_deltify = p_deltify;
9809 print_searching = 1;
9810 print_total = 1;
9811 print_deltify = 1;
9814 if (nobj_written > 0) {
9815 p_written = (nobj_written * 100) / nobj_total;
9816 if (p_written != a->last_p_written) {
9817 a->last_p_written = p_written;
9818 print_searching = 1;
9819 print_total = 1;
9820 print_deltify = 1;
9821 print_written = 1;
9826 if (bytes_sent > 0) {
9827 p_sent = (bytes_sent * 100) / packfile_size;
9828 if (p_sent != a->last_p_sent) {
9829 a->last_p_sent = p_sent;
9830 print_searching = 1;
9831 print_total = 1;
9832 print_deltify = 1;
9833 print_written = 1;
9834 print_sent = 1;
9836 a->sent_something = 1;
9839 if (print_searching || print_total || print_deltify || print_written ||
9840 print_sent)
9841 printf("\r");
9842 if (print_searching)
9843 printf("packing %d reference%s", ncommits,
9844 ncommits == 1 ? "" : "s");
9845 if (print_total)
9846 printf("; %d object%s", nobj_total,
9847 nobj_total == 1 ? "" : "s");
9848 if (print_deltify)
9849 printf("; deltify: %d%%", p_deltify);
9850 if (print_sent)
9851 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9852 scaled_packsize, p_sent);
9853 else if (print_written)
9854 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9855 scaled_packsize, p_written);
9856 if (print_searching || print_total || print_deltify ||
9857 print_written || print_sent) {
9858 a->printed_something = 1;
9859 fflush(stdout);
9861 return NULL;
9864 static const struct got_error *
9865 cmd_send(int argc, char *argv[])
9867 const struct got_error *error = NULL;
9868 char *cwd = NULL, *repo_path = NULL;
9869 const char *remote_name;
9870 char *proto = NULL, *host = NULL, *port = NULL;
9871 char *repo_name = NULL, *server_path = NULL;
9872 const struct got_remote_repo *remotes;
9873 struct got_remote_repo *remote = NULL;
9874 int nremotes, nbranches = 0, ndelete_branches = 0;
9875 struct got_repository *repo = NULL;
9876 struct got_worktree *worktree = NULL;
9877 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9878 struct got_pathlist_head branches;
9879 struct got_pathlist_head tags;
9880 struct got_reflist_head all_branches;
9881 struct got_reflist_head all_tags;
9882 struct got_pathlist_head delete_args;
9883 struct got_pathlist_head delete_branches;
9884 struct got_reflist_entry *re;
9885 struct got_pathlist_entry *pe;
9886 int i, ch, sendfd = -1, sendstatus;
9887 pid_t sendpid = -1;
9888 struct got_send_progress_arg spa;
9889 int verbosity = 0, overwrite_refs = 0;
9890 int send_all_branches = 0, send_all_tags = 0;
9891 struct got_reference *ref = NULL;
9892 int *pack_fds = NULL;
9894 TAILQ_INIT(&branches);
9895 TAILQ_INIT(&tags);
9896 TAILQ_INIT(&all_branches);
9897 TAILQ_INIT(&all_tags);
9898 TAILQ_INIT(&delete_args);
9899 TAILQ_INIT(&delete_branches);
9901 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9902 switch (ch) {
9903 case 'a':
9904 send_all_branches = 1;
9905 break;
9906 case 'b':
9907 error = got_pathlist_append(&branches, optarg, NULL);
9908 if (error)
9909 return error;
9910 nbranches++;
9911 break;
9912 case 'd':
9913 error = got_pathlist_append(&delete_args, optarg, NULL);
9914 if (error)
9915 return error;
9916 break;
9917 case 'f':
9918 overwrite_refs = 1;
9919 break;
9920 case 'q':
9921 verbosity = -1;
9922 break;
9923 case 'r':
9924 repo_path = realpath(optarg, NULL);
9925 if (repo_path == NULL)
9926 return got_error_from_errno2("realpath",
9927 optarg);
9928 got_path_strip_trailing_slashes(repo_path);
9929 break;
9930 case 'T':
9931 send_all_tags = 1;
9932 break;
9933 case 't':
9934 error = got_pathlist_append(&tags, optarg, NULL);
9935 if (error)
9936 return error;
9937 break;
9938 case 'v':
9939 if (verbosity < 0)
9940 verbosity = 0;
9941 else if (verbosity < 3)
9942 verbosity++;
9943 break;
9944 default:
9945 usage_send();
9946 /* NOTREACHED */
9949 argc -= optind;
9950 argv += optind;
9952 if (send_all_branches && !TAILQ_EMPTY(&branches))
9953 option_conflict('a', 'b');
9954 if (send_all_tags && !TAILQ_EMPTY(&tags))
9955 option_conflict('T', 't');
9958 if (argc == 0)
9959 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9960 else if (argc == 1)
9961 remote_name = argv[0];
9962 else
9963 usage_send();
9965 cwd = getcwd(NULL, 0);
9966 if (cwd == NULL) {
9967 error = got_error_from_errno("getcwd");
9968 goto done;
9971 error = got_repo_pack_fds_open(&pack_fds);
9972 if (error != NULL)
9973 goto done;
9975 if (repo_path == NULL) {
9976 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9977 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9978 goto done;
9979 else
9980 error = NULL;
9981 if (worktree) {
9982 repo_path =
9983 strdup(got_worktree_get_repo_path(worktree));
9984 if (repo_path == NULL)
9985 error = got_error_from_errno("strdup");
9986 if (error)
9987 goto done;
9988 } else {
9989 repo_path = strdup(cwd);
9990 if (repo_path == NULL) {
9991 error = got_error_from_errno("strdup");
9992 goto done;
9997 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9998 if (error)
9999 goto done;
10001 if (worktree) {
10002 worktree_conf = got_worktree_get_gotconfig(worktree);
10003 if (worktree_conf) {
10004 got_gotconfig_get_remotes(&nremotes, &remotes,
10005 worktree_conf);
10006 for (i = 0; i < nremotes; i++) {
10007 if (strcmp(remotes[i].name, remote_name) == 0) {
10008 error = got_repo_remote_repo_dup(&remote,
10009 &remotes[i]);
10010 if (error)
10011 goto done;
10012 break;
10017 if (remote == NULL) {
10018 repo_conf = got_repo_get_gotconfig(repo);
10019 if (repo_conf) {
10020 got_gotconfig_get_remotes(&nremotes, &remotes,
10021 repo_conf);
10022 for (i = 0; i < nremotes; i++) {
10023 if (strcmp(remotes[i].name, remote_name) == 0) {
10024 error = got_repo_remote_repo_dup(&remote,
10025 &remotes[i]);
10026 if (error)
10027 goto done;
10028 break;
10033 if (remote == NULL) {
10034 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
10035 for (i = 0; i < nremotes; i++) {
10036 if (strcmp(remotes[i].name, remote_name) == 0) {
10037 error = got_repo_remote_repo_dup(&remote,
10038 &remotes[i]);
10039 if (error)
10040 goto done;
10041 break;
10045 if (remote == NULL) {
10046 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
10047 goto done;
10050 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
10051 &repo_name, remote->send_url);
10052 if (error)
10053 goto done;
10055 if (strcmp(proto, "git") == 0) {
10056 #ifndef PROFILE
10057 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
10058 "sendfd dns inet unveil", NULL) == -1)
10059 err(1, "pledge");
10060 #endif
10061 } else if (strcmp(proto, "git+ssh") == 0 ||
10062 strcmp(proto, "ssh") == 0) {
10063 #ifndef PROFILE
10064 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
10065 "sendfd unveil", NULL) == -1)
10066 err(1, "pledge");
10067 #endif
10068 } else if (strcmp(proto, "http") == 0 ||
10069 strcmp(proto, "git+http") == 0) {
10070 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
10071 goto done;
10072 } else {
10073 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
10074 goto done;
10077 error = got_dial_apply_unveil(proto);
10078 if (error)
10079 goto done;
10081 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
10082 if (error)
10083 goto done;
10085 if (send_all_branches) {
10086 error = got_ref_list(&all_branches, repo, "refs/heads",
10087 got_ref_cmp_by_name, NULL);
10088 if (error)
10089 goto done;
10090 TAILQ_FOREACH(re, &all_branches, entry) {
10091 const char *branchname = got_ref_get_name(re->ref);
10092 error = got_pathlist_append(&branches,
10093 branchname, NULL);
10094 if (error)
10095 goto done;
10096 nbranches++;
10098 } else if (nbranches == 0) {
10099 for (i = 0; i < remote->nsend_branches; i++) {
10100 error = got_pathlist_append(&branches,
10101 remote->send_branches[i], NULL);
10102 if (error)
10103 goto done;
10107 if (send_all_tags) {
10108 error = got_ref_list(&all_tags, repo, "refs/tags",
10109 got_ref_cmp_by_name, NULL);
10110 if (error)
10111 goto done;
10112 TAILQ_FOREACH(re, &all_tags, entry) {
10113 const char *tagname = got_ref_get_name(re->ref);
10114 error = got_pathlist_append(&tags,
10115 tagname, NULL);
10116 if (error)
10117 goto done;
10122 * To prevent accidents only branches in refs/heads/ can be deleted
10123 * with 'got send -d'.
10124 * Deleting anything else requires local repository access or Git.
10126 TAILQ_FOREACH(pe, &delete_args, entry) {
10127 const char *branchname = pe->path;
10128 char *s;
10129 struct got_pathlist_entry *new;
10130 if (strncmp(branchname, "refs/heads/", 11) == 0) {
10131 s = strdup(branchname);
10132 if (s == NULL) {
10133 error = got_error_from_errno("strdup");
10134 goto done;
10136 } else {
10137 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10138 error = got_error_from_errno("asprintf");
10139 goto done;
10142 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10143 if (error || new == NULL /* duplicate */)
10144 free(s);
10145 if (error)
10146 goto done;
10147 ndelete_branches++;
10150 if (nbranches == 0 && ndelete_branches == 0) {
10151 struct got_reference *head_ref;
10152 if (worktree)
10153 error = got_ref_open(&head_ref, repo,
10154 got_worktree_get_head_ref_name(worktree), 0);
10155 else
10156 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10157 if (error)
10158 goto done;
10159 if (got_ref_is_symbolic(head_ref)) {
10160 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10161 got_ref_close(head_ref);
10162 if (error)
10163 goto done;
10164 } else
10165 ref = head_ref;
10166 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10167 NULL);
10168 if (error)
10169 goto done;
10170 nbranches++;
10173 if (worktree) {
10174 /* Release work tree lock. */
10175 got_worktree_close(worktree);
10176 worktree = NULL;
10179 if (verbosity >= 0) {
10180 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10181 remote->name, proto, host,
10182 port ? ":" : "", port ? port : "",
10183 *server_path == '/' ? "" : "/", server_path);
10186 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10187 server_path, verbosity);
10188 if (error)
10189 goto done;
10191 memset(&spa, 0, sizeof(spa));
10192 spa.last_scaled_packsize[0] = '\0';
10193 spa.last_p_deltify = -1;
10194 spa.last_p_written = -1;
10195 spa.verbosity = verbosity;
10196 spa.delete_branches = &delete_branches;
10197 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10198 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10199 check_cancelled, NULL);
10200 if (spa.printed_something)
10201 putchar('\n');
10202 if (error)
10203 goto done;
10204 if (!spa.sent_something && verbosity >= 0)
10205 printf("Already up-to-date\n");
10206 done:
10207 if (sendpid > 0) {
10208 if (kill(sendpid, SIGTERM) == -1)
10209 error = got_error_from_errno("kill");
10210 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10211 error = got_error_from_errno("waitpid");
10213 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10214 error = got_error_from_errno("close");
10215 if (repo) {
10216 const struct got_error *close_err = got_repo_close(repo);
10217 if (error == NULL)
10218 error = close_err;
10220 if (worktree)
10221 got_worktree_close(worktree);
10222 if (pack_fds) {
10223 const struct got_error *pack_err =
10224 got_repo_pack_fds_close(pack_fds);
10225 if (error == NULL)
10226 error = pack_err;
10228 if (ref)
10229 got_ref_close(ref);
10230 got_repo_free_remote_repo_data(remote);
10231 free(remote);
10232 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10233 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10234 got_ref_list_free(&all_branches);
10235 got_ref_list_free(&all_tags);
10236 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10237 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10238 free(cwd);
10239 free(repo_path);
10240 free(proto);
10241 free(host);
10242 free(port);
10243 free(server_path);
10244 free(repo_name);
10245 return error;
10249 * Print and if delete is set delete all ref_prefix references.
10250 * If wanted_ref is not NULL, only print or delete this reference.
10252 static const struct got_error *
10253 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10254 const char *wanted_ref, int delete, struct got_worktree *worktree,
10255 struct got_repository *repo)
10257 const struct got_error *err;
10258 struct got_pathlist_head paths;
10259 struct got_reflist_head refs;
10260 struct got_reflist_entry *re;
10261 struct got_reflist_object_id_map *refs_idmap = NULL;
10262 struct got_commit_object *commit = NULL;
10263 struct got_object_id *id = NULL;
10264 const char *header_prefix;
10265 char *uuidstr = NULL;
10266 int found = 0;
10268 TAILQ_INIT(&refs);
10269 TAILQ_INIT(&paths);
10271 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10272 if (err)
10273 goto done;
10275 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10276 if (err)
10277 goto done;
10279 if (worktree != NULL) {
10280 err = got_worktree_get_uuid(&uuidstr, worktree);
10281 if (err)
10282 goto done;
10285 if (wanted_ref) {
10286 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10287 wanted_ref += 11;
10290 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10291 header_prefix = "backout";
10292 else
10293 header_prefix = "cherrypick";
10295 TAILQ_FOREACH(re, &refs, entry) {
10296 const char *refname, *wt;
10298 refname = got_ref_get_name(re->ref);
10300 err = check_cancelled(NULL);
10301 if (err)
10302 goto done;
10304 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10305 refname += prefix_len + 1; /* skip '-' delimiter */
10306 else
10307 continue;
10309 wt = refname;
10311 if (worktree == NULL || strncmp(refname, uuidstr,
10312 GOT_WORKTREE_UUID_STRLEN) == 0)
10313 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10314 else
10315 continue;
10317 err = got_repo_match_object_id(&id, NULL, refname,
10318 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10319 if (err)
10320 goto done;
10322 err = got_object_open_as_commit(&commit, repo, id);
10323 if (err)
10324 goto done;
10326 if (wanted_ref)
10327 found = strncmp(wanted_ref, refname,
10328 strlen(wanted_ref)) == 0;
10329 if (wanted_ref && !found) {
10330 struct got_reflist_head *ci_refs;
10332 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10333 id);
10335 if (ci_refs) {
10336 char *refs_str = NULL;
10337 char const *r = NULL;
10339 err = build_refs_str(&refs_str, ci_refs, id,
10340 repo, 1);
10341 if (err)
10342 goto done;
10344 r = refs_str;
10345 while (r) {
10346 if (strncmp(r, wanted_ref,
10347 strlen(wanted_ref)) == 0) {
10348 found = 1;
10349 break;
10351 r = strchr(r, ' ');
10352 if (r)
10353 ++r;
10355 free(refs_str);
10359 if (wanted_ref == NULL || found) {
10360 if (delete) {
10361 err = got_ref_delete(re->ref, repo);
10362 if (err)
10363 goto done;
10364 printf("Deleted: ");
10365 err = print_commit_oneline(commit, id, repo,
10366 refs_idmap);
10367 } else {
10369 * Print paths modified by commit to help
10370 * associate commits with worktree changes.
10372 err = get_changed_paths(&paths, commit,
10373 repo, NULL);
10374 if (err)
10375 goto done;
10377 err = print_commit(commit, id, repo, NULL,
10378 &paths, NULL, 0, 0, refs_idmap, NULL,
10379 header_prefix);
10380 got_pathlist_free(&paths,
10381 GOT_PATHLIST_FREE_ALL);
10383 if (worktree == NULL)
10384 printf("work tree: %.*s\n\n",
10385 GOT_WORKTREE_UUID_STRLEN, wt);
10387 if (err || found)
10388 goto done;
10391 got_object_commit_close(commit);
10392 commit = NULL;
10393 free(id);
10394 id = NULL;
10397 if (wanted_ref != NULL && !found)
10398 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10400 done:
10401 free(id);
10402 free(uuidstr);
10403 got_ref_list_free(&refs);
10404 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10405 if (refs_idmap)
10406 got_reflist_object_id_map_free(refs_idmap);
10407 if (commit)
10408 got_object_commit_close(commit);
10409 return err;
10413 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10414 * identified by id for log messages to prepopulate the editor on commit.
10416 static const struct got_error *
10417 logmsg_ref(struct got_object_id *id, const char *prefix,
10418 struct got_worktree *worktree, struct got_repository *repo)
10420 const struct got_error *err = NULL;
10421 char *idstr, *ref = NULL, *refname = NULL;
10422 int histedit_in_progress;
10423 int rebase_in_progress, merge_in_progress;
10426 * Silently refuse to create merge reference if any histedit, merge,
10427 * or rebase operation is in progress.
10429 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10430 worktree);
10431 if (err)
10432 return err;
10433 if (histedit_in_progress)
10434 return NULL;
10436 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10437 if (err)
10438 return err;
10439 if (rebase_in_progress)
10440 return NULL;
10442 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10443 repo);
10444 if (err)
10445 return err;
10446 if (merge_in_progress)
10447 return NULL;
10449 err = got_object_id_str(&idstr, id);
10450 if (err)
10451 return err;
10453 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10454 if (err)
10455 goto done;
10457 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10458 err = got_error_from_errno("asprintf");
10459 goto done;
10462 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10463 -1, repo);
10464 done:
10465 free(ref);
10466 free(idstr);
10467 free(refname);
10468 return err;
10471 __dead static void
10472 usage_cherrypick(void)
10474 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10475 getprogname());
10476 exit(1);
10479 static const struct got_error *
10480 cmd_cherrypick(int argc, char *argv[])
10482 const struct got_error *error = NULL;
10483 struct got_worktree *worktree = NULL;
10484 struct got_repository *repo = NULL;
10485 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10486 struct got_object_id *commit_id = NULL;
10487 struct got_commit_object *commit = NULL;
10488 struct got_object_qid *pid;
10489 int ch, list_refs = 0, remove_refs = 0;
10490 struct got_update_progress_arg upa;
10491 int *pack_fds = NULL;
10493 #ifndef PROFILE
10494 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10495 "unveil", NULL) == -1)
10496 err(1, "pledge");
10497 #endif
10499 while ((ch = getopt(argc, argv, "lX")) != -1) {
10500 switch (ch) {
10501 case 'l':
10502 list_refs = 1;
10503 break;
10504 case 'X':
10505 remove_refs = 1;
10506 break;
10507 default:
10508 usage_cherrypick();
10509 /* NOTREACHED */
10513 argc -= optind;
10514 argv += optind;
10516 if (list_refs || remove_refs) {
10517 if (argc != 0 && argc != 1)
10518 usage_cherrypick();
10519 } else if (argc != 1)
10520 usage_cherrypick();
10521 if (list_refs && remove_refs)
10522 option_conflict('l', 'X');
10524 cwd = getcwd(NULL, 0);
10525 if (cwd == NULL) {
10526 error = got_error_from_errno("getcwd");
10527 goto done;
10530 error = got_repo_pack_fds_open(&pack_fds);
10531 if (error != NULL)
10532 goto done;
10534 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10535 if (error) {
10536 if (list_refs || remove_refs) {
10537 if (error->code != GOT_ERR_NOT_WORKTREE)
10538 goto done;
10539 } else {
10540 if (error->code == GOT_ERR_NOT_WORKTREE)
10541 error = wrap_not_worktree_error(error,
10542 "cherrypick", cwd);
10543 goto done;
10547 error = got_repo_open(&repo,
10548 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10549 NULL, pack_fds);
10550 if (error != NULL)
10551 goto done;
10553 error = apply_unveil(got_repo_get_path(repo), 0,
10554 worktree ? got_worktree_get_root_path(worktree) : NULL);
10555 if (error)
10556 goto done;
10558 if (list_refs || remove_refs) {
10559 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10560 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10561 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10562 goto done;
10565 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10566 if (error != NULL)
10567 goto done;
10569 error = got_repo_match_object_id(&commit_id, NULL,
10570 keyword_idstr != NULL ? keyword_idstr : argv[0],
10571 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10572 if (error)
10573 goto done;
10574 error = got_object_id_str(&commit_id_str, commit_id);
10575 if (error)
10576 goto done;
10578 error = got_object_open_as_commit(&commit, repo, commit_id);
10579 if (error)
10580 goto done;
10581 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10582 memset(&upa, 0, sizeof(upa));
10583 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10584 commit_id, repo, update_progress, &upa, check_cancelled,
10585 NULL);
10586 if (error != NULL)
10587 goto done;
10589 if (upa.did_something) {
10590 error = logmsg_ref(commit_id,
10591 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10592 if (error)
10593 goto done;
10594 printf("Merged commit %s\n", commit_id_str);
10596 print_merge_progress_stats(&upa);
10597 done:
10598 free(cwd);
10599 free(keyword_idstr);
10600 if (commit)
10601 got_object_commit_close(commit);
10602 free(commit_id_str);
10603 if (worktree)
10604 got_worktree_close(worktree);
10605 if (repo) {
10606 const struct got_error *close_err = got_repo_close(repo);
10607 if (error == NULL)
10608 error = close_err;
10610 if (pack_fds) {
10611 const struct got_error *pack_err =
10612 got_repo_pack_fds_close(pack_fds);
10613 if (error == NULL)
10614 error = pack_err;
10617 return error;
10620 __dead static void
10621 usage_backout(void)
10623 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10624 exit(1);
10627 static const struct got_error *
10628 cmd_backout(int argc, char *argv[])
10630 const struct got_error *error = NULL;
10631 struct got_worktree *worktree = NULL;
10632 struct got_repository *repo = NULL;
10633 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10634 struct got_object_id *commit_id = NULL;
10635 struct got_commit_object *commit = NULL;
10636 struct got_object_qid *pid;
10637 int ch, list_refs = 0, remove_refs = 0;
10638 struct got_update_progress_arg upa;
10639 int *pack_fds = NULL;
10641 #ifndef PROFILE
10642 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10643 "unveil", NULL) == -1)
10644 err(1, "pledge");
10645 #endif
10647 while ((ch = getopt(argc, argv, "lX")) != -1) {
10648 switch (ch) {
10649 case 'l':
10650 list_refs = 1;
10651 break;
10652 case 'X':
10653 remove_refs = 1;
10654 break;
10655 default:
10656 usage_backout();
10657 /* NOTREACHED */
10661 argc -= optind;
10662 argv += optind;
10664 if (list_refs || remove_refs) {
10665 if (argc != 0 && argc != 1)
10666 usage_backout();
10667 } else if (argc != 1)
10668 usage_backout();
10669 if (list_refs && remove_refs)
10670 option_conflict('l', 'X');
10672 cwd = getcwd(NULL, 0);
10673 if (cwd == NULL) {
10674 error = got_error_from_errno("getcwd");
10675 goto done;
10678 error = got_repo_pack_fds_open(&pack_fds);
10679 if (error != NULL)
10680 goto done;
10682 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10683 if (error) {
10684 if (list_refs || remove_refs) {
10685 if (error->code != GOT_ERR_NOT_WORKTREE)
10686 goto done;
10687 } else {
10688 if (error->code == GOT_ERR_NOT_WORKTREE)
10689 error = wrap_not_worktree_error(error,
10690 "backout", cwd);
10691 goto done;
10695 error = got_repo_open(&repo,
10696 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10697 NULL, pack_fds);
10698 if (error != NULL)
10699 goto done;
10701 error = apply_unveil(got_repo_get_path(repo), 0,
10702 worktree ? got_worktree_get_root_path(worktree) : NULL);
10703 if (error)
10704 goto done;
10706 if (list_refs || remove_refs) {
10707 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10708 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10709 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10710 goto done;
10713 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10714 if (error != NULL)
10715 goto done;
10717 error = got_repo_match_object_id(&commit_id, NULL,
10718 keyword_idstr != NULL ? keyword_idstr : argv[0],
10719 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10720 if (error)
10721 goto done;
10722 error = got_object_id_str(&commit_id_str, commit_id);
10723 if (error)
10724 goto done;
10726 error = got_object_open_as_commit(&commit, repo, commit_id);
10727 if (error)
10728 goto done;
10729 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10730 if (pid == NULL) {
10731 error = got_error(GOT_ERR_ROOT_COMMIT);
10732 goto done;
10735 memset(&upa, 0, sizeof(upa));
10736 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10737 repo, update_progress, &upa, check_cancelled, NULL);
10738 if (error != NULL)
10739 goto done;
10741 if (upa.did_something) {
10742 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10743 worktree, repo);
10744 if (error)
10745 goto done;
10746 printf("Backed out commit %s\n", commit_id_str);
10748 print_merge_progress_stats(&upa);
10749 done:
10750 free(cwd);
10751 free(keyword_idstr);
10752 if (commit)
10753 got_object_commit_close(commit);
10754 free(commit_id_str);
10755 if (worktree)
10756 got_worktree_close(worktree);
10757 if (repo) {
10758 const struct got_error *close_err = got_repo_close(repo);
10759 if (error == NULL)
10760 error = close_err;
10762 if (pack_fds) {
10763 const struct got_error *pack_err =
10764 got_repo_pack_fds_close(pack_fds);
10765 if (error == NULL)
10766 error = pack_err;
10768 return error;
10771 __dead static void
10772 usage_rebase(void)
10774 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10775 exit(1);
10778 static void
10779 trim_logmsg(char *logmsg, int limit)
10781 char *nl;
10782 size_t len;
10784 len = strlen(logmsg);
10785 if (len > limit)
10786 len = limit;
10787 logmsg[len] = '\0';
10788 nl = strchr(logmsg, '\n');
10789 if (nl)
10790 *nl = '\0';
10793 static const struct got_error *
10794 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10796 const struct got_error *err;
10797 char *logmsg0 = NULL;
10798 const char *s;
10800 err = got_object_commit_get_logmsg(&logmsg0, commit);
10801 if (err)
10802 return err;
10804 s = logmsg0;
10805 while (isspace((unsigned char)s[0]))
10806 s++;
10808 *logmsg = strdup(s);
10809 if (*logmsg == NULL) {
10810 err = got_error_from_errno("strdup");
10811 goto done;
10814 trim_logmsg(*logmsg, limit);
10815 done:
10816 free(logmsg0);
10817 return err;
10820 static const struct got_error *
10821 show_rebase_merge_conflict(struct got_object_id *id,
10822 struct got_repository *repo)
10824 const struct got_error *err;
10825 struct got_commit_object *commit = NULL;
10826 char *id_str = NULL, *logmsg = NULL;
10828 err = got_object_open_as_commit(&commit, repo, id);
10829 if (err)
10830 return err;
10832 err = got_object_id_str(&id_str, id);
10833 if (err)
10834 goto done;
10836 id_str[12] = '\0';
10838 err = get_short_logmsg(&logmsg, 42, commit);
10839 if (err)
10840 goto done;
10842 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10843 done:
10844 free(id_str);
10845 got_object_commit_close(commit);
10846 free(logmsg);
10847 return err;
10850 static const struct got_error *
10851 show_rebase_progress(struct got_commit_object *commit,
10852 struct got_object_id *old_id, struct got_object_id *new_id)
10854 const struct got_error *err;
10855 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10857 err = got_object_id_str(&old_id_str, old_id);
10858 if (err)
10859 goto done;
10861 if (new_id) {
10862 err = got_object_id_str(&new_id_str, new_id);
10863 if (err)
10864 goto done;
10867 old_id_str[12] = '\0';
10868 if (new_id_str)
10869 new_id_str[12] = '\0';
10871 err = get_short_logmsg(&logmsg, 42, commit);
10872 if (err)
10873 goto done;
10875 printf("%s -> %s: %s\n", old_id_str,
10876 new_id_str ? new_id_str : "no-op change", logmsg);
10877 done:
10878 free(old_id_str);
10879 free(new_id_str);
10880 free(logmsg);
10881 return err;
10884 static const struct got_error *
10885 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10886 struct got_reference *branch, struct got_reference *tmp_branch,
10887 struct got_repository *repo, int create_backup)
10889 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10890 return got_worktree_rebase_complete(worktree, fileindex,
10891 tmp_branch, branch, repo, create_backup);
10894 static const struct got_error *
10895 rebase_commit(struct got_pathlist_head *merged_paths,
10896 struct got_worktree *worktree, struct got_fileindex *fileindex,
10897 struct got_reference *tmp_branch, const char *committer,
10898 struct got_object_id *commit_id, int allow_conflict,
10899 struct got_repository *repo)
10901 const struct got_error *error;
10902 struct got_commit_object *commit;
10903 struct got_object_id *new_commit_id;
10905 error = got_object_open_as_commit(&commit, repo, commit_id);
10906 if (error)
10907 return error;
10909 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10910 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10911 allow_conflict, repo);
10912 if (error) {
10913 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10914 goto done;
10915 error = show_rebase_progress(commit, commit_id, NULL);
10916 } else {
10917 error = show_rebase_progress(commit, commit_id, new_commit_id);
10918 free(new_commit_id);
10920 done:
10921 got_object_commit_close(commit);
10922 return error;
10925 struct check_path_prefix_arg {
10926 const char *path_prefix;
10927 size_t len;
10928 int errcode;
10931 static const struct got_error *
10932 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10933 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10934 struct got_object_id *id1, struct got_object_id *id2,
10935 const char *path1, const char *path2,
10936 mode_t mode1, mode_t mode2, struct got_repository *repo)
10938 struct check_path_prefix_arg *a = arg;
10940 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10941 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10942 return got_error(a->errcode);
10944 return NULL;
10947 static const struct got_error *
10948 check_path_prefix(struct got_object_id *parent_id,
10949 struct got_object_id *commit_id, const char *path_prefix,
10950 int errcode, struct got_repository *repo)
10952 const struct got_error *err;
10953 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10954 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10955 struct check_path_prefix_arg cpp_arg;
10957 if (got_path_is_root_dir(path_prefix))
10958 return NULL;
10960 err = got_object_open_as_commit(&commit, repo, commit_id);
10961 if (err)
10962 goto done;
10964 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10965 if (err)
10966 goto done;
10968 err = got_object_open_as_tree(&tree1, repo,
10969 got_object_commit_get_tree_id(parent_commit));
10970 if (err)
10971 goto done;
10973 err = got_object_open_as_tree(&tree2, repo,
10974 got_object_commit_get_tree_id(commit));
10975 if (err)
10976 goto done;
10978 cpp_arg.path_prefix = path_prefix;
10979 while (cpp_arg.path_prefix[0] == '/')
10980 cpp_arg.path_prefix++;
10981 cpp_arg.len = strlen(cpp_arg.path_prefix);
10982 cpp_arg.errcode = errcode;
10983 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10984 check_path_prefix_in_diff, &cpp_arg, 0);
10985 done:
10986 if (tree1)
10987 got_object_tree_close(tree1);
10988 if (tree2)
10989 got_object_tree_close(tree2);
10990 if (commit)
10991 got_object_commit_close(commit);
10992 if (parent_commit)
10993 got_object_commit_close(parent_commit);
10994 return err;
10997 static const struct got_error *
10998 collect_commits(struct got_object_id_queue *commits,
10999 struct got_object_id *initial_commit_id,
11000 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
11001 const char *path_prefix, int path_prefix_errcode,
11002 struct got_repository *repo)
11004 const struct got_error *err = NULL;
11005 struct got_commit_graph *graph = NULL;
11006 struct got_object_id parent_id, commit_id;
11007 struct got_object_qid *qid;
11009 err = got_commit_graph_open(&graph, "/", 1);
11010 if (err)
11011 return err;
11013 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
11014 check_cancelled, NULL);
11015 if (err)
11016 goto done;
11018 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
11019 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
11020 err = got_commit_graph_iter_next(&parent_id, graph, repo,
11021 check_cancelled, NULL);
11022 if (err) {
11023 if (err->code == GOT_ERR_ITER_COMPLETED) {
11024 err = got_error_msg(GOT_ERR_ANCESTRY,
11025 "ran out of commits to rebase before "
11026 "youngest common ancestor commit has "
11027 "been reached?!?");
11029 goto done;
11030 } else {
11031 err = check_path_prefix(&parent_id, &commit_id,
11032 path_prefix, path_prefix_errcode, repo);
11033 if (err)
11034 goto done;
11036 err = got_object_qid_alloc(&qid, &commit_id);
11037 if (err)
11038 goto done;
11039 STAILQ_INSERT_HEAD(commits, qid, entry);
11041 memcpy(&commit_id, &parent_id, sizeof(commit_id));
11044 done:
11045 got_commit_graph_close(graph);
11046 return err;
11049 static const struct got_error *
11050 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
11052 const struct got_error *err = NULL;
11053 time_t committer_time;
11054 struct tm tm;
11055 char datebuf[11]; /* YYYY-MM-DD + NUL */
11056 char *author0 = NULL, *author, *smallerthan;
11057 char *logmsg0 = NULL, *logmsg, *newline;
11059 committer_time = got_object_commit_get_committer_time(commit);
11060 if (gmtime_r(&committer_time, &tm) == NULL)
11061 return got_error_from_errno("gmtime_r");
11062 if (strftime(datebuf, sizeof(datebuf), "%F", &tm) == 0)
11063 return got_error(GOT_ERR_NO_SPACE);
11065 author0 = strdup(got_object_commit_get_author(commit));
11066 if (author0 == NULL)
11067 return got_error_from_errno("strdup");
11068 author = author0;
11069 smallerthan = strchr(author, '<');
11070 if (smallerthan && smallerthan[1] != '\0')
11071 author = smallerthan + 1;
11072 author[strcspn(author, "@>")] = '\0';
11074 err = got_object_commit_get_logmsg(&logmsg0, commit);
11075 if (err)
11076 goto done;
11077 logmsg = logmsg0;
11078 while (*logmsg == '\n')
11079 logmsg++;
11080 newline = strchr(logmsg, '\n');
11081 if (newline)
11082 *newline = '\0';
11084 if (asprintf(brief_str, "%s %s %s",
11085 datebuf, author, logmsg) == -1)
11086 err = got_error_from_errno("asprintf");
11087 done:
11088 free(author0);
11089 free(logmsg0);
11090 return err;
11093 static const struct got_error *
11094 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
11095 struct got_repository *repo)
11097 const struct got_error *err;
11098 char *id_str;
11100 err = got_object_id_str(&id_str, id);
11101 if (err)
11102 return err;
11104 err = got_ref_delete(ref, repo);
11105 if (err)
11106 goto done;
11108 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
11109 done:
11110 free(id_str);
11111 return err;
11114 static const struct got_error *
11115 print_backup_ref(const char *branch_name, const char *new_id_str,
11116 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
11117 struct got_reflist_object_id_map *refs_idmap,
11118 struct got_repository *repo)
11120 const struct got_error *err = NULL;
11121 struct got_reflist_head *refs;
11122 char *refs_str = NULL;
11123 struct got_object_id *new_commit_id = NULL;
11124 struct got_commit_object *new_commit = NULL;
11125 char *new_commit_brief_str = NULL;
11126 struct got_object_id *yca_id = NULL;
11127 struct got_commit_object *yca_commit = NULL;
11128 char *yca_id_str = NULL, *yca_brief_str = NULL;
11129 char *custom_refs_str;
11131 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
11132 return got_error_from_errno("asprintf");
11134 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
11135 0, 0, refs_idmap, custom_refs_str, NULL);
11136 if (err)
11137 goto done;
11139 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11140 if (err)
11141 goto done;
11143 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11144 if (refs) {
11145 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11146 if (err)
11147 goto done;
11150 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11151 if (err)
11152 goto done;
11154 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11155 if (err)
11156 goto done;
11158 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11159 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11160 if (err)
11161 goto done;
11163 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11164 refs_str ? " (" : "", refs_str ? refs_str : "",
11165 refs_str ? ")" : "", new_commit_brief_str);
11166 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11167 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11168 free(refs_str);
11169 refs_str = NULL;
11171 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11172 if (err)
11173 goto done;
11175 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11176 if (err)
11177 goto done;
11179 err = got_object_id_str(&yca_id_str, yca_id);
11180 if (err)
11181 goto done;
11183 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11184 if (refs) {
11185 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11186 if (err)
11187 goto done;
11189 printf("history forked at %s%s%s%s\n %s\n",
11190 yca_id_str,
11191 refs_str ? " (" : "", refs_str ? refs_str : "",
11192 refs_str ? ")" : "", yca_brief_str);
11194 done:
11195 free(custom_refs_str);
11196 free(new_commit_id);
11197 free(refs_str);
11198 free(yca_id);
11199 free(yca_id_str);
11200 free(yca_brief_str);
11201 if (new_commit)
11202 got_object_commit_close(new_commit);
11203 if (yca_commit)
11204 got_object_commit_close(yca_commit);
11206 return err;
11209 static const struct got_error *
11210 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11211 struct got_repository *repo)
11213 const struct got_error *err;
11214 struct got_reflist_head refs;
11215 struct got_reflist_entry *re;
11216 char *uuidstr = NULL;
11217 static char msg[160];
11219 TAILQ_INIT(&refs);
11221 err = got_worktree_get_uuid(&uuidstr, worktree);
11222 if (err)
11223 goto done;
11225 err = got_ref_list(&refs, repo, "refs/got/worktree",
11226 got_ref_cmp_by_name, repo);
11227 if (err)
11228 goto done;
11230 TAILQ_FOREACH(re, &refs, entry) {
11231 const char *cmd, *refname, *type;
11233 refname = got_ref_get_name(re->ref);
11235 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11236 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11237 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11238 cmd = "cherrypick";
11239 type = "cherrypicked";
11240 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11241 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11242 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11243 cmd = "backout";
11244 type = "backed-out";
11245 } else
11246 continue;
11248 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11249 continue;
11251 snprintf(msg, sizeof(msg),
11252 "work tree has references created by %s commits which "
11253 "must be removed with 'got %s -X' before running the %s "
11254 "command", type, cmd, caller);
11255 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11256 goto done;
11259 done:
11260 free(uuidstr);
11261 got_ref_list_free(&refs);
11262 return err;
11265 static const struct got_error *
11266 process_backup_refs(const char *backup_ref_prefix,
11267 const char *wanted_branch_name,
11268 int delete, struct got_repository *repo)
11270 const struct got_error *err;
11271 struct got_reflist_head refs, backup_refs;
11272 struct got_reflist_entry *re;
11273 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11274 struct got_object_id *old_commit_id = NULL;
11275 char *branch_name = NULL;
11276 struct got_commit_object *old_commit = NULL;
11277 struct got_reflist_object_id_map *refs_idmap = NULL;
11278 int wanted_branch_found = 0;
11280 TAILQ_INIT(&refs);
11281 TAILQ_INIT(&backup_refs);
11283 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11284 if (err)
11285 return err;
11287 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11288 if (err)
11289 goto done;
11291 if (wanted_branch_name) {
11292 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11293 wanted_branch_name += 11;
11296 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11297 got_ref_cmp_by_commit_timestamp_descending, repo);
11298 if (err)
11299 goto done;
11301 TAILQ_FOREACH(re, &backup_refs, entry) {
11302 const char *refname = got_ref_get_name(re->ref);
11303 char *slash;
11305 err = check_cancelled(NULL);
11306 if (err)
11307 break;
11309 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11310 if (err)
11311 break;
11313 err = got_object_open_as_commit(&old_commit, repo,
11314 old_commit_id);
11315 if (err)
11316 break;
11318 if (strncmp(backup_ref_prefix, refname,
11319 backup_ref_prefix_len) == 0)
11320 refname += backup_ref_prefix_len;
11322 while (refname[0] == '/')
11323 refname++;
11325 branch_name = strdup(refname);
11326 if (branch_name == NULL) {
11327 err = got_error_from_errno("strdup");
11328 break;
11330 slash = strrchr(branch_name, '/');
11331 if (slash) {
11332 *slash = '\0';
11333 refname += strlen(branch_name) + 1;
11336 if (wanted_branch_name == NULL ||
11337 strcmp(wanted_branch_name, branch_name) == 0) {
11338 wanted_branch_found = 1;
11339 if (delete) {
11340 err = delete_backup_ref(re->ref,
11341 old_commit_id, repo);
11342 } else {
11343 err = print_backup_ref(branch_name, refname,
11344 old_commit_id, old_commit, refs_idmap,
11345 repo);
11347 if (err)
11348 break;
11351 free(old_commit_id);
11352 old_commit_id = NULL;
11353 free(branch_name);
11354 branch_name = NULL;
11355 got_object_commit_close(old_commit);
11356 old_commit = NULL;
11359 if (wanted_branch_name && !wanted_branch_found) {
11360 err = got_error_fmt(GOT_ERR_NOT_REF,
11361 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11363 done:
11364 if (refs_idmap)
11365 got_reflist_object_id_map_free(refs_idmap);
11366 got_ref_list_free(&refs);
11367 got_ref_list_free(&backup_refs);
11368 free(old_commit_id);
11369 free(branch_name);
11370 if (old_commit)
11371 got_object_commit_close(old_commit);
11372 return err;
11375 static const struct got_error *
11376 abort_progress(void *arg, unsigned char status, const char *path)
11379 * Unversioned files should not clutter progress output when
11380 * an operation is aborted.
11382 if (status == GOT_STATUS_UNVERSIONED)
11383 return NULL;
11385 return update_progress(arg, status, path);
11388 static const struct got_error *
11389 find_merge_commit_yca(struct got_object_id **new_yca_id,
11390 struct got_object_id *branch_head_commit_id,
11391 struct got_object_id *yca_id,
11392 struct got_object_id *base_commit_id,
11393 struct got_repository *repo)
11395 const struct got_error *err = NULL;
11396 struct got_commit_graph *graph = NULL;
11397 struct got_commit_object *commit = NULL;
11399 *new_yca_id = NULL;
11401 err = got_commit_graph_open(&graph, "/", 1);
11402 if (err)
11403 return err;
11405 err = got_commit_graph_bfsort(graph, base_commit_id,
11406 repo, check_cancelled, NULL);
11407 if (err)
11408 goto done;
11410 for (;;) {
11411 struct got_object_id id;
11413 err = got_commit_graph_iter_next(&id, graph, repo,
11414 check_cancelled, NULL);
11415 if (err) {
11416 if (err->code == GOT_ERR_ITER_COMPLETED)
11417 err = NULL;
11418 break;
11421 err = got_object_open_as_commit(&commit, repo, &id);
11422 if (err)
11423 break;
11425 if (got_object_commit_get_nparents(commit) > 1) {
11426 /* Search for a better YCA using toposort. */
11427 err = got_commit_graph_find_youngest_common_ancestor(
11428 new_yca_id, base_commit_id, branch_head_commit_id,
11429 0, 1, repo, check_cancelled, NULL);
11430 break;
11433 if (got_object_id_cmp(&id, yca_id) == 0)
11434 break;
11435 got_object_commit_close(commit);
11436 commit = NULL;
11438 done:
11439 got_commit_graph_close(graph);
11440 if (commit)
11441 got_object_commit_close(commit);
11442 return err;
11445 static const struct got_error *
11446 cmd_rebase(int argc, char *argv[])
11448 const struct got_error *error = NULL;
11449 struct got_worktree *worktree = NULL;
11450 struct got_repository *repo = NULL;
11451 struct got_fileindex *fileindex = NULL;
11452 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11453 struct got_reference *branch = NULL;
11454 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11455 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11456 struct got_object_id *resume_commit_id = NULL;
11457 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11458 struct got_object_id *head_commit_id = NULL;
11459 struct got_reference *head_ref = NULL;
11460 struct got_commit_object *commit = NULL;
11461 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11462 int histedit_in_progress = 0, merge_in_progress = 0;
11463 int create_backup = 1, list_backups = 0, delete_backups = 0;
11464 int allow_conflict = 0;
11465 struct got_object_id_queue commits;
11466 struct got_pathlist_head merged_paths;
11467 const struct got_object_id_queue *parent_ids;
11468 struct got_object_qid *qid, *pid;
11469 struct got_update_progress_arg upa;
11470 int *pack_fds = NULL;
11472 STAILQ_INIT(&commits);
11473 TAILQ_INIT(&merged_paths);
11474 memset(&upa, 0, sizeof(upa));
11476 #ifndef PROFILE
11477 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11478 "unveil", NULL) == -1)
11479 err(1, "pledge");
11480 #endif
11482 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11483 switch (ch) {
11484 case 'a':
11485 abort_rebase = 1;
11486 break;
11487 case 'C':
11488 allow_conflict = 1;
11489 break;
11490 case 'c':
11491 continue_rebase = 1;
11492 break;
11493 case 'l':
11494 list_backups = 1;
11495 break;
11496 case 'X':
11497 delete_backups = 1;
11498 break;
11499 default:
11500 usage_rebase();
11501 /* NOTREACHED */
11505 argc -= optind;
11506 argv += optind;
11508 if (list_backups) {
11509 if (abort_rebase)
11510 option_conflict('l', 'a');
11511 if (allow_conflict)
11512 option_conflict('l', 'C');
11513 if (continue_rebase)
11514 option_conflict('l', 'c');
11515 if (delete_backups)
11516 option_conflict('l', 'X');
11517 if (argc != 0 && argc != 1)
11518 usage_rebase();
11519 } else if (delete_backups) {
11520 if (abort_rebase)
11521 option_conflict('X', 'a');
11522 if (allow_conflict)
11523 option_conflict('X', 'C');
11524 if (continue_rebase)
11525 option_conflict('X', 'c');
11526 if (list_backups)
11527 option_conflict('l', 'X');
11528 if (argc != 0 && argc != 1)
11529 usage_rebase();
11530 } else if (allow_conflict) {
11531 if (abort_rebase)
11532 option_conflict('C', 'a');
11533 if (!continue_rebase)
11534 errx(1, "-C option requires -c");
11535 } else {
11536 if (abort_rebase && continue_rebase)
11537 usage_rebase();
11538 else if (abort_rebase || continue_rebase) {
11539 if (argc != 0)
11540 usage_rebase();
11541 } else if (argc != 1)
11542 usage_rebase();
11545 cwd = getcwd(NULL, 0);
11546 if (cwd == NULL) {
11547 error = got_error_from_errno("getcwd");
11548 goto done;
11551 error = got_repo_pack_fds_open(&pack_fds);
11552 if (error != NULL)
11553 goto done;
11555 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11556 if (error) {
11557 if (list_backups || delete_backups) {
11558 if (error->code != GOT_ERR_NOT_WORKTREE)
11559 goto done;
11560 } else {
11561 if (error->code == GOT_ERR_NOT_WORKTREE)
11562 error = wrap_not_worktree_error(error,
11563 "rebase", cwd);
11564 goto done;
11568 error = get_gitconfig_path(&gitconfig_path);
11569 if (error)
11570 goto done;
11571 error = got_repo_open(&repo,
11572 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11573 gitconfig_path, pack_fds);
11574 if (error != NULL)
11575 goto done;
11577 if (worktree != NULL && !list_backups && !delete_backups) {
11578 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11579 if (error)
11580 goto done;
11583 error = get_author(&committer, repo, worktree);
11584 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11585 goto done;
11587 error = apply_unveil(got_repo_get_path(repo), 0,
11588 worktree ? got_worktree_get_root_path(worktree) : NULL);
11589 if (error)
11590 goto done;
11592 if (list_backups || delete_backups) {
11593 error = process_backup_refs(
11594 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11595 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11596 goto done; /* nothing else to do */
11599 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11600 worktree);
11601 if (error)
11602 goto done;
11603 if (histedit_in_progress) {
11604 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11605 goto done;
11608 error = got_worktree_merge_in_progress(&merge_in_progress,
11609 worktree, repo);
11610 if (error)
11611 goto done;
11612 if (merge_in_progress) {
11613 error = got_error(GOT_ERR_MERGE_BUSY);
11614 goto done;
11617 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11618 if (error)
11619 goto done;
11621 if (abort_rebase) {
11622 if (!rebase_in_progress) {
11623 error = got_error(GOT_ERR_NOT_REBASING);
11624 goto done;
11626 error = got_worktree_rebase_continue(&resume_commit_id,
11627 &new_base_branch, &tmp_branch, &branch, &fileindex,
11628 worktree, repo);
11629 if (error)
11630 goto done;
11631 printf("Switching work tree to %s\n",
11632 got_ref_get_symref_target(new_base_branch));
11633 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11634 new_base_branch, abort_progress, &upa);
11635 if (error)
11636 goto done;
11637 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11638 print_merge_progress_stats(&upa);
11639 goto done; /* nothing else to do */
11642 if (continue_rebase) {
11643 if (!rebase_in_progress) {
11644 error = got_error(GOT_ERR_NOT_REBASING);
11645 goto done;
11647 error = got_worktree_rebase_continue(&resume_commit_id,
11648 &new_base_branch, &tmp_branch, &branch, &fileindex,
11649 worktree, repo);
11650 if (error)
11651 goto done;
11653 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11654 committer, resume_commit_id, allow_conflict, repo);
11655 if (error)
11656 goto done;
11658 yca_id = got_object_id_dup(resume_commit_id);
11659 if (yca_id == NULL) {
11660 error = got_error_from_errno("got_object_id_dup");
11661 goto done;
11663 } else {
11664 error = got_ref_open(&branch, repo, argv[0], 0);
11665 if (error != NULL)
11666 goto done;
11667 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11668 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11669 "will not rebase a branch which lives outside "
11670 "the \"refs/heads/\" reference namespace");
11671 goto done;
11675 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11676 if (error)
11677 goto done;
11679 if (!continue_rebase) {
11680 struct got_object_id *base_commit_id;
11682 error = got_ref_open(&head_ref, repo,
11683 got_worktree_get_head_ref_name(worktree), 0);
11684 if (error)
11685 goto done;
11686 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11687 if (error)
11688 goto done;
11689 base_commit_id = got_worktree_get_base_commit_id(worktree);
11690 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11691 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11692 goto done;
11695 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11696 base_commit_id, branch_head_commit_id, 1, 0,
11697 repo, check_cancelled, NULL);
11698 if (error) {
11699 if (error->code == GOT_ERR_ANCESTRY) {
11700 error = got_error_msg(GOT_ERR_ANCESTRY,
11701 "specified branch shares no common "
11702 "ancestry with work tree's branch");
11704 goto done;
11708 * If a merge commit appears between the new base branch tip
11709 * and a YCA found via first-parent traversal then we might
11710 * find a better YCA using topologically sorted commits.
11712 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11713 struct got_object_id *better_yca_id;
11714 error = find_merge_commit_yca(&better_yca_id,
11715 branch_head_commit_id, yca_id,
11716 base_commit_id, repo);
11717 if (error)
11718 goto done;
11719 if (better_yca_id) {
11720 free(yca_id);
11721 yca_id = better_yca_id;
11725 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11726 struct got_pathlist_head paths;
11727 const char *branch_name = got_ref_get_name(branch);
11728 const char *base =
11729 got_worktree_get_head_ref_name(worktree);
11731 if (strcmp(branch_name, base) == 0) {
11732 error = got_error_fmt(GOT_ERR_WRONG_BRANCH,
11733 "cannot rebase %s onto itself",
11734 branch_name);
11735 goto done;
11736 } else {
11737 printf("%s is already based on %s\n",
11738 branch_name, base);
11740 error = switch_head_ref(branch, branch_head_commit_id,
11741 worktree, repo);
11742 if (error)
11743 goto done;
11744 error = got_worktree_set_base_commit_id(worktree, repo,
11745 branch_head_commit_id);
11746 if (error)
11747 goto done;
11748 TAILQ_INIT(&paths);
11749 error = got_pathlist_append(&paths, "", NULL);
11750 if (error)
11751 goto done;
11752 error = got_worktree_checkout_files(worktree,
11753 &paths, repo, update_progress, &upa,
11754 check_cancelled, NULL);
11755 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11756 if (error)
11757 goto done;
11758 if (upa.did_something) {
11759 char *id_str;
11760 error = got_object_id_str(&id_str,
11761 branch_head_commit_id);
11762 if (error)
11763 goto done;
11764 printf("Updated to %s: %s\n",
11765 got_worktree_get_head_ref_name(worktree),
11766 id_str);
11767 free(id_str);
11768 } else
11769 printf("Already up-to-date\n");
11770 print_update_progress_stats(&upa);
11771 goto done;
11775 commit_id = branch_head_commit_id;
11776 error = got_object_open_as_commit(&commit, repo, commit_id);
11777 if (error)
11778 goto done;
11780 parent_ids = got_object_commit_get_parent_ids(commit);
11781 pid = STAILQ_FIRST(parent_ids);
11782 if (pid) {
11783 error = collect_commits(&commits, commit_id, &pid->id,
11784 yca_id, got_worktree_get_path_prefix(worktree),
11785 GOT_ERR_REBASE_PATH, repo);
11786 if (error)
11787 goto done;
11790 got_object_commit_close(commit);
11791 commit = NULL;
11793 if (!continue_rebase) {
11794 error = got_worktree_rebase_prepare(&new_base_branch,
11795 &tmp_branch, &fileindex, worktree, branch, repo);
11796 if (error)
11797 goto done;
11800 if (STAILQ_EMPTY(&commits)) {
11801 if (continue_rebase) {
11802 error = rebase_complete(worktree, fileindex,
11803 branch, tmp_branch, repo, create_backup);
11804 goto done;
11805 } else {
11806 /* Fast-forward the reference of the branch. */
11807 struct got_object_id *new_head_commit_id;
11808 char *id_str;
11809 error = got_ref_resolve(&new_head_commit_id, repo,
11810 new_base_branch);
11811 if (error)
11812 goto done;
11813 error = got_object_id_str(&id_str, new_head_commit_id);
11814 if (error)
11815 goto done;
11816 printf("Forwarding %s to commit %s\n",
11817 got_ref_get_name(branch), id_str);
11818 free(id_str);
11819 error = got_ref_change_ref(branch,
11820 new_head_commit_id);
11821 if (error)
11822 goto done;
11823 /* No backup needed since objects did not change. */
11824 create_backup = 0;
11828 pid = NULL;
11829 STAILQ_FOREACH(qid, &commits, entry) {
11831 commit_id = &qid->id;
11832 parent_id = pid ? &pid->id : yca_id;
11833 pid = qid;
11835 memset(&upa, 0, sizeof(upa));
11836 error = got_worktree_rebase_merge_files(&merged_paths,
11837 worktree, fileindex, parent_id, commit_id, repo,
11838 update_progress, &upa, check_cancelled, NULL);
11839 if (error)
11840 goto done;
11842 print_merge_progress_stats(&upa);
11843 if (upa.conflicts > 0 || upa.missing > 0 ||
11844 upa.not_deleted > 0 || upa.unversioned > 0) {
11845 if (upa.conflicts > 0) {
11846 error = show_rebase_merge_conflict(&qid->id,
11847 repo);
11848 if (error)
11849 goto done;
11851 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11852 break;
11855 error = rebase_commit(&merged_paths, worktree, fileindex,
11856 tmp_branch, committer, commit_id, 0, repo);
11857 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11858 if (error)
11859 goto done;
11862 if (upa.conflicts > 0 || upa.missing > 0 ||
11863 upa.not_deleted > 0 || upa.unversioned > 0) {
11864 error = got_worktree_rebase_postpone(worktree, fileindex);
11865 if (error)
11866 goto done;
11867 if (upa.conflicts > 0 && upa.missing == 0 &&
11868 upa.not_deleted == 0 && upa.unversioned == 0) {
11869 error = got_error_msg(GOT_ERR_CONFLICTS,
11870 "conflicts must be resolved before rebasing "
11871 "can continue");
11872 } else if (upa.conflicts > 0) {
11873 error = got_error_msg(GOT_ERR_CONFLICTS,
11874 "conflicts must be resolved before rebasing "
11875 "can continue; changes destined for some "
11876 "files were not yet merged and should be "
11877 "merged manually if required before the "
11878 "rebase operation is continued");
11879 } else {
11880 error = got_error_msg(GOT_ERR_CONFLICTS,
11881 "changes destined for some files were not "
11882 "yet merged and should be merged manually "
11883 "if required before the rebase operation "
11884 "is continued");
11886 } else
11887 error = rebase_complete(worktree, fileindex, branch,
11888 tmp_branch, repo, create_backup);
11889 done:
11890 free(cwd);
11891 free(committer);
11892 free(gitconfig_path);
11893 got_object_id_queue_free(&commits);
11894 free(branch_head_commit_id);
11895 free(resume_commit_id);
11896 free(head_commit_id);
11897 free(yca_id);
11898 if (commit)
11899 got_object_commit_close(commit);
11900 if (branch)
11901 got_ref_close(branch);
11902 if (new_base_branch)
11903 got_ref_close(new_base_branch);
11904 if (tmp_branch)
11905 got_ref_close(tmp_branch);
11906 if (head_ref)
11907 got_ref_close(head_ref);
11908 if (worktree)
11909 got_worktree_close(worktree);
11910 if (repo) {
11911 const struct got_error *close_err = got_repo_close(repo);
11912 if (error == NULL)
11913 error = close_err;
11915 if (pack_fds) {
11916 const struct got_error *pack_err =
11917 got_repo_pack_fds_close(pack_fds);
11918 if (error == NULL)
11919 error = pack_err;
11921 return error;
11924 __dead static void
11925 usage_histedit(void)
11927 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11928 "[branch]\n", getprogname());
11929 exit(1);
11932 #define GOT_HISTEDIT_PICK 'p'
11933 #define GOT_HISTEDIT_EDIT 'e'
11934 #define GOT_HISTEDIT_FOLD 'f'
11935 #define GOT_HISTEDIT_DROP 'd'
11936 #define GOT_HISTEDIT_MESG 'm'
11938 static const struct got_histedit_cmd {
11939 unsigned char code;
11940 const char *name;
11941 const char *desc;
11942 } got_histedit_cmds[] = {
11943 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11944 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11945 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11946 "be used" },
11947 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11948 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11951 struct got_histedit_list_entry {
11952 TAILQ_ENTRY(got_histedit_list_entry) entry;
11953 struct got_object_id *commit_id;
11954 const struct got_histedit_cmd *cmd;
11955 char *logmsg;
11957 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11959 static const struct got_error *
11960 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11961 FILE *f, struct got_repository *repo)
11963 const struct got_error *err = NULL;
11964 char *logmsg = NULL, *id_str = NULL;
11965 struct got_commit_object *commit = NULL;
11966 int n;
11968 err = got_object_open_as_commit(&commit, repo, commit_id);
11969 if (err)
11970 goto done;
11972 err = get_short_logmsg(&logmsg, 34, commit);
11973 if (err)
11974 goto done;
11976 err = got_object_id_str(&id_str, commit_id);
11977 if (err)
11978 goto done;
11980 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11981 if (n < 0)
11982 err = got_ferror(f, GOT_ERR_IO);
11983 done:
11984 if (commit)
11985 got_object_commit_close(commit);
11986 free(id_str);
11987 free(logmsg);
11988 return err;
11991 static const struct got_error *
11992 histedit_write_commit_list(struct got_object_id_queue *commits,
11993 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11994 int edit_only, struct got_repository *repo)
11996 const struct got_error *err = NULL;
11997 struct got_object_qid *qid;
11998 const char *histedit_cmd = NULL;
12000 if (STAILQ_EMPTY(commits))
12001 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12003 STAILQ_FOREACH(qid, commits, entry) {
12004 histedit_cmd = got_histedit_cmds[0].name;
12005 if (drop_only)
12006 histedit_cmd = "drop";
12007 else if (edit_only)
12008 histedit_cmd = "edit";
12009 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
12010 histedit_cmd = "fold";
12011 else if (edit_logmsg_only)
12012 histedit_cmd = "mesg";
12013 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
12014 if (err)
12015 break;
12018 return err;
12021 static const struct got_error *
12022 write_cmd_list(FILE *f, const char *branch_name,
12023 struct got_object_id_queue *commits)
12025 const struct got_error *err = NULL;
12026 size_t i;
12027 int n;
12028 char *id_str;
12029 struct got_object_qid *qid;
12031 qid = STAILQ_FIRST(commits);
12032 err = got_object_id_str(&id_str, &qid->id);
12033 if (err)
12034 return err;
12036 n = fprintf(f,
12037 "# Editing the history of branch '%s' starting at\n"
12038 "# commit %s\n"
12039 "# Commits will be processed in order from top to "
12040 "bottom of this file.\n", branch_name, id_str);
12041 if (n < 0) {
12042 err = got_ferror(f, GOT_ERR_IO);
12043 goto done;
12046 n = fprintf(f, "# Available histedit commands:\n");
12047 if (n < 0) {
12048 err = got_ferror(f, GOT_ERR_IO);
12049 goto done;
12052 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12053 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
12054 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
12055 cmd->desc);
12056 if (n < 0) {
12057 err = got_ferror(f, GOT_ERR_IO);
12058 break;
12061 done:
12062 free(id_str);
12063 return err;
12066 static const struct got_error *
12067 histedit_syntax_error(int lineno)
12069 static char msg[42];
12070 int ret;
12072 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
12073 lineno);
12074 if (ret < 0 || (size_t)ret >= sizeof(msg))
12075 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
12077 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
12080 static const struct got_error *
12081 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
12082 char *logmsg, struct got_repository *repo)
12084 const struct got_error *err;
12085 struct got_commit_object *folded_commit = NULL;
12086 char *id_str, *folded_logmsg = NULL;
12088 err = got_object_id_str(&id_str, hle->commit_id);
12089 if (err)
12090 return err;
12092 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
12093 if (err)
12094 goto done;
12096 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
12097 if (err)
12098 goto done;
12099 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
12100 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
12101 folded_logmsg) == -1) {
12102 err = got_error_from_errno("asprintf");
12104 done:
12105 if (folded_commit)
12106 got_object_commit_close(folded_commit);
12107 free(id_str);
12108 free(folded_logmsg);
12109 return err;
12112 static struct got_histedit_list_entry *
12113 get_folded_commits(struct got_histedit_list_entry *hle)
12115 struct got_histedit_list_entry *prev, *folded = NULL;
12117 prev = TAILQ_PREV(hle, got_histedit_list, entry);
12118 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
12119 prev->cmd->code == GOT_HISTEDIT_DROP)) {
12120 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
12121 folded = prev;
12122 prev = TAILQ_PREV(prev, got_histedit_list, entry);
12125 return folded;
12128 static const struct got_error *
12129 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
12130 const char *editor, struct got_repository *repo)
12132 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
12133 char *logmsg = NULL, *new_msg = NULL;
12134 const struct got_error *err = NULL;
12135 struct got_commit_object *commit = NULL;
12136 int logmsg_len;
12137 int fd = -1;
12138 struct got_histedit_list_entry *folded = NULL;
12140 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12141 if (err)
12142 return err;
12144 folded = get_folded_commits(hle);
12145 if (folded) {
12146 while (folded != hle) {
12147 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12148 folded = TAILQ_NEXT(folded, entry);
12149 continue;
12151 err = append_folded_commit_msg(&new_msg, folded,
12152 logmsg, repo);
12153 if (err)
12154 goto done;
12155 free(logmsg);
12156 logmsg = new_msg;
12157 folded = TAILQ_NEXT(folded, entry);
12161 err = got_object_id_str(&id_str, hle->commit_id);
12162 if (err)
12163 goto done;
12164 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12165 if (err)
12166 goto done;
12167 logmsg_len = asprintf(&new_msg,
12168 "%s\n# original log message of commit %s: %s",
12169 logmsg ? logmsg : "", id_str, orig_logmsg);
12170 if (logmsg_len == -1) {
12171 err = got_error_from_errno("asprintf");
12172 goto done;
12174 free(logmsg);
12175 logmsg = new_msg;
12177 err = got_object_id_str(&id_str, hle->commit_id);
12178 if (err)
12179 goto done;
12181 err = got_opentemp_named_fd(&logmsg_path, &fd,
12182 GOT_TMPDIR_STR "/got-logmsg", "");
12183 if (err)
12184 goto done;
12186 if (write(fd, logmsg, logmsg_len) == -1) {
12187 err = got_error_from_errno2("write", logmsg_path);
12188 goto done;
12190 if (close(fd) == -1) {
12191 err = got_error_from_errno2("close", logmsg_path);
12192 goto done;
12194 fd = -1;
12196 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12197 logmsg_len, 0);
12198 if (err) {
12199 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12200 goto done;
12201 err = NULL;
12202 hle->logmsg = strdup(new_msg);
12203 if (hle->logmsg == NULL)
12204 err = got_error_from_errno("strdup");
12206 done:
12207 if (fd != -1 && close(fd) == -1 && err == NULL)
12208 err = got_error_from_errno2("close", logmsg_path);
12209 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12210 err = got_error_from_errno2("unlink", logmsg_path);
12211 free(logmsg_path);
12212 free(logmsg);
12213 free(orig_logmsg);
12214 if (commit)
12215 got_object_commit_close(commit);
12216 return err;
12219 static const struct got_error *
12220 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12221 FILE *f, struct got_repository *repo)
12223 const struct got_error *err = NULL;
12224 char *line = NULL, *p, *end;
12225 size_t i, linesize = 0;
12226 ssize_t linelen;
12227 int lineno = 0;
12228 const struct got_histedit_cmd *cmd;
12229 struct got_object_id *commit_id = NULL;
12230 struct got_histedit_list_entry *hle = NULL;
12232 for (;;) {
12233 linelen = getline(&line, &linesize, f);
12234 if (linelen == -1) {
12235 const struct got_error *getline_err;
12236 if (feof(f))
12237 break;
12238 getline_err = got_error_from_errno("getline");
12239 err = got_ferror(f, getline_err->code);
12240 break;
12242 lineno++;
12243 p = line;
12244 while (isspace((unsigned char)p[0]))
12245 p++;
12246 if (p[0] == '#' || p[0] == '\0')
12247 continue;
12248 cmd = NULL;
12249 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12250 cmd = &got_histedit_cmds[i];
12251 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12252 isspace((unsigned char)p[strlen(cmd->name)])) {
12253 p += strlen(cmd->name);
12254 break;
12256 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12257 p++;
12258 break;
12261 if (i == nitems(got_histedit_cmds)) {
12262 err = histedit_syntax_error(lineno);
12263 break;
12265 while (isspace((unsigned char)p[0]))
12266 p++;
12267 end = p;
12268 while (end[0] && !isspace((unsigned char)end[0]))
12269 end++;
12270 *end = '\0';
12271 err = got_object_resolve_id_str(&commit_id, repo, p);
12272 if (err) {
12273 /* override error code */
12274 err = histedit_syntax_error(lineno);
12275 break;
12277 hle = malloc(sizeof(*hle));
12278 if (hle == NULL) {
12279 err = got_error_from_errno("malloc");
12280 break;
12282 hle->cmd = cmd;
12283 hle->commit_id = commit_id;
12284 hle->logmsg = NULL;
12285 commit_id = NULL;
12286 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12289 free(line);
12290 free(commit_id);
12291 return err;
12294 static const struct got_error *
12295 histedit_check_script(struct got_histedit_list *histedit_cmds,
12296 struct got_object_id_queue *commits, struct got_repository *repo)
12298 const struct got_error *err = NULL;
12299 struct got_object_qid *qid;
12300 struct got_histedit_list_entry *hle;
12301 static char msg[128];
12302 char *id_str;
12304 if (TAILQ_EMPTY(histedit_cmds))
12305 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12306 "histedit script contains no commands");
12307 if (STAILQ_EMPTY(commits))
12308 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12310 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12311 struct got_histedit_list_entry *hle2;
12312 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12313 if (hle == hle2)
12314 continue;
12315 if (got_object_id_cmp(hle->commit_id,
12316 hle2->commit_id) != 0)
12317 continue;
12318 err = got_object_id_str(&id_str, hle->commit_id);
12319 if (err)
12320 return err;
12321 snprintf(msg, sizeof(msg), "commit %s is listed "
12322 "more than once in histedit script", id_str);
12323 free(id_str);
12324 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12328 STAILQ_FOREACH(qid, commits, entry) {
12329 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12330 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12331 break;
12333 if (hle == NULL) {
12334 err = got_object_id_str(&id_str, &qid->id);
12335 if (err)
12336 return err;
12337 snprintf(msg, sizeof(msg),
12338 "commit %s missing from histedit script", id_str);
12339 free(id_str);
12340 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12344 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12345 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12346 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12347 "last commit in histedit script cannot be folded");
12349 return NULL;
12352 static const struct got_error *
12353 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12354 const char *editor, const char *path,
12355 struct got_object_id_queue *commits, struct got_repository *repo)
12357 const struct got_error *err = NULL;
12358 struct stat st, st2;
12359 struct timespec timeout;
12360 FILE *f = NULL;
12362 if (stat(path, &st) == -1) {
12363 err = got_error_from_errno2("stat", path);
12364 goto done;
12367 if (spawn_editor(editor, path) == -1) {
12368 err = got_error_from_errno("failed spawning editor");
12369 goto done;
12372 timeout.tv_sec = 0;
12373 timeout.tv_nsec = 1;
12374 nanosleep(&timeout, NULL);
12376 if (stat(path, &st2) == -1) {
12377 err = got_error_from_errno2("stat", path);
12378 goto done;
12381 if (st.st_size == st2.st_size &&
12382 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12383 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12384 "no changes made to histedit script, aborting");
12385 goto done;
12388 f = fopen(path, "re");
12389 if (f == NULL) {
12390 err = got_error_from_errno("fopen");
12391 goto done;
12393 err = histedit_parse_list(histedit_cmds, f, repo);
12394 if (err)
12395 goto done;
12397 err = histedit_check_script(histedit_cmds, commits, repo);
12398 done:
12399 if (f && fclose(f) == EOF && err == NULL)
12400 err = got_error_from_errno("fclose");
12401 return err;
12404 static const struct got_error *
12405 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12406 struct got_object_id_queue *, const char *, const char *, const char *,
12407 struct got_repository *);
12409 static const struct got_error *
12410 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12411 struct got_object_id_queue *commits, const char *branch_name,
12412 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12413 const char *editor, struct got_repository *repo)
12415 const struct got_error *err;
12416 FILE *f = NULL;
12417 char *path = NULL;
12419 err = got_opentemp_named(&path, &f, "got-histedit", "");
12420 if (err)
12421 return err;
12423 err = write_cmd_list(f, branch_name, commits);
12424 if (err)
12425 goto done;
12427 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12428 fold_only, drop_only, edit_only, repo);
12429 if (err)
12430 goto done;
12432 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12433 rewind(f);
12434 err = histedit_parse_list(histedit_cmds, f, repo);
12435 } else {
12436 if (fclose(f) == EOF) {
12437 err = got_error_from_errno("fclose");
12438 goto done;
12440 f = NULL;
12441 err = histedit_run_editor(histedit_cmds, editor, path,
12442 commits, repo);
12443 if (err) {
12444 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12445 err->code != GOT_ERR_HISTEDIT_CMD)
12446 goto done;
12447 err = histedit_edit_list_retry(histedit_cmds, err,
12448 commits, editor, path, branch_name, repo);
12451 done:
12452 if (f && fclose(f) == EOF && err == NULL)
12453 err = got_error_from_errno("fclose");
12454 if (path && unlink(path) != 0 && err == NULL)
12455 err = got_error_from_errno2("unlink", path);
12456 free(path);
12457 return err;
12460 static const struct got_error *
12461 histedit_save_list(struct got_histedit_list *histedit_cmds,
12462 struct got_worktree *worktree, struct got_repository *repo)
12464 const struct got_error *err = NULL;
12465 char *path = NULL;
12466 FILE *f = NULL;
12467 struct got_histedit_list_entry *hle;
12469 err = got_worktree_get_histedit_script_path(&path, worktree);
12470 if (err)
12471 return err;
12473 f = fopen(path, "we");
12474 if (f == NULL) {
12475 err = got_error_from_errno2("fopen", path);
12476 goto done;
12478 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12479 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12480 repo);
12481 if (err)
12482 break;
12484 done:
12485 if (f && fclose(f) == EOF && err == NULL)
12486 err = got_error_from_errno("fclose");
12487 free(path);
12488 return err;
12491 static void
12492 histedit_free_list(struct got_histedit_list *histedit_cmds)
12494 struct got_histedit_list_entry *hle;
12496 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12497 TAILQ_REMOVE(histedit_cmds, hle, entry);
12498 free(hle);
12502 static const struct got_error *
12503 histedit_load_list(struct got_histedit_list *histedit_cmds,
12504 const char *path, struct got_repository *repo)
12506 const struct got_error *err = NULL;
12507 FILE *f = NULL;
12509 f = fopen(path, "re");
12510 if (f == NULL) {
12511 err = got_error_from_errno2("fopen", path);
12512 goto done;
12515 err = histedit_parse_list(histedit_cmds, f, repo);
12516 done:
12517 if (f && fclose(f) == EOF && err == NULL)
12518 err = got_error_from_errno("fclose");
12519 return err;
12522 static const struct got_error *
12523 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12524 const struct got_error *edit_err, struct got_object_id_queue *commits,
12525 const char *editor, const char *path, const char *branch_name,
12526 struct got_repository *repo)
12528 const struct got_error *err = NULL, *prev_err = edit_err;
12529 int resp = ' ';
12531 while (resp != 'c' && resp != 'r' && resp != 'a') {
12532 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12533 "or (a)bort: ", getprogname(), prev_err->msg);
12534 resp = getchar();
12535 if (resp == '\n')
12536 resp = getchar();
12537 if (resp == 'c') {
12538 histedit_free_list(histedit_cmds);
12539 err = histedit_run_editor(histedit_cmds, editor, path,
12540 commits, repo);
12541 if (err) {
12542 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12543 err->code != GOT_ERR_HISTEDIT_CMD)
12544 break;
12545 prev_err = err;
12546 resp = ' ';
12547 continue;
12549 break;
12550 } else if (resp == 'r') {
12551 histedit_free_list(histedit_cmds);
12552 err = histedit_edit_script(histedit_cmds,
12553 commits, branch_name, 0, 0, 0, 0, editor, repo);
12554 if (err) {
12555 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12556 err->code != GOT_ERR_HISTEDIT_CMD)
12557 break;
12558 prev_err = err;
12559 resp = ' ';
12560 continue;
12562 break;
12563 } else if (resp == 'a') {
12564 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12565 break;
12566 } else
12567 printf("invalid response '%c'\n", resp);
12570 return err;
12573 static const struct got_error *
12574 histedit_complete(struct got_worktree *worktree,
12575 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12576 struct got_reference *branch, struct got_repository *repo)
12578 printf("Switching work tree to %s\n",
12579 got_ref_get_symref_target(branch));
12580 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12581 branch, repo);
12584 static const struct got_error *
12585 show_histedit_progress(struct got_commit_object *commit,
12586 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12588 const struct got_error *err;
12589 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12591 err = got_object_id_str(&old_id_str, hle->commit_id);
12592 if (err)
12593 goto done;
12595 if (new_id) {
12596 err = got_object_id_str(&new_id_str, new_id);
12597 if (err)
12598 goto done;
12601 old_id_str[12] = '\0';
12602 if (new_id_str)
12603 new_id_str[12] = '\0';
12605 if (hle->logmsg) {
12606 logmsg = strdup(hle->logmsg);
12607 if (logmsg == NULL) {
12608 err = got_error_from_errno("strdup");
12609 goto done;
12611 trim_logmsg(logmsg, 42);
12612 } else {
12613 err = get_short_logmsg(&logmsg, 42, commit);
12614 if (err)
12615 goto done;
12618 switch (hle->cmd->code) {
12619 case GOT_HISTEDIT_PICK:
12620 case GOT_HISTEDIT_EDIT:
12621 case GOT_HISTEDIT_MESG:
12622 printf("%s -> %s: %s\n", old_id_str,
12623 new_id_str ? new_id_str : "no-op change", logmsg);
12624 break;
12625 case GOT_HISTEDIT_DROP:
12626 case GOT_HISTEDIT_FOLD:
12627 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12628 logmsg);
12629 break;
12630 default:
12631 break;
12633 done:
12634 free(old_id_str);
12635 free(new_id_str);
12636 return err;
12639 static const struct got_error *
12640 histedit_commit(struct got_pathlist_head *merged_paths,
12641 struct got_worktree *worktree, struct got_fileindex *fileindex,
12642 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12643 const char *committer, int allow_conflict, const char *editor,
12644 struct got_repository *repo)
12646 const struct got_error *err;
12647 struct got_commit_object *commit;
12648 struct got_object_id *new_commit_id;
12650 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12651 && hle->logmsg == NULL) {
12652 err = histedit_edit_logmsg(hle, editor, repo);
12653 if (err)
12654 return err;
12657 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12658 if (err)
12659 return err;
12661 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12662 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12663 hle->logmsg, allow_conflict, repo);
12664 if (err) {
12665 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12666 goto done;
12667 err = show_histedit_progress(commit, hle, NULL);
12668 } else {
12669 err = show_histedit_progress(commit, hle, new_commit_id);
12670 free(new_commit_id);
12672 done:
12673 got_object_commit_close(commit);
12674 return err;
12677 static const struct got_error *
12678 histedit_skip_commit(struct got_histedit_list_entry *hle,
12679 struct got_worktree *worktree, struct got_repository *repo)
12681 const struct got_error *error;
12682 struct got_commit_object *commit;
12684 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12685 repo);
12686 if (error)
12687 return error;
12689 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12690 if (error)
12691 return error;
12693 error = show_histedit_progress(commit, hle, NULL);
12694 got_object_commit_close(commit);
12695 return error;
12698 static const struct got_error *
12699 check_local_changes(void *arg, unsigned char status,
12700 unsigned char staged_status, const char *path,
12701 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12702 struct got_object_id *commit_id, int dirfd, const char *de_name)
12704 int *have_local_changes = arg;
12706 switch (status) {
12707 case GOT_STATUS_ADD:
12708 case GOT_STATUS_DELETE:
12709 case GOT_STATUS_MODIFY:
12710 case GOT_STATUS_CONFLICT:
12711 *have_local_changes = 1;
12712 return got_error(GOT_ERR_CANCELLED);
12713 default:
12714 break;
12717 switch (staged_status) {
12718 case GOT_STATUS_ADD:
12719 case GOT_STATUS_DELETE:
12720 case GOT_STATUS_MODIFY:
12721 *have_local_changes = 1;
12722 return got_error(GOT_ERR_CANCELLED);
12723 default:
12724 break;
12727 return NULL;
12730 static const struct got_error *
12731 cmd_histedit(int argc, char *argv[])
12733 const struct got_error *error = NULL;
12734 struct got_worktree *worktree = NULL;
12735 struct got_fileindex *fileindex = NULL;
12736 struct got_repository *repo = NULL;
12737 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12738 struct got_reference *branch = NULL;
12739 struct got_reference *tmp_branch = NULL;
12740 struct got_object_id *resume_commit_id = NULL;
12741 struct got_object_id *base_commit_id = NULL;
12742 struct got_object_id *head_commit_id = NULL;
12743 struct got_commit_object *commit = NULL;
12744 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12745 struct got_update_progress_arg upa;
12746 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12747 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12748 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12749 const char *edit_script_path = NULL;
12750 char *editor = NULL;
12751 struct got_object_id_queue commits;
12752 struct got_pathlist_head merged_paths;
12753 const struct got_object_id_queue *parent_ids;
12754 struct got_object_qid *pid;
12755 struct got_histedit_list histedit_cmds;
12756 struct got_histedit_list_entry *hle;
12757 int *pack_fds = NULL;
12759 STAILQ_INIT(&commits);
12760 TAILQ_INIT(&histedit_cmds);
12761 TAILQ_INIT(&merged_paths);
12762 memset(&upa, 0, sizeof(upa));
12764 #ifndef PROFILE
12765 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12766 "unveil", NULL) == -1)
12767 err(1, "pledge");
12768 #endif
12770 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12771 switch (ch) {
12772 case 'a':
12773 abort_edit = 1;
12774 break;
12775 case 'C':
12776 allow_conflict = 1;
12777 break;
12778 case 'c':
12779 continue_edit = 1;
12780 break;
12781 case 'd':
12782 drop_only = 1;
12783 break;
12784 case 'e':
12785 edit_only = 1;
12786 break;
12787 case 'F':
12788 edit_script_path = optarg;
12789 break;
12790 case 'f':
12791 fold_only = 1;
12792 break;
12793 case 'l':
12794 list_backups = 1;
12795 break;
12796 case 'm':
12797 edit_logmsg_only = 1;
12798 break;
12799 case 'X':
12800 delete_backups = 1;
12801 break;
12802 default:
12803 usage_histedit();
12804 /* NOTREACHED */
12808 argc -= optind;
12809 argv += optind;
12811 if (abort_edit && allow_conflict)
12812 option_conflict('a', 'C');
12813 if (abort_edit && continue_edit)
12814 option_conflict('a', 'c');
12815 if (edit_script_path && allow_conflict)
12816 option_conflict('F', 'C');
12817 if (edit_script_path && edit_logmsg_only)
12818 option_conflict('F', 'm');
12819 if (abort_edit && edit_logmsg_only)
12820 option_conflict('a', 'm');
12821 if (edit_logmsg_only && allow_conflict)
12822 option_conflict('m', 'C');
12823 if (continue_edit && edit_logmsg_only)
12824 option_conflict('c', 'm');
12825 if (abort_edit && fold_only)
12826 option_conflict('a', 'f');
12827 if (fold_only && allow_conflict)
12828 option_conflict('f', 'C');
12829 if (continue_edit && fold_only)
12830 option_conflict('c', 'f');
12831 if (fold_only && edit_logmsg_only)
12832 option_conflict('f', 'm');
12833 if (edit_script_path && fold_only)
12834 option_conflict('F', 'f');
12835 if (abort_edit && edit_only)
12836 option_conflict('a', 'e');
12837 if (continue_edit && edit_only)
12838 option_conflict('c', 'e');
12839 if (edit_only && edit_logmsg_only)
12840 option_conflict('e', 'm');
12841 if (edit_script_path && edit_only)
12842 option_conflict('F', 'e');
12843 if (fold_only && edit_only)
12844 option_conflict('f', 'e');
12845 if (drop_only && abort_edit)
12846 option_conflict('d', 'a');
12847 if (drop_only && allow_conflict)
12848 option_conflict('d', 'C');
12849 if (drop_only && continue_edit)
12850 option_conflict('d', 'c');
12851 if (drop_only && edit_logmsg_only)
12852 option_conflict('d', 'm');
12853 if (drop_only && edit_only)
12854 option_conflict('d', 'e');
12855 if (drop_only && edit_script_path)
12856 option_conflict('d', 'F');
12857 if (drop_only && fold_only)
12858 option_conflict('d', 'f');
12859 if (list_backups) {
12860 if (abort_edit)
12861 option_conflict('l', 'a');
12862 if (allow_conflict)
12863 option_conflict('l', 'C');
12864 if (continue_edit)
12865 option_conflict('l', 'c');
12866 if (edit_script_path)
12867 option_conflict('l', 'F');
12868 if (edit_logmsg_only)
12869 option_conflict('l', 'm');
12870 if (drop_only)
12871 option_conflict('l', 'd');
12872 if (fold_only)
12873 option_conflict('l', 'f');
12874 if (edit_only)
12875 option_conflict('l', 'e');
12876 if (delete_backups)
12877 option_conflict('l', 'X');
12878 if (argc != 0 && argc != 1)
12879 usage_histedit();
12880 } else if (delete_backups) {
12881 if (abort_edit)
12882 option_conflict('X', 'a');
12883 if (allow_conflict)
12884 option_conflict('X', 'C');
12885 if (continue_edit)
12886 option_conflict('X', 'c');
12887 if (drop_only)
12888 option_conflict('X', 'd');
12889 if (edit_script_path)
12890 option_conflict('X', 'F');
12891 if (edit_logmsg_only)
12892 option_conflict('X', 'm');
12893 if (fold_only)
12894 option_conflict('X', 'f');
12895 if (edit_only)
12896 option_conflict('X', 'e');
12897 if (list_backups)
12898 option_conflict('X', 'l');
12899 if (argc != 0 && argc != 1)
12900 usage_histedit();
12901 } else if (allow_conflict && !continue_edit)
12902 errx(1, "-C option requires -c");
12903 else if (argc != 0)
12904 usage_histedit();
12906 cwd = getcwd(NULL, 0);
12907 if (cwd == NULL) {
12908 error = got_error_from_errno("getcwd");
12909 goto done;
12912 error = got_repo_pack_fds_open(&pack_fds);
12913 if (error != NULL)
12914 goto done;
12916 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12917 if (error) {
12918 if (list_backups || delete_backups) {
12919 if (error->code != GOT_ERR_NOT_WORKTREE)
12920 goto done;
12921 } else {
12922 if (error->code == GOT_ERR_NOT_WORKTREE)
12923 error = wrap_not_worktree_error(error,
12924 "histedit", cwd);
12925 goto done;
12929 if (list_backups || delete_backups) {
12930 error = got_repo_open(&repo,
12931 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12932 NULL, pack_fds);
12933 if (error != NULL)
12934 goto done;
12935 error = apply_unveil(got_repo_get_path(repo), 0,
12936 worktree ? got_worktree_get_root_path(worktree) : NULL);
12937 if (error)
12938 goto done;
12939 error = process_backup_refs(
12940 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12941 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12942 goto done; /* nothing else to do */
12943 } else {
12944 error = get_gitconfig_path(&gitconfig_path);
12945 if (error)
12946 goto done;
12947 error = got_repo_open(&repo,
12948 got_worktree_get_repo_path(worktree), gitconfig_path,
12949 pack_fds);
12950 if (error != NULL)
12951 goto done;
12952 error = get_editor(&editor);
12953 if (error)
12954 goto done;
12955 if (unveil(editor, "x") != 0) {
12956 error = got_error_from_errno2("unveil", editor);
12957 goto done;
12959 if (edit_script_path) {
12960 if (unveil(edit_script_path, "r") != 0) {
12961 error = got_error_from_errno2("unveil",
12962 edit_script_path);
12963 goto done;
12966 error = apply_unveil(got_repo_get_path(repo), 0,
12967 got_worktree_get_root_path(worktree));
12968 if (error)
12969 goto done;
12972 if (worktree != NULL && !list_backups && !delete_backups) {
12973 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12974 if (error)
12975 goto done;
12978 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12979 if (error)
12980 goto done;
12981 if (rebase_in_progress) {
12982 error = got_error(GOT_ERR_REBASING);
12983 goto done;
12986 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12987 repo);
12988 if (error)
12989 goto done;
12990 if (merge_in_progress) {
12991 error = got_error(GOT_ERR_MERGE_BUSY);
12992 goto done;
12995 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12996 if (error)
12997 goto done;
12999 if (edit_in_progress && edit_logmsg_only) {
13000 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
13001 "histedit operation is in progress in this "
13002 "work tree and must be continued or aborted "
13003 "before the -m option can be used");
13004 goto done;
13006 if (edit_in_progress && drop_only) {
13007 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
13008 "histedit operation is in progress in this "
13009 "work tree and must be continued or aborted "
13010 "before the -d option can be used");
13011 goto done;
13013 if (edit_in_progress && fold_only) {
13014 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
13015 "histedit operation is in progress in this "
13016 "work tree and must be continued or aborted "
13017 "before the -f option can be used");
13018 goto done;
13020 if (edit_in_progress && edit_only) {
13021 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
13022 "histedit operation is in progress in this "
13023 "work tree and must be continued or aborted "
13024 "before the -e option can be used");
13025 goto done;
13028 if (edit_in_progress && abort_edit) {
13029 error = got_worktree_histedit_continue(&resume_commit_id,
13030 &tmp_branch, &branch, &base_commit_id, &fileindex,
13031 worktree, repo);
13032 if (error)
13033 goto done;
13034 printf("Switching work tree to %s\n",
13035 got_ref_get_symref_target(branch));
13036 error = got_worktree_histedit_abort(worktree, fileindex, repo,
13037 branch, base_commit_id, abort_progress, &upa);
13038 if (error)
13039 goto done;
13040 printf("Histedit of %s aborted\n",
13041 got_ref_get_symref_target(branch));
13042 print_merge_progress_stats(&upa);
13043 goto done; /* nothing else to do */
13044 } else if (abort_edit) {
13045 error = got_error(GOT_ERR_NOT_HISTEDIT);
13046 goto done;
13049 error = get_author(&committer, repo, worktree);
13050 if (error)
13051 goto done;
13053 if (continue_edit) {
13054 char *path;
13056 if (!edit_in_progress) {
13057 error = got_error(GOT_ERR_NOT_HISTEDIT);
13058 goto done;
13061 error = got_worktree_get_histedit_script_path(&path, worktree);
13062 if (error)
13063 goto done;
13065 error = histedit_load_list(&histedit_cmds, path, repo);
13066 free(path);
13067 if (error)
13068 goto done;
13070 error = got_worktree_histedit_continue(&resume_commit_id,
13071 &tmp_branch, &branch, &base_commit_id, &fileindex,
13072 worktree, repo);
13073 if (error)
13074 goto done;
13076 error = got_ref_resolve(&head_commit_id, repo, branch);
13077 if (error)
13078 goto done;
13080 error = got_object_open_as_commit(&commit, repo,
13081 head_commit_id);
13082 if (error)
13083 goto done;
13084 parent_ids = got_object_commit_get_parent_ids(commit);
13085 pid = STAILQ_FIRST(parent_ids);
13086 if (pid == NULL) {
13087 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13088 goto done;
13090 error = collect_commits(&commits, head_commit_id, &pid->id,
13091 base_commit_id, got_worktree_get_path_prefix(worktree),
13092 GOT_ERR_HISTEDIT_PATH, repo);
13093 got_object_commit_close(commit);
13094 commit = NULL;
13095 if (error)
13096 goto done;
13097 } else {
13098 if (edit_in_progress) {
13099 error = got_error(GOT_ERR_HISTEDIT_BUSY);
13100 goto done;
13103 error = got_ref_open(&branch, repo,
13104 got_worktree_get_head_ref_name(worktree), 0);
13105 if (error != NULL)
13106 goto done;
13108 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
13109 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
13110 "will not edit commit history of a branch outside "
13111 "the \"refs/heads/\" reference namespace");
13112 goto done;
13115 error = got_ref_resolve(&head_commit_id, repo, branch);
13116 got_ref_close(branch);
13117 branch = NULL;
13118 if (error)
13119 goto done;
13121 error = got_object_open_as_commit(&commit, repo,
13122 head_commit_id);
13123 if (error)
13124 goto done;
13125 parent_ids = got_object_commit_get_parent_ids(commit);
13126 pid = STAILQ_FIRST(parent_ids);
13127 if (pid == NULL) {
13128 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13129 goto done;
13131 error = collect_commits(&commits, head_commit_id, &pid->id,
13132 got_worktree_get_base_commit_id(worktree),
13133 got_worktree_get_path_prefix(worktree),
13134 GOT_ERR_HISTEDIT_PATH, repo);
13135 got_object_commit_close(commit);
13136 commit = NULL;
13137 if (error)
13138 goto done;
13140 if (STAILQ_EMPTY(&commits)) {
13141 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13142 goto done;
13145 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
13146 &base_commit_id, &fileindex, worktree, repo);
13147 if (error)
13148 goto done;
13150 if (edit_script_path) {
13151 error = histedit_load_list(&histedit_cmds,
13152 edit_script_path, repo);
13153 if (error) {
13154 got_worktree_histedit_abort(worktree, fileindex,
13155 repo, branch, base_commit_id,
13156 abort_progress, &upa);
13157 print_merge_progress_stats(&upa);
13158 goto done;
13160 } else {
13161 const char *branch_name;
13162 branch_name = got_ref_get_symref_target(branch);
13163 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13164 branch_name += 11;
13165 error = histedit_edit_script(&histedit_cmds, &commits,
13166 branch_name, edit_logmsg_only, fold_only,
13167 drop_only, edit_only, editor, repo);
13168 if (error) {
13169 got_worktree_histedit_abort(worktree, fileindex,
13170 repo, branch, base_commit_id,
13171 abort_progress, &upa);
13172 print_merge_progress_stats(&upa);
13173 goto done;
13178 error = histedit_save_list(&histedit_cmds, worktree,
13179 repo);
13180 if (error) {
13181 got_worktree_histedit_abort(worktree, fileindex,
13182 repo, branch, base_commit_id,
13183 abort_progress, &upa);
13184 print_merge_progress_stats(&upa);
13185 goto done;
13190 error = histedit_check_script(&histedit_cmds, &commits, repo);
13191 if (error)
13192 goto done;
13194 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13195 if (resume_commit_id) {
13196 if (got_object_id_cmp(hle->commit_id,
13197 resume_commit_id) != 0)
13198 continue;
13200 resume_commit_id = NULL;
13201 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13202 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13203 error = histedit_skip_commit(hle, worktree,
13204 repo);
13205 if (error)
13206 goto done;
13207 } else {
13208 struct got_pathlist_head paths;
13209 int have_changes = 0;
13211 TAILQ_INIT(&paths);
13212 error = got_pathlist_append(&paths, "", NULL);
13213 if (error)
13214 goto done;
13215 error = got_worktree_status(worktree, &paths,
13216 repo, 0, check_local_changes, &have_changes,
13217 check_cancelled, NULL);
13218 got_pathlist_free(&paths,
13219 GOT_PATHLIST_FREE_NONE);
13220 if (error) {
13221 if (error->code != GOT_ERR_CANCELLED)
13222 goto done;
13223 if (sigint_received || sigpipe_received)
13224 goto done;
13226 if (have_changes) {
13227 error = histedit_commit(NULL, worktree,
13228 fileindex, tmp_branch, hle,
13229 committer, allow_conflict, editor,
13230 repo);
13231 if (error)
13232 goto done;
13233 } else {
13234 error = histedit_skip_commit(hle,
13235 worktree, repo);
13236 if (error)
13237 goto done;
13240 continue;
13243 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13244 error = histedit_skip_commit(hle, worktree, repo);
13245 if (error)
13246 goto done;
13247 continue;
13249 error = got_object_open_as_commit(&commit, repo,
13250 hle->commit_id);
13251 if (error)
13252 goto done;
13253 parent_ids = got_object_commit_get_parent_ids(commit);
13254 pid = STAILQ_FIRST(parent_ids);
13256 error = got_worktree_histedit_merge_files(&merged_paths,
13257 worktree, fileindex, &pid->id, hle->commit_id, repo,
13258 update_progress, &upa, check_cancelled, NULL);
13259 if (error)
13260 goto done;
13261 got_object_commit_close(commit);
13262 commit = NULL;
13264 print_merge_progress_stats(&upa);
13265 if (upa.conflicts > 0 || upa.missing > 0 ||
13266 upa.not_deleted > 0 || upa.unversioned > 0) {
13267 if (upa.conflicts > 0) {
13268 error = show_rebase_merge_conflict(
13269 hle->commit_id, repo);
13270 if (error)
13271 goto done;
13273 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13274 break;
13277 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13278 char *id_str;
13279 error = got_object_id_str(&id_str, hle->commit_id);
13280 if (error)
13281 goto done;
13282 printf("Stopping histedit for amending commit %s\n",
13283 id_str);
13284 free(id_str);
13285 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13286 error = got_worktree_histedit_postpone(worktree,
13287 fileindex);
13288 goto done;
13289 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13290 error = histedit_skip_commit(hle, worktree, repo);
13291 if (error)
13292 goto done;
13293 continue;
13294 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13295 error = histedit_edit_logmsg(hle, editor, repo);
13296 if (error)
13297 goto done;
13300 error = histedit_commit(&merged_paths, worktree, fileindex,
13301 tmp_branch, hle, committer, allow_conflict, editor, repo);
13302 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13303 if (error)
13304 goto done;
13307 if (upa.conflicts > 0 || upa.missing > 0 ||
13308 upa.not_deleted > 0 || upa.unversioned > 0) {
13309 error = got_worktree_histedit_postpone(worktree, fileindex);
13310 if (error)
13311 goto done;
13312 if (upa.conflicts > 0 && upa.missing == 0 &&
13313 upa.not_deleted == 0 && upa.unversioned == 0) {
13314 error = got_error_msg(GOT_ERR_CONFLICTS,
13315 "conflicts must be resolved before histedit "
13316 "can continue");
13317 } else if (upa.conflicts > 0) {
13318 error = got_error_msg(GOT_ERR_CONFLICTS,
13319 "conflicts must be resolved before histedit "
13320 "can continue; changes destined for some "
13321 "files were not yet merged and should be "
13322 "merged manually if required before the "
13323 "histedit operation is continued");
13324 } else {
13325 error = got_error_msg(GOT_ERR_CONFLICTS,
13326 "changes destined for some files were not "
13327 "yet merged and should be merged manually "
13328 "if required before the histedit operation "
13329 "is continued");
13331 } else
13332 error = histedit_complete(worktree, fileindex, tmp_branch,
13333 branch, repo);
13334 done:
13335 free(cwd);
13336 free(editor);
13337 free(committer);
13338 free(gitconfig_path);
13339 got_object_id_queue_free(&commits);
13340 histedit_free_list(&histedit_cmds);
13341 free(head_commit_id);
13342 free(base_commit_id);
13343 free(resume_commit_id);
13344 if (commit)
13345 got_object_commit_close(commit);
13346 if (branch)
13347 got_ref_close(branch);
13348 if (tmp_branch)
13349 got_ref_close(tmp_branch);
13350 if (worktree)
13351 got_worktree_close(worktree);
13352 if (repo) {
13353 const struct got_error *close_err = got_repo_close(repo);
13354 if (error == NULL)
13355 error = close_err;
13357 if (pack_fds) {
13358 const struct got_error *pack_err =
13359 got_repo_pack_fds_close(pack_fds);
13360 if (error == NULL)
13361 error = pack_err;
13363 return error;
13366 __dead static void
13367 usage_integrate(void)
13369 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13370 exit(1);
13373 static const struct got_error *
13374 cmd_integrate(int argc, char *argv[])
13376 const struct got_error *error = NULL;
13377 struct got_repository *repo = NULL;
13378 struct got_worktree *worktree = NULL;
13379 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13380 const char *branch_arg = NULL;
13381 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13382 struct got_fileindex *fileindex = NULL;
13383 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13384 int ch;
13385 struct got_update_progress_arg upa;
13386 int *pack_fds = NULL;
13388 #ifndef PROFILE
13389 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13390 "unveil", NULL) == -1)
13391 err(1, "pledge");
13392 #endif
13394 while ((ch = getopt(argc, argv, "")) != -1) {
13395 switch (ch) {
13396 default:
13397 usage_integrate();
13398 /* NOTREACHED */
13402 argc -= optind;
13403 argv += optind;
13405 if (argc != 1)
13406 usage_integrate();
13407 branch_arg = argv[0];
13409 cwd = getcwd(NULL, 0);
13410 if (cwd == NULL) {
13411 error = got_error_from_errno("getcwd");
13412 goto done;
13415 error = got_repo_pack_fds_open(&pack_fds);
13416 if (error != NULL)
13417 goto done;
13419 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13420 if (error) {
13421 if (error->code == GOT_ERR_NOT_WORKTREE)
13422 error = wrap_not_worktree_error(error, "integrate",
13423 cwd);
13424 goto done;
13427 error = check_rebase_or_histedit_in_progress(worktree);
13428 if (error)
13429 goto done;
13431 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13432 NULL, pack_fds);
13433 if (error != NULL)
13434 goto done;
13436 error = apply_unveil(got_repo_get_path(repo), 0,
13437 got_worktree_get_root_path(worktree));
13438 if (error)
13439 goto done;
13441 error = check_merge_in_progress(worktree, repo);
13442 if (error)
13443 goto done;
13445 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13446 error = got_error_from_errno("asprintf");
13447 goto done;
13450 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13451 &base_branch_ref, worktree, refname, repo);
13452 if (error)
13453 goto done;
13455 refname = strdup(got_ref_get_name(branch_ref));
13456 if (refname == NULL) {
13457 error = got_error_from_errno("strdup");
13458 got_worktree_integrate_abort(worktree, fileindex, repo,
13459 branch_ref, base_branch_ref);
13460 goto done;
13462 base_refname = strdup(got_ref_get_name(base_branch_ref));
13463 if (base_refname == NULL) {
13464 error = got_error_from_errno("strdup");
13465 got_worktree_integrate_abort(worktree, fileindex, repo,
13466 branch_ref, base_branch_ref);
13467 goto done;
13469 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13470 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13471 got_worktree_integrate_abort(worktree, fileindex, repo,
13472 branch_ref, base_branch_ref);
13473 goto done;
13476 error = got_ref_resolve(&commit_id, repo, branch_ref);
13477 if (error)
13478 goto done;
13480 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13481 if (error)
13482 goto done;
13484 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13485 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13486 "specified branch has already been integrated");
13487 got_worktree_integrate_abort(worktree, fileindex, repo,
13488 branch_ref, base_branch_ref);
13489 goto done;
13492 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13493 if (error) {
13494 if (error->code == GOT_ERR_ANCESTRY)
13495 error = got_error(GOT_ERR_REBASE_REQUIRED);
13496 got_worktree_integrate_abort(worktree, fileindex, repo,
13497 branch_ref, base_branch_ref);
13498 goto done;
13501 memset(&upa, 0, sizeof(upa));
13502 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13503 branch_ref, base_branch_ref, update_progress, &upa,
13504 check_cancelled, NULL);
13505 if (error)
13506 goto done;
13508 printf("Integrated %s into %s\n", refname, base_refname);
13509 print_update_progress_stats(&upa);
13510 done:
13511 if (repo) {
13512 const struct got_error *close_err = got_repo_close(repo);
13513 if (error == NULL)
13514 error = close_err;
13516 if (worktree)
13517 got_worktree_close(worktree);
13518 if (pack_fds) {
13519 const struct got_error *pack_err =
13520 got_repo_pack_fds_close(pack_fds);
13521 if (error == NULL)
13522 error = pack_err;
13524 free(cwd);
13525 free(base_commit_id);
13526 free(commit_id);
13527 free(refname);
13528 free(base_refname);
13529 return error;
13532 __dead static void
13533 usage_merge(void)
13535 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13536 exit(1);
13539 static const struct got_error *
13540 cmd_merge(int argc, char *argv[])
13542 const struct got_error *error = NULL;
13543 struct got_worktree *worktree = NULL;
13544 struct got_repository *repo = NULL;
13545 struct got_fileindex *fileindex = NULL;
13546 char *cwd = NULL, *id_str = NULL, *author = NULL;
13547 char *gitconfig_path = NULL;
13548 struct got_reference *branch = NULL, *wt_branch = NULL;
13549 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13550 struct got_object_id *wt_branch_tip = NULL;
13551 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13552 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13553 struct got_update_progress_arg upa;
13554 struct got_object_id *merge_commit_id = NULL;
13555 char *branch_name = NULL;
13556 int *pack_fds = NULL;
13558 memset(&upa, 0, sizeof(upa));
13560 #ifndef PROFILE
13561 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13562 "unveil", NULL) == -1)
13563 err(1, "pledge");
13564 #endif
13566 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13567 switch (ch) {
13568 case 'a':
13569 abort_merge = 1;
13570 break;
13571 case 'C':
13572 allow_conflict = 1;
13573 break;
13574 case 'c':
13575 continue_merge = 1;
13576 break;
13577 case 'M':
13578 prefer_fast_forward = 0;
13579 break;
13580 case 'n':
13581 interrupt_merge = 1;
13582 break;
13583 default:
13584 usage_merge();
13585 /* NOTREACHED */
13589 argc -= optind;
13590 argv += optind;
13592 if (abort_merge) {
13593 if (continue_merge)
13594 option_conflict('a', 'c');
13595 if (!prefer_fast_forward)
13596 option_conflict('a', 'M');
13597 if (interrupt_merge)
13598 option_conflict('a', 'n');
13599 } else if (continue_merge) {
13600 if (!prefer_fast_forward)
13601 option_conflict('c', 'M');
13602 if (interrupt_merge)
13603 option_conflict('c', 'n');
13605 if (allow_conflict) {
13606 if (!continue_merge)
13607 errx(1, "-C option requires -c");
13609 if (abort_merge || continue_merge) {
13610 if (argc != 0)
13611 usage_merge();
13612 } else if (argc != 1)
13613 usage_merge();
13615 cwd = getcwd(NULL, 0);
13616 if (cwd == NULL) {
13617 error = got_error_from_errno("getcwd");
13618 goto done;
13621 error = got_repo_pack_fds_open(&pack_fds);
13622 if (error != NULL)
13623 goto done;
13625 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13626 if (error) {
13627 if (error->code == GOT_ERR_NOT_WORKTREE)
13628 error = wrap_not_worktree_error(error,
13629 "merge", cwd);
13630 goto done;
13633 error = get_gitconfig_path(&gitconfig_path);
13634 if (error)
13635 goto done;
13636 error = got_repo_open(&repo,
13637 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13638 gitconfig_path, pack_fds);
13639 if (error != NULL)
13640 goto done;
13642 if (worktree != NULL) {
13643 error = worktree_has_logmsg_ref("merge", worktree, repo);
13644 if (error)
13645 goto done;
13648 error = apply_unveil(got_repo_get_path(repo), 0,
13649 worktree ? got_worktree_get_root_path(worktree) : NULL);
13650 if (error)
13651 goto done;
13653 error = check_rebase_or_histedit_in_progress(worktree);
13654 if (error)
13655 goto done;
13657 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13658 repo);
13659 if (error)
13660 goto done;
13662 if (merge_in_progress && !(abort_merge || continue_merge)) {
13663 error = got_error(GOT_ERR_MERGE_BUSY);
13664 goto done;
13667 if (!merge_in_progress && (abort_merge || continue_merge)) {
13668 error = got_error(GOT_ERR_NOT_MERGING);
13669 goto done;
13672 if (abort_merge) {
13673 error = got_worktree_merge_continue(&branch_name,
13674 &branch_tip, &fileindex, worktree, repo);
13675 if (error)
13676 goto done;
13677 error = got_worktree_merge_abort(worktree, fileindex, repo,
13678 abort_progress, &upa);
13679 if (error)
13680 goto done;
13681 printf("Merge of %s aborted\n", branch_name);
13682 goto done; /* nothing else to do */
13685 if (strncmp(got_worktree_get_head_ref_name(worktree),
13686 "refs/heads/", 11) != 0) {
13687 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13688 "work tree's current branch %s is outside the "
13689 "\"refs/heads/\" reference namespace; "
13690 "update -b required",
13691 got_worktree_get_head_ref_name(worktree));
13692 goto done;
13695 error = get_author(&author, repo, worktree);
13696 if (error)
13697 goto done;
13699 error = got_ref_open(&wt_branch, repo,
13700 got_worktree_get_head_ref_name(worktree), 0);
13701 if (error)
13702 goto done;
13703 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13704 if (error)
13705 goto done;
13707 if (continue_merge) {
13708 struct got_object_id *base_commit_id;
13709 base_commit_id = got_worktree_get_base_commit_id(worktree);
13710 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13711 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13712 goto done;
13714 error = got_worktree_merge_continue(&branch_name,
13715 &branch_tip, &fileindex, worktree, repo);
13716 if (error)
13717 goto done;
13718 } else {
13719 error = got_ref_open(&branch, repo, argv[0], 0);
13720 if (error != NULL)
13721 goto done;
13722 branch_name = strdup(got_ref_get_name(branch));
13723 if (branch_name == NULL) {
13724 error = got_error_from_errno("strdup");
13725 goto done;
13727 error = got_ref_resolve(&branch_tip, repo, branch);
13728 if (error)
13729 goto done;
13732 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13733 wt_branch_tip, branch_tip, 0, 0, repo,
13734 check_cancelled, NULL);
13735 if (error && error->code != GOT_ERR_ANCESTRY)
13736 goto done;
13738 if (!continue_merge) {
13739 error = check_path_prefix(wt_branch_tip, branch_tip,
13740 got_worktree_get_path_prefix(worktree),
13741 GOT_ERR_MERGE_PATH, repo);
13742 if (error)
13743 goto done;
13744 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13745 if (error)
13746 goto done;
13747 if (prefer_fast_forward && yca_id &&
13748 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13749 struct got_pathlist_head paths;
13750 if (interrupt_merge) {
13751 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13752 "there are no changes to merge since %s "
13753 "is already based on %s; merge cannot be "
13754 "interrupted for amending; -n",
13755 branch_name, got_ref_get_name(wt_branch));
13756 goto done;
13758 printf("Forwarding %s to %s\n",
13759 got_ref_get_name(wt_branch), branch_name);
13760 error = got_ref_change_ref(wt_branch, branch_tip);
13761 if (error)
13762 goto done;
13763 error = got_ref_write(wt_branch, repo);
13764 if (error)
13765 goto done;
13766 error = got_worktree_set_base_commit_id(worktree, repo,
13767 branch_tip);
13768 if (error)
13769 goto done;
13770 TAILQ_INIT(&paths);
13771 error = got_pathlist_append(&paths, "", NULL);
13772 if (error)
13773 goto done;
13774 error = got_worktree_checkout_files(worktree,
13775 &paths, repo, update_progress, &upa,
13776 check_cancelled, NULL);
13777 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13778 if (error)
13779 goto done;
13780 if (upa.did_something) {
13781 char *id_str;
13782 error = got_object_id_str(&id_str, branch_tip);
13783 if (error)
13784 goto done;
13785 printf("Updated to commit %s\n", id_str);
13786 free(id_str);
13787 } else
13788 printf("Already up-to-date\n");
13789 print_update_progress_stats(&upa);
13790 goto done;
13792 error = got_worktree_merge_write_refs(worktree, branch, repo);
13793 if (error)
13794 goto done;
13796 error = got_worktree_merge_branch(worktree, fileindex,
13797 yca_id, branch_tip, repo, update_progress, &upa,
13798 check_cancelled, NULL);
13799 if (error)
13800 goto done;
13801 print_merge_progress_stats(&upa);
13802 if (!upa.did_something) {
13803 error = got_worktree_merge_abort(worktree, fileindex,
13804 repo, abort_progress, &upa);
13805 if (error)
13806 goto done;
13807 printf("Already up-to-date\n");
13808 goto done;
13812 if (interrupt_merge) {
13813 error = got_worktree_merge_postpone(worktree, fileindex);
13814 if (error)
13815 goto done;
13816 printf("Merge of %s interrupted on request\n", branch_name);
13817 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13818 upa.not_deleted > 0 || upa.unversioned > 0) {
13819 error = got_worktree_merge_postpone(worktree, fileindex);
13820 if (error)
13821 goto done;
13822 if (upa.conflicts > 0 && upa.missing == 0 &&
13823 upa.not_deleted == 0 && upa.unversioned == 0) {
13824 error = got_error_msg(GOT_ERR_CONFLICTS,
13825 "conflicts must be resolved before merging "
13826 "can continue");
13827 } else if (upa.conflicts > 0) {
13828 error = got_error_msg(GOT_ERR_CONFLICTS,
13829 "conflicts must be resolved before merging "
13830 "can continue; changes destined for some "
13831 "files were not yet merged and "
13832 "should be merged manually if required before the "
13833 "merge operation is continued");
13834 } else {
13835 error = got_error_msg(GOT_ERR_CONFLICTS,
13836 "changes destined for some "
13837 "files were not yet merged and should be "
13838 "merged manually if required before the "
13839 "merge operation is continued");
13841 goto done;
13842 } else {
13843 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13844 fileindex, author, NULL, 1, branch_tip, branch_name,
13845 allow_conflict, repo, continue_merge ? print_status : NULL,
13846 NULL);
13847 if (error)
13848 goto done;
13849 error = got_worktree_merge_complete(worktree, fileindex, repo);
13850 if (error)
13851 goto done;
13852 error = got_object_id_str(&id_str, merge_commit_id);
13853 if (error)
13854 goto done;
13855 printf("Merged %s into %s: %s\n", branch_name,
13856 got_worktree_get_head_ref_name(worktree),
13857 id_str);
13860 done:
13861 free(cwd);
13862 free(gitconfig_path);
13863 free(id_str);
13864 free(merge_commit_id);
13865 free(author);
13866 free(branch_tip);
13867 free(branch_name);
13868 free(yca_id);
13869 if (branch)
13870 got_ref_close(branch);
13871 if (wt_branch)
13872 got_ref_close(wt_branch);
13873 if (worktree)
13874 got_worktree_close(worktree);
13875 if (repo) {
13876 const struct got_error *close_err = got_repo_close(repo);
13877 if (error == NULL)
13878 error = close_err;
13880 if (pack_fds) {
13881 const struct got_error *pack_err =
13882 got_repo_pack_fds_close(pack_fds);
13883 if (error == NULL)
13884 error = pack_err;
13886 return error;
13889 __dead static void
13890 usage_stage(void)
13892 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13893 "[path ...]\n", getprogname());
13894 exit(1);
13897 static const struct got_error *
13898 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13899 const char *path, struct got_object_id *blob_id,
13900 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13901 int dirfd, const char *de_name)
13903 const struct got_error *err = NULL;
13904 char *id_str = NULL;
13906 if (staged_status != GOT_STATUS_ADD &&
13907 staged_status != GOT_STATUS_MODIFY &&
13908 staged_status != GOT_STATUS_DELETE)
13909 return NULL;
13911 if (staged_status == GOT_STATUS_ADD ||
13912 staged_status == GOT_STATUS_MODIFY)
13913 err = got_object_id_str(&id_str, staged_blob_id);
13914 else
13915 err = got_object_id_str(&id_str, blob_id);
13916 if (err)
13917 return err;
13919 printf("%s %c %s\n", id_str, staged_status, path);
13920 free(id_str);
13921 return NULL;
13924 static const struct got_error *
13925 cmd_stage(int argc, char *argv[])
13927 const struct got_error *error = NULL;
13928 struct got_repository *repo = NULL;
13929 struct got_worktree *worktree = NULL;
13930 char *cwd = NULL;
13931 struct got_pathlist_head paths;
13932 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13933 FILE *patch_script_file = NULL;
13934 const char *patch_script_path = NULL;
13935 struct choose_patch_arg cpa;
13936 int *pack_fds = NULL;
13938 TAILQ_INIT(&paths);
13940 #ifndef PROFILE
13941 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13942 "unveil", NULL) == -1)
13943 err(1, "pledge");
13944 #endif
13946 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13947 switch (ch) {
13948 case 'F':
13949 patch_script_path = optarg;
13950 break;
13951 case 'l':
13952 list_stage = 1;
13953 break;
13954 case 'p':
13955 pflag = 1;
13956 break;
13957 case 'S':
13958 allow_bad_symlinks = 1;
13959 break;
13960 default:
13961 usage_stage();
13962 /* NOTREACHED */
13966 argc -= optind;
13967 argv += optind;
13969 if (list_stage && (pflag || patch_script_path))
13970 errx(1, "-l option cannot be used with other options");
13971 if (patch_script_path && !pflag)
13972 errx(1, "-F option can only be used together with -p option");
13974 cwd = getcwd(NULL, 0);
13975 if (cwd == NULL) {
13976 error = got_error_from_errno("getcwd");
13977 goto done;
13980 error = got_repo_pack_fds_open(&pack_fds);
13981 if (error != NULL)
13982 goto done;
13984 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13985 if (error) {
13986 if (error->code == GOT_ERR_NOT_WORKTREE)
13987 error = wrap_not_worktree_error(error, "stage", cwd);
13988 goto done;
13991 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13992 NULL, pack_fds);
13993 if (error != NULL)
13994 goto done;
13996 if (patch_script_path) {
13997 patch_script_file = fopen(patch_script_path, "re");
13998 if (patch_script_file == NULL) {
13999 error = got_error_from_errno2("fopen",
14000 patch_script_path);
14001 goto done;
14004 error = apply_unveil(got_repo_get_path(repo), 0,
14005 got_worktree_get_root_path(worktree));
14006 if (error)
14007 goto done;
14009 error = check_merge_in_progress(worktree, repo);
14010 if (error)
14011 goto done;
14013 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14014 if (error)
14015 goto done;
14017 if (list_stage)
14018 error = got_worktree_status(worktree, &paths, repo, 0,
14019 print_stage, NULL, check_cancelled, NULL);
14020 else {
14021 cpa.patch_script_file = patch_script_file;
14022 cpa.action = "stage";
14023 error = got_worktree_stage(worktree, &paths,
14024 pflag ? NULL : print_status, NULL,
14025 pflag ? choose_patch : NULL, &cpa,
14026 allow_bad_symlinks, repo);
14028 done:
14029 if (patch_script_file && fclose(patch_script_file) == EOF &&
14030 error == NULL)
14031 error = got_error_from_errno2("fclose", patch_script_path);
14032 if (repo) {
14033 const struct got_error *close_err = got_repo_close(repo);
14034 if (error == NULL)
14035 error = close_err;
14037 if (worktree)
14038 got_worktree_close(worktree);
14039 if (pack_fds) {
14040 const struct got_error *pack_err =
14041 got_repo_pack_fds_close(pack_fds);
14042 if (error == NULL)
14043 error = pack_err;
14045 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14046 free(cwd);
14047 return error;
14050 __dead static void
14051 usage_unstage(void)
14053 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
14054 "[path ...]\n", getprogname());
14055 exit(1);
14059 static const struct got_error *
14060 cmd_unstage(int argc, char *argv[])
14062 const struct got_error *error = NULL;
14063 struct got_repository *repo = NULL;
14064 struct got_worktree *worktree = NULL;
14065 char *cwd = NULL;
14066 struct got_pathlist_head paths;
14067 int ch, pflag = 0;
14068 struct got_update_progress_arg upa;
14069 FILE *patch_script_file = NULL;
14070 const char *patch_script_path = NULL;
14071 struct choose_patch_arg cpa;
14072 int *pack_fds = NULL;
14074 TAILQ_INIT(&paths);
14076 #ifndef PROFILE
14077 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
14078 "unveil", NULL) == -1)
14079 err(1, "pledge");
14080 #endif
14082 while ((ch = getopt(argc, argv, "F:p")) != -1) {
14083 switch (ch) {
14084 case 'F':
14085 patch_script_path = optarg;
14086 break;
14087 case 'p':
14088 pflag = 1;
14089 break;
14090 default:
14091 usage_unstage();
14092 /* NOTREACHED */
14096 argc -= optind;
14097 argv += optind;
14099 if (patch_script_path && !pflag)
14100 errx(1, "-F option can only be used together with -p option");
14102 cwd = getcwd(NULL, 0);
14103 if (cwd == NULL) {
14104 error = got_error_from_errno("getcwd");
14105 goto done;
14108 error = got_repo_pack_fds_open(&pack_fds);
14109 if (error != NULL)
14110 goto done;
14112 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14113 if (error) {
14114 if (error->code == GOT_ERR_NOT_WORKTREE)
14115 error = wrap_not_worktree_error(error, "unstage", cwd);
14116 goto done;
14119 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
14120 NULL, pack_fds);
14121 if (error != NULL)
14122 goto done;
14124 if (patch_script_path) {
14125 patch_script_file = fopen(patch_script_path, "re");
14126 if (patch_script_file == NULL) {
14127 error = got_error_from_errno2("fopen",
14128 patch_script_path);
14129 goto done;
14133 error = apply_unveil(got_repo_get_path(repo), 0,
14134 got_worktree_get_root_path(worktree));
14135 if (error)
14136 goto done;
14138 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14139 if (error)
14140 goto done;
14142 cpa.patch_script_file = patch_script_file;
14143 cpa.action = "unstage";
14144 memset(&upa, 0, sizeof(upa));
14145 error = got_worktree_unstage(worktree, &paths, update_progress,
14146 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14147 if (!error)
14148 print_merge_progress_stats(&upa);
14149 done:
14150 if (patch_script_file && fclose(patch_script_file) == EOF &&
14151 error == NULL)
14152 error = got_error_from_errno2("fclose", patch_script_path);
14153 if (repo) {
14154 const struct got_error *close_err = got_repo_close(repo);
14155 if (error == NULL)
14156 error = close_err;
14158 if (worktree)
14159 got_worktree_close(worktree);
14160 if (pack_fds) {
14161 const struct got_error *pack_err =
14162 got_repo_pack_fds_close(pack_fds);
14163 if (error == NULL)
14164 error = pack_err;
14166 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14167 free(cwd);
14168 return error;
14171 __dead static void
14172 usage_cat(void)
14174 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14175 "arg ...\n", getprogname());
14176 exit(1);
14179 static const struct got_error *
14180 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14182 const struct got_error *err;
14183 struct got_blob_object *blob;
14184 int fd = -1;
14186 fd = got_opentempfd();
14187 if (fd == -1)
14188 return got_error_from_errno("got_opentempfd");
14190 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14191 if (err)
14192 goto done;
14194 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14195 done:
14196 if (fd != -1 && close(fd) == -1 && err == NULL)
14197 err = got_error_from_errno("close");
14198 if (blob)
14199 got_object_blob_close(blob);
14200 return err;
14203 static const struct got_error *
14204 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14206 const struct got_error *err;
14207 struct got_tree_object *tree;
14208 int nentries, i;
14210 err = got_object_open_as_tree(&tree, repo, id);
14211 if (err)
14212 return err;
14214 nentries = got_object_tree_get_nentries(tree);
14215 for (i = 0; i < nentries; i++) {
14216 struct got_tree_entry *te;
14217 char *id_str;
14218 if (sigint_received || sigpipe_received)
14219 break;
14220 te = got_object_tree_get_entry(tree, i);
14221 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14222 if (err)
14223 break;
14224 fprintf(outfile, "%s %.7o %s\n", id_str,
14225 got_tree_entry_get_mode(te),
14226 got_tree_entry_get_name(te));
14227 free(id_str);
14230 got_object_tree_close(tree);
14231 return err;
14234 static const struct got_error *
14235 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14237 const struct got_error *err;
14238 struct got_commit_object *commit;
14239 const struct got_object_id_queue *parent_ids;
14240 struct got_object_qid *pid;
14241 char *id_str = NULL;
14242 const char *logmsg = NULL;
14243 char gmtoff[6];
14245 err = got_object_open_as_commit(&commit, repo, id);
14246 if (err)
14247 return err;
14249 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14250 if (err)
14251 goto done;
14253 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14254 parent_ids = got_object_commit_get_parent_ids(commit);
14255 fprintf(outfile, "numparents %d\n",
14256 got_object_commit_get_nparents(commit));
14257 STAILQ_FOREACH(pid, parent_ids, entry) {
14258 char *pid_str;
14259 err = got_object_id_str(&pid_str, &pid->id);
14260 if (err)
14261 goto done;
14262 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14263 free(pid_str);
14265 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14266 got_object_commit_get_author_gmtoff(commit));
14267 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14268 got_object_commit_get_author(commit),
14269 (long long)got_object_commit_get_author_time(commit),
14270 gmtoff);
14272 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14273 got_object_commit_get_committer_gmtoff(commit));
14274 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14275 got_object_commit_get_committer(commit),
14276 (long long)got_object_commit_get_committer_time(commit),
14277 gmtoff);
14279 logmsg = got_object_commit_get_logmsg_raw(commit);
14280 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14281 fprintf(outfile, "%s", logmsg);
14282 done:
14283 free(id_str);
14284 got_object_commit_close(commit);
14285 return err;
14288 static const struct got_error *
14289 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14291 const struct got_error *err;
14292 struct got_tag_object *tag;
14293 char *id_str = NULL;
14294 const char *tagmsg = NULL;
14295 char gmtoff[6];
14297 err = got_object_open_as_tag(&tag, repo, id);
14298 if (err)
14299 return err;
14301 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14302 if (err)
14303 goto done;
14305 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14307 switch (got_object_tag_get_object_type(tag)) {
14308 case GOT_OBJ_TYPE_BLOB:
14309 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14310 GOT_OBJ_LABEL_BLOB);
14311 break;
14312 case GOT_OBJ_TYPE_TREE:
14313 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14314 GOT_OBJ_LABEL_TREE);
14315 break;
14316 case GOT_OBJ_TYPE_COMMIT:
14317 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14318 GOT_OBJ_LABEL_COMMIT);
14319 break;
14320 case GOT_OBJ_TYPE_TAG:
14321 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14322 GOT_OBJ_LABEL_TAG);
14323 break;
14324 default:
14325 break;
14328 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14329 got_object_tag_get_name(tag));
14331 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14332 got_object_tag_get_tagger_gmtoff(tag));
14333 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14334 got_object_tag_get_tagger(tag),
14335 (long long)got_object_tag_get_tagger_time(tag),
14336 gmtoff);
14338 tagmsg = got_object_tag_get_message(tag);
14339 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14340 fprintf(outfile, "%s", tagmsg);
14341 done:
14342 free(id_str);
14343 got_object_tag_close(tag);
14344 return err;
14347 static const struct got_error *
14348 cmd_cat(int argc, char *argv[])
14350 const struct got_error *error;
14351 struct got_repository *repo = NULL;
14352 struct got_worktree *worktree = NULL;
14353 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14354 char *keyword_idstr = NULL;
14355 const char *commit_id_str = NULL;
14356 struct got_object_id *id = NULL, *commit_id = NULL;
14357 struct got_commit_object *commit = NULL;
14358 int ch, obj_type, i, force_path = 0;
14359 struct got_reflist_head refs;
14360 int *pack_fds = NULL;
14362 TAILQ_INIT(&refs);
14364 #ifndef PROFILE
14365 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14366 NULL) == -1)
14367 err(1, "pledge");
14368 #endif
14370 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14371 switch (ch) {
14372 case 'c':
14373 commit_id_str = optarg;
14374 break;
14375 case 'P':
14376 force_path = 1;
14377 break;
14378 case 'r':
14379 repo_path = realpath(optarg, NULL);
14380 if (repo_path == NULL)
14381 return got_error_from_errno2("realpath",
14382 optarg);
14383 got_path_strip_trailing_slashes(repo_path);
14384 break;
14385 default:
14386 usage_cat();
14387 /* NOTREACHED */
14391 argc -= optind;
14392 argv += optind;
14394 cwd = getcwd(NULL, 0);
14395 if (cwd == NULL) {
14396 error = got_error_from_errno("getcwd");
14397 goto done;
14400 error = got_repo_pack_fds_open(&pack_fds);
14401 if (error != NULL)
14402 goto done;
14404 if (repo_path == NULL) {
14405 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14406 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14407 goto done;
14408 if (worktree) {
14409 repo_path = strdup(
14410 got_worktree_get_repo_path(worktree));
14411 if (repo_path == NULL) {
14412 error = got_error_from_errno("strdup");
14413 goto done;
14416 if (commit_id_str == NULL) {
14417 /* Release work tree lock. */
14418 got_worktree_close(worktree);
14419 worktree = NULL;
14424 if (repo_path == NULL) {
14425 repo_path = strdup(cwd);
14426 if (repo_path == NULL)
14427 return got_error_from_errno("strdup");
14430 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14431 free(repo_path);
14432 if (error != NULL)
14433 goto done;
14435 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14436 if (error)
14437 goto done;
14439 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14440 if (error)
14441 goto done;
14443 if (commit_id_str != NULL) {
14444 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14445 repo, worktree);
14446 if (error != NULL)
14447 goto done;
14448 if (keyword_idstr != NULL)
14449 commit_id_str = keyword_idstr;
14450 if (worktree != NULL) {
14451 got_worktree_close(worktree);
14452 worktree = NULL;
14454 } else
14455 commit_id_str = GOT_REF_HEAD;
14456 error = got_repo_match_object_id(&commit_id, NULL,
14457 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14458 if (error)
14459 goto done;
14461 error = got_object_open_as_commit(&commit, repo, commit_id);
14462 if (error)
14463 goto done;
14465 for (i = 0; i < argc; i++) {
14466 if (force_path) {
14467 error = got_object_id_by_path(&id, repo, commit,
14468 argv[i]);
14469 if (error)
14470 break;
14471 } else {
14472 error = got_repo_match_object_id(&id, &label, argv[i],
14473 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14474 repo);
14475 if (error) {
14476 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14477 error->code != GOT_ERR_NOT_REF)
14478 break;
14479 error = got_object_id_by_path(&id, repo,
14480 commit, argv[i]);
14481 if (error)
14482 break;
14486 error = got_object_get_type(&obj_type, repo, id);
14487 if (error)
14488 break;
14490 switch (obj_type) {
14491 case GOT_OBJ_TYPE_BLOB:
14492 error = cat_blob(id, repo, stdout);
14493 break;
14494 case GOT_OBJ_TYPE_TREE:
14495 error = cat_tree(id, repo, stdout);
14496 break;
14497 case GOT_OBJ_TYPE_COMMIT:
14498 error = cat_commit(id, repo, stdout);
14499 break;
14500 case GOT_OBJ_TYPE_TAG:
14501 error = cat_tag(id, repo, stdout);
14502 break;
14503 default:
14504 error = got_error(GOT_ERR_OBJ_TYPE);
14505 break;
14507 if (error)
14508 break;
14509 free(label);
14510 label = NULL;
14511 free(id);
14512 id = NULL;
14514 done:
14515 free(cwd);
14516 free(label);
14517 free(id);
14518 free(commit_id);
14519 free(keyword_idstr);
14520 if (commit)
14521 got_object_commit_close(commit);
14522 if (worktree)
14523 got_worktree_close(worktree);
14524 if (repo) {
14525 const struct got_error *close_err = got_repo_close(repo);
14526 if (error == NULL)
14527 error = close_err;
14529 if (pack_fds) {
14530 const struct got_error *pack_err =
14531 got_repo_pack_fds_close(pack_fds);
14532 if (error == NULL)
14533 error = pack_err;
14536 got_ref_list_free(&refs);
14537 return error;
14540 __dead static void
14541 usage_info(void)
14543 fprintf(stderr, "usage: %s info [path ...]\n",
14544 getprogname());
14545 exit(1);
14548 static const struct got_error *
14549 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14550 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14551 struct got_object_id *commit_id)
14553 const struct got_error *err = NULL;
14554 char *id_str = NULL;
14555 char datebuf[128];
14556 struct tm mytm, *tm;
14557 struct got_pathlist_head *paths = arg;
14558 struct got_pathlist_entry *pe;
14561 * Clear error indication from any of the path arguments which
14562 * would cause this file index entry to be displayed.
14564 TAILQ_FOREACH(pe, paths, entry) {
14565 if (got_path_cmp(path, pe->path, strlen(path),
14566 pe->path_len) == 0 ||
14567 got_path_is_child(path, pe->path, pe->path_len))
14568 pe->data = NULL; /* no error */
14571 printf(GOT_COMMIT_SEP_STR);
14572 if (S_ISLNK(mode))
14573 printf("symlink: %s\n", path);
14574 else if (S_ISREG(mode)) {
14575 printf("file: %s\n", path);
14576 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14577 } else if (S_ISDIR(mode))
14578 printf("directory: %s\n", path);
14579 else
14580 printf("something: %s\n", path);
14582 tm = localtime_r(&mtime, &mytm);
14583 if (tm == NULL)
14584 return NULL;
14585 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14586 return got_error(GOT_ERR_NO_SPACE);
14587 printf("timestamp: %s\n", datebuf);
14589 if (blob_id) {
14590 err = got_object_id_str(&id_str, blob_id);
14591 if (err)
14592 return err;
14593 printf("based on blob: %s\n", id_str);
14594 free(id_str);
14597 if (staged_blob_id) {
14598 err = got_object_id_str(&id_str, staged_blob_id);
14599 if (err)
14600 return err;
14601 printf("based on staged blob: %s\n", id_str);
14602 free(id_str);
14605 if (commit_id) {
14606 err = got_object_id_str(&id_str, commit_id);
14607 if (err)
14608 return err;
14609 printf("based on commit: %s\n", id_str);
14610 free(id_str);
14613 return NULL;
14616 static const struct got_error *
14617 cmd_info(int argc, char *argv[])
14619 const struct got_error *error = NULL;
14620 struct got_repository *repo = NULL;
14621 struct got_worktree *worktree = NULL;
14622 struct got_fileindex *fileindex = NULL;
14623 char *cwd = NULL, *id_str = NULL;
14624 struct got_pathlist_head paths;
14625 char *uuidstr = NULL;
14626 int *pack_fds = NULL;
14627 int ch, show_files = 0;
14629 TAILQ_INIT(&paths);
14631 #ifndef PROFILE
14632 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14633 NULL) == -1)
14634 err(1, "pledge");
14635 #endif
14637 while ((ch = getopt(argc, argv, "")) != -1) {
14638 switch (ch) {
14639 default:
14640 usage_info();
14641 /* NOTREACHED */
14645 argc -= optind;
14646 argv += optind;
14648 cwd = getcwd(NULL, 0);
14649 if (cwd == NULL) {
14650 error = got_error_from_errno("getcwd");
14651 goto done;
14654 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14655 if (error) {
14656 if (error->code == GOT_ERR_NOT_WORKTREE)
14657 error = wrap_not_worktree_error(error, "info", cwd);
14658 goto done;
14661 error = got_repo_pack_fds_open(&pack_fds);
14662 if (error != NULL)
14663 goto done;
14665 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree), NULL,
14666 pack_fds);
14667 if (error)
14668 goto done;
14670 #ifndef PROFILE
14671 /* Remove "wpath cpath proc exec sendfd" promises. */
14672 if (pledge("stdio rpath flock unveil", NULL) == -1)
14673 err(1, "pledge");
14674 #endif
14675 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14676 if (error)
14677 goto done;
14679 if (argc >= 1) {
14680 error = get_worktree_paths_from_argv(&paths, argc, argv,
14681 worktree);
14682 if (error)
14683 goto done;
14684 show_files = 1;
14687 error = got_worktree_path_info_prepare(&fileindex, worktree, repo);
14688 if (error)
14689 goto done;
14691 error = got_object_id_str(&id_str,
14692 got_worktree_get_base_commit_id(worktree));
14693 if (error)
14694 goto done;
14696 error = got_worktree_get_uuid(&uuidstr, worktree);
14697 if (error)
14698 goto done;
14700 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14701 printf("work tree base commit: %s\n", id_str);
14702 printf("work tree path prefix: %s\n",
14703 got_worktree_get_path_prefix(worktree));
14704 printf("work tree branch reference: %s\n",
14705 got_worktree_get_head_ref_name(worktree));
14706 printf("work tree UUID: %s\n", uuidstr);
14707 printf("work tree format version: %d\n",
14708 got_worktree_get_format_version(worktree));
14709 printf("file index version: %u\n",
14710 got_worktree_get_fileindex_version(fileindex));
14711 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14713 if (show_files) {
14714 struct got_pathlist_entry *pe;
14715 TAILQ_FOREACH(pe, &paths, entry) {
14716 if (pe->path_len == 0)
14717 continue;
14719 * Assume this path will fail. This will be corrected
14720 * in print_path_info() in case the path does suceeed.
14722 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14724 error = got_worktree_path_info(worktree, fileindex, &paths,
14725 print_path_info, &paths, check_cancelled, NULL);
14726 if (error)
14727 goto done;
14728 TAILQ_FOREACH(pe, &paths, entry) {
14729 if (pe->data != NULL) {
14730 const struct got_error *perr;
14732 perr = pe->data;
14733 error = got_error_path(pe->path, perr->code);
14734 break;
14738 done:
14739 if (worktree) {
14740 const struct got_error *cerr;
14742 cerr = got_worktree_path_info_complete(fileindex, worktree);
14743 if (error == NULL)
14744 error = cerr;
14745 got_worktree_close(worktree);
14747 if (repo) {
14748 const struct got_error *close_err = got_repo_close(repo);
14749 if (error == NULL)
14750 error = close_err;
14752 if (pack_fds) {
14753 const struct got_error *pack_err =
14754 got_repo_pack_fds_close(pack_fds);
14755 if (error == NULL)
14756 error = pack_err;
14758 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14759 free(cwd);
14760 free(id_str);
14761 free(uuidstr);
14762 return error;