Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.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>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
269 return 1;
272 return 0;
275 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
276 list_commands(stderr);
277 return 1;
280 __dead static void
281 usage(int hflag, int status)
283 FILE *fp = (status == 0) ? stdout : stderr;
285 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
286 getprogname());
287 if (hflag)
288 list_commands(fp);
289 exit(status);
292 static const struct got_error *
293 get_editor(char **abspath)
295 const struct got_error *err = NULL;
296 const char *editor;
298 *abspath = NULL;
300 editor = getenv("VISUAL");
301 if (editor == NULL)
302 editor = getenv("EDITOR");
304 if (editor) {
305 err = got_path_find_prog(abspath, editor);
306 if (err)
307 return err;
310 if (*abspath == NULL) {
311 *abspath = strdup("/bin/ed");
312 if (*abspath == NULL)
313 return got_error_from_errno("strdup");
316 return NULL;
319 static const struct got_error *
320 apply_unveil(const char *repo_path, int repo_read_only,
321 const char *worktree_path)
323 const struct got_error *err;
325 #ifdef PROFILE
326 if (unveil("gmon.out", "rwc") != 0)
327 return got_error_from_errno2("unveil", "gmon.out");
328 #endif
329 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
330 return got_error_from_errno2("unveil", repo_path);
332 if (worktree_path && unveil(worktree_path, "rwc") != 0)
333 return got_error_from_errno2("unveil", worktree_path);
335 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
336 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
338 err = got_privsep_unveil_exec_helpers();
339 if (err != NULL)
340 return err;
342 if (unveil(NULL, NULL) != 0)
343 return got_error_from_errno("unveil");
345 return NULL;
348 __dead static void
349 usage_import(void)
351 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
352 "[-r repository-path] directory\n", getprogname());
353 exit(1);
356 static int
357 spawn_editor(const char *editor, const char *file)
359 pid_t pid;
360 sig_t sighup, sigint, sigquit;
361 int st = -1;
363 sighup = signal(SIGHUP, SIG_IGN);
364 sigint = signal(SIGINT, SIG_IGN);
365 sigquit = signal(SIGQUIT, SIG_IGN);
367 switch (pid = fork()) {
368 case -1:
369 goto doneediting;
370 case 0:
371 execl(editor, editor, file, (char *)NULL);
372 _exit(127);
375 while (waitpid(pid, &st, 0) == -1)
376 if (errno != EINTR)
377 break;
379 doneediting:
380 (void)signal(SIGHUP, sighup);
381 (void)signal(SIGINT, sigint);
382 (void)signal(SIGQUIT, sigquit);
384 if (!WIFEXITED(st)) {
385 errno = EINTR;
386 return -1;
389 return WEXITSTATUS(st);
392 static const struct got_error *
393 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
395 const struct got_error *err = NULL;
396 char *line = NULL;
397 size_t linesize = 0;
399 *logmsg = NULL;
400 *len = 0;
402 if (fseeko(fp, 0L, SEEK_SET) == -1)
403 return got_error_from_errno("fseeko");
405 *logmsg = malloc(filesize + 1);
406 if (*logmsg == NULL)
407 return got_error_from_errno("malloc");
408 (*logmsg)[0] = '\0';
410 while (getline(&line, &linesize, fp) != -1) {
411 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
412 continue; /* remove comments and leading empty lines */
413 *len = strlcat(*logmsg, line, filesize + 1);
414 if (*len >= filesize + 1) {
415 err = got_error(GOT_ERR_NO_SPACE);
416 goto done;
419 if (ferror(fp)) {
420 err = got_ferror(fp, GOT_ERR_IO);
421 goto done;
424 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
425 (*logmsg)[*len - 1] = '\0';
426 (*len)--;
428 done:
429 free(line);
430 if (err) {
431 free(*logmsg);
432 *logmsg = NULL;
433 *len = 0;
435 return err;
438 static const struct got_error *
439 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
440 const char *initial_content, size_t initial_content_len,
441 int require_modification)
443 const struct got_error *err = NULL;
444 struct stat st, st2;
445 FILE *fp = NULL;
446 size_t logmsg_len;
448 *logmsg = NULL;
450 if (stat(logmsg_path, &st) == -1)
451 return got_error_from_errno2("stat", logmsg_path);
453 if (spawn_editor(editor, logmsg_path) == -1)
454 return got_error_from_errno("failed spawning editor");
456 if (require_modification) {
457 struct timespec timeout;
459 timeout.tv_sec = 0;
460 timeout.tv_nsec = 1;
461 nanosleep(&timeout, NULL);
464 if (stat(logmsg_path, &st2) == -1)
465 return got_error_from_errno("stat");
467 if (require_modification && st.st_size == st2.st_size &&
468 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
469 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
470 "no changes made to commit message, aborting");
472 fp = fopen(logmsg_path, "re");
473 if (fp == NULL) {
474 err = got_error_from_errno("fopen");
475 goto done;
478 /* strip comments and leading/trailing newlines */
479 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
480 if (err)
481 goto done;
482 if (logmsg_len == 0) {
483 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
484 "commit message cannot be empty, aborting");
485 goto done;
487 done:
488 if (fp && fclose(fp) == EOF && err == NULL)
489 err = got_error_from_errno("fclose");
490 if (err) {
491 free(*logmsg);
492 *logmsg = NULL;
494 return err;
497 static const struct got_error *
498 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
499 const char *path_dir, const char *branch_name)
501 char *initial_content = NULL;
502 const struct got_error *err = NULL;
503 int initial_content_len;
504 int fd = -1;
506 initial_content_len = asprintf(&initial_content,
507 "\n# %s to be imported to branch %s\n", path_dir,
508 branch_name);
509 if (initial_content_len == -1)
510 return got_error_from_errno("asprintf");
512 err = got_opentemp_named_fd(logmsg_path, &fd,
513 GOT_TMPDIR_STR "/got-importmsg", "");
514 if (err)
515 goto done;
517 if (write(fd, initial_content, initial_content_len) == -1) {
518 err = got_error_from_errno2("write", *logmsg_path);
519 goto done;
522 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
523 initial_content_len, 1);
524 done:
525 if (fd != -1 && close(fd) == -1 && err == NULL)
526 err = got_error_from_errno2("close", *logmsg_path);
527 free(initial_content);
528 if (err) {
529 free(*logmsg_path);
530 *logmsg_path = NULL;
532 return err;
535 static const struct got_error *
536 import_progress(void *arg, const char *path)
538 printf("A %s\n", path);
539 return NULL;
542 static const struct got_error *
543 valid_author(const char *author)
545 const char *email = author;
547 /*
548 * Git' expects the author (or committer) to be in the form
549 * "name <email>", which are mostly free form (see the
550 * "committer" description in git-fast-import(1)). We're only
551 * doing this to avoid git's object parser breaking on commits
552 * we create.
553 */
555 while (*author && *author != '\n' && *author != '<' && *author != '>')
556 author++;
557 if (author != email && *author == '<' && *(author - 1) != ' ')
558 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
559 "between author name and email required", email);
560 if (*author++ != '<')
561 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
562 while (*author && *author != '\n' && *author != '<' && *author != '>')
563 author++;
564 if (strcmp(author, ">") != 0)
565 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
566 return NULL;
569 static const struct got_error *
570 get_author(char **author, struct got_repository *repo,
571 struct got_worktree *worktree)
573 const struct got_error *err = NULL;
574 const char *got_author = NULL, *name, *email;
575 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
577 *author = NULL;
579 if (worktree)
580 worktree_conf = got_worktree_get_gotconfig(worktree);
581 repo_conf = got_repo_get_gotconfig(repo);
583 /*
584 * Priority of potential author information sources, from most
585 * significant to least significant:
586 * 1) work tree's .got/got.conf file
587 * 2) repository's got.conf file
588 * 3) repository's git config file
589 * 4) environment variables
590 * 5) global git config files (in user's home directory or /etc)
591 */
593 if (worktree_conf)
594 got_author = got_gotconfig_get_author(worktree_conf);
595 if (got_author == NULL)
596 got_author = got_gotconfig_get_author(repo_conf);
597 if (got_author == NULL) {
598 name = got_repo_get_gitconfig_author_name(repo);
599 email = got_repo_get_gitconfig_author_email(repo);
600 if (name && email) {
601 if (asprintf(author, "%s <%s>", name, email) == -1)
602 return got_error_from_errno("asprintf");
603 return NULL;
606 got_author = getenv("GOT_AUTHOR");
607 if (got_author == NULL) {
608 name = got_repo_get_global_gitconfig_author_name(repo);
609 email = got_repo_get_global_gitconfig_author_email(
610 repo);
611 if (name && email) {
612 if (asprintf(author, "%s <%s>", name, email)
613 == -1)
614 return got_error_from_errno("asprintf");
615 return NULL;
617 /* TODO: Look up user in password database? */
618 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
622 *author = strdup(got_author);
623 if (*author == NULL)
624 return got_error_from_errno("strdup");
626 err = valid_author(*author);
627 if (err) {
628 free(*author);
629 *author = NULL;
631 return err;
634 static const struct got_error *
635 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
636 struct got_worktree *worktree)
638 const char *got_allowed_signers = NULL;
639 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
641 *allowed_signers = NULL;
643 if (worktree)
644 worktree_conf = got_worktree_get_gotconfig(worktree);
645 repo_conf = got_repo_get_gotconfig(repo);
647 /*
648 * Priority of potential author information sources, from most
649 * significant to least significant:
650 * 1) work tree's .got/got.conf file
651 * 2) repository's got.conf file
652 */
654 if (worktree_conf)
655 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
656 worktree_conf);
657 if (got_allowed_signers == NULL)
658 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
659 repo_conf);
661 if (got_allowed_signers) {
662 *allowed_signers = strdup(got_allowed_signers);
663 if (*allowed_signers == NULL)
664 return got_error_from_errno("strdup");
666 return NULL;
669 static const struct got_error *
670 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
671 struct got_worktree *worktree)
673 const char *got_revoked_signers = NULL;
674 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
676 *revoked_signers = NULL;
678 if (worktree)
679 worktree_conf = got_worktree_get_gotconfig(worktree);
680 repo_conf = got_repo_get_gotconfig(repo);
682 /*
683 * Priority of potential author information sources, from most
684 * significant to least significant:
685 * 1) work tree's .got/got.conf file
686 * 2) repository's got.conf file
687 */
689 if (worktree_conf)
690 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
691 worktree_conf);
692 if (got_revoked_signers == NULL)
693 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
694 repo_conf);
696 if (got_revoked_signers) {
697 *revoked_signers = strdup(got_revoked_signers);
698 if (*revoked_signers == NULL)
699 return got_error_from_errno("strdup");
701 return NULL;
704 static const char *
705 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
707 const char *got_signer_id = NULL;
708 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
710 if (worktree)
711 worktree_conf = got_worktree_get_gotconfig(worktree);
712 repo_conf = got_repo_get_gotconfig(repo);
714 /*
715 * Priority of potential author information sources, from most
716 * significant to least significant:
717 * 1) work tree's .got/got.conf file
718 * 2) repository's got.conf file
719 */
721 if (worktree_conf)
722 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
723 if (got_signer_id == NULL)
724 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
726 return got_signer_id;
729 static const struct got_error *
730 get_gitconfig_path(char **gitconfig_path)
732 const char *homedir = getenv("HOME");
734 *gitconfig_path = NULL;
735 if (homedir) {
736 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
737 return got_error_from_errno("asprintf");
740 return NULL;
743 static const struct got_error *
744 cmd_import(int argc, char *argv[])
746 const struct got_error *error = NULL;
747 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
748 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
749 const char *branch_name = NULL;
750 char *id_str = NULL, *logmsg_path = NULL;
751 char refname[PATH_MAX] = "refs/heads/";
752 struct got_repository *repo = NULL;
753 struct got_reference *branch_ref = NULL, *head_ref = NULL;
754 struct got_object_id *new_commit_id = NULL;
755 int ch, n = 0;
756 struct got_pathlist_head ignores;
757 struct got_pathlist_entry *pe;
758 int preserve_logmsg = 0;
759 int *pack_fds = NULL;
761 TAILQ_INIT(&ignores);
763 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
764 switch (ch) {
765 case 'b':
766 branch_name = optarg;
767 break;
768 case 'I':
769 if (optarg[0] == '\0')
770 break;
771 error = got_pathlist_insert(&pe, &ignores, optarg,
772 NULL);
773 if (error)
774 goto done;
775 break;
776 case 'm':
777 logmsg = strdup(optarg);
778 if (logmsg == NULL) {
779 error = got_error_from_errno("strdup");
780 goto done;
782 break;
783 case 'r':
784 repo_path = realpath(optarg, NULL);
785 if (repo_path == NULL) {
786 error = got_error_from_errno2("realpath",
787 optarg);
788 goto done;
790 break;
791 default:
792 usage_import();
793 /* NOTREACHED */
797 argc -= optind;
798 argv += optind;
800 #ifndef PROFILE
801 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
802 "unveil",
803 NULL) == -1)
804 err(1, "pledge");
805 #endif
806 if (argc != 1)
807 usage_import();
809 if (repo_path == NULL) {
810 repo_path = getcwd(NULL, 0);
811 if (repo_path == NULL)
812 return got_error_from_errno("getcwd");
814 got_path_strip_trailing_slashes(repo_path);
815 error = get_gitconfig_path(&gitconfig_path);
816 if (error)
817 goto done;
818 error = got_repo_pack_fds_open(&pack_fds);
819 if (error != NULL)
820 goto done;
821 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
822 if (error)
823 goto done;
825 error = get_author(&author, repo, NULL);
826 if (error)
827 return error;
829 /*
830 * Don't let the user create a branch name with a leading '-'.
831 * While technically a valid reference name, this case is usually
832 * an unintended typo.
833 */
834 if (branch_name && branch_name[0] == '-')
835 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
837 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
838 if (error && error->code != GOT_ERR_NOT_REF)
839 goto done;
841 if (branch_name)
842 n = strlcat(refname, branch_name, sizeof(refname));
843 else if (head_ref && got_ref_is_symbolic(head_ref))
844 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
845 sizeof(refname));
846 else
847 n = strlcat(refname, "main", sizeof(refname));
848 if (n >= sizeof(refname)) {
849 error = got_error(GOT_ERR_NO_SPACE);
850 goto done;
853 error = got_ref_open(&branch_ref, repo, refname, 0);
854 if (error) {
855 if (error->code != GOT_ERR_NOT_REF)
856 goto done;
857 } else {
858 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
859 "import target branch already exists");
860 goto done;
863 path_dir = realpath(argv[0], NULL);
864 if (path_dir == NULL) {
865 error = got_error_from_errno2("realpath", argv[0]);
866 goto done;
868 got_path_strip_trailing_slashes(path_dir);
870 /*
871 * unveil(2) traverses exec(2); if an editor is used we have
872 * to apply unveil after the log message has been written.
873 */
874 if (logmsg == NULL || strlen(logmsg) == 0) {
875 error = get_editor(&editor);
876 if (error)
877 goto done;
878 free(logmsg);
879 error = collect_import_msg(&logmsg, &logmsg_path, editor,
880 path_dir, refname);
881 if (error) {
882 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
883 logmsg_path != NULL)
884 preserve_logmsg = 1;
885 goto done;
889 if (unveil(path_dir, "r") != 0) {
890 error = got_error_from_errno2("unveil", path_dir);
891 if (logmsg_path)
892 preserve_logmsg = 1;
893 goto done;
896 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
897 if (error) {
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = got_repo_import(&new_commit_id, path_dir, logmsg,
904 author, &ignores, repo, import_progress, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_write(branch_ref, repo);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_object_id_str(&id_str, new_commit_id);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
933 if (error) {
934 if (error->code != GOT_ERR_NOT_REF) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
941 branch_ref);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_write(head_ref, repo);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
956 printf("Created branch %s with commit %s\n",
957 got_ref_get_name(branch_ref), id_str);
958 done:
959 if (pack_fds) {
960 const struct got_error *pack_err =
961 got_repo_pack_fds_close(pack_fds);
962 if (error == NULL)
963 error = pack_err;
965 if (preserve_logmsg) {
966 fprintf(stderr, "%s: log message preserved in %s\n",
967 getprogname(), logmsg_path);
968 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
969 error = got_error_from_errno2("unlink", logmsg_path);
970 free(logmsg);
971 free(logmsg_path);
972 free(repo_path);
973 free(editor);
974 free(new_commit_id);
975 free(id_str);
976 free(author);
977 free(gitconfig_path);
978 if (branch_ref)
979 got_ref_close(branch_ref);
980 if (head_ref)
981 got_ref_close(head_ref);
982 return error;
985 __dead static void
986 usage_clone(void)
988 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
989 "repository-URL [directory]\n", getprogname());
990 exit(1);
993 struct got_fetch_progress_arg {
994 char last_scaled_size[FMT_SCALED_STRSIZE];
995 int last_p_indexed;
996 int last_p_resolved;
997 int verbosity;
999 struct got_repository *repo;
1001 int create_configs;
1002 int configs_created;
1003 struct {
1004 struct got_pathlist_head *symrefs;
1005 struct got_pathlist_head *wanted_branches;
1006 struct got_pathlist_head *wanted_refs;
1007 const char *proto;
1008 const char *host;
1009 const char *port;
1010 const char *remote_repo_path;
1011 const char *git_url;
1012 int fetch_all_branches;
1013 int mirror_references;
1014 } config_info;
1017 /* XXX forward declaration */
1018 static const struct got_error *
1019 create_config_files(const char *proto, const char *host, const char *port,
1020 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1021 int mirror_references, struct got_pathlist_head *symrefs,
1022 struct got_pathlist_head *wanted_branches,
1023 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1025 static const struct got_error *
1026 fetch_progress(void *arg, const char *message, off_t packfile_size,
1027 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1029 const struct got_error *err = NULL;
1030 struct got_fetch_progress_arg *a = arg;
1031 char scaled_size[FMT_SCALED_STRSIZE];
1032 int p_indexed, p_resolved;
1033 int print_size = 0, print_indexed = 0, print_resolved = 0;
1036 * In order to allow a failed clone to be resumed with 'got fetch'
1037 * we try to create configuration files as soon as possible.
1038 * Once the server has sent information about its default branch
1039 * we have all required information.
1041 if (a->create_configs && !a->configs_created &&
1042 !TAILQ_EMPTY(a->config_info.symrefs)) {
1043 err = create_config_files(a->config_info.proto,
1044 a->config_info.host, a->config_info.port,
1045 a->config_info.remote_repo_path,
1046 a->config_info.git_url,
1047 a->config_info.fetch_all_branches,
1048 a->config_info.mirror_references,
1049 a->config_info.symrefs,
1050 a->config_info.wanted_branches,
1051 a->config_info.wanted_refs, a->repo);
1052 if (err)
1053 return err;
1054 a->configs_created = 1;
1057 if (a->verbosity < 0)
1058 return NULL;
1060 if (message && message[0] != '\0') {
1061 printf("\rserver: %s", message);
1062 fflush(stdout);
1063 return NULL;
1066 if (packfile_size > 0 || nobj_indexed > 0) {
1067 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1068 (a->last_scaled_size[0] == '\0' ||
1069 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1070 print_size = 1;
1071 if (strlcpy(a->last_scaled_size, scaled_size,
1072 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1073 return got_error(GOT_ERR_NO_SPACE);
1075 if (nobj_indexed > 0) {
1076 p_indexed = (nobj_indexed * 100) / nobj_total;
1077 if (p_indexed != a->last_p_indexed) {
1078 a->last_p_indexed = p_indexed;
1079 print_indexed = 1;
1080 print_size = 1;
1083 if (nobj_resolved > 0) {
1084 p_resolved = (nobj_resolved * 100) /
1085 (nobj_total - nobj_loose);
1086 if (p_resolved != a->last_p_resolved) {
1087 a->last_p_resolved = p_resolved;
1088 print_resolved = 1;
1089 print_indexed = 1;
1090 print_size = 1;
1095 if (print_size || print_indexed || print_resolved)
1096 printf("\r");
1097 if (print_size)
1098 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1099 if (print_indexed)
1100 printf("; indexing %d%%", p_indexed);
1101 if (print_resolved)
1102 printf("; resolving deltas %d%%", p_resolved);
1103 if (print_size || print_indexed || print_resolved)
1104 fflush(stdout);
1106 return NULL;
1109 static const struct got_error *
1110 create_symref(const char *refname, struct got_reference *target_ref,
1111 int verbosity, struct got_repository *repo)
1113 const struct got_error *err;
1114 struct got_reference *head_symref;
1116 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1117 if (err)
1118 return err;
1120 err = got_ref_write(head_symref, repo);
1121 if (err == NULL && verbosity > 0) {
1122 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1123 got_ref_get_name(target_ref));
1125 got_ref_close(head_symref);
1126 return err;
1129 static const struct got_error *
1130 list_remote_refs(struct got_pathlist_head *symrefs,
1131 struct got_pathlist_head *refs)
1133 const struct got_error *err;
1134 struct got_pathlist_entry *pe;
1136 TAILQ_FOREACH(pe, symrefs, entry) {
1137 const char *refname = pe->path;
1138 const char *targetref = pe->data;
1140 printf("%s: %s\n", refname, targetref);
1143 TAILQ_FOREACH(pe, refs, entry) {
1144 const char *refname = pe->path;
1145 struct got_object_id *id = pe->data;
1146 char *id_str;
1148 err = got_object_id_str(&id_str, id);
1149 if (err)
1150 return err;
1151 printf("%s: %s\n", refname, id_str);
1152 free(id_str);
1155 return NULL;
1158 static const struct got_error *
1159 create_ref(const char *refname, struct got_object_id *id,
1160 int verbosity, struct got_repository *repo)
1162 const struct got_error *err = NULL;
1163 struct got_reference *ref;
1164 char *id_str;
1166 err = got_object_id_str(&id_str, id);
1167 if (err)
1168 return err;
1170 err = got_ref_alloc(&ref, refname, id);
1171 if (err)
1172 goto done;
1174 err = got_ref_write(ref, repo);
1175 got_ref_close(ref);
1177 if (err == NULL && verbosity >= 0)
1178 printf("Created reference %s: %s\n", refname, id_str);
1179 done:
1180 free(id_str);
1181 return err;
1184 static int
1185 match_wanted_ref(const char *refname, const char *wanted_ref)
1187 if (strncmp(refname, "refs/", 5) != 0)
1188 return 0;
1189 refname += 5;
1192 * Prevent fetching of references that won't make any
1193 * sense outside of the remote repository's context.
1195 if (strncmp(refname, "got/", 4) == 0)
1196 return 0;
1197 if (strncmp(refname, "remotes/", 8) == 0)
1198 return 0;
1200 if (strncmp(wanted_ref, "refs/", 5) == 0)
1201 wanted_ref += 5;
1203 /* Allow prefix match. */
1204 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1205 return 1;
1207 /* Allow exact match. */
1208 return (strcmp(refname, wanted_ref) == 0);
1211 static int
1212 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1214 struct got_pathlist_entry *pe;
1216 TAILQ_FOREACH(pe, wanted_refs, entry) {
1217 if (match_wanted_ref(refname, pe->path))
1218 return 1;
1221 return 0;
1224 static const struct got_error *
1225 create_wanted_ref(const char *refname, struct got_object_id *id,
1226 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1228 const struct got_error *err;
1229 char *remote_refname;
1231 if (strncmp("refs/", refname, 5) == 0)
1232 refname += 5;
1234 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1235 remote_repo_name, refname) == -1)
1236 return got_error_from_errno("asprintf");
1238 err = create_ref(remote_refname, id, verbosity, repo);
1239 free(remote_refname);
1240 return err;
1243 static const struct got_error *
1244 create_gotconfig(const char *proto, const char *host, const char *port,
1245 const char *remote_repo_path, const char *default_branch,
1246 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1247 struct got_pathlist_head *wanted_refs, int mirror_references,
1248 struct got_repository *repo)
1250 const struct got_error *err = NULL;
1251 char *gotconfig_path = NULL;
1252 char *gotconfig = NULL;
1253 FILE *gotconfig_file = NULL;
1254 const char *branchname = NULL;
1255 char *branches = NULL, *refs = NULL;
1256 ssize_t n;
1258 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1259 struct got_pathlist_entry *pe;
1260 TAILQ_FOREACH(pe, wanted_branches, entry) {
1261 char *s;
1262 branchname = pe->path;
1263 if (strncmp(branchname, "refs/heads/", 11) == 0)
1264 branchname += 11;
1265 if (asprintf(&s, "%s\"%s\" ",
1266 branches ? branches : "", branchname) == -1) {
1267 err = got_error_from_errno("asprintf");
1268 goto done;
1270 free(branches);
1271 branches = s;
1273 } else if (!fetch_all_branches && default_branch) {
1274 branchname = default_branch;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1278 err = got_error_from_errno("asprintf");
1279 goto done;
1282 if (!TAILQ_EMPTY(wanted_refs)) {
1283 struct got_pathlist_entry *pe;
1284 TAILQ_FOREACH(pe, wanted_refs, entry) {
1285 char *s;
1286 const char *refname = pe->path;
1287 if (strncmp(refname, "refs/", 5) == 0)
1288 branchname += 5;
1289 if (asprintf(&s, "%s\"%s\" ",
1290 refs ? refs : "", refname) == -1) {
1291 err = got_error_from_errno("asprintf");
1292 goto done;
1294 free(refs);
1295 refs = s;
1299 /* Create got.conf(5). */
1300 gotconfig_path = got_repo_get_path_gotconfig(repo);
1301 if (gotconfig_path == NULL) {
1302 err = got_error_from_errno("got_repo_get_path_gotconfig");
1303 goto done;
1305 gotconfig_file = fopen(gotconfig_path, "ae");
1306 if (gotconfig_file == NULL) {
1307 err = got_error_from_errno2("fopen", gotconfig_path);
1308 goto done;
1310 if (asprintf(&gotconfig,
1311 "remote \"%s\" {\n"
1312 "\tserver %s\n"
1313 "\tprotocol %s\n"
1314 "%s%s%s"
1315 "\trepository \"%s\"\n"
1316 "%s%s%s"
1317 "%s%s%s"
1318 "%s"
1319 "%s"
1320 "}\n",
1321 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1322 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1323 remote_repo_path, branches ? "\tbranch { " : "",
1324 branches ? branches : "", branches ? "}\n" : "",
1325 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1326 mirror_references ? "\tmirror_references yes\n" : "",
1327 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1328 err = got_error_from_errno("asprintf");
1329 goto done;
1331 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1332 if (n != strlen(gotconfig)) {
1333 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1334 goto done;
1337 done:
1338 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1339 err = got_error_from_errno2("fclose", gotconfig_path);
1340 free(gotconfig_path);
1341 free(branches);
1342 return err;
1345 static const struct got_error *
1346 create_gitconfig(const char *git_url, const char *default_branch,
1347 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1348 struct got_pathlist_head *wanted_refs, int mirror_references,
1349 struct got_repository *repo)
1351 const struct got_error *err = NULL;
1352 char *gitconfig_path = NULL;
1353 char *gitconfig = NULL;
1354 FILE *gitconfig_file = NULL;
1355 char *branches = NULL, *refs = NULL;
1356 const char *branchname;
1357 ssize_t n;
1359 /* Create a config file Git can understand. */
1360 gitconfig_path = got_repo_get_path_gitconfig(repo);
1361 if (gitconfig_path == NULL) {
1362 err = got_error_from_errno("got_repo_get_path_gitconfig");
1363 goto done;
1365 gitconfig_file = fopen(gitconfig_path, "ae");
1366 if (gitconfig_file == NULL) {
1367 err = got_error_from_errno2("fopen", gitconfig_path);
1368 goto done;
1370 if (fetch_all_branches) {
1371 if (mirror_references) {
1372 if (asprintf(&branches,
1373 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1374 err = got_error_from_errno("asprintf");
1375 goto done;
1377 } else if (asprintf(&branches,
1378 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1379 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1380 err = got_error_from_errno("asprintf");
1381 goto done;
1383 } else if (!TAILQ_EMPTY(wanted_branches)) {
1384 struct got_pathlist_entry *pe;
1385 TAILQ_FOREACH(pe, wanted_branches, entry) {
1386 char *s;
1387 branchname = pe->path;
1388 if (strncmp(branchname, "refs/heads/", 11) == 0)
1389 branchname += 11;
1390 if (mirror_references) {
1391 if (asprintf(&s,
1392 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1393 branches ? branches : "",
1394 branchname, branchname) == -1) {
1395 err = got_error_from_errno("asprintf");
1396 goto done;
1398 } else if (asprintf(&s,
1399 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1400 branches ? branches : "",
1401 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1402 branchname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 free(branches);
1407 branches = s;
1409 } else {
1411 * If the server specified a default branch, use just that one.
1412 * Otherwise fall back to fetching all branches on next fetch.
1414 if (default_branch) {
1415 branchname = default_branch;
1416 if (strncmp(branchname, "refs/heads/", 11) == 0)
1417 branchname += 11;
1418 } else
1419 branchname = "*"; /* fall back to all branches */
1420 if (mirror_references) {
1421 if (asprintf(&branches,
1422 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1423 branchname, branchname) == -1) {
1424 err = got_error_from_errno("asprintf");
1425 goto done;
1427 } else if (asprintf(&branches,
1428 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1429 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1430 branchname) == -1) {
1431 err = got_error_from_errno("asprintf");
1432 goto done;
1435 if (!TAILQ_EMPTY(wanted_refs)) {
1436 struct got_pathlist_entry *pe;
1437 TAILQ_FOREACH(pe, wanted_refs, entry) {
1438 char *s;
1439 const char *refname = pe->path;
1440 if (strncmp(refname, "refs/", 5) == 0)
1441 refname += 5;
1442 if (mirror_references) {
1443 if (asprintf(&s,
1444 "%s\tfetch = refs/%s:refs/%s\n",
1445 refs ? refs : "", refname, refname) == -1) {
1446 err = got_error_from_errno("asprintf");
1447 goto done;
1449 } else if (asprintf(&s,
1450 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1451 refs ? refs : "",
1452 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1453 refname) == -1) {
1454 err = got_error_from_errno("asprintf");
1455 goto done;
1457 free(refs);
1458 refs = s;
1462 if (asprintf(&gitconfig,
1463 "[remote \"%s\"]\n"
1464 "\turl = %s\n"
1465 "%s"
1466 "%s"
1467 "\tfetch = refs/tags/*:refs/tags/*\n",
1468 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1469 refs ? refs : "") == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1474 if (n != strlen(gitconfig)) {
1475 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1476 goto done;
1478 done:
1479 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1480 err = got_error_from_errno2("fclose", gitconfig_path);
1481 free(gitconfig_path);
1482 free(branches);
1483 return err;
1486 static const struct got_error *
1487 create_config_files(const char *proto, const char *host, const char *port,
1488 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1489 int mirror_references, struct got_pathlist_head *symrefs,
1490 struct got_pathlist_head *wanted_branches,
1491 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1493 const struct got_error *err = NULL;
1494 const char *default_branch = NULL;
1495 struct got_pathlist_entry *pe;
1498 * If we asked for a set of wanted branches then use the first
1499 * one of those.
1501 if (!TAILQ_EMPTY(wanted_branches)) {
1502 pe = TAILQ_FIRST(wanted_branches);
1503 default_branch = pe->path;
1504 } else {
1505 /* First HEAD ref listed by server is the default branch. */
1506 TAILQ_FOREACH(pe, symrefs, entry) {
1507 const char *refname = pe->path;
1508 const char *target = pe->data;
1510 if (strcmp(refname, GOT_REF_HEAD) != 0)
1511 continue;
1513 default_branch = target;
1514 break;
1518 /* Create got.conf(5). */
1519 err = create_gotconfig(proto, host, port, remote_repo_path,
1520 default_branch, fetch_all_branches, wanted_branches,
1521 wanted_refs, mirror_references, repo);
1522 if (err)
1523 return err;
1525 /* Create a config file Git can understand. */
1526 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1527 wanted_branches, wanted_refs, mirror_references, repo);
1530 static const struct got_error *
1531 cmd_clone(int argc, char *argv[])
1533 const struct got_error *error = NULL;
1534 const char *uri, *dirname;
1535 char *proto, *host, *port, *repo_name, *server_path;
1536 char *default_destdir = NULL, *id_str = NULL;
1537 const char *repo_path;
1538 struct got_repository *repo = NULL;
1539 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1540 struct got_pathlist_entry *pe;
1541 struct got_object_id *pack_hash = NULL;
1542 int ch, fetchfd = -1, fetchstatus;
1543 pid_t fetchpid = -1;
1544 struct got_fetch_progress_arg fpa;
1545 char *git_url = NULL;
1546 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1547 int list_refs_only = 0;
1548 int *pack_fds = NULL;
1550 TAILQ_INIT(&refs);
1551 TAILQ_INIT(&symrefs);
1552 TAILQ_INIT(&wanted_branches);
1553 TAILQ_INIT(&wanted_refs);
1555 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1556 switch (ch) {
1557 case 'a':
1558 fetch_all_branches = 1;
1559 break;
1560 case 'b':
1561 error = got_pathlist_append(&wanted_branches,
1562 optarg, NULL);
1563 if (error)
1564 return error;
1565 break;
1566 case 'l':
1567 list_refs_only = 1;
1568 break;
1569 case 'm':
1570 mirror_references = 1;
1571 break;
1572 case 'q':
1573 verbosity = -1;
1574 break;
1575 case 'R':
1576 error = got_pathlist_append(&wanted_refs,
1577 optarg, NULL);
1578 if (error)
1579 return error;
1580 break;
1581 case 'v':
1582 if (verbosity < 0)
1583 verbosity = 0;
1584 else if (verbosity < 3)
1585 verbosity++;
1586 break;
1587 default:
1588 usage_clone();
1589 break;
1592 argc -= optind;
1593 argv += optind;
1595 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1596 option_conflict('a', 'b');
1597 if (list_refs_only) {
1598 if (!TAILQ_EMPTY(&wanted_branches))
1599 option_conflict('l', 'b');
1600 if (fetch_all_branches)
1601 option_conflict('l', 'a');
1602 if (mirror_references)
1603 option_conflict('l', 'm');
1604 if (!TAILQ_EMPTY(&wanted_refs))
1605 option_conflict('l', 'R');
1608 uri = argv[0];
1610 if (argc == 1)
1611 dirname = NULL;
1612 else if (argc == 2)
1613 dirname = argv[1];
1614 else
1615 usage_clone();
1617 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1618 &repo_name, uri);
1619 if (error)
1620 goto done;
1622 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1623 host, port ? ":" : "", port ? port : "",
1624 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1625 error = got_error_from_errno("asprintf");
1626 goto done;
1629 if (strcmp(proto, "git") == 0) {
1630 #ifndef PROFILE
1631 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1632 "sendfd dns inet unveil", NULL) == -1)
1633 err(1, "pledge");
1634 #endif
1635 } else if (strcmp(proto, "git+ssh") == 0 ||
1636 strcmp(proto, "ssh") == 0) {
1637 #ifndef PROFILE
1638 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1639 "sendfd unveil", NULL) == -1)
1640 err(1, "pledge");
1641 #endif
1642 } else if (strcmp(proto, "http") == 0 ||
1643 strcmp(proto, "git+http") == 0) {
1644 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1645 goto done;
1646 } else {
1647 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1648 goto done;
1650 if (dirname == NULL) {
1651 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1652 error = got_error_from_errno("asprintf");
1653 goto done;
1655 repo_path = default_destdir;
1656 } else
1657 repo_path = dirname;
1659 if (!list_refs_only) {
1660 error = got_path_mkdir(repo_path);
1661 if (error &&
1662 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1663 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1664 goto done;
1665 if (!got_path_dir_is_empty(repo_path)) {
1666 error = got_error_path(repo_path,
1667 GOT_ERR_DIR_NOT_EMPTY);
1668 goto done;
1672 error = got_dial_apply_unveil(proto);
1673 if (error)
1674 goto done;
1676 error = apply_unveil(repo_path, 0, NULL);
1677 if (error)
1678 goto done;
1680 if (verbosity >= 0)
1681 printf("Connecting to %s\n", git_url);
1683 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1684 server_path, verbosity);
1685 if (error)
1686 goto done;
1688 if (!list_refs_only) {
1689 error = got_repo_init(repo_path, NULL);
1690 if (error)
1691 goto done;
1692 error = got_repo_pack_fds_open(&pack_fds);
1693 if (error != NULL)
1694 goto done;
1695 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1696 if (error)
1697 goto done;
1700 fpa.last_scaled_size[0] = '\0';
1701 fpa.last_p_indexed = -1;
1702 fpa.last_p_resolved = -1;
1703 fpa.verbosity = verbosity;
1704 fpa.create_configs = 1;
1705 fpa.configs_created = 0;
1706 fpa.repo = repo;
1707 fpa.config_info.symrefs = &symrefs;
1708 fpa.config_info.wanted_branches = &wanted_branches;
1709 fpa.config_info.wanted_refs = &wanted_refs;
1710 fpa.config_info.proto = proto;
1711 fpa.config_info.host = host;
1712 fpa.config_info.port = port;
1713 fpa.config_info.remote_repo_path = server_path;
1714 fpa.config_info.git_url = git_url;
1715 fpa.config_info.fetch_all_branches = fetch_all_branches;
1716 fpa.config_info.mirror_references = mirror_references;
1717 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1718 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1719 fetch_all_branches, &wanted_branches, &wanted_refs,
1720 list_refs_only, verbosity, fetchfd, repo, NULL,
1721 fetch_progress, &fpa);
1722 if (error)
1723 goto done;
1725 if (list_refs_only) {
1726 error = list_remote_refs(&symrefs, &refs);
1727 goto done;
1730 if (pack_hash == NULL) {
1731 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1732 "server sent an empty pack file");
1733 goto done;
1735 error = got_object_id_str(&id_str, pack_hash);
1736 if (error)
1737 goto done;
1738 if (verbosity >= 0)
1739 printf("\nFetched %s.pack\n", id_str);
1740 free(id_str);
1742 /* Set up references provided with the pack file. */
1743 TAILQ_FOREACH(pe, &refs, entry) {
1744 const char *refname = pe->path;
1745 struct got_object_id *id = pe->data;
1746 char *remote_refname;
1748 if (is_wanted_ref(&wanted_refs, refname) &&
1749 !mirror_references) {
1750 error = create_wanted_ref(refname, id,
1751 GOT_FETCH_DEFAULT_REMOTE_NAME,
1752 verbosity - 1, repo);
1753 if (error)
1754 goto done;
1755 continue;
1758 error = create_ref(refname, id, verbosity - 1, repo);
1759 if (error)
1760 goto done;
1762 if (mirror_references)
1763 continue;
1765 if (strncmp("refs/heads/", refname, 11) != 0)
1766 continue;
1768 if (asprintf(&remote_refname,
1769 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1770 refname + 11) == -1) {
1771 error = got_error_from_errno("asprintf");
1772 goto done;
1774 error = create_ref(remote_refname, id, verbosity - 1, repo);
1775 free(remote_refname);
1776 if (error)
1777 goto done;
1780 /* Set the HEAD reference if the server provided one. */
1781 TAILQ_FOREACH(pe, &symrefs, entry) {
1782 struct got_reference *target_ref;
1783 const char *refname = pe->path;
1784 const char *target = pe->data;
1785 char *remote_refname = NULL, *remote_target = NULL;
1787 if (strcmp(refname, GOT_REF_HEAD) != 0)
1788 continue;
1790 error = got_ref_open(&target_ref, repo, target, 0);
1791 if (error) {
1792 if (error->code == GOT_ERR_NOT_REF) {
1793 error = NULL;
1794 continue;
1796 goto done;
1799 error = create_symref(refname, target_ref, verbosity, repo);
1800 got_ref_close(target_ref);
1801 if (error)
1802 goto done;
1804 if (mirror_references)
1805 continue;
1807 if (strncmp("refs/heads/", target, 11) != 0)
1808 continue;
1810 if (asprintf(&remote_refname,
1811 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1812 refname) == -1) {
1813 error = got_error_from_errno("asprintf");
1814 goto done;
1816 if (asprintf(&remote_target,
1817 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1818 target + 11) == -1) {
1819 error = got_error_from_errno("asprintf");
1820 free(remote_refname);
1821 goto done;
1823 error = got_ref_open(&target_ref, repo, remote_target, 0);
1824 if (error) {
1825 free(remote_refname);
1826 free(remote_target);
1827 if (error->code == GOT_ERR_NOT_REF) {
1828 error = NULL;
1829 continue;
1831 goto done;
1833 error = create_symref(remote_refname, target_ref,
1834 verbosity - 1, repo);
1835 free(remote_refname);
1836 free(remote_target);
1837 got_ref_close(target_ref);
1838 if (error)
1839 goto done;
1841 if (pe == NULL) {
1843 * We failed to set the HEAD reference. If we asked for
1844 * a set of wanted branches use the first of one of those
1845 * which could be fetched instead.
1847 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1848 const char *target = pe->path;
1849 struct got_reference *target_ref;
1851 error = got_ref_open(&target_ref, repo, target, 0);
1852 if (error) {
1853 if (error->code == GOT_ERR_NOT_REF) {
1854 error = NULL;
1855 continue;
1857 goto done;
1860 error = create_symref(GOT_REF_HEAD, target_ref,
1861 verbosity, repo);
1862 got_ref_close(target_ref);
1863 if (error)
1864 goto done;
1865 break;
1868 if (!fpa.configs_created && pe != NULL) {
1869 error = create_config_files(fpa.config_info.proto,
1870 fpa.config_info.host, fpa.config_info.port,
1871 fpa.config_info.remote_repo_path,
1872 fpa.config_info.git_url,
1873 fpa.config_info.fetch_all_branches,
1874 fpa.config_info.mirror_references,
1875 fpa.config_info.symrefs,
1876 fpa.config_info.wanted_branches,
1877 fpa.config_info.wanted_refs, fpa.repo);
1878 if (error)
1879 goto done;
1883 if (verbosity >= 0)
1884 printf("Created %s repository '%s'\n",
1885 mirror_references ? "mirrored" : "cloned", repo_path);
1886 done:
1887 if (pack_fds) {
1888 const struct got_error *pack_err =
1889 got_repo_pack_fds_close(pack_fds);
1890 if (error == NULL)
1891 error = pack_err;
1893 if (fetchpid > 0) {
1894 if (kill(fetchpid, SIGTERM) == -1)
1895 error = got_error_from_errno("kill");
1896 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1897 error = got_error_from_errno("waitpid");
1899 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1900 error = got_error_from_errno("close");
1901 if (repo) {
1902 const struct got_error *close_err = got_repo_close(repo);
1903 if (error == NULL)
1904 error = close_err;
1906 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1907 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1908 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1909 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1910 free(pack_hash);
1911 free(proto);
1912 free(host);
1913 free(port);
1914 free(server_path);
1915 free(repo_name);
1916 free(default_destdir);
1917 free(git_url);
1918 return error;
1921 static const struct got_error *
1922 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1923 int replace_tags, int verbosity, struct got_repository *repo)
1925 const struct got_error *err = NULL;
1926 char *new_id_str = NULL;
1927 struct got_object_id *old_id = NULL;
1929 err = got_object_id_str(&new_id_str, new_id);
1930 if (err)
1931 goto done;
1933 if (!replace_tags &&
1934 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1935 err = got_ref_resolve(&old_id, repo, ref);
1936 if (err)
1937 goto done;
1938 if (got_object_id_cmp(old_id, new_id) == 0)
1939 goto done;
1940 if (verbosity >= 0) {
1941 printf("Rejecting update of existing tag %s: %s\n",
1942 got_ref_get_name(ref), new_id_str);
1944 goto done;
1947 if (got_ref_is_symbolic(ref)) {
1948 if (verbosity >= 0) {
1949 printf("Replacing reference %s: %s\n",
1950 got_ref_get_name(ref),
1951 got_ref_get_symref_target(ref));
1953 err = got_ref_change_symref_to_ref(ref, new_id);
1954 if (err)
1955 goto done;
1956 err = got_ref_write(ref, repo);
1957 if (err)
1958 goto done;
1959 } else {
1960 err = got_ref_resolve(&old_id, repo, ref);
1961 if (err)
1962 goto done;
1963 if (got_object_id_cmp(old_id, new_id) == 0)
1964 goto done;
1966 err = got_ref_change_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1974 if (verbosity >= 0)
1975 printf("Updated %s: %s\n", got_ref_get_name(ref),
1976 new_id_str);
1977 done:
1978 free(old_id);
1979 free(new_id_str);
1980 return err;
1983 static const struct got_error *
1984 update_symref(const char *refname, struct got_reference *target_ref,
1985 int verbosity, struct got_repository *repo)
1987 const struct got_error *err = NULL, *unlock_err;
1988 struct got_reference *symref;
1989 int symref_is_locked = 0;
1991 err = got_ref_open(&symref, repo, refname, 1);
1992 if (err) {
1993 if (err->code != GOT_ERR_NOT_REF)
1994 return err;
1995 err = got_ref_alloc_symref(&symref, refname, target_ref);
1996 if (err)
1997 goto done;
1999 err = got_ref_write(symref, repo);
2000 if (err)
2001 goto done;
2003 if (verbosity >= 0)
2004 printf("Created reference %s: %s\n",
2005 got_ref_get_name(symref),
2006 got_ref_get_symref_target(symref));
2007 } else {
2008 symref_is_locked = 1;
2010 if (strcmp(got_ref_get_symref_target(symref),
2011 got_ref_get_name(target_ref)) == 0)
2012 goto done;
2014 err = got_ref_change_symref(symref,
2015 got_ref_get_name(target_ref));
2016 if (err)
2017 goto done;
2019 err = got_ref_write(symref, repo);
2020 if (err)
2021 goto done;
2023 if (verbosity >= 0)
2024 printf("Updated %s: %s\n", got_ref_get_name(symref),
2025 got_ref_get_symref_target(symref));
2028 done:
2029 if (symref_is_locked) {
2030 unlock_err = got_ref_unlock(symref);
2031 if (unlock_err && err == NULL)
2032 err = unlock_err;
2034 got_ref_close(symref);
2035 return err;
2038 __dead static void
2039 usage_fetch(void)
2041 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2042 "[-R reference] [-r repository-path] [remote-repository]\n",
2043 getprogname());
2044 exit(1);
2047 static const struct got_error *
2048 delete_missing_ref(struct got_reference *ref,
2049 int verbosity, struct got_repository *repo)
2051 const struct got_error *err = NULL;
2052 struct got_object_id *id = NULL;
2053 char *id_str = NULL;
2055 if (got_ref_is_symbolic(ref)) {
2056 err = got_ref_delete(ref, repo);
2057 if (err)
2058 return err;
2059 if (verbosity >= 0) {
2060 printf("Deleted %s: %s\n",
2061 got_ref_get_name(ref),
2062 got_ref_get_symref_target(ref));
2064 } else {
2065 err = got_ref_resolve(&id, repo, ref);
2066 if (err)
2067 return err;
2068 err = got_object_id_str(&id_str, id);
2069 if (err)
2070 goto done;
2072 err = got_ref_delete(ref, repo);
2073 if (err)
2074 goto done;
2075 if (verbosity >= 0) {
2076 printf("Deleted %s: %s\n",
2077 got_ref_get_name(ref), id_str);
2080 done:
2081 free(id);
2082 free(id_str);
2083 return err;
2086 static const struct got_error *
2087 delete_missing_refs(struct got_pathlist_head *their_refs,
2088 struct got_pathlist_head *their_symrefs,
2089 const struct got_remote_repo *remote,
2090 int verbosity, struct got_repository *repo)
2092 const struct got_error *err = NULL, *unlock_err;
2093 struct got_reflist_head my_refs;
2094 struct got_reflist_entry *re;
2095 struct got_pathlist_entry *pe;
2096 char *remote_namespace = NULL;
2097 char *local_refname = NULL;
2099 TAILQ_INIT(&my_refs);
2101 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2102 == -1)
2103 return got_error_from_errno("asprintf");
2105 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2106 if (err)
2107 goto done;
2109 TAILQ_FOREACH(re, &my_refs, entry) {
2110 const char *refname = got_ref_get_name(re->ref);
2111 const char *their_refname;
2113 if (remote->mirror_references) {
2114 their_refname = refname;
2115 } else {
2116 if (strncmp(refname, remote_namespace,
2117 strlen(remote_namespace)) == 0) {
2118 if (strcmp(refname + strlen(remote_namespace),
2119 GOT_REF_HEAD) == 0)
2120 continue;
2121 if (asprintf(&local_refname, "refs/heads/%s",
2122 refname + strlen(remote_namespace)) == -1) {
2123 err = got_error_from_errno("asprintf");
2124 goto done;
2126 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2127 continue;
2129 their_refname = local_refname;
2132 TAILQ_FOREACH(pe, their_refs, entry) {
2133 if (strcmp(their_refname, pe->path) == 0)
2134 break;
2136 if (pe != NULL)
2137 continue;
2139 TAILQ_FOREACH(pe, their_symrefs, entry) {
2140 if (strcmp(their_refname, pe->path) == 0)
2141 break;
2143 if (pe != NULL)
2144 continue;
2146 err = delete_missing_ref(re->ref, verbosity, repo);
2147 if (err)
2148 break;
2150 if (local_refname) {
2151 struct got_reference *ref;
2152 err = got_ref_open(&ref, repo, local_refname, 1);
2153 if (err) {
2154 if (err->code != GOT_ERR_NOT_REF)
2155 break;
2156 free(local_refname);
2157 local_refname = NULL;
2158 continue;
2160 err = delete_missing_ref(ref, verbosity, repo);
2161 if (err)
2162 break;
2163 unlock_err = got_ref_unlock(ref);
2164 got_ref_close(ref);
2165 if (unlock_err && err == NULL) {
2166 err = unlock_err;
2167 break;
2170 free(local_refname);
2171 local_refname = NULL;
2174 done:
2175 got_ref_list_free(&my_refs);
2176 free(remote_namespace);
2177 free(local_refname);
2178 return err;
2181 static const struct got_error *
2182 update_wanted_ref(const char *refname, struct got_object_id *id,
2183 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2185 const struct got_error *err, *unlock_err;
2186 char *remote_refname;
2187 struct got_reference *ref;
2189 if (strncmp("refs/", refname, 5) == 0)
2190 refname += 5;
2192 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2193 remote_repo_name, refname) == -1)
2194 return got_error_from_errno("asprintf");
2196 err = got_ref_open(&ref, repo, remote_refname, 1);
2197 if (err) {
2198 if (err->code != GOT_ERR_NOT_REF)
2199 goto done;
2200 err = create_ref(remote_refname, id, verbosity, repo);
2201 } else {
2202 err = update_ref(ref, id, 0, verbosity, repo);
2203 unlock_err = got_ref_unlock(ref);
2204 if (unlock_err && err == NULL)
2205 err = unlock_err;
2206 got_ref_close(ref);
2208 done:
2209 free(remote_refname);
2210 return err;
2213 static const struct got_error *
2214 delete_ref(struct got_repository *repo, struct got_reference *ref)
2216 const struct got_error *err = NULL;
2217 struct got_object_id *id = NULL;
2218 char *id_str = NULL;
2219 const char *target;
2221 if (got_ref_is_symbolic(ref)) {
2222 target = got_ref_get_symref_target(ref);
2223 } else {
2224 err = got_ref_resolve(&id, repo, ref);
2225 if (err)
2226 goto done;
2227 err = got_object_id_str(&id_str, id);
2228 if (err)
2229 goto done;
2230 target = id_str;
2233 err = got_ref_delete(ref, repo);
2234 if (err)
2235 goto done;
2237 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2238 done:
2239 free(id);
2240 free(id_str);
2241 return err;
2244 static const struct got_error *
2245 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2247 const struct got_error *err = NULL;
2248 struct got_reflist_head refs;
2249 struct got_reflist_entry *re;
2250 char *prefix;
2252 TAILQ_INIT(&refs);
2254 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2255 err = got_error_from_errno("asprintf");
2256 goto done;
2258 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2259 if (err)
2260 goto done;
2262 TAILQ_FOREACH(re, &refs, entry)
2263 delete_ref(repo, re->ref);
2264 done:
2265 got_ref_list_free(&refs);
2266 return err;
2269 static const struct got_error *
2270 cmd_fetch(int argc, char *argv[])
2272 const struct got_error *error = NULL, *unlock_err;
2273 char *cwd = NULL, *repo_path = NULL;
2274 const char *remote_name;
2275 char *proto = NULL, *host = NULL, *port = NULL;
2276 char *repo_name = NULL, *server_path = NULL;
2277 const struct got_remote_repo *remotes, *remote = NULL;
2278 int nremotes;
2279 char *id_str = NULL;
2280 struct got_repository *repo = NULL;
2281 struct got_worktree *worktree = NULL;
2282 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2283 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2284 struct got_pathlist_entry *pe;
2285 struct got_object_id *pack_hash = NULL;
2286 int i, ch, fetchfd = -1, fetchstatus;
2287 pid_t fetchpid = -1;
2288 struct got_fetch_progress_arg fpa;
2289 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2290 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2291 int *pack_fds = NULL, have_bflag = 0;
2292 const char *worktree_branch = NULL;
2294 TAILQ_INIT(&refs);
2295 TAILQ_INIT(&symrefs);
2296 TAILQ_INIT(&wanted_branches);
2297 TAILQ_INIT(&wanted_refs);
2299 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2300 switch (ch) {
2301 case 'a':
2302 fetch_all_branches = 1;
2303 break;
2304 case 'b':
2305 error = got_pathlist_append(&wanted_branches,
2306 optarg, NULL);
2307 if (error)
2308 return error;
2309 have_bflag = 1;
2310 break;
2311 case 'd':
2312 delete_refs = 1;
2313 break;
2314 case 'l':
2315 list_refs_only = 1;
2316 break;
2317 case 'q':
2318 verbosity = -1;
2319 break;
2320 case 'R':
2321 error = got_pathlist_append(&wanted_refs,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 break;
2326 case 'r':
2327 repo_path = realpath(optarg, NULL);
2328 if (repo_path == NULL)
2329 return got_error_from_errno2("realpath",
2330 optarg);
2331 got_path_strip_trailing_slashes(repo_path);
2332 break;
2333 case 't':
2334 replace_tags = 1;
2335 break;
2336 case 'v':
2337 if (verbosity < 0)
2338 verbosity = 0;
2339 else if (verbosity < 3)
2340 verbosity++;
2341 break;
2342 case 'X':
2343 delete_remote = 1;
2344 break;
2345 default:
2346 usage_fetch();
2347 break;
2350 argc -= optind;
2351 argv += optind;
2353 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2354 option_conflict('a', 'b');
2355 if (list_refs_only) {
2356 if (!TAILQ_EMPTY(&wanted_branches))
2357 option_conflict('l', 'b');
2358 if (fetch_all_branches)
2359 option_conflict('l', 'a');
2360 if (delete_refs)
2361 option_conflict('l', 'd');
2362 if (delete_remote)
2363 option_conflict('l', 'X');
2365 if (delete_remote) {
2366 if (fetch_all_branches)
2367 option_conflict('X', 'a');
2368 if (!TAILQ_EMPTY(&wanted_branches))
2369 option_conflict('X', 'b');
2370 if (delete_refs)
2371 option_conflict('X', 'd');
2372 if (replace_tags)
2373 option_conflict('X', 't');
2374 if (!TAILQ_EMPTY(&wanted_refs))
2375 option_conflict('X', 'R');
2378 if (argc == 0) {
2379 if (delete_remote)
2380 errx(1, "-X option requires a remote name");
2381 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2382 } else if (argc == 1)
2383 remote_name = argv[0];
2384 else
2385 usage_fetch();
2387 cwd = getcwd(NULL, 0);
2388 if (cwd == NULL) {
2389 error = got_error_from_errno("getcwd");
2390 goto done;
2393 error = got_repo_pack_fds_open(&pack_fds);
2394 if (error != NULL)
2395 goto done;
2397 if (repo_path == NULL) {
2398 error = got_worktree_open(&worktree, cwd);
2399 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2400 goto done;
2401 else
2402 error = NULL;
2403 if (worktree) {
2404 repo_path =
2405 strdup(got_worktree_get_repo_path(worktree));
2406 if (repo_path == NULL)
2407 error = got_error_from_errno("strdup");
2408 if (error)
2409 goto done;
2410 } else {
2411 repo_path = strdup(cwd);
2412 if (repo_path == NULL) {
2413 error = got_error_from_errno("strdup");
2414 goto done;
2419 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2420 if (error)
2421 goto done;
2423 if (delete_remote) {
2424 error = delete_refs_for_remote(repo, remote_name);
2425 goto done; /* nothing else to do */
2428 if (worktree) {
2429 worktree_conf = got_worktree_get_gotconfig(worktree);
2430 if (worktree_conf) {
2431 got_gotconfig_get_remotes(&nremotes, &remotes,
2432 worktree_conf);
2433 for (i = 0; i < nremotes; i++) {
2434 if (strcmp(remotes[i].name, remote_name) == 0) {
2435 remote = &remotes[i];
2436 break;
2441 if (remote == NULL) {
2442 repo_conf = got_repo_get_gotconfig(repo);
2443 if (repo_conf) {
2444 got_gotconfig_get_remotes(&nremotes, &remotes,
2445 repo_conf);
2446 for (i = 0; i < nremotes; i++) {
2447 if (strcmp(remotes[i].name, remote_name) == 0) {
2448 remote = &remotes[i];
2449 break;
2454 if (remote == NULL) {
2455 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2456 for (i = 0; i < nremotes; i++) {
2457 if (strcmp(remotes[i].name, remote_name) == 0) {
2458 remote = &remotes[i];
2459 break;
2463 if (remote == NULL) {
2464 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2465 goto done;
2468 if (TAILQ_EMPTY(&wanted_branches)) {
2469 if (!fetch_all_branches)
2470 fetch_all_branches = remote->fetch_all_branches;
2471 for (i = 0; i < remote->nfetch_branches; i++) {
2472 error = got_pathlist_append(&wanted_branches,
2473 remote->fetch_branches[i], NULL);
2474 if (error)
2475 goto done;
2478 if (TAILQ_EMPTY(&wanted_refs)) {
2479 for (i = 0; i < remote->nfetch_refs; i++) {
2480 error = got_pathlist_append(&wanted_refs,
2481 remote->fetch_refs[i], NULL);
2482 if (error)
2483 goto done;
2487 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2488 &repo_name, remote->fetch_url);
2489 if (error)
2490 goto done;
2492 if (strcmp(proto, "git") == 0) {
2493 #ifndef PROFILE
2494 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2495 "sendfd dns inet unveil", NULL) == -1)
2496 err(1, "pledge");
2497 #endif
2498 } else if (strcmp(proto, "git+ssh") == 0 ||
2499 strcmp(proto, "ssh") == 0) {
2500 #ifndef PROFILE
2501 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2502 "sendfd unveil", NULL) == -1)
2503 err(1, "pledge");
2504 #endif
2505 } else if (strcmp(proto, "http") == 0 ||
2506 strcmp(proto, "git+http") == 0) {
2507 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2508 goto done;
2509 } else {
2510 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2511 goto done;
2514 error = got_dial_apply_unveil(proto);
2515 if (error)
2516 goto done;
2518 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2519 if (error)
2520 goto done;
2522 if (verbosity >= 0) {
2523 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2524 remote->name, proto, host,
2525 port ? ":" : "", port ? port : "",
2526 *server_path == '/' ? "" : "/", server_path);
2529 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2530 server_path, verbosity);
2531 if (error)
2532 goto done;
2534 if (worktree && !have_bflag) {
2535 const char *refname;
2537 refname = got_worktree_get_head_ref_name(worktree);
2538 if (strncmp(refname, "refs/heads/", 11) == 0)
2539 worktree_branch = refname;
2542 fpa.last_scaled_size[0] = '\0';
2543 fpa.last_p_indexed = -1;
2544 fpa.last_p_resolved = -1;
2545 fpa.verbosity = verbosity;
2546 fpa.repo = repo;
2547 fpa.create_configs = 0;
2548 fpa.configs_created = 0;
2549 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2550 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2551 remote->mirror_references, fetch_all_branches, &wanted_branches,
2552 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2553 worktree_branch, fetch_progress, &fpa);
2554 if (error)
2555 goto done;
2557 if (list_refs_only) {
2558 error = list_remote_refs(&symrefs, &refs);
2559 goto done;
2562 if (pack_hash == NULL) {
2563 if (verbosity >= 0)
2564 printf("Already up-to-date\n");
2565 } else if (verbosity >= 0) {
2566 error = got_object_id_str(&id_str, pack_hash);
2567 if (error)
2568 goto done;
2569 printf("\nFetched %s.pack\n", id_str);
2570 free(id_str);
2571 id_str = NULL;
2574 /* Update references provided with the pack file. */
2575 TAILQ_FOREACH(pe, &refs, entry) {
2576 const char *refname = pe->path;
2577 struct got_object_id *id = pe->data;
2578 struct got_reference *ref;
2579 char *remote_refname;
2581 if (is_wanted_ref(&wanted_refs, refname) &&
2582 !remote->mirror_references) {
2583 error = update_wanted_ref(refname, id,
2584 remote->name, verbosity, repo);
2585 if (error)
2586 goto done;
2587 continue;
2590 if (remote->mirror_references ||
2591 strncmp("refs/tags/", refname, 10) == 0) {
2592 error = got_ref_open(&ref, repo, refname, 1);
2593 if (error) {
2594 if (error->code != GOT_ERR_NOT_REF)
2595 goto done;
2596 error = create_ref(refname, id, verbosity,
2597 repo);
2598 if (error)
2599 goto done;
2600 } else {
2601 error = update_ref(ref, id, replace_tags,
2602 verbosity, repo);
2603 unlock_err = got_ref_unlock(ref);
2604 if (unlock_err && error == NULL)
2605 error = unlock_err;
2606 got_ref_close(ref);
2607 if (error)
2608 goto done;
2610 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2611 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2612 remote_name, refname + 11) == -1) {
2613 error = got_error_from_errno("asprintf");
2614 goto done;
2617 error = got_ref_open(&ref, repo, remote_refname, 1);
2618 if (error) {
2619 if (error->code != GOT_ERR_NOT_REF)
2620 goto done;
2621 error = create_ref(remote_refname, id,
2622 verbosity, repo);
2623 if (error)
2624 goto done;
2625 } else {
2626 error = update_ref(ref, id, replace_tags,
2627 verbosity, repo);
2628 unlock_err = got_ref_unlock(ref);
2629 if (unlock_err && error == NULL)
2630 error = unlock_err;
2631 got_ref_close(ref);
2632 if (error)
2633 goto done;
2636 /* Also create a local branch if none exists yet. */
2637 error = got_ref_open(&ref, repo, refname, 1);
2638 if (error) {
2639 if (error->code != GOT_ERR_NOT_REF)
2640 goto done;
2641 error = create_ref(refname, id, verbosity,
2642 repo);
2643 if (error)
2644 goto done;
2645 } else {
2646 unlock_err = got_ref_unlock(ref);
2647 if (unlock_err && error == NULL)
2648 error = unlock_err;
2649 got_ref_close(ref);
2653 if (delete_refs) {
2654 error = delete_missing_refs(&refs, &symrefs, remote,
2655 verbosity, repo);
2656 if (error)
2657 goto done;
2660 if (!remote->mirror_references) {
2661 /* Update remote HEAD reference if the server provided one. */
2662 TAILQ_FOREACH(pe, &symrefs, entry) {
2663 struct got_reference *target_ref;
2664 const char *refname = pe->path;
2665 const char *target = pe->data;
2666 char *remote_refname = NULL, *remote_target = NULL;
2668 if (strcmp(refname, GOT_REF_HEAD) != 0)
2669 continue;
2671 if (strncmp("refs/heads/", target, 11) != 0)
2672 continue;
2674 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2675 remote->name, refname) == -1) {
2676 error = got_error_from_errno("asprintf");
2677 goto done;
2679 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2680 remote->name, target + 11) == -1) {
2681 error = got_error_from_errno("asprintf");
2682 free(remote_refname);
2683 goto done;
2686 error = got_ref_open(&target_ref, repo, remote_target,
2687 0);
2688 if (error) {
2689 free(remote_refname);
2690 free(remote_target);
2691 if (error->code == GOT_ERR_NOT_REF) {
2692 error = NULL;
2693 continue;
2695 goto done;
2697 error = update_symref(remote_refname, target_ref,
2698 verbosity, repo);
2699 free(remote_refname);
2700 free(remote_target);
2701 got_ref_close(target_ref);
2702 if (error)
2703 goto done;
2706 done:
2707 if (fetchpid > 0) {
2708 if (kill(fetchpid, SIGTERM) == -1)
2709 error = got_error_from_errno("kill");
2710 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2711 error = got_error_from_errno("waitpid");
2713 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2714 error = got_error_from_errno("close");
2715 if (repo) {
2716 const struct got_error *close_err = got_repo_close(repo);
2717 if (error == NULL)
2718 error = close_err;
2720 if (worktree)
2721 got_worktree_close(worktree);
2722 if (pack_fds) {
2723 const struct got_error *pack_err =
2724 got_repo_pack_fds_close(pack_fds);
2725 if (error == NULL)
2726 error = pack_err;
2728 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2729 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2730 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2731 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2732 free(id_str);
2733 free(cwd);
2734 free(repo_path);
2735 free(pack_hash);
2736 free(proto);
2737 free(host);
2738 free(port);
2739 free(server_path);
2740 free(repo_name);
2741 return error;
2745 __dead static void
2746 usage_checkout(void)
2748 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2749 "[-p path-prefix] repository-path [work-tree-path]\n",
2750 getprogname());
2751 exit(1);
2754 static void
2755 show_worktree_base_ref_warning(void)
2757 fprintf(stderr, "%s: warning: could not create a reference "
2758 "to the work tree's base commit; the commit could be "
2759 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2760 "repository writable and running 'got update' will prevent this\n",
2761 getprogname());
2764 struct got_checkout_progress_arg {
2765 const char *worktree_path;
2766 int had_base_commit_ref_error;
2767 int verbosity;
2770 static const struct got_error *
2771 checkout_progress(void *arg, unsigned char status, const char *path)
2773 struct got_checkout_progress_arg *a = arg;
2775 /* Base commit bump happens silently. */
2776 if (status == GOT_STATUS_BUMP_BASE)
2777 return NULL;
2779 if (status == GOT_STATUS_BASE_REF_ERR) {
2780 a->had_base_commit_ref_error = 1;
2781 return NULL;
2784 while (path[0] == '/')
2785 path++;
2787 if (a->verbosity >= 0)
2788 printf("%c %s/%s\n", status, a->worktree_path, path);
2790 return NULL;
2793 static const struct got_error *
2794 check_cancelled(void *arg)
2796 if (sigint_received || sigpipe_received)
2797 return got_error(GOT_ERR_CANCELLED);
2798 return NULL;
2801 static const struct got_error *
2802 check_linear_ancestry(struct got_object_id *commit_id,
2803 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2804 struct got_repository *repo)
2806 const struct got_error *err = NULL;
2807 struct got_object_id *yca_id;
2809 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2810 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2811 if (err)
2812 return err;
2814 if (yca_id == NULL)
2815 return got_error(GOT_ERR_ANCESTRY);
2818 * Require a straight line of history between the target commit
2819 * and the work tree's base commit.
2821 * Non-linear situations such as this require a rebase:
2823 * (commit) D F (base_commit)
2824 * \ /
2825 * C E
2826 * \ /
2827 * B (yca)
2828 * |
2829 * A
2831 * 'got update' only handles linear cases:
2832 * Update forwards in time: A (base/yca) - B - C - D (commit)
2833 * Update backwards in time: D (base) - C - B - A (commit/yca)
2835 if (allow_forwards_in_time_only) {
2836 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2837 return got_error(GOT_ERR_ANCESTRY);
2838 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2839 got_object_id_cmp(base_commit_id, yca_id) != 0)
2840 return got_error(GOT_ERR_ANCESTRY);
2842 free(yca_id);
2843 return NULL;
2846 static const struct got_error *
2847 check_same_branch(struct got_object_id *commit_id,
2848 struct got_reference *head_ref, struct got_object_id *yca_id,
2849 struct got_repository *repo)
2851 const struct got_error *err = NULL;
2852 struct got_commit_graph *graph = NULL;
2853 struct got_object_id *head_commit_id = NULL;
2854 int is_same_branch = 0;
2856 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2857 if (err)
2858 goto done;
2860 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2861 is_same_branch = 1;
2862 goto done;
2864 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2865 is_same_branch = 1;
2866 goto done;
2869 err = got_commit_graph_open(&graph, "/", 1);
2870 if (err)
2871 goto done;
2873 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2874 check_cancelled, NULL);
2875 if (err)
2876 goto done;
2878 for (;;) {
2879 struct got_object_id id;
2881 err = got_commit_graph_iter_next(&id, graph, repo,
2882 check_cancelled, NULL);
2883 if (err) {
2884 if (err->code == GOT_ERR_ITER_COMPLETED)
2885 err = NULL;
2886 break;
2889 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2890 break;
2891 if (got_object_id_cmp(&id, commit_id) == 0) {
2892 is_same_branch = 1;
2893 break;
2896 done:
2897 if (graph)
2898 got_commit_graph_close(graph);
2899 free(head_commit_id);
2900 if (!err && !is_same_branch)
2901 err = got_error(GOT_ERR_ANCESTRY);
2902 return err;
2905 static const struct got_error *
2906 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2908 static char msg[512];
2909 const char *branch_name;
2911 if (got_ref_is_symbolic(ref))
2912 branch_name = got_ref_get_symref_target(ref);
2913 else
2914 branch_name = got_ref_get_name(ref);
2916 if (strncmp("refs/heads/", branch_name, 11) == 0)
2917 branch_name += 11;
2919 snprintf(msg, sizeof(msg),
2920 "target commit is not contained in branch '%s'; "
2921 "the branch to use must be specified with -b; "
2922 "if necessary a new branch can be created for "
2923 "this commit with 'got branch -c %s BRANCH_NAME'",
2924 branch_name, commit_id_str);
2926 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2929 static const struct got_error *
2930 cmd_checkout(int argc, char *argv[])
2932 const struct got_error *error = NULL;
2933 struct got_repository *repo = NULL;
2934 struct got_reference *head_ref = NULL, *ref = NULL;
2935 struct got_worktree *worktree = NULL;
2936 char *repo_path = NULL;
2937 char *worktree_path = NULL;
2938 const char *path_prefix = "";
2939 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2940 char *commit_id_str = NULL;
2941 struct got_object_id *commit_id = NULL;
2942 char *cwd = NULL;
2943 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2944 struct got_pathlist_head paths;
2945 struct got_checkout_progress_arg cpa;
2946 int *pack_fds = NULL;
2948 TAILQ_INIT(&paths);
2950 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2951 switch (ch) {
2952 case 'b':
2953 branch_name = optarg;
2954 break;
2955 case 'c':
2956 commit_id_str = strdup(optarg);
2957 if (commit_id_str == NULL)
2958 return got_error_from_errno("strdup");
2959 break;
2960 case 'E':
2961 allow_nonempty = 1;
2962 break;
2963 case 'p':
2964 path_prefix = optarg;
2965 break;
2966 case 'q':
2967 verbosity = -1;
2968 break;
2969 default:
2970 usage_checkout();
2971 /* NOTREACHED */
2975 argc -= optind;
2976 argv += optind;
2978 #ifndef PROFILE
2979 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2980 "unveil", NULL) == -1)
2981 err(1, "pledge");
2982 #endif
2983 if (argc == 1) {
2984 char *base, *dotgit;
2985 const char *path;
2986 repo_path = realpath(argv[0], NULL);
2987 if (repo_path == NULL)
2988 return got_error_from_errno2("realpath", argv[0]);
2989 cwd = getcwd(NULL, 0);
2990 if (cwd == NULL) {
2991 error = got_error_from_errno("getcwd");
2992 goto done;
2994 if (path_prefix[0])
2995 path = path_prefix;
2996 else
2997 path = repo_path;
2998 error = got_path_basename(&base, path);
2999 if (error)
3000 goto done;
3001 dotgit = strstr(base, ".git");
3002 if (dotgit)
3003 *dotgit = '\0';
3004 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3005 error = got_error_from_errno("asprintf");
3006 free(base);
3007 goto done;
3009 free(base);
3010 } else if (argc == 2) {
3011 repo_path = realpath(argv[0], NULL);
3012 if (repo_path == NULL) {
3013 error = got_error_from_errno2("realpath", argv[0]);
3014 goto done;
3016 worktree_path = realpath(argv[1], NULL);
3017 if (worktree_path == NULL) {
3018 if (errno != ENOENT) {
3019 error = got_error_from_errno2("realpath",
3020 argv[1]);
3021 goto done;
3023 worktree_path = strdup(argv[1]);
3024 if (worktree_path == NULL) {
3025 error = got_error_from_errno("strdup");
3026 goto done;
3029 } else
3030 usage_checkout();
3032 got_path_strip_trailing_slashes(repo_path);
3033 got_path_strip_trailing_slashes(worktree_path);
3035 error = got_repo_pack_fds_open(&pack_fds);
3036 if (error != NULL)
3037 goto done;
3039 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3040 if (error != NULL)
3041 goto done;
3043 /* Pre-create work tree path for unveil(2) */
3044 error = got_path_mkdir(worktree_path);
3045 if (error) {
3046 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3047 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3048 goto done;
3049 if (!allow_nonempty &&
3050 !got_path_dir_is_empty(worktree_path)) {
3051 error = got_error_path(worktree_path,
3052 GOT_ERR_DIR_NOT_EMPTY);
3053 goto done;
3057 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3058 if (error)
3059 goto done;
3061 error = got_ref_open(&head_ref, repo, branch_name, 0);
3062 if (error != NULL)
3063 goto done;
3065 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3066 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3067 goto done;
3069 error = got_worktree_open(&worktree, worktree_path);
3070 if (error != NULL)
3071 goto done;
3073 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3074 path_prefix);
3075 if (error != NULL)
3076 goto done;
3077 if (!same_path_prefix) {
3078 error = got_error(GOT_ERR_PATH_PREFIX);
3079 goto done;
3082 if (commit_id_str) {
3083 struct got_reflist_head refs;
3084 TAILQ_INIT(&refs);
3085 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3086 NULL);
3087 if (error)
3088 goto done;
3089 error = got_repo_match_object_id(&commit_id, NULL,
3090 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3091 got_ref_list_free(&refs);
3092 if (error)
3093 goto done;
3094 error = check_linear_ancestry(commit_id,
3095 got_worktree_get_base_commit_id(worktree), 0, repo);
3096 if (error != NULL) {
3097 if (error->code == GOT_ERR_ANCESTRY) {
3098 error = checkout_ancestry_error(
3099 head_ref, commit_id_str);
3101 goto done;
3103 error = check_same_branch(commit_id, head_ref, NULL, repo);
3104 if (error) {
3105 if (error->code == GOT_ERR_ANCESTRY) {
3106 error = checkout_ancestry_error(
3107 head_ref, commit_id_str);
3109 goto done;
3111 error = got_worktree_set_base_commit_id(worktree, repo,
3112 commit_id);
3113 if (error)
3114 goto done;
3115 /* Expand potentially abbreviated commit ID string. */
3116 free(commit_id_str);
3117 error = got_object_id_str(&commit_id_str, commit_id);
3118 if (error)
3119 goto done;
3120 } else {
3121 commit_id = got_object_id_dup(
3122 got_worktree_get_base_commit_id(worktree));
3123 if (commit_id == NULL) {
3124 error = got_error_from_errno("got_object_id_dup");
3125 goto done;
3127 error = got_object_id_str(&commit_id_str, commit_id);
3128 if (error)
3129 goto done;
3132 error = got_pathlist_append(&paths, "", NULL);
3133 if (error)
3134 goto done;
3135 cpa.worktree_path = worktree_path;
3136 cpa.had_base_commit_ref_error = 0;
3137 cpa.verbosity = verbosity;
3138 error = got_worktree_checkout_files(worktree, &paths, repo,
3139 checkout_progress, &cpa, check_cancelled, NULL);
3140 if (error != NULL)
3141 goto done;
3143 if (got_ref_is_symbolic(head_ref)) {
3144 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3145 if (error)
3146 goto done;
3147 refname = got_ref_get_name(ref);
3148 } else
3149 refname = got_ref_get_name(head_ref);
3150 printf("Checked out %s: %s\n", refname, commit_id_str);
3151 printf("Now shut up and hack\n");
3152 if (cpa.had_base_commit_ref_error)
3153 show_worktree_base_ref_warning();
3154 done:
3155 if (pack_fds) {
3156 const struct got_error *pack_err =
3157 got_repo_pack_fds_close(pack_fds);
3158 if (error == NULL)
3159 error = pack_err;
3161 if (head_ref)
3162 got_ref_close(head_ref);
3163 if (ref)
3164 got_ref_close(ref);
3165 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3166 free(commit_id_str);
3167 free(commit_id);
3168 free(repo_path);
3169 free(worktree_path);
3170 free(cwd);
3171 return error;
3174 struct got_update_progress_arg {
3175 int did_something;
3176 int conflicts;
3177 int obstructed;
3178 int not_updated;
3179 int missing;
3180 int not_deleted;
3181 int unversioned;
3182 int verbosity;
3185 static void
3186 print_update_progress_stats(struct got_update_progress_arg *upa)
3188 if (!upa->did_something)
3189 return;
3191 if (upa->conflicts > 0)
3192 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3193 if (upa->obstructed > 0)
3194 printf("File paths obstructed by a non-regular file: %d\n",
3195 upa->obstructed);
3196 if (upa->not_updated > 0)
3197 printf("Files not updated because of existing merge "
3198 "conflicts: %d\n", upa->not_updated);
3202 * The meaning of some status codes differs between merge-style operations and
3203 * update operations. For example, the ! status code means "file was missing"
3204 * if changes were merged into the work tree, and "missing file was restored"
3205 * if the work tree was updated. This function should be used by any operation
3206 * which merges changes into the work tree without updating the work tree.
3208 static void
3209 print_merge_progress_stats(struct got_update_progress_arg *upa)
3211 if (!upa->did_something)
3212 return;
3214 if (upa->conflicts > 0)
3215 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3216 if (upa->obstructed > 0)
3217 printf("File paths obstructed by a non-regular file: %d\n",
3218 upa->obstructed);
3219 if (upa->missing > 0)
3220 printf("Files which had incoming changes but could not be "
3221 "found in the work tree: %d\n", upa->missing);
3222 if (upa->not_deleted > 0)
3223 printf("Files not deleted due to differences in deleted "
3224 "content: %d\n", upa->not_deleted);
3225 if (upa->unversioned > 0)
3226 printf("Files not merged because an unversioned file was "
3227 "found in the work tree: %d\n", upa->unversioned);
3230 __dead static void
3231 usage_update(void)
3233 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3234 "[path ...]\n", getprogname());
3235 exit(1);
3238 static const struct got_error *
3239 update_progress(void *arg, unsigned char status, const char *path)
3241 struct got_update_progress_arg *upa = arg;
3243 if (status == GOT_STATUS_EXISTS ||
3244 status == GOT_STATUS_BASE_REF_ERR)
3245 return NULL;
3247 upa->did_something = 1;
3249 /* Base commit bump happens silently. */
3250 if (status == GOT_STATUS_BUMP_BASE)
3251 return NULL;
3253 if (status == GOT_STATUS_CONFLICT)
3254 upa->conflicts++;
3255 if (status == GOT_STATUS_OBSTRUCTED)
3256 upa->obstructed++;
3257 if (status == GOT_STATUS_CANNOT_UPDATE)
3258 upa->not_updated++;
3259 if (status == GOT_STATUS_MISSING)
3260 upa->missing++;
3261 if (status == GOT_STATUS_CANNOT_DELETE)
3262 upa->not_deleted++;
3263 if (status == GOT_STATUS_UNVERSIONED)
3264 upa->unversioned++;
3266 while (path[0] == '/')
3267 path++;
3268 if (upa->verbosity >= 0)
3269 printf("%c %s\n", status, path);
3271 return NULL;
3274 static const struct got_error *
3275 switch_head_ref(struct got_reference *head_ref,
3276 struct got_object_id *commit_id, struct got_worktree *worktree,
3277 struct got_repository *repo)
3279 const struct got_error *err = NULL;
3280 char *base_id_str;
3281 int ref_has_moved = 0;
3283 /* Trivial case: switching between two different references. */
3284 if (strcmp(got_ref_get_name(head_ref),
3285 got_worktree_get_head_ref_name(worktree)) != 0) {
3286 printf("Switching work tree from %s to %s\n",
3287 got_worktree_get_head_ref_name(worktree),
3288 got_ref_get_name(head_ref));
3289 return got_worktree_set_head_ref(worktree, head_ref);
3292 err = check_linear_ancestry(commit_id,
3293 got_worktree_get_base_commit_id(worktree), 0, repo);
3294 if (err) {
3295 if (err->code != GOT_ERR_ANCESTRY)
3296 return err;
3297 ref_has_moved = 1;
3299 if (!ref_has_moved)
3300 return NULL;
3302 /* Switching to a rebased branch with the same reference name. */
3303 err = got_object_id_str(&base_id_str,
3304 got_worktree_get_base_commit_id(worktree));
3305 if (err)
3306 return err;
3307 printf("Reference %s now points at a different branch\n",
3308 got_worktree_get_head_ref_name(worktree));
3309 printf("Switching work tree from %s to %s\n", base_id_str,
3310 got_worktree_get_head_ref_name(worktree));
3311 return NULL;
3314 static const struct got_error *
3315 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3317 const struct got_error *err;
3318 int in_progress;
3320 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3321 if (err)
3322 return err;
3323 if (in_progress)
3324 return got_error(GOT_ERR_REBASING);
3326 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3327 if (err)
3328 return err;
3329 if (in_progress)
3330 return got_error(GOT_ERR_HISTEDIT_BUSY);
3332 return NULL;
3335 static const struct got_error *
3336 check_merge_in_progress(struct got_worktree *worktree,
3337 struct got_repository *repo)
3339 const struct got_error *err;
3340 int in_progress;
3342 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3343 if (err)
3344 return err;
3345 if (in_progress)
3346 return got_error(GOT_ERR_MERGE_BUSY);
3348 return NULL;
3351 static const struct got_error *
3352 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3353 char *argv[], struct got_worktree *worktree)
3355 const struct got_error *err = NULL;
3356 char *path;
3357 struct got_pathlist_entry *new;
3358 int i;
3360 if (argc == 0) {
3361 path = strdup("");
3362 if (path == NULL)
3363 return got_error_from_errno("strdup");
3364 return got_pathlist_append(paths, path, NULL);
3367 for (i = 0; i < argc; i++) {
3368 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3369 if (err)
3370 break;
3371 err = got_pathlist_insert(&new, paths, path, NULL);
3372 if (err || new == NULL /* duplicate */) {
3373 free(path);
3374 if (err)
3375 break;
3379 return err;
3382 static const struct got_error *
3383 wrap_not_worktree_error(const struct got_error *orig_err,
3384 const char *cmdname, const char *path)
3386 const struct got_error *err;
3387 struct got_repository *repo;
3388 static char msg[512];
3389 int *pack_fds = NULL;
3391 err = got_repo_pack_fds_open(&pack_fds);
3392 if (err)
3393 return err;
3395 err = got_repo_open(&repo, path, NULL, pack_fds);
3396 if (err)
3397 return orig_err;
3399 snprintf(msg, sizeof(msg),
3400 "'got %s' needs a work tree in addition to a git repository\n"
3401 "Work trees can be checked out from this Git repository with "
3402 "'got checkout'.\n"
3403 "The got(1) manual page contains more information.", cmdname);
3404 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3405 got_repo_close(repo);
3406 if (pack_fds) {
3407 const struct got_error *pack_err =
3408 got_repo_pack_fds_close(pack_fds);
3409 if (err == NULL)
3410 err = pack_err;
3412 return err;
3415 static const struct got_error *
3416 cmd_update(int argc, char *argv[])
3418 const struct got_error *error = NULL;
3419 struct got_repository *repo = NULL;
3420 struct got_worktree *worktree = NULL;
3421 char *worktree_path = NULL;
3422 struct got_object_id *commit_id = NULL;
3423 char *commit_id_str = NULL;
3424 const char *branch_name = NULL;
3425 struct got_reference *head_ref = NULL;
3426 struct got_pathlist_head paths;
3427 struct got_pathlist_entry *pe;
3428 int ch, verbosity = 0;
3429 struct got_update_progress_arg upa;
3430 int *pack_fds = NULL;
3432 TAILQ_INIT(&paths);
3434 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3435 switch (ch) {
3436 case 'b':
3437 branch_name = optarg;
3438 break;
3439 case 'c':
3440 commit_id_str = strdup(optarg);
3441 if (commit_id_str == NULL)
3442 return got_error_from_errno("strdup");
3443 break;
3444 case 'q':
3445 verbosity = -1;
3446 break;
3447 default:
3448 usage_update();
3449 /* NOTREACHED */
3453 argc -= optind;
3454 argv += optind;
3456 #ifndef PROFILE
3457 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3458 "unveil", NULL) == -1)
3459 err(1, "pledge");
3460 #endif
3461 worktree_path = getcwd(NULL, 0);
3462 if (worktree_path == NULL) {
3463 error = got_error_from_errno("getcwd");
3464 goto done;
3467 error = got_repo_pack_fds_open(&pack_fds);
3468 if (error != NULL)
3469 goto done;
3471 error = got_worktree_open(&worktree, worktree_path);
3472 if (error) {
3473 if (error->code == GOT_ERR_NOT_WORKTREE)
3474 error = wrap_not_worktree_error(error, "update",
3475 worktree_path);
3476 goto done;
3479 error = check_rebase_or_histedit_in_progress(worktree);
3480 if (error)
3481 goto done;
3483 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3484 NULL, pack_fds);
3485 if (error != NULL)
3486 goto done;
3488 error = apply_unveil(got_repo_get_path(repo), 0,
3489 got_worktree_get_root_path(worktree));
3490 if (error)
3491 goto done;
3493 error = check_merge_in_progress(worktree, repo);
3494 if (error)
3495 goto done;
3497 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3498 if (error)
3499 goto done;
3501 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3502 got_worktree_get_head_ref_name(worktree), 0);
3503 if (error != NULL)
3504 goto done;
3505 if (commit_id_str == NULL) {
3506 error = got_ref_resolve(&commit_id, repo, head_ref);
3507 if (error != NULL)
3508 goto done;
3509 error = got_object_id_str(&commit_id_str, commit_id);
3510 if (error != NULL)
3511 goto done;
3512 } else {
3513 struct got_reflist_head refs;
3514 TAILQ_INIT(&refs);
3515 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3516 NULL);
3517 if (error)
3518 goto done;
3519 error = got_repo_match_object_id(&commit_id, NULL,
3520 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3521 got_ref_list_free(&refs);
3522 free(commit_id_str);
3523 commit_id_str = NULL;
3524 if (error)
3525 goto done;
3526 error = got_object_id_str(&commit_id_str, commit_id);
3527 if (error)
3528 goto done;
3531 if (branch_name) {
3532 struct got_object_id *head_commit_id;
3533 TAILQ_FOREACH(pe, &paths, entry) {
3534 if (pe->path_len == 0)
3535 continue;
3536 error = got_error_msg(GOT_ERR_BAD_PATH,
3537 "switching between branches requires that "
3538 "the entire work tree gets updated");
3539 goto done;
3541 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3542 if (error)
3543 goto done;
3544 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3545 repo);
3546 free(head_commit_id);
3547 if (error != NULL)
3548 goto done;
3549 error = check_same_branch(commit_id, head_ref, NULL, repo);
3550 if (error)
3551 goto done;
3552 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3553 if (error)
3554 goto done;
3555 } else {
3556 error = check_linear_ancestry(commit_id,
3557 got_worktree_get_base_commit_id(worktree), 0, repo);
3558 if (error != NULL) {
3559 if (error->code == GOT_ERR_ANCESTRY)
3560 error = got_error(GOT_ERR_BRANCH_MOVED);
3561 goto done;
3563 error = check_same_branch(commit_id, head_ref, NULL, repo);
3564 if (error)
3565 goto done;
3568 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3569 commit_id) != 0) {
3570 error = got_worktree_set_base_commit_id(worktree, repo,
3571 commit_id);
3572 if (error)
3573 goto done;
3576 memset(&upa, 0, sizeof(upa));
3577 upa.verbosity = verbosity;
3578 error = got_worktree_checkout_files(worktree, &paths, repo,
3579 update_progress, &upa, check_cancelled, NULL);
3580 if (error != NULL)
3581 goto done;
3583 if (upa.did_something) {
3584 printf("Updated to %s: %s\n",
3585 got_worktree_get_head_ref_name(worktree), commit_id_str);
3586 } else
3587 printf("Already up-to-date\n");
3589 print_update_progress_stats(&upa);
3590 done:
3591 if (pack_fds) {
3592 const struct got_error *pack_err =
3593 got_repo_pack_fds_close(pack_fds);
3594 if (error == NULL)
3595 error = pack_err;
3597 free(worktree_path);
3598 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3599 free(commit_id);
3600 free(commit_id_str);
3601 return error;
3604 static const struct got_error *
3605 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3606 const char *path, int diff_context, int ignore_whitespace,
3607 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3608 struct got_repository *repo, FILE *outfile)
3610 const struct got_error *err = NULL;
3611 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3612 FILE *f1 = NULL, *f2 = NULL;
3613 int fd1 = -1, fd2 = -1;
3615 fd1 = got_opentempfd();
3616 if (fd1 == -1)
3617 return got_error_from_errno("got_opentempfd");
3618 fd2 = got_opentempfd();
3619 if (fd2 == -1) {
3620 err = got_error_from_errno("got_opentempfd");
3621 goto done;
3624 if (blob_id1) {
3625 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3626 fd1);
3627 if (err)
3628 goto done;
3631 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3632 if (err)
3633 goto done;
3635 f1 = got_opentemp();
3636 if (f1 == NULL) {
3637 err = got_error_from_errno("got_opentemp");
3638 goto done;
3640 f2 = got_opentemp();
3641 if (f2 == NULL) {
3642 err = got_error_from_errno("got_opentemp");
3643 goto done;
3646 while (path[0] == '/')
3647 path++;
3648 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3649 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3650 force_text_diff, dsa, outfile);
3651 done:
3652 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3653 err = got_error_from_errno("close");
3654 if (blob1)
3655 got_object_blob_close(blob1);
3656 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3657 err = got_error_from_errno("close");
3658 got_object_blob_close(blob2);
3659 if (f1 && fclose(f1) == EOF && err == NULL)
3660 err = got_error_from_errno("fclose");
3661 if (f2 && fclose(f2) == EOF && err == NULL)
3662 err = got_error_from_errno("fclose");
3663 return err;
3666 static const struct got_error *
3667 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3668 const char *path, int diff_context, int ignore_whitespace,
3669 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3670 struct got_repository *repo, FILE *outfile)
3672 const struct got_error *err = NULL;
3673 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3674 struct got_diff_blob_output_unidiff_arg arg;
3675 FILE *f1 = NULL, *f2 = NULL;
3676 int fd1 = -1, fd2 = -1;
3678 if (tree_id1) {
3679 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3680 if (err)
3681 goto done;
3682 fd1 = got_opentempfd();
3683 if (fd1 == -1) {
3684 err = got_error_from_errno("got_opentempfd");
3685 goto done;
3689 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3690 if (err)
3691 goto done;
3693 f1 = got_opentemp();
3694 if (f1 == NULL) {
3695 err = got_error_from_errno("got_opentemp");
3696 goto done;
3699 f2 = got_opentemp();
3700 if (f2 == NULL) {
3701 err = got_error_from_errno("got_opentemp");
3702 goto done;
3704 fd2 = got_opentempfd();
3705 if (fd2 == -1) {
3706 err = got_error_from_errno("got_opentempfd");
3707 goto done;
3709 arg.diff_context = diff_context;
3710 arg.ignore_whitespace = ignore_whitespace;
3711 arg.force_text_diff = force_text_diff;
3712 arg.diffstat = dsa;
3713 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3714 arg.outfile = outfile;
3715 arg.lines = NULL;
3716 arg.nlines = 0;
3717 while (path[0] == '/')
3718 path++;
3719 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3720 got_diff_blob_output_unidiff, &arg, 1);
3721 done:
3722 if (tree1)
3723 got_object_tree_close(tree1);
3724 if (tree2)
3725 got_object_tree_close(tree2);
3726 if (f1 && fclose(f1) == EOF && err == NULL)
3727 err = got_error_from_errno("fclose");
3728 if (f2 && fclose(f2) == EOF && err == NULL)
3729 err = got_error_from_errno("fclose");
3730 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3731 err = got_error_from_errno("close");
3732 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3733 err = got_error_from_errno("close");
3734 return err;
3737 static const struct got_error *
3738 get_changed_paths(struct got_pathlist_head *paths,
3739 struct got_commit_object *commit, struct got_repository *repo,
3740 struct got_diffstat_cb_arg *dsa)
3742 const struct got_error *err = NULL;
3743 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3744 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3745 struct got_object_qid *qid;
3746 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3747 FILE *f1 = NULL, *f2 = NULL;
3748 int fd1 = -1, fd2 = -1;
3750 if (dsa) {
3751 cb = got_diff_tree_compute_diffstat;
3753 f1 = got_opentemp();
3754 if (f1 == NULL) {
3755 err = got_error_from_errno("got_opentemp");
3756 goto done;
3758 f2 = got_opentemp();
3759 if (f2 == NULL) {
3760 err = got_error_from_errno("got_opentemp");
3761 goto done;
3763 fd1 = got_opentempfd();
3764 if (fd1 == -1) {
3765 err = got_error_from_errno("got_opentempfd");
3766 goto done;
3768 fd2 = got_opentempfd();
3769 if (fd2 == -1) {
3770 err = got_error_from_errno("got_opentempfd");
3771 goto done;
3775 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3776 if (qid != NULL) {
3777 struct got_commit_object *pcommit;
3778 err = got_object_open_as_commit(&pcommit, repo,
3779 &qid->id);
3780 if (err)
3781 return err;
3783 tree_id1 = got_object_id_dup(
3784 got_object_commit_get_tree_id(pcommit));
3785 if (tree_id1 == NULL) {
3786 got_object_commit_close(pcommit);
3787 return got_error_from_errno("got_object_id_dup");
3789 got_object_commit_close(pcommit);
3793 if (tree_id1) {
3794 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3795 if (err)
3796 goto done;
3799 tree_id2 = got_object_commit_get_tree_id(commit);
3800 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3801 if (err)
3802 goto done;
3804 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3805 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3806 done:
3807 if (tree1)
3808 got_object_tree_close(tree1);
3809 if (tree2)
3810 got_object_tree_close(tree2);
3811 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3812 err = got_error_from_errno("close");
3813 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3814 err = got_error_from_errno("close");
3815 if (f1 && fclose(f1) == EOF && err == NULL)
3816 err = got_error_from_errno("fclose");
3817 if (f2 && fclose(f2) == EOF && err == NULL)
3818 err = got_error_from_errno("fclose");
3819 free(tree_id1);
3820 return err;
3823 static const struct got_error *
3824 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3825 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3826 struct got_repository *repo, FILE *outfile)
3828 const struct got_error *err = NULL;
3829 struct got_commit_object *pcommit = NULL;
3830 char *id_str1 = NULL, *id_str2 = NULL;
3831 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3832 struct got_object_qid *qid;
3834 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3835 if (qid != NULL) {
3836 err = got_object_open_as_commit(&pcommit, repo,
3837 &qid->id);
3838 if (err)
3839 return err;
3840 err = got_object_id_str(&id_str1, &qid->id);
3841 if (err)
3842 goto done;
3845 err = got_object_id_str(&id_str2, id);
3846 if (err)
3847 goto done;
3849 if (path && path[0] != '\0') {
3850 int obj_type;
3851 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3852 if (err)
3853 goto done;
3854 if (pcommit) {
3855 err = got_object_id_by_path(&obj_id1, repo,
3856 pcommit, path);
3857 if (err) {
3858 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3859 free(obj_id2);
3860 goto done;
3864 err = got_object_get_type(&obj_type, repo, obj_id2);
3865 if (err) {
3866 free(obj_id2);
3867 goto done;
3869 fprintf(outfile,
3870 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3871 fprintf(outfile, "commit - %s\n",
3872 id_str1 ? id_str1 : "/dev/null");
3873 fprintf(outfile, "commit + %s\n", id_str2);
3874 switch (obj_type) {
3875 case GOT_OBJ_TYPE_BLOB:
3876 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3877 0, 0, dsa, repo, outfile);
3878 break;
3879 case GOT_OBJ_TYPE_TREE:
3880 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3881 0, 0, dsa, repo, outfile);
3882 break;
3883 default:
3884 err = got_error(GOT_ERR_OBJ_TYPE);
3885 break;
3887 free(obj_id1);
3888 free(obj_id2);
3889 } else {
3890 obj_id2 = got_object_commit_get_tree_id(commit);
3891 if (pcommit)
3892 obj_id1 = got_object_commit_get_tree_id(pcommit);
3893 fprintf(outfile,
3894 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3895 fprintf(outfile, "commit - %s\n",
3896 id_str1 ? id_str1 : "/dev/null");
3897 fprintf(outfile, "commit + %s\n", id_str2);
3898 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3899 dsa, repo, outfile);
3901 done:
3902 free(id_str1);
3903 free(id_str2);
3904 if (pcommit)
3905 got_object_commit_close(pcommit);
3906 return err;
3909 static char *
3910 get_datestr(time_t *time, char *datebuf)
3912 struct tm mytm, *tm;
3913 char *p, *s;
3915 tm = gmtime_r(time, &mytm);
3916 if (tm == NULL)
3917 return NULL;
3918 s = asctime_r(tm, datebuf);
3919 if (s == NULL)
3920 return NULL;
3921 p = strchr(s, '\n');
3922 if (p)
3923 *p = '\0';
3924 return s;
3927 static const struct got_error *
3928 match_commit(int *have_match, struct got_object_id *id,
3929 struct got_commit_object *commit, regex_t *regex)
3931 const struct got_error *err = NULL;
3932 regmatch_t regmatch;
3933 char *id_str = NULL, *logmsg = NULL;
3935 *have_match = 0;
3937 err = got_object_id_str(&id_str, id);
3938 if (err)
3939 return err;
3941 err = got_object_commit_get_logmsg(&logmsg, commit);
3942 if (err)
3943 goto done;
3945 if (regexec(regex, got_object_commit_get_author(commit), 1,
3946 &regmatch, 0) == 0 ||
3947 regexec(regex, got_object_commit_get_committer(commit), 1,
3948 &regmatch, 0) == 0 ||
3949 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3950 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3951 *have_match = 1;
3952 done:
3953 free(id_str);
3954 free(logmsg);
3955 return err;
3958 static void
3959 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3960 regex_t *regex)
3962 regmatch_t regmatch;
3963 struct got_pathlist_entry *pe;
3965 *have_match = 0;
3967 TAILQ_FOREACH(pe, changed_paths, entry) {
3968 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3969 *have_match = 1;
3970 break;
3975 static const struct got_error *
3976 match_patch(int *have_match, struct got_commit_object *commit,
3977 struct got_object_id *id, const char *path, int diff_context,
3978 struct got_repository *repo, regex_t *regex, FILE *f)
3980 const struct got_error *err = NULL;
3981 char *line = NULL;
3982 size_t linesize = 0;
3983 regmatch_t regmatch;
3985 *have_match = 0;
3987 err = got_opentemp_truncate(f);
3988 if (err)
3989 return err;
3991 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3992 if (err)
3993 goto done;
3995 if (fseeko(f, 0L, SEEK_SET) == -1) {
3996 err = got_error_from_errno("fseeko");
3997 goto done;
4000 while (getline(&line, &linesize, f) != -1) {
4001 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4002 *have_match = 1;
4003 break;
4006 done:
4007 free(line);
4008 return err;
4011 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4013 static const struct got_error*
4014 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4015 struct got_object_id *id, struct got_repository *repo,
4016 int local_only)
4018 static const struct got_error *err = NULL;
4019 struct got_reflist_entry *re;
4020 char *s;
4021 const char *name;
4023 *refs_str = NULL;
4025 TAILQ_FOREACH(re, refs, entry) {
4026 struct got_tag_object *tag = NULL;
4027 struct got_object_id *ref_id;
4028 int cmp;
4030 name = got_ref_get_name(re->ref);
4031 if (strcmp(name, GOT_REF_HEAD) == 0)
4032 continue;
4033 if (strncmp(name, "refs/", 5) == 0)
4034 name += 5;
4035 if (strncmp(name, "got/", 4) == 0)
4036 continue;
4037 if (strncmp(name, "heads/", 6) == 0)
4038 name += 6;
4039 if (strncmp(name, "remotes/", 8) == 0) {
4040 if (local_only)
4041 continue;
4042 name += 8;
4043 s = strstr(name, "/" GOT_REF_HEAD);
4044 if (s != NULL && s[strlen(s)] == '\0')
4045 continue;
4047 err = got_ref_resolve(&ref_id, repo, re->ref);
4048 if (err)
4049 break;
4050 if (strncmp(name, "tags/", 5) == 0) {
4051 err = got_object_open_as_tag(&tag, repo, ref_id);
4052 if (err) {
4053 if (err->code != GOT_ERR_OBJ_TYPE) {
4054 free(ref_id);
4055 break;
4057 /* Ref points at something other than a tag. */
4058 err = NULL;
4059 tag = NULL;
4062 cmp = got_object_id_cmp(tag ?
4063 got_object_tag_get_object_id(tag) : ref_id, id);
4064 free(ref_id);
4065 if (tag)
4066 got_object_tag_close(tag);
4067 if (cmp != 0)
4068 continue;
4069 s = *refs_str;
4070 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4071 s ? ", " : "", name) == -1) {
4072 err = got_error_from_errno("asprintf");
4073 free(s);
4074 *refs_str = NULL;
4075 break;
4077 free(s);
4080 return err;
4083 static const struct got_error *
4084 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4085 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4087 const struct got_error *err = NULL;
4088 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4089 char *comma, *s, *nl;
4090 struct got_reflist_head *refs;
4091 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4092 struct tm tm;
4093 time_t committer_time;
4095 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4096 if (refs) {
4097 err = build_refs_str(&ref_str, refs, id, repo, 1);
4098 if (err)
4099 return err;
4101 /* Display the first matching ref only. */
4102 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4103 *comma = '\0';
4106 if (ref_str == NULL) {
4107 err = got_object_id_str(&id_str, id);
4108 if (err)
4109 return err;
4112 committer_time = got_object_commit_get_committer_time(commit);
4113 if (gmtime_r(&committer_time, &tm) == NULL) {
4114 err = got_error_from_errno("gmtime_r");
4115 goto done;
4117 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4118 err = got_error(GOT_ERR_NO_SPACE);
4119 goto done;
4122 err = got_object_commit_get_logmsg(&logmsg0, commit);
4123 if (err)
4124 goto done;
4126 s = logmsg0;
4127 while (isspace((unsigned char)s[0]))
4128 s++;
4130 nl = strchr(s, '\n');
4131 if (nl) {
4132 *nl = '\0';
4135 if (ref_str)
4136 printf("%s%-7s %s\n", datebuf, ref_str, s);
4137 else
4138 printf("%s%.7s %s\n", datebuf, id_str, s);
4140 if (fflush(stdout) != 0 && err == NULL)
4141 err = got_error_from_errno("fflush");
4142 done:
4143 free(id_str);
4144 free(ref_str);
4145 free(logmsg0);
4146 return err;
4149 static const struct got_error *
4150 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4152 struct got_pathlist_entry *pe;
4154 if (header != NULL)
4155 printf("%s\n", header);
4157 TAILQ_FOREACH(pe, dsa->paths, entry) {
4158 struct got_diff_changed_path *cp = pe->data;
4159 int pad = dsa->max_path_len - pe->path_len + 1;
4161 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4162 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4164 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4165 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4166 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4168 if (fflush(stdout) != 0)
4169 return got_error_from_errno("fflush");
4171 return NULL;
4174 static const struct got_error *
4175 printfile(FILE *f)
4177 char buf[8192];
4178 size_t r;
4180 if (fseeko(f, 0L, SEEK_SET) == -1)
4181 return got_error_from_errno("fseek");
4183 for (;;) {
4184 r = fread(buf, 1, sizeof(buf), f);
4185 if (r == 0) {
4186 if (ferror(f))
4187 return got_error_from_errno("fread");
4188 if (feof(f))
4189 break;
4191 if (fwrite(buf, 1, r, stdout) != r)
4192 return got_ferror(stdout, GOT_ERR_IO);
4195 return NULL;
4198 static const struct got_error *
4199 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4200 struct got_repository *repo, const char *path,
4201 struct got_pathlist_head *changed_paths,
4202 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4203 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4204 const char *prefix)
4206 const struct got_error *err = NULL;
4207 FILE *f = NULL;
4208 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4209 char datebuf[26];
4210 time_t committer_time;
4211 const char *author, *committer;
4212 char *refs_str = NULL;
4214 err = got_object_id_str(&id_str, id);
4215 if (err)
4216 return err;
4218 if (custom_refs_str == NULL) {
4219 struct got_reflist_head *refs;
4220 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4221 if (refs) {
4222 err = build_refs_str(&refs_str, refs, id, repo, 0);
4223 if (err)
4224 goto done;
4228 printf(GOT_COMMIT_SEP_STR);
4229 if (custom_refs_str)
4230 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4231 custom_refs_str);
4232 else
4233 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4234 refs_str ? " (" : "", refs_str ? refs_str : "",
4235 refs_str ? ")" : "");
4236 free(id_str);
4237 id_str = NULL;
4238 free(refs_str);
4239 refs_str = NULL;
4240 printf("from: %s\n", got_object_commit_get_author(commit));
4241 author = got_object_commit_get_author(commit);
4242 committer = got_object_commit_get_committer(commit);
4243 if (strcmp(author, committer) != 0)
4244 printf("via: %s\n", committer);
4245 committer_time = got_object_commit_get_committer_time(commit);
4246 datestr = get_datestr(&committer_time, datebuf);
4247 if (datestr)
4248 printf("date: %s UTC\n", datestr);
4249 if (got_object_commit_get_nparents(commit) > 1) {
4250 const struct got_object_id_queue *parent_ids;
4251 struct got_object_qid *qid;
4252 int n = 1;
4253 parent_ids = got_object_commit_get_parent_ids(commit);
4254 STAILQ_FOREACH(qid, parent_ids, entry) {
4255 err = got_object_id_str(&id_str, &qid->id);
4256 if (err)
4257 goto done;
4258 printf("parent %d: %s\n", n++, id_str);
4259 free(id_str);
4260 id_str = NULL;
4264 err = got_object_commit_get_logmsg(&logmsg0, commit);
4265 if (err)
4266 goto done;
4268 logmsg = logmsg0;
4269 do {
4270 line = strsep(&logmsg, "\n");
4271 if (line)
4272 printf(" %s\n", line);
4273 } while (line);
4274 free(logmsg0);
4276 if (changed_paths && diffstat == NULL) {
4277 struct got_pathlist_entry *pe;
4279 TAILQ_FOREACH(pe, changed_paths, entry) {
4280 struct got_diff_changed_path *cp = pe->data;
4282 printf(" %c %s\n", cp->status, pe->path);
4284 printf("\n");
4286 if (show_patch) {
4287 if (diffstat) {
4288 f = got_opentemp();
4289 if (f == NULL) {
4290 err = got_error_from_errno("got_opentemp");
4291 goto done;
4295 err = print_patch(commit, id, path, diff_context, diffstat,
4296 repo, diffstat == NULL ? stdout : f);
4297 if (err)
4298 goto done;
4300 if (diffstat) {
4301 err = print_diffstat(diffstat, NULL);
4302 if (err)
4303 goto done;
4304 if (show_patch) {
4305 err = printfile(f);
4306 if (err)
4307 goto done;
4310 if (show_patch)
4311 printf("\n");
4313 if (fflush(stdout) != 0 && err == NULL)
4314 err = got_error_from_errno("fflush");
4315 done:
4316 if (f && fclose(f) == EOF && err == NULL)
4317 err = got_error_from_errno("fclose");
4318 free(id_str);
4319 free(refs_str);
4320 return err;
4323 static const struct got_error *
4324 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4325 struct got_repository *repo, const char *path, int show_changed_paths,
4326 int show_diffstat, int show_patch, const char *search_pattern,
4327 int diff_context, int limit, int log_branches, int reverse_display_order,
4328 struct got_reflist_object_id_map *refs_idmap, int one_line,
4329 FILE *tmpfile)
4331 const struct got_error *err;
4332 struct got_commit_graph *graph;
4333 regex_t regex;
4334 int have_match;
4335 struct got_object_id_queue reversed_commits;
4336 struct got_object_qid *qid;
4337 struct got_commit_object *commit;
4338 struct got_pathlist_head changed_paths;
4340 STAILQ_INIT(&reversed_commits);
4341 TAILQ_INIT(&changed_paths);
4343 if (search_pattern && regcomp(&regex, search_pattern,
4344 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4345 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4347 err = got_commit_graph_open(&graph, path, !log_branches);
4348 if (err)
4349 return err;
4350 err = got_commit_graph_iter_start(graph, root_id, repo,
4351 check_cancelled, NULL);
4352 if (err)
4353 goto done;
4354 for (;;) {
4355 struct got_object_id id;
4356 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4357 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4359 if (sigint_received || sigpipe_received)
4360 break;
4362 err = got_commit_graph_iter_next(&id, graph, repo,
4363 check_cancelled, NULL);
4364 if (err) {
4365 if (err->code == GOT_ERR_ITER_COMPLETED)
4366 err = NULL;
4367 break;
4370 err = got_object_open_as_commit(&commit, repo, &id);
4371 if (err)
4372 break;
4374 if ((show_changed_paths || (show_diffstat && !show_patch))
4375 && !reverse_display_order) {
4376 err = get_changed_paths(&changed_paths, commit, repo,
4377 show_diffstat ? &dsa : NULL);
4378 if (err)
4379 break;
4382 if (search_pattern) {
4383 err = match_commit(&have_match, &id, commit, &regex);
4384 if (err) {
4385 got_object_commit_close(commit);
4386 break;
4388 if (have_match == 0 && show_changed_paths)
4389 match_changed_paths(&have_match,
4390 &changed_paths, &regex);
4391 if (have_match == 0 && show_patch) {
4392 err = match_patch(&have_match, commit, &id,
4393 path, diff_context, repo, &regex, tmpfile);
4394 if (err)
4395 break;
4397 if (have_match == 0) {
4398 got_object_commit_close(commit);
4399 got_pathlist_free(&changed_paths,
4400 GOT_PATHLIST_FREE_ALL);
4401 continue;
4405 if (reverse_display_order) {
4406 err = got_object_qid_alloc(&qid, &id);
4407 if (err)
4408 break;
4409 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4410 got_object_commit_close(commit);
4411 } else {
4412 if (one_line)
4413 err = print_commit_oneline(commit, &id,
4414 repo, refs_idmap);
4415 else
4416 err = print_commit(commit, &id, repo, path,
4417 (show_changed_paths || show_diffstat) ?
4418 &changed_paths : NULL,
4419 show_diffstat ? &dsa : NULL, show_patch,
4420 diff_context, refs_idmap, NULL, NULL);
4421 got_object_commit_close(commit);
4422 if (err)
4423 break;
4425 if ((limit && --limit == 0) ||
4426 (end_id && got_object_id_cmp(&id, end_id) == 0))
4427 break;
4429 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4431 if (reverse_display_order) {
4432 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4433 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4434 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4436 err = got_object_open_as_commit(&commit, repo,
4437 &qid->id);
4438 if (err)
4439 break;
4440 if (show_changed_paths ||
4441 (show_diffstat && !show_patch)) {
4442 err = get_changed_paths(&changed_paths, commit,
4443 repo, show_diffstat ? &dsa : NULL);
4444 if (err)
4445 break;
4447 if (one_line)
4448 err = print_commit_oneline(commit, &qid->id,
4449 repo, refs_idmap);
4450 else
4451 err = print_commit(commit, &qid->id, repo, path,
4452 (show_changed_paths || show_diffstat) ?
4453 &changed_paths : NULL,
4454 show_diffstat ? &dsa : NULL, show_patch,
4455 diff_context, refs_idmap, NULL, NULL);
4456 got_object_commit_close(commit);
4457 if (err)
4458 break;
4459 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4462 done:
4463 while (!STAILQ_EMPTY(&reversed_commits)) {
4464 qid = STAILQ_FIRST(&reversed_commits);
4465 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4466 got_object_qid_free(qid);
4468 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4469 if (search_pattern)
4470 regfree(&regex);
4471 got_commit_graph_close(graph);
4472 return err;
4475 __dead static void
4476 usage_log(void)
4478 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4479 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4480 "[path]\n", getprogname());
4481 exit(1);
4484 static int
4485 get_default_log_limit(void)
4487 const char *got_default_log_limit;
4488 long long n;
4489 const char *errstr;
4491 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4492 if (got_default_log_limit == NULL)
4493 return 0;
4494 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4495 if (errstr != NULL)
4496 return 0;
4497 return n;
4500 static const struct got_error *
4501 cmd_log(int argc, char *argv[])
4503 const struct got_error *error;
4504 struct got_repository *repo = NULL;
4505 struct got_worktree *worktree = NULL;
4506 struct got_object_id *start_id = NULL, *end_id = NULL;
4507 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4508 const char *start_commit = NULL, *end_commit = NULL;
4509 const char *search_pattern = NULL;
4510 int diff_context = -1, ch;
4511 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4512 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4513 const char *errstr;
4514 struct got_reflist_head refs;
4515 struct got_reflist_object_id_map *refs_idmap = NULL;
4516 FILE *tmpfile = NULL;
4517 int *pack_fds = NULL;
4519 TAILQ_INIT(&refs);
4521 #ifndef PROFILE
4522 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4523 NULL)
4524 == -1)
4525 err(1, "pledge");
4526 #endif
4528 limit = get_default_log_limit();
4530 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4531 switch (ch) {
4532 case 'b':
4533 log_branches = 1;
4534 break;
4535 case 'C':
4536 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4537 &errstr);
4538 if (errstr != NULL)
4539 errx(1, "number of context lines is %s: %s",
4540 errstr, optarg);
4541 break;
4542 case 'c':
4543 start_commit = optarg;
4544 break;
4545 case 'd':
4546 show_diffstat = 1;
4547 break;
4548 case 'l':
4549 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4550 if (errstr != NULL)
4551 errx(1, "number of commits is %s: %s",
4552 errstr, optarg);
4553 break;
4554 case 'P':
4555 show_changed_paths = 1;
4556 break;
4557 case 'p':
4558 show_patch = 1;
4559 break;
4560 case 'R':
4561 reverse_display_order = 1;
4562 break;
4563 case 'r':
4564 repo_path = realpath(optarg, NULL);
4565 if (repo_path == NULL)
4566 return got_error_from_errno2("realpath",
4567 optarg);
4568 got_path_strip_trailing_slashes(repo_path);
4569 break;
4570 case 'S':
4571 search_pattern = optarg;
4572 break;
4573 case 's':
4574 one_line = 1;
4575 break;
4576 case 'x':
4577 end_commit = optarg;
4578 break;
4579 default:
4580 usage_log();
4581 /* NOTREACHED */
4585 argc -= optind;
4586 argv += optind;
4588 if (diff_context == -1)
4589 diff_context = 3;
4590 else if (!show_patch)
4591 errx(1, "-C requires -p");
4593 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4594 errx(1, "cannot use -s with -d, -p or -P");
4596 cwd = getcwd(NULL, 0);
4597 if (cwd == NULL) {
4598 error = got_error_from_errno("getcwd");
4599 goto done;
4602 error = got_repo_pack_fds_open(&pack_fds);
4603 if (error != NULL)
4604 goto done;
4606 if (repo_path == NULL) {
4607 error = got_worktree_open(&worktree, cwd);
4608 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4609 goto done;
4610 error = NULL;
4613 if (argc == 1) {
4614 if (worktree) {
4615 error = got_worktree_resolve_path(&path, worktree,
4616 argv[0]);
4617 if (error)
4618 goto done;
4619 } else {
4620 path = strdup(argv[0]);
4621 if (path == NULL) {
4622 error = got_error_from_errno("strdup");
4623 goto done;
4626 } else if (argc != 0)
4627 usage_log();
4629 if (repo_path == NULL) {
4630 repo_path = worktree ?
4631 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4633 if (repo_path == NULL) {
4634 error = got_error_from_errno("strdup");
4635 goto done;
4638 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4639 if (error != NULL)
4640 goto done;
4642 error = apply_unveil(got_repo_get_path(repo), 1,
4643 worktree ? got_worktree_get_root_path(worktree) : NULL);
4644 if (error)
4645 goto done;
4647 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4648 if (error)
4649 goto done;
4651 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4652 if (error)
4653 goto done;
4655 if (start_commit == NULL) {
4656 struct got_reference *head_ref;
4657 struct got_commit_object *commit = NULL;
4658 error = got_ref_open(&head_ref, repo,
4659 worktree ? got_worktree_get_head_ref_name(worktree)
4660 : GOT_REF_HEAD, 0);
4661 if (error != NULL)
4662 goto done;
4663 error = got_ref_resolve(&start_id, repo, head_ref);
4664 got_ref_close(head_ref);
4665 if (error != NULL)
4666 goto done;
4667 error = got_object_open_as_commit(&commit, repo,
4668 start_id);
4669 if (error != NULL)
4670 goto done;
4671 got_object_commit_close(commit);
4672 } else {
4673 error = got_repo_match_object_id(&start_id, NULL,
4674 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4675 if (error != NULL)
4676 goto done;
4678 if (end_commit != NULL) {
4679 error = got_repo_match_object_id(&end_id, NULL,
4680 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4681 if (error != NULL)
4682 goto done;
4685 if (worktree) {
4687 * If a path was specified on the command line it was resolved
4688 * to a path in the work tree above. Prepend the work tree's
4689 * path prefix to obtain the corresponding in-repository path.
4691 if (path) {
4692 const char *prefix;
4693 prefix = got_worktree_get_path_prefix(worktree);
4694 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4695 (path[0] != '\0') ? "/" : "", path) == -1) {
4696 error = got_error_from_errno("asprintf");
4697 goto done;
4700 } else
4701 error = got_repo_map_path(&in_repo_path, repo,
4702 path ? path : "");
4703 if (error != NULL)
4704 goto done;
4705 if (in_repo_path) {
4706 free(path);
4707 path = in_repo_path;
4710 if (worktree) {
4711 /* Release work tree lock. */
4712 got_worktree_close(worktree);
4713 worktree = NULL;
4716 if (search_pattern && show_patch) {
4717 tmpfile = got_opentemp();
4718 if (tmpfile == NULL) {
4719 error = got_error_from_errno("got_opentemp");
4720 goto done;
4724 error = print_commits(start_id, end_id, repo, path ? path : "",
4725 show_changed_paths, show_diffstat, show_patch, search_pattern,
4726 diff_context, limit, log_branches, reverse_display_order,
4727 refs_idmap, one_line, tmpfile);
4728 done:
4729 free(path);
4730 free(repo_path);
4731 free(cwd);
4732 if (worktree)
4733 got_worktree_close(worktree);
4734 if (repo) {
4735 const struct got_error *close_err = got_repo_close(repo);
4736 if (error == NULL)
4737 error = close_err;
4739 if (pack_fds) {
4740 const struct got_error *pack_err =
4741 got_repo_pack_fds_close(pack_fds);
4742 if (error == NULL)
4743 error = pack_err;
4745 if (refs_idmap)
4746 got_reflist_object_id_map_free(refs_idmap);
4747 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4748 error = got_error_from_errno("fclose");
4749 got_ref_list_free(&refs);
4750 return error;
4753 __dead static void
4754 usage_diff(void)
4756 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4757 "[-r repository-path] [object1 object2 | path ...]\n",
4758 getprogname());
4759 exit(1);
4762 struct print_diff_arg {
4763 struct got_repository *repo;
4764 struct got_worktree *worktree;
4765 struct got_diffstat_cb_arg *diffstat;
4766 int diff_context;
4767 const char *id_str;
4768 int header_shown;
4769 int diff_staged;
4770 enum got_diff_algorithm diff_algo;
4771 int ignore_whitespace;
4772 int force_text_diff;
4773 FILE *f1;
4774 FILE *f2;
4775 FILE *outfile;
4779 * Create a file which contains the target path of a symlink so we can feed
4780 * it as content to the diff engine.
4782 static const struct got_error *
4783 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4784 const char *abspath)
4786 const struct got_error *err = NULL;
4787 char target_path[PATH_MAX];
4788 ssize_t target_len, outlen;
4790 *fd = -1;
4792 if (dirfd != -1) {
4793 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4794 if (target_len == -1)
4795 return got_error_from_errno2("readlinkat", abspath);
4796 } else {
4797 target_len = readlink(abspath, target_path, PATH_MAX);
4798 if (target_len == -1)
4799 return got_error_from_errno2("readlink", abspath);
4802 *fd = got_opentempfd();
4803 if (*fd == -1)
4804 return got_error_from_errno("got_opentempfd");
4806 outlen = write(*fd, target_path, target_len);
4807 if (outlen == -1) {
4808 err = got_error_from_errno("got_opentempfd");
4809 goto done;
4812 if (lseek(*fd, 0, SEEK_SET) == -1) {
4813 err = got_error_from_errno2("lseek", abspath);
4814 goto done;
4816 done:
4817 if (err) {
4818 close(*fd);
4819 *fd = -1;
4821 return err;
4824 static const struct got_error *
4825 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4826 const char *path, struct got_object_id *blob_id,
4827 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4828 int dirfd, const char *de_name)
4830 struct print_diff_arg *a = arg;
4831 const struct got_error *err = NULL;
4832 struct got_blob_object *blob1 = NULL;
4833 int fd = -1, fd1 = -1, fd2 = -1;
4834 FILE *f2 = NULL;
4835 char *abspath = NULL, *label1 = NULL;
4836 struct stat sb;
4837 off_t size1 = 0;
4838 int f2_exists = 0;
4840 memset(&sb, 0, sizeof(sb));
4842 if (a->diff_staged) {
4843 if (staged_status != GOT_STATUS_MODIFY &&
4844 staged_status != GOT_STATUS_ADD &&
4845 staged_status != GOT_STATUS_DELETE)
4846 return NULL;
4847 } else {
4848 if (staged_status == GOT_STATUS_DELETE)
4849 return NULL;
4850 if (status == GOT_STATUS_NONEXISTENT)
4851 return got_error_set_errno(ENOENT, path);
4852 if (status != GOT_STATUS_MODIFY &&
4853 status != GOT_STATUS_ADD &&
4854 status != GOT_STATUS_DELETE &&
4855 status != GOT_STATUS_CONFLICT)
4856 return NULL;
4859 err = got_opentemp_truncate(a->f1);
4860 if (err)
4861 return got_error_from_errno("got_opentemp_truncate");
4862 err = got_opentemp_truncate(a->f2);
4863 if (err)
4864 return got_error_from_errno("got_opentemp_truncate");
4866 if (!a->header_shown) {
4867 if (fprintf(a->outfile, "diff %s%s\n",
4868 a->diff_staged ? "-s " : "",
4869 got_worktree_get_root_path(a->worktree)) < 0) {
4870 err = got_error_from_errno("fprintf");
4871 goto done;
4873 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4874 err = got_error_from_errno("fprintf");
4875 goto done;
4877 if (fprintf(a->outfile, "path + %s%s\n",
4878 got_worktree_get_root_path(a->worktree),
4879 a->diff_staged ? " (staged changes)" : "") < 0) {
4880 err = got_error_from_errno("fprintf");
4881 goto done;
4883 a->header_shown = 1;
4886 if (a->diff_staged) {
4887 const char *label1 = NULL, *label2 = NULL;
4888 switch (staged_status) {
4889 case GOT_STATUS_MODIFY:
4890 label1 = path;
4891 label2 = path;
4892 break;
4893 case GOT_STATUS_ADD:
4894 label2 = path;
4895 break;
4896 case GOT_STATUS_DELETE:
4897 label1 = path;
4898 break;
4899 default:
4900 return got_error(GOT_ERR_FILE_STATUS);
4902 fd1 = got_opentempfd();
4903 if (fd1 == -1) {
4904 err = got_error_from_errno("got_opentempfd");
4905 goto done;
4907 fd2 = got_opentempfd();
4908 if (fd2 == -1) {
4909 err = got_error_from_errno("got_opentempfd");
4910 goto done;
4912 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4913 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4914 a->diff_algo, a->diff_context, a->ignore_whitespace,
4915 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4916 goto done;
4919 fd1 = got_opentempfd();
4920 if (fd1 == -1) {
4921 err = got_error_from_errno("got_opentempfd");
4922 goto done;
4925 if (staged_status == GOT_STATUS_ADD ||
4926 staged_status == GOT_STATUS_MODIFY) {
4927 char *id_str;
4928 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4929 8192, fd1);
4930 if (err)
4931 goto done;
4932 err = got_object_id_str(&id_str, staged_blob_id);
4933 if (err)
4934 goto done;
4935 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4936 err = got_error_from_errno("asprintf");
4937 free(id_str);
4938 goto done;
4940 free(id_str);
4941 } else if (status != GOT_STATUS_ADD) {
4942 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4943 fd1);
4944 if (err)
4945 goto done;
4948 if (status != GOT_STATUS_DELETE) {
4949 if (asprintf(&abspath, "%s/%s",
4950 got_worktree_get_root_path(a->worktree), path) == -1) {
4951 err = got_error_from_errno("asprintf");
4952 goto done;
4955 if (dirfd != -1) {
4956 fd = openat(dirfd, de_name,
4957 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4958 if (fd == -1) {
4959 if (!got_err_open_nofollow_on_symlink()) {
4960 err = got_error_from_errno2("openat",
4961 abspath);
4962 goto done;
4964 err = get_symlink_target_file(&fd, dirfd,
4965 de_name, abspath);
4966 if (err)
4967 goto done;
4969 } else {
4970 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4971 if (fd == -1) {
4972 if (!got_err_open_nofollow_on_symlink()) {
4973 err = got_error_from_errno2("open",
4974 abspath);
4975 goto done;
4977 err = get_symlink_target_file(&fd, dirfd,
4978 de_name, abspath);
4979 if (err)
4980 goto done;
4983 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4984 err = got_error_from_errno2("fstatat", abspath);
4985 goto done;
4987 f2 = fdopen(fd, "r");
4988 if (f2 == NULL) {
4989 err = got_error_from_errno2("fdopen", abspath);
4990 goto done;
4992 fd = -1;
4993 f2_exists = 1;
4996 if (blob1) {
4997 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4998 a->f1, blob1);
4999 if (err)
5000 goto done;
5003 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5004 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5005 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5006 done:
5007 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5008 err = got_error_from_errno("close");
5009 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5010 err = got_error_from_errno("close");
5011 if (blob1)
5012 got_object_blob_close(blob1);
5013 if (fd != -1 && close(fd) == -1 && err == NULL)
5014 err = got_error_from_errno("close");
5015 if (f2 && fclose(f2) == EOF && err == NULL)
5016 err = got_error_from_errno("fclose");
5017 free(abspath);
5018 return err;
5021 static const struct got_error *
5022 cmd_diff(int argc, char *argv[])
5024 const struct got_error *error;
5025 struct got_repository *repo = NULL;
5026 struct got_worktree *worktree = NULL;
5027 char *cwd = NULL, *repo_path = NULL;
5028 const char *commit_args[2] = { NULL, NULL };
5029 int ncommit_args = 0;
5030 struct got_object_id *ids[2] = { NULL, NULL };
5031 char *labels[2] = { NULL, NULL };
5032 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5033 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5034 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5035 const char *errstr;
5036 struct got_reflist_head refs;
5037 struct got_pathlist_head diffstat_paths, paths;
5038 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5039 int fd1 = -1, fd2 = -1;
5040 int *pack_fds = NULL;
5041 struct got_diffstat_cb_arg dsa;
5043 memset(&dsa, 0, sizeof(dsa));
5045 TAILQ_INIT(&refs);
5046 TAILQ_INIT(&paths);
5047 TAILQ_INIT(&diffstat_paths);
5049 #ifndef PROFILE
5050 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5051 NULL) == -1)
5052 err(1, "pledge");
5053 #endif
5055 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5056 switch (ch) {
5057 case 'a':
5058 force_text_diff = 1;
5059 break;
5060 case 'C':
5061 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5062 &errstr);
5063 if (errstr != NULL)
5064 errx(1, "number of context lines is %s: %s",
5065 errstr, optarg);
5066 break;
5067 case 'c':
5068 if (ncommit_args >= 2)
5069 errx(1, "too many -c options used");
5070 commit_args[ncommit_args++] = optarg;
5071 break;
5072 case 'd':
5073 show_diffstat = 1;
5074 break;
5075 case 'P':
5076 force_path = 1;
5077 break;
5078 case 'r':
5079 repo_path = realpath(optarg, NULL);
5080 if (repo_path == NULL)
5081 return got_error_from_errno2("realpath",
5082 optarg);
5083 got_path_strip_trailing_slashes(repo_path);
5084 rflag = 1;
5085 break;
5086 case 's':
5087 diff_staged = 1;
5088 break;
5089 case 'w':
5090 ignore_whitespace = 1;
5091 break;
5092 default:
5093 usage_diff();
5094 /* NOTREACHED */
5098 argc -= optind;
5099 argv += optind;
5101 cwd = getcwd(NULL, 0);
5102 if (cwd == NULL) {
5103 error = got_error_from_errno("getcwd");
5104 goto done;
5107 error = got_repo_pack_fds_open(&pack_fds);
5108 if (error != NULL)
5109 goto done;
5111 if (repo_path == NULL) {
5112 error = got_worktree_open(&worktree, cwd);
5113 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5114 goto done;
5115 else
5116 error = NULL;
5117 if (worktree) {
5118 repo_path =
5119 strdup(got_worktree_get_repo_path(worktree));
5120 if (repo_path == NULL) {
5121 error = got_error_from_errno("strdup");
5122 goto done;
5124 } else {
5125 repo_path = strdup(cwd);
5126 if (repo_path == NULL) {
5127 error = got_error_from_errno("strdup");
5128 goto done;
5133 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5134 free(repo_path);
5135 if (error != NULL)
5136 goto done;
5138 if (show_diffstat) {
5139 dsa.paths = &diffstat_paths;
5140 dsa.force_text = force_text_diff;
5141 dsa.ignore_ws = ignore_whitespace;
5142 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5145 if (rflag || worktree == NULL || ncommit_args > 0) {
5146 if (force_path) {
5147 error = got_error_msg(GOT_ERR_NOT_IMPL,
5148 "-P option can only be used when diffing "
5149 "a work tree");
5150 goto done;
5152 if (diff_staged) {
5153 error = got_error_msg(GOT_ERR_NOT_IMPL,
5154 "-s option can only be used when diffing "
5155 "a work tree");
5156 goto done;
5160 error = apply_unveil(got_repo_get_path(repo), 1,
5161 worktree ? got_worktree_get_root_path(worktree) : NULL);
5162 if (error)
5163 goto done;
5165 if ((!force_path && argc == 2) || ncommit_args > 0) {
5166 int obj_type = (ncommit_args > 0 ?
5167 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5168 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5169 NULL);
5170 if (error)
5171 goto done;
5172 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5173 const char *arg;
5174 if (ncommit_args > 0)
5175 arg = commit_args[i];
5176 else
5177 arg = argv[i];
5178 error = got_repo_match_object_id(&ids[i], &labels[i],
5179 arg, obj_type, &refs, repo);
5180 if (error) {
5181 if (error->code != GOT_ERR_NOT_REF &&
5182 error->code != GOT_ERR_NO_OBJ)
5183 goto done;
5184 if (ncommit_args > 0)
5185 goto done;
5186 error = NULL;
5187 break;
5192 f1 = got_opentemp();
5193 if (f1 == NULL) {
5194 error = got_error_from_errno("got_opentemp");
5195 goto done;
5198 f2 = got_opentemp();
5199 if (f2 == NULL) {
5200 error = got_error_from_errno("got_opentemp");
5201 goto done;
5204 outfile = got_opentemp();
5205 if (outfile == NULL) {
5206 error = got_error_from_errno("got_opentemp");
5207 goto done;
5210 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5211 struct print_diff_arg arg;
5212 char *id_str;
5214 if (worktree == NULL) {
5215 if (argc == 2 && ids[0] == NULL) {
5216 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5217 goto done;
5218 } else if (argc == 2 && ids[1] == NULL) {
5219 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5220 goto done;
5221 } else if (argc > 0) {
5222 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5223 "%s", "specified paths cannot be resolved");
5224 goto done;
5225 } else {
5226 error = got_error(GOT_ERR_NOT_WORKTREE);
5227 goto done;
5231 error = get_worktree_paths_from_argv(&paths, argc, argv,
5232 worktree);
5233 if (error)
5234 goto done;
5236 error = got_object_id_str(&id_str,
5237 got_worktree_get_base_commit_id(worktree));
5238 if (error)
5239 goto done;
5240 arg.repo = repo;
5241 arg.worktree = worktree;
5242 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5243 arg.diff_context = diff_context;
5244 arg.id_str = id_str;
5245 arg.header_shown = 0;
5246 arg.diff_staged = diff_staged;
5247 arg.ignore_whitespace = ignore_whitespace;
5248 arg.force_text_diff = force_text_diff;
5249 arg.diffstat = show_diffstat ? &dsa : NULL;
5250 arg.f1 = f1;
5251 arg.f2 = f2;
5252 arg.outfile = outfile;
5254 error = got_worktree_status(worktree, &paths, repo, 0,
5255 print_diff, &arg, check_cancelled, NULL);
5256 free(id_str);
5257 if (error)
5258 goto done;
5260 if (show_diffstat && dsa.nfiles > 0) {
5261 char *header;
5263 if (asprintf(&header, "diffstat %s%s",
5264 diff_staged ? "-s " : "",
5265 got_worktree_get_root_path(worktree)) == -1) {
5266 error = got_error_from_errno("asprintf");
5267 goto done;
5270 error = print_diffstat(&dsa, header);
5271 free(header);
5272 if (error)
5273 goto done;
5276 error = printfile(outfile);
5277 goto done;
5280 if (ncommit_args == 1) {
5281 struct got_commit_object *commit;
5282 error = got_object_open_as_commit(&commit, repo, ids[0]);
5283 if (error)
5284 goto done;
5286 labels[1] = labels[0];
5287 ids[1] = ids[0];
5288 if (got_object_commit_get_nparents(commit) > 0) {
5289 const struct got_object_id_queue *pids;
5290 struct got_object_qid *pid;
5291 pids = got_object_commit_get_parent_ids(commit);
5292 pid = STAILQ_FIRST(pids);
5293 ids[0] = got_object_id_dup(&pid->id);
5294 if (ids[0] == NULL) {
5295 error = got_error_from_errno(
5296 "got_object_id_dup");
5297 got_object_commit_close(commit);
5298 goto done;
5300 error = got_object_id_str(&labels[0], ids[0]);
5301 if (error) {
5302 got_object_commit_close(commit);
5303 goto done;
5305 } else {
5306 ids[0] = NULL;
5307 labels[0] = strdup("/dev/null");
5308 if (labels[0] == NULL) {
5309 error = got_error_from_errno("strdup");
5310 got_object_commit_close(commit);
5311 goto done;
5315 got_object_commit_close(commit);
5318 if (ncommit_args == 0 && argc > 2) {
5319 error = got_error_msg(GOT_ERR_BAD_PATH,
5320 "path arguments cannot be used when diffing two objects");
5321 goto done;
5324 if (ids[0]) {
5325 error = got_object_get_type(&type1, repo, ids[0]);
5326 if (error)
5327 goto done;
5330 error = got_object_get_type(&type2, repo, ids[1]);
5331 if (error)
5332 goto done;
5333 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5334 error = got_error(GOT_ERR_OBJ_TYPE);
5335 goto done;
5337 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5338 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5339 "path arguments cannot be used when diffing blobs");
5340 goto done;
5343 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5344 char *in_repo_path;
5345 struct got_pathlist_entry *new;
5346 if (worktree) {
5347 const char *prefix;
5348 char *p;
5349 error = got_worktree_resolve_path(&p, worktree,
5350 argv[i]);
5351 if (error)
5352 goto done;
5353 prefix = got_worktree_get_path_prefix(worktree);
5354 while (prefix[0] == '/')
5355 prefix++;
5356 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5357 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5358 p) == -1) {
5359 error = got_error_from_errno("asprintf");
5360 free(p);
5361 goto done;
5363 free(p);
5364 } else {
5365 char *mapped_path, *s;
5366 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5367 if (error)
5368 goto done;
5369 s = mapped_path;
5370 while (s[0] == '/')
5371 s++;
5372 in_repo_path = strdup(s);
5373 if (in_repo_path == NULL) {
5374 error = got_error_from_errno("asprintf");
5375 free(mapped_path);
5376 goto done;
5378 free(mapped_path);
5381 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5382 if (error || new == NULL /* duplicate */)
5383 free(in_repo_path);
5384 if (error)
5385 goto done;
5388 if (worktree) {
5389 /* Release work tree lock. */
5390 got_worktree_close(worktree);
5391 worktree = NULL;
5394 fd1 = got_opentempfd();
5395 if (fd1 == -1) {
5396 error = got_error_from_errno("got_opentempfd");
5397 goto done;
5400 fd2 = got_opentempfd();
5401 if (fd2 == -1) {
5402 error = got_error_from_errno("got_opentempfd");
5403 goto done;
5406 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5407 case GOT_OBJ_TYPE_BLOB:
5408 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5409 fd1, fd2, ids[0], ids[1], NULL, NULL,
5410 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5411 ignore_whitespace, force_text_diff,
5412 show_diffstat ? &dsa : NULL, repo, outfile);
5413 break;
5414 case GOT_OBJ_TYPE_TREE:
5415 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5416 ids[0], ids[1], &paths, "", "",
5417 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5418 ignore_whitespace, force_text_diff,
5419 show_diffstat ? &dsa : NULL, repo, outfile);
5420 break;
5421 case GOT_OBJ_TYPE_COMMIT:
5422 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5423 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5424 fd1, fd2, ids[0], ids[1], &paths,
5425 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5426 ignore_whitespace, force_text_diff,
5427 show_diffstat ? &dsa : NULL, repo, outfile);
5428 break;
5429 default:
5430 error = got_error(GOT_ERR_OBJ_TYPE);
5432 if (error)
5433 goto done;
5435 if (show_diffstat && dsa.nfiles > 0) {
5436 char *header = NULL;
5438 if (asprintf(&header, "diffstat %s %s",
5439 labels[0], labels[1]) == -1) {
5440 error = got_error_from_errno("asprintf");
5441 goto done;
5444 error = print_diffstat(&dsa, header);
5445 free(header);
5446 if (error)
5447 goto done;
5450 error = printfile(outfile);
5452 done:
5453 free(labels[0]);
5454 free(labels[1]);
5455 free(ids[0]);
5456 free(ids[1]);
5457 if (worktree)
5458 got_worktree_close(worktree);
5459 if (repo) {
5460 const struct got_error *close_err = got_repo_close(repo);
5461 if (error == NULL)
5462 error = close_err;
5464 if (pack_fds) {
5465 const struct got_error *pack_err =
5466 got_repo_pack_fds_close(pack_fds);
5467 if (error == NULL)
5468 error = pack_err;
5470 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5471 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5472 got_ref_list_free(&refs);
5473 if (outfile && fclose(outfile) == EOF && error == NULL)
5474 error = got_error_from_errno("fclose");
5475 if (f1 && fclose(f1) == EOF && error == NULL)
5476 error = got_error_from_errno("fclose");
5477 if (f2 && fclose(f2) == EOF && error == NULL)
5478 error = got_error_from_errno("fclose");
5479 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5480 error = got_error_from_errno("close");
5481 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5482 error = got_error_from_errno("close");
5483 return error;
5486 __dead static void
5487 usage_blame(void)
5489 fprintf(stderr,
5490 "usage: %s blame [-c commit] [-r repository-path] path\n",
5491 getprogname());
5492 exit(1);
5495 struct blame_line {
5496 int annotated;
5497 char *id_str;
5498 char *committer;
5499 char datebuf[11]; /* YYYY-MM-DD + NUL */
5502 struct blame_cb_args {
5503 struct blame_line *lines;
5504 int nlines;
5505 int nlines_prec;
5506 int lineno_cur;
5507 off_t *line_offsets;
5508 FILE *f;
5509 struct got_repository *repo;
5512 static const struct got_error *
5513 blame_cb(void *arg, int nlines, int lineno,
5514 struct got_commit_object *commit, struct got_object_id *id)
5516 const struct got_error *err = NULL;
5517 struct blame_cb_args *a = arg;
5518 struct blame_line *bline;
5519 char *line = NULL;
5520 size_t linesize = 0;
5521 off_t offset;
5522 struct tm tm;
5523 time_t committer_time;
5525 if (nlines != a->nlines ||
5526 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5527 return got_error(GOT_ERR_RANGE);
5529 if (sigint_received)
5530 return got_error(GOT_ERR_ITER_COMPLETED);
5532 if (lineno == -1)
5533 return NULL; /* no change in this commit */
5535 /* Annotate this line. */
5536 bline = &a->lines[lineno - 1];
5537 if (bline->annotated)
5538 return NULL;
5539 err = got_object_id_str(&bline->id_str, id);
5540 if (err)
5541 return err;
5543 bline->committer = strdup(got_object_commit_get_committer(commit));
5544 if (bline->committer == NULL) {
5545 err = got_error_from_errno("strdup");
5546 goto done;
5549 committer_time = got_object_commit_get_committer_time(commit);
5550 if (gmtime_r(&committer_time, &tm) == NULL)
5551 return got_error_from_errno("gmtime_r");
5552 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5553 &tm) == 0) {
5554 err = got_error(GOT_ERR_NO_SPACE);
5555 goto done;
5557 bline->annotated = 1;
5559 /* Print lines annotated so far. */
5560 bline = &a->lines[a->lineno_cur - 1];
5561 if (!bline->annotated)
5562 goto done;
5564 offset = a->line_offsets[a->lineno_cur - 1];
5565 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5566 err = got_error_from_errno("fseeko");
5567 goto done;
5570 while (a->lineno_cur <= a->nlines && bline->annotated) {
5571 char *smallerthan, *at, *nl, *committer;
5572 size_t len;
5574 if (getline(&line, &linesize, a->f) == -1) {
5575 if (ferror(a->f))
5576 err = got_error_from_errno("getline");
5577 break;
5580 committer = bline->committer;
5581 smallerthan = strchr(committer, '<');
5582 if (smallerthan && smallerthan[1] != '\0')
5583 committer = smallerthan + 1;
5584 at = strchr(committer, '@');
5585 if (at)
5586 *at = '\0';
5587 len = strlen(committer);
5588 if (len >= 9)
5589 committer[8] = '\0';
5591 nl = strchr(line, '\n');
5592 if (nl)
5593 *nl = '\0';
5594 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5595 bline->id_str, bline->datebuf, committer, line);
5597 a->lineno_cur++;
5598 bline = &a->lines[a->lineno_cur - 1];
5600 done:
5601 free(line);
5602 return err;
5605 static const struct got_error *
5606 cmd_blame(int argc, char *argv[])
5608 const struct got_error *error;
5609 struct got_repository *repo = NULL;
5610 struct got_worktree *worktree = NULL;
5611 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5612 char *link_target = NULL;
5613 struct got_object_id *obj_id = NULL;
5614 struct got_object_id *commit_id = NULL;
5615 struct got_commit_object *commit = NULL;
5616 struct got_blob_object *blob = NULL;
5617 char *commit_id_str = NULL;
5618 struct blame_cb_args bca;
5619 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5620 off_t filesize;
5621 int *pack_fds = NULL;
5622 FILE *f1 = NULL, *f2 = NULL;
5624 fd1 = got_opentempfd();
5625 if (fd1 == -1)
5626 return got_error_from_errno("got_opentempfd");
5628 memset(&bca, 0, sizeof(bca));
5630 #ifndef PROFILE
5631 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5632 NULL) == -1)
5633 err(1, "pledge");
5634 #endif
5636 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5637 switch (ch) {
5638 case 'c':
5639 commit_id_str = optarg;
5640 break;
5641 case 'r':
5642 repo_path = realpath(optarg, NULL);
5643 if (repo_path == NULL)
5644 return got_error_from_errno2("realpath",
5645 optarg);
5646 got_path_strip_trailing_slashes(repo_path);
5647 break;
5648 default:
5649 usage_blame();
5650 /* NOTREACHED */
5654 argc -= optind;
5655 argv += optind;
5657 if (argc == 1)
5658 path = argv[0];
5659 else
5660 usage_blame();
5662 cwd = getcwd(NULL, 0);
5663 if (cwd == NULL) {
5664 error = got_error_from_errno("getcwd");
5665 goto done;
5668 error = got_repo_pack_fds_open(&pack_fds);
5669 if (error != NULL)
5670 goto done;
5672 if (repo_path == NULL) {
5673 error = got_worktree_open(&worktree, cwd);
5674 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5675 goto done;
5676 else
5677 error = NULL;
5678 if (worktree) {
5679 repo_path =
5680 strdup(got_worktree_get_repo_path(worktree));
5681 if (repo_path == NULL) {
5682 error = got_error_from_errno("strdup");
5683 if (error)
5684 goto done;
5686 } else {
5687 repo_path = strdup(cwd);
5688 if (repo_path == NULL) {
5689 error = got_error_from_errno("strdup");
5690 goto done;
5695 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5696 if (error != NULL)
5697 goto done;
5699 if (worktree) {
5700 const char *prefix = got_worktree_get_path_prefix(worktree);
5701 char *p;
5703 error = got_worktree_resolve_path(&p, worktree, path);
5704 if (error)
5705 goto done;
5706 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5707 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5708 p) == -1) {
5709 error = got_error_from_errno("asprintf");
5710 free(p);
5711 goto done;
5713 free(p);
5714 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5715 } else {
5716 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5717 if (error)
5718 goto done;
5719 error = got_repo_map_path(&in_repo_path, repo, path);
5721 if (error)
5722 goto done;
5724 if (commit_id_str == NULL) {
5725 struct got_reference *head_ref;
5726 error = got_ref_open(&head_ref, repo, worktree ?
5727 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5728 if (error != NULL)
5729 goto done;
5730 error = got_ref_resolve(&commit_id, repo, head_ref);
5731 got_ref_close(head_ref);
5732 if (error != NULL)
5733 goto done;
5734 } else {
5735 struct got_reflist_head refs;
5736 TAILQ_INIT(&refs);
5737 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5738 NULL);
5739 if (error)
5740 goto done;
5741 error = got_repo_match_object_id(&commit_id, NULL,
5742 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5743 got_ref_list_free(&refs);
5744 if (error)
5745 goto done;
5748 if (worktree) {
5749 /* Release work tree lock. */
5750 got_worktree_close(worktree);
5751 worktree = NULL;
5754 error = got_object_open_as_commit(&commit, repo, commit_id);
5755 if (error)
5756 goto done;
5758 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5759 commit, repo);
5760 if (error)
5761 goto done;
5763 error = got_object_id_by_path(&obj_id, repo, commit,
5764 link_target ? link_target : in_repo_path);
5765 if (error)
5766 goto done;
5768 error = got_object_get_type(&obj_type, repo, obj_id);
5769 if (error)
5770 goto done;
5772 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5773 error = got_error_path(link_target ? link_target : in_repo_path,
5774 GOT_ERR_OBJ_TYPE);
5775 goto done;
5778 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5779 if (error)
5780 goto done;
5781 bca.f = got_opentemp();
5782 if (bca.f == NULL) {
5783 error = got_error_from_errno("got_opentemp");
5784 goto done;
5786 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5787 &bca.line_offsets, bca.f, blob);
5788 if (error || bca.nlines == 0)
5789 goto done;
5791 /* Don't include \n at EOF in the blame line count. */
5792 if (bca.line_offsets[bca.nlines - 1] == filesize)
5793 bca.nlines--;
5795 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5796 if (bca.lines == NULL) {
5797 error = got_error_from_errno("calloc");
5798 goto done;
5800 bca.lineno_cur = 1;
5801 bca.nlines_prec = 0;
5802 i = bca.nlines;
5803 while (i > 0) {
5804 i /= 10;
5805 bca.nlines_prec++;
5807 bca.repo = repo;
5809 fd2 = got_opentempfd();
5810 if (fd2 == -1) {
5811 error = got_error_from_errno("got_opentempfd");
5812 goto done;
5814 fd3 = got_opentempfd();
5815 if (fd3 == -1) {
5816 error = got_error_from_errno("got_opentempfd");
5817 goto done;
5819 f1 = got_opentemp();
5820 if (f1 == NULL) {
5821 error = got_error_from_errno("got_opentemp");
5822 goto done;
5824 f2 = got_opentemp();
5825 if (f2 == NULL) {
5826 error = got_error_from_errno("got_opentemp");
5827 goto done;
5829 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5830 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5831 check_cancelled, NULL, fd2, fd3, f1, f2);
5832 done:
5833 free(in_repo_path);
5834 free(link_target);
5835 free(repo_path);
5836 free(cwd);
5837 free(commit_id);
5838 free(obj_id);
5839 if (commit)
5840 got_object_commit_close(commit);
5842 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5843 error = got_error_from_errno("close");
5844 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5845 error = got_error_from_errno("close");
5846 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5847 error = got_error_from_errno("close");
5848 if (f1 && fclose(f1) == EOF && error == NULL)
5849 error = got_error_from_errno("fclose");
5850 if (f2 && fclose(f2) == EOF && error == NULL)
5851 error = got_error_from_errno("fclose");
5853 if (blob)
5854 got_object_blob_close(blob);
5855 if (worktree)
5856 got_worktree_close(worktree);
5857 if (repo) {
5858 const struct got_error *close_err = got_repo_close(repo);
5859 if (error == NULL)
5860 error = close_err;
5862 if (pack_fds) {
5863 const struct got_error *pack_err =
5864 got_repo_pack_fds_close(pack_fds);
5865 if (error == NULL)
5866 error = pack_err;
5868 if (bca.lines) {
5869 for (i = 0; i < bca.nlines; i++) {
5870 struct blame_line *bline = &bca.lines[i];
5871 free(bline->id_str);
5872 free(bline->committer);
5874 free(bca.lines);
5876 free(bca.line_offsets);
5877 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5878 error = got_error_from_errno("fclose");
5879 return error;
5882 __dead static void
5883 usage_tree(void)
5885 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5886 "[path]\n", getprogname());
5887 exit(1);
5890 static const struct got_error *
5891 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5892 const char *root_path, struct got_repository *repo)
5894 const struct got_error *err = NULL;
5895 int is_root_path = (strcmp(path, root_path) == 0);
5896 const char *modestr = "";
5897 mode_t mode = got_tree_entry_get_mode(te);
5898 char *link_target = NULL;
5900 path += strlen(root_path);
5901 while (path[0] == '/')
5902 path++;
5904 if (got_object_tree_entry_is_submodule(te))
5905 modestr = "$";
5906 else if (S_ISLNK(mode)) {
5907 int i;
5909 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5910 if (err)
5911 return err;
5912 for (i = 0; i < strlen(link_target); i++) {
5913 if (!isprint((unsigned char)link_target[i]))
5914 link_target[i] = '?';
5917 modestr = "@";
5919 else if (S_ISDIR(mode))
5920 modestr = "/";
5921 else if (mode & S_IXUSR)
5922 modestr = "*";
5924 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5925 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5926 link_target ? " -> ": "", link_target ? link_target : "");
5928 free(link_target);
5929 return NULL;
5932 static const struct got_error *
5933 print_tree(const char *path, struct got_commit_object *commit,
5934 int show_ids, int recurse, const char *root_path,
5935 struct got_repository *repo)
5937 const struct got_error *err = NULL;
5938 struct got_object_id *tree_id = NULL;
5939 struct got_tree_object *tree = NULL;
5940 int nentries, i;
5942 err = got_object_id_by_path(&tree_id, repo, commit, path);
5943 if (err)
5944 goto done;
5946 err = got_object_open_as_tree(&tree, repo, tree_id);
5947 if (err)
5948 goto done;
5949 nentries = got_object_tree_get_nentries(tree);
5950 for (i = 0; i < nentries; i++) {
5951 struct got_tree_entry *te;
5952 char *id = NULL;
5954 if (sigint_received || sigpipe_received)
5955 break;
5957 te = got_object_tree_get_entry(tree, i);
5958 if (show_ids) {
5959 char *id_str;
5960 err = got_object_id_str(&id_str,
5961 got_tree_entry_get_id(te));
5962 if (err)
5963 goto done;
5964 if (asprintf(&id, "%s ", id_str) == -1) {
5965 err = got_error_from_errno("asprintf");
5966 free(id_str);
5967 goto done;
5969 free(id_str);
5971 err = print_entry(te, id, path, root_path, repo);
5972 free(id);
5973 if (err)
5974 goto done;
5976 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5977 char *child_path;
5978 if (asprintf(&child_path, "%s%s%s", path,
5979 path[0] == '/' && path[1] == '\0' ? "" : "/",
5980 got_tree_entry_get_name(te)) == -1) {
5981 err = got_error_from_errno("asprintf");
5982 goto done;
5984 err = print_tree(child_path, commit, show_ids, 1,
5985 root_path, repo);
5986 free(child_path);
5987 if (err)
5988 goto done;
5991 done:
5992 if (tree)
5993 got_object_tree_close(tree);
5994 free(tree_id);
5995 return err;
5998 static const struct got_error *
5999 cmd_tree(int argc, char *argv[])
6001 const struct got_error *error;
6002 struct got_repository *repo = NULL;
6003 struct got_worktree *worktree = NULL;
6004 const char *path, *refname = NULL;
6005 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6006 struct got_object_id *commit_id = NULL;
6007 struct got_commit_object *commit = NULL;
6008 char *commit_id_str = NULL;
6009 int show_ids = 0, recurse = 0;
6010 int ch;
6011 int *pack_fds = NULL;
6013 #ifndef PROFILE
6014 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6015 NULL) == -1)
6016 err(1, "pledge");
6017 #endif
6019 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6020 switch (ch) {
6021 case 'c':
6022 commit_id_str = optarg;
6023 break;
6024 case 'i':
6025 show_ids = 1;
6026 break;
6027 case 'R':
6028 recurse = 1;
6029 break;
6030 case 'r':
6031 repo_path = realpath(optarg, NULL);
6032 if (repo_path == NULL)
6033 return got_error_from_errno2("realpath",
6034 optarg);
6035 got_path_strip_trailing_slashes(repo_path);
6036 break;
6037 default:
6038 usage_tree();
6039 /* NOTREACHED */
6043 argc -= optind;
6044 argv += optind;
6046 if (argc == 1)
6047 path = argv[0];
6048 else if (argc > 1)
6049 usage_tree();
6050 else
6051 path = NULL;
6053 cwd = getcwd(NULL, 0);
6054 if (cwd == NULL) {
6055 error = got_error_from_errno("getcwd");
6056 goto done;
6059 error = got_repo_pack_fds_open(&pack_fds);
6060 if (error != NULL)
6061 goto done;
6063 if (repo_path == NULL) {
6064 error = got_worktree_open(&worktree, cwd);
6065 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6066 goto done;
6067 else
6068 error = NULL;
6069 if (worktree) {
6070 repo_path =
6071 strdup(got_worktree_get_repo_path(worktree));
6072 if (repo_path == NULL)
6073 error = got_error_from_errno("strdup");
6074 if (error)
6075 goto done;
6076 } else {
6077 repo_path = strdup(cwd);
6078 if (repo_path == NULL) {
6079 error = got_error_from_errno("strdup");
6080 goto done;
6085 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6086 if (error != NULL)
6087 goto done;
6089 if (worktree) {
6090 const char *prefix = got_worktree_get_path_prefix(worktree);
6091 char *p;
6093 if (path == NULL)
6094 path = "";
6095 error = got_worktree_resolve_path(&p, worktree, path);
6096 if (error)
6097 goto done;
6098 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6099 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6100 p) == -1) {
6101 error = got_error_from_errno("asprintf");
6102 free(p);
6103 goto done;
6105 free(p);
6106 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6107 if (error)
6108 goto done;
6109 } else {
6110 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6111 if (error)
6112 goto done;
6113 if (path == NULL)
6114 path = "/";
6115 error = got_repo_map_path(&in_repo_path, repo, path);
6116 if (error != NULL)
6117 goto done;
6120 if (commit_id_str == NULL) {
6121 struct got_reference *head_ref;
6122 if (worktree)
6123 refname = got_worktree_get_head_ref_name(worktree);
6124 else
6125 refname = GOT_REF_HEAD;
6126 error = got_ref_open(&head_ref, repo, refname, 0);
6127 if (error != NULL)
6128 goto done;
6129 error = got_ref_resolve(&commit_id, repo, head_ref);
6130 got_ref_close(head_ref);
6131 if (error != NULL)
6132 goto done;
6133 } else {
6134 struct got_reflist_head refs;
6135 TAILQ_INIT(&refs);
6136 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6137 NULL);
6138 if (error)
6139 goto done;
6140 error = got_repo_match_object_id(&commit_id, NULL,
6141 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6142 got_ref_list_free(&refs);
6143 if (error)
6144 goto done;
6147 if (worktree) {
6148 /* Release work tree lock. */
6149 got_worktree_close(worktree);
6150 worktree = NULL;
6153 error = got_object_open_as_commit(&commit, repo, commit_id);
6154 if (error)
6155 goto done;
6157 error = print_tree(in_repo_path, commit, show_ids, recurse,
6158 in_repo_path, repo);
6159 done:
6160 free(in_repo_path);
6161 free(repo_path);
6162 free(cwd);
6163 free(commit_id);
6164 if (commit)
6165 got_object_commit_close(commit);
6166 if (worktree)
6167 got_worktree_close(worktree);
6168 if (repo) {
6169 const struct got_error *close_err = got_repo_close(repo);
6170 if (error == NULL)
6171 error = close_err;
6173 if (pack_fds) {
6174 const struct got_error *pack_err =
6175 got_repo_pack_fds_close(pack_fds);
6176 if (error == NULL)
6177 error = pack_err;
6179 return error;
6182 __dead static void
6183 usage_status(void)
6185 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6186 "[-s status-codes] [path ...]\n", getprogname());
6187 exit(1);
6190 struct got_status_arg {
6191 char *status_codes;
6192 int suppress;
6195 static const struct got_error *
6196 print_status(void *arg, unsigned char status, unsigned char staged_status,
6197 const char *path, struct got_object_id *blob_id,
6198 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6199 int dirfd, const char *de_name)
6201 struct got_status_arg *st = arg;
6203 if (status == staged_status && (status == GOT_STATUS_DELETE))
6204 status = GOT_STATUS_NO_CHANGE;
6205 if (st != NULL && st->status_codes) {
6206 size_t ncodes = strlen(st->status_codes);
6207 int i, j = 0;
6209 for (i = 0; i < ncodes ; i++) {
6210 if (st->suppress) {
6211 if (status == st->status_codes[i] ||
6212 staged_status == st->status_codes[i]) {
6213 j++;
6214 continue;
6216 } else {
6217 if (status == st->status_codes[i] ||
6218 staged_status == st->status_codes[i])
6219 break;
6223 if (st->suppress && j == 0)
6224 goto print;
6226 if (i == ncodes)
6227 return NULL;
6229 print:
6230 printf("%c%c %s\n", status, staged_status, path);
6231 return NULL;
6234 static const struct got_error *
6235 cmd_status(int argc, char *argv[])
6237 const struct got_error *error = NULL;
6238 struct got_repository *repo = NULL;
6239 struct got_worktree *worktree = NULL;
6240 struct got_status_arg st;
6241 char *cwd = NULL;
6242 struct got_pathlist_head paths;
6243 int ch, i, no_ignores = 0;
6244 int *pack_fds = NULL;
6246 TAILQ_INIT(&paths);
6248 memset(&st, 0, sizeof(st));
6249 st.status_codes = NULL;
6250 st.suppress = 0;
6252 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6253 switch (ch) {
6254 case 'I':
6255 no_ignores = 1;
6256 break;
6257 case 'S':
6258 if (st.status_codes != NULL && st.suppress == 0)
6259 option_conflict('S', 's');
6260 st.suppress = 1;
6261 /* fallthrough */
6262 case 's':
6263 for (i = 0; i < strlen(optarg); i++) {
6264 switch (optarg[i]) {
6265 case GOT_STATUS_MODIFY:
6266 case GOT_STATUS_ADD:
6267 case GOT_STATUS_DELETE:
6268 case GOT_STATUS_CONFLICT:
6269 case GOT_STATUS_MISSING:
6270 case GOT_STATUS_OBSTRUCTED:
6271 case GOT_STATUS_UNVERSIONED:
6272 case GOT_STATUS_MODE_CHANGE:
6273 case GOT_STATUS_NONEXISTENT:
6274 break;
6275 default:
6276 errx(1, "invalid status code '%c'",
6277 optarg[i]);
6280 if (ch == 's' && st.suppress)
6281 option_conflict('s', 'S');
6282 st.status_codes = optarg;
6283 break;
6284 default:
6285 usage_status();
6286 /* NOTREACHED */
6290 argc -= optind;
6291 argv += optind;
6293 #ifndef PROFILE
6294 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6295 NULL) == -1)
6296 err(1, "pledge");
6297 #endif
6298 cwd = getcwd(NULL, 0);
6299 if (cwd == NULL) {
6300 error = got_error_from_errno("getcwd");
6301 goto done;
6304 error = got_repo_pack_fds_open(&pack_fds);
6305 if (error != NULL)
6306 goto done;
6308 error = got_worktree_open(&worktree, cwd);
6309 if (error) {
6310 if (error->code == GOT_ERR_NOT_WORKTREE)
6311 error = wrap_not_worktree_error(error, "status", cwd);
6312 goto done;
6315 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6316 NULL, pack_fds);
6317 if (error != NULL)
6318 goto done;
6320 error = apply_unveil(got_repo_get_path(repo), 1,
6321 got_worktree_get_root_path(worktree));
6322 if (error)
6323 goto done;
6325 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6326 if (error)
6327 goto done;
6329 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6330 print_status, &st, check_cancelled, NULL);
6331 done:
6332 if (pack_fds) {
6333 const struct got_error *pack_err =
6334 got_repo_pack_fds_close(pack_fds);
6335 if (error == NULL)
6336 error = pack_err;
6339 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6340 free(cwd);
6341 return error;
6344 __dead static void
6345 usage_ref(void)
6347 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6348 "[-s reference] [name]\n", getprogname());
6349 exit(1);
6352 static const struct got_error *
6353 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6355 static const struct got_error *err = NULL;
6356 struct got_reflist_head refs;
6357 struct got_reflist_entry *re;
6359 TAILQ_INIT(&refs);
6360 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6361 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6362 repo);
6363 if (err)
6364 return err;
6366 TAILQ_FOREACH(re, &refs, entry) {
6367 char *refstr;
6368 refstr = got_ref_to_str(re->ref);
6369 if (refstr == NULL) {
6370 err = got_error_from_errno("got_ref_to_str");
6371 break;
6373 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6374 free(refstr);
6377 got_ref_list_free(&refs);
6378 return err;
6381 static const struct got_error *
6382 delete_ref_by_name(struct got_repository *repo, const char *refname)
6384 const struct got_error *err;
6385 struct got_reference *ref;
6387 err = got_ref_open(&ref, repo, refname, 0);
6388 if (err)
6389 return err;
6391 err = delete_ref(repo, ref);
6392 got_ref_close(ref);
6393 return err;
6396 static const struct got_error *
6397 add_ref(struct got_repository *repo, const char *refname, const char *target)
6399 const struct got_error *err = NULL;
6400 struct got_object_id *id = NULL;
6401 struct got_reference *ref = NULL;
6402 struct got_reflist_head refs;
6405 * Don't let the user create a reference name with a leading '-'.
6406 * While technically a valid reference name, this case is usually
6407 * an unintended typo.
6409 if (refname[0] == '-')
6410 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6412 TAILQ_INIT(&refs);
6413 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6414 if (err)
6415 goto done;
6416 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6417 &refs, repo);
6418 got_ref_list_free(&refs);
6419 if (err)
6420 goto done;
6422 err = got_ref_alloc(&ref, refname, id);
6423 if (err)
6424 goto done;
6426 err = got_ref_write(ref, repo);
6427 done:
6428 if (ref)
6429 got_ref_close(ref);
6430 free(id);
6431 return err;
6434 static const struct got_error *
6435 add_symref(struct got_repository *repo, const char *refname, const char *target)
6437 const struct got_error *err = NULL;
6438 struct got_reference *ref = NULL;
6439 struct got_reference *target_ref = NULL;
6442 * Don't let the user create a reference name with a leading '-'.
6443 * While technically a valid reference name, this case is usually
6444 * an unintended typo.
6446 if (refname[0] == '-')
6447 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6449 err = got_ref_open(&target_ref, repo, target, 0);
6450 if (err)
6451 return err;
6453 err = got_ref_alloc_symref(&ref, refname, target_ref);
6454 if (err)
6455 goto done;
6457 err = got_ref_write(ref, repo);
6458 done:
6459 if (target_ref)
6460 got_ref_close(target_ref);
6461 if (ref)
6462 got_ref_close(ref);
6463 return err;
6466 static const struct got_error *
6467 cmd_ref(int argc, char *argv[])
6469 const struct got_error *error = NULL;
6470 struct got_repository *repo = NULL;
6471 struct got_worktree *worktree = NULL;
6472 char *cwd = NULL, *repo_path = NULL;
6473 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6474 const char *obj_arg = NULL, *symref_target= NULL;
6475 char *refname = NULL;
6476 int *pack_fds = NULL;
6478 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6479 switch (ch) {
6480 case 'c':
6481 obj_arg = optarg;
6482 break;
6483 case 'd':
6484 do_delete = 1;
6485 break;
6486 case 'l':
6487 do_list = 1;
6488 break;
6489 case 'r':
6490 repo_path = realpath(optarg, NULL);
6491 if (repo_path == NULL)
6492 return got_error_from_errno2("realpath",
6493 optarg);
6494 got_path_strip_trailing_slashes(repo_path);
6495 break;
6496 case 's':
6497 symref_target = optarg;
6498 break;
6499 case 't':
6500 sort_by_time = 1;
6501 break;
6502 default:
6503 usage_ref();
6504 /* NOTREACHED */
6508 if (obj_arg && do_list)
6509 option_conflict('c', 'l');
6510 if (obj_arg && do_delete)
6511 option_conflict('c', 'd');
6512 if (obj_arg && symref_target)
6513 option_conflict('c', 's');
6514 if (symref_target && do_delete)
6515 option_conflict('s', 'd');
6516 if (symref_target && do_list)
6517 option_conflict('s', 'l');
6518 if (do_delete && do_list)
6519 option_conflict('d', 'l');
6520 if (sort_by_time && !do_list)
6521 errx(1, "-t option requires -l option");
6523 argc -= optind;
6524 argv += optind;
6526 if (do_list) {
6527 if (argc != 0 && argc != 1)
6528 usage_ref();
6529 if (argc == 1) {
6530 refname = strdup(argv[0]);
6531 if (refname == NULL) {
6532 error = got_error_from_errno("strdup");
6533 goto done;
6536 } else {
6537 if (argc != 1)
6538 usage_ref();
6539 refname = strdup(argv[0]);
6540 if (refname == NULL) {
6541 error = got_error_from_errno("strdup");
6542 goto done;
6546 if (refname)
6547 got_path_strip_trailing_slashes(refname);
6549 #ifndef PROFILE
6550 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6551 "sendfd unveil", NULL) == -1)
6552 err(1, "pledge");
6553 #endif
6554 cwd = getcwd(NULL, 0);
6555 if (cwd == NULL) {
6556 error = got_error_from_errno("getcwd");
6557 goto done;
6560 error = got_repo_pack_fds_open(&pack_fds);
6561 if (error != NULL)
6562 goto done;
6564 if (repo_path == NULL) {
6565 error = got_worktree_open(&worktree, cwd);
6566 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6567 goto done;
6568 else
6569 error = NULL;
6570 if (worktree) {
6571 repo_path =
6572 strdup(got_worktree_get_repo_path(worktree));
6573 if (repo_path == NULL)
6574 error = got_error_from_errno("strdup");
6575 if (error)
6576 goto done;
6577 } else {
6578 repo_path = strdup(cwd);
6579 if (repo_path == NULL) {
6580 error = got_error_from_errno("strdup");
6581 goto done;
6586 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6587 if (error != NULL)
6588 goto done;
6590 #ifndef PROFILE
6591 if (do_list) {
6592 /* Remove "cpath" promise. */
6593 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6594 NULL) == -1)
6595 err(1, "pledge");
6597 #endif
6599 error = apply_unveil(got_repo_get_path(repo), do_list,
6600 worktree ? got_worktree_get_root_path(worktree) : NULL);
6601 if (error)
6602 goto done;
6604 if (do_list)
6605 error = list_refs(repo, refname, sort_by_time);
6606 else if (do_delete)
6607 error = delete_ref_by_name(repo, refname);
6608 else if (symref_target)
6609 error = add_symref(repo, refname, symref_target);
6610 else {
6611 if (obj_arg == NULL)
6612 usage_ref();
6613 error = add_ref(repo, refname, obj_arg);
6615 done:
6616 free(refname);
6617 if (repo) {
6618 const struct got_error *close_err = got_repo_close(repo);
6619 if (error == NULL)
6620 error = close_err;
6622 if (worktree)
6623 got_worktree_close(worktree);
6624 if (pack_fds) {
6625 const struct got_error *pack_err =
6626 got_repo_pack_fds_close(pack_fds);
6627 if (error == NULL)
6628 error = pack_err;
6630 free(cwd);
6631 free(repo_path);
6632 return error;
6635 __dead static void
6636 usage_branch(void)
6638 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6639 "[-r repository-path] [name]\n", getprogname());
6640 exit(1);
6643 static const struct got_error *
6644 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6645 struct got_reference *ref)
6647 const struct got_error *err = NULL;
6648 const char *refname, *marker = " ";
6649 char *refstr;
6651 refname = got_ref_get_name(ref);
6652 if (worktree && strcmp(refname,
6653 got_worktree_get_head_ref_name(worktree)) == 0) {
6654 struct got_object_id *id = NULL;
6656 err = got_ref_resolve(&id, repo, ref);
6657 if (err)
6658 return err;
6659 if (got_object_id_cmp(id,
6660 got_worktree_get_base_commit_id(worktree)) == 0)
6661 marker = "* ";
6662 else
6663 marker = "~ ";
6664 free(id);
6667 if (strncmp(refname, "refs/heads/", 11) == 0)
6668 refname += 11;
6669 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6670 refname += 18;
6671 if (strncmp(refname, "refs/remotes/", 13) == 0)
6672 refname += 13;
6674 refstr = got_ref_to_str(ref);
6675 if (refstr == NULL)
6676 return got_error_from_errno("got_ref_to_str");
6678 printf("%s%s: %s\n", marker, refname, refstr);
6679 free(refstr);
6680 return NULL;
6683 static const struct got_error *
6684 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6686 const char *refname;
6688 if (worktree == NULL)
6689 return got_error(GOT_ERR_NOT_WORKTREE);
6691 refname = got_worktree_get_head_ref_name(worktree);
6693 if (strncmp(refname, "refs/heads/", 11) == 0)
6694 refname += 11;
6695 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6696 refname += 18;
6698 printf("%s\n", refname);
6700 return NULL;
6703 static const struct got_error *
6704 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6705 int sort_by_time)
6707 static const struct got_error *err = NULL;
6708 struct got_reflist_head refs;
6709 struct got_reflist_entry *re;
6710 struct got_reference *temp_ref = NULL;
6711 int rebase_in_progress, histedit_in_progress;
6713 TAILQ_INIT(&refs);
6715 if (worktree) {
6716 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6717 worktree);
6718 if (err)
6719 return err;
6721 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6722 worktree);
6723 if (err)
6724 return err;
6726 if (rebase_in_progress || histedit_in_progress) {
6727 err = got_ref_open(&temp_ref, repo,
6728 got_worktree_get_head_ref_name(worktree), 0);
6729 if (err)
6730 return err;
6731 list_branch(repo, worktree, temp_ref);
6732 got_ref_close(temp_ref);
6736 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6737 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6738 repo);
6739 if (err)
6740 return err;
6742 TAILQ_FOREACH(re, &refs, entry)
6743 list_branch(repo, worktree, re->ref);
6745 got_ref_list_free(&refs);
6747 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6748 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6749 repo);
6750 if (err)
6751 return err;
6753 TAILQ_FOREACH(re, &refs, entry)
6754 list_branch(repo, worktree, re->ref);
6756 got_ref_list_free(&refs);
6758 return NULL;
6761 static const struct got_error *
6762 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6763 const char *branch_name)
6765 const struct got_error *err = NULL;
6766 struct got_reference *ref = NULL;
6767 char *refname, *remote_refname = NULL;
6769 if (strncmp(branch_name, "refs/", 5) == 0)
6770 branch_name += 5;
6771 if (strncmp(branch_name, "heads/", 6) == 0)
6772 branch_name += 6;
6773 else if (strncmp(branch_name, "remotes/", 8) == 0)
6774 branch_name += 8;
6776 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6777 return got_error_from_errno("asprintf");
6779 if (asprintf(&remote_refname, "refs/remotes/%s",
6780 branch_name) == -1) {
6781 err = got_error_from_errno("asprintf");
6782 goto done;
6785 err = got_ref_open(&ref, repo, refname, 0);
6786 if (err) {
6787 const struct got_error *err2;
6788 if (err->code != GOT_ERR_NOT_REF)
6789 goto done;
6791 * Keep 'err' intact such that if neither branch exists
6792 * we report "refs/heads" rather than "refs/remotes" in
6793 * our error message.
6795 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6796 if (err2)
6797 goto done;
6798 err = NULL;
6801 if (worktree &&
6802 strcmp(got_worktree_get_head_ref_name(worktree),
6803 got_ref_get_name(ref)) == 0) {
6804 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6805 "will not delete this work tree's current branch");
6806 goto done;
6809 err = delete_ref(repo, ref);
6810 done:
6811 if (ref)
6812 got_ref_close(ref);
6813 free(refname);
6814 free(remote_refname);
6815 return err;
6818 static const struct got_error *
6819 add_branch(struct got_repository *repo, const char *branch_name,
6820 struct got_object_id *base_commit_id)
6822 const struct got_error *err = NULL;
6823 struct got_reference *ref = NULL;
6824 char *refname = NULL;
6827 * Don't let the user create a branch name with a leading '-'.
6828 * While technically a valid reference name, this case is usually
6829 * an unintended typo.
6831 if (branch_name[0] == '-')
6832 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6834 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6835 branch_name += 11;
6837 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6838 err = got_error_from_errno("asprintf");
6839 goto done;
6842 err = got_ref_open(&ref, repo, refname, 0);
6843 if (err == NULL) {
6844 err = got_error(GOT_ERR_BRANCH_EXISTS);
6845 goto done;
6846 } else if (err->code != GOT_ERR_NOT_REF)
6847 goto done;
6849 err = got_ref_alloc(&ref, refname, base_commit_id);
6850 if (err)
6851 goto done;
6853 err = got_ref_write(ref, repo);
6854 done:
6855 if (ref)
6856 got_ref_close(ref);
6857 free(refname);
6858 return err;
6861 static const struct got_error *
6862 cmd_branch(int argc, char *argv[])
6864 const struct got_error *error = NULL;
6865 struct got_repository *repo = NULL;
6866 struct got_worktree *worktree = NULL;
6867 char *cwd = NULL, *repo_path = NULL;
6868 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6869 const char *delref = NULL, *commit_id_arg = NULL;
6870 struct got_reference *ref = NULL;
6871 struct got_pathlist_head paths;
6872 struct got_object_id *commit_id = NULL;
6873 char *commit_id_str = NULL;
6874 int *pack_fds = NULL;
6876 TAILQ_INIT(&paths);
6878 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6879 switch (ch) {
6880 case 'c':
6881 commit_id_arg = optarg;
6882 break;
6883 case 'd':
6884 delref = optarg;
6885 break;
6886 case 'l':
6887 do_list = 1;
6888 break;
6889 case 'n':
6890 do_update = 0;
6891 break;
6892 case 'r':
6893 repo_path = realpath(optarg, NULL);
6894 if (repo_path == NULL)
6895 return got_error_from_errno2("realpath",
6896 optarg);
6897 got_path_strip_trailing_slashes(repo_path);
6898 break;
6899 case 't':
6900 sort_by_time = 1;
6901 break;
6902 default:
6903 usage_branch();
6904 /* NOTREACHED */
6908 if (do_list && delref)
6909 option_conflict('l', 'd');
6910 if (sort_by_time && !do_list)
6911 errx(1, "-t option requires -l option");
6913 argc -= optind;
6914 argv += optind;
6916 if (!do_list && !delref && argc == 0)
6917 do_show = 1;
6919 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6920 errx(1, "-c option can only be used when creating a branch");
6922 if (do_list || delref) {
6923 if (argc > 0)
6924 usage_branch();
6925 } else if (!do_show && argc != 1)
6926 usage_branch();
6928 #ifndef PROFILE
6929 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6930 "sendfd unveil", NULL) == -1)
6931 err(1, "pledge");
6932 #endif
6933 cwd = getcwd(NULL, 0);
6934 if (cwd == NULL) {
6935 error = got_error_from_errno("getcwd");
6936 goto done;
6939 error = got_repo_pack_fds_open(&pack_fds);
6940 if (error != NULL)
6941 goto done;
6943 if (repo_path == NULL) {
6944 error = got_worktree_open(&worktree, cwd);
6945 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6946 goto done;
6947 else
6948 error = NULL;
6949 if (worktree) {
6950 repo_path =
6951 strdup(got_worktree_get_repo_path(worktree));
6952 if (repo_path == NULL)
6953 error = got_error_from_errno("strdup");
6954 if (error)
6955 goto done;
6956 } else {
6957 repo_path = strdup(cwd);
6958 if (repo_path == NULL) {
6959 error = got_error_from_errno("strdup");
6960 goto done;
6965 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6966 if (error != NULL)
6967 goto done;
6969 #ifndef PROFILE
6970 if (do_list || do_show) {
6971 /* Remove "cpath" promise. */
6972 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6973 NULL) == -1)
6974 err(1, "pledge");
6976 #endif
6978 error = apply_unveil(got_repo_get_path(repo), do_list,
6979 worktree ? got_worktree_get_root_path(worktree) : NULL);
6980 if (error)
6981 goto done;
6983 if (do_show)
6984 error = show_current_branch(repo, worktree);
6985 else if (do_list)
6986 error = list_branches(repo, worktree, sort_by_time);
6987 else if (delref)
6988 error = delete_branch(repo, worktree, delref);
6989 else {
6990 struct got_reflist_head refs;
6991 TAILQ_INIT(&refs);
6992 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6993 NULL);
6994 if (error)
6995 goto done;
6996 if (commit_id_arg == NULL)
6997 commit_id_arg = worktree ?
6998 got_worktree_get_head_ref_name(worktree) :
6999 GOT_REF_HEAD;
7000 error = got_repo_match_object_id(&commit_id, NULL,
7001 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7002 got_ref_list_free(&refs);
7003 if (error)
7004 goto done;
7005 error = add_branch(repo, argv[0], commit_id);
7006 if (error)
7007 goto done;
7008 if (worktree && do_update) {
7009 struct got_update_progress_arg upa;
7010 char *branch_refname = NULL;
7012 error = got_object_id_str(&commit_id_str, commit_id);
7013 if (error)
7014 goto done;
7015 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7016 worktree);
7017 if (error)
7018 goto done;
7019 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7020 == -1) {
7021 error = got_error_from_errno("asprintf");
7022 goto done;
7024 error = got_ref_open(&ref, repo, branch_refname, 0);
7025 free(branch_refname);
7026 if (error)
7027 goto done;
7028 error = switch_head_ref(ref, commit_id, worktree,
7029 repo);
7030 if (error)
7031 goto done;
7032 error = got_worktree_set_base_commit_id(worktree, repo,
7033 commit_id);
7034 if (error)
7035 goto done;
7036 memset(&upa, 0, sizeof(upa));
7037 error = got_worktree_checkout_files(worktree, &paths,
7038 repo, update_progress, &upa, check_cancelled,
7039 NULL);
7040 if (error)
7041 goto done;
7042 if (upa.did_something) {
7043 printf("Updated to %s: %s\n",
7044 got_worktree_get_head_ref_name(worktree),
7045 commit_id_str);
7047 print_update_progress_stats(&upa);
7050 done:
7051 if (ref)
7052 got_ref_close(ref);
7053 if (repo) {
7054 const struct got_error *close_err = got_repo_close(repo);
7055 if (error == NULL)
7056 error = close_err;
7058 if (worktree)
7059 got_worktree_close(worktree);
7060 if (pack_fds) {
7061 const struct got_error *pack_err =
7062 got_repo_pack_fds_close(pack_fds);
7063 if (error == NULL)
7064 error = pack_err;
7066 free(cwd);
7067 free(repo_path);
7068 free(commit_id);
7069 free(commit_id_str);
7070 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7071 return error;
7075 __dead static void
7076 usage_tag(void)
7078 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7079 "[-r repository-path] [-s signer-id] name\n", getprogname());
7080 exit(1);
7083 #if 0
7084 static const struct got_error *
7085 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7087 const struct got_error *err = NULL;
7088 struct got_reflist_entry *re, *se, *new;
7089 struct got_object_id *re_id, *se_id;
7090 struct got_tag_object *re_tag, *se_tag;
7091 time_t re_time, se_time;
7093 STAILQ_FOREACH(re, tags, entry) {
7094 se = STAILQ_FIRST(sorted);
7095 if (se == NULL) {
7096 err = got_reflist_entry_dup(&new, re);
7097 if (err)
7098 return err;
7099 STAILQ_INSERT_HEAD(sorted, new, entry);
7100 continue;
7101 } else {
7102 err = got_ref_resolve(&re_id, repo, re->ref);
7103 if (err)
7104 break;
7105 err = got_object_open_as_tag(&re_tag, repo, re_id);
7106 free(re_id);
7107 if (err)
7108 break;
7109 re_time = got_object_tag_get_tagger_time(re_tag);
7110 got_object_tag_close(re_tag);
7113 while (se) {
7114 err = got_ref_resolve(&se_id, repo, re->ref);
7115 if (err)
7116 break;
7117 err = got_object_open_as_tag(&se_tag, repo, se_id);
7118 free(se_id);
7119 if (err)
7120 break;
7121 se_time = got_object_tag_get_tagger_time(se_tag);
7122 got_object_tag_close(se_tag);
7124 if (se_time > re_time) {
7125 err = got_reflist_entry_dup(&new, re);
7126 if (err)
7127 return err;
7128 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7129 break;
7131 se = STAILQ_NEXT(se, entry);
7132 continue;
7135 done:
7136 return err;
7138 #endif
7140 static const struct got_error *
7141 get_tag_refname(char **refname, const char *tag_name)
7143 const struct got_error *err;
7145 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7146 *refname = strdup(tag_name);
7147 if (*refname == NULL)
7148 return got_error_from_errno("strdup");
7149 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7150 err = got_error_from_errno("asprintf");
7151 *refname = NULL;
7152 return err;
7155 return NULL;
7158 static const struct got_error *
7159 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7160 const char *allowed_signers, const char *revoked_signers, int verbosity)
7162 static const struct got_error *err = NULL;
7163 struct got_reflist_head refs;
7164 struct got_reflist_entry *re;
7165 char *wanted_refname = NULL;
7166 int bad_sigs = 0;
7168 TAILQ_INIT(&refs);
7170 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7171 if (err)
7172 return err;
7174 if (tag_name) {
7175 struct got_reference *ref;
7176 err = get_tag_refname(&wanted_refname, tag_name);
7177 if (err)
7178 goto done;
7179 /* Wanted tag reference should exist. */
7180 err = got_ref_open(&ref, repo, wanted_refname, 0);
7181 if (err)
7182 goto done;
7183 got_ref_close(ref);
7186 TAILQ_FOREACH(re, &refs, entry) {
7187 const char *refname;
7188 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7189 char datebuf[26];
7190 const char *tagger, *ssh_sig = NULL;
7191 char *sig_msg = NULL;
7192 time_t tagger_time;
7193 struct got_object_id *id;
7194 struct got_tag_object *tag;
7195 struct got_commit_object *commit = NULL;
7197 refname = got_ref_get_name(re->ref);
7198 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7199 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7200 continue;
7201 refname += 10;
7202 refstr = got_ref_to_str(re->ref);
7203 if (refstr == NULL) {
7204 err = got_error_from_errno("got_ref_to_str");
7205 break;
7208 err = got_ref_resolve(&id, repo, re->ref);
7209 if (err)
7210 break;
7211 err = got_object_open_as_tag(&tag, repo, id);
7212 if (err) {
7213 if (err->code != GOT_ERR_OBJ_TYPE) {
7214 free(id);
7215 break;
7217 /* "lightweight" tag */
7218 err = got_object_open_as_commit(&commit, repo, id);
7219 if (err) {
7220 free(id);
7221 break;
7223 tagger = got_object_commit_get_committer(commit);
7224 tagger_time =
7225 got_object_commit_get_committer_time(commit);
7226 err = got_object_id_str(&id_str, id);
7227 free(id);
7228 if (err)
7229 break;
7230 } else {
7231 free(id);
7232 tagger = got_object_tag_get_tagger(tag);
7233 tagger_time = got_object_tag_get_tagger_time(tag);
7234 err = got_object_id_str(&id_str,
7235 got_object_tag_get_object_id(tag));
7236 if (err)
7237 break;
7240 if (tag && verify_tags) {
7241 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7242 got_object_tag_get_message(tag));
7243 if (ssh_sig && allowed_signers == NULL) {
7244 err = got_error_msg(
7245 GOT_ERR_VERIFY_TAG_SIGNATURE,
7246 "SSH signature verification requires "
7247 "setting allowed_signers in "
7248 "got.conf(5)");
7249 break;
7253 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7254 free(refstr);
7255 printf("from: %s\n", tagger);
7256 datestr = get_datestr(&tagger_time, datebuf);
7257 if (datestr)
7258 printf("date: %s UTC\n", datestr);
7259 if (commit)
7260 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7261 else {
7262 switch (got_object_tag_get_object_type(tag)) {
7263 case GOT_OBJ_TYPE_BLOB:
7264 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7265 id_str);
7266 break;
7267 case GOT_OBJ_TYPE_TREE:
7268 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7269 id_str);
7270 break;
7271 case GOT_OBJ_TYPE_COMMIT:
7272 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7273 id_str);
7274 break;
7275 case GOT_OBJ_TYPE_TAG:
7276 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7277 id_str);
7278 break;
7279 default:
7280 break;
7283 free(id_str);
7285 if (ssh_sig) {
7286 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7287 allowed_signers, revoked_signers, verbosity);
7288 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7289 bad_sigs = 1;
7290 else if (err)
7291 break;
7292 printf("signature: %s", sig_msg);
7293 free(sig_msg);
7294 sig_msg = NULL;
7297 if (commit) {
7298 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7299 if (err)
7300 break;
7301 got_object_commit_close(commit);
7302 } else {
7303 tagmsg0 = strdup(got_object_tag_get_message(tag));
7304 got_object_tag_close(tag);
7305 if (tagmsg0 == NULL) {
7306 err = got_error_from_errno("strdup");
7307 break;
7311 tagmsg = tagmsg0;
7312 do {
7313 line = strsep(&tagmsg, "\n");
7314 if (line)
7315 printf(" %s\n", line);
7316 } while (line);
7317 free(tagmsg0);
7319 done:
7320 got_ref_list_free(&refs);
7321 free(wanted_refname);
7323 if (err == NULL && bad_sigs)
7324 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7325 return err;
7328 static const struct got_error *
7329 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7330 const char *tag_name, const char *repo_path)
7332 const struct got_error *err = NULL;
7333 char *template = NULL, *initial_content = NULL;
7334 char *editor = NULL;
7335 int initial_content_len;
7336 int fd = -1;
7338 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7339 err = got_error_from_errno("asprintf");
7340 goto done;
7343 initial_content_len = asprintf(&initial_content,
7344 "\n# tagging commit %s as %s\n",
7345 commit_id_str, tag_name);
7346 if (initial_content_len == -1) {
7347 err = got_error_from_errno("asprintf");
7348 goto done;
7351 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7352 if (err)
7353 goto done;
7355 if (write(fd, initial_content, initial_content_len) == -1) {
7356 err = got_error_from_errno2("write", *tagmsg_path);
7357 goto done;
7360 err = get_editor(&editor);
7361 if (err)
7362 goto done;
7363 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7364 initial_content_len, 1);
7365 done:
7366 free(initial_content);
7367 free(template);
7368 free(editor);
7370 if (fd != -1 && close(fd) == -1 && err == NULL)
7371 err = got_error_from_errno2("close", *tagmsg_path);
7373 if (err) {
7374 free(*tagmsg);
7375 *tagmsg = NULL;
7377 return err;
7380 static const struct got_error *
7381 add_tag(struct got_repository *repo, const char *tagger,
7382 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7383 const char *signer_id, int verbosity)
7385 const struct got_error *err = NULL;
7386 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7387 char *label = NULL, *commit_id_str = NULL;
7388 struct got_reference *ref = NULL;
7389 char *refname = NULL, *tagmsg = NULL;
7390 char *tagmsg_path = NULL, *tag_id_str = NULL;
7391 int preserve_tagmsg = 0;
7392 struct got_reflist_head refs;
7394 TAILQ_INIT(&refs);
7397 * Don't let the user create a tag name with a leading '-'.
7398 * While technically a valid reference name, this case is usually
7399 * an unintended typo.
7401 if (tag_name[0] == '-')
7402 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7404 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7405 if (err)
7406 goto done;
7408 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7409 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7410 if (err)
7411 goto done;
7413 err = got_object_id_str(&commit_id_str, commit_id);
7414 if (err)
7415 goto done;
7417 err = get_tag_refname(&refname, tag_name);
7418 if (err)
7419 goto done;
7420 if (strncmp("refs/tags/", tag_name, 10) == 0)
7421 tag_name += 10;
7423 err = got_ref_open(&ref, repo, refname, 0);
7424 if (err == NULL) {
7425 err = got_error(GOT_ERR_TAG_EXISTS);
7426 goto done;
7427 } else if (err->code != GOT_ERR_NOT_REF)
7428 goto done;
7430 if (tagmsg_arg == NULL) {
7431 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7432 tag_name, got_repo_get_path(repo));
7433 if (err) {
7434 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7435 tagmsg_path != NULL)
7436 preserve_tagmsg = 1;
7437 goto done;
7439 /* Editor is done; we can now apply unveil(2) */
7440 err = got_sigs_apply_unveil();
7441 if (err)
7442 goto done;
7443 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7444 if (err)
7445 goto done;
7448 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7449 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7450 verbosity);
7451 if (err) {
7452 if (tagmsg_path)
7453 preserve_tagmsg = 1;
7454 goto done;
7457 err = got_ref_alloc(&ref, refname, tag_id);
7458 if (err) {
7459 if (tagmsg_path)
7460 preserve_tagmsg = 1;
7461 goto done;
7464 err = got_ref_write(ref, repo);
7465 if (err) {
7466 if (tagmsg_path)
7467 preserve_tagmsg = 1;
7468 goto done;
7471 err = got_object_id_str(&tag_id_str, tag_id);
7472 if (err) {
7473 if (tagmsg_path)
7474 preserve_tagmsg = 1;
7475 goto done;
7477 printf("Created tag %s\n", tag_id_str);
7478 done:
7479 if (preserve_tagmsg) {
7480 fprintf(stderr, "%s: tag message preserved in %s\n",
7481 getprogname(), tagmsg_path);
7482 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7483 err = got_error_from_errno2("unlink", tagmsg_path);
7484 free(tag_id_str);
7485 if (ref)
7486 got_ref_close(ref);
7487 free(commit_id);
7488 free(commit_id_str);
7489 free(refname);
7490 free(tagmsg);
7491 free(tagmsg_path);
7492 got_ref_list_free(&refs);
7493 return err;
7496 static const struct got_error *
7497 cmd_tag(int argc, char *argv[])
7499 const struct got_error *error = NULL;
7500 struct got_repository *repo = NULL;
7501 struct got_worktree *worktree = NULL;
7502 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7503 char *gitconfig_path = NULL, *tagger = NULL;
7504 char *allowed_signers = NULL, *revoked_signers = NULL;
7505 const char *signer_id = NULL;
7506 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7507 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7508 int *pack_fds = NULL;
7510 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7511 switch (ch) {
7512 case 'c':
7513 commit_id_arg = optarg;
7514 break;
7515 case 'l':
7516 do_list = 1;
7517 break;
7518 case 'm':
7519 tagmsg = optarg;
7520 break;
7521 case 'r':
7522 repo_path = realpath(optarg, NULL);
7523 if (repo_path == NULL) {
7524 error = got_error_from_errno2("realpath",
7525 optarg);
7526 goto done;
7528 got_path_strip_trailing_slashes(repo_path);
7529 break;
7530 case 's':
7531 signer_id = optarg;
7532 break;
7533 case 'V':
7534 verify_tags = 1;
7535 break;
7536 case 'v':
7537 if (verbosity < 0)
7538 verbosity = 0;
7539 else if (verbosity < 3)
7540 verbosity++;
7541 break;
7542 default:
7543 usage_tag();
7544 /* NOTREACHED */
7548 argc -= optind;
7549 argv += optind;
7551 if (do_list || verify_tags) {
7552 if (commit_id_arg != NULL)
7553 errx(1,
7554 "-c option can only be used when creating a tag");
7555 if (tagmsg) {
7556 if (do_list)
7557 option_conflict('l', 'm');
7558 else
7559 option_conflict('V', 'm');
7561 if (signer_id) {
7562 if (do_list)
7563 option_conflict('l', 's');
7564 else
7565 option_conflict('V', 's');
7567 if (argc > 1)
7568 usage_tag();
7569 } else if (argc != 1)
7570 usage_tag();
7572 if (argc == 1)
7573 tag_name = argv[0];
7575 #ifndef PROFILE
7576 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7577 "sendfd unveil", NULL) == -1)
7578 err(1, "pledge");
7579 #endif
7580 cwd = getcwd(NULL, 0);
7581 if (cwd == NULL) {
7582 error = got_error_from_errno("getcwd");
7583 goto done;
7586 error = got_repo_pack_fds_open(&pack_fds);
7587 if (error != NULL)
7588 goto done;
7590 if (repo_path == NULL) {
7591 error = got_worktree_open(&worktree, cwd);
7592 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7593 goto done;
7594 else
7595 error = NULL;
7596 if (worktree) {
7597 repo_path =
7598 strdup(got_worktree_get_repo_path(worktree));
7599 if (repo_path == NULL)
7600 error = got_error_from_errno("strdup");
7601 if (error)
7602 goto done;
7603 } else {
7604 repo_path = strdup(cwd);
7605 if (repo_path == NULL) {
7606 error = got_error_from_errno("strdup");
7607 goto done;
7612 if (do_list || verify_tags) {
7613 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7614 if (error != NULL)
7615 goto done;
7616 error = get_allowed_signers(&allowed_signers, repo, worktree);
7617 if (error)
7618 goto done;
7619 error = get_revoked_signers(&revoked_signers, repo, worktree);
7620 if (error)
7621 goto done;
7622 if (worktree) {
7623 /* Release work tree lock. */
7624 got_worktree_close(worktree);
7625 worktree = NULL;
7629 * Remove "cpath" promise unless needed for signature tmpfile
7630 * creation.
7632 if (verify_tags)
7633 got_sigs_apply_unveil();
7634 else {
7635 #ifndef PROFILE
7636 if (pledge("stdio rpath wpath flock proc exec sendfd "
7637 "unveil", NULL) == -1)
7638 err(1, "pledge");
7639 #endif
7641 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7642 if (error)
7643 goto done;
7644 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7645 revoked_signers, verbosity);
7646 } else {
7647 error = get_gitconfig_path(&gitconfig_path);
7648 if (error)
7649 goto done;
7650 error = got_repo_open(&repo, repo_path, gitconfig_path,
7651 pack_fds);
7652 if (error != NULL)
7653 goto done;
7655 error = get_author(&tagger, repo, worktree);
7656 if (error)
7657 goto done;
7658 if (signer_id == NULL)
7659 signer_id = get_signer_id(repo, worktree);
7661 if (tagmsg) {
7662 if (signer_id) {
7663 error = got_sigs_apply_unveil();
7664 if (error)
7665 goto done;
7667 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7668 if (error)
7669 goto done;
7672 if (commit_id_arg == NULL) {
7673 struct got_reference *head_ref;
7674 struct got_object_id *commit_id;
7675 error = got_ref_open(&head_ref, repo,
7676 worktree ? got_worktree_get_head_ref_name(worktree)
7677 : GOT_REF_HEAD, 0);
7678 if (error)
7679 goto done;
7680 error = got_ref_resolve(&commit_id, repo, head_ref);
7681 got_ref_close(head_ref);
7682 if (error)
7683 goto done;
7684 error = got_object_id_str(&commit_id_str, commit_id);
7685 free(commit_id);
7686 if (error)
7687 goto done;
7690 if (worktree) {
7691 /* Release work tree lock. */
7692 got_worktree_close(worktree);
7693 worktree = NULL;
7696 error = add_tag(repo, tagger, tag_name,
7697 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7698 signer_id, verbosity);
7700 done:
7701 if (repo) {
7702 const struct got_error *close_err = got_repo_close(repo);
7703 if (error == NULL)
7704 error = close_err;
7706 if (worktree)
7707 got_worktree_close(worktree);
7708 if (pack_fds) {
7709 const struct got_error *pack_err =
7710 got_repo_pack_fds_close(pack_fds);
7711 if (error == NULL)
7712 error = pack_err;
7714 free(cwd);
7715 free(repo_path);
7716 free(gitconfig_path);
7717 free(commit_id_str);
7718 free(tagger);
7719 free(allowed_signers);
7720 free(revoked_signers);
7721 return error;
7724 __dead static void
7725 usage_add(void)
7727 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7728 exit(1);
7731 static const struct got_error *
7732 add_progress(void *arg, unsigned char status, const char *path)
7734 while (path[0] == '/')
7735 path++;
7736 printf("%c %s\n", status, path);
7737 return NULL;
7740 static const struct got_error *
7741 cmd_add(int argc, char *argv[])
7743 const struct got_error *error = NULL;
7744 struct got_repository *repo = NULL;
7745 struct got_worktree *worktree = NULL;
7746 char *cwd = NULL;
7747 struct got_pathlist_head paths;
7748 struct got_pathlist_entry *pe;
7749 int ch, can_recurse = 0, no_ignores = 0;
7750 int *pack_fds = NULL;
7752 TAILQ_INIT(&paths);
7754 while ((ch = getopt(argc, argv, "IR")) != -1) {
7755 switch (ch) {
7756 case 'I':
7757 no_ignores = 1;
7758 break;
7759 case 'R':
7760 can_recurse = 1;
7761 break;
7762 default:
7763 usage_add();
7764 /* NOTREACHED */
7768 argc -= optind;
7769 argv += optind;
7771 #ifndef PROFILE
7772 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7773 NULL) == -1)
7774 err(1, "pledge");
7775 #endif
7776 if (argc < 1)
7777 usage_add();
7779 cwd = getcwd(NULL, 0);
7780 if (cwd == NULL) {
7781 error = got_error_from_errno("getcwd");
7782 goto done;
7785 error = got_repo_pack_fds_open(&pack_fds);
7786 if (error != NULL)
7787 goto done;
7789 error = got_worktree_open(&worktree, cwd);
7790 if (error) {
7791 if (error->code == GOT_ERR_NOT_WORKTREE)
7792 error = wrap_not_worktree_error(error, "add", cwd);
7793 goto done;
7796 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7797 NULL, pack_fds);
7798 if (error != NULL)
7799 goto done;
7801 error = apply_unveil(got_repo_get_path(repo), 1,
7802 got_worktree_get_root_path(worktree));
7803 if (error)
7804 goto done;
7806 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7807 if (error)
7808 goto done;
7810 if (!can_recurse) {
7811 char *ondisk_path;
7812 struct stat sb;
7813 TAILQ_FOREACH(pe, &paths, entry) {
7814 if (asprintf(&ondisk_path, "%s/%s",
7815 got_worktree_get_root_path(worktree),
7816 pe->path) == -1) {
7817 error = got_error_from_errno("asprintf");
7818 goto done;
7820 if (lstat(ondisk_path, &sb) == -1) {
7821 if (errno == ENOENT) {
7822 free(ondisk_path);
7823 continue;
7825 error = got_error_from_errno2("lstat",
7826 ondisk_path);
7827 free(ondisk_path);
7828 goto done;
7830 free(ondisk_path);
7831 if (S_ISDIR(sb.st_mode)) {
7832 error = got_error_msg(GOT_ERR_BAD_PATH,
7833 "adding directories requires -R option");
7834 goto done;
7839 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7840 NULL, repo, no_ignores);
7841 done:
7842 if (repo) {
7843 const struct got_error *close_err = got_repo_close(repo);
7844 if (error == NULL)
7845 error = close_err;
7847 if (worktree)
7848 got_worktree_close(worktree);
7849 if (pack_fds) {
7850 const struct got_error *pack_err =
7851 got_repo_pack_fds_close(pack_fds);
7852 if (error == NULL)
7853 error = pack_err;
7855 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7856 free(cwd);
7857 return error;
7860 __dead static void
7861 usage_remove(void)
7863 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7864 getprogname());
7865 exit(1);
7868 static const struct got_error *
7869 print_remove_status(void *arg, unsigned char status,
7870 unsigned char staged_status, const char *path)
7872 while (path[0] == '/')
7873 path++;
7874 if (status == GOT_STATUS_NONEXISTENT)
7875 return NULL;
7876 if (status == staged_status && (status == GOT_STATUS_DELETE))
7877 status = GOT_STATUS_NO_CHANGE;
7878 printf("%c%c %s\n", status, staged_status, path);
7879 return NULL;
7882 static const struct got_error *
7883 cmd_remove(int argc, char *argv[])
7885 const struct got_error *error = NULL;
7886 struct got_worktree *worktree = NULL;
7887 struct got_repository *repo = NULL;
7888 const char *status_codes = NULL;
7889 char *cwd = NULL;
7890 struct got_pathlist_head paths;
7891 struct got_pathlist_entry *pe;
7892 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7893 int ignore_missing_paths = 0;
7894 int *pack_fds = NULL;
7896 TAILQ_INIT(&paths);
7898 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7899 switch (ch) {
7900 case 'f':
7901 delete_local_mods = 1;
7902 ignore_missing_paths = 1;
7903 break;
7904 case 'k':
7905 keep_on_disk = 1;
7906 break;
7907 case 'R':
7908 can_recurse = 1;
7909 break;
7910 case 's':
7911 for (i = 0; i < strlen(optarg); i++) {
7912 switch (optarg[i]) {
7913 case GOT_STATUS_MODIFY:
7914 delete_local_mods = 1;
7915 break;
7916 case GOT_STATUS_MISSING:
7917 ignore_missing_paths = 1;
7918 break;
7919 default:
7920 errx(1, "invalid status code '%c'",
7921 optarg[i]);
7924 status_codes = optarg;
7925 break;
7926 default:
7927 usage_remove();
7928 /* NOTREACHED */
7932 argc -= optind;
7933 argv += optind;
7935 #ifndef PROFILE
7936 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7937 NULL) == -1)
7938 err(1, "pledge");
7939 #endif
7940 if (argc < 1)
7941 usage_remove();
7943 cwd = getcwd(NULL, 0);
7944 if (cwd == NULL) {
7945 error = got_error_from_errno("getcwd");
7946 goto done;
7949 error = got_repo_pack_fds_open(&pack_fds);
7950 if (error != NULL)
7951 goto done;
7953 error = got_worktree_open(&worktree, cwd);
7954 if (error) {
7955 if (error->code == GOT_ERR_NOT_WORKTREE)
7956 error = wrap_not_worktree_error(error, "remove", cwd);
7957 goto done;
7960 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7961 NULL, pack_fds);
7962 if (error)
7963 goto done;
7965 error = apply_unveil(got_repo_get_path(repo), 1,
7966 got_worktree_get_root_path(worktree));
7967 if (error)
7968 goto done;
7970 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7971 if (error)
7972 goto done;
7974 if (!can_recurse) {
7975 char *ondisk_path;
7976 struct stat sb;
7977 TAILQ_FOREACH(pe, &paths, entry) {
7978 if (asprintf(&ondisk_path, "%s/%s",
7979 got_worktree_get_root_path(worktree),
7980 pe->path) == -1) {
7981 error = got_error_from_errno("asprintf");
7982 goto done;
7984 if (lstat(ondisk_path, &sb) == -1) {
7985 if (errno == ENOENT) {
7986 free(ondisk_path);
7987 continue;
7989 error = got_error_from_errno2("lstat",
7990 ondisk_path);
7991 free(ondisk_path);
7992 goto done;
7994 free(ondisk_path);
7995 if (S_ISDIR(sb.st_mode)) {
7996 error = got_error_msg(GOT_ERR_BAD_PATH,
7997 "removing directories requires -R option");
7998 goto done;
8003 error = got_worktree_schedule_delete(worktree, &paths,
8004 delete_local_mods, status_codes, print_remove_status, NULL,
8005 repo, keep_on_disk, ignore_missing_paths);
8006 done:
8007 if (repo) {
8008 const struct got_error *close_err = got_repo_close(repo);
8009 if (error == NULL)
8010 error = close_err;
8012 if (worktree)
8013 got_worktree_close(worktree);
8014 if (pack_fds) {
8015 const struct got_error *pack_err =
8016 got_repo_pack_fds_close(pack_fds);
8017 if (error == NULL)
8018 error = pack_err;
8020 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8021 free(cwd);
8022 return error;
8025 __dead static void
8026 usage_patch(void)
8028 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8029 "[patchfile]\n", getprogname());
8030 exit(1);
8033 static const struct got_error *
8034 patch_from_stdin(int *patchfd)
8036 const struct got_error *err = NULL;
8037 ssize_t r;
8038 char buf[BUFSIZ];
8039 sig_t sighup, sigint, sigquit;
8041 *patchfd = got_opentempfd();
8042 if (*patchfd == -1)
8043 return got_error_from_errno("got_opentempfd");
8045 sighup = signal(SIGHUP, SIG_DFL);
8046 sigint = signal(SIGINT, SIG_DFL);
8047 sigquit = signal(SIGQUIT, SIG_DFL);
8049 for (;;) {
8050 r = read(0, buf, sizeof(buf));
8051 if (r == -1) {
8052 err = got_error_from_errno("read");
8053 break;
8055 if (r == 0)
8056 break;
8057 if (write(*patchfd, buf, r) == -1) {
8058 err = got_error_from_errno("write");
8059 break;
8063 signal(SIGHUP, sighup);
8064 signal(SIGINT, sigint);
8065 signal(SIGQUIT, sigquit);
8067 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8068 err = got_error_from_errno("lseek");
8070 if (err != NULL) {
8071 close(*patchfd);
8072 *patchfd = -1;
8075 return err;
8078 static const struct got_error *
8079 patch_progress(void *arg, const char *old, const char *new,
8080 unsigned char status, const struct got_error *error, int old_from,
8081 int old_lines, int new_from, int new_lines, int offset,
8082 int ws_mangled, const struct got_error *hunk_err)
8084 const char *path = new == NULL ? old : new;
8086 while (*path == '/')
8087 path++;
8089 if (status != 0)
8090 printf("%c %s\n", status, path);
8092 if (error != NULL)
8093 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8095 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8096 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8097 old_lines, new_from, new_lines);
8098 if (hunk_err != NULL)
8099 printf("%s\n", hunk_err->msg);
8100 else if (offset != 0)
8101 printf("applied with offset %d\n", offset);
8102 else
8103 printf("hunk contains mangled whitespace\n");
8106 return NULL;
8109 static const struct got_error *
8110 cmd_patch(int argc, char *argv[])
8112 const struct got_error *error = NULL, *close_error = NULL;
8113 struct got_worktree *worktree = NULL;
8114 struct got_repository *repo = NULL;
8115 struct got_reflist_head refs;
8116 struct got_object_id *commit_id = NULL;
8117 const char *commit_id_str = NULL;
8118 struct stat sb;
8119 const char *errstr;
8120 char *cwd = NULL;
8121 int ch, nop = 0, strip = -1, reverse = 0;
8122 int patchfd;
8123 int *pack_fds = NULL;
8125 TAILQ_INIT(&refs);
8127 #ifndef PROFILE
8128 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8129 "unveil", NULL) == -1)
8130 err(1, "pledge");
8131 #endif
8133 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8134 switch (ch) {
8135 case 'c':
8136 commit_id_str = optarg;
8137 break;
8138 case 'n':
8139 nop = 1;
8140 break;
8141 case 'p':
8142 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8143 if (errstr != NULL)
8144 errx(1, "pathname strip count is %s: %s",
8145 errstr, optarg);
8146 break;
8147 case 'R':
8148 reverse = 1;
8149 break;
8150 default:
8151 usage_patch();
8152 /* NOTREACHED */
8156 argc -= optind;
8157 argv += optind;
8159 if (argc == 0) {
8160 error = patch_from_stdin(&patchfd);
8161 if (error)
8162 return error;
8163 } else if (argc == 1) {
8164 patchfd = open(argv[0], O_RDONLY);
8165 if (patchfd == -1) {
8166 error = got_error_from_errno2("open", argv[0]);
8167 return error;
8169 if (fstat(patchfd, &sb) == -1) {
8170 error = got_error_from_errno2("fstat", argv[0]);
8171 goto done;
8173 if (!S_ISREG(sb.st_mode)) {
8174 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8175 goto done;
8177 } else
8178 usage_patch();
8180 if ((cwd = getcwd(NULL, 0)) == NULL) {
8181 error = got_error_from_errno("getcwd");
8182 goto done;
8185 error = got_repo_pack_fds_open(&pack_fds);
8186 if (error != NULL)
8187 goto done;
8189 error = got_worktree_open(&worktree, cwd);
8190 if (error != NULL)
8191 goto done;
8193 const char *repo_path = got_worktree_get_repo_path(worktree);
8194 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8195 if (error != NULL)
8196 goto done;
8198 error = apply_unveil(got_repo_get_path(repo), 0,
8199 got_worktree_get_root_path(worktree));
8200 if (error != NULL)
8201 goto done;
8203 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8204 if (error)
8205 goto done;
8207 if (commit_id_str != NULL) {
8208 error = got_repo_match_object_id(&commit_id, NULL,
8209 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8210 if (error)
8211 goto done;
8214 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8215 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8217 done:
8218 got_ref_list_free(&refs);
8219 free(commit_id);
8220 if (repo) {
8221 close_error = got_repo_close(repo);
8222 if (error == NULL)
8223 error = close_error;
8225 if (worktree != NULL) {
8226 close_error = got_worktree_close(worktree);
8227 if (error == NULL)
8228 error = close_error;
8230 if (pack_fds) {
8231 const struct got_error *pack_err =
8232 got_repo_pack_fds_close(pack_fds);
8233 if (error == NULL)
8234 error = pack_err;
8236 free(cwd);
8237 return error;
8240 __dead static void
8241 usage_revert(void)
8243 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8244 getprogname());
8245 exit(1);
8248 static const struct got_error *
8249 revert_progress(void *arg, unsigned char status, const char *path)
8251 if (status == GOT_STATUS_UNVERSIONED)
8252 return NULL;
8254 while (path[0] == '/')
8255 path++;
8256 printf("%c %s\n", status, path);
8257 return NULL;
8260 struct choose_patch_arg {
8261 FILE *patch_script_file;
8262 const char *action;
8265 static const struct got_error *
8266 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8267 int nchanges, const char *action)
8269 const struct got_error *err;
8270 char *line = NULL;
8271 size_t linesize = 0;
8272 ssize_t linelen;
8274 switch (status) {
8275 case GOT_STATUS_ADD:
8276 printf("A %s\n%s this addition? [y/n] ", path, action);
8277 break;
8278 case GOT_STATUS_DELETE:
8279 printf("D %s\n%s this deletion? [y/n] ", path, action);
8280 break;
8281 case GOT_STATUS_MODIFY:
8282 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8283 return got_error_from_errno("fseek");
8284 printf(GOT_COMMIT_SEP_STR);
8285 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8286 printf("%s", line);
8287 if (linelen == -1 && ferror(patch_file)) {
8288 err = got_error_from_errno("getline");
8289 free(line);
8290 return err;
8292 free(line);
8293 printf(GOT_COMMIT_SEP_STR);
8294 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8295 path, n, nchanges, action);
8296 break;
8297 default:
8298 return got_error_path(path, GOT_ERR_FILE_STATUS);
8301 fflush(stdout);
8302 return NULL;
8305 static const struct got_error *
8306 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8307 FILE *patch_file, int n, int nchanges)
8309 const struct got_error *err = NULL;
8310 char *line = NULL;
8311 size_t linesize = 0;
8312 ssize_t linelen;
8313 int resp = ' ';
8314 struct choose_patch_arg *a = arg;
8316 *choice = GOT_PATCH_CHOICE_NONE;
8318 if (a->patch_script_file) {
8319 char *nl;
8320 err = show_change(status, path, patch_file, n, nchanges,
8321 a->action);
8322 if (err)
8323 return err;
8324 linelen = getline(&line, &linesize, a->patch_script_file);
8325 if (linelen == -1) {
8326 if (ferror(a->patch_script_file))
8327 return got_error_from_errno("getline");
8328 return NULL;
8330 nl = strchr(line, '\n');
8331 if (nl)
8332 *nl = '\0';
8333 if (strcmp(line, "y") == 0) {
8334 *choice = GOT_PATCH_CHOICE_YES;
8335 printf("y\n");
8336 } else if (strcmp(line, "n") == 0) {
8337 *choice = GOT_PATCH_CHOICE_NO;
8338 printf("n\n");
8339 } else if (strcmp(line, "q") == 0 &&
8340 status == GOT_STATUS_MODIFY) {
8341 *choice = GOT_PATCH_CHOICE_QUIT;
8342 printf("q\n");
8343 } else
8344 printf("invalid response '%s'\n", line);
8345 free(line);
8346 return NULL;
8349 while (resp != 'y' && resp != 'n' && resp != 'q') {
8350 err = show_change(status, path, patch_file, n, nchanges,
8351 a->action);
8352 if (err)
8353 return err;
8354 resp = getchar();
8355 if (resp == '\n')
8356 resp = getchar();
8357 if (status == GOT_STATUS_MODIFY) {
8358 if (resp != 'y' && resp != 'n' && resp != 'q') {
8359 printf("invalid response '%c'\n", resp);
8360 resp = ' ';
8362 } else if (resp != 'y' && resp != 'n') {
8363 printf("invalid response '%c'\n", resp);
8364 resp = ' ';
8368 if (resp == 'y')
8369 *choice = GOT_PATCH_CHOICE_YES;
8370 else if (resp == 'n')
8371 *choice = GOT_PATCH_CHOICE_NO;
8372 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8373 *choice = GOT_PATCH_CHOICE_QUIT;
8375 return NULL;
8378 struct wt_commitable_path_arg {
8379 struct got_pathlist_head *commit_paths;
8380 int *has_changes;
8384 * Shortcut work tree status callback to determine if the set of paths scanned
8385 * has at least one versioned path that is being modified and, if not NULL, is
8386 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8387 * soon as a path is passed with a status that satisfies this criteria.
8389 static const struct got_error *
8390 worktree_has_commitable_path(void *arg, unsigned char status,
8391 unsigned char staged_status, const char *path,
8392 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8393 struct got_object_id *commit_id, int dirfd, const char *de_name)
8395 struct wt_commitable_path_arg *a = arg;
8397 if (status == staged_status && (status == GOT_STATUS_DELETE))
8398 status = GOT_STATUS_NO_CHANGE;
8400 if (!(status == GOT_STATUS_NO_CHANGE ||
8401 status == GOT_STATUS_UNVERSIONED) ||
8402 staged_status != GOT_STATUS_NO_CHANGE) {
8403 if (a->commit_paths != NULL) {
8404 struct got_pathlist_entry *pe;
8406 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8407 if (strncmp(path, pe->path,
8408 pe->path_len) == 0) {
8409 *a->has_changes = 1;
8410 break;
8413 } else
8414 *a->has_changes = 1;
8416 if (*a->has_changes)
8417 return got_error(GOT_ERR_FILE_MODIFIED);
8420 return NULL;
8424 * Check that the changeset of the commit identified by id is
8425 * comprised of at least one modified path that is being committed.
8427 static const struct got_error *
8428 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8429 struct got_object_id *id, struct got_worktree *worktree,
8430 struct got_repository *repo)
8432 const struct got_error *err;
8433 struct got_pathlist_head paths;
8434 struct got_commit_object *commit = NULL, *pcommit = NULL;
8435 struct got_tree_object *tree = NULL, *ptree = NULL;
8436 struct got_object_qid *pid;
8438 TAILQ_INIT(&paths);
8440 err = got_object_open_as_commit(&commit, repo, id);
8441 if (err)
8442 goto done;
8444 err = got_object_open_as_tree(&tree, repo,
8445 got_object_commit_get_tree_id(commit));
8446 if (err)
8447 goto done;
8449 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8450 if (pid != NULL) {
8451 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8452 if (err)
8453 goto done;
8455 err = got_object_open_as_tree(&ptree, repo,
8456 got_object_commit_get_tree_id(pcommit));
8457 if (err)
8458 goto done;
8461 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8462 got_diff_tree_collect_changed_paths, &paths, 0);
8463 if (err)
8464 goto done;
8466 err = got_worktree_status(worktree, &paths, repo, 0,
8467 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8468 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8470 * At least one changed path in the referenced commit is
8471 * modified in the work tree, that's all we need to know!
8473 err = NULL;
8476 done:
8477 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8478 if (commit)
8479 got_object_commit_close(commit);
8480 if (pcommit)
8481 got_object_commit_close(pcommit);
8482 if (tree)
8483 got_object_tree_close(tree);
8484 if (ptree)
8485 got_object_tree_close(ptree);
8486 return err;
8490 * Remove any "logmsg" reference comprised entirely of paths that have
8491 * been reverted in this work tree. If any path in the logmsg ref changeset
8492 * remains in a changed state in the worktree, do not remove the reference.
8494 static const struct got_error *
8495 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8497 const struct got_error *err;
8498 struct got_reflist_head refs;
8499 struct got_reflist_entry *re;
8500 struct got_commit_object *commit = NULL;
8501 struct got_object_id *commit_id = NULL;
8502 struct wt_commitable_path_arg wcpa;
8503 char *uuidstr = NULL;
8505 TAILQ_INIT(&refs);
8507 err = got_worktree_get_uuid(&uuidstr, worktree);
8508 if (err)
8509 goto done;
8511 err = got_ref_list(&refs, repo, "refs/got/worktree",
8512 got_ref_cmp_by_name, repo);
8513 if (err)
8514 goto done;
8516 TAILQ_FOREACH(re, &refs, entry) {
8517 const char *refname;
8518 int has_changes = 0;
8520 refname = got_ref_get_name(re->ref);
8522 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8523 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8524 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8525 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8526 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8527 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8528 else
8529 continue;
8531 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8532 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8533 else
8534 continue;
8536 err = got_repo_match_object_id(&commit_id, NULL, refname,
8537 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8538 if (err)
8539 goto done;
8541 err = got_object_open_as_commit(&commit, repo, commit_id);
8542 if (err)
8543 goto done;
8545 wcpa.commit_paths = NULL;
8546 wcpa.has_changes = &has_changes;
8548 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8549 worktree, repo);
8550 if (err)
8551 goto done;
8553 if (!has_changes) {
8554 err = got_ref_delete(re->ref, repo);
8555 if (err)
8556 goto done;
8559 got_object_commit_close(commit);
8560 commit = NULL;
8561 free(commit_id);
8562 commit_id = NULL;
8565 done:
8566 free(uuidstr);
8567 free(commit_id);
8568 got_ref_list_free(&refs);
8569 if (commit)
8570 got_object_commit_close(commit);
8571 return err;
8574 static const struct got_error *
8575 cmd_revert(int argc, char *argv[])
8577 const struct got_error *error = NULL;
8578 struct got_worktree *worktree = NULL;
8579 struct got_repository *repo = NULL;
8580 char *cwd = NULL, *path = NULL;
8581 struct got_pathlist_head paths;
8582 struct got_pathlist_entry *pe;
8583 int ch, can_recurse = 0, pflag = 0;
8584 FILE *patch_script_file = NULL;
8585 const char *patch_script_path = NULL;
8586 struct choose_patch_arg cpa;
8587 int *pack_fds = NULL;
8589 TAILQ_INIT(&paths);
8591 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8592 switch (ch) {
8593 case 'F':
8594 patch_script_path = optarg;
8595 break;
8596 case 'p':
8597 pflag = 1;
8598 break;
8599 case 'R':
8600 can_recurse = 1;
8601 break;
8602 default:
8603 usage_revert();
8604 /* NOTREACHED */
8608 argc -= optind;
8609 argv += optind;
8611 #ifndef PROFILE
8612 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8613 "unveil", NULL) == -1)
8614 err(1, "pledge");
8615 #endif
8616 if (argc < 1)
8617 usage_revert();
8618 if (patch_script_path && !pflag)
8619 errx(1, "-F option can only be used together with -p option");
8621 cwd = getcwd(NULL, 0);
8622 if (cwd == NULL) {
8623 error = got_error_from_errno("getcwd");
8624 goto done;
8627 error = got_repo_pack_fds_open(&pack_fds);
8628 if (error != NULL)
8629 goto done;
8631 error = got_worktree_open(&worktree, cwd);
8632 if (error) {
8633 if (error->code == GOT_ERR_NOT_WORKTREE)
8634 error = wrap_not_worktree_error(error, "revert", cwd);
8635 goto done;
8638 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8639 NULL, pack_fds);
8640 if (error != NULL)
8641 goto done;
8643 if (patch_script_path) {
8644 patch_script_file = fopen(patch_script_path, "re");
8645 if (patch_script_file == NULL) {
8646 error = got_error_from_errno2("fopen",
8647 patch_script_path);
8648 goto done;
8653 * XXX "c" perm needed on repo dir to delete merge references.
8655 error = apply_unveil(got_repo_get_path(repo), 0,
8656 got_worktree_get_root_path(worktree));
8657 if (error)
8658 goto done;
8660 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8661 if (error)
8662 goto done;
8664 if (!can_recurse) {
8665 char *ondisk_path;
8666 struct stat sb;
8667 TAILQ_FOREACH(pe, &paths, entry) {
8668 if (asprintf(&ondisk_path, "%s/%s",
8669 got_worktree_get_root_path(worktree),
8670 pe->path) == -1) {
8671 error = got_error_from_errno("asprintf");
8672 goto done;
8674 if (lstat(ondisk_path, &sb) == -1) {
8675 if (errno == ENOENT) {
8676 free(ondisk_path);
8677 continue;
8679 error = got_error_from_errno2("lstat",
8680 ondisk_path);
8681 free(ondisk_path);
8682 goto done;
8684 free(ondisk_path);
8685 if (S_ISDIR(sb.st_mode)) {
8686 error = got_error_msg(GOT_ERR_BAD_PATH,
8687 "reverting directories requires -R option");
8688 goto done;
8693 cpa.patch_script_file = patch_script_file;
8694 cpa.action = "revert";
8695 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8696 pflag ? choose_patch : NULL, &cpa, repo);
8698 error = rm_logmsg_ref(worktree, repo);
8699 done:
8700 if (patch_script_file && fclose(patch_script_file) == EOF &&
8701 error == NULL)
8702 error = got_error_from_errno2("fclose", patch_script_path);
8703 if (repo) {
8704 const struct got_error *close_err = got_repo_close(repo);
8705 if (error == NULL)
8706 error = close_err;
8708 if (worktree)
8709 got_worktree_close(worktree);
8710 if (pack_fds) {
8711 const struct got_error *pack_err =
8712 got_repo_pack_fds_close(pack_fds);
8713 if (error == NULL)
8714 error = pack_err;
8716 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8717 free(path);
8718 free(cwd);
8719 return error;
8722 __dead static void
8723 usage_commit(void)
8725 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8726 "[-m message] [path ...]\n", getprogname());
8727 exit(1);
8730 struct collect_commit_logmsg_arg {
8731 const char *cmdline_log;
8732 const char *prepared_log;
8733 const char *merged_log;
8734 int non_interactive;
8735 const char *editor;
8736 const char *worktree_path;
8737 const char *branch_name;
8738 const char *repo_path;
8739 char *logmsg_path;
8743 static const struct got_error *
8744 read_prepared_logmsg(char **logmsg, const char *path)
8746 const struct got_error *err = NULL;
8747 FILE *f = NULL;
8748 struct stat sb;
8749 size_t r;
8751 *logmsg = NULL;
8752 memset(&sb, 0, sizeof(sb));
8754 f = fopen(path, "re");
8755 if (f == NULL)
8756 return got_error_from_errno2("fopen", path);
8758 if (fstat(fileno(f), &sb) == -1) {
8759 err = got_error_from_errno2("fstat", path);
8760 goto done;
8762 if (sb.st_size == 0) {
8763 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8764 goto done;
8767 *logmsg = malloc(sb.st_size + 1);
8768 if (*logmsg == NULL) {
8769 err = got_error_from_errno("malloc");
8770 goto done;
8773 r = fread(*logmsg, 1, sb.st_size, f);
8774 if (r != sb.st_size) {
8775 if (ferror(f))
8776 err = got_error_from_errno2("fread", path);
8777 else
8778 err = got_error(GOT_ERR_IO);
8779 goto done;
8781 (*logmsg)[sb.st_size] = '\0';
8782 done:
8783 if (fclose(f) == EOF && err == NULL)
8784 err = got_error_from_errno2("fclose", path);
8785 if (err) {
8786 free(*logmsg);
8787 *logmsg = NULL;
8789 return err;
8792 static const struct got_error *
8793 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8794 const char *diff_path, char **logmsg, void *arg)
8796 char *initial_content = NULL;
8797 struct got_pathlist_entry *pe;
8798 const struct got_error *err = NULL;
8799 char *template = NULL;
8800 char *prepared_msg = NULL, *merged_msg = NULL;
8801 struct collect_commit_logmsg_arg *a = arg;
8802 int initial_content_len;
8803 int fd = -1;
8804 size_t len;
8806 /* if a message was specified on the command line, just use it */
8807 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8808 len = strlen(a->cmdline_log) + 1;
8809 *logmsg = malloc(len + 1);
8810 if (*logmsg == NULL)
8811 return got_error_from_errno("malloc");
8812 strlcpy(*logmsg, a->cmdline_log, len);
8813 return NULL;
8814 } else if (a->prepared_log != NULL && a->non_interactive)
8815 return read_prepared_logmsg(logmsg, a->prepared_log);
8817 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8818 return got_error_from_errno("asprintf");
8820 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8821 if (err)
8822 goto done;
8824 if (a->prepared_log) {
8825 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8826 if (err)
8827 goto done;
8828 } else if (a->merged_log) {
8829 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8830 if (err)
8831 goto done;
8834 initial_content_len = asprintf(&initial_content,
8835 "%s%s\n# changes to be committed on branch %s:\n",
8836 prepared_msg ? prepared_msg : "",
8837 merged_msg ? merged_msg : "", a->branch_name);
8838 if (initial_content_len == -1) {
8839 err = got_error_from_errno("asprintf");
8840 goto done;
8843 if (write(fd, initial_content, initial_content_len) == -1) {
8844 err = got_error_from_errno2("write", a->logmsg_path);
8845 goto done;
8848 TAILQ_FOREACH(pe, commitable_paths, entry) {
8849 struct got_commitable *ct = pe->data;
8850 dprintf(fd, "# %c %s\n",
8851 got_commitable_get_status(ct),
8852 got_commitable_get_path(ct));
8855 if (diff_path) {
8856 dprintf(fd, "# detailed changes can be viewed in %s\n",
8857 diff_path);
8860 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8861 initial_content_len, a->prepared_log ? 0 : 1);
8862 done:
8863 free(initial_content);
8864 free(template);
8865 free(prepared_msg);
8866 free(merged_msg);
8868 if (fd != -1 && close(fd) == -1 && err == NULL)
8869 err = got_error_from_errno2("close", a->logmsg_path);
8871 /* Editor is done; we can now apply unveil(2) */
8872 if (err == NULL)
8873 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8874 if (err) {
8875 free(*logmsg);
8876 *logmsg = NULL;
8878 return err;
8881 static const struct got_error *
8882 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8883 const char *type, int has_content)
8885 const struct got_error *err = NULL;
8886 char *logmsg = NULL;
8888 err = got_object_commit_get_logmsg(&logmsg, commit);
8889 if (err)
8890 return err;
8892 if (fprintf(f, "%s# log message of %s commit %s:%s",
8893 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8894 err = got_ferror(f, GOT_ERR_IO);
8896 free(logmsg);
8897 return err;
8901 * Lookup "logmsg" references of backed-out and cherrypicked commits
8902 * belonging to the current work tree. If found, and the worktree has
8903 * at least one modified file that was changed in the referenced commit,
8904 * add its log message to a new temporary file at *logmsg_path.
8905 * Add all refs found to matched_refs to be scheduled for removal on
8906 * successful commit.
8908 static const struct got_error *
8909 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8910 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8911 struct got_repository *repo)
8913 const struct got_error *err;
8914 struct got_commit_object *commit = NULL;
8915 struct got_object_id *id = NULL;
8916 struct got_reflist_head refs;
8917 struct got_reflist_entry *re, *re_match;
8918 FILE *f = NULL;
8919 char *uuidstr = NULL;
8920 int added_logmsg = 0;
8922 TAILQ_INIT(&refs);
8924 *logmsg_path = NULL;
8926 err = got_worktree_get_uuid(&uuidstr, worktree);
8927 if (err)
8928 goto done;
8930 err = got_ref_list(&refs, repo, "refs/got/worktree",
8931 got_ref_cmp_by_name, repo);
8932 if (err)
8933 goto done;
8935 TAILQ_FOREACH(re, &refs, entry) {
8936 const char *refname, *type;
8937 struct wt_commitable_path_arg wcpa;
8938 int add_logmsg = 0;
8940 refname = got_ref_get_name(re->ref);
8942 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8943 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8944 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8945 type = "cherrypicked";
8946 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8947 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8948 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8949 type = "backed-out";
8950 } else
8951 continue;
8953 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8954 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8955 else
8956 continue;
8958 err = got_repo_match_object_id(&id, NULL, refname,
8959 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8960 if (err)
8961 goto done;
8963 err = got_object_open_as_commit(&commit, repo, id);
8964 if (err)
8965 goto done;
8967 wcpa.commit_paths = paths;
8968 wcpa.has_changes = &add_logmsg;
8970 err = commit_path_changed_in_worktree(&wcpa, id,
8971 worktree, repo);
8972 if (err)
8973 goto done;
8975 if (add_logmsg) {
8976 if (f == NULL) {
8977 err = got_opentemp_named(logmsg_path, &f,
8978 "got-commit-logmsg", "");
8979 if (err)
8980 goto done;
8982 err = cat_logmsg(f, commit, refname, type,
8983 added_logmsg);
8984 if (err)
8985 goto done;
8986 if (!added_logmsg)
8987 ++added_logmsg;
8989 err = got_reflist_entry_dup(&re_match, re);
8990 if (err)
8991 goto done;
8992 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
8995 got_object_commit_close(commit);
8996 commit = NULL;
8997 free(id);
8998 id = NULL;
9001 done:
9002 free(id);
9003 free(uuidstr);
9004 got_ref_list_free(&refs);
9005 if (commit)
9006 got_object_commit_close(commit);
9007 if (f && fclose(f) == EOF && err == NULL)
9008 err = got_error_from_errno("fclose");
9009 if (!added_logmsg) {
9010 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9011 err = got_error_from_errno2("unlink", *logmsg_path);
9012 *logmsg_path = NULL;
9014 return err;
9017 static const struct got_error *
9018 cmd_commit(int argc, char *argv[])
9020 const struct got_error *error = NULL;
9021 struct got_worktree *worktree = NULL;
9022 struct got_repository *repo = NULL;
9023 char *cwd = NULL, *id_str = NULL;
9024 struct got_object_id *id = NULL;
9025 const char *logmsg = NULL;
9026 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9027 struct collect_commit_logmsg_arg cl_arg;
9028 const char *author = NULL;
9029 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9030 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9031 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9032 int show_diff = 1;
9033 struct got_pathlist_head paths;
9034 struct got_reflist_head refs;
9035 struct got_reflist_entry *re;
9036 int *pack_fds = NULL;
9038 TAILQ_INIT(&refs);
9039 TAILQ_INIT(&paths);
9040 cl_arg.logmsg_path = NULL;
9042 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9043 switch (ch) {
9044 case 'A':
9045 author = optarg;
9046 error = valid_author(author);
9047 if (error)
9048 return error;
9049 break;
9050 case 'F':
9051 if (logmsg != NULL)
9052 option_conflict('F', 'm');
9053 prepared_logmsg = realpath(optarg, NULL);
9054 if (prepared_logmsg == NULL)
9055 return got_error_from_errno2("realpath",
9056 optarg);
9057 break;
9058 case 'm':
9059 if (prepared_logmsg)
9060 option_conflict('m', 'F');
9061 logmsg = optarg;
9062 break;
9063 case 'N':
9064 non_interactive = 1;
9065 break;
9066 case 'n':
9067 show_diff = 0;
9068 break;
9069 case 'S':
9070 allow_bad_symlinks = 1;
9071 break;
9072 default:
9073 usage_commit();
9074 /* NOTREACHED */
9078 argc -= optind;
9079 argv += optind;
9081 #ifndef PROFILE
9082 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9083 "unveil", NULL) == -1)
9084 err(1, "pledge");
9085 #endif
9086 cwd = getcwd(NULL, 0);
9087 if (cwd == NULL) {
9088 error = got_error_from_errno("getcwd");
9089 goto done;
9092 error = got_repo_pack_fds_open(&pack_fds);
9093 if (error != NULL)
9094 goto done;
9096 error = got_worktree_open(&worktree, cwd);
9097 if (error) {
9098 if (error->code == GOT_ERR_NOT_WORKTREE)
9099 error = wrap_not_worktree_error(error, "commit", cwd);
9100 goto done;
9103 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9104 if (error)
9105 goto done;
9106 if (rebase_in_progress) {
9107 error = got_error(GOT_ERR_REBASING);
9108 goto done;
9111 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9112 worktree);
9113 if (error)
9114 goto done;
9116 error = get_gitconfig_path(&gitconfig_path);
9117 if (error)
9118 goto done;
9119 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9120 gitconfig_path, pack_fds);
9121 if (error != NULL)
9122 goto done;
9124 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9125 if (error)
9126 goto done;
9127 if (merge_in_progress) {
9128 error = got_error(GOT_ERR_MERGE_BUSY);
9129 goto done;
9132 error = get_author(&committer, repo, worktree);
9133 if (error)
9134 goto done;
9136 if (author != NULL && !strcmp(committer, author)) {
9137 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9138 goto done;
9141 if (author == NULL)
9142 author = committer;
9145 * unveil(2) traverses exec(2); if an editor is used we have
9146 * to apply unveil after the log message has been written.
9148 if (logmsg == NULL || strlen(logmsg) == 0)
9149 error = get_editor(&editor);
9150 else
9151 error = apply_unveil(got_repo_get_path(repo), 0,
9152 got_worktree_get_root_path(worktree));
9153 if (error)
9154 goto done;
9156 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9157 if (error)
9158 goto done;
9160 if (prepared_logmsg == NULL) {
9161 error = lookup_logmsg_ref(&merged_logmsg,
9162 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9163 if (error)
9164 goto done;
9167 cl_arg.editor = editor;
9168 cl_arg.cmdline_log = logmsg;
9169 cl_arg.prepared_log = prepared_logmsg;
9170 cl_arg.merged_log = merged_logmsg;
9171 cl_arg.non_interactive = non_interactive;
9172 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9173 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9174 if (!histedit_in_progress) {
9175 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9176 error = got_error(GOT_ERR_COMMIT_BRANCH);
9177 goto done;
9179 cl_arg.branch_name += 11;
9181 cl_arg.repo_path = got_repo_get_path(repo);
9182 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9183 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9184 print_status, NULL, repo);
9185 if (error) {
9186 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9187 cl_arg.logmsg_path != NULL)
9188 preserve_logmsg = 1;
9189 goto done;
9192 error = got_object_id_str(&id_str, id);
9193 if (error)
9194 goto done;
9195 printf("Created commit %s\n", id_str);
9197 TAILQ_FOREACH(re, &refs, entry) {
9198 error = got_ref_delete(re->ref, repo);
9199 if (error)
9200 goto done;
9203 done:
9204 if (preserve_logmsg) {
9205 fprintf(stderr, "%s: log message preserved in %s\n",
9206 getprogname(), cl_arg.logmsg_path);
9207 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9208 error == NULL)
9209 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9210 free(cl_arg.logmsg_path);
9211 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9212 error = got_error_from_errno2("unlink", merged_logmsg);
9213 free(merged_logmsg);
9214 if (repo) {
9215 const struct got_error *close_err = got_repo_close(repo);
9216 if (error == NULL)
9217 error = close_err;
9219 if (worktree)
9220 got_worktree_close(worktree);
9221 if (pack_fds) {
9222 const struct got_error *pack_err =
9223 got_repo_pack_fds_close(pack_fds);
9224 if (error == NULL)
9225 error = pack_err;
9227 got_ref_list_free(&refs);
9228 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9229 free(cwd);
9230 free(id_str);
9231 free(gitconfig_path);
9232 free(editor);
9233 free(committer);
9234 free(prepared_logmsg);
9235 return error;
9238 __dead static void
9239 usage_send(void)
9241 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9242 "[-r repository-path] [-t tag] [remote-repository]\n",
9243 getprogname());
9244 exit(1);
9247 static void
9248 print_load_info(int print_colored, int print_found, int print_trees,
9249 int ncolored, int nfound, int ntrees)
9251 if (print_colored) {
9252 printf("%d commit%s colored", ncolored,
9253 ncolored == 1 ? "" : "s");
9255 if (print_found) {
9256 printf("%s%d object%s found",
9257 ncolored > 0 ? "; " : "",
9258 nfound, nfound == 1 ? "" : "s");
9260 if (print_trees) {
9261 printf("; %d tree%s scanned", ntrees,
9262 ntrees == 1 ? "" : "s");
9266 struct got_send_progress_arg {
9267 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9268 int verbosity;
9269 int last_ncolored;
9270 int last_nfound;
9271 int last_ntrees;
9272 int loading_done;
9273 int last_ncommits;
9274 int last_nobj_total;
9275 int last_p_deltify;
9276 int last_p_written;
9277 int last_p_sent;
9278 int printed_something;
9279 int sent_something;
9280 struct got_pathlist_head *delete_branches;
9283 static const struct got_error *
9284 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9285 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9286 int nobj_written, off_t bytes_sent, const char *refname,
9287 const char *errmsg, int success)
9289 struct got_send_progress_arg *a = arg;
9290 char scaled_packsize[FMT_SCALED_STRSIZE];
9291 char scaled_sent[FMT_SCALED_STRSIZE];
9292 int p_deltify = 0, p_written = 0, p_sent = 0;
9293 int print_colored = 0, print_found = 0, print_trees = 0;
9294 int print_searching = 0, print_total = 0;
9295 int print_deltify = 0, print_written = 0, print_sent = 0;
9297 if (a->verbosity < 0)
9298 return NULL;
9300 if (refname) {
9301 const char *status = success ? "accepted" : "rejected";
9303 if (success) {
9304 struct got_pathlist_entry *pe;
9305 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9306 const char *branchname = pe->path;
9307 if (got_path_cmp(branchname, refname,
9308 strlen(branchname), strlen(refname)) == 0) {
9309 status = "deleted";
9310 a->sent_something = 1;
9311 break;
9316 if (a->printed_something)
9317 putchar('\n');
9318 printf("Server has %s %s", status, refname);
9319 if (errmsg)
9320 printf(": %s", errmsg);
9321 a->printed_something = 1;
9322 return NULL;
9325 if (a->last_ncolored != ncolored) {
9326 print_colored = 1;
9327 a->last_ncolored = ncolored;
9330 if (a->last_nfound != nfound) {
9331 print_colored = 1;
9332 print_found = 1;
9333 a->last_nfound = nfound;
9336 if (a->last_ntrees != ntrees) {
9337 print_colored = 1;
9338 print_found = 1;
9339 print_trees = 1;
9340 a->last_ntrees = ntrees;
9343 if ((print_colored || print_found || print_trees) &&
9344 !a->loading_done) {
9345 printf("\r");
9346 print_load_info(print_colored, print_found, print_trees,
9347 ncolored, nfound, ntrees);
9348 a->printed_something = 1;
9349 fflush(stdout);
9350 return NULL;
9351 } else if (!a->loading_done) {
9352 printf("\r");
9353 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9354 printf("\n");
9355 a->loading_done = 1;
9358 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9359 return got_error_from_errno("fmt_scaled");
9360 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9361 return got_error_from_errno("fmt_scaled");
9363 if (a->last_ncommits != ncommits) {
9364 print_searching = 1;
9365 a->last_ncommits = ncommits;
9368 if (a->last_nobj_total != nobj_total) {
9369 print_searching = 1;
9370 print_total = 1;
9371 a->last_nobj_total = nobj_total;
9374 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9375 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9376 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9377 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9378 return got_error(GOT_ERR_NO_SPACE);
9381 if (nobj_deltify > 0 || nobj_written > 0) {
9382 if (nobj_deltify > 0) {
9383 p_deltify = (nobj_deltify * 100) / nobj_total;
9384 if (p_deltify != a->last_p_deltify) {
9385 a->last_p_deltify = p_deltify;
9386 print_searching = 1;
9387 print_total = 1;
9388 print_deltify = 1;
9391 if (nobj_written > 0) {
9392 p_written = (nobj_written * 100) / nobj_total;
9393 if (p_written != a->last_p_written) {
9394 a->last_p_written = p_written;
9395 print_searching = 1;
9396 print_total = 1;
9397 print_deltify = 1;
9398 print_written = 1;
9403 if (bytes_sent > 0) {
9404 p_sent = (bytes_sent * 100) / packfile_size;
9405 if (p_sent != a->last_p_sent) {
9406 a->last_p_sent = p_sent;
9407 print_searching = 1;
9408 print_total = 1;
9409 print_deltify = 1;
9410 print_written = 1;
9411 print_sent = 1;
9413 a->sent_something = 1;
9416 if (print_searching || print_total || print_deltify || print_written ||
9417 print_sent)
9418 printf("\r");
9419 if (print_searching)
9420 printf("packing %d reference%s", ncommits,
9421 ncommits == 1 ? "" : "s");
9422 if (print_total)
9423 printf("; %d object%s", nobj_total,
9424 nobj_total == 1 ? "" : "s");
9425 if (print_deltify)
9426 printf("; deltify: %d%%", p_deltify);
9427 if (print_sent)
9428 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9429 scaled_packsize, p_sent);
9430 else if (print_written)
9431 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9432 scaled_packsize, p_written);
9433 if (print_searching || print_total || print_deltify ||
9434 print_written || print_sent) {
9435 a->printed_something = 1;
9436 fflush(stdout);
9438 return NULL;
9441 static const struct got_error *
9442 cmd_send(int argc, char *argv[])
9444 const struct got_error *error = NULL;
9445 char *cwd = NULL, *repo_path = NULL;
9446 const char *remote_name;
9447 char *proto = NULL, *host = NULL, *port = NULL;
9448 char *repo_name = NULL, *server_path = NULL;
9449 const struct got_remote_repo *remotes, *remote = NULL;
9450 int nremotes, nbranches = 0, ndelete_branches = 0;
9451 struct got_repository *repo = NULL;
9452 struct got_worktree *worktree = NULL;
9453 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9454 struct got_pathlist_head branches;
9455 struct got_pathlist_head tags;
9456 struct got_reflist_head all_branches;
9457 struct got_reflist_head all_tags;
9458 struct got_pathlist_head delete_args;
9459 struct got_pathlist_head delete_branches;
9460 struct got_reflist_entry *re;
9461 struct got_pathlist_entry *pe;
9462 int i, ch, sendfd = -1, sendstatus;
9463 pid_t sendpid = -1;
9464 struct got_send_progress_arg spa;
9465 int verbosity = 0, overwrite_refs = 0;
9466 int send_all_branches = 0, send_all_tags = 0;
9467 struct got_reference *ref = NULL;
9468 int *pack_fds = NULL;
9470 TAILQ_INIT(&branches);
9471 TAILQ_INIT(&tags);
9472 TAILQ_INIT(&all_branches);
9473 TAILQ_INIT(&all_tags);
9474 TAILQ_INIT(&delete_args);
9475 TAILQ_INIT(&delete_branches);
9477 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9478 switch (ch) {
9479 case 'a':
9480 send_all_branches = 1;
9481 break;
9482 case 'b':
9483 error = got_pathlist_append(&branches, optarg, NULL);
9484 if (error)
9485 return error;
9486 nbranches++;
9487 break;
9488 case 'd':
9489 error = got_pathlist_append(&delete_args, optarg, NULL);
9490 if (error)
9491 return error;
9492 break;
9493 case 'f':
9494 overwrite_refs = 1;
9495 break;
9496 case 'q':
9497 verbosity = -1;
9498 break;
9499 case 'r':
9500 repo_path = realpath(optarg, NULL);
9501 if (repo_path == NULL)
9502 return got_error_from_errno2("realpath",
9503 optarg);
9504 got_path_strip_trailing_slashes(repo_path);
9505 break;
9506 case 'T':
9507 send_all_tags = 1;
9508 break;
9509 case 't':
9510 error = got_pathlist_append(&tags, optarg, NULL);
9511 if (error)
9512 return error;
9513 break;
9514 case 'v':
9515 if (verbosity < 0)
9516 verbosity = 0;
9517 else if (verbosity < 3)
9518 verbosity++;
9519 break;
9520 default:
9521 usage_send();
9522 /* NOTREACHED */
9525 argc -= optind;
9526 argv += optind;
9528 if (send_all_branches && !TAILQ_EMPTY(&branches))
9529 option_conflict('a', 'b');
9530 if (send_all_tags && !TAILQ_EMPTY(&tags))
9531 option_conflict('T', 't');
9534 if (argc == 0)
9535 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9536 else if (argc == 1)
9537 remote_name = argv[0];
9538 else
9539 usage_send();
9541 cwd = getcwd(NULL, 0);
9542 if (cwd == NULL) {
9543 error = got_error_from_errno("getcwd");
9544 goto done;
9547 error = got_repo_pack_fds_open(&pack_fds);
9548 if (error != NULL)
9549 goto done;
9551 if (repo_path == NULL) {
9552 error = got_worktree_open(&worktree, cwd);
9553 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9554 goto done;
9555 else
9556 error = NULL;
9557 if (worktree) {
9558 repo_path =
9559 strdup(got_worktree_get_repo_path(worktree));
9560 if (repo_path == NULL)
9561 error = got_error_from_errno("strdup");
9562 if (error)
9563 goto done;
9564 } else {
9565 repo_path = strdup(cwd);
9566 if (repo_path == NULL) {
9567 error = got_error_from_errno("strdup");
9568 goto done;
9573 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9574 if (error)
9575 goto done;
9577 if (worktree) {
9578 worktree_conf = got_worktree_get_gotconfig(worktree);
9579 if (worktree_conf) {
9580 got_gotconfig_get_remotes(&nremotes, &remotes,
9581 worktree_conf);
9582 for (i = 0; i < nremotes; i++) {
9583 if (strcmp(remotes[i].name, remote_name) == 0) {
9584 remote = &remotes[i];
9585 break;
9590 if (remote == NULL) {
9591 repo_conf = got_repo_get_gotconfig(repo);
9592 if (repo_conf) {
9593 got_gotconfig_get_remotes(&nremotes, &remotes,
9594 repo_conf);
9595 for (i = 0; i < nremotes; i++) {
9596 if (strcmp(remotes[i].name, remote_name) == 0) {
9597 remote = &remotes[i];
9598 break;
9603 if (remote == NULL) {
9604 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9605 for (i = 0; i < nremotes; i++) {
9606 if (strcmp(remotes[i].name, remote_name) == 0) {
9607 remote = &remotes[i];
9608 break;
9612 if (remote == NULL) {
9613 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9614 goto done;
9617 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9618 &repo_name, remote->send_url);
9619 if (error)
9620 goto done;
9622 if (strcmp(proto, "git") == 0) {
9623 #ifndef PROFILE
9624 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9625 "sendfd dns inet unveil", NULL) == -1)
9626 err(1, "pledge");
9627 #endif
9628 } else if (strcmp(proto, "git+ssh") == 0 ||
9629 strcmp(proto, "ssh") == 0) {
9630 #ifndef PROFILE
9631 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9632 "sendfd unveil", NULL) == -1)
9633 err(1, "pledge");
9634 #endif
9635 } else if (strcmp(proto, "http") == 0 ||
9636 strcmp(proto, "git+http") == 0) {
9637 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9638 goto done;
9639 } else {
9640 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9641 goto done;
9644 error = got_dial_apply_unveil(proto);
9645 if (error)
9646 goto done;
9648 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9649 if (error)
9650 goto done;
9652 if (send_all_branches) {
9653 error = got_ref_list(&all_branches, repo, "refs/heads",
9654 got_ref_cmp_by_name, NULL);
9655 if (error)
9656 goto done;
9657 TAILQ_FOREACH(re, &all_branches, entry) {
9658 const char *branchname = got_ref_get_name(re->ref);
9659 error = got_pathlist_append(&branches,
9660 branchname, NULL);
9661 if (error)
9662 goto done;
9663 nbranches++;
9665 } else if (nbranches == 0) {
9666 for (i = 0; i < remote->nsend_branches; i++) {
9667 error = got_pathlist_append(&branches,
9668 remote->send_branches[i], NULL);
9669 if (error)
9670 goto done;
9674 if (send_all_tags) {
9675 error = got_ref_list(&all_tags, repo, "refs/tags",
9676 got_ref_cmp_by_name, NULL);
9677 if (error)
9678 goto done;
9679 TAILQ_FOREACH(re, &all_tags, entry) {
9680 const char *tagname = got_ref_get_name(re->ref);
9681 error = got_pathlist_append(&tags,
9682 tagname, NULL);
9683 if (error)
9684 goto done;
9689 * To prevent accidents only branches in refs/heads/ can be deleted
9690 * with 'got send -d'.
9691 * Deleting anything else requires local repository access or Git.
9693 TAILQ_FOREACH(pe, &delete_args, entry) {
9694 const char *branchname = pe->path;
9695 char *s;
9696 struct got_pathlist_entry *new;
9697 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9698 s = strdup(branchname);
9699 if (s == NULL) {
9700 error = got_error_from_errno("strdup");
9701 goto done;
9703 } else {
9704 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9705 error = got_error_from_errno("asprintf");
9706 goto done;
9709 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9710 if (error || new == NULL /* duplicate */)
9711 free(s);
9712 if (error)
9713 goto done;
9714 ndelete_branches++;
9717 if (nbranches == 0 && ndelete_branches == 0) {
9718 struct got_reference *head_ref;
9719 if (worktree)
9720 error = got_ref_open(&head_ref, repo,
9721 got_worktree_get_head_ref_name(worktree), 0);
9722 else
9723 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9724 if (error)
9725 goto done;
9726 if (got_ref_is_symbolic(head_ref)) {
9727 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9728 got_ref_close(head_ref);
9729 if (error)
9730 goto done;
9731 } else
9732 ref = head_ref;
9733 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9734 NULL);
9735 if (error)
9736 goto done;
9737 nbranches++;
9740 if (verbosity >= 0) {
9741 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9742 remote->name, proto, host,
9743 port ? ":" : "", port ? port : "",
9744 *server_path == '/' ? "" : "/", server_path);
9747 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9748 server_path, verbosity);
9749 if (error)
9750 goto done;
9752 memset(&spa, 0, sizeof(spa));
9753 spa.last_scaled_packsize[0] = '\0';
9754 spa.last_p_deltify = -1;
9755 spa.last_p_written = -1;
9756 spa.verbosity = verbosity;
9757 spa.delete_branches = &delete_branches;
9758 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9759 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9760 check_cancelled, NULL);
9761 if (spa.printed_something)
9762 putchar('\n');
9763 if (error)
9764 goto done;
9765 if (!spa.sent_something && verbosity >= 0)
9766 printf("Already up-to-date\n");
9767 done:
9768 if (sendpid > 0) {
9769 if (kill(sendpid, SIGTERM) == -1)
9770 error = got_error_from_errno("kill");
9771 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9772 error = got_error_from_errno("waitpid");
9774 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9775 error = got_error_from_errno("close");
9776 if (repo) {
9777 const struct got_error *close_err = got_repo_close(repo);
9778 if (error == NULL)
9779 error = close_err;
9781 if (worktree)
9782 got_worktree_close(worktree);
9783 if (pack_fds) {
9784 const struct got_error *pack_err =
9785 got_repo_pack_fds_close(pack_fds);
9786 if (error == NULL)
9787 error = pack_err;
9789 if (ref)
9790 got_ref_close(ref);
9791 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9792 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9793 got_ref_list_free(&all_branches);
9794 got_ref_list_free(&all_tags);
9795 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9796 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9797 free(cwd);
9798 free(repo_path);
9799 free(proto);
9800 free(host);
9801 free(port);
9802 free(server_path);
9803 free(repo_name);
9804 return error;
9808 * Print and if delete is set delete all ref_prefix references.
9809 * If wanted_ref is not NULL, only print or delete this reference.
9811 static const struct got_error *
9812 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9813 const char *wanted_ref, int delete, struct got_worktree *worktree,
9814 struct got_repository *repo)
9816 const struct got_error *err;
9817 struct got_pathlist_head paths;
9818 struct got_reflist_head refs;
9819 struct got_reflist_entry *re;
9820 struct got_reflist_object_id_map *refs_idmap = NULL;
9821 struct got_commit_object *commit = NULL;
9822 struct got_object_id *id = NULL;
9823 const char *header_prefix;
9824 char *uuidstr = NULL;
9825 int found = 0;
9827 TAILQ_INIT(&refs);
9828 TAILQ_INIT(&paths);
9830 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9831 if (err)
9832 goto done;
9834 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9835 if (err)
9836 goto done;
9838 if (worktree != NULL) {
9839 err = got_worktree_get_uuid(&uuidstr, worktree);
9840 if (err)
9841 goto done;
9844 if (wanted_ref) {
9845 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9846 wanted_ref += 11;
9849 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9850 header_prefix = "backout";
9851 else
9852 header_prefix = "cherrypick";
9854 TAILQ_FOREACH(re, &refs, entry) {
9855 const char *refname, *wt;
9857 refname = got_ref_get_name(re->ref);
9859 err = check_cancelled(NULL);
9860 if (err)
9861 goto done;
9863 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9864 refname += prefix_len + 1; /* skip '-' delimiter */
9865 else
9866 continue;
9868 wt = refname;
9870 if (worktree == NULL || strncmp(refname, uuidstr,
9871 GOT_WORKTREE_UUID_STRLEN) == 0)
9872 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9873 else
9874 continue;
9876 err = got_repo_match_object_id(&id, NULL, refname,
9877 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9878 if (err)
9879 goto done;
9881 err = got_object_open_as_commit(&commit, repo, id);
9882 if (err)
9883 goto done;
9885 if (wanted_ref)
9886 found = strncmp(wanted_ref, refname,
9887 strlen(wanted_ref)) == 0;
9888 if (wanted_ref && !found) {
9889 struct got_reflist_head *ci_refs;
9891 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9892 id);
9894 if (ci_refs) {
9895 char *refs_str = NULL;
9896 char const *r = NULL;
9898 err = build_refs_str(&refs_str, ci_refs, id,
9899 repo, 1);
9900 if (err)
9901 goto done;
9903 r = refs_str;
9904 while (r) {
9905 if (strncmp(r, wanted_ref,
9906 strlen(wanted_ref)) == 0) {
9907 found = 1;
9908 break;
9910 r = strchr(r, ' ');
9911 if (r)
9912 ++r;
9914 free(refs_str);
9918 if (wanted_ref == NULL || found) {
9919 if (delete) {
9920 err = got_ref_delete(re->ref, repo);
9921 if (err)
9922 goto done;
9923 printf("Deleted: ");
9924 err = print_commit_oneline(commit, id, repo,
9925 refs_idmap);
9926 } else {
9928 * Print paths modified by commit to help
9929 * associate commits with worktree changes.
9931 err = get_changed_paths(&paths, commit,
9932 repo, NULL);
9933 if (err)
9934 goto done;
9936 err = print_commit(commit, id, repo, NULL,
9937 &paths, NULL, 0, 0, refs_idmap, NULL,
9938 header_prefix);
9939 got_pathlist_free(&paths,
9940 GOT_PATHLIST_FREE_ALL);
9942 if (worktree == NULL)
9943 printf("work tree: %.*s\n\n",
9944 GOT_WORKTREE_UUID_STRLEN, wt);
9946 if (err || found)
9947 goto done;
9950 got_object_commit_close(commit);
9951 commit = NULL;
9952 free(id);
9953 id = NULL;
9956 if (wanted_ref != NULL && !found)
9957 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9959 done:
9960 free(id);
9961 free(uuidstr);
9962 got_ref_list_free(&refs);
9963 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9964 if (refs_idmap)
9965 got_reflist_object_id_map_free(refs_idmap);
9966 if (commit)
9967 got_object_commit_close(commit);
9968 return err;
9972 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9973 * identified by id for log messages to prepopulate the editor on commit.
9975 static const struct got_error *
9976 logmsg_ref(struct got_object_id *id, const char *prefix,
9977 struct got_worktree *worktree, struct got_repository *repo)
9979 const struct got_error *err = NULL;
9980 char *idstr, *ref = NULL, *refname = NULL;
9981 int histedit_in_progress;
9982 int rebase_in_progress, merge_in_progress;
9985 * Silenty refuse to create merge reference if any histedit, merge,
9986 * or rebase operation is in progress.
9988 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9989 worktree);
9990 if (err)
9991 return err;
9992 if (histedit_in_progress)
9993 return NULL;
9995 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9996 if (err)
9997 return err;
9998 if (rebase_in_progress)
9999 return NULL;
10001 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10002 repo);
10003 if (err)
10004 return err;
10005 if (merge_in_progress)
10006 return NULL;
10008 err = got_object_id_str(&idstr, id);
10009 if (err)
10010 return err;
10012 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10013 if (err)
10014 goto done;
10016 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10017 err = got_error_from_errno("asprintf");
10018 goto done;
10021 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10022 -1, repo);
10023 done:
10024 free(ref);
10025 free(idstr);
10026 free(refname);
10027 return err;
10030 __dead static void
10031 usage_cherrypick(void)
10033 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10034 getprogname());
10035 exit(1);
10038 static const struct got_error *
10039 cmd_cherrypick(int argc, char *argv[])
10041 const struct got_error *error = NULL;
10042 struct got_worktree *worktree = NULL;
10043 struct got_repository *repo = NULL;
10044 char *cwd = NULL, *commit_id_str = NULL;
10045 struct got_object_id *commit_id = NULL;
10046 struct got_commit_object *commit = NULL;
10047 struct got_object_qid *pid;
10048 int ch, list_refs = 0, remove_refs = 0;
10049 struct got_update_progress_arg upa;
10050 int *pack_fds = NULL;
10052 while ((ch = getopt(argc, argv, "lX")) != -1) {
10053 switch (ch) {
10054 case 'l':
10055 list_refs = 1;
10056 break;
10057 case 'X':
10058 remove_refs = 1;
10059 break;
10060 default:
10061 usage_cherrypick();
10062 /* NOTREACHED */
10066 argc -= optind;
10067 argv += optind;
10069 #ifndef PROFILE
10070 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10071 "unveil", NULL) == -1)
10072 err(1, "pledge");
10073 #endif
10074 if (list_refs || remove_refs) {
10075 if (argc != 0 && argc != 1)
10076 usage_cherrypick();
10077 } else if (argc != 1)
10078 usage_cherrypick();
10079 if (list_refs && remove_refs)
10080 option_conflict('l', 'X');
10082 cwd = getcwd(NULL, 0);
10083 if (cwd == NULL) {
10084 error = got_error_from_errno("getcwd");
10085 goto done;
10088 error = got_repo_pack_fds_open(&pack_fds);
10089 if (error != NULL)
10090 goto done;
10092 error = got_worktree_open(&worktree, cwd);
10093 if (error) {
10094 if (list_refs || remove_refs) {
10095 if (error->code != GOT_ERR_NOT_WORKTREE)
10096 goto done;
10097 } else {
10098 if (error->code == GOT_ERR_NOT_WORKTREE)
10099 error = wrap_not_worktree_error(error,
10100 "cherrypick", cwd);
10101 goto done;
10105 error = got_repo_open(&repo,
10106 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10107 NULL, pack_fds);
10108 if (error != NULL)
10109 goto done;
10111 error = apply_unveil(got_repo_get_path(repo), 0,
10112 worktree ? got_worktree_get_root_path(worktree) : NULL);
10113 if (error)
10114 goto done;
10116 if (list_refs || remove_refs) {
10117 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10118 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10119 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10120 goto done;
10123 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10124 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10125 if (error)
10126 goto done;
10127 error = got_object_id_str(&commit_id_str, commit_id);
10128 if (error)
10129 goto done;
10131 error = got_object_open_as_commit(&commit, repo, commit_id);
10132 if (error)
10133 goto done;
10134 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10135 memset(&upa, 0, sizeof(upa));
10136 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10137 commit_id, repo, update_progress, &upa, check_cancelled,
10138 NULL);
10139 if (error != NULL)
10140 goto done;
10142 if (upa.did_something) {
10143 error = logmsg_ref(commit_id,
10144 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10145 if (error)
10146 goto done;
10147 printf("Merged commit %s\n", commit_id_str);
10149 print_merge_progress_stats(&upa);
10150 done:
10151 free(cwd);
10152 if (commit)
10153 got_object_commit_close(commit);
10154 free(commit_id_str);
10155 if (worktree)
10156 got_worktree_close(worktree);
10157 if (repo) {
10158 const struct got_error *close_err = got_repo_close(repo);
10159 if (error == NULL)
10160 error = close_err;
10162 if (pack_fds) {
10163 const struct got_error *pack_err =
10164 got_repo_pack_fds_close(pack_fds);
10165 if (error == NULL)
10166 error = pack_err;
10169 return error;
10172 __dead static void
10173 usage_backout(void)
10175 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10176 exit(1);
10179 static const struct got_error *
10180 cmd_backout(int argc, char *argv[])
10182 const struct got_error *error = NULL;
10183 struct got_worktree *worktree = NULL;
10184 struct got_repository *repo = NULL;
10185 char *cwd = NULL, *commit_id_str = NULL;
10186 struct got_object_id *commit_id = NULL;
10187 struct got_commit_object *commit = NULL;
10188 struct got_object_qid *pid;
10189 int ch, list_refs = 0, remove_refs = 0;
10190 struct got_update_progress_arg upa;
10191 int *pack_fds = NULL;
10193 while ((ch = getopt(argc, argv, "lX")) != -1) {
10194 switch (ch) {
10195 case 'l':
10196 list_refs = 1;
10197 break;
10198 case 'X':
10199 remove_refs = 1;
10200 break;
10201 default:
10202 usage_backout();
10203 /* NOTREACHED */
10207 argc -= optind;
10208 argv += optind;
10210 #ifndef PROFILE
10211 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10212 "unveil", NULL) == -1)
10213 err(1, "pledge");
10214 #endif
10215 if (list_refs || remove_refs) {
10216 if (argc != 0 && argc != 1)
10217 usage_backout();
10218 } else if (argc != 1)
10219 usage_backout();
10220 if (list_refs && remove_refs)
10221 option_conflict('l', 'X');
10223 cwd = getcwd(NULL, 0);
10224 if (cwd == NULL) {
10225 error = got_error_from_errno("getcwd");
10226 goto done;
10229 error = got_repo_pack_fds_open(&pack_fds);
10230 if (error != NULL)
10231 goto done;
10233 error = got_worktree_open(&worktree, cwd);
10234 if (error) {
10235 if (list_refs || remove_refs) {
10236 if (error->code != GOT_ERR_NOT_WORKTREE)
10237 goto done;
10238 } else {
10239 if (error->code == GOT_ERR_NOT_WORKTREE)
10240 error = wrap_not_worktree_error(error,
10241 "backout", cwd);
10242 goto done;
10246 error = got_repo_open(&repo,
10247 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10248 NULL, pack_fds);
10249 if (error != NULL)
10250 goto done;
10252 error = apply_unveil(got_repo_get_path(repo), 0,
10253 worktree ? got_worktree_get_root_path(worktree) : NULL);
10254 if (error)
10255 goto done;
10257 if (list_refs || remove_refs) {
10258 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10259 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10260 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10261 goto done;
10264 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10265 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10266 if (error)
10267 goto done;
10268 error = got_object_id_str(&commit_id_str, commit_id);
10269 if (error)
10270 goto done;
10272 error = got_object_open_as_commit(&commit, repo, commit_id);
10273 if (error)
10274 goto done;
10275 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10276 if (pid == NULL) {
10277 error = got_error(GOT_ERR_ROOT_COMMIT);
10278 goto done;
10281 memset(&upa, 0, sizeof(upa));
10282 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10283 repo, update_progress, &upa, check_cancelled, NULL);
10284 if (error != NULL)
10285 goto done;
10287 if (upa.did_something) {
10288 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10289 worktree, repo);
10290 if (error)
10291 goto done;
10292 printf("Backed out commit %s\n", commit_id_str);
10294 print_merge_progress_stats(&upa);
10295 done:
10296 free(cwd);
10297 if (commit)
10298 got_object_commit_close(commit);
10299 free(commit_id_str);
10300 if (worktree)
10301 got_worktree_close(worktree);
10302 if (repo) {
10303 const struct got_error *close_err = got_repo_close(repo);
10304 if (error == NULL)
10305 error = close_err;
10307 if (pack_fds) {
10308 const struct got_error *pack_err =
10309 got_repo_pack_fds_close(pack_fds);
10310 if (error == NULL)
10311 error = pack_err;
10313 return error;
10316 __dead static void
10317 usage_rebase(void)
10319 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10320 exit(1);
10323 static void
10324 trim_logmsg(char *logmsg, int limit)
10326 char *nl;
10327 size_t len;
10329 len = strlen(logmsg);
10330 if (len > limit)
10331 len = limit;
10332 logmsg[len] = '\0';
10333 nl = strchr(logmsg, '\n');
10334 if (nl)
10335 *nl = '\0';
10338 static const struct got_error *
10339 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10341 const struct got_error *err;
10342 char *logmsg0 = NULL;
10343 const char *s;
10345 err = got_object_commit_get_logmsg(&logmsg0, commit);
10346 if (err)
10347 return err;
10349 s = logmsg0;
10350 while (isspace((unsigned char)s[0]))
10351 s++;
10353 *logmsg = strdup(s);
10354 if (*logmsg == NULL) {
10355 err = got_error_from_errno("strdup");
10356 goto done;
10359 trim_logmsg(*logmsg, limit);
10360 done:
10361 free(logmsg0);
10362 return err;
10365 static const struct got_error *
10366 show_rebase_merge_conflict(struct got_object_id *id,
10367 struct got_repository *repo)
10369 const struct got_error *err;
10370 struct got_commit_object *commit = NULL;
10371 char *id_str = NULL, *logmsg = NULL;
10373 err = got_object_open_as_commit(&commit, repo, id);
10374 if (err)
10375 return err;
10377 err = got_object_id_str(&id_str, id);
10378 if (err)
10379 goto done;
10381 id_str[12] = '\0';
10383 err = get_short_logmsg(&logmsg, 42, commit);
10384 if (err)
10385 goto done;
10387 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10388 done:
10389 free(id_str);
10390 got_object_commit_close(commit);
10391 free(logmsg);
10392 return err;
10395 static const struct got_error *
10396 show_rebase_progress(struct got_commit_object *commit,
10397 struct got_object_id *old_id, struct got_object_id *new_id)
10399 const struct got_error *err;
10400 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10402 err = got_object_id_str(&old_id_str, old_id);
10403 if (err)
10404 goto done;
10406 if (new_id) {
10407 err = got_object_id_str(&new_id_str, new_id);
10408 if (err)
10409 goto done;
10412 old_id_str[12] = '\0';
10413 if (new_id_str)
10414 new_id_str[12] = '\0';
10416 err = get_short_logmsg(&logmsg, 42, commit);
10417 if (err)
10418 goto done;
10420 printf("%s -> %s: %s\n", old_id_str,
10421 new_id_str ? new_id_str : "no-op change", logmsg);
10422 done:
10423 free(old_id_str);
10424 free(new_id_str);
10425 free(logmsg);
10426 return err;
10429 static const struct got_error *
10430 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10431 struct got_reference *branch, struct got_reference *tmp_branch,
10432 struct got_repository *repo, int create_backup)
10434 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10435 return got_worktree_rebase_complete(worktree, fileindex,
10436 tmp_branch, branch, repo, create_backup);
10439 static const struct got_error *
10440 rebase_commit(struct got_pathlist_head *merged_paths,
10441 struct got_worktree *worktree, struct got_fileindex *fileindex,
10442 struct got_reference *tmp_branch, const char *committer,
10443 struct got_object_id *commit_id, struct got_repository *repo)
10445 const struct got_error *error;
10446 struct got_commit_object *commit;
10447 struct got_object_id *new_commit_id;
10449 error = got_object_open_as_commit(&commit, repo, commit_id);
10450 if (error)
10451 return error;
10453 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10454 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10455 repo);
10456 if (error) {
10457 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10458 goto done;
10459 error = show_rebase_progress(commit, commit_id, NULL);
10460 } else {
10461 error = show_rebase_progress(commit, commit_id, new_commit_id);
10462 free(new_commit_id);
10464 done:
10465 got_object_commit_close(commit);
10466 return error;
10469 struct check_path_prefix_arg {
10470 const char *path_prefix;
10471 size_t len;
10472 int errcode;
10475 static const struct got_error *
10476 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10477 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10478 struct got_object_id *id1, struct got_object_id *id2,
10479 const char *path1, const char *path2,
10480 mode_t mode1, mode_t mode2, struct got_repository *repo)
10482 struct check_path_prefix_arg *a = arg;
10484 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10485 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10486 return got_error(a->errcode);
10488 return NULL;
10491 static const struct got_error *
10492 check_path_prefix(struct got_object_id *parent_id,
10493 struct got_object_id *commit_id, const char *path_prefix,
10494 int errcode, struct got_repository *repo)
10496 const struct got_error *err;
10497 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10498 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10499 struct check_path_prefix_arg cpp_arg;
10501 if (got_path_is_root_dir(path_prefix))
10502 return NULL;
10504 err = got_object_open_as_commit(&commit, repo, commit_id);
10505 if (err)
10506 goto done;
10508 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10509 if (err)
10510 goto done;
10512 err = got_object_open_as_tree(&tree1, repo,
10513 got_object_commit_get_tree_id(parent_commit));
10514 if (err)
10515 goto done;
10517 err = got_object_open_as_tree(&tree2, repo,
10518 got_object_commit_get_tree_id(commit));
10519 if (err)
10520 goto done;
10522 cpp_arg.path_prefix = path_prefix;
10523 while (cpp_arg.path_prefix[0] == '/')
10524 cpp_arg.path_prefix++;
10525 cpp_arg.len = strlen(cpp_arg.path_prefix);
10526 cpp_arg.errcode = errcode;
10527 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10528 check_path_prefix_in_diff, &cpp_arg, 0);
10529 done:
10530 if (tree1)
10531 got_object_tree_close(tree1);
10532 if (tree2)
10533 got_object_tree_close(tree2);
10534 if (commit)
10535 got_object_commit_close(commit);
10536 if (parent_commit)
10537 got_object_commit_close(parent_commit);
10538 return err;
10541 static const struct got_error *
10542 collect_commits(struct got_object_id_queue *commits,
10543 struct got_object_id *initial_commit_id,
10544 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10545 const char *path_prefix, int path_prefix_errcode,
10546 struct got_repository *repo)
10548 const struct got_error *err = NULL;
10549 struct got_commit_graph *graph = NULL;
10550 struct got_object_id parent_id, commit_id;
10551 struct got_object_qid *qid;
10553 err = got_commit_graph_open(&graph, "/", 1);
10554 if (err)
10555 return err;
10557 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10558 check_cancelled, NULL);
10559 if (err)
10560 goto done;
10562 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10563 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10564 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10565 check_cancelled, NULL);
10566 if (err) {
10567 if (err->code == GOT_ERR_ITER_COMPLETED) {
10568 err = got_error_msg(GOT_ERR_ANCESTRY,
10569 "ran out of commits to rebase before "
10570 "youngest common ancestor commit has "
10571 "been reached?!?");
10573 goto done;
10574 } else {
10575 err = check_path_prefix(&parent_id, &commit_id,
10576 path_prefix, path_prefix_errcode, repo);
10577 if (err)
10578 goto done;
10580 err = got_object_qid_alloc(&qid, &commit_id);
10581 if (err)
10582 goto done;
10583 STAILQ_INSERT_HEAD(commits, qid, entry);
10585 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10588 done:
10589 got_commit_graph_close(graph);
10590 return err;
10593 static const struct got_error *
10594 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10596 const struct got_error *err = NULL;
10597 time_t committer_time;
10598 struct tm tm;
10599 char datebuf[11]; /* YYYY-MM-DD + NUL */
10600 char *author0 = NULL, *author, *smallerthan;
10601 char *logmsg0 = NULL, *logmsg, *newline;
10603 committer_time = got_object_commit_get_committer_time(commit);
10604 if (gmtime_r(&committer_time, &tm) == NULL)
10605 return got_error_from_errno("gmtime_r");
10606 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10607 return got_error(GOT_ERR_NO_SPACE);
10609 author0 = strdup(got_object_commit_get_author(commit));
10610 if (author0 == NULL)
10611 return got_error_from_errno("strdup");
10612 author = author0;
10613 smallerthan = strchr(author, '<');
10614 if (smallerthan && smallerthan[1] != '\0')
10615 author = smallerthan + 1;
10616 author[strcspn(author, "@>")] = '\0';
10618 err = got_object_commit_get_logmsg(&logmsg0, commit);
10619 if (err)
10620 goto done;
10621 logmsg = logmsg0;
10622 while (*logmsg == '\n')
10623 logmsg++;
10624 newline = strchr(logmsg, '\n');
10625 if (newline)
10626 *newline = '\0';
10628 if (asprintf(brief_str, "%s %s %s",
10629 datebuf, author, logmsg) == -1)
10630 err = got_error_from_errno("asprintf");
10631 done:
10632 free(author0);
10633 free(logmsg0);
10634 return err;
10637 static const struct got_error *
10638 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10639 struct got_repository *repo)
10641 const struct got_error *err;
10642 char *id_str;
10644 err = got_object_id_str(&id_str, id);
10645 if (err)
10646 return err;
10648 err = got_ref_delete(ref, repo);
10649 if (err)
10650 goto done;
10652 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10653 done:
10654 free(id_str);
10655 return err;
10658 static const struct got_error *
10659 print_backup_ref(const char *branch_name, const char *new_id_str,
10660 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10661 struct got_reflist_object_id_map *refs_idmap,
10662 struct got_repository *repo)
10664 const struct got_error *err = NULL;
10665 struct got_reflist_head *refs;
10666 char *refs_str = NULL;
10667 struct got_object_id *new_commit_id = NULL;
10668 struct got_commit_object *new_commit = NULL;
10669 char *new_commit_brief_str = NULL;
10670 struct got_object_id *yca_id = NULL;
10671 struct got_commit_object *yca_commit = NULL;
10672 char *yca_id_str = NULL, *yca_brief_str = NULL;
10673 char *custom_refs_str;
10675 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10676 return got_error_from_errno("asprintf");
10678 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10679 0, 0, refs_idmap, custom_refs_str, NULL);
10680 if (err)
10681 goto done;
10683 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10684 if (err)
10685 goto done;
10687 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10688 if (refs) {
10689 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10690 if (err)
10691 goto done;
10694 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10695 if (err)
10696 goto done;
10698 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10699 if (err)
10700 goto done;
10702 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10703 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10704 if (err)
10705 goto done;
10707 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10708 refs_str ? " (" : "", refs_str ? refs_str : "",
10709 refs_str ? ")" : "", new_commit_brief_str);
10710 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10711 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10712 free(refs_str);
10713 refs_str = NULL;
10715 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10716 if (err)
10717 goto done;
10719 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10720 if (err)
10721 goto done;
10723 err = got_object_id_str(&yca_id_str, yca_id);
10724 if (err)
10725 goto done;
10727 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10728 if (refs) {
10729 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10730 if (err)
10731 goto done;
10733 printf("history forked at %s%s%s%s\n %s\n",
10734 yca_id_str,
10735 refs_str ? " (" : "", refs_str ? refs_str : "",
10736 refs_str ? ")" : "", yca_brief_str);
10738 done:
10739 free(custom_refs_str);
10740 free(new_commit_id);
10741 free(refs_str);
10742 free(yca_id);
10743 free(yca_id_str);
10744 free(yca_brief_str);
10745 if (new_commit)
10746 got_object_commit_close(new_commit);
10747 if (yca_commit)
10748 got_object_commit_close(yca_commit);
10750 return err;
10753 static const struct got_error *
10754 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10755 struct got_repository *repo)
10757 const struct got_error *err;
10758 struct got_reflist_head refs;
10759 struct got_reflist_entry *re;
10760 char *uuidstr = NULL;
10761 static char msg[160];
10763 TAILQ_INIT(&refs);
10765 err = got_worktree_get_uuid(&uuidstr, worktree);
10766 if (err)
10767 goto done;
10769 err = got_ref_list(&refs, repo, "refs/got/worktree",
10770 got_ref_cmp_by_name, repo);
10771 if (err)
10772 goto done;
10774 TAILQ_FOREACH(re, &refs, entry) {
10775 const char *cmd, *refname, *type;
10777 refname = got_ref_get_name(re->ref);
10779 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10780 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10781 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10782 cmd = "cherrypick";
10783 type = "cherrypicked";
10784 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10785 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10786 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10787 cmd = "backout";
10788 type = "backed-out";
10789 } else
10790 continue;
10792 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10793 continue;
10795 snprintf(msg, sizeof(msg),
10796 "work tree has references created by %s commits which "
10797 "must be removed with 'got %s -X' before running the %s "
10798 "command", type, cmd, caller);
10799 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10800 goto done;
10803 done:
10804 free(uuidstr);
10805 got_ref_list_free(&refs);
10806 return err;
10809 static const struct got_error *
10810 process_backup_refs(const char *backup_ref_prefix,
10811 const char *wanted_branch_name,
10812 int delete, struct got_repository *repo)
10814 const struct got_error *err;
10815 struct got_reflist_head refs, backup_refs;
10816 struct got_reflist_entry *re;
10817 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10818 struct got_object_id *old_commit_id = NULL;
10819 char *branch_name = NULL;
10820 struct got_commit_object *old_commit = NULL;
10821 struct got_reflist_object_id_map *refs_idmap = NULL;
10822 int wanted_branch_found = 0;
10824 TAILQ_INIT(&refs);
10825 TAILQ_INIT(&backup_refs);
10827 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10828 if (err)
10829 return err;
10831 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10832 if (err)
10833 goto done;
10835 if (wanted_branch_name) {
10836 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10837 wanted_branch_name += 11;
10840 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10841 got_ref_cmp_by_commit_timestamp_descending, repo);
10842 if (err)
10843 goto done;
10845 TAILQ_FOREACH(re, &backup_refs, entry) {
10846 const char *refname = got_ref_get_name(re->ref);
10847 char *slash;
10849 err = check_cancelled(NULL);
10850 if (err)
10851 break;
10853 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10854 if (err)
10855 break;
10857 err = got_object_open_as_commit(&old_commit, repo,
10858 old_commit_id);
10859 if (err)
10860 break;
10862 if (strncmp(backup_ref_prefix, refname,
10863 backup_ref_prefix_len) == 0)
10864 refname += backup_ref_prefix_len;
10866 while (refname[0] == '/')
10867 refname++;
10869 branch_name = strdup(refname);
10870 if (branch_name == NULL) {
10871 err = got_error_from_errno("strdup");
10872 break;
10874 slash = strrchr(branch_name, '/');
10875 if (slash) {
10876 *slash = '\0';
10877 refname += strlen(branch_name) + 1;
10880 if (wanted_branch_name == NULL ||
10881 strcmp(wanted_branch_name, branch_name) == 0) {
10882 wanted_branch_found = 1;
10883 if (delete) {
10884 err = delete_backup_ref(re->ref,
10885 old_commit_id, repo);
10886 } else {
10887 err = print_backup_ref(branch_name, refname,
10888 old_commit_id, old_commit, refs_idmap,
10889 repo);
10891 if (err)
10892 break;
10895 free(old_commit_id);
10896 old_commit_id = NULL;
10897 free(branch_name);
10898 branch_name = NULL;
10899 got_object_commit_close(old_commit);
10900 old_commit = NULL;
10903 if (wanted_branch_name && !wanted_branch_found) {
10904 err = got_error_fmt(GOT_ERR_NOT_REF,
10905 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10907 done:
10908 if (refs_idmap)
10909 got_reflist_object_id_map_free(refs_idmap);
10910 got_ref_list_free(&refs);
10911 got_ref_list_free(&backup_refs);
10912 free(old_commit_id);
10913 free(branch_name);
10914 if (old_commit)
10915 got_object_commit_close(old_commit);
10916 return err;
10919 static const struct got_error *
10920 abort_progress(void *arg, unsigned char status, const char *path)
10923 * Unversioned files should not clutter progress output when
10924 * an operation is aborted.
10926 if (status == GOT_STATUS_UNVERSIONED)
10927 return NULL;
10929 return update_progress(arg, status, path);
10932 static const struct got_error *
10933 cmd_rebase(int argc, char *argv[])
10935 const struct got_error *error = NULL;
10936 struct got_worktree *worktree = NULL;
10937 struct got_repository *repo = NULL;
10938 struct got_fileindex *fileindex = NULL;
10939 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10940 struct got_reference *branch = NULL;
10941 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10942 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10943 struct got_object_id *resume_commit_id = NULL;
10944 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10945 struct got_object_id *head_commit_id = NULL;
10946 struct got_reference *head_ref = NULL;
10947 struct got_commit_object *commit = NULL;
10948 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10949 int histedit_in_progress = 0, merge_in_progress = 0;
10950 int create_backup = 1, list_backups = 0, delete_backups = 0;
10951 struct got_object_id_queue commits;
10952 struct got_pathlist_head merged_paths;
10953 const struct got_object_id_queue *parent_ids;
10954 struct got_object_qid *qid, *pid;
10955 struct got_update_progress_arg upa;
10956 int *pack_fds = NULL;
10958 STAILQ_INIT(&commits);
10959 TAILQ_INIT(&merged_paths);
10960 memset(&upa, 0, sizeof(upa));
10962 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10963 switch (ch) {
10964 case 'a':
10965 abort_rebase = 1;
10966 break;
10967 case 'c':
10968 continue_rebase = 1;
10969 break;
10970 case 'l':
10971 list_backups = 1;
10972 break;
10973 case 'X':
10974 delete_backups = 1;
10975 break;
10976 default:
10977 usage_rebase();
10978 /* NOTREACHED */
10982 argc -= optind;
10983 argv += optind;
10985 #ifndef PROFILE
10986 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10987 "unveil", NULL) == -1)
10988 err(1, "pledge");
10989 #endif
10990 if (list_backups) {
10991 if (abort_rebase)
10992 option_conflict('l', 'a');
10993 if (continue_rebase)
10994 option_conflict('l', 'c');
10995 if (delete_backups)
10996 option_conflict('l', 'X');
10997 if (argc != 0 && argc != 1)
10998 usage_rebase();
10999 } else if (delete_backups) {
11000 if (abort_rebase)
11001 option_conflict('X', 'a');
11002 if (continue_rebase)
11003 option_conflict('X', 'c');
11004 if (list_backups)
11005 option_conflict('l', 'X');
11006 if (argc != 0 && argc != 1)
11007 usage_rebase();
11008 } else {
11009 if (abort_rebase && continue_rebase)
11010 usage_rebase();
11011 else if (abort_rebase || continue_rebase) {
11012 if (argc != 0)
11013 usage_rebase();
11014 } else if (argc != 1)
11015 usage_rebase();
11018 cwd = getcwd(NULL, 0);
11019 if (cwd == NULL) {
11020 error = got_error_from_errno("getcwd");
11021 goto done;
11024 error = got_repo_pack_fds_open(&pack_fds);
11025 if (error != NULL)
11026 goto done;
11028 error = got_worktree_open(&worktree, cwd);
11029 if (error) {
11030 if (list_backups || delete_backups) {
11031 if (error->code != GOT_ERR_NOT_WORKTREE)
11032 goto done;
11033 } else {
11034 if (error->code == GOT_ERR_NOT_WORKTREE)
11035 error = wrap_not_worktree_error(error,
11036 "rebase", cwd);
11037 goto done;
11041 error = get_gitconfig_path(&gitconfig_path);
11042 if (error)
11043 goto done;
11044 error = got_repo_open(&repo,
11045 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11046 gitconfig_path, pack_fds);
11047 if (error != NULL)
11048 goto done;
11050 if (worktree != NULL && !list_backups && !delete_backups) {
11051 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11052 if (error)
11053 goto done;
11056 error = get_author(&committer, repo, worktree);
11057 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11058 goto done;
11060 error = apply_unveil(got_repo_get_path(repo), 0,
11061 worktree ? got_worktree_get_root_path(worktree) : NULL);
11062 if (error)
11063 goto done;
11065 if (list_backups || delete_backups) {
11066 error = process_backup_refs(
11067 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11068 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11069 goto done; /* nothing else to do */
11072 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11073 worktree);
11074 if (error)
11075 goto done;
11076 if (histedit_in_progress) {
11077 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11078 goto done;
11081 error = got_worktree_merge_in_progress(&merge_in_progress,
11082 worktree, repo);
11083 if (error)
11084 goto done;
11085 if (merge_in_progress) {
11086 error = got_error(GOT_ERR_MERGE_BUSY);
11087 goto done;
11090 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11091 if (error)
11092 goto done;
11094 if (abort_rebase) {
11095 if (!rebase_in_progress) {
11096 error = got_error(GOT_ERR_NOT_REBASING);
11097 goto done;
11099 error = got_worktree_rebase_continue(&resume_commit_id,
11100 &new_base_branch, &tmp_branch, &branch, &fileindex,
11101 worktree, repo);
11102 if (error)
11103 goto done;
11104 printf("Switching work tree to %s\n",
11105 got_ref_get_symref_target(new_base_branch));
11106 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11107 new_base_branch, abort_progress, &upa);
11108 if (error)
11109 goto done;
11110 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11111 print_merge_progress_stats(&upa);
11112 goto done; /* nothing else to do */
11115 if (continue_rebase) {
11116 if (!rebase_in_progress) {
11117 error = got_error(GOT_ERR_NOT_REBASING);
11118 goto done;
11120 error = got_worktree_rebase_continue(&resume_commit_id,
11121 &new_base_branch, &tmp_branch, &branch, &fileindex,
11122 worktree, repo);
11123 if (error)
11124 goto done;
11126 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11127 committer, resume_commit_id, repo);
11128 if (error)
11129 goto done;
11131 yca_id = got_object_id_dup(resume_commit_id);
11132 if (yca_id == NULL) {
11133 error = got_error_from_errno("got_object_id_dup");
11134 goto done;
11136 } else {
11137 error = got_ref_open(&branch, repo, argv[0], 0);
11138 if (error != NULL)
11139 goto done;
11140 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11141 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11142 "will not rebase a branch which lives outside "
11143 "the \"refs/heads/\" reference namespace");
11144 goto done;
11148 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11149 if (error)
11150 goto done;
11152 if (!continue_rebase) {
11153 struct got_object_id *base_commit_id;
11155 error = got_ref_open(&head_ref, repo,
11156 got_worktree_get_head_ref_name(worktree), 0);
11157 if (error)
11158 goto done;
11159 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11160 if (error)
11161 goto done;
11162 base_commit_id = got_worktree_get_base_commit_id(worktree);
11163 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11164 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11165 goto done;
11168 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11169 base_commit_id, branch_head_commit_id, 1, repo,
11170 check_cancelled, NULL);
11171 if (error) {
11172 if (error->code == GOT_ERR_ANCESTRY) {
11173 error = got_error_msg(GOT_ERR_ANCESTRY,
11174 "specified branch shares no common "
11175 "ancestry with work tree's branch");
11177 goto done;
11180 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11181 if (error) {
11182 if (error->code != GOT_ERR_ANCESTRY)
11183 goto done;
11184 error = NULL;
11185 } else {
11186 struct got_pathlist_head paths;
11187 printf("%s is already based on %s\n",
11188 got_ref_get_name(branch),
11189 got_worktree_get_head_ref_name(worktree));
11190 error = switch_head_ref(branch, branch_head_commit_id,
11191 worktree, repo);
11192 if (error)
11193 goto done;
11194 error = got_worktree_set_base_commit_id(worktree, repo,
11195 branch_head_commit_id);
11196 if (error)
11197 goto done;
11198 TAILQ_INIT(&paths);
11199 error = got_pathlist_append(&paths, "", NULL);
11200 if (error)
11201 goto done;
11202 error = got_worktree_checkout_files(worktree,
11203 &paths, repo, update_progress, &upa,
11204 check_cancelled, NULL);
11205 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11206 if (error)
11207 goto done;
11208 if (upa.did_something) {
11209 char *id_str;
11210 error = got_object_id_str(&id_str,
11211 branch_head_commit_id);
11212 if (error)
11213 goto done;
11214 printf("Updated to %s: %s\n",
11215 got_worktree_get_head_ref_name(worktree),
11216 id_str);
11217 free(id_str);
11218 } else
11219 printf("Already up-to-date\n");
11220 print_update_progress_stats(&upa);
11221 goto done;
11225 commit_id = branch_head_commit_id;
11226 error = got_object_open_as_commit(&commit, repo, commit_id);
11227 if (error)
11228 goto done;
11230 parent_ids = got_object_commit_get_parent_ids(commit);
11231 pid = STAILQ_FIRST(parent_ids);
11232 if (pid) {
11233 error = collect_commits(&commits, commit_id, &pid->id,
11234 yca_id, got_worktree_get_path_prefix(worktree),
11235 GOT_ERR_REBASE_PATH, repo);
11236 if (error)
11237 goto done;
11240 got_object_commit_close(commit);
11241 commit = NULL;
11243 if (!continue_rebase) {
11244 error = got_worktree_rebase_prepare(&new_base_branch,
11245 &tmp_branch, &fileindex, worktree, branch, repo);
11246 if (error)
11247 goto done;
11250 if (STAILQ_EMPTY(&commits)) {
11251 if (continue_rebase) {
11252 error = rebase_complete(worktree, fileindex,
11253 branch, tmp_branch, repo, create_backup);
11254 goto done;
11255 } else {
11256 /* Fast-forward the reference of the branch. */
11257 struct got_object_id *new_head_commit_id;
11258 char *id_str;
11259 error = got_ref_resolve(&new_head_commit_id, repo,
11260 new_base_branch);
11261 if (error)
11262 goto done;
11263 error = got_object_id_str(&id_str, new_head_commit_id);
11264 if (error)
11265 goto done;
11266 printf("Forwarding %s to commit %s\n",
11267 got_ref_get_name(branch), id_str);
11268 free(id_str);
11269 error = got_ref_change_ref(branch,
11270 new_head_commit_id);
11271 if (error)
11272 goto done;
11273 /* No backup needed since objects did not change. */
11274 create_backup = 0;
11278 pid = NULL;
11279 STAILQ_FOREACH(qid, &commits, entry) {
11281 commit_id = &qid->id;
11282 parent_id = pid ? &pid->id : yca_id;
11283 pid = qid;
11285 memset(&upa, 0, sizeof(upa));
11286 error = got_worktree_rebase_merge_files(&merged_paths,
11287 worktree, fileindex, parent_id, commit_id, repo,
11288 update_progress, &upa, check_cancelled, NULL);
11289 if (error)
11290 goto done;
11292 print_merge_progress_stats(&upa);
11293 if (upa.conflicts > 0 || upa.missing > 0 ||
11294 upa.not_deleted > 0 || upa.unversioned > 0) {
11295 if (upa.conflicts > 0) {
11296 error = show_rebase_merge_conflict(&qid->id,
11297 repo);
11298 if (error)
11299 goto done;
11301 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11302 break;
11305 error = rebase_commit(&merged_paths, worktree, fileindex,
11306 tmp_branch, committer, commit_id, repo);
11307 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11308 if (error)
11309 goto done;
11312 if (upa.conflicts > 0 || upa.missing > 0 ||
11313 upa.not_deleted > 0 || upa.unversioned > 0) {
11314 error = got_worktree_rebase_postpone(worktree, fileindex);
11315 if (error)
11316 goto done;
11317 if (upa.conflicts > 0 && upa.missing == 0 &&
11318 upa.not_deleted == 0 && upa.unversioned == 0) {
11319 error = got_error_msg(GOT_ERR_CONFLICTS,
11320 "conflicts must be resolved before rebasing "
11321 "can continue");
11322 } else if (upa.conflicts > 0) {
11323 error = got_error_msg(GOT_ERR_CONFLICTS,
11324 "conflicts must be resolved before rebasing "
11325 "can continue; changes destined for some "
11326 "files were not yet merged and should be "
11327 "merged manually if required before the "
11328 "rebase operation is continued");
11329 } else {
11330 error = got_error_msg(GOT_ERR_CONFLICTS,
11331 "changes destined for some files were not "
11332 "yet merged and should be merged manually "
11333 "if required before the rebase operation "
11334 "is continued");
11336 } else
11337 error = rebase_complete(worktree, fileindex, branch,
11338 tmp_branch, repo, create_backup);
11339 done:
11340 free(cwd);
11341 free(committer);
11342 free(gitconfig_path);
11343 got_object_id_queue_free(&commits);
11344 free(branch_head_commit_id);
11345 free(resume_commit_id);
11346 free(head_commit_id);
11347 free(yca_id);
11348 if (commit)
11349 got_object_commit_close(commit);
11350 if (branch)
11351 got_ref_close(branch);
11352 if (new_base_branch)
11353 got_ref_close(new_base_branch);
11354 if (tmp_branch)
11355 got_ref_close(tmp_branch);
11356 if (head_ref)
11357 got_ref_close(head_ref);
11358 if (worktree)
11359 got_worktree_close(worktree);
11360 if (repo) {
11361 const struct got_error *close_err = got_repo_close(repo);
11362 if (error == NULL)
11363 error = close_err;
11365 if (pack_fds) {
11366 const struct got_error *pack_err =
11367 got_repo_pack_fds_close(pack_fds);
11368 if (error == NULL)
11369 error = pack_err;
11371 return error;
11374 __dead static void
11375 usage_histedit(void)
11377 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11378 "[branch]\n", getprogname());
11379 exit(1);
11382 #define GOT_HISTEDIT_PICK 'p'
11383 #define GOT_HISTEDIT_EDIT 'e'
11384 #define GOT_HISTEDIT_FOLD 'f'
11385 #define GOT_HISTEDIT_DROP 'd'
11386 #define GOT_HISTEDIT_MESG 'm'
11388 static const struct got_histedit_cmd {
11389 unsigned char code;
11390 const char *name;
11391 const char *desc;
11392 } got_histedit_cmds[] = {
11393 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11394 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11395 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11396 "be used" },
11397 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11398 { GOT_HISTEDIT_MESG, "mesg",
11399 "single-line log message for commit above (open editor if empty)" },
11402 struct got_histedit_list_entry {
11403 TAILQ_ENTRY(got_histedit_list_entry) entry;
11404 struct got_object_id *commit_id;
11405 const struct got_histedit_cmd *cmd;
11406 char *logmsg;
11408 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11410 static const struct got_error *
11411 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11412 FILE *f, struct got_repository *repo)
11414 const struct got_error *err = NULL;
11415 char *logmsg = NULL, *id_str = NULL;
11416 struct got_commit_object *commit = NULL;
11417 int n;
11419 err = got_object_open_as_commit(&commit, repo, commit_id);
11420 if (err)
11421 goto done;
11423 err = get_short_logmsg(&logmsg, 34, commit);
11424 if (err)
11425 goto done;
11427 err = got_object_id_str(&id_str, commit_id);
11428 if (err)
11429 goto done;
11431 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11432 if (n < 0)
11433 err = got_ferror(f, GOT_ERR_IO);
11434 done:
11435 if (commit)
11436 got_object_commit_close(commit);
11437 free(id_str);
11438 free(logmsg);
11439 return err;
11442 static const struct got_error *
11443 histedit_write_commit_list(struct got_object_id_queue *commits,
11444 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11445 int edit_only, struct got_repository *repo)
11447 const struct got_error *err = NULL;
11448 struct got_object_qid *qid;
11449 const char *histedit_cmd = NULL;
11451 if (STAILQ_EMPTY(commits))
11452 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11454 STAILQ_FOREACH(qid, commits, entry) {
11455 histedit_cmd = got_histedit_cmds[0].name;
11456 if (drop_only)
11457 histedit_cmd = "drop";
11458 else if (edit_only)
11459 histedit_cmd = "edit";
11460 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11461 histedit_cmd = "fold";
11462 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11463 if (err)
11464 break;
11465 if (edit_logmsg_only) {
11466 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11467 if (n < 0) {
11468 err = got_ferror(f, GOT_ERR_IO);
11469 break;
11474 return err;
11477 static const struct got_error *
11478 write_cmd_list(FILE *f, const char *branch_name,
11479 struct got_object_id_queue *commits)
11481 const struct got_error *err = NULL;
11482 size_t i;
11483 int n;
11484 char *id_str;
11485 struct got_object_qid *qid;
11487 qid = STAILQ_FIRST(commits);
11488 err = got_object_id_str(&id_str, &qid->id);
11489 if (err)
11490 return err;
11492 n = fprintf(f,
11493 "# Editing the history of branch '%s' starting at\n"
11494 "# commit %s\n"
11495 "# Commits will be processed in order from top to "
11496 "bottom of this file.\n", branch_name, id_str);
11497 if (n < 0) {
11498 err = got_ferror(f, GOT_ERR_IO);
11499 goto done;
11502 n = fprintf(f, "# Available histedit commands:\n");
11503 if (n < 0) {
11504 err = got_ferror(f, GOT_ERR_IO);
11505 goto done;
11508 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11509 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11510 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11511 cmd->desc);
11512 if (n < 0) {
11513 err = got_ferror(f, GOT_ERR_IO);
11514 break;
11517 done:
11518 free(id_str);
11519 return err;
11522 static const struct got_error *
11523 histedit_syntax_error(int lineno)
11525 static char msg[42];
11526 int ret;
11528 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11529 lineno);
11530 if (ret < 0 || (size_t)ret >= sizeof(msg))
11531 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11533 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11536 static const struct got_error *
11537 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11538 char *logmsg, struct got_repository *repo)
11540 const struct got_error *err;
11541 struct got_commit_object *folded_commit = NULL;
11542 char *id_str, *folded_logmsg = NULL;
11544 err = got_object_id_str(&id_str, hle->commit_id);
11545 if (err)
11546 return err;
11548 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11549 if (err)
11550 goto done;
11552 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11553 if (err)
11554 goto done;
11555 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11556 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11557 folded_logmsg) == -1) {
11558 err = got_error_from_errno("asprintf");
11560 done:
11561 if (folded_commit)
11562 got_object_commit_close(folded_commit);
11563 free(id_str);
11564 free(folded_logmsg);
11565 return err;
11568 static struct got_histedit_list_entry *
11569 get_folded_commits(struct got_histedit_list_entry *hle)
11571 struct got_histedit_list_entry *prev, *folded = NULL;
11573 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11574 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11575 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11576 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11577 folded = prev;
11578 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11581 return folded;
11584 static const struct got_error *
11585 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11586 struct got_repository *repo)
11588 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11589 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11590 const struct got_error *err = NULL;
11591 struct got_commit_object *commit = NULL;
11592 int logmsg_len;
11593 int fd;
11594 struct got_histedit_list_entry *folded = NULL;
11596 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11597 if (err)
11598 return err;
11600 folded = get_folded_commits(hle);
11601 if (folded) {
11602 while (folded != hle) {
11603 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11604 folded = TAILQ_NEXT(folded, entry);
11605 continue;
11607 err = append_folded_commit_msg(&new_msg, folded,
11608 logmsg, repo);
11609 if (err)
11610 goto done;
11611 free(logmsg);
11612 logmsg = new_msg;
11613 folded = TAILQ_NEXT(folded, entry);
11617 err = got_object_id_str(&id_str, hle->commit_id);
11618 if (err)
11619 goto done;
11620 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11621 if (err)
11622 goto done;
11623 logmsg_len = asprintf(&new_msg,
11624 "%s\n# original log message of commit %s: %s",
11625 logmsg ? logmsg : "", id_str, orig_logmsg);
11626 if (logmsg_len == -1) {
11627 err = got_error_from_errno("asprintf");
11628 goto done;
11630 free(logmsg);
11631 logmsg = new_msg;
11633 err = got_object_id_str(&id_str, hle->commit_id);
11634 if (err)
11635 goto done;
11637 err = got_opentemp_named_fd(&logmsg_path, &fd,
11638 GOT_TMPDIR_STR "/got-logmsg", "");
11639 if (err)
11640 goto done;
11642 write(fd, logmsg, logmsg_len);
11643 close(fd);
11645 err = get_editor(&editor);
11646 if (err)
11647 goto done;
11649 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11650 logmsg_len, 0);
11651 if (err) {
11652 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11653 goto done;
11654 err = NULL;
11655 hle->logmsg = strdup(new_msg);
11656 if (hle->logmsg == NULL)
11657 err = got_error_from_errno("strdup");
11659 done:
11660 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11661 err = got_error_from_errno2("unlink", logmsg_path);
11662 free(logmsg_path);
11663 free(logmsg);
11664 free(orig_logmsg);
11665 free(editor);
11666 if (commit)
11667 got_object_commit_close(commit);
11668 return err;
11671 static const struct got_error *
11672 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11673 FILE *f, struct got_repository *repo)
11675 const struct got_error *err = NULL;
11676 char *line = NULL, *p, *end;
11677 size_t i, size;
11678 ssize_t len;
11679 int lineno = 0, lastcmd = -1;
11680 const struct got_histedit_cmd *cmd;
11681 struct got_object_id *commit_id = NULL;
11682 struct got_histedit_list_entry *hle = NULL;
11684 for (;;) {
11685 len = getline(&line, &size, f);
11686 if (len == -1) {
11687 const struct got_error *getline_err;
11688 if (feof(f))
11689 break;
11690 getline_err = got_error_from_errno("getline");
11691 err = got_ferror(f, getline_err->code);
11692 break;
11694 lineno++;
11695 p = line;
11696 while (isspace((unsigned char)p[0]))
11697 p++;
11698 if (p[0] == '#' || p[0] == '\0') {
11699 free(line);
11700 line = NULL;
11701 continue;
11703 cmd = NULL;
11704 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11705 cmd = &got_histedit_cmds[i];
11706 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11707 isspace((unsigned char)p[strlen(cmd->name)])) {
11708 p += strlen(cmd->name);
11709 break;
11711 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11712 p++;
11713 break;
11716 if (i == nitems(got_histedit_cmds)) {
11717 err = histedit_syntax_error(lineno);
11718 break;
11720 while (isspace((unsigned char)p[0]))
11721 p++;
11722 if (cmd->code == GOT_HISTEDIT_MESG) {
11723 if (lastcmd != GOT_HISTEDIT_PICK &&
11724 lastcmd != GOT_HISTEDIT_EDIT) {
11725 err = got_error(GOT_ERR_HISTEDIT_CMD);
11726 break;
11728 if (p[0] == '\0') {
11729 err = histedit_edit_logmsg(hle, repo);
11730 if (err)
11731 break;
11732 } else {
11733 hle->logmsg = strdup(p);
11734 if (hle->logmsg == NULL) {
11735 err = got_error_from_errno("strdup");
11736 break;
11739 free(line);
11740 line = NULL;
11741 lastcmd = cmd->code;
11742 continue;
11743 } else {
11744 end = p;
11745 while (end[0] && !isspace((unsigned char)end[0]))
11746 end++;
11747 *end = '\0';
11749 err = got_object_resolve_id_str(&commit_id, repo, p);
11750 if (err) {
11751 /* override error code */
11752 err = histedit_syntax_error(lineno);
11753 break;
11756 hle = malloc(sizeof(*hle));
11757 if (hle == NULL) {
11758 err = got_error_from_errno("malloc");
11759 break;
11761 hle->cmd = cmd;
11762 hle->commit_id = commit_id;
11763 hle->logmsg = NULL;
11764 commit_id = NULL;
11765 free(line);
11766 line = NULL;
11767 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11768 lastcmd = cmd->code;
11771 free(line);
11772 free(commit_id);
11773 return err;
11776 static const struct got_error *
11777 histedit_check_script(struct got_histedit_list *histedit_cmds,
11778 struct got_object_id_queue *commits, struct got_repository *repo)
11780 const struct got_error *err = NULL;
11781 struct got_object_qid *qid;
11782 struct got_histedit_list_entry *hle;
11783 static char msg[92];
11784 char *id_str;
11786 if (TAILQ_EMPTY(histedit_cmds))
11787 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11788 "histedit script contains no commands");
11789 if (STAILQ_EMPTY(commits))
11790 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11792 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11793 struct got_histedit_list_entry *hle2;
11794 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11795 if (hle == hle2)
11796 continue;
11797 if (got_object_id_cmp(hle->commit_id,
11798 hle2->commit_id) != 0)
11799 continue;
11800 err = got_object_id_str(&id_str, hle->commit_id);
11801 if (err)
11802 return err;
11803 snprintf(msg, sizeof(msg), "commit %s is listed "
11804 "more than once in histedit script", id_str);
11805 free(id_str);
11806 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11810 STAILQ_FOREACH(qid, commits, entry) {
11811 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11812 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11813 break;
11815 if (hle == NULL) {
11816 err = got_object_id_str(&id_str, &qid->id);
11817 if (err)
11818 return err;
11819 snprintf(msg, sizeof(msg),
11820 "commit %s missing from histedit script", id_str);
11821 free(id_str);
11822 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11826 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11827 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11828 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11829 "last commit in histedit script cannot be folded");
11831 return NULL;
11834 static const struct got_error *
11835 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11836 const char *path, struct got_object_id_queue *commits,
11837 struct got_repository *repo)
11839 const struct got_error *err = NULL;
11840 char *editor;
11841 FILE *f = NULL;
11843 err = get_editor(&editor);
11844 if (err)
11845 return err;
11847 if (spawn_editor(editor, path) == -1) {
11848 err = got_error_from_errno("failed spawning editor");
11849 goto done;
11852 f = fopen(path, "re");
11853 if (f == NULL) {
11854 err = got_error_from_errno("fopen");
11855 goto done;
11857 err = histedit_parse_list(histedit_cmds, f, repo);
11858 if (err)
11859 goto done;
11861 err = histedit_check_script(histedit_cmds, commits, repo);
11862 done:
11863 if (f && fclose(f) == EOF && err == NULL)
11864 err = got_error_from_errno("fclose");
11865 free(editor);
11866 return err;
11869 static const struct got_error *
11870 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11871 struct got_object_id_queue *, const char *, const char *,
11872 struct got_repository *);
11874 static const struct got_error *
11875 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11876 struct got_object_id_queue *commits, const char *branch_name,
11877 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11878 struct got_repository *repo)
11880 const struct got_error *err;
11881 FILE *f = NULL;
11882 char *path = NULL;
11884 err = got_opentemp_named(&path, &f, "got-histedit", "");
11885 if (err)
11886 return err;
11888 err = write_cmd_list(f, branch_name, commits);
11889 if (err)
11890 goto done;
11892 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11893 fold_only, drop_only, edit_only, repo);
11894 if (err)
11895 goto done;
11897 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11898 rewind(f);
11899 err = histedit_parse_list(histedit_cmds, f, repo);
11900 } else {
11901 if (fclose(f) == EOF) {
11902 err = got_error_from_errno("fclose");
11903 goto done;
11905 f = NULL;
11906 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11907 if (err) {
11908 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11909 err->code != GOT_ERR_HISTEDIT_CMD)
11910 goto done;
11911 err = histedit_edit_list_retry(histedit_cmds, err,
11912 commits, path, branch_name, repo);
11915 done:
11916 if (f && fclose(f) == EOF && err == NULL)
11917 err = got_error_from_errno("fclose");
11918 if (path && unlink(path) != 0 && err == NULL)
11919 err = got_error_from_errno2("unlink", path);
11920 free(path);
11921 return err;
11924 static const struct got_error *
11925 histedit_save_list(struct got_histedit_list *histedit_cmds,
11926 struct got_worktree *worktree, struct got_repository *repo)
11928 const struct got_error *err = NULL;
11929 char *path = NULL;
11930 FILE *f = NULL;
11931 struct got_histedit_list_entry *hle;
11932 struct got_commit_object *commit = NULL;
11934 err = got_worktree_get_histedit_script_path(&path, worktree);
11935 if (err)
11936 return err;
11938 f = fopen(path, "we");
11939 if (f == NULL) {
11940 err = got_error_from_errno2("fopen", path);
11941 goto done;
11943 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11944 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11945 repo);
11946 if (err)
11947 break;
11949 if (hle->logmsg) {
11950 int n = fprintf(f, "%c %s\n",
11951 GOT_HISTEDIT_MESG, hle->logmsg);
11952 if (n < 0) {
11953 err = got_ferror(f, GOT_ERR_IO);
11954 break;
11958 done:
11959 if (f && fclose(f) == EOF && err == NULL)
11960 err = got_error_from_errno("fclose");
11961 free(path);
11962 if (commit)
11963 got_object_commit_close(commit);
11964 return err;
11967 static void
11968 histedit_free_list(struct got_histedit_list *histedit_cmds)
11970 struct got_histedit_list_entry *hle;
11972 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11973 TAILQ_REMOVE(histedit_cmds, hle, entry);
11974 free(hle);
11978 static const struct got_error *
11979 histedit_load_list(struct got_histedit_list *histedit_cmds,
11980 const char *path, struct got_repository *repo)
11982 const struct got_error *err = NULL;
11983 FILE *f = NULL;
11985 f = fopen(path, "re");
11986 if (f == NULL) {
11987 err = got_error_from_errno2("fopen", path);
11988 goto done;
11991 err = histedit_parse_list(histedit_cmds, f, repo);
11992 done:
11993 if (f && fclose(f) == EOF && err == NULL)
11994 err = got_error_from_errno("fclose");
11995 return err;
11998 static const struct got_error *
11999 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12000 const struct got_error *edit_err, struct got_object_id_queue *commits,
12001 const char *path, const char *branch_name, struct got_repository *repo)
12003 const struct got_error *err = NULL, *prev_err = edit_err;
12004 int resp = ' ';
12006 while (resp != 'c' && resp != 'r' && resp != 'a') {
12007 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12008 "or (a)bort: ", getprogname(), prev_err->msg);
12009 resp = getchar();
12010 if (resp == '\n')
12011 resp = getchar();
12012 if (resp == 'c') {
12013 histedit_free_list(histedit_cmds);
12014 err = histedit_run_editor(histedit_cmds, path, commits,
12015 repo);
12016 if (err) {
12017 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12018 err->code != GOT_ERR_HISTEDIT_CMD)
12019 break;
12020 prev_err = err;
12021 resp = ' ';
12022 continue;
12024 break;
12025 } else if (resp == 'r') {
12026 histedit_free_list(histedit_cmds);
12027 err = histedit_edit_script(histedit_cmds,
12028 commits, branch_name, 0, 0, 0, 0, repo);
12029 if (err) {
12030 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12031 err->code != GOT_ERR_HISTEDIT_CMD)
12032 break;
12033 prev_err = err;
12034 resp = ' ';
12035 continue;
12037 break;
12038 } else if (resp == 'a') {
12039 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12040 break;
12041 } else
12042 printf("invalid response '%c'\n", resp);
12045 return err;
12048 static const struct got_error *
12049 histedit_complete(struct got_worktree *worktree,
12050 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12051 struct got_reference *branch, struct got_repository *repo)
12053 printf("Switching work tree to %s\n",
12054 got_ref_get_symref_target(branch));
12055 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12056 branch, repo);
12059 static const struct got_error *
12060 show_histedit_progress(struct got_commit_object *commit,
12061 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12063 const struct got_error *err;
12064 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12066 err = got_object_id_str(&old_id_str, hle->commit_id);
12067 if (err)
12068 goto done;
12070 if (new_id) {
12071 err = got_object_id_str(&new_id_str, new_id);
12072 if (err)
12073 goto done;
12076 old_id_str[12] = '\0';
12077 if (new_id_str)
12078 new_id_str[12] = '\0';
12080 if (hle->logmsg) {
12081 logmsg = strdup(hle->logmsg);
12082 if (logmsg == NULL) {
12083 err = got_error_from_errno("strdup");
12084 goto done;
12086 trim_logmsg(logmsg, 42);
12087 } else {
12088 err = get_short_logmsg(&logmsg, 42, commit);
12089 if (err)
12090 goto done;
12093 switch (hle->cmd->code) {
12094 case GOT_HISTEDIT_PICK:
12095 case GOT_HISTEDIT_EDIT:
12096 printf("%s -> %s: %s\n", old_id_str,
12097 new_id_str ? new_id_str : "no-op change", logmsg);
12098 break;
12099 case GOT_HISTEDIT_DROP:
12100 case GOT_HISTEDIT_FOLD:
12101 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12102 logmsg);
12103 break;
12104 default:
12105 break;
12107 done:
12108 free(old_id_str);
12109 free(new_id_str);
12110 return err;
12113 static const struct got_error *
12114 histedit_commit(struct got_pathlist_head *merged_paths,
12115 struct got_worktree *worktree, struct got_fileindex *fileindex,
12116 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12117 const char *committer, struct got_repository *repo)
12119 const struct got_error *err;
12120 struct got_commit_object *commit;
12121 struct got_object_id *new_commit_id;
12123 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12124 && hle->logmsg == NULL) {
12125 err = histedit_edit_logmsg(hle, repo);
12126 if (err)
12127 return err;
12130 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12131 if (err)
12132 return err;
12134 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12135 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12136 hle->logmsg, repo);
12137 if (err) {
12138 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12139 goto done;
12140 err = show_histedit_progress(commit, hle, NULL);
12141 } else {
12142 err = show_histedit_progress(commit, hle, new_commit_id);
12143 free(new_commit_id);
12145 done:
12146 got_object_commit_close(commit);
12147 return err;
12150 static const struct got_error *
12151 histedit_skip_commit(struct got_histedit_list_entry *hle,
12152 struct got_worktree *worktree, struct got_repository *repo)
12154 const struct got_error *error;
12155 struct got_commit_object *commit;
12157 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12158 repo);
12159 if (error)
12160 return error;
12162 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12163 if (error)
12164 return error;
12166 error = show_histedit_progress(commit, hle, NULL);
12167 got_object_commit_close(commit);
12168 return error;
12171 static const struct got_error *
12172 check_local_changes(void *arg, unsigned char status,
12173 unsigned char staged_status, const char *path,
12174 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12175 struct got_object_id *commit_id, int dirfd, const char *de_name)
12177 int *have_local_changes = arg;
12179 switch (status) {
12180 case GOT_STATUS_ADD:
12181 case GOT_STATUS_DELETE:
12182 case GOT_STATUS_MODIFY:
12183 case GOT_STATUS_CONFLICT:
12184 *have_local_changes = 1;
12185 return got_error(GOT_ERR_CANCELLED);
12186 default:
12187 break;
12190 switch (staged_status) {
12191 case GOT_STATUS_ADD:
12192 case GOT_STATUS_DELETE:
12193 case GOT_STATUS_MODIFY:
12194 *have_local_changes = 1;
12195 return got_error(GOT_ERR_CANCELLED);
12196 default:
12197 break;
12200 return NULL;
12203 static const struct got_error *
12204 cmd_histedit(int argc, char *argv[])
12206 const struct got_error *error = NULL;
12207 struct got_worktree *worktree = NULL;
12208 struct got_fileindex *fileindex = NULL;
12209 struct got_repository *repo = NULL;
12210 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12211 struct got_reference *branch = NULL;
12212 struct got_reference *tmp_branch = NULL;
12213 struct got_object_id *resume_commit_id = NULL;
12214 struct got_object_id *base_commit_id = NULL;
12215 struct got_object_id *head_commit_id = NULL;
12216 struct got_commit_object *commit = NULL;
12217 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12218 struct got_update_progress_arg upa;
12219 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12220 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12221 int list_backups = 0, delete_backups = 0;
12222 const char *edit_script_path = NULL;
12223 struct got_object_id_queue commits;
12224 struct got_pathlist_head merged_paths;
12225 const struct got_object_id_queue *parent_ids;
12226 struct got_object_qid *pid;
12227 struct got_histedit_list histedit_cmds;
12228 struct got_histedit_list_entry *hle;
12229 int *pack_fds = NULL;
12231 STAILQ_INIT(&commits);
12232 TAILQ_INIT(&histedit_cmds);
12233 TAILQ_INIT(&merged_paths);
12234 memset(&upa, 0, sizeof(upa));
12236 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12237 switch (ch) {
12238 case 'a':
12239 abort_edit = 1;
12240 break;
12241 case 'c':
12242 continue_edit = 1;
12243 break;
12244 case 'd':
12245 drop_only = 1;
12246 break;
12247 case 'e':
12248 edit_only = 1;
12249 break;
12250 case 'F':
12251 edit_script_path = optarg;
12252 break;
12253 case 'f':
12254 fold_only = 1;
12255 break;
12256 case 'l':
12257 list_backups = 1;
12258 break;
12259 case 'm':
12260 edit_logmsg_only = 1;
12261 break;
12262 case 'X':
12263 delete_backups = 1;
12264 break;
12265 default:
12266 usage_histedit();
12267 /* NOTREACHED */
12271 argc -= optind;
12272 argv += optind;
12274 #ifndef PROFILE
12275 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12276 "unveil", NULL) == -1)
12277 err(1, "pledge");
12278 #endif
12279 if (abort_edit && continue_edit)
12280 option_conflict('a', 'c');
12281 if (edit_script_path && edit_logmsg_only)
12282 option_conflict('F', 'm');
12283 if (abort_edit && edit_logmsg_only)
12284 option_conflict('a', 'm');
12285 if (continue_edit && edit_logmsg_only)
12286 option_conflict('c', 'm');
12287 if (abort_edit && fold_only)
12288 option_conflict('a', 'f');
12289 if (continue_edit && fold_only)
12290 option_conflict('c', 'f');
12291 if (fold_only && edit_logmsg_only)
12292 option_conflict('f', 'm');
12293 if (edit_script_path && fold_only)
12294 option_conflict('F', 'f');
12295 if (abort_edit && edit_only)
12296 option_conflict('a', 'e');
12297 if (continue_edit && edit_only)
12298 option_conflict('c', 'e');
12299 if (edit_only && edit_logmsg_only)
12300 option_conflict('e', 'm');
12301 if (edit_script_path && edit_only)
12302 option_conflict('F', 'e');
12303 if (fold_only && edit_only)
12304 option_conflict('f', 'e');
12305 if (drop_only && abort_edit)
12306 option_conflict('d', 'a');
12307 if (drop_only && continue_edit)
12308 option_conflict('d', 'c');
12309 if (drop_only && edit_logmsg_only)
12310 option_conflict('d', 'm');
12311 if (drop_only && edit_only)
12312 option_conflict('d', 'e');
12313 if (drop_only && edit_script_path)
12314 option_conflict('d', 'F');
12315 if (drop_only && fold_only)
12316 option_conflict('d', 'f');
12317 if (list_backups) {
12318 if (abort_edit)
12319 option_conflict('l', 'a');
12320 if (continue_edit)
12321 option_conflict('l', 'c');
12322 if (edit_script_path)
12323 option_conflict('l', 'F');
12324 if (edit_logmsg_only)
12325 option_conflict('l', 'm');
12326 if (drop_only)
12327 option_conflict('l', 'd');
12328 if (fold_only)
12329 option_conflict('l', 'f');
12330 if (edit_only)
12331 option_conflict('l', 'e');
12332 if (delete_backups)
12333 option_conflict('l', 'X');
12334 if (argc != 0 && argc != 1)
12335 usage_histedit();
12336 } else if (delete_backups) {
12337 if (abort_edit)
12338 option_conflict('X', 'a');
12339 if (continue_edit)
12340 option_conflict('X', 'c');
12341 if (drop_only)
12342 option_conflict('X', 'd');
12343 if (edit_script_path)
12344 option_conflict('X', 'F');
12345 if (edit_logmsg_only)
12346 option_conflict('X', 'm');
12347 if (fold_only)
12348 option_conflict('X', 'f');
12349 if (edit_only)
12350 option_conflict('X', 'e');
12351 if (list_backups)
12352 option_conflict('X', 'l');
12353 if (argc != 0 && argc != 1)
12354 usage_histedit();
12355 } else if (argc != 0)
12356 usage_histedit();
12359 * This command cannot apply unveil(2) in all cases because the
12360 * user may choose to run an editor to edit the histedit script
12361 * and to edit individual commit log messages.
12362 * unveil(2) traverses exec(2); if an editor is used we have to
12363 * apply unveil after edit script and log messages have been written.
12364 * XXX TODO: Make use of unveil(2) where possible.
12367 cwd = getcwd(NULL, 0);
12368 if (cwd == NULL) {
12369 error = got_error_from_errno("getcwd");
12370 goto done;
12373 error = got_repo_pack_fds_open(&pack_fds);
12374 if (error != NULL)
12375 goto done;
12377 error = got_worktree_open(&worktree, cwd);
12378 if (error) {
12379 if (list_backups || delete_backups) {
12380 if (error->code != GOT_ERR_NOT_WORKTREE)
12381 goto done;
12382 } else {
12383 if (error->code == GOT_ERR_NOT_WORKTREE)
12384 error = wrap_not_worktree_error(error,
12385 "histedit", cwd);
12386 goto done;
12390 if (list_backups || delete_backups) {
12391 error = got_repo_open(&repo,
12392 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12393 NULL, pack_fds);
12394 if (error != NULL)
12395 goto done;
12396 error = apply_unveil(got_repo_get_path(repo), 0,
12397 worktree ? got_worktree_get_root_path(worktree) : NULL);
12398 if (error)
12399 goto done;
12400 error = process_backup_refs(
12401 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12402 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12403 goto done; /* nothing else to do */
12406 error = get_gitconfig_path(&gitconfig_path);
12407 if (error)
12408 goto done;
12409 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12410 gitconfig_path, pack_fds);
12411 if (error != NULL)
12412 goto done;
12414 if (worktree != NULL && !list_backups && !delete_backups) {
12415 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12416 if (error)
12417 goto done;
12420 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12421 if (error)
12422 goto done;
12423 if (rebase_in_progress) {
12424 error = got_error(GOT_ERR_REBASING);
12425 goto done;
12428 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12429 repo);
12430 if (error)
12431 goto done;
12432 if (merge_in_progress) {
12433 error = got_error(GOT_ERR_MERGE_BUSY);
12434 goto done;
12437 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12438 if (error)
12439 goto done;
12441 if (edit_in_progress && edit_logmsg_only) {
12442 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12443 "histedit operation is in progress in this "
12444 "work tree and must be continued or aborted "
12445 "before the -m option can be used");
12446 goto done;
12448 if (edit_in_progress && drop_only) {
12449 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12450 "histedit operation is in progress in this "
12451 "work tree and must be continued or aborted "
12452 "before the -d option can be used");
12453 goto done;
12455 if (edit_in_progress && fold_only) {
12456 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12457 "histedit operation is in progress in this "
12458 "work tree and must be continued or aborted "
12459 "before the -f option can be used");
12460 goto done;
12462 if (edit_in_progress && edit_only) {
12463 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12464 "histedit operation is in progress in this "
12465 "work tree and must be continued or aborted "
12466 "before the -e option can be used");
12467 goto done;
12470 if (edit_in_progress && abort_edit) {
12471 error = got_worktree_histedit_continue(&resume_commit_id,
12472 &tmp_branch, &branch, &base_commit_id, &fileindex,
12473 worktree, repo);
12474 if (error)
12475 goto done;
12476 printf("Switching work tree to %s\n",
12477 got_ref_get_symref_target(branch));
12478 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12479 branch, base_commit_id, abort_progress, &upa);
12480 if (error)
12481 goto done;
12482 printf("Histedit of %s aborted\n",
12483 got_ref_get_symref_target(branch));
12484 print_merge_progress_stats(&upa);
12485 goto done; /* nothing else to do */
12486 } else if (abort_edit) {
12487 error = got_error(GOT_ERR_NOT_HISTEDIT);
12488 goto done;
12491 error = get_author(&committer, repo, worktree);
12492 if (error)
12493 goto done;
12495 if (continue_edit) {
12496 char *path;
12498 if (!edit_in_progress) {
12499 error = got_error(GOT_ERR_NOT_HISTEDIT);
12500 goto done;
12503 error = got_worktree_get_histedit_script_path(&path, worktree);
12504 if (error)
12505 goto done;
12507 error = histedit_load_list(&histedit_cmds, path, repo);
12508 free(path);
12509 if (error)
12510 goto done;
12512 error = got_worktree_histedit_continue(&resume_commit_id,
12513 &tmp_branch, &branch, &base_commit_id, &fileindex,
12514 worktree, repo);
12515 if (error)
12516 goto done;
12518 error = got_ref_resolve(&head_commit_id, repo, branch);
12519 if (error)
12520 goto done;
12522 error = got_object_open_as_commit(&commit, repo,
12523 head_commit_id);
12524 if (error)
12525 goto done;
12526 parent_ids = got_object_commit_get_parent_ids(commit);
12527 pid = STAILQ_FIRST(parent_ids);
12528 if (pid == NULL) {
12529 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12530 goto done;
12532 error = collect_commits(&commits, head_commit_id, &pid->id,
12533 base_commit_id, got_worktree_get_path_prefix(worktree),
12534 GOT_ERR_HISTEDIT_PATH, repo);
12535 got_object_commit_close(commit);
12536 commit = NULL;
12537 if (error)
12538 goto done;
12539 } else {
12540 if (edit_in_progress) {
12541 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12542 goto done;
12545 error = got_ref_open(&branch, repo,
12546 got_worktree_get_head_ref_name(worktree), 0);
12547 if (error != NULL)
12548 goto done;
12550 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12551 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12552 "will not edit commit history of a branch outside "
12553 "the \"refs/heads/\" reference namespace");
12554 goto done;
12557 error = got_ref_resolve(&head_commit_id, repo, branch);
12558 got_ref_close(branch);
12559 branch = NULL;
12560 if (error)
12561 goto done;
12563 error = got_object_open_as_commit(&commit, repo,
12564 head_commit_id);
12565 if (error)
12566 goto done;
12567 parent_ids = got_object_commit_get_parent_ids(commit);
12568 pid = STAILQ_FIRST(parent_ids);
12569 if (pid == NULL) {
12570 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12571 goto done;
12573 error = collect_commits(&commits, head_commit_id, &pid->id,
12574 got_worktree_get_base_commit_id(worktree),
12575 got_worktree_get_path_prefix(worktree),
12576 GOT_ERR_HISTEDIT_PATH, repo);
12577 got_object_commit_close(commit);
12578 commit = NULL;
12579 if (error)
12580 goto done;
12582 if (STAILQ_EMPTY(&commits)) {
12583 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12584 goto done;
12587 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12588 &base_commit_id, &fileindex, worktree, repo);
12589 if (error)
12590 goto done;
12592 if (edit_script_path) {
12593 error = histedit_load_list(&histedit_cmds,
12594 edit_script_path, repo);
12595 if (error) {
12596 got_worktree_histedit_abort(worktree, fileindex,
12597 repo, branch, base_commit_id,
12598 abort_progress, &upa);
12599 print_merge_progress_stats(&upa);
12600 goto done;
12602 } else {
12603 const char *branch_name;
12604 branch_name = got_ref_get_symref_target(branch);
12605 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12606 branch_name += 11;
12607 error = histedit_edit_script(&histedit_cmds, &commits,
12608 branch_name, edit_logmsg_only, fold_only,
12609 drop_only, edit_only, repo);
12610 if (error) {
12611 got_worktree_histedit_abort(worktree, fileindex,
12612 repo, branch, base_commit_id,
12613 abort_progress, &upa);
12614 print_merge_progress_stats(&upa);
12615 goto done;
12620 error = histedit_save_list(&histedit_cmds, worktree,
12621 repo);
12622 if (error) {
12623 got_worktree_histedit_abort(worktree, fileindex,
12624 repo, branch, base_commit_id,
12625 abort_progress, &upa);
12626 print_merge_progress_stats(&upa);
12627 goto done;
12632 error = histedit_check_script(&histedit_cmds, &commits, repo);
12633 if (error)
12634 goto done;
12636 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12637 if (resume_commit_id) {
12638 if (got_object_id_cmp(hle->commit_id,
12639 resume_commit_id) != 0)
12640 continue;
12642 resume_commit_id = NULL;
12643 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12644 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12645 error = histedit_skip_commit(hle, worktree,
12646 repo);
12647 if (error)
12648 goto done;
12649 } else {
12650 struct got_pathlist_head paths;
12651 int have_changes = 0;
12653 TAILQ_INIT(&paths);
12654 error = got_pathlist_append(&paths, "", NULL);
12655 if (error)
12656 goto done;
12657 error = got_worktree_status(worktree, &paths,
12658 repo, 0, check_local_changes, &have_changes,
12659 check_cancelled, NULL);
12660 got_pathlist_free(&paths,
12661 GOT_PATHLIST_FREE_NONE);
12662 if (error) {
12663 if (error->code != GOT_ERR_CANCELLED)
12664 goto done;
12665 if (sigint_received || sigpipe_received)
12666 goto done;
12668 if (have_changes) {
12669 error = histedit_commit(NULL, worktree,
12670 fileindex, tmp_branch, hle,
12671 committer, repo);
12672 if (error)
12673 goto done;
12674 } else {
12675 error = got_object_open_as_commit(
12676 &commit, repo, hle->commit_id);
12677 if (error)
12678 goto done;
12679 error = show_histedit_progress(commit,
12680 hle, NULL);
12681 got_object_commit_close(commit);
12682 commit = NULL;
12683 if (error)
12684 goto done;
12687 continue;
12690 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12691 error = histedit_skip_commit(hle, worktree, repo);
12692 if (error)
12693 goto done;
12694 continue;
12697 error = got_object_open_as_commit(&commit, repo,
12698 hle->commit_id);
12699 if (error)
12700 goto done;
12701 parent_ids = got_object_commit_get_parent_ids(commit);
12702 pid = STAILQ_FIRST(parent_ids);
12704 error = got_worktree_histedit_merge_files(&merged_paths,
12705 worktree, fileindex, &pid->id, hle->commit_id, repo,
12706 update_progress, &upa, check_cancelled, NULL);
12707 if (error)
12708 goto done;
12709 got_object_commit_close(commit);
12710 commit = NULL;
12712 print_merge_progress_stats(&upa);
12713 if (upa.conflicts > 0 || upa.missing > 0 ||
12714 upa.not_deleted > 0 || upa.unversioned > 0) {
12715 if (upa.conflicts > 0) {
12716 error = show_rebase_merge_conflict(
12717 hle->commit_id, repo);
12718 if (error)
12719 goto done;
12721 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12722 break;
12725 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12726 char *id_str;
12727 error = got_object_id_str(&id_str, hle->commit_id);
12728 if (error)
12729 goto done;
12730 printf("Stopping histedit for amending commit %s\n",
12731 id_str);
12732 free(id_str);
12733 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12734 error = got_worktree_histedit_postpone(worktree,
12735 fileindex);
12736 goto done;
12739 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12740 error = histedit_skip_commit(hle, worktree, repo);
12741 if (error)
12742 goto done;
12743 continue;
12746 error = histedit_commit(&merged_paths, worktree, fileindex,
12747 tmp_branch, hle, committer, repo);
12748 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12749 if (error)
12750 goto done;
12753 if (upa.conflicts > 0 || upa.missing > 0 ||
12754 upa.not_deleted > 0 || upa.unversioned > 0) {
12755 error = got_worktree_histedit_postpone(worktree, fileindex);
12756 if (error)
12757 goto done;
12758 if (upa.conflicts > 0 && upa.missing == 0 &&
12759 upa.not_deleted == 0 && upa.unversioned == 0) {
12760 error = got_error_msg(GOT_ERR_CONFLICTS,
12761 "conflicts must be resolved before histedit "
12762 "can continue");
12763 } else if (upa.conflicts > 0) {
12764 error = got_error_msg(GOT_ERR_CONFLICTS,
12765 "conflicts must be resolved before histedit "
12766 "can continue; changes destined for some "
12767 "files were not yet merged and should be "
12768 "merged manually if required before the "
12769 "histedit operation is continued");
12770 } else {
12771 error = got_error_msg(GOT_ERR_CONFLICTS,
12772 "changes destined for some files were not "
12773 "yet merged and should be merged manually "
12774 "if required before the histedit operation "
12775 "is continued");
12777 } else
12778 error = histedit_complete(worktree, fileindex, tmp_branch,
12779 branch, repo);
12780 done:
12781 free(cwd);
12782 free(committer);
12783 free(gitconfig_path);
12784 got_object_id_queue_free(&commits);
12785 histedit_free_list(&histedit_cmds);
12786 free(head_commit_id);
12787 free(base_commit_id);
12788 free(resume_commit_id);
12789 if (commit)
12790 got_object_commit_close(commit);
12791 if (branch)
12792 got_ref_close(branch);
12793 if (tmp_branch)
12794 got_ref_close(tmp_branch);
12795 if (worktree)
12796 got_worktree_close(worktree);
12797 if (repo) {
12798 const struct got_error *close_err = got_repo_close(repo);
12799 if (error == NULL)
12800 error = close_err;
12802 if (pack_fds) {
12803 const struct got_error *pack_err =
12804 got_repo_pack_fds_close(pack_fds);
12805 if (error == NULL)
12806 error = pack_err;
12808 return error;
12811 __dead static void
12812 usage_integrate(void)
12814 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12815 exit(1);
12818 static const struct got_error *
12819 cmd_integrate(int argc, char *argv[])
12821 const struct got_error *error = NULL;
12822 struct got_repository *repo = NULL;
12823 struct got_worktree *worktree = NULL;
12824 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12825 const char *branch_arg = NULL;
12826 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12827 struct got_fileindex *fileindex = NULL;
12828 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12829 int ch;
12830 struct got_update_progress_arg upa;
12831 int *pack_fds = NULL;
12833 while ((ch = getopt(argc, argv, "")) != -1) {
12834 switch (ch) {
12835 default:
12836 usage_integrate();
12837 /* NOTREACHED */
12841 argc -= optind;
12842 argv += optind;
12844 if (argc != 1)
12845 usage_integrate();
12846 branch_arg = argv[0];
12847 #ifndef PROFILE
12848 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12849 "unveil", NULL) == -1)
12850 err(1, "pledge");
12851 #endif
12852 cwd = getcwd(NULL, 0);
12853 if (cwd == NULL) {
12854 error = got_error_from_errno("getcwd");
12855 goto done;
12858 error = got_repo_pack_fds_open(&pack_fds);
12859 if (error != NULL)
12860 goto done;
12862 error = got_worktree_open(&worktree, cwd);
12863 if (error) {
12864 if (error->code == GOT_ERR_NOT_WORKTREE)
12865 error = wrap_not_worktree_error(error, "integrate",
12866 cwd);
12867 goto done;
12870 error = check_rebase_or_histedit_in_progress(worktree);
12871 if (error)
12872 goto done;
12874 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12875 NULL, pack_fds);
12876 if (error != NULL)
12877 goto done;
12879 error = apply_unveil(got_repo_get_path(repo), 0,
12880 got_worktree_get_root_path(worktree));
12881 if (error)
12882 goto done;
12884 error = check_merge_in_progress(worktree, repo);
12885 if (error)
12886 goto done;
12888 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12889 error = got_error_from_errno("asprintf");
12890 goto done;
12893 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12894 &base_branch_ref, worktree, refname, repo);
12895 if (error)
12896 goto done;
12898 refname = strdup(got_ref_get_name(branch_ref));
12899 if (refname == NULL) {
12900 error = got_error_from_errno("strdup");
12901 got_worktree_integrate_abort(worktree, fileindex, repo,
12902 branch_ref, base_branch_ref);
12903 goto done;
12905 base_refname = strdup(got_ref_get_name(base_branch_ref));
12906 if (base_refname == NULL) {
12907 error = got_error_from_errno("strdup");
12908 got_worktree_integrate_abort(worktree, fileindex, repo,
12909 branch_ref, base_branch_ref);
12910 goto done;
12912 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12913 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12914 got_worktree_integrate_abort(worktree, fileindex, repo,
12915 branch_ref, base_branch_ref);
12916 goto done;
12919 error = got_ref_resolve(&commit_id, repo, branch_ref);
12920 if (error)
12921 goto done;
12923 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12924 if (error)
12925 goto done;
12927 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12928 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12929 "specified branch has already been integrated");
12930 got_worktree_integrate_abort(worktree, fileindex, repo,
12931 branch_ref, base_branch_ref);
12932 goto done;
12935 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12936 if (error) {
12937 if (error->code == GOT_ERR_ANCESTRY)
12938 error = got_error(GOT_ERR_REBASE_REQUIRED);
12939 got_worktree_integrate_abort(worktree, fileindex, repo,
12940 branch_ref, base_branch_ref);
12941 goto done;
12944 memset(&upa, 0, sizeof(upa));
12945 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12946 branch_ref, base_branch_ref, update_progress, &upa,
12947 check_cancelled, NULL);
12948 if (error)
12949 goto done;
12951 printf("Integrated %s into %s\n", refname, base_refname);
12952 print_update_progress_stats(&upa);
12953 done:
12954 if (repo) {
12955 const struct got_error *close_err = got_repo_close(repo);
12956 if (error == NULL)
12957 error = close_err;
12959 if (worktree)
12960 got_worktree_close(worktree);
12961 if (pack_fds) {
12962 const struct got_error *pack_err =
12963 got_repo_pack_fds_close(pack_fds);
12964 if (error == NULL)
12965 error = pack_err;
12967 free(cwd);
12968 free(base_commit_id);
12969 free(commit_id);
12970 free(refname);
12971 free(base_refname);
12972 return error;
12975 __dead static void
12976 usage_merge(void)
12978 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12979 exit(1);
12982 static const struct got_error *
12983 cmd_merge(int argc, char *argv[])
12985 const struct got_error *error = NULL;
12986 struct got_worktree *worktree = NULL;
12987 struct got_repository *repo = NULL;
12988 struct got_fileindex *fileindex = NULL;
12989 char *cwd = NULL, *id_str = NULL, *author = NULL;
12990 struct got_reference *branch = NULL, *wt_branch = NULL;
12991 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12992 struct got_object_id *wt_branch_tip = NULL;
12993 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12994 int interrupt_merge = 0;
12995 struct got_update_progress_arg upa;
12996 struct got_object_id *merge_commit_id = NULL;
12997 char *branch_name = NULL;
12998 int *pack_fds = NULL;
13000 memset(&upa, 0, sizeof(upa));
13002 while ((ch = getopt(argc, argv, "acn")) != -1) {
13003 switch (ch) {
13004 case 'a':
13005 abort_merge = 1;
13006 break;
13007 case 'c':
13008 continue_merge = 1;
13009 break;
13010 case 'n':
13011 interrupt_merge = 1;
13012 break;
13013 default:
13014 usage_merge();
13015 /* NOTREACHED */
13019 argc -= optind;
13020 argv += optind;
13022 #ifndef PROFILE
13023 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13024 "unveil", NULL) == -1)
13025 err(1, "pledge");
13026 #endif
13028 if (abort_merge && continue_merge)
13029 option_conflict('a', 'c');
13030 if (abort_merge || continue_merge) {
13031 if (argc != 0)
13032 usage_merge();
13033 } else if (argc != 1)
13034 usage_merge();
13036 cwd = getcwd(NULL, 0);
13037 if (cwd == NULL) {
13038 error = got_error_from_errno("getcwd");
13039 goto done;
13042 error = got_repo_pack_fds_open(&pack_fds);
13043 if (error != NULL)
13044 goto done;
13046 error = got_worktree_open(&worktree, cwd);
13047 if (error) {
13048 if (error->code == GOT_ERR_NOT_WORKTREE)
13049 error = wrap_not_worktree_error(error,
13050 "merge", cwd);
13051 goto done;
13054 error = got_repo_open(&repo,
13055 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13056 pack_fds);
13057 if (error != NULL)
13058 goto done;
13060 if (worktree != NULL) {
13061 error = worktree_has_logmsg_ref("merge", worktree, repo);
13062 if (error)
13063 goto done;
13066 error = apply_unveil(got_repo_get_path(repo), 0,
13067 worktree ? got_worktree_get_root_path(worktree) : NULL);
13068 if (error)
13069 goto done;
13071 error = check_rebase_or_histedit_in_progress(worktree);
13072 if (error)
13073 goto done;
13075 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13076 repo);
13077 if (error)
13078 goto done;
13080 if (abort_merge) {
13081 if (!merge_in_progress) {
13082 error = got_error(GOT_ERR_NOT_MERGING);
13083 goto done;
13085 error = got_worktree_merge_continue(&branch_name,
13086 &branch_tip, &fileindex, worktree, repo);
13087 if (error)
13088 goto done;
13089 error = got_worktree_merge_abort(worktree, fileindex, repo,
13090 abort_progress, &upa);
13091 if (error)
13092 goto done;
13093 printf("Merge of %s aborted\n", branch_name);
13094 goto done; /* nothing else to do */
13097 error = get_author(&author, repo, worktree);
13098 if (error)
13099 goto done;
13101 if (continue_merge) {
13102 if (!merge_in_progress) {
13103 error = got_error(GOT_ERR_NOT_MERGING);
13104 goto done;
13106 error = got_worktree_merge_continue(&branch_name,
13107 &branch_tip, &fileindex, worktree, repo);
13108 if (error)
13109 goto done;
13110 } else {
13111 error = got_ref_open(&branch, repo, argv[0], 0);
13112 if (error != NULL)
13113 goto done;
13114 branch_name = strdup(got_ref_get_name(branch));
13115 if (branch_name == NULL) {
13116 error = got_error_from_errno("strdup");
13117 goto done;
13119 error = got_ref_resolve(&branch_tip, repo, branch);
13120 if (error)
13121 goto done;
13124 error = got_ref_open(&wt_branch, repo,
13125 got_worktree_get_head_ref_name(worktree), 0);
13126 if (error)
13127 goto done;
13128 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13129 if (error)
13130 goto done;
13131 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13132 wt_branch_tip, branch_tip, 0, repo,
13133 check_cancelled, NULL);
13134 if (error && error->code != GOT_ERR_ANCESTRY)
13135 goto done;
13137 if (!continue_merge) {
13138 error = check_path_prefix(wt_branch_tip, branch_tip,
13139 got_worktree_get_path_prefix(worktree),
13140 GOT_ERR_MERGE_PATH, repo);
13141 if (error)
13142 goto done;
13143 if (yca_id) {
13144 error = check_same_branch(wt_branch_tip, branch,
13145 yca_id, repo);
13146 if (error) {
13147 if (error->code != GOT_ERR_ANCESTRY)
13148 goto done;
13149 error = NULL;
13150 } else {
13151 static char msg[512];
13152 snprintf(msg, sizeof(msg),
13153 "cannot create a merge commit because "
13154 "%s is based on %s; %s can be integrated "
13155 "with 'got integrate' instead", branch_name,
13156 got_worktree_get_head_ref_name(worktree),
13157 branch_name);
13158 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13159 goto done;
13162 error = got_worktree_merge_prepare(&fileindex, worktree,
13163 branch, repo);
13164 if (error)
13165 goto done;
13167 error = got_worktree_merge_branch(worktree, fileindex,
13168 yca_id, branch_tip, repo, update_progress, &upa,
13169 check_cancelled, NULL);
13170 if (error)
13171 goto done;
13172 print_merge_progress_stats(&upa);
13173 if (!upa.did_something) {
13174 error = got_worktree_merge_abort(worktree, fileindex,
13175 repo, abort_progress, &upa);
13176 if (error)
13177 goto done;
13178 printf("Already up-to-date\n");
13179 goto done;
13183 if (interrupt_merge) {
13184 error = got_worktree_merge_postpone(worktree, fileindex);
13185 if (error)
13186 goto done;
13187 printf("Merge of %s interrupted on request\n", branch_name);
13188 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13189 upa.not_deleted > 0 || upa.unversioned > 0) {
13190 error = got_worktree_merge_postpone(worktree, fileindex);
13191 if (error)
13192 goto done;
13193 if (upa.conflicts > 0 && upa.missing == 0 &&
13194 upa.not_deleted == 0 && upa.unversioned == 0) {
13195 error = got_error_msg(GOT_ERR_CONFLICTS,
13196 "conflicts must be resolved before merging "
13197 "can continue");
13198 } else if (upa.conflicts > 0) {
13199 error = got_error_msg(GOT_ERR_CONFLICTS,
13200 "conflicts must be resolved before merging "
13201 "can continue; changes destined for some "
13202 "files were not yet merged and "
13203 "should be merged manually if required before the "
13204 "merge operation is continued");
13205 } else {
13206 error = got_error_msg(GOT_ERR_CONFLICTS,
13207 "changes destined for some "
13208 "files were not yet merged and should be "
13209 "merged manually if required before the "
13210 "merge operation is continued");
13212 goto done;
13213 } else {
13214 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13215 fileindex, author, NULL, 1, branch_tip, branch_name,
13216 repo, continue_merge ? print_status : NULL, NULL);
13217 if (error)
13218 goto done;
13219 error = got_worktree_merge_complete(worktree, fileindex, repo);
13220 if (error)
13221 goto done;
13222 error = got_object_id_str(&id_str, merge_commit_id);
13223 if (error)
13224 goto done;
13225 printf("Merged %s into %s: %s\n", branch_name,
13226 got_worktree_get_head_ref_name(worktree),
13227 id_str);
13230 done:
13231 free(id_str);
13232 free(merge_commit_id);
13233 free(author);
13234 free(branch_tip);
13235 free(branch_name);
13236 free(yca_id);
13237 if (branch)
13238 got_ref_close(branch);
13239 if (wt_branch)
13240 got_ref_close(wt_branch);
13241 if (worktree)
13242 got_worktree_close(worktree);
13243 if (repo) {
13244 const struct got_error *close_err = got_repo_close(repo);
13245 if (error == NULL)
13246 error = close_err;
13248 if (pack_fds) {
13249 const struct got_error *pack_err =
13250 got_repo_pack_fds_close(pack_fds);
13251 if (error == NULL)
13252 error = pack_err;
13254 return error;
13257 __dead static void
13258 usage_stage(void)
13260 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13261 "[path ...]\n", getprogname());
13262 exit(1);
13265 static const struct got_error *
13266 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13267 const char *path, struct got_object_id *blob_id,
13268 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13269 int dirfd, const char *de_name)
13271 const struct got_error *err = NULL;
13272 char *id_str = NULL;
13274 if (staged_status != GOT_STATUS_ADD &&
13275 staged_status != GOT_STATUS_MODIFY &&
13276 staged_status != GOT_STATUS_DELETE)
13277 return NULL;
13279 if (staged_status == GOT_STATUS_ADD ||
13280 staged_status == GOT_STATUS_MODIFY)
13281 err = got_object_id_str(&id_str, staged_blob_id);
13282 else
13283 err = got_object_id_str(&id_str, blob_id);
13284 if (err)
13285 return err;
13287 printf("%s %c %s\n", id_str, staged_status, path);
13288 free(id_str);
13289 return NULL;
13292 static const struct got_error *
13293 cmd_stage(int argc, char *argv[])
13295 const struct got_error *error = NULL;
13296 struct got_repository *repo = NULL;
13297 struct got_worktree *worktree = NULL;
13298 char *cwd = NULL;
13299 struct got_pathlist_head paths;
13300 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13301 FILE *patch_script_file = NULL;
13302 const char *patch_script_path = NULL;
13303 struct choose_patch_arg cpa;
13304 int *pack_fds = NULL;
13306 TAILQ_INIT(&paths);
13308 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13309 switch (ch) {
13310 case 'F':
13311 patch_script_path = optarg;
13312 break;
13313 case 'l':
13314 list_stage = 1;
13315 break;
13316 case 'p':
13317 pflag = 1;
13318 break;
13319 case 'S':
13320 allow_bad_symlinks = 1;
13321 break;
13322 default:
13323 usage_stage();
13324 /* NOTREACHED */
13328 argc -= optind;
13329 argv += optind;
13331 #ifndef PROFILE
13332 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13333 "unveil", NULL) == -1)
13334 err(1, "pledge");
13335 #endif
13336 if (list_stage && (pflag || patch_script_path))
13337 errx(1, "-l option cannot be used with other options");
13338 if (patch_script_path && !pflag)
13339 errx(1, "-F option can only be used together with -p option");
13341 cwd = getcwd(NULL, 0);
13342 if (cwd == NULL) {
13343 error = got_error_from_errno("getcwd");
13344 goto done;
13347 error = got_repo_pack_fds_open(&pack_fds);
13348 if (error != NULL)
13349 goto done;
13351 error = got_worktree_open(&worktree, cwd);
13352 if (error) {
13353 if (error->code == GOT_ERR_NOT_WORKTREE)
13354 error = wrap_not_worktree_error(error, "stage", cwd);
13355 goto done;
13358 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13359 NULL, pack_fds);
13360 if (error != NULL)
13361 goto done;
13363 if (patch_script_path) {
13364 patch_script_file = fopen(patch_script_path, "re");
13365 if (patch_script_file == NULL) {
13366 error = got_error_from_errno2("fopen",
13367 patch_script_path);
13368 goto done;
13371 error = apply_unveil(got_repo_get_path(repo), 0,
13372 got_worktree_get_root_path(worktree));
13373 if (error)
13374 goto done;
13376 error = check_merge_in_progress(worktree, repo);
13377 if (error)
13378 goto done;
13380 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13381 if (error)
13382 goto done;
13384 if (list_stage)
13385 error = got_worktree_status(worktree, &paths, repo, 0,
13386 print_stage, NULL, check_cancelled, NULL);
13387 else {
13388 cpa.patch_script_file = patch_script_file;
13389 cpa.action = "stage";
13390 error = got_worktree_stage(worktree, &paths,
13391 pflag ? NULL : print_status, NULL,
13392 pflag ? choose_patch : NULL, &cpa,
13393 allow_bad_symlinks, repo);
13395 done:
13396 if (patch_script_file && fclose(patch_script_file) == EOF &&
13397 error == NULL)
13398 error = got_error_from_errno2("fclose", patch_script_path);
13399 if (repo) {
13400 const struct got_error *close_err = got_repo_close(repo);
13401 if (error == NULL)
13402 error = close_err;
13404 if (worktree)
13405 got_worktree_close(worktree);
13406 if (pack_fds) {
13407 const struct got_error *pack_err =
13408 got_repo_pack_fds_close(pack_fds);
13409 if (error == NULL)
13410 error = pack_err;
13412 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13413 free(cwd);
13414 return error;
13417 __dead static void
13418 usage_unstage(void)
13420 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13421 "[path ...]\n", getprogname());
13422 exit(1);
13426 static const struct got_error *
13427 cmd_unstage(int argc, char *argv[])
13429 const struct got_error *error = NULL;
13430 struct got_repository *repo = NULL;
13431 struct got_worktree *worktree = NULL;
13432 char *cwd = NULL;
13433 struct got_pathlist_head paths;
13434 int ch, pflag = 0;
13435 struct got_update_progress_arg upa;
13436 FILE *patch_script_file = NULL;
13437 const char *patch_script_path = NULL;
13438 struct choose_patch_arg cpa;
13439 int *pack_fds = NULL;
13441 TAILQ_INIT(&paths);
13443 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13444 switch (ch) {
13445 case 'F':
13446 patch_script_path = optarg;
13447 break;
13448 case 'p':
13449 pflag = 1;
13450 break;
13451 default:
13452 usage_unstage();
13453 /* NOTREACHED */
13457 argc -= optind;
13458 argv += optind;
13460 #ifndef PROFILE
13461 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13462 "unveil", NULL) == -1)
13463 err(1, "pledge");
13464 #endif
13465 if (patch_script_path && !pflag)
13466 errx(1, "-F option can only be used together with -p option");
13468 cwd = getcwd(NULL, 0);
13469 if (cwd == NULL) {
13470 error = got_error_from_errno("getcwd");
13471 goto done;
13474 error = got_repo_pack_fds_open(&pack_fds);
13475 if (error != NULL)
13476 goto done;
13478 error = got_worktree_open(&worktree, cwd);
13479 if (error) {
13480 if (error->code == GOT_ERR_NOT_WORKTREE)
13481 error = wrap_not_worktree_error(error, "unstage", cwd);
13482 goto done;
13485 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13486 NULL, pack_fds);
13487 if (error != NULL)
13488 goto done;
13490 if (patch_script_path) {
13491 patch_script_file = fopen(patch_script_path, "re");
13492 if (patch_script_file == NULL) {
13493 error = got_error_from_errno2("fopen",
13494 patch_script_path);
13495 goto done;
13499 error = apply_unveil(got_repo_get_path(repo), 0,
13500 got_worktree_get_root_path(worktree));
13501 if (error)
13502 goto done;
13504 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13505 if (error)
13506 goto done;
13508 cpa.patch_script_file = patch_script_file;
13509 cpa.action = "unstage";
13510 memset(&upa, 0, sizeof(upa));
13511 error = got_worktree_unstage(worktree, &paths, update_progress,
13512 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13513 if (!error)
13514 print_merge_progress_stats(&upa);
13515 done:
13516 if (patch_script_file && fclose(patch_script_file) == EOF &&
13517 error == NULL)
13518 error = got_error_from_errno2("fclose", patch_script_path);
13519 if (repo) {
13520 const struct got_error *close_err = got_repo_close(repo);
13521 if (error == NULL)
13522 error = close_err;
13524 if (worktree)
13525 got_worktree_close(worktree);
13526 if (pack_fds) {
13527 const struct got_error *pack_err =
13528 got_repo_pack_fds_close(pack_fds);
13529 if (error == NULL)
13530 error = pack_err;
13532 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13533 free(cwd);
13534 return error;
13537 __dead static void
13538 usage_cat(void)
13540 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13541 "arg ...\n", getprogname());
13542 exit(1);
13545 static const struct got_error *
13546 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13548 const struct got_error *err;
13549 struct got_blob_object *blob;
13550 int fd = -1;
13552 fd = got_opentempfd();
13553 if (fd == -1)
13554 return got_error_from_errno("got_opentempfd");
13556 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13557 if (err)
13558 goto done;
13560 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13561 done:
13562 if (fd != -1 && close(fd) == -1 && err == NULL)
13563 err = got_error_from_errno("close");
13564 if (blob)
13565 got_object_blob_close(blob);
13566 return err;
13569 static const struct got_error *
13570 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13572 const struct got_error *err;
13573 struct got_tree_object *tree;
13574 int nentries, i;
13576 err = got_object_open_as_tree(&tree, repo, id);
13577 if (err)
13578 return err;
13580 nentries = got_object_tree_get_nentries(tree);
13581 for (i = 0; i < nentries; i++) {
13582 struct got_tree_entry *te;
13583 char *id_str;
13584 if (sigint_received || sigpipe_received)
13585 break;
13586 te = got_object_tree_get_entry(tree, i);
13587 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13588 if (err)
13589 break;
13590 fprintf(outfile, "%s %.7o %s\n", id_str,
13591 got_tree_entry_get_mode(te),
13592 got_tree_entry_get_name(te));
13593 free(id_str);
13596 got_object_tree_close(tree);
13597 return err;
13600 static const struct got_error *
13601 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13603 const struct got_error *err;
13604 struct got_commit_object *commit;
13605 const struct got_object_id_queue *parent_ids;
13606 struct got_object_qid *pid;
13607 char *id_str = NULL;
13608 const char *logmsg = NULL;
13609 char gmtoff[6];
13611 err = got_object_open_as_commit(&commit, repo, id);
13612 if (err)
13613 return err;
13615 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13616 if (err)
13617 goto done;
13619 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13620 parent_ids = got_object_commit_get_parent_ids(commit);
13621 fprintf(outfile, "numparents %d\n",
13622 got_object_commit_get_nparents(commit));
13623 STAILQ_FOREACH(pid, parent_ids, entry) {
13624 char *pid_str;
13625 err = got_object_id_str(&pid_str, &pid->id);
13626 if (err)
13627 goto done;
13628 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13629 free(pid_str);
13631 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13632 got_object_commit_get_author_gmtoff(commit));
13633 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13634 got_object_commit_get_author(commit),
13635 (long long)got_object_commit_get_author_time(commit),
13636 gmtoff);
13638 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13639 got_object_commit_get_committer_gmtoff(commit));
13640 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13641 got_object_commit_get_committer(commit),
13642 (long long)got_object_commit_get_committer_time(commit),
13643 gmtoff);
13645 logmsg = got_object_commit_get_logmsg_raw(commit);
13646 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13647 fprintf(outfile, "%s", logmsg);
13648 done:
13649 free(id_str);
13650 got_object_commit_close(commit);
13651 return err;
13654 static const struct got_error *
13655 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13657 const struct got_error *err;
13658 struct got_tag_object *tag;
13659 char *id_str = NULL;
13660 const char *tagmsg = NULL;
13661 char gmtoff[6];
13663 err = got_object_open_as_tag(&tag, repo, id);
13664 if (err)
13665 return err;
13667 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13668 if (err)
13669 goto done;
13671 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13673 switch (got_object_tag_get_object_type(tag)) {
13674 case GOT_OBJ_TYPE_BLOB:
13675 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13676 GOT_OBJ_LABEL_BLOB);
13677 break;
13678 case GOT_OBJ_TYPE_TREE:
13679 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13680 GOT_OBJ_LABEL_TREE);
13681 break;
13682 case GOT_OBJ_TYPE_COMMIT:
13683 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13684 GOT_OBJ_LABEL_COMMIT);
13685 break;
13686 case GOT_OBJ_TYPE_TAG:
13687 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13688 GOT_OBJ_LABEL_TAG);
13689 break;
13690 default:
13691 break;
13694 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13695 got_object_tag_get_name(tag));
13697 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13698 got_object_tag_get_tagger_gmtoff(tag));
13699 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13700 got_object_tag_get_tagger(tag),
13701 (long long)got_object_tag_get_tagger_time(tag),
13702 gmtoff);
13704 tagmsg = got_object_tag_get_message(tag);
13705 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13706 fprintf(outfile, "%s", tagmsg);
13707 done:
13708 free(id_str);
13709 got_object_tag_close(tag);
13710 return err;
13713 static const struct got_error *
13714 cmd_cat(int argc, char *argv[])
13716 const struct got_error *error;
13717 struct got_repository *repo = NULL;
13718 struct got_worktree *worktree = NULL;
13719 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13720 const char *commit_id_str = NULL;
13721 struct got_object_id *id = NULL, *commit_id = NULL;
13722 struct got_commit_object *commit = NULL;
13723 int ch, obj_type, i, force_path = 0;
13724 struct got_reflist_head refs;
13725 int *pack_fds = NULL;
13727 TAILQ_INIT(&refs);
13729 #ifndef PROFILE
13730 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13731 NULL) == -1)
13732 err(1, "pledge");
13733 #endif
13735 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13736 switch (ch) {
13737 case 'c':
13738 commit_id_str = optarg;
13739 break;
13740 case 'P':
13741 force_path = 1;
13742 break;
13743 case 'r':
13744 repo_path = realpath(optarg, NULL);
13745 if (repo_path == NULL)
13746 return got_error_from_errno2("realpath",
13747 optarg);
13748 got_path_strip_trailing_slashes(repo_path);
13749 break;
13750 default:
13751 usage_cat();
13752 /* NOTREACHED */
13756 argc -= optind;
13757 argv += optind;
13759 cwd = getcwd(NULL, 0);
13760 if (cwd == NULL) {
13761 error = got_error_from_errno("getcwd");
13762 goto done;
13765 error = got_repo_pack_fds_open(&pack_fds);
13766 if (error != NULL)
13767 goto done;
13769 if (repo_path == NULL) {
13770 error = got_worktree_open(&worktree, cwd);
13771 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13772 goto done;
13773 if (worktree) {
13774 repo_path = strdup(
13775 got_worktree_get_repo_path(worktree));
13776 if (repo_path == NULL) {
13777 error = got_error_from_errno("strdup");
13778 goto done;
13781 /* Release work tree lock. */
13782 got_worktree_close(worktree);
13783 worktree = NULL;
13787 if (repo_path == NULL) {
13788 repo_path = strdup(cwd);
13789 if (repo_path == NULL)
13790 return got_error_from_errno("strdup");
13793 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13794 free(repo_path);
13795 if (error != NULL)
13796 goto done;
13798 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13799 if (error)
13800 goto done;
13802 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13803 if (error)
13804 goto done;
13806 if (commit_id_str == NULL)
13807 commit_id_str = GOT_REF_HEAD;
13808 error = got_repo_match_object_id(&commit_id, NULL,
13809 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13810 if (error)
13811 goto done;
13813 error = got_object_open_as_commit(&commit, repo, commit_id);
13814 if (error)
13815 goto done;
13817 for (i = 0; i < argc; i++) {
13818 if (force_path) {
13819 error = got_object_id_by_path(&id, repo, commit,
13820 argv[i]);
13821 if (error)
13822 break;
13823 } else {
13824 error = got_repo_match_object_id(&id, &label, argv[i],
13825 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13826 repo);
13827 if (error) {
13828 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13829 error->code != GOT_ERR_NOT_REF)
13830 break;
13831 error = got_object_id_by_path(&id, repo,
13832 commit, argv[i]);
13833 if (error)
13834 break;
13838 error = got_object_get_type(&obj_type, repo, id);
13839 if (error)
13840 break;
13842 switch (obj_type) {
13843 case GOT_OBJ_TYPE_BLOB:
13844 error = cat_blob(id, repo, stdout);
13845 break;
13846 case GOT_OBJ_TYPE_TREE:
13847 error = cat_tree(id, repo, stdout);
13848 break;
13849 case GOT_OBJ_TYPE_COMMIT:
13850 error = cat_commit(id, repo, stdout);
13851 break;
13852 case GOT_OBJ_TYPE_TAG:
13853 error = cat_tag(id, repo, stdout);
13854 break;
13855 default:
13856 error = got_error(GOT_ERR_OBJ_TYPE);
13857 break;
13859 if (error)
13860 break;
13861 free(label);
13862 label = NULL;
13863 free(id);
13864 id = NULL;
13866 done:
13867 free(label);
13868 free(id);
13869 free(commit_id);
13870 if (commit)
13871 got_object_commit_close(commit);
13872 if (worktree)
13873 got_worktree_close(worktree);
13874 if (repo) {
13875 const struct got_error *close_err = got_repo_close(repo);
13876 if (error == NULL)
13877 error = close_err;
13879 if (pack_fds) {
13880 const struct got_error *pack_err =
13881 got_repo_pack_fds_close(pack_fds);
13882 if (error == NULL)
13883 error = pack_err;
13886 got_ref_list_free(&refs);
13887 return error;
13890 __dead static void
13891 usage_info(void)
13893 fprintf(stderr, "usage: %s info [path ...]\n",
13894 getprogname());
13895 exit(1);
13898 static const struct got_error *
13899 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13900 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13901 struct got_object_id *commit_id)
13903 const struct got_error *err = NULL;
13904 char *id_str = NULL;
13905 char datebuf[128];
13906 struct tm mytm, *tm;
13907 struct got_pathlist_head *paths = arg;
13908 struct got_pathlist_entry *pe;
13911 * Clear error indication from any of the path arguments which
13912 * would cause this file index entry to be displayed.
13914 TAILQ_FOREACH(pe, paths, entry) {
13915 if (got_path_cmp(path, pe->path, strlen(path),
13916 pe->path_len) == 0 ||
13917 got_path_is_child(path, pe->path, pe->path_len))
13918 pe->data = NULL; /* no error */
13921 printf(GOT_COMMIT_SEP_STR);
13922 if (S_ISLNK(mode))
13923 printf("symlink: %s\n", path);
13924 else if (S_ISREG(mode)) {
13925 printf("file: %s\n", path);
13926 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13927 } else if (S_ISDIR(mode))
13928 printf("directory: %s\n", path);
13929 else
13930 printf("something: %s\n", path);
13932 tm = localtime_r(&mtime, &mytm);
13933 if (tm == NULL)
13934 return NULL;
13935 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13936 return got_error(GOT_ERR_NO_SPACE);
13937 printf("timestamp: %s\n", datebuf);
13939 if (blob_id) {
13940 err = got_object_id_str(&id_str, blob_id);
13941 if (err)
13942 return err;
13943 printf("based on blob: %s\n", id_str);
13944 free(id_str);
13947 if (staged_blob_id) {
13948 err = got_object_id_str(&id_str, staged_blob_id);
13949 if (err)
13950 return err;
13951 printf("based on staged blob: %s\n", id_str);
13952 free(id_str);
13955 if (commit_id) {
13956 err = got_object_id_str(&id_str, commit_id);
13957 if (err)
13958 return err;
13959 printf("based on commit: %s\n", id_str);
13960 free(id_str);
13963 return NULL;
13966 static const struct got_error *
13967 cmd_info(int argc, char *argv[])
13969 const struct got_error *error = NULL;
13970 struct got_worktree *worktree = NULL;
13971 char *cwd = NULL, *id_str = NULL;
13972 struct got_pathlist_head paths;
13973 char *uuidstr = NULL;
13974 int ch, show_files = 0;
13976 TAILQ_INIT(&paths);
13978 while ((ch = getopt(argc, argv, "")) != -1) {
13979 switch (ch) {
13980 default:
13981 usage_info();
13982 /* NOTREACHED */
13986 argc -= optind;
13987 argv += optind;
13989 #ifndef PROFILE
13990 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13991 NULL) == -1)
13992 err(1, "pledge");
13993 #endif
13994 cwd = getcwd(NULL, 0);
13995 if (cwd == NULL) {
13996 error = got_error_from_errno("getcwd");
13997 goto done;
14000 error = got_worktree_open(&worktree, cwd);
14001 if (error) {
14002 if (error->code == GOT_ERR_NOT_WORKTREE)
14003 error = wrap_not_worktree_error(error, "info", cwd);
14004 goto done;
14007 #ifndef PROFILE
14008 /* Remove "wpath cpath proc exec sendfd" promises. */
14009 if (pledge("stdio rpath flock unveil", NULL) == -1)
14010 err(1, "pledge");
14011 #endif
14012 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14013 if (error)
14014 goto done;
14016 if (argc >= 1) {
14017 error = get_worktree_paths_from_argv(&paths, argc, argv,
14018 worktree);
14019 if (error)
14020 goto done;
14021 show_files = 1;
14024 error = got_object_id_str(&id_str,
14025 got_worktree_get_base_commit_id(worktree));
14026 if (error)
14027 goto done;
14029 error = got_worktree_get_uuid(&uuidstr, worktree);
14030 if (error)
14031 goto done;
14033 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14034 printf("work tree base commit: %s\n", id_str);
14035 printf("work tree path prefix: %s\n",
14036 got_worktree_get_path_prefix(worktree));
14037 printf("work tree branch reference: %s\n",
14038 got_worktree_get_head_ref_name(worktree));
14039 printf("work tree UUID: %s\n", uuidstr);
14040 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14042 if (show_files) {
14043 struct got_pathlist_entry *pe;
14044 TAILQ_FOREACH(pe, &paths, entry) {
14045 if (pe->path_len == 0)
14046 continue;
14048 * Assume this path will fail. This will be corrected
14049 * in print_path_info() in case the path does suceeed.
14051 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14053 error = got_worktree_path_info(worktree, &paths,
14054 print_path_info, &paths, check_cancelled, NULL);
14055 if (error)
14056 goto done;
14057 TAILQ_FOREACH(pe, &paths, entry) {
14058 if (pe->data != NULL) {
14059 const struct got_error *perr;
14061 perr = pe->data;
14062 error = got_error_fmt(perr->code, "%s",
14063 pe->path);
14064 break;
14068 done:
14069 if (worktree)
14070 got_worktree_close(worktree);
14071 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14072 free(cwd);
14073 free(id_str);
14074 free(uuidstr);
14075 return error;