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 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
394 const char *initial_content, size_t initial_content_len,
395 int require_modification)
397 const struct got_error *err = NULL;
398 char *line = NULL;
399 size_t linesize = 0;
400 struct stat st, st2;
401 FILE *fp = NULL;
402 size_t len, logmsg_len;
403 char *initial_content_stripped = NULL, *buf = NULL, *s;
405 *logmsg = NULL;
407 if (stat(logmsg_path, &st) == -1)
408 return got_error_from_errno2("stat", logmsg_path);
410 if (spawn_editor(editor, logmsg_path) == -1)
411 return got_error_from_errno("failed spawning editor");
413 if (stat(logmsg_path, &st2) == -1)
414 return got_error_from_errno("stat");
416 if (require_modification &&
417 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
418 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
419 "no changes made to commit message, aborting");
421 /*
422 * Set up a stripped version of the initial content without comments
423 * and blank lines. We need this in order to check if the message
424 * has in fact been edited.
425 */
426 initial_content_stripped = malloc(initial_content_len + 1);
427 if (initial_content_stripped == NULL)
428 return got_error_from_errno("malloc");
429 initial_content_stripped[0] = '\0';
431 buf = strdup(initial_content);
432 if (buf == NULL) {
433 err = got_error_from_errno("strdup");
434 goto done;
436 s = buf;
437 len = 0;
438 while ((line = strsep(&s, "\n")) != NULL) {
439 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
440 continue; /* remove comments and leading empty lines */
441 len = strlcat(initial_content_stripped, line,
442 initial_content_len + 1);
443 if (len >= initial_content_len + 1) {
444 err = got_error(GOT_ERR_NO_SPACE);
445 goto done;
448 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
449 initial_content_stripped[len - 1] = '\0';
450 len--;
453 logmsg_len = st2.st_size;
454 *logmsg = malloc(logmsg_len + 1);
455 if (*logmsg == NULL)
456 return got_error_from_errno("malloc");
457 (*logmsg)[0] = '\0';
459 fp = fopen(logmsg_path, "re");
460 if (fp == NULL) {
461 err = got_error_from_errno("fopen");
462 goto done;
465 len = 0;
466 while (getline(&line, &linesize, fp) != -1) {
467 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
468 continue; /* remove comments and leading empty lines */
469 len = strlcat(*logmsg, line, logmsg_len + 1);
470 if (len >= logmsg_len + 1) {
471 err = got_error(GOT_ERR_NO_SPACE);
472 goto done;
475 free(line);
476 if (ferror(fp)) {
477 err = got_ferror(fp, GOT_ERR_IO);
478 goto done;
480 while (len > 0 && (*logmsg)[len - 1] == '\n') {
481 (*logmsg)[len - 1] = '\0';
482 len--;
485 if (len == 0) {
486 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
487 "commit message cannot be empty, aborting");
488 goto done;
490 if (require_modification &&
491 strcmp(*logmsg, initial_content_stripped) == 0)
492 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
493 "no changes made to commit message, aborting");
494 done:
495 free(initial_content_stripped);
496 free(buf);
497 if (fp && fclose(fp) == EOF && err == NULL)
498 err = got_error_from_errno("fclose");
499 if (err) {
500 free(*logmsg);
501 *logmsg = NULL;
503 return err;
506 static const struct got_error *
507 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
508 const char *path_dir, const char *branch_name)
510 char *initial_content = NULL;
511 const struct got_error *err = NULL;
512 int initial_content_len;
513 int fd = -1;
515 initial_content_len = asprintf(&initial_content,
516 "\n# %s to be imported to branch %s\n", path_dir,
517 branch_name);
518 if (initial_content_len == -1)
519 return got_error_from_errno("asprintf");
521 err = got_opentemp_named_fd(logmsg_path, &fd,
522 GOT_TMPDIR_STR "/got-importmsg", "");
523 if (err)
524 goto done;
526 if (write(fd, initial_content, initial_content_len) == -1) {
527 err = got_error_from_errno2("write", *logmsg_path);
528 goto done;
531 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
532 initial_content_len, 1);
533 done:
534 if (fd != -1 && close(fd) == -1 && err == NULL)
535 err = got_error_from_errno2("close", *logmsg_path);
536 free(initial_content);
537 if (err) {
538 free(*logmsg_path);
539 *logmsg_path = NULL;
541 return err;
544 static const struct got_error *
545 import_progress(void *arg, const char *path)
547 printf("A %s\n", path);
548 return NULL;
551 static const struct got_error *
552 valid_author(const char *author)
554 const char *email = author;
556 /*
557 * Git' expects the author (or committer) to be in the form
558 * "name <email>", which are mostly free form (see the
559 * "committer" description in git-fast-import(1)). We're only
560 * doing this to avoid git's object parser breaking on commits
561 * we create.
562 */
564 while (*author && *author != '\n' && *author != '<' && *author != '>')
565 author++;
566 if (author != email && *author == '<' && *(author - 1) != ' ')
567 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
568 "between author name and email required", email);
569 if (*author++ != '<')
570 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
571 while (*author && *author != '\n' && *author != '<' && *author != '>')
572 author++;
573 if (strcmp(author, ">") != 0)
574 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
575 return NULL;
578 static const struct got_error *
579 get_author(char **author, struct got_repository *repo,
580 struct got_worktree *worktree)
582 const struct got_error *err = NULL;
583 const char *got_author = NULL, *name, *email;
584 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
586 *author = NULL;
588 if (worktree)
589 worktree_conf = got_worktree_get_gotconfig(worktree);
590 repo_conf = got_repo_get_gotconfig(repo);
592 /*
593 * Priority of potential author information sources, from most
594 * significant to least significant:
595 * 1) work tree's .got/got.conf file
596 * 2) repository's got.conf file
597 * 3) repository's git config file
598 * 4) environment variables
599 * 5) global git config files (in user's home directory or /etc)
600 */
602 if (worktree_conf)
603 got_author = got_gotconfig_get_author(worktree_conf);
604 if (got_author == NULL)
605 got_author = got_gotconfig_get_author(repo_conf);
606 if (got_author == NULL) {
607 name = got_repo_get_gitconfig_author_name(repo);
608 email = got_repo_get_gitconfig_author_email(repo);
609 if (name && email) {
610 if (asprintf(author, "%s <%s>", name, email) == -1)
611 return got_error_from_errno("asprintf");
612 return NULL;
615 got_author = getenv("GOT_AUTHOR");
616 if (got_author == NULL) {
617 name = got_repo_get_global_gitconfig_author_name(repo);
618 email = got_repo_get_global_gitconfig_author_email(
619 repo);
620 if (name && email) {
621 if (asprintf(author, "%s <%s>", name, email)
622 == -1)
623 return got_error_from_errno("asprintf");
624 return NULL;
626 /* TODO: Look up user in password database? */
627 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
631 *author = strdup(got_author);
632 if (*author == NULL)
633 return got_error_from_errno("strdup");
635 err = valid_author(*author);
636 if (err) {
637 free(*author);
638 *author = NULL;
640 return err;
643 static const struct got_error *
644 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
645 struct got_worktree *worktree)
647 const char *got_allowed_signers = NULL;
648 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
650 *allowed_signers = NULL;
652 if (worktree)
653 worktree_conf = got_worktree_get_gotconfig(worktree);
654 repo_conf = got_repo_get_gotconfig(repo);
656 /*
657 * Priority of potential author information sources, from most
658 * significant to least significant:
659 * 1) work tree's .got/got.conf file
660 * 2) repository's got.conf file
661 */
663 if (worktree_conf)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 worktree_conf);
666 if (got_allowed_signers == NULL)
667 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
668 repo_conf);
670 if (got_allowed_signers) {
671 *allowed_signers = strdup(got_allowed_signers);
672 if (*allowed_signers == NULL)
673 return got_error_from_errno("strdup");
675 return NULL;
678 static const struct got_error *
679 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
680 struct got_worktree *worktree)
682 const char *got_revoked_signers = NULL;
683 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
685 *revoked_signers = NULL;
687 if (worktree)
688 worktree_conf = got_worktree_get_gotconfig(worktree);
689 repo_conf = got_repo_get_gotconfig(repo);
691 /*
692 * Priority of potential author information sources, from most
693 * significant to least significant:
694 * 1) work tree's .got/got.conf file
695 * 2) repository's got.conf file
696 */
698 if (worktree_conf)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 worktree_conf);
701 if (got_revoked_signers == NULL)
702 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
703 repo_conf);
705 if (got_revoked_signers) {
706 *revoked_signers = strdup(got_revoked_signers);
707 if (*revoked_signers == NULL)
708 return got_error_from_errno("strdup");
710 return NULL;
713 static const char *
714 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
716 const char *got_signer_id = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 if (worktree)
720 worktree_conf = got_worktree_get_gotconfig(worktree);
721 repo_conf = got_repo_get_gotconfig(repo);
723 /*
724 * Priority of potential author information sources, from most
725 * significant to least significant:
726 * 1) work tree's .got/got.conf file
727 * 2) repository's got.conf file
728 */
730 if (worktree_conf)
731 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
732 if (got_signer_id == NULL)
733 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
735 return got_signer_id;
738 static const struct got_error *
739 get_gitconfig_path(char **gitconfig_path)
741 const char *homedir = getenv("HOME");
743 *gitconfig_path = NULL;
744 if (homedir) {
745 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
746 return got_error_from_errno("asprintf");
749 return NULL;
752 static const struct got_error *
753 cmd_import(int argc, char *argv[])
755 const struct got_error *error = NULL;
756 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
757 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
758 const char *branch_name = NULL;
759 char *id_str = NULL, *logmsg_path = NULL;
760 char refname[PATH_MAX] = "refs/heads/";
761 struct got_repository *repo = NULL;
762 struct got_reference *branch_ref = NULL, *head_ref = NULL;
763 struct got_object_id *new_commit_id = NULL;
764 int ch, n = 0;
765 struct got_pathlist_head ignores;
766 struct got_pathlist_entry *pe;
767 int preserve_logmsg = 0;
768 int *pack_fds = NULL;
770 TAILQ_INIT(&ignores);
772 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
773 switch (ch) {
774 case 'b':
775 branch_name = optarg;
776 break;
777 case 'I':
778 if (optarg[0] == '\0')
779 break;
780 error = got_pathlist_insert(&pe, &ignores, optarg,
781 NULL);
782 if (error)
783 goto done;
784 break;
785 case 'm':
786 logmsg = strdup(optarg);
787 if (logmsg == NULL) {
788 error = got_error_from_errno("strdup");
789 goto done;
791 break;
792 case 'r':
793 repo_path = realpath(optarg, NULL);
794 if (repo_path == NULL) {
795 error = got_error_from_errno2("realpath",
796 optarg);
797 goto done;
799 break;
800 default:
801 usage_import();
802 /* NOTREACHED */
806 argc -= optind;
807 argv += optind;
809 #ifndef PROFILE
810 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
811 "unveil",
812 NULL) == -1)
813 err(1, "pledge");
814 #endif
815 if (argc != 1)
816 usage_import();
818 if (repo_path == NULL) {
819 repo_path = getcwd(NULL, 0);
820 if (repo_path == NULL)
821 return got_error_from_errno("getcwd");
823 got_path_strip_trailing_slashes(repo_path);
824 error = get_gitconfig_path(&gitconfig_path);
825 if (error)
826 goto done;
827 error = got_repo_pack_fds_open(&pack_fds);
828 if (error != NULL)
829 goto done;
830 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
831 if (error)
832 goto done;
834 error = get_author(&author, repo, NULL);
835 if (error)
836 return error;
838 /*
839 * Don't let the user create a branch name with a leading '-'.
840 * While technically a valid reference name, this case is usually
841 * an unintended typo.
842 */
843 if (branch_name && branch_name[0] == '-')
844 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
846 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
847 if (error && error->code != GOT_ERR_NOT_REF)
848 goto done;
850 if (branch_name)
851 n = strlcat(refname, branch_name, sizeof(refname));
852 else if (head_ref && got_ref_is_symbolic(head_ref))
853 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
854 sizeof(refname));
855 else
856 n = strlcat(refname, "main", sizeof(refname));
857 if (n >= sizeof(refname)) {
858 error = got_error(GOT_ERR_NO_SPACE);
859 goto done;
862 error = got_ref_open(&branch_ref, repo, refname, 0);
863 if (error) {
864 if (error->code != GOT_ERR_NOT_REF)
865 goto done;
866 } else {
867 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
868 "import target branch already exists");
869 goto done;
872 path_dir = realpath(argv[0], NULL);
873 if (path_dir == NULL) {
874 error = got_error_from_errno2("realpath", argv[0]);
875 goto done;
877 got_path_strip_trailing_slashes(path_dir);
879 /*
880 * unveil(2) traverses exec(2); if an editor is used we have
881 * to apply unveil after the log message has been written.
882 */
883 if (logmsg == NULL || strlen(logmsg) == 0) {
884 error = get_editor(&editor);
885 if (error)
886 goto done;
887 free(logmsg);
888 error = collect_import_msg(&logmsg, &logmsg_path, editor,
889 path_dir, refname);
890 if (error) {
891 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
892 logmsg_path != NULL)
893 preserve_logmsg = 1;
894 goto done;
898 if (unveil(path_dir, "r") != 0) {
899 error = got_error_from_errno2("unveil", path_dir);
900 if (logmsg_path)
901 preserve_logmsg = 1;
902 goto done;
905 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
906 if (error) {
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = got_repo_import(&new_commit_id, path_dir, logmsg,
913 author, &ignores, repo, import_progress, NULL);
914 if (error) {
915 if (logmsg_path)
916 preserve_logmsg = 1;
917 goto done;
920 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_write(branch_ref, repo);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_object_id_str(&id_str, new_commit_id);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
942 if (error) {
943 if (error->code != GOT_ERR_NOT_REF) {
944 if (logmsg_path)
945 preserve_logmsg = 1;
946 goto done;
949 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
950 branch_ref);
951 if (error) {
952 if (logmsg_path)
953 preserve_logmsg = 1;
954 goto done;
957 error = got_ref_write(head_ref, repo);
958 if (error) {
959 if (logmsg_path)
960 preserve_logmsg = 1;
961 goto done;
965 printf("Created branch %s with commit %s\n",
966 got_ref_get_name(branch_ref), id_str);
967 done:
968 if (pack_fds) {
969 const struct got_error *pack_err =
970 got_repo_pack_fds_close(pack_fds);
971 if (error == NULL)
972 error = pack_err;
974 if (preserve_logmsg) {
975 fprintf(stderr, "%s: log message preserved in %s\n",
976 getprogname(), logmsg_path);
977 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
978 error = got_error_from_errno2("unlink", logmsg_path);
979 free(logmsg);
980 free(logmsg_path);
981 free(repo_path);
982 free(editor);
983 free(new_commit_id);
984 free(id_str);
985 free(author);
986 free(gitconfig_path);
987 if (branch_ref)
988 got_ref_close(branch_ref);
989 if (head_ref)
990 got_ref_close(head_ref);
991 return error;
994 __dead static void
995 usage_clone(void)
997 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
998 "repository-URL [directory]\n", getprogname());
999 exit(1);
1002 struct got_fetch_progress_arg {
1003 char last_scaled_size[FMT_SCALED_STRSIZE];
1004 int last_p_indexed;
1005 int last_p_resolved;
1006 int verbosity;
1008 struct got_repository *repo;
1010 int create_configs;
1011 int configs_created;
1012 struct {
1013 struct got_pathlist_head *symrefs;
1014 struct got_pathlist_head *wanted_branches;
1015 struct got_pathlist_head *wanted_refs;
1016 const char *proto;
1017 const char *host;
1018 const char *port;
1019 const char *remote_repo_path;
1020 const char *git_url;
1021 int fetch_all_branches;
1022 int mirror_references;
1023 } config_info;
1026 /* XXX forward declaration */
1027 static const struct got_error *
1028 create_config_files(const char *proto, const char *host, const char *port,
1029 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1030 int mirror_references, struct got_pathlist_head *symrefs,
1031 struct got_pathlist_head *wanted_branches,
1032 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1034 static const struct got_error *
1035 fetch_progress(void *arg, const char *message, off_t packfile_size,
1036 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1038 const struct got_error *err = NULL;
1039 struct got_fetch_progress_arg *a = arg;
1040 char scaled_size[FMT_SCALED_STRSIZE];
1041 int p_indexed, p_resolved;
1042 int print_size = 0, print_indexed = 0, print_resolved = 0;
1045 * In order to allow a failed clone to be resumed with 'got fetch'
1046 * we try to create configuration files as soon as possible.
1047 * Once the server has sent information about its default branch
1048 * we have all required information.
1050 if (a->create_configs && !a->configs_created &&
1051 !TAILQ_EMPTY(a->config_info.symrefs)) {
1052 err = create_config_files(a->config_info.proto,
1053 a->config_info.host, a->config_info.port,
1054 a->config_info.remote_repo_path,
1055 a->config_info.git_url,
1056 a->config_info.fetch_all_branches,
1057 a->config_info.mirror_references,
1058 a->config_info.symrefs,
1059 a->config_info.wanted_branches,
1060 a->config_info.wanted_refs, a->repo);
1061 if (err)
1062 return err;
1063 a->configs_created = 1;
1066 if (a->verbosity < 0)
1067 return NULL;
1069 if (message && message[0] != '\0') {
1070 printf("\rserver: %s", message);
1071 fflush(stdout);
1072 return NULL;
1075 if (packfile_size > 0 || nobj_indexed > 0) {
1076 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1077 (a->last_scaled_size[0] == '\0' ||
1078 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1079 print_size = 1;
1080 if (strlcpy(a->last_scaled_size, scaled_size,
1081 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1082 return got_error(GOT_ERR_NO_SPACE);
1084 if (nobj_indexed > 0) {
1085 p_indexed = (nobj_indexed * 100) / nobj_total;
1086 if (p_indexed != a->last_p_indexed) {
1087 a->last_p_indexed = p_indexed;
1088 print_indexed = 1;
1089 print_size = 1;
1092 if (nobj_resolved > 0) {
1093 p_resolved = (nobj_resolved * 100) /
1094 (nobj_total - nobj_loose);
1095 if (p_resolved != a->last_p_resolved) {
1096 a->last_p_resolved = p_resolved;
1097 print_resolved = 1;
1098 print_indexed = 1;
1099 print_size = 1;
1104 if (print_size || print_indexed || print_resolved)
1105 printf("\r");
1106 if (print_size)
1107 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1108 if (print_indexed)
1109 printf("; indexing %d%%", p_indexed);
1110 if (print_resolved)
1111 printf("; resolving deltas %d%%", p_resolved);
1112 if (print_size || print_indexed || print_resolved)
1113 fflush(stdout);
1115 return NULL;
1118 static const struct got_error *
1119 create_symref(const char *refname, struct got_reference *target_ref,
1120 int verbosity, struct got_repository *repo)
1122 const struct got_error *err;
1123 struct got_reference *head_symref;
1125 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1126 if (err)
1127 return err;
1129 err = got_ref_write(head_symref, repo);
1130 if (err == NULL && verbosity > 0) {
1131 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1132 got_ref_get_name(target_ref));
1134 got_ref_close(head_symref);
1135 return err;
1138 static const struct got_error *
1139 list_remote_refs(struct got_pathlist_head *symrefs,
1140 struct got_pathlist_head *refs)
1142 const struct got_error *err;
1143 struct got_pathlist_entry *pe;
1145 TAILQ_FOREACH(pe, symrefs, entry) {
1146 const char *refname = pe->path;
1147 const char *targetref = pe->data;
1149 printf("%s: %s\n", refname, targetref);
1152 TAILQ_FOREACH(pe, refs, entry) {
1153 const char *refname = pe->path;
1154 struct got_object_id *id = pe->data;
1155 char *id_str;
1157 err = got_object_id_str(&id_str, id);
1158 if (err)
1159 return err;
1160 printf("%s: %s\n", refname, id_str);
1161 free(id_str);
1164 return NULL;
1167 static const struct got_error *
1168 create_ref(const char *refname, struct got_object_id *id,
1169 int verbosity, struct got_repository *repo)
1171 const struct got_error *err = NULL;
1172 struct got_reference *ref;
1173 char *id_str;
1175 err = got_object_id_str(&id_str, id);
1176 if (err)
1177 return err;
1179 err = got_ref_alloc(&ref, refname, id);
1180 if (err)
1181 goto done;
1183 err = got_ref_write(ref, repo);
1184 got_ref_close(ref);
1186 if (err == NULL && verbosity >= 0)
1187 printf("Created reference %s: %s\n", refname, id_str);
1188 done:
1189 free(id_str);
1190 return err;
1193 static int
1194 match_wanted_ref(const char *refname, const char *wanted_ref)
1196 if (strncmp(refname, "refs/", 5) != 0)
1197 return 0;
1198 refname += 5;
1201 * Prevent fetching of references that won't make any
1202 * sense outside of the remote repository's context.
1204 if (strncmp(refname, "got/", 4) == 0)
1205 return 0;
1206 if (strncmp(refname, "remotes/", 8) == 0)
1207 return 0;
1209 if (strncmp(wanted_ref, "refs/", 5) == 0)
1210 wanted_ref += 5;
1212 /* Allow prefix match. */
1213 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1214 return 1;
1216 /* Allow exact match. */
1217 return (strcmp(refname, wanted_ref) == 0);
1220 static int
1221 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1223 struct got_pathlist_entry *pe;
1225 TAILQ_FOREACH(pe, wanted_refs, entry) {
1226 if (match_wanted_ref(refname, pe->path))
1227 return 1;
1230 return 0;
1233 static const struct got_error *
1234 create_wanted_ref(const char *refname, struct got_object_id *id,
1235 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1237 const struct got_error *err;
1238 char *remote_refname;
1240 if (strncmp("refs/", refname, 5) == 0)
1241 refname += 5;
1243 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1244 remote_repo_name, refname) == -1)
1245 return got_error_from_errno("asprintf");
1247 err = create_ref(remote_refname, id, verbosity, repo);
1248 free(remote_refname);
1249 return err;
1252 static const struct got_error *
1253 create_gotconfig(const char *proto, const char *host, const char *port,
1254 const char *remote_repo_path, const char *default_branch,
1255 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1256 struct got_pathlist_head *wanted_refs, int mirror_references,
1257 struct got_repository *repo)
1259 const struct got_error *err = NULL;
1260 char *gotconfig_path = NULL;
1261 char *gotconfig = NULL;
1262 FILE *gotconfig_file = NULL;
1263 const char *branchname = NULL;
1264 char *branches = NULL, *refs = NULL;
1265 ssize_t n;
1267 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1268 struct got_pathlist_entry *pe;
1269 TAILQ_FOREACH(pe, wanted_branches, entry) {
1270 char *s;
1271 branchname = pe->path;
1272 if (strncmp(branchname, "refs/heads/", 11) == 0)
1273 branchname += 11;
1274 if (asprintf(&s, "%s\"%s\" ",
1275 branches ? branches : "", branchname) == -1) {
1276 err = got_error_from_errno("asprintf");
1277 goto done;
1279 free(branches);
1280 branches = s;
1282 } else if (!fetch_all_branches && default_branch) {
1283 branchname = default_branch;
1284 if (strncmp(branchname, "refs/heads/", 11) == 0)
1285 branchname += 11;
1286 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1287 err = got_error_from_errno("asprintf");
1288 goto done;
1291 if (!TAILQ_EMPTY(wanted_refs)) {
1292 struct got_pathlist_entry *pe;
1293 TAILQ_FOREACH(pe, wanted_refs, entry) {
1294 char *s;
1295 const char *refname = pe->path;
1296 if (strncmp(refname, "refs/", 5) == 0)
1297 branchname += 5;
1298 if (asprintf(&s, "%s\"%s\" ",
1299 refs ? refs : "", refname) == -1) {
1300 err = got_error_from_errno("asprintf");
1301 goto done;
1303 free(refs);
1304 refs = s;
1308 /* Create got.conf(5). */
1309 gotconfig_path = got_repo_get_path_gotconfig(repo);
1310 if (gotconfig_path == NULL) {
1311 err = got_error_from_errno("got_repo_get_path_gotconfig");
1312 goto done;
1314 gotconfig_file = fopen(gotconfig_path, "ae");
1315 if (gotconfig_file == NULL) {
1316 err = got_error_from_errno2("fopen", gotconfig_path);
1317 goto done;
1319 if (asprintf(&gotconfig,
1320 "remote \"%s\" {\n"
1321 "\tserver %s\n"
1322 "\tprotocol %s\n"
1323 "%s%s%s"
1324 "\trepository \"%s\"\n"
1325 "%s%s%s"
1326 "%s%s%s"
1327 "%s"
1328 "%s"
1329 "}\n",
1330 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1331 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1332 remote_repo_path, branches ? "\tbranch { " : "",
1333 branches ? branches : "", branches ? "}\n" : "",
1334 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1335 mirror_references ? "\tmirror_references yes\n" : "",
1336 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1337 err = got_error_from_errno("asprintf");
1338 goto done;
1340 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1341 if (n != strlen(gotconfig)) {
1342 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1343 goto done;
1346 done:
1347 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1348 err = got_error_from_errno2("fclose", gotconfig_path);
1349 free(gotconfig_path);
1350 free(branches);
1351 return err;
1354 static const struct got_error *
1355 create_gitconfig(const char *git_url, const char *default_branch,
1356 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1357 struct got_pathlist_head *wanted_refs, int mirror_references,
1358 struct got_repository *repo)
1360 const struct got_error *err = NULL;
1361 char *gitconfig_path = NULL;
1362 char *gitconfig = NULL;
1363 FILE *gitconfig_file = NULL;
1364 char *branches = NULL, *refs = NULL;
1365 const char *branchname;
1366 ssize_t n;
1368 /* Create a config file Git can understand. */
1369 gitconfig_path = got_repo_get_path_gitconfig(repo);
1370 if (gitconfig_path == NULL) {
1371 err = got_error_from_errno("got_repo_get_path_gitconfig");
1372 goto done;
1374 gitconfig_file = fopen(gitconfig_path, "ae");
1375 if (gitconfig_file == NULL) {
1376 err = got_error_from_errno2("fopen", gitconfig_path);
1377 goto done;
1379 if (fetch_all_branches) {
1380 if (mirror_references) {
1381 if (asprintf(&branches,
1382 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1383 err = got_error_from_errno("asprintf");
1384 goto done;
1386 } else if (asprintf(&branches,
1387 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1388 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1389 err = got_error_from_errno("asprintf");
1390 goto done;
1392 } else if (!TAILQ_EMPTY(wanted_branches)) {
1393 struct got_pathlist_entry *pe;
1394 TAILQ_FOREACH(pe, wanted_branches, entry) {
1395 char *s;
1396 branchname = pe->path;
1397 if (strncmp(branchname, "refs/heads/", 11) == 0)
1398 branchname += 11;
1399 if (mirror_references) {
1400 if (asprintf(&s,
1401 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1402 branches ? branches : "",
1403 branchname, branchname) == -1) {
1404 err = got_error_from_errno("asprintf");
1405 goto done;
1407 } else if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1409 branches ? branches : "",
1410 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1411 branchname) == -1) {
1412 err = got_error_from_errno("asprintf");
1413 goto done;
1415 free(branches);
1416 branches = s;
1418 } else {
1420 * If the server specified a default branch, use just that one.
1421 * Otherwise fall back to fetching all branches on next fetch.
1423 if (default_branch) {
1424 branchname = default_branch;
1425 if (strncmp(branchname, "refs/heads/", 11) == 0)
1426 branchname += 11;
1427 } else
1428 branchname = "*"; /* fall back to all branches */
1429 if (mirror_references) {
1430 if (asprintf(&branches,
1431 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1432 branchname, branchname) == -1) {
1433 err = got_error_from_errno("asprintf");
1434 goto done;
1436 } else if (asprintf(&branches,
1437 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1438 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1439 branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1444 if (!TAILQ_EMPTY(wanted_refs)) {
1445 struct got_pathlist_entry *pe;
1446 TAILQ_FOREACH(pe, wanted_refs, entry) {
1447 char *s;
1448 const char *refname = pe->path;
1449 if (strncmp(refname, "refs/", 5) == 0)
1450 refname += 5;
1451 if (mirror_references) {
1452 if (asprintf(&s,
1453 "%s\tfetch = refs/%s:refs/%s\n",
1454 refs ? refs : "", refname, refname) == -1) {
1455 err = got_error_from_errno("asprintf");
1456 goto done;
1458 } else if (asprintf(&s,
1459 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1460 refs ? refs : "",
1461 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1462 refname) == -1) {
1463 err = got_error_from_errno("asprintf");
1464 goto done;
1466 free(refs);
1467 refs = s;
1471 if (asprintf(&gitconfig,
1472 "[remote \"%s\"]\n"
1473 "\turl = %s\n"
1474 "%s"
1475 "%s"
1476 "\tfetch = refs/tags/*:refs/tags/*\n",
1477 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1478 refs ? refs : "") == -1) {
1479 err = got_error_from_errno("asprintf");
1480 goto done;
1482 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1483 if (n != strlen(gitconfig)) {
1484 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1485 goto done;
1487 done:
1488 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1489 err = got_error_from_errno2("fclose", gitconfig_path);
1490 free(gitconfig_path);
1491 free(branches);
1492 return err;
1495 static const struct got_error *
1496 create_config_files(const char *proto, const char *host, const char *port,
1497 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1498 int mirror_references, struct got_pathlist_head *symrefs,
1499 struct got_pathlist_head *wanted_branches,
1500 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1502 const struct got_error *err = NULL;
1503 const char *default_branch = NULL;
1504 struct got_pathlist_entry *pe;
1507 * If we asked for a set of wanted branches then use the first
1508 * one of those.
1510 if (!TAILQ_EMPTY(wanted_branches)) {
1511 pe = TAILQ_FIRST(wanted_branches);
1512 default_branch = pe->path;
1513 } else {
1514 /* First HEAD ref listed by server is the default branch. */
1515 TAILQ_FOREACH(pe, symrefs, entry) {
1516 const char *refname = pe->path;
1517 const char *target = pe->data;
1519 if (strcmp(refname, GOT_REF_HEAD) != 0)
1520 continue;
1522 default_branch = target;
1523 break;
1527 /* Create got.conf(5). */
1528 err = create_gotconfig(proto, host, port, remote_repo_path,
1529 default_branch, fetch_all_branches, wanted_branches,
1530 wanted_refs, mirror_references, repo);
1531 if (err)
1532 return err;
1534 /* Create a config file Git can understand. */
1535 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1536 wanted_branches, wanted_refs, mirror_references, repo);
1539 static const struct got_error *
1540 cmd_clone(int argc, char *argv[])
1542 const struct got_error *error = NULL;
1543 const char *uri, *dirname;
1544 char *proto, *host, *port, *repo_name, *server_path;
1545 char *default_destdir = NULL, *id_str = NULL;
1546 const char *repo_path;
1547 struct got_repository *repo = NULL;
1548 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1549 struct got_pathlist_entry *pe;
1550 struct got_object_id *pack_hash = NULL;
1551 int ch, fetchfd = -1, fetchstatus;
1552 pid_t fetchpid = -1;
1553 struct got_fetch_progress_arg fpa;
1554 char *git_url = NULL;
1555 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1556 int list_refs_only = 0;
1557 int *pack_fds = NULL;
1559 TAILQ_INIT(&refs);
1560 TAILQ_INIT(&symrefs);
1561 TAILQ_INIT(&wanted_branches);
1562 TAILQ_INIT(&wanted_refs);
1564 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1565 switch (ch) {
1566 case 'a':
1567 fetch_all_branches = 1;
1568 break;
1569 case 'b':
1570 error = got_pathlist_append(&wanted_branches,
1571 optarg, NULL);
1572 if (error)
1573 return error;
1574 break;
1575 case 'l':
1576 list_refs_only = 1;
1577 break;
1578 case 'm':
1579 mirror_references = 1;
1580 break;
1581 case 'q':
1582 verbosity = -1;
1583 break;
1584 case 'R':
1585 error = got_pathlist_append(&wanted_refs,
1586 optarg, NULL);
1587 if (error)
1588 return error;
1589 break;
1590 case 'v':
1591 if (verbosity < 0)
1592 verbosity = 0;
1593 else if (verbosity < 3)
1594 verbosity++;
1595 break;
1596 default:
1597 usage_clone();
1598 break;
1601 argc -= optind;
1602 argv += optind;
1604 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1605 option_conflict('a', 'b');
1606 if (list_refs_only) {
1607 if (!TAILQ_EMPTY(&wanted_branches))
1608 option_conflict('l', 'b');
1609 if (fetch_all_branches)
1610 option_conflict('l', 'a');
1611 if (mirror_references)
1612 option_conflict('l', 'm');
1613 if (!TAILQ_EMPTY(&wanted_refs))
1614 option_conflict('l', 'R');
1617 uri = argv[0];
1619 if (argc == 1)
1620 dirname = NULL;
1621 else if (argc == 2)
1622 dirname = argv[1];
1623 else
1624 usage_clone();
1626 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1627 &repo_name, uri);
1628 if (error)
1629 goto done;
1631 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1632 host, port ? ":" : "", port ? port : "",
1633 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1634 error = got_error_from_errno("asprintf");
1635 goto done;
1638 if (strcmp(proto, "git") == 0) {
1639 #ifndef PROFILE
1640 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1641 "sendfd dns inet unveil", NULL) == -1)
1642 err(1, "pledge");
1643 #endif
1644 } else if (strcmp(proto, "git+ssh") == 0 ||
1645 strcmp(proto, "ssh") == 0) {
1646 #ifndef PROFILE
1647 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1648 "sendfd unveil", NULL) == -1)
1649 err(1, "pledge");
1650 #endif
1651 } else if (strcmp(proto, "http") == 0 ||
1652 strcmp(proto, "git+http") == 0) {
1653 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1654 goto done;
1655 } else {
1656 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1657 goto done;
1659 if (dirname == NULL) {
1660 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1661 error = got_error_from_errno("asprintf");
1662 goto done;
1664 repo_path = default_destdir;
1665 } else
1666 repo_path = dirname;
1668 if (!list_refs_only) {
1669 error = got_path_mkdir(repo_path);
1670 if (error &&
1671 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1672 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1673 goto done;
1674 if (!got_path_dir_is_empty(repo_path)) {
1675 error = got_error_path(repo_path,
1676 GOT_ERR_DIR_NOT_EMPTY);
1677 goto done;
1681 error = got_dial_apply_unveil(proto);
1682 if (error)
1683 goto done;
1685 error = apply_unveil(repo_path, 0, NULL);
1686 if (error)
1687 goto done;
1689 if (verbosity >= 0)
1690 printf("Connecting to %s\n", git_url);
1692 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1693 server_path, verbosity);
1694 if (error)
1695 goto done;
1697 if (!list_refs_only) {
1698 error = got_repo_init(repo_path, NULL);
1699 if (error)
1700 goto done;
1701 error = got_repo_pack_fds_open(&pack_fds);
1702 if (error != NULL)
1703 goto done;
1704 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1705 if (error)
1706 goto done;
1709 fpa.last_scaled_size[0] = '\0';
1710 fpa.last_p_indexed = -1;
1711 fpa.last_p_resolved = -1;
1712 fpa.verbosity = verbosity;
1713 fpa.create_configs = 1;
1714 fpa.configs_created = 0;
1715 fpa.repo = repo;
1716 fpa.config_info.symrefs = &symrefs;
1717 fpa.config_info.wanted_branches = &wanted_branches;
1718 fpa.config_info.wanted_refs = &wanted_refs;
1719 fpa.config_info.proto = proto;
1720 fpa.config_info.host = host;
1721 fpa.config_info.port = port;
1722 fpa.config_info.remote_repo_path = server_path;
1723 fpa.config_info.git_url = git_url;
1724 fpa.config_info.fetch_all_branches = fetch_all_branches;
1725 fpa.config_info.mirror_references = mirror_references;
1726 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1727 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1728 fetch_all_branches, &wanted_branches, &wanted_refs,
1729 list_refs_only, verbosity, fetchfd, repo,
1730 fetch_progress, &fpa);
1731 if (error)
1732 goto done;
1734 if (list_refs_only) {
1735 error = list_remote_refs(&symrefs, &refs);
1736 goto done;
1739 if (pack_hash == NULL) {
1740 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1741 "server sent an empty pack file");
1742 goto done;
1744 error = got_object_id_str(&id_str, pack_hash);
1745 if (error)
1746 goto done;
1747 if (verbosity >= 0)
1748 printf("\nFetched %s.pack\n", id_str);
1749 free(id_str);
1751 /* Set up references provided with the pack file. */
1752 TAILQ_FOREACH(pe, &refs, entry) {
1753 const char *refname = pe->path;
1754 struct got_object_id *id = pe->data;
1755 char *remote_refname;
1757 if (is_wanted_ref(&wanted_refs, refname) &&
1758 !mirror_references) {
1759 error = create_wanted_ref(refname, id,
1760 GOT_FETCH_DEFAULT_REMOTE_NAME,
1761 verbosity - 1, repo);
1762 if (error)
1763 goto done;
1764 continue;
1767 error = create_ref(refname, id, verbosity - 1, repo);
1768 if (error)
1769 goto done;
1771 if (mirror_references)
1772 continue;
1774 if (strncmp("refs/heads/", refname, 11) != 0)
1775 continue;
1777 if (asprintf(&remote_refname,
1778 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1779 refname + 11) == -1) {
1780 error = got_error_from_errno("asprintf");
1781 goto done;
1783 error = create_ref(remote_refname, id, verbosity - 1, repo);
1784 free(remote_refname);
1785 if (error)
1786 goto done;
1789 /* Set the HEAD reference if the server provided one. */
1790 TAILQ_FOREACH(pe, &symrefs, entry) {
1791 struct got_reference *target_ref;
1792 const char *refname = pe->path;
1793 const char *target = pe->data;
1794 char *remote_refname = NULL, *remote_target = NULL;
1796 if (strcmp(refname, GOT_REF_HEAD) != 0)
1797 continue;
1799 error = got_ref_open(&target_ref, repo, target, 0);
1800 if (error) {
1801 if (error->code == GOT_ERR_NOT_REF) {
1802 error = NULL;
1803 continue;
1805 goto done;
1808 error = create_symref(refname, target_ref, verbosity, repo);
1809 got_ref_close(target_ref);
1810 if (error)
1811 goto done;
1813 if (mirror_references)
1814 continue;
1816 if (strncmp("refs/heads/", target, 11) != 0)
1817 continue;
1819 if (asprintf(&remote_refname,
1820 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1821 refname) == -1) {
1822 error = got_error_from_errno("asprintf");
1823 goto done;
1825 if (asprintf(&remote_target,
1826 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1827 target + 11) == -1) {
1828 error = got_error_from_errno("asprintf");
1829 free(remote_refname);
1830 goto done;
1832 error = got_ref_open(&target_ref, repo, remote_target, 0);
1833 if (error) {
1834 free(remote_refname);
1835 free(remote_target);
1836 if (error->code == GOT_ERR_NOT_REF) {
1837 error = NULL;
1838 continue;
1840 goto done;
1842 error = create_symref(remote_refname, target_ref,
1843 verbosity - 1, repo);
1844 free(remote_refname);
1845 free(remote_target);
1846 got_ref_close(target_ref);
1847 if (error)
1848 goto done;
1850 if (pe == NULL) {
1852 * We failed to set the HEAD reference. If we asked for
1853 * a set of wanted branches use the first of one of those
1854 * which could be fetched instead.
1856 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1857 const char *target = pe->path;
1858 struct got_reference *target_ref;
1860 error = got_ref_open(&target_ref, repo, target, 0);
1861 if (error) {
1862 if (error->code == GOT_ERR_NOT_REF) {
1863 error = NULL;
1864 continue;
1866 goto done;
1869 error = create_symref(GOT_REF_HEAD, target_ref,
1870 verbosity, repo);
1871 got_ref_close(target_ref);
1872 if (error)
1873 goto done;
1874 break;
1877 if (!fpa.configs_created && pe != NULL) {
1878 error = create_config_files(fpa.config_info.proto,
1879 fpa.config_info.host, fpa.config_info.port,
1880 fpa.config_info.remote_repo_path,
1881 fpa.config_info.git_url,
1882 fpa.config_info.fetch_all_branches,
1883 fpa.config_info.mirror_references,
1884 fpa.config_info.symrefs,
1885 fpa.config_info.wanted_branches,
1886 fpa.config_info.wanted_refs, fpa.repo);
1887 if (error)
1888 goto done;
1892 if (verbosity >= 0)
1893 printf("Created %s repository '%s'\n",
1894 mirror_references ? "mirrored" : "cloned", repo_path);
1895 done:
1896 if (pack_fds) {
1897 const struct got_error *pack_err =
1898 got_repo_pack_fds_close(pack_fds);
1899 if (error == NULL)
1900 error = pack_err;
1902 if (fetchpid > 0) {
1903 if (kill(fetchpid, SIGTERM) == -1)
1904 error = got_error_from_errno("kill");
1905 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1906 error = got_error_from_errno("waitpid");
1908 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1909 error = got_error_from_errno("close");
1910 if (repo) {
1911 const struct got_error *close_err = got_repo_close(repo);
1912 if (error == NULL)
1913 error = close_err;
1915 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1916 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1917 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1918 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1919 free(pack_hash);
1920 free(proto);
1921 free(host);
1922 free(port);
1923 free(server_path);
1924 free(repo_name);
1925 free(default_destdir);
1926 free(git_url);
1927 return error;
1930 static const struct got_error *
1931 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1932 int replace_tags, int verbosity, struct got_repository *repo)
1934 const struct got_error *err = NULL;
1935 char *new_id_str = NULL;
1936 struct got_object_id *old_id = NULL;
1938 err = got_object_id_str(&new_id_str, new_id);
1939 if (err)
1940 goto done;
1942 if (!replace_tags &&
1943 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1944 err = got_ref_resolve(&old_id, repo, ref);
1945 if (err)
1946 goto done;
1947 if (got_object_id_cmp(old_id, new_id) == 0)
1948 goto done;
1949 if (verbosity >= 0) {
1950 printf("Rejecting update of existing tag %s: %s\n",
1951 got_ref_get_name(ref), new_id_str);
1953 goto done;
1956 if (got_ref_is_symbolic(ref)) {
1957 if (verbosity >= 0) {
1958 printf("Replacing reference %s: %s\n",
1959 got_ref_get_name(ref),
1960 got_ref_get_symref_target(ref));
1962 err = got_ref_change_symref_to_ref(ref, new_id);
1963 if (err)
1964 goto done;
1965 err = got_ref_write(ref, repo);
1966 if (err)
1967 goto done;
1968 } else {
1969 err = got_ref_resolve(&old_id, repo, ref);
1970 if (err)
1971 goto done;
1972 if (got_object_id_cmp(old_id, new_id) == 0)
1973 goto done;
1975 err = got_ref_change_ref(ref, new_id);
1976 if (err)
1977 goto done;
1978 err = got_ref_write(ref, repo);
1979 if (err)
1980 goto done;
1983 if (verbosity >= 0)
1984 printf("Updated %s: %s\n", got_ref_get_name(ref),
1985 new_id_str);
1986 done:
1987 free(old_id);
1988 free(new_id_str);
1989 return err;
1992 static const struct got_error *
1993 update_symref(const char *refname, struct got_reference *target_ref,
1994 int verbosity, struct got_repository *repo)
1996 const struct got_error *err = NULL, *unlock_err;
1997 struct got_reference *symref;
1998 int symref_is_locked = 0;
2000 err = got_ref_open(&symref, repo, refname, 1);
2001 if (err) {
2002 if (err->code != GOT_ERR_NOT_REF)
2003 return err;
2004 err = got_ref_alloc_symref(&symref, refname, target_ref);
2005 if (err)
2006 goto done;
2008 err = got_ref_write(symref, repo);
2009 if (err)
2010 goto done;
2012 if (verbosity >= 0)
2013 printf("Created reference %s: %s\n",
2014 got_ref_get_name(symref),
2015 got_ref_get_symref_target(symref));
2016 } else {
2017 symref_is_locked = 1;
2019 if (strcmp(got_ref_get_symref_target(symref),
2020 got_ref_get_name(target_ref)) == 0)
2021 goto done;
2023 err = got_ref_change_symref(symref,
2024 got_ref_get_name(target_ref));
2025 if (err)
2026 goto done;
2028 err = got_ref_write(symref, repo);
2029 if (err)
2030 goto done;
2032 if (verbosity >= 0)
2033 printf("Updated %s: %s\n", got_ref_get_name(symref),
2034 got_ref_get_symref_target(symref));
2037 done:
2038 if (symref_is_locked) {
2039 unlock_err = got_ref_unlock(symref);
2040 if (unlock_err && err == NULL)
2041 err = unlock_err;
2043 got_ref_close(symref);
2044 return err;
2047 __dead static void
2048 usage_fetch(void)
2050 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2051 "[-R reference] [-r repository-path] [remote-repository]\n",
2052 getprogname());
2053 exit(1);
2056 static const struct got_error *
2057 delete_missing_ref(struct got_reference *ref,
2058 int verbosity, struct got_repository *repo)
2060 const struct got_error *err = NULL;
2061 struct got_object_id *id = NULL;
2062 char *id_str = NULL;
2064 if (got_ref_is_symbolic(ref)) {
2065 err = got_ref_delete(ref, repo);
2066 if (err)
2067 return err;
2068 if (verbosity >= 0) {
2069 printf("Deleted %s: %s\n",
2070 got_ref_get_name(ref),
2071 got_ref_get_symref_target(ref));
2073 } else {
2074 err = got_ref_resolve(&id, repo, ref);
2075 if (err)
2076 return err;
2077 err = got_object_id_str(&id_str, id);
2078 if (err)
2079 goto done;
2081 err = got_ref_delete(ref, repo);
2082 if (err)
2083 goto done;
2084 if (verbosity >= 0) {
2085 printf("Deleted %s: %s\n",
2086 got_ref_get_name(ref), id_str);
2089 done:
2090 free(id);
2091 free(id_str);
2092 return err;
2095 static const struct got_error *
2096 delete_missing_refs(struct got_pathlist_head *their_refs,
2097 struct got_pathlist_head *their_symrefs,
2098 const struct got_remote_repo *remote,
2099 int verbosity, struct got_repository *repo)
2101 const struct got_error *err = NULL, *unlock_err;
2102 struct got_reflist_head my_refs;
2103 struct got_reflist_entry *re;
2104 struct got_pathlist_entry *pe;
2105 char *remote_namespace = NULL;
2106 char *local_refname = NULL;
2108 TAILQ_INIT(&my_refs);
2110 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2111 == -1)
2112 return got_error_from_errno("asprintf");
2114 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2115 if (err)
2116 goto done;
2118 TAILQ_FOREACH(re, &my_refs, entry) {
2119 const char *refname = got_ref_get_name(re->ref);
2120 const char *their_refname;
2122 if (remote->mirror_references) {
2123 their_refname = refname;
2124 } else {
2125 if (strncmp(refname, remote_namespace,
2126 strlen(remote_namespace)) == 0) {
2127 if (strcmp(refname + strlen(remote_namespace),
2128 GOT_REF_HEAD) == 0)
2129 continue;
2130 if (asprintf(&local_refname, "refs/heads/%s",
2131 refname + strlen(remote_namespace)) == -1) {
2132 err = got_error_from_errno("asprintf");
2133 goto done;
2135 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2136 continue;
2138 their_refname = local_refname;
2141 TAILQ_FOREACH(pe, their_refs, entry) {
2142 if (strcmp(their_refname, pe->path) == 0)
2143 break;
2145 if (pe != NULL)
2146 continue;
2148 TAILQ_FOREACH(pe, their_symrefs, entry) {
2149 if (strcmp(their_refname, pe->path) == 0)
2150 break;
2152 if (pe != NULL)
2153 continue;
2155 err = delete_missing_ref(re->ref, verbosity, repo);
2156 if (err)
2157 break;
2159 if (local_refname) {
2160 struct got_reference *ref;
2161 err = got_ref_open(&ref, repo, local_refname, 1);
2162 if (err) {
2163 if (err->code != GOT_ERR_NOT_REF)
2164 break;
2165 free(local_refname);
2166 local_refname = NULL;
2167 continue;
2169 err = delete_missing_ref(ref, verbosity, repo);
2170 if (err)
2171 break;
2172 unlock_err = got_ref_unlock(ref);
2173 got_ref_close(ref);
2174 if (unlock_err && err == NULL) {
2175 err = unlock_err;
2176 break;
2179 free(local_refname);
2180 local_refname = NULL;
2183 done:
2184 got_ref_list_free(&my_refs);
2185 free(remote_namespace);
2186 free(local_refname);
2187 return err;
2190 static const struct got_error *
2191 update_wanted_ref(const char *refname, struct got_object_id *id,
2192 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2194 const struct got_error *err, *unlock_err;
2195 char *remote_refname;
2196 struct got_reference *ref;
2198 if (strncmp("refs/", refname, 5) == 0)
2199 refname += 5;
2201 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2202 remote_repo_name, refname) == -1)
2203 return got_error_from_errno("asprintf");
2205 err = got_ref_open(&ref, repo, remote_refname, 1);
2206 if (err) {
2207 if (err->code != GOT_ERR_NOT_REF)
2208 goto done;
2209 err = create_ref(remote_refname, id, verbosity, repo);
2210 } else {
2211 err = update_ref(ref, id, 0, verbosity, repo);
2212 unlock_err = got_ref_unlock(ref);
2213 if (unlock_err && err == NULL)
2214 err = unlock_err;
2215 got_ref_close(ref);
2217 done:
2218 free(remote_refname);
2219 return err;
2222 static const struct got_error *
2223 delete_ref(struct got_repository *repo, struct got_reference *ref)
2225 const struct got_error *err = NULL;
2226 struct got_object_id *id = NULL;
2227 char *id_str = NULL;
2228 const char *target;
2230 if (got_ref_is_symbolic(ref)) {
2231 target = got_ref_get_symref_target(ref);
2232 } else {
2233 err = got_ref_resolve(&id, repo, ref);
2234 if (err)
2235 goto done;
2236 err = got_object_id_str(&id_str, id);
2237 if (err)
2238 goto done;
2239 target = id_str;
2242 err = got_ref_delete(ref, repo);
2243 if (err)
2244 goto done;
2246 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2247 done:
2248 free(id);
2249 free(id_str);
2250 return err;
2253 static const struct got_error *
2254 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2256 const struct got_error *err = NULL;
2257 struct got_reflist_head refs;
2258 struct got_reflist_entry *re;
2259 char *prefix;
2261 TAILQ_INIT(&refs);
2263 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2264 err = got_error_from_errno("asprintf");
2265 goto done;
2267 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2268 if (err)
2269 goto done;
2271 TAILQ_FOREACH(re, &refs, entry)
2272 delete_ref(repo, re->ref);
2273 done:
2274 got_ref_list_free(&refs);
2275 return err;
2278 static const struct got_error *
2279 cmd_fetch(int argc, char *argv[])
2281 const struct got_error *error = NULL, *unlock_err;
2282 char *cwd = NULL, *repo_path = NULL;
2283 const char *remote_name;
2284 char *proto = NULL, *host = NULL, *port = NULL;
2285 char *repo_name = NULL, *server_path = NULL;
2286 const struct got_remote_repo *remotes, *remote = NULL;
2287 int nremotes;
2288 char *id_str = NULL;
2289 struct got_repository *repo = NULL;
2290 struct got_worktree *worktree = NULL;
2291 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2292 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2293 struct got_pathlist_entry *pe;
2294 struct got_object_id *pack_hash = NULL;
2295 int i, ch, fetchfd = -1, fetchstatus;
2296 pid_t fetchpid = -1;
2297 struct got_fetch_progress_arg fpa;
2298 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2299 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2300 int *pack_fds = NULL;
2302 TAILQ_INIT(&refs);
2303 TAILQ_INIT(&symrefs);
2304 TAILQ_INIT(&wanted_branches);
2305 TAILQ_INIT(&wanted_refs);
2307 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2308 switch (ch) {
2309 case 'a':
2310 fetch_all_branches = 1;
2311 break;
2312 case 'b':
2313 error = got_pathlist_append(&wanted_branches,
2314 optarg, NULL);
2315 if (error)
2316 return error;
2317 break;
2318 case 'd':
2319 delete_refs = 1;
2320 break;
2321 case 'l':
2322 list_refs_only = 1;
2323 break;
2324 case 'q':
2325 verbosity = -1;
2326 break;
2327 case 'R':
2328 error = got_pathlist_append(&wanted_refs,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 break;
2333 case 'r':
2334 repo_path = realpath(optarg, NULL);
2335 if (repo_path == NULL)
2336 return got_error_from_errno2("realpath",
2337 optarg);
2338 got_path_strip_trailing_slashes(repo_path);
2339 break;
2340 case 't':
2341 replace_tags = 1;
2342 break;
2343 case 'v':
2344 if (verbosity < 0)
2345 verbosity = 0;
2346 else if (verbosity < 3)
2347 verbosity++;
2348 break;
2349 case 'X':
2350 delete_remote = 1;
2351 break;
2352 default:
2353 usage_fetch();
2354 break;
2357 argc -= optind;
2358 argv += optind;
2360 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2361 option_conflict('a', 'b');
2362 if (list_refs_only) {
2363 if (!TAILQ_EMPTY(&wanted_branches))
2364 option_conflict('l', 'b');
2365 if (fetch_all_branches)
2366 option_conflict('l', 'a');
2367 if (delete_refs)
2368 option_conflict('l', 'd');
2369 if (delete_remote)
2370 option_conflict('l', 'X');
2372 if (delete_remote) {
2373 if (fetch_all_branches)
2374 option_conflict('X', 'a');
2375 if (!TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('X', 'b');
2377 if (delete_refs)
2378 option_conflict('X', 'd');
2379 if (replace_tags)
2380 option_conflict('X', 't');
2381 if (!TAILQ_EMPTY(&wanted_refs))
2382 option_conflict('X', 'R');
2385 if (argc == 0) {
2386 if (delete_remote)
2387 errx(1, "-X option requires a remote name");
2388 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2389 } else if (argc == 1)
2390 remote_name = argv[0];
2391 else
2392 usage_fetch();
2394 cwd = getcwd(NULL, 0);
2395 if (cwd == NULL) {
2396 error = got_error_from_errno("getcwd");
2397 goto done;
2400 error = got_repo_pack_fds_open(&pack_fds);
2401 if (error != NULL)
2402 goto done;
2404 if (repo_path == NULL) {
2405 error = got_worktree_open(&worktree, cwd);
2406 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2407 goto done;
2408 else
2409 error = NULL;
2410 if (worktree) {
2411 repo_path =
2412 strdup(got_worktree_get_repo_path(worktree));
2413 if (repo_path == NULL)
2414 error = got_error_from_errno("strdup");
2415 if (error)
2416 goto done;
2417 } else {
2418 repo_path = strdup(cwd);
2419 if (repo_path == NULL) {
2420 error = got_error_from_errno("strdup");
2421 goto done;
2426 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2427 if (error)
2428 goto done;
2430 if (delete_remote) {
2431 error = delete_refs_for_remote(repo, remote_name);
2432 goto done; /* nothing else to do */
2435 if (worktree) {
2436 worktree_conf = got_worktree_get_gotconfig(worktree);
2437 if (worktree_conf) {
2438 got_gotconfig_get_remotes(&nremotes, &remotes,
2439 worktree_conf);
2440 for (i = 0; i < nremotes; i++) {
2441 if (strcmp(remotes[i].name, remote_name) == 0) {
2442 remote = &remotes[i];
2443 break;
2447 if (TAILQ_EMPTY(&wanted_branches)) {
2448 error = got_pathlist_append(&wanted_branches,
2449 got_worktree_get_head_ref_name(worktree), NULL);
2450 if (error)
2451 goto done;
2454 if (remote == NULL) {
2455 repo_conf = got_repo_get_gotconfig(repo);
2456 if (repo_conf) {
2457 got_gotconfig_get_remotes(&nremotes, &remotes,
2458 repo_conf);
2459 for (i = 0; i < nremotes; i++) {
2460 if (strcmp(remotes[i].name, remote_name) == 0) {
2461 remote = &remotes[i];
2462 break;
2467 if (remote == NULL) {
2468 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2469 for (i = 0; i < nremotes; i++) {
2470 if (strcmp(remotes[i].name, remote_name) == 0) {
2471 remote = &remotes[i];
2472 break;
2476 if (remote == NULL) {
2477 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2478 goto done;
2481 if (TAILQ_EMPTY(&wanted_branches)) {
2482 if (!fetch_all_branches)
2483 fetch_all_branches = remote->fetch_all_branches;
2484 for (i = 0; i < remote->nfetch_branches; i++) {
2485 error = got_pathlist_append(&wanted_branches,
2486 remote->fetch_branches[i], NULL);
2487 if (error)
2488 goto done;
2491 if (TAILQ_EMPTY(&wanted_refs)) {
2492 for (i = 0; i < remote->nfetch_refs; i++) {
2493 error = got_pathlist_append(&wanted_refs,
2494 remote->fetch_refs[i], NULL);
2495 if (error)
2496 goto done;
2500 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2501 &repo_name, remote->fetch_url);
2502 if (error)
2503 goto done;
2505 if (strcmp(proto, "git") == 0) {
2506 #ifndef PROFILE
2507 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2508 "sendfd dns inet unveil", NULL) == -1)
2509 err(1, "pledge");
2510 #endif
2511 } else if (strcmp(proto, "git+ssh") == 0 ||
2512 strcmp(proto, "ssh") == 0) {
2513 #ifndef PROFILE
2514 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2515 "sendfd unveil", NULL) == -1)
2516 err(1, "pledge");
2517 #endif
2518 } else if (strcmp(proto, "http") == 0 ||
2519 strcmp(proto, "git+http") == 0) {
2520 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2521 goto done;
2522 } else {
2523 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2524 goto done;
2527 error = got_dial_apply_unveil(proto);
2528 if (error)
2529 goto done;
2531 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2532 if (error)
2533 goto done;
2535 if (verbosity >= 0) {
2536 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2537 remote->name, proto, host,
2538 port ? ":" : "", port ? port : "",
2539 *server_path == '/' ? "" : "/", server_path);
2542 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2543 server_path, verbosity);
2544 if (error)
2545 goto done;
2547 fpa.last_scaled_size[0] = '\0';
2548 fpa.last_p_indexed = -1;
2549 fpa.last_p_resolved = -1;
2550 fpa.verbosity = verbosity;
2551 fpa.repo = repo;
2552 fpa.create_configs = 0;
2553 fpa.configs_created = 0;
2554 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2555 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2556 remote->mirror_references, fetch_all_branches, &wanted_branches,
2557 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2558 fetch_progress, &fpa);
2559 if (error)
2560 goto done;
2562 if (list_refs_only) {
2563 error = list_remote_refs(&symrefs, &refs);
2564 goto done;
2567 if (pack_hash == NULL) {
2568 if (verbosity >= 0)
2569 printf("Already up-to-date\n");
2570 } else if (verbosity >= 0) {
2571 error = got_object_id_str(&id_str, pack_hash);
2572 if (error)
2573 goto done;
2574 printf("\nFetched %s.pack\n", id_str);
2575 free(id_str);
2576 id_str = NULL;
2579 /* Update references provided with the pack file. */
2580 TAILQ_FOREACH(pe, &refs, entry) {
2581 const char *refname = pe->path;
2582 struct got_object_id *id = pe->data;
2583 struct got_reference *ref;
2584 char *remote_refname;
2586 if (is_wanted_ref(&wanted_refs, refname) &&
2587 !remote->mirror_references) {
2588 error = update_wanted_ref(refname, id,
2589 remote->name, verbosity, repo);
2590 if (error)
2591 goto done;
2592 continue;
2595 if (remote->mirror_references ||
2596 strncmp("refs/tags/", refname, 10) == 0) {
2597 error = got_ref_open(&ref, repo, refname, 1);
2598 if (error) {
2599 if (error->code != GOT_ERR_NOT_REF)
2600 goto done;
2601 error = create_ref(refname, id, verbosity,
2602 repo);
2603 if (error)
2604 goto done;
2605 } else {
2606 error = update_ref(ref, id, replace_tags,
2607 verbosity, repo);
2608 unlock_err = got_ref_unlock(ref);
2609 if (unlock_err && error == NULL)
2610 error = unlock_err;
2611 got_ref_close(ref);
2612 if (error)
2613 goto done;
2615 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2616 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2617 remote_name, refname + 11) == -1) {
2618 error = got_error_from_errno("asprintf");
2619 goto done;
2622 error = got_ref_open(&ref, repo, remote_refname, 1);
2623 if (error) {
2624 if (error->code != GOT_ERR_NOT_REF)
2625 goto done;
2626 error = create_ref(remote_refname, id,
2627 verbosity, repo);
2628 if (error)
2629 goto done;
2630 } else {
2631 error = update_ref(ref, id, replace_tags,
2632 verbosity, repo);
2633 unlock_err = got_ref_unlock(ref);
2634 if (unlock_err && error == NULL)
2635 error = unlock_err;
2636 got_ref_close(ref);
2637 if (error)
2638 goto done;
2641 /* Also create a local branch if none exists yet. */
2642 error = got_ref_open(&ref, repo, refname, 1);
2643 if (error) {
2644 if (error->code != GOT_ERR_NOT_REF)
2645 goto done;
2646 error = create_ref(refname, id, verbosity,
2647 repo);
2648 if (error)
2649 goto done;
2650 } else {
2651 unlock_err = got_ref_unlock(ref);
2652 if (unlock_err && error == NULL)
2653 error = unlock_err;
2654 got_ref_close(ref);
2658 if (delete_refs) {
2659 error = delete_missing_refs(&refs, &symrefs, remote,
2660 verbosity, repo);
2661 if (error)
2662 goto done;
2665 if (!remote->mirror_references) {
2666 /* Update remote HEAD reference if the server provided one. */
2667 TAILQ_FOREACH(pe, &symrefs, entry) {
2668 struct got_reference *target_ref;
2669 const char *refname = pe->path;
2670 const char *target = pe->data;
2671 char *remote_refname = NULL, *remote_target = NULL;
2673 if (strcmp(refname, GOT_REF_HEAD) != 0)
2674 continue;
2676 if (strncmp("refs/heads/", target, 11) != 0)
2677 continue;
2679 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2680 remote->name, refname) == -1) {
2681 error = got_error_from_errno("asprintf");
2682 goto done;
2684 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2685 remote->name, target + 11) == -1) {
2686 error = got_error_from_errno("asprintf");
2687 free(remote_refname);
2688 goto done;
2691 error = got_ref_open(&target_ref, repo, remote_target,
2692 0);
2693 if (error) {
2694 free(remote_refname);
2695 free(remote_target);
2696 if (error->code == GOT_ERR_NOT_REF) {
2697 error = NULL;
2698 continue;
2700 goto done;
2702 error = update_symref(remote_refname, target_ref,
2703 verbosity, repo);
2704 free(remote_refname);
2705 free(remote_target);
2706 got_ref_close(target_ref);
2707 if (error)
2708 goto done;
2711 done:
2712 if (fetchpid > 0) {
2713 if (kill(fetchpid, SIGTERM) == -1)
2714 error = got_error_from_errno("kill");
2715 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2716 error = got_error_from_errno("waitpid");
2718 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2719 error = got_error_from_errno("close");
2720 if (repo) {
2721 const struct got_error *close_err = got_repo_close(repo);
2722 if (error == NULL)
2723 error = close_err;
2725 if (worktree)
2726 got_worktree_close(worktree);
2727 if (pack_fds) {
2728 const struct got_error *pack_err =
2729 got_repo_pack_fds_close(pack_fds);
2730 if (error == NULL)
2731 error = pack_err;
2733 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2734 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2735 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2736 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2737 free(id_str);
2738 free(cwd);
2739 free(repo_path);
2740 free(pack_hash);
2741 free(proto);
2742 free(host);
2743 free(port);
2744 free(server_path);
2745 free(repo_name);
2746 return error;
2750 __dead static void
2751 usage_checkout(void)
2753 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2754 "[-p path-prefix] repository-path [work-tree-path]\n",
2755 getprogname());
2756 exit(1);
2759 static void
2760 show_worktree_base_ref_warning(void)
2762 fprintf(stderr, "%s: warning: could not create a reference "
2763 "to the work tree's base commit; the commit could be "
2764 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2765 "repository writable and running 'got update' will prevent this\n",
2766 getprogname());
2769 struct got_checkout_progress_arg {
2770 const char *worktree_path;
2771 int had_base_commit_ref_error;
2772 int verbosity;
2775 static const struct got_error *
2776 checkout_progress(void *arg, unsigned char status, const char *path)
2778 struct got_checkout_progress_arg *a = arg;
2780 /* Base commit bump happens silently. */
2781 if (status == GOT_STATUS_BUMP_BASE)
2782 return NULL;
2784 if (status == GOT_STATUS_BASE_REF_ERR) {
2785 a->had_base_commit_ref_error = 1;
2786 return NULL;
2789 while (path[0] == '/')
2790 path++;
2792 if (a->verbosity >= 0)
2793 printf("%c %s/%s\n", status, a->worktree_path, path);
2795 return NULL;
2798 static const struct got_error *
2799 check_cancelled(void *arg)
2801 if (sigint_received || sigpipe_received)
2802 return got_error(GOT_ERR_CANCELLED);
2803 return NULL;
2806 static const struct got_error *
2807 check_linear_ancestry(struct got_object_id *commit_id,
2808 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2809 struct got_repository *repo)
2811 const struct got_error *err = NULL;
2812 struct got_object_id *yca_id;
2814 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2815 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2816 if (err)
2817 return err;
2819 if (yca_id == NULL)
2820 return got_error(GOT_ERR_ANCESTRY);
2823 * Require a straight line of history between the target commit
2824 * and the work tree's base commit.
2826 * Non-linear situations such as this require a rebase:
2828 * (commit) D F (base_commit)
2829 * \ /
2830 * C E
2831 * \ /
2832 * B (yca)
2833 * |
2834 * A
2836 * 'got update' only handles linear cases:
2837 * Update forwards in time: A (base/yca) - B - C - D (commit)
2838 * Update backwards in time: D (base) - C - B - A (commit/yca)
2840 if (allow_forwards_in_time_only) {
2841 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2842 return got_error(GOT_ERR_ANCESTRY);
2843 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2844 got_object_id_cmp(base_commit_id, yca_id) != 0)
2845 return got_error(GOT_ERR_ANCESTRY);
2847 free(yca_id);
2848 return NULL;
2851 static const struct got_error *
2852 check_same_branch(struct got_object_id *commit_id,
2853 struct got_reference *head_ref, struct got_object_id *yca_id,
2854 struct got_repository *repo)
2856 const struct got_error *err = NULL;
2857 struct got_commit_graph *graph = NULL;
2858 struct got_object_id *head_commit_id = NULL;
2859 int is_same_branch = 0;
2861 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2862 if (err)
2863 goto done;
2865 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2866 is_same_branch = 1;
2867 goto done;
2869 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2870 is_same_branch = 1;
2871 goto done;
2874 err = got_commit_graph_open(&graph, "/", 1);
2875 if (err)
2876 goto done;
2878 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2879 check_cancelled, NULL);
2880 if (err)
2881 goto done;
2883 for (;;) {
2884 struct got_object_id id;
2886 err = got_commit_graph_iter_next(&id, graph, repo,
2887 check_cancelled, NULL);
2888 if (err) {
2889 if (err->code == GOT_ERR_ITER_COMPLETED)
2890 err = NULL;
2891 break;
2894 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2895 break;
2896 if (got_object_id_cmp(&id, commit_id) == 0) {
2897 is_same_branch = 1;
2898 break;
2901 done:
2902 if (graph)
2903 got_commit_graph_close(graph);
2904 free(head_commit_id);
2905 if (!err && !is_same_branch)
2906 err = got_error(GOT_ERR_ANCESTRY);
2907 return err;
2910 static const struct got_error *
2911 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2913 static char msg[512];
2914 const char *branch_name;
2916 if (got_ref_is_symbolic(ref))
2917 branch_name = got_ref_get_symref_target(ref);
2918 else
2919 branch_name = got_ref_get_name(ref);
2921 if (strncmp("refs/heads/", branch_name, 11) == 0)
2922 branch_name += 11;
2924 snprintf(msg, sizeof(msg),
2925 "target commit is not contained in branch '%s'; "
2926 "the branch to use must be specified with -b; "
2927 "if necessary a new branch can be created for "
2928 "this commit with 'got branch -c %s BRANCH_NAME'",
2929 branch_name, commit_id_str);
2931 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2934 static const struct got_error *
2935 cmd_checkout(int argc, char *argv[])
2937 const struct got_error *error = NULL;
2938 struct got_repository *repo = NULL;
2939 struct got_reference *head_ref = NULL, *ref = NULL;
2940 struct got_worktree *worktree = NULL;
2941 char *repo_path = NULL;
2942 char *worktree_path = NULL;
2943 const char *path_prefix = "";
2944 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2945 char *commit_id_str = NULL;
2946 struct got_object_id *commit_id = NULL;
2947 char *cwd = NULL;
2948 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2949 struct got_pathlist_head paths;
2950 struct got_checkout_progress_arg cpa;
2951 int *pack_fds = NULL;
2953 TAILQ_INIT(&paths);
2955 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2956 switch (ch) {
2957 case 'b':
2958 branch_name = optarg;
2959 break;
2960 case 'c':
2961 commit_id_str = strdup(optarg);
2962 if (commit_id_str == NULL)
2963 return got_error_from_errno("strdup");
2964 break;
2965 case 'E':
2966 allow_nonempty = 1;
2967 break;
2968 case 'p':
2969 path_prefix = optarg;
2970 break;
2971 case 'q':
2972 verbosity = -1;
2973 break;
2974 default:
2975 usage_checkout();
2976 /* NOTREACHED */
2980 argc -= optind;
2981 argv += optind;
2983 #ifndef PROFILE
2984 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2985 "unveil", NULL) == -1)
2986 err(1, "pledge");
2987 #endif
2988 if (argc == 1) {
2989 char *base, *dotgit;
2990 const char *path;
2991 repo_path = realpath(argv[0], NULL);
2992 if (repo_path == NULL)
2993 return got_error_from_errno2("realpath", argv[0]);
2994 cwd = getcwd(NULL, 0);
2995 if (cwd == NULL) {
2996 error = got_error_from_errno("getcwd");
2997 goto done;
2999 if (path_prefix[0])
3000 path = path_prefix;
3001 else
3002 path = repo_path;
3003 error = got_path_basename(&base, path);
3004 if (error)
3005 goto done;
3006 dotgit = strstr(base, ".git");
3007 if (dotgit)
3008 *dotgit = '\0';
3009 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3010 error = got_error_from_errno("asprintf");
3011 free(base);
3012 goto done;
3014 free(base);
3015 } else if (argc == 2) {
3016 repo_path = realpath(argv[0], NULL);
3017 if (repo_path == NULL) {
3018 error = got_error_from_errno2("realpath", argv[0]);
3019 goto done;
3021 worktree_path = realpath(argv[1], NULL);
3022 if (worktree_path == NULL) {
3023 if (errno != ENOENT) {
3024 error = got_error_from_errno2("realpath",
3025 argv[1]);
3026 goto done;
3028 worktree_path = strdup(argv[1]);
3029 if (worktree_path == NULL) {
3030 error = got_error_from_errno("strdup");
3031 goto done;
3034 } else
3035 usage_checkout();
3037 got_path_strip_trailing_slashes(repo_path);
3038 got_path_strip_trailing_slashes(worktree_path);
3040 error = got_repo_pack_fds_open(&pack_fds);
3041 if (error != NULL)
3042 goto done;
3044 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3045 if (error != NULL)
3046 goto done;
3048 /* Pre-create work tree path for unveil(2) */
3049 error = got_path_mkdir(worktree_path);
3050 if (error) {
3051 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3052 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3053 goto done;
3054 if (!allow_nonempty &&
3055 !got_path_dir_is_empty(worktree_path)) {
3056 error = got_error_path(worktree_path,
3057 GOT_ERR_DIR_NOT_EMPTY);
3058 goto done;
3062 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3063 if (error)
3064 goto done;
3066 error = got_ref_open(&head_ref, repo, branch_name, 0);
3067 if (error != NULL)
3068 goto done;
3070 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3071 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3072 goto done;
3074 error = got_worktree_open(&worktree, worktree_path);
3075 if (error != NULL)
3076 goto done;
3078 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3079 path_prefix);
3080 if (error != NULL)
3081 goto done;
3082 if (!same_path_prefix) {
3083 error = got_error(GOT_ERR_PATH_PREFIX);
3084 goto done;
3087 if (commit_id_str) {
3088 struct got_reflist_head refs;
3089 TAILQ_INIT(&refs);
3090 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3091 NULL);
3092 if (error)
3093 goto done;
3094 error = got_repo_match_object_id(&commit_id, NULL,
3095 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3096 got_ref_list_free(&refs);
3097 if (error)
3098 goto done;
3099 error = check_linear_ancestry(commit_id,
3100 got_worktree_get_base_commit_id(worktree), 0, repo);
3101 if (error != NULL) {
3102 if (error->code == GOT_ERR_ANCESTRY) {
3103 error = checkout_ancestry_error(
3104 head_ref, commit_id_str);
3106 goto done;
3108 error = check_same_branch(commit_id, head_ref, NULL, repo);
3109 if (error) {
3110 if (error->code == GOT_ERR_ANCESTRY) {
3111 error = checkout_ancestry_error(
3112 head_ref, commit_id_str);
3114 goto done;
3116 error = got_worktree_set_base_commit_id(worktree, repo,
3117 commit_id);
3118 if (error)
3119 goto done;
3120 /* Expand potentially abbreviated commit ID string. */
3121 free(commit_id_str);
3122 error = got_object_id_str(&commit_id_str, commit_id);
3123 if (error)
3124 goto done;
3125 } else {
3126 commit_id = got_object_id_dup(
3127 got_worktree_get_base_commit_id(worktree));
3128 if (commit_id == NULL) {
3129 error = got_error_from_errno("got_object_id_dup");
3130 goto done;
3132 error = got_object_id_str(&commit_id_str, commit_id);
3133 if (error)
3134 goto done;
3137 error = got_pathlist_append(&paths, "", NULL);
3138 if (error)
3139 goto done;
3140 cpa.worktree_path = worktree_path;
3141 cpa.had_base_commit_ref_error = 0;
3142 cpa.verbosity = verbosity;
3143 error = got_worktree_checkout_files(worktree, &paths, repo,
3144 checkout_progress, &cpa, check_cancelled, NULL);
3145 if (error != NULL)
3146 goto done;
3148 if (got_ref_is_symbolic(head_ref)) {
3149 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3150 if (error)
3151 goto done;
3152 refname = got_ref_get_name(ref);
3153 } else
3154 refname = got_ref_get_name(head_ref);
3155 printf("Checked out %s: %s\n", refname, commit_id_str);
3156 printf("Now shut up and hack\n");
3157 if (cpa.had_base_commit_ref_error)
3158 show_worktree_base_ref_warning();
3159 done:
3160 if (pack_fds) {
3161 const struct got_error *pack_err =
3162 got_repo_pack_fds_close(pack_fds);
3163 if (error == NULL)
3164 error = pack_err;
3166 if (head_ref)
3167 got_ref_close(head_ref);
3168 if (ref)
3169 got_ref_close(ref);
3170 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3171 free(commit_id_str);
3172 free(commit_id);
3173 free(repo_path);
3174 free(worktree_path);
3175 free(cwd);
3176 return error;
3179 struct got_update_progress_arg {
3180 int did_something;
3181 int conflicts;
3182 int obstructed;
3183 int not_updated;
3184 int missing;
3185 int not_deleted;
3186 int unversioned;
3187 int verbosity;
3190 static void
3191 print_update_progress_stats(struct got_update_progress_arg *upa)
3193 if (!upa->did_something)
3194 return;
3196 if (upa->conflicts > 0)
3197 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3198 if (upa->obstructed > 0)
3199 printf("File paths obstructed by a non-regular file: %d\n",
3200 upa->obstructed);
3201 if (upa->not_updated > 0)
3202 printf("Files not updated because of existing merge "
3203 "conflicts: %d\n", upa->not_updated);
3207 * The meaning of some status codes differs between merge-style operations and
3208 * update operations. For example, the ! status code means "file was missing"
3209 * if changes were merged into the work tree, and "missing file was restored"
3210 * if the work tree was updated. This function should be used by any operation
3211 * which merges changes into the work tree without updating the work tree.
3213 static void
3214 print_merge_progress_stats(struct got_update_progress_arg *upa)
3216 if (!upa->did_something)
3217 return;
3219 if (upa->conflicts > 0)
3220 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3221 if (upa->obstructed > 0)
3222 printf("File paths obstructed by a non-regular file: %d\n",
3223 upa->obstructed);
3224 if (upa->missing > 0)
3225 printf("Files which had incoming changes but could not be "
3226 "found in the work tree: %d\n", upa->missing);
3227 if (upa->not_deleted > 0)
3228 printf("Files not deleted due to differences in deleted "
3229 "content: %d\n", upa->not_deleted);
3230 if (upa->unversioned > 0)
3231 printf("Files not merged because an unversioned file was "
3232 "found in the work tree: %d\n", upa->unversioned);
3235 __dead static void
3236 usage_update(void)
3238 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3239 "[path ...]\n", getprogname());
3240 exit(1);
3243 static const struct got_error *
3244 update_progress(void *arg, unsigned char status, const char *path)
3246 struct got_update_progress_arg *upa = arg;
3248 if (status == GOT_STATUS_EXISTS ||
3249 status == GOT_STATUS_BASE_REF_ERR)
3250 return NULL;
3252 upa->did_something = 1;
3254 /* Base commit bump happens silently. */
3255 if (status == GOT_STATUS_BUMP_BASE)
3256 return NULL;
3258 if (status == GOT_STATUS_CONFLICT)
3259 upa->conflicts++;
3260 if (status == GOT_STATUS_OBSTRUCTED)
3261 upa->obstructed++;
3262 if (status == GOT_STATUS_CANNOT_UPDATE)
3263 upa->not_updated++;
3264 if (status == GOT_STATUS_MISSING)
3265 upa->missing++;
3266 if (status == GOT_STATUS_CANNOT_DELETE)
3267 upa->not_deleted++;
3268 if (status == GOT_STATUS_UNVERSIONED)
3269 upa->unversioned++;
3271 while (path[0] == '/')
3272 path++;
3273 if (upa->verbosity >= 0)
3274 printf("%c %s\n", status, path);
3276 return NULL;
3279 static const struct got_error *
3280 switch_head_ref(struct got_reference *head_ref,
3281 struct got_object_id *commit_id, struct got_worktree *worktree,
3282 struct got_repository *repo)
3284 const struct got_error *err = NULL;
3285 char *base_id_str;
3286 int ref_has_moved = 0;
3288 /* Trivial case: switching between two different references. */
3289 if (strcmp(got_ref_get_name(head_ref),
3290 got_worktree_get_head_ref_name(worktree)) != 0) {
3291 printf("Switching work tree from %s to %s\n",
3292 got_worktree_get_head_ref_name(worktree),
3293 got_ref_get_name(head_ref));
3294 return got_worktree_set_head_ref(worktree, head_ref);
3297 err = check_linear_ancestry(commit_id,
3298 got_worktree_get_base_commit_id(worktree), 0, repo);
3299 if (err) {
3300 if (err->code != GOT_ERR_ANCESTRY)
3301 return err;
3302 ref_has_moved = 1;
3304 if (!ref_has_moved)
3305 return NULL;
3307 /* Switching to a rebased branch with the same reference name. */
3308 err = got_object_id_str(&base_id_str,
3309 got_worktree_get_base_commit_id(worktree));
3310 if (err)
3311 return err;
3312 printf("Reference %s now points at a different branch\n",
3313 got_worktree_get_head_ref_name(worktree));
3314 printf("Switching work tree from %s to %s\n", base_id_str,
3315 got_worktree_get_head_ref_name(worktree));
3316 return NULL;
3319 static const struct got_error *
3320 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3322 const struct got_error *err;
3323 int in_progress;
3325 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3326 if (err)
3327 return err;
3328 if (in_progress)
3329 return got_error(GOT_ERR_REBASING);
3331 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3332 if (err)
3333 return err;
3334 if (in_progress)
3335 return got_error(GOT_ERR_HISTEDIT_BUSY);
3337 return NULL;
3340 static const struct got_error *
3341 check_merge_in_progress(struct got_worktree *worktree,
3342 struct got_repository *repo)
3344 const struct got_error *err;
3345 int in_progress;
3347 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3348 if (err)
3349 return err;
3350 if (in_progress)
3351 return got_error(GOT_ERR_MERGE_BUSY);
3353 return NULL;
3356 static const struct got_error *
3357 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3358 char *argv[], struct got_worktree *worktree)
3360 const struct got_error *err = NULL;
3361 char *path;
3362 struct got_pathlist_entry *new;
3363 int i;
3365 if (argc == 0) {
3366 path = strdup("");
3367 if (path == NULL)
3368 return got_error_from_errno("strdup");
3369 return got_pathlist_append(paths, path, NULL);
3372 for (i = 0; i < argc; i++) {
3373 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3374 if (err)
3375 break;
3376 err = got_pathlist_insert(&new, paths, path, NULL);
3377 if (err || new == NULL /* duplicate */) {
3378 free(path);
3379 if (err)
3380 break;
3384 return err;
3387 static const struct got_error *
3388 wrap_not_worktree_error(const struct got_error *orig_err,
3389 const char *cmdname, const char *path)
3391 const struct got_error *err;
3392 struct got_repository *repo;
3393 static char msg[512];
3394 int *pack_fds = NULL;
3396 err = got_repo_pack_fds_open(&pack_fds);
3397 if (err)
3398 return err;
3400 err = got_repo_open(&repo, path, NULL, pack_fds);
3401 if (err)
3402 return orig_err;
3404 snprintf(msg, sizeof(msg),
3405 "'got %s' needs a work tree in addition to a git repository\n"
3406 "Work trees can be checked out from this Git repository with "
3407 "'got checkout'.\n"
3408 "The got(1) manual page contains more information.", cmdname);
3409 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3410 got_repo_close(repo);
3411 if (pack_fds) {
3412 const struct got_error *pack_err =
3413 got_repo_pack_fds_close(pack_fds);
3414 if (err == NULL)
3415 err = pack_err;
3417 return err;
3420 static const struct got_error *
3421 cmd_update(int argc, char *argv[])
3423 const struct got_error *error = NULL;
3424 struct got_repository *repo = NULL;
3425 struct got_worktree *worktree = NULL;
3426 char *worktree_path = NULL;
3427 struct got_object_id *commit_id = NULL;
3428 char *commit_id_str = NULL;
3429 const char *branch_name = NULL;
3430 struct got_reference *head_ref = NULL;
3431 struct got_pathlist_head paths;
3432 struct got_pathlist_entry *pe;
3433 int ch, verbosity = 0;
3434 struct got_update_progress_arg upa;
3435 int *pack_fds = NULL;
3437 TAILQ_INIT(&paths);
3439 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3440 switch (ch) {
3441 case 'b':
3442 branch_name = optarg;
3443 break;
3444 case 'c':
3445 commit_id_str = strdup(optarg);
3446 if (commit_id_str == NULL)
3447 return got_error_from_errno("strdup");
3448 break;
3449 case 'q':
3450 verbosity = -1;
3451 break;
3452 default:
3453 usage_update();
3454 /* NOTREACHED */
3458 argc -= optind;
3459 argv += optind;
3461 #ifndef PROFILE
3462 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3463 "unveil", NULL) == -1)
3464 err(1, "pledge");
3465 #endif
3466 worktree_path = getcwd(NULL, 0);
3467 if (worktree_path == NULL) {
3468 error = got_error_from_errno("getcwd");
3469 goto done;
3472 error = got_repo_pack_fds_open(&pack_fds);
3473 if (error != NULL)
3474 goto done;
3476 error = got_worktree_open(&worktree, worktree_path);
3477 if (error) {
3478 if (error->code == GOT_ERR_NOT_WORKTREE)
3479 error = wrap_not_worktree_error(error, "update",
3480 worktree_path);
3481 goto done;
3484 error = check_rebase_or_histedit_in_progress(worktree);
3485 if (error)
3486 goto done;
3488 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3489 NULL, pack_fds);
3490 if (error != NULL)
3491 goto done;
3493 error = apply_unveil(got_repo_get_path(repo), 0,
3494 got_worktree_get_root_path(worktree));
3495 if (error)
3496 goto done;
3498 error = check_merge_in_progress(worktree, repo);
3499 if (error)
3500 goto done;
3502 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3503 if (error)
3504 goto done;
3506 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3507 got_worktree_get_head_ref_name(worktree), 0);
3508 if (error != NULL)
3509 goto done;
3510 if (commit_id_str == NULL) {
3511 error = got_ref_resolve(&commit_id, repo, head_ref);
3512 if (error != NULL)
3513 goto done;
3514 error = got_object_id_str(&commit_id_str, commit_id);
3515 if (error != NULL)
3516 goto done;
3517 } else {
3518 struct got_reflist_head refs;
3519 TAILQ_INIT(&refs);
3520 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3521 NULL);
3522 if (error)
3523 goto done;
3524 error = got_repo_match_object_id(&commit_id, NULL,
3525 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3526 got_ref_list_free(&refs);
3527 free(commit_id_str);
3528 commit_id_str = NULL;
3529 if (error)
3530 goto done;
3531 error = got_object_id_str(&commit_id_str, commit_id);
3532 if (error)
3533 goto done;
3536 if (branch_name) {
3537 struct got_object_id *head_commit_id;
3538 TAILQ_FOREACH(pe, &paths, entry) {
3539 if (pe->path_len == 0)
3540 continue;
3541 error = got_error_msg(GOT_ERR_BAD_PATH,
3542 "switching between branches requires that "
3543 "the entire work tree gets updated");
3544 goto done;
3546 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3547 if (error)
3548 goto done;
3549 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3550 repo);
3551 free(head_commit_id);
3552 if (error != NULL)
3553 goto done;
3554 error = check_same_branch(commit_id, head_ref, NULL, repo);
3555 if (error)
3556 goto done;
3557 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3558 if (error)
3559 goto done;
3560 } else {
3561 error = check_linear_ancestry(commit_id,
3562 got_worktree_get_base_commit_id(worktree), 0, repo);
3563 if (error != NULL) {
3564 if (error->code == GOT_ERR_ANCESTRY)
3565 error = got_error(GOT_ERR_BRANCH_MOVED);
3566 goto done;
3568 error = check_same_branch(commit_id, head_ref, NULL, repo);
3569 if (error)
3570 goto done;
3573 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3574 commit_id) != 0) {
3575 error = got_worktree_set_base_commit_id(worktree, repo,
3576 commit_id);
3577 if (error)
3578 goto done;
3581 memset(&upa, 0, sizeof(upa));
3582 upa.verbosity = verbosity;
3583 error = got_worktree_checkout_files(worktree, &paths, repo,
3584 update_progress, &upa, check_cancelled, NULL);
3585 if (error != NULL)
3586 goto done;
3588 if (upa.did_something) {
3589 printf("Updated to %s: %s\n",
3590 got_worktree_get_head_ref_name(worktree), commit_id_str);
3591 } else
3592 printf("Already up-to-date\n");
3594 print_update_progress_stats(&upa);
3595 done:
3596 if (pack_fds) {
3597 const struct got_error *pack_err =
3598 got_repo_pack_fds_close(pack_fds);
3599 if (error == NULL)
3600 error = pack_err;
3602 free(worktree_path);
3603 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3604 free(commit_id);
3605 free(commit_id_str);
3606 return error;
3609 static const struct got_error *
3610 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3611 const char *path, int diff_context, int ignore_whitespace,
3612 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3613 struct got_repository *repo, FILE *outfile)
3615 const struct got_error *err = NULL;
3616 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3617 FILE *f1 = NULL, *f2 = NULL;
3618 int fd1 = -1, fd2 = -1;
3620 fd1 = got_opentempfd();
3621 if (fd1 == -1)
3622 return got_error_from_errno("got_opentempfd");
3623 fd2 = got_opentempfd();
3624 if (fd2 == -1) {
3625 err = got_error_from_errno("got_opentempfd");
3626 goto done;
3629 if (blob_id1) {
3630 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3631 fd1);
3632 if (err)
3633 goto done;
3636 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3637 if (err)
3638 goto done;
3640 f1 = got_opentemp();
3641 if (f1 == NULL) {
3642 err = got_error_from_errno("got_opentemp");
3643 goto done;
3645 f2 = got_opentemp();
3646 if (f2 == NULL) {
3647 err = got_error_from_errno("got_opentemp");
3648 goto done;
3651 while (path[0] == '/')
3652 path++;
3653 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3654 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3655 force_text_diff, dsa, outfile);
3656 done:
3657 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3658 err = got_error_from_errno("close");
3659 if (blob1)
3660 got_object_blob_close(blob1);
3661 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3662 err = got_error_from_errno("close");
3663 got_object_blob_close(blob2);
3664 if (f1 && fclose(f1) == EOF && err == NULL)
3665 err = got_error_from_errno("fclose");
3666 if (f2 && fclose(f2) == EOF && err == NULL)
3667 err = got_error_from_errno("fclose");
3668 return err;
3671 static const struct got_error *
3672 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3673 const char *path, int diff_context, int ignore_whitespace,
3674 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3675 struct got_repository *repo, FILE *outfile)
3677 const struct got_error *err = NULL;
3678 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3679 struct got_diff_blob_output_unidiff_arg arg;
3680 FILE *f1 = NULL, *f2 = NULL;
3681 int fd1 = -1, fd2 = -1;
3683 if (tree_id1) {
3684 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3685 if (err)
3686 goto done;
3687 fd1 = got_opentempfd();
3688 if (fd1 == -1) {
3689 err = got_error_from_errno("got_opentempfd");
3690 goto done;
3694 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3695 if (err)
3696 goto done;
3698 f1 = got_opentemp();
3699 if (f1 == NULL) {
3700 err = got_error_from_errno("got_opentemp");
3701 goto done;
3704 f2 = got_opentemp();
3705 if (f2 == NULL) {
3706 err = got_error_from_errno("got_opentemp");
3707 goto done;
3709 fd2 = got_opentempfd();
3710 if (fd2 == -1) {
3711 err = got_error_from_errno("got_opentempfd");
3712 goto done;
3714 arg.diff_context = diff_context;
3715 arg.ignore_whitespace = ignore_whitespace;
3716 arg.force_text_diff = force_text_diff;
3717 arg.diffstat = dsa;
3718 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3719 arg.outfile = outfile;
3720 arg.lines = NULL;
3721 arg.nlines = 0;
3722 while (path[0] == '/')
3723 path++;
3724 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3725 got_diff_blob_output_unidiff, &arg, 1);
3726 done:
3727 if (tree1)
3728 got_object_tree_close(tree1);
3729 if (tree2)
3730 got_object_tree_close(tree2);
3731 if (f1 && fclose(f1) == EOF && err == NULL)
3732 err = got_error_from_errno("fclose");
3733 if (f2 && fclose(f2) == EOF && err == NULL)
3734 err = got_error_from_errno("fclose");
3735 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3736 err = got_error_from_errno("close");
3737 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3738 err = got_error_from_errno("close");
3739 return err;
3742 static const struct got_error *
3743 get_changed_paths(struct got_pathlist_head *paths,
3744 struct got_commit_object *commit, struct got_repository *repo,
3745 struct got_diffstat_cb_arg *dsa)
3747 const struct got_error *err = NULL;
3748 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3749 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3750 struct got_object_qid *qid;
3751 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3752 FILE *f1 = NULL, *f2 = NULL;
3753 int fd1 = -1, fd2 = -1;
3755 if (dsa) {
3756 cb = got_diff_tree_compute_diffstat;
3758 f1 = got_opentemp();
3759 if (f1 == NULL) {
3760 err = got_error_from_errno("got_opentemp");
3761 goto done;
3763 f2 = got_opentemp();
3764 if (f2 == NULL) {
3765 err = got_error_from_errno("got_opentemp");
3766 goto done;
3768 fd1 = got_opentempfd();
3769 if (fd1 == -1) {
3770 err = got_error_from_errno("got_opentempfd");
3771 goto done;
3773 fd2 = got_opentempfd();
3774 if (fd2 == -1) {
3775 err = got_error_from_errno("got_opentempfd");
3776 goto done;
3780 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3781 if (qid != NULL) {
3782 struct got_commit_object *pcommit;
3783 err = got_object_open_as_commit(&pcommit, repo,
3784 &qid->id);
3785 if (err)
3786 return err;
3788 tree_id1 = got_object_id_dup(
3789 got_object_commit_get_tree_id(pcommit));
3790 if (tree_id1 == NULL) {
3791 got_object_commit_close(pcommit);
3792 return got_error_from_errno("got_object_id_dup");
3794 got_object_commit_close(pcommit);
3798 if (tree_id1) {
3799 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3800 if (err)
3801 goto done;
3804 tree_id2 = got_object_commit_get_tree_id(commit);
3805 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3806 if (err)
3807 goto done;
3809 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3810 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3811 done:
3812 if (tree1)
3813 got_object_tree_close(tree1);
3814 if (tree2)
3815 got_object_tree_close(tree2);
3816 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3817 err = got_error_from_errno("close");
3818 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3819 err = got_error_from_errno("close");
3820 if (f1 && fclose(f1) == EOF && err == NULL)
3821 err = got_error_from_errno("fclose");
3822 if (f2 && fclose(f2) == EOF && err == NULL)
3823 err = got_error_from_errno("fclose");
3824 free(tree_id1);
3825 return err;
3828 static const struct got_error *
3829 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3830 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3831 struct got_repository *repo, FILE *outfile)
3833 const struct got_error *err = NULL;
3834 struct got_commit_object *pcommit = NULL;
3835 char *id_str1 = NULL, *id_str2 = NULL;
3836 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3837 struct got_object_qid *qid;
3839 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3840 if (qid != NULL) {
3841 err = got_object_open_as_commit(&pcommit, repo,
3842 &qid->id);
3843 if (err)
3844 return err;
3845 err = got_object_id_str(&id_str1, &qid->id);
3846 if (err)
3847 goto done;
3850 err = got_object_id_str(&id_str2, id);
3851 if (err)
3852 goto done;
3854 if (path && path[0] != '\0') {
3855 int obj_type;
3856 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3857 if (err)
3858 goto done;
3859 if (pcommit) {
3860 err = got_object_id_by_path(&obj_id1, repo,
3861 pcommit, path);
3862 if (err) {
3863 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3864 free(obj_id2);
3865 goto done;
3869 err = got_object_get_type(&obj_type, repo, obj_id2);
3870 if (err) {
3871 free(obj_id2);
3872 goto done;
3874 fprintf(outfile,
3875 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3876 fprintf(outfile, "commit - %s\n",
3877 id_str1 ? id_str1 : "/dev/null");
3878 fprintf(outfile, "commit + %s\n", id_str2);
3879 switch (obj_type) {
3880 case GOT_OBJ_TYPE_BLOB:
3881 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3882 0, 0, dsa, repo, outfile);
3883 break;
3884 case GOT_OBJ_TYPE_TREE:
3885 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3886 0, 0, dsa, repo, outfile);
3887 break;
3888 default:
3889 err = got_error(GOT_ERR_OBJ_TYPE);
3890 break;
3892 free(obj_id1);
3893 free(obj_id2);
3894 } else {
3895 obj_id2 = got_object_commit_get_tree_id(commit);
3896 if (pcommit)
3897 obj_id1 = got_object_commit_get_tree_id(pcommit);
3898 fprintf(outfile,
3899 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3900 fprintf(outfile, "commit - %s\n",
3901 id_str1 ? id_str1 : "/dev/null");
3902 fprintf(outfile, "commit + %s\n", id_str2);
3903 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3904 dsa, repo, outfile);
3906 done:
3907 free(id_str1);
3908 free(id_str2);
3909 if (pcommit)
3910 got_object_commit_close(pcommit);
3911 return err;
3914 static char *
3915 get_datestr(time_t *time, char *datebuf)
3917 struct tm mytm, *tm;
3918 char *p, *s;
3920 tm = gmtime_r(time, &mytm);
3921 if (tm == NULL)
3922 return NULL;
3923 s = asctime_r(tm, datebuf);
3924 if (s == NULL)
3925 return NULL;
3926 p = strchr(s, '\n');
3927 if (p)
3928 *p = '\0';
3929 return s;
3932 static const struct got_error *
3933 match_commit(int *have_match, struct got_object_id *id,
3934 struct got_commit_object *commit, regex_t *regex)
3936 const struct got_error *err = NULL;
3937 regmatch_t regmatch;
3938 char *id_str = NULL, *logmsg = NULL;
3940 *have_match = 0;
3942 err = got_object_id_str(&id_str, id);
3943 if (err)
3944 return err;
3946 err = got_object_commit_get_logmsg(&logmsg, commit);
3947 if (err)
3948 goto done;
3950 if (regexec(regex, got_object_commit_get_author(commit), 1,
3951 &regmatch, 0) == 0 ||
3952 regexec(regex, got_object_commit_get_committer(commit), 1,
3953 &regmatch, 0) == 0 ||
3954 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3955 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3956 *have_match = 1;
3957 done:
3958 free(id_str);
3959 free(logmsg);
3960 return err;
3963 static void
3964 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3965 regex_t *regex)
3967 regmatch_t regmatch;
3968 struct got_pathlist_entry *pe;
3970 *have_match = 0;
3972 TAILQ_FOREACH(pe, changed_paths, entry) {
3973 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3974 *have_match = 1;
3975 break;
3980 static const struct got_error *
3981 match_patch(int *have_match, struct got_commit_object *commit,
3982 struct got_object_id *id, const char *path, int diff_context,
3983 struct got_repository *repo, regex_t *regex, FILE *f)
3985 const struct got_error *err = NULL;
3986 char *line = NULL;
3987 size_t linesize = 0;
3988 regmatch_t regmatch;
3990 *have_match = 0;
3992 err = got_opentemp_truncate(f);
3993 if (err)
3994 return err;
3996 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3997 if (err)
3998 goto done;
4000 if (fseeko(f, 0L, SEEK_SET) == -1) {
4001 err = got_error_from_errno("fseeko");
4002 goto done;
4005 while (getline(&line, &linesize, f) != -1) {
4006 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4007 *have_match = 1;
4008 break;
4011 done:
4012 free(line);
4013 return err;
4016 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4018 static const struct got_error*
4019 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4020 struct got_object_id *id, struct got_repository *repo,
4021 int local_only)
4023 static const struct got_error *err = NULL;
4024 struct got_reflist_entry *re;
4025 char *s;
4026 const char *name;
4028 *refs_str = NULL;
4030 TAILQ_FOREACH(re, refs, entry) {
4031 struct got_tag_object *tag = NULL;
4032 struct got_object_id *ref_id;
4033 int cmp;
4035 name = got_ref_get_name(re->ref);
4036 if (strcmp(name, GOT_REF_HEAD) == 0)
4037 continue;
4038 if (strncmp(name, "refs/", 5) == 0)
4039 name += 5;
4040 if (strncmp(name, "got/", 4) == 0)
4041 continue;
4042 if (strncmp(name, "heads/", 6) == 0)
4043 name += 6;
4044 if (strncmp(name, "remotes/", 8) == 0) {
4045 if (local_only)
4046 continue;
4047 name += 8;
4048 s = strstr(name, "/" GOT_REF_HEAD);
4049 if (s != NULL && s[strlen(s)] == '\0')
4050 continue;
4052 err = got_ref_resolve(&ref_id, repo, re->ref);
4053 if (err)
4054 break;
4055 if (strncmp(name, "tags/", 5) == 0) {
4056 err = got_object_open_as_tag(&tag, repo, ref_id);
4057 if (err) {
4058 if (err->code != GOT_ERR_OBJ_TYPE) {
4059 free(ref_id);
4060 break;
4062 /* Ref points at something other than a tag. */
4063 err = NULL;
4064 tag = NULL;
4067 cmp = got_object_id_cmp(tag ?
4068 got_object_tag_get_object_id(tag) : ref_id, id);
4069 free(ref_id);
4070 if (tag)
4071 got_object_tag_close(tag);
4072 if (cmp != 0)
4073 continue;
4074 s = *refs_str;
4075 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4076 s ? ", " : "", name) == -1) {
4077 err = got_error_from_errno("asprintf");
4078 free(s);
4079 *refs_str = NULL;
4080 break;
4082 free(s);
4085 return err;
4088 static const struct got_error *
4089 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4090 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4092 const struct got_error *err = NULL;
4093 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4094 char *comma, *s, *nl;
4095 struct got_reflist_head *refs;
4096 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4097 struct tm tm;
4098 time_t committer_time;
4100 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4101 if (refs) {
4102 err = build_refs_str(&ref_str, refs, id, repo, 1);
4103 if (err)
4104 return err;
4106 /* Display the first matching ref only. */
4107 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4108 *comma = '\0';
4111 if (ref_str == NULL) {
4112 err = got_object_id_str(&id_str, id);
4113 if (err)
4114 return err;
4117 committer_time = got_object_commit_get_committer_time(commit);
4118 if (gmtime_r(&committer_time, &tm) == NULL) {
4119 err = got_error_from_errno("gmtime_r");
4120 goto done;
4122 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4123 err = got_error(GOT_ERR_NO_SPACE);
4124 goto done;
4127 err = got_object_commit_get_logmsg(&logmsg0, commit);
4128 if (err)
4129 goto done;
4131 s = logmsg0;
4132 while (isspace((unsigned char)s[0]))
4133 s++;
4135 nl = strchr(s, '\n');
4136 if (nl) {
4137 *nl = '\0';
4140 if (ref_str)
4141 printf("%s%-7s %s\n", datebuf, ref_str, s);
4142 else
4143 printf("%s%.7s %s\n", datebuf, id_str, s);
4145 if (fflush(stdout) != 0 && err == NULL)
4146 err = got_error_from_errno("fflush");
4147 done:
4148 free(id_str);
4149 free(ref_str);
4150 free(logmsg0);
4151 return err;
4154 static const struct got_error *
4155 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4157 struct got_pathlist_entry *pe;
4159 if (header != NULL)
4160 printf("%s\n", header);
4162 TAILQ_FOREACH(pe, dsa->paths, entry) {
4163 struct got_diff_changed_path *cp = pe->data;
4164 int pad = dsa->max_path_len - pe->path_len + 1;
4166 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4167 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4169 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4170 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4171 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4173 if (fflush(stdout) != 0)
4174 return got_error_from_errno("fflush");
4176 return NULL;
4179 static const struct got_error *
4180 printfile(FILE *f)
4182 char buf[8192];
4183 size_t r;
4185 if (fseeko(f, 0L, SEEK_SET) == -1)
4186 return got_error_from_errno("fseek");
4188 for (;;) {
4189 r = fread(buf, 1, sizeof(buf), f);
4190 if (r == 0) {
4191 if (ferror(f))
4192 return got_error_from_errno("fread");
4193 if (feof(f))
4194 break;
4196 if (fwrite(buf, 1, r, stdout) != r)
4197 return got_ferror(stdout, GOT_ERR_IO);
4200 return NULL;
4203 static const struct got_error *
4204 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4205 struct got_repository *repo, const char *path,
4206 struct got_pathlist_head *changed_paths,
4207 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4208 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4209 const char *prefix)
4211 const struct got_error *err = NULL;
4212 FILE *f = NULL;
4213 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4214 char datebuf[26];
4215 time_t committer_time;
4216 const char *author, *committer;
4217 char *refs_str = NULL;
4219 err = got_object_id_str(&id_str, id);
4220 if (err)
4221 return err;
4223 if (custom_refs_str == NULL) {
4224 struct got_reflist_head *refs;
4225 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4226 if (refs) {
4227 err = build_refs_str(&refs_str, refs, id, repo, 0);
4228 if (err)
4229 goto done;
4233 printf(GOT_COMMIT_SEP_STR);
4234 if (custom_refs_str)
4235 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4236 custom_refs_str);
4237 else
4238 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4239 refs_str ? " (" : "", refs_str ? refs_str : "",
4240 refs_str ? ")" : "");
4241 free(id_str);
4242 id_str = NULL;
4243 free(refs_str);
4244 refs_str = NULL;
4245 printf("from: %s\n", got_object_commit_get_author(commit));
4246 author = got_object_commit_get_author(commit);
4247 committer = got_object_commit_get_committer(commit);
4248 if (strcmp(author, committer) != 0)
4249 printf("via: %s\n", committer);
4250 committer_time = got_object_commit_get_committer_time(commit);
4251 datestr = get_datestr(&committer_time, datebuf);
4252 if (datestr)
4253 printf("date: %s UTC\n", datestr);
4254 if (got_object_commit_get_nparents(commit) > 1) {
4255 const struct got_object_id_queue *parent_ids;
4256 struct got_object_qid *qid;
4257 int n = 1;
4258 parent_ids = got_object_commit_get_parent_ids(commit);
4259 STAILQ_FOREACH(qid, parent_ids, entry) {
4260 err = got_object_id_str(&id_str, &qid->id);
4261 if (err)
4262 goto done;
4263 printf("parent %d: %s\n", n++, id_str);
4264 free(id_str);
4265 id_str = NULL;
4269 err = got_object_commit_get_logmsg(&logmsg0, commit);
4270 if (err)
4271 goto done;
4273 logmsg = logmsg0;
4274 do {
4275 line = strsep(&logmsg, "\n");
4276 if (line)
4277 printf(" %s\n", line);
4278 } while (line);
4279 free(logmsg0);
4281 if (changed_paths && diffstat == NULL) {
4282 struct got_pathlist_entry *pe;
4284 TAILQ_FOREACH(pe, changed_paths, entry) {
4285 struct got_diff_changed_path *cp = pe->data;
4287 printf(" %c %s\n", cp->status, pe->path);
4289 printf("\n");
4291 if (show_patch) {
4292 if (diffstat) {
4293 f = got_opentemp();
4294 if (f == NULL) {
4295 err = got_error_from_errno("got_opentemp");
4296 goto done;
4300 err = print_patch(commit, id, path, diff_context, diffstat,
4301 repo, diffstat == NULL ? stdout : f);
4302 if (err)
4303 goto done;
4305 if (diffstat) {
4306 err = print_diffstat(diffstat, NULL);
4307 if (err)
4308 goto done;
4309 if (show_patch) {
4310 err = printfile(f);
4311 if (err)
4312 goto done;
4315 if (show_patch)
4316 printf("\n");
4318 if (fflush(stdout) != 0 && err == NULL)
4319 err = got_error_from_errno("fflush");
4320 done:
4321 if (f && fclose(f) == EOF && err == NULL)
4322 err = got_error_from_errno("fclose");
4323 free(id_str);
4324 free(refs_str);
4325 return err;
4328 static const struct got_error *
4329 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4330 struct got_repository *repo, const char *path, int show_changed_paths,
4331 int show_diffstat, int show_patch, const char *search_pattern,
4332 int diff_context, int limit, int log_branches, int reverse_display_order,
4333 struct got_reflist_object_id_map *refs_idmap, int one_line,
4334 FILE *tmpfile)
4336 const struct got_error *err;
4337 struct got_commit_graph *graph;
4338 regex_t regex;
4339 int have_match;
4340 struct got_object_id_queue reversed_commits;
4341 struct got_object_qid *qid;
4342 struct got_commit_object *commit;
4343 struct got_pathlist_head changed_paths;
4345 STAILQ_INIT(&reversed_commits);
4346 TAILQ_INIT(&changed_paths);
4348 if (search_pattern && regcomp(&regex, search_pattern,
4349 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4350 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4352 err = got_commit_graph_open(&graph, path, !log_branches);
4353 if (err)
4354 return err;
4355 err = got_commit_graph_iter_start(graph, root_id, repo,
4356 check_cancelled, NULL);
4357 if (err)
4358 goto done;
4359 for (;;) {
4360 struct got_object_id id;
4361 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4362 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4364 if (sigint_received || sigpipe_received)
4365 break;
4367 err = got_commit_graph_iter_next(&id, graph, repo,
4368 check_cancelled, NULL);
4369 if (err) {
4370 if (err->code == GOT_ERR_ITER_COMPLETED)
4371 err = NULL;
4372 break;
4375 err = got_object_open_as_commit(&commit, repo, &id);
4376 if (err)
4377 break;
4379 if ((show_changed_paths || (show_diffstat && !show_patch))
4380 && !reverse_display_order) {
4381 err = get_changed_paths(&changed_paths, commit, repo,
4382 show_diffstat ? &dsa : NULL);
4383 if (err)
4384 break;
4387 if (search_pattern) {
4388 err = match_commit(&have_match, &id, commit, &regex);
4389 if (err) {
4390 got_object_commit_close(commit);
4391 break;
4393 if (have_match == 0 && show_changed_paths)
4394 match_changed_paths(&have_match,
4395 &changed_paths, &regex);
4396 if (have_match == 0 && show_patch) {
4397 err = match_patch(&have_match, commit, &id,
4398 path, diff_context, repo, &regex, tmpfile);
4399 if (err)
4400 break;
4402 if (have_match == 0) {
4403 got_object_commit_close(commit);
4404 got_pathlist_free(&changed_paths,
4405 GOT_PATHLIST_FREE_ALL);
4406 continue;
4410 if (reverse_display_order) {
4411 err = got_object_qid_alloc(&qid, &id);
4412 if (err)
4413 break;
4414 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4415 got_object_commit_close(commit);
4416 } else {
4417 if (one_line)
4418 err = print_commit_oneline(commit, &id,
4419 repo, refs_idmap);
4420 else
4421 err = print_commit(commit, &id, repo, path,
4422 (show_changed_paths || show_diffstat) ?
4423 &changed_paths : NULL,
4424 show_diffstat ? &dsa : NULL, show_patch,
4425 diff_context, refs_idmap, NULL, NULL);
4426 got_object_commit_close(commit);
4427 if (err)
4428 break;
4430 if ((limit && --limit == 0) ||
4431 (end_id && got_object_id_cmp(&id, end_id) == 0))
4432 break;
4434 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4436 if (reverse_display_order) {
4437 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4438 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4439 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4441 err = got_object_open_as_commit(&commit, repo,
4442 &qid->id);
4443 if (err)
4444 break;
4445 if (show_changed_paths ||
4446 (show_diffstat && !show_patch)) {
4447 err = get_changed_paths(&changed_paths, commit,
4448 repo, show_diffstat ? &dsa : NULL);
4449 if (err)
4450 break;
4452 if (one_line)
4453 err = print_commit_oneline(commit, &qid->id,
4454 repo, refs_idmap);
4455 else
4456 err = print_commit(commit, &qid->id, repo, path,
4457 (show_changed_paths || show_diffstat) ?
4458 &changed_paths : NULL,
4459 show_diffstat ? &dsa : NULL, show_patch,
4460 diff_context, refs_idmap, NULL, NULL);
4461 got_object_commit_close(commit);
4462 if (err)
4463 break;
4464 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4467 done:
4468 while (!STAILQ_EMPTY(&reversed_commits)) {
4469 qid = STAILQ_FIRST(&reversed_commits);
4470 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4471 got_object_qid_free(qid);
4473 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4474 if (search_pattern)
4475 regfree(&regex);
4476 got_commit_graph_close(graph);
4477 return err;
4480 __dead static void
4481 usage_log(void)
4483 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4484 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4485 "[path]\n", getprogname());
4486 exit(1);
4489 static int
4490 get_default_log_limit(void)
4492 const char *got_default_log_limit;
4493 long long n;
4494 const char *errstr;
4496 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4497 if (got_default_log_limit == NULL)
4498 return 0;
4499 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4500 if (errstr != NULL)
4501 return 0;
4502 return n;
4505 static const struct got_error *
4506 cmd_log(int argc, char *argv[])
4508 const struct got_error *error;
4509 struct got_repository *repo = NULL;
4510 struct got_worktree *worktree = NULL;
4511 struct got_object_id *start_id = NULL, *end_id = NULL;
4512 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4513 const char *start_commit = NULL, *end_commit = NULL;
4514 const char *search_pattern = NULL;
4515 int diff_context = -1, ch;
4516 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4517 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4518 const char *errstr;
4519 struct got_reflist_head refs;
4520 struct got_reflist_object_id_map *refs_idmap = NULL;
4521 FILE *tmpfile = NULL;
4522 int *pack_fds = NULL;
4524 TAILQ_INIT(&refs);
4526 #ifndef PROFILE
4527 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4528 NULL)
4529 == -1)
4530 err(1, "pledge");
4531 #endif
4533 limit = get_default_log_limit();
4535 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4536 switch (ch) {
4537 case 'b':
4538 log_branches = 1;
4539 break;
4540 case 'C':
4541 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4542 &errstr);
4543 if (errstr != NULL)
4544 errx(1, "number of context lines is %s: %s",
4545 errstr, optarg);
4546 break;
4547 case 'c':
4548 start_commit = optarg;
4549 break;
4550 case 'd':
4551 show_diffstat = 1;
4552 break;
4553 case 'l':
4554 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4555 if (errstr != NULL)
4556 errx(1, "number of commits is %s: %s",
4557 errstr, optarg);
4558 break;
4559 case 'P':
4560 show_changed_paths = 1;
4561 break;
4562 case 'p':
4563 show_patch = 1;
4564 break;
4565 case 'R':
4566 reverse_display_order = 1;
4567 break;
4568 case 'r':
4569 repo_path = realpath(optarg, NULL);
4570 if (repo_path == NULL)
4571 return got_error_from_errno2("realpath",
4572 optarg);
4573 got_path_strip_trailing_slashes(repo_path);
4574 break;
4575 case 'S':
4576 search_pattern = optarg;
4577 break;
4578 case 's':
4579 one_line = 1;
4580 break;
4581 case 'x':
4582 end_commit = optarg;
4583 break;
4584 default:
4585 usage_log();
4586 /* NOTREACHED */
4590 argc -= optind;
4591 argv += optind;
4593 if (diff_context == -1)
4594 diff_context = 3;
4595 else if (!show_patch)
4596 errx(1, "-C requires -p");
4598 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4599 errx(1, "cannot use -s with -d, -p or -P");
4601 cwd = getcwd(NULL, 0);
4602 if (cwd == NULL) {
4603 error = got_error_from_errno("getcwd");
4604 goto done;
4607 error = got_repo_pack_fds_open(&pack_fds);
4608 if (error != NULL)
4609 goto done;
4611 if (repo_path == NULL) {
4612 error = got_worktree_open(&worktree, cwd);
4613 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4614 goto done;
4615 error = NULL;
4618 if (argc == 1) {
4619 if (worktree) {
4620 error = got_worktree_resolve_path(&path, worktree,
4621 argv[0]);
4622 if (error)
4623 goto done;
4624 } else {
4625 path = strdup(argv[0]);
4626 if (path == NULL) {
4627 error = got_error_from_errno("strdup");
4628 goto done;
4631 } else if (argc != 0)
4632 usage_log();
4634 if (repo_path == NULL) {
4635 repo_path = worktree ?
4636 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4638 if (repo_path == NULL) {
4639 error = got_error_from_errno("strdup");
4640 goto done;
4643 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4644 if (error != NULL)
4645 goto done;
4647 error = apply_unveil(got_repo_get_path(repo), 1,
4648 worktree ? got_worktree_get_root_path(worktree) : NULL);
4649 if (error)
4650 goto done;
4652 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4653 if (error)
4654 goto done;
4656 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4657 if (error)
4658 goto done;
4660 if (start_commit == NULL) {
4661 struct got_reference *head_ref;
4662 struct got_commit_object *commit = NULL;
4663 error = got_ref_open(&head_ref, repo,
4664 worktree ? got_worktree_get_head_ref_name(worktree)
4665 : GOT_REF_HEAD, 0);
4666 if (error != NULL)
4667 goto done;
4668 error = got_ref_resolve(&start_id, repo, head_ref);
4669 got_ref_close(head_ref);
4670 if (error != NULL)
4671 goto done;
4672 error = got_object_open_as_commit(&commit, repo,
4673 start_id);
4674 if (error != NULL)
4675 goto done;
4676 got_object_commit_close(commit);
4677 } else {
4678 error = got_repo_match_object_id(&start_id, NULL,
4679 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4680 if (error != NULL)
4681 goto done;
4683 if (end_commit != NULL) {
4684 error = got_repo_match_object_id(&end_id, NULL,
4685 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4686 if (error != NULL)
4687 goto done;
4690 if (worktree) {
4692 * If a path was specified on the command line it was resolved
4693 * to a path in the work tree above. Prepend the work tree's
4694 * path prefix to obtain the corresponding in-repository path.
4696 if (path) {
4697 const char *prefix;
4698 prefix = got_worktree_get_path_prefix(worktree);
4699 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4700 (path[0] != '\0') ? "/" : "", path) == -1) {
4701 error = got_error_from_errno("asprintf");
4702 goto done;
4705 } else
4706 error = got_repo_map_path(&in_repo_path, repo,
4707 path ? path : "");
4708 if (error != NULL)
4709 goto done;
4710 if (in_repo_path) {
4711 free(path);
4712 path = in_repo_path;
4715 if (worktree) {
4716 /* Release work tree lock. */
4717 got_worktree_close(worktree);
4718 worktree = NULL;
4721 if (search_pattern && show_patch) {
4722 tmpfile = got_opentemp();
4723 if (tmpfile == NULL) {
4724 error = got_error_from_errno("got_opentemp");
4725 goto done;
4729 error = print_commits(start_id, end_id, repo, path ? path : "",
4730 show_changed_paths, show_diffstat, show_patch, search_pattern,
4731 diff_context, limit, log_branches, reverse_display_order,
4732 refs_idmap, one_line, tmpfile);
4733 done:
4734 free(path);
4735 free(repo_path);
4736 free(cwd);
4737 if (worktree)
4738 got_worktree_close(worktree);
4739 if (repo) {
4740 const struct got_error *close_err = got_repo_close(repo);
4741 if (error == NULL)
4742 error = close_err;
4744 if (pack_fds) {
4745 const struct got_error *pack_err =
4746 got_repo_pack_fds_close(pack_fds);
4747 if (error == NULL)
4748 error = pack_err;
4750 if (refs_idmap)
4751 got_reflist_object_id_map_free(refs_idmap);
4752 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4753 error = got_error_from_errno("fclose");
4754 got_ref_list_free(&refs);
4755 return error;
4758 __dead static void
4759 usage_diff(void)
4761 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4762 "[-r repository-path] [object1 object2 | path ...]\n",
4763 getprogname());
4764 exit(1);
4767 struct print_diff_arg {
4768 struct got_repository *repo;
4769 struct got_worktree *worktree;
4770 struct got_diffstat_cb_arg *diffstat;
4771 int diff_context;
4772 const char *id_str;
4773 int header_shown;
4774 int diff_staged;
4775 enum got_diff_algorithm diff_algo;
4776 int ignore_whitespace;
4777 int force_text_diff;
4778 FILE *f1;
4779 FILE *f2;
4780 FILE *outfile;
4784 * Create a file which contains the target path of a symlink so we can feed
4785 * it as content to the diff engine.
4787 static const struct got_error *
4788 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4789 const char *abspath)
4791 const struct got_error *err = NULL;
4792 char target_path[PATH_MAX];
4793 ssize_t target_len, outlen;
4795 *fd = -1;
4797 if (dirfd != -1) {
4798 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4799 if (target_len == -1)
4800 return got_error_from_errno2("readlinkat", abspath);
4801 } else {
4802 target_len = readlink(abspath, target_path, PATH_MAX);
4803 if (target_len == -1)
4804 return got_error_from_errno2("readlink", abspath);
4807 *fd = got_opentempfd();
4808 if (*fd == -1)
4809 return got_error_from_errno("got_opentempfd");
4811 outlen = write(*fd, target_path, target_len);
4812 if (outlen == -1) {
4813 err = got_error_from_errno("got_opentempfd");
4814 goto done;
4817 if (lseek(*fd, 0, SEEK_SET) == -1) {
4818 err = got_error_from_errno2("lseek", abspath);
4819 goto done;
4821 done:
4822 if (err) {
4823 close(*fd);
4824 *fd = -1;
4826 return err;
4829 static const struct got_error *
4830 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4831 const char *path, struct got_object_id *blob_id,
4832 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4833 int dirfd, const char *de_name)
4835 struct print_diff_arg *a = arg;
4836 const struct got_error *err = NULL;
4837 struct got_blob_object *blob1 = NULL;
4838 int fd = -1, fd1 = -1, fd2 = -1;
4839 FILE *f2 = NULL;
4840 char *abspath = NULL, *label1 = NULL;
4841 struct stat sb;
4842 off_t size1 = 0;
4843 int f2_exists = 0;
4845 memset(&sb, 0, sizeof(sb));
4847 if (a->diff_staged) {
4848 if (staged_status != GOT_STATUS_MODIFY &&
4849 staged_status != GOT_STATUS_ADD &&
4850 staged_status != GOT_STATUS_DELETE)
4851 return NULL;
4852 } else {
4853 if (staged_status == GOT_STATUS_DELETE)
4854 return NULL;
4855 if (status == GOT_STATUS_NONEXISTENT)
4856 return got_error_set_errno(ENOENT, path);
4857 if (status != GOT_STATUS_MODIFY &&
4858 status != GOT_STATUS_ADD &&
4859 status != GOT_STATUS_DELETE &&
4860 status != GOT_STATUS_CONFLICT)
4861 return NULL;
4864 err = got_opentemp_truncate(a->f1);
4865 if (err)
4866 return got_error_from_errno("got_opentemp_truncate");
4867 err = got_opentemp_truncate(a->f2);
4868 if (err)
4869 return got_error_from_errno("got_opentemp_truncate");
4871 if (!a->header_shown) {
4872 if (fprintf(a->outfile, "diff %s%s\n",
4873 a->diff_staged ? "-s " : "",
4874 got_worktree_get_root_path(a->worktree)) < 0) {
4875 err = got_error_from_errno("fprintf");
4876 goto done;
4878 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4879 err = got_error_from_errno("fprintf");
4880 goto done;
4882 if (fprintf(a->outfile, "path + %s%s\n",
4883 got_worktree_get_root_path(a->worktree),
4884 a->diff_staged ? " (staged changes)" : "") < 0) {
4885 err = got_error_from_errno("fprintf");
4886 goto done;
4888 a->header_shown = 1;
4891 if (a->diff_staged) {
4892 const char *label1 = NULL, *label2 = NULL;
4893 switch (staged_status) {
4894 case GOT_STATUS_MODIFY:
4895 label1 = path;
4896 label2 = path;
4897 break;
4898 case GOT_STATUS_ADD:
4899 label2 = path;
4900 break;
4901 case GOT_STATUS_DELETE:
4902 label1 = path;
4903 break;
4904 default:
4905 return got_error(GOT_ERR_FILE_STATUS);
4907 fd1 = got_opentempfd();
4908 if (fd1 == -1) {
4909 err = got_error_from_errno("got_opentempfd");
4910 goto done;
4912 fd2 = got_opentempfd();
4913 if (fd2 == -1) {
4914 err = got_error_from_errno("got_opentempfd");
4915 goto done;
4917 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4918 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4919 a->diff_algo, a->diff_context, a->ignore_whitespace,
4920 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4921 goto done;
4924 fd1 = got_opentempfd();
4925 if (fd1 == -1) {
4926 err = got_error_from_errno("got_opentempfd");
4927 goto done;
4930 if (staged_status == GOT_STATUS_ADD ||
4931 staged_status == GOT_STATUS_MODIFY) {
4932 char *id_str;
4933 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4934 8192, fd1);
4935 if (err)
4936 goto done;
4937 err = got_object_id_str(&id_str, staged_blob_id);
4938 if (err)
4939 goto done;
4940 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4941 err = got_error_from_errno("asprintf");
4942 free(id_str);
4943 goto done;
4945 free(id_str);
4946 } else if (status != GOT_STATUS_ADD) {
4947 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4948 fd1);
4949 if (err)
4950 goto done;
4953 if (status != GOT_STATUS_DELETE) {
4954 if (asprintf(&abspath, "%s/%s",
4955 got_worktree_get_root_path(a->worktree), path) == -1) {
4956 err = got_error_from_errno("asprintf");
4957 goto done;
4960 if (dirfd != -1) {
4961 fd = openat(dirfd, de_name,
4962 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4963 if (fd == -1) {
4964 if (!got_err_open_nofollow_on_symlink()) {
4965 err = got_error_from_errno2("openat",
4966 abspath);
4967 goto done;
4969 err = get_symlink_target_file(&fd, dirfd,
4970 de_name, abspath);
4971 if (err)
4972 goto done;
4974 } else {
4975 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4976 if (fd == -1) {
4977 if (!got_err_open_nofollow_on_symlink()) {
4978 err = got_error_from_errno2("open",
4979 abspath);
4980 goto done;
4982 err = get_symlink_target_file(&fd, dirfd,
4983 de_name, abspath);
4984 if (err)
4985 goto done;
4988 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4989 err = got_error_from_errno2("fstatat", abspath);
4990 goto done;
4992 f2 = fdopen(fd, "r");
4993 if (f2 == NULL) {
4994 err = got_error_from_errno2("fdopen", abspath);
4995 goto done;
4997 fd = -1;
4998 f2_exists = 1;
5001 if (blob1) {
5002 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5003 a->f1, blob1);
5004 if (err)
5005 goto done;
5008 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5009 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5010 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5011 done:
5012 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5013 err = got_error_from_errno("close");
5014 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5015 err = got_error_from_errno("close");
5016 if (blob1)
5017 got_object_blob_close(blob1);
5018 if (fd != -1 && close(fd) == -1 && err == NULL)
5019 err = got_error_from_errno("close");
5020 if (f2 && fclose(f2) == EOF && err == NULL)
5021 err = got_error_from_errno("fclose");
5022 free(abspath);
5023 return err;
5026 static const struct got_error *
5027 cmd_diff(int argc, char *argv[])
5029 const struct got_error *error;
5030 struct got_repository *repo = NULL;
5031 struct got_worktree *worktree = NULL;
5032 char *cwd = NULL, *repo_path = NULL;
5033 const char *commit_args[2] = { NULL, NULL };
5034 int ncommit_args = 0;
5035 struct got_object_id *ids[2] = { NULL, NULL };
5036 char *labels[2] = { NULL, NULL };
5037 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5038 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5039 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5040 const char *errstr;
5041 struct got_reflist_head refs;
5042 struct got_pathlist_head diffstat_paths, paths;
5043 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5044 int fd1 = -1, fd2 = -1;
5045 int *pack_fds = NULL;
5046 struct got_diffstat_cb_arg dsa;
5048 memset(&dsa, 0, sizeof(dsa));
5050 TAILQ_INIT(&refs);
5051 TAILQ_INIT(&paths);
5052 TAILQ_INIT(&diffstat_paths);
5054 #ifndef PROFILE
5055 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5056 NULL) == -1)
5057 err(1, "pledge");
5058 #endif
5060 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5061 switch (ch) {
5062 case 'a':
5063 force_text_diff = 1;
5064 break;
5065 case 'C':
5066 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5067 &errstr);
5068 if (errstr != NULL)
5069 errx(1, "number of context lines is %s: %s",
5070 errstr, optarg);
5071 break;
5072 case 'c':
5073 if (ncommit_args >= 2)
5074 errx(1, "too many -c options used");
5075 commit_args[ncommit_args++] = optarg;
5076 break;
5077 case 'd':
5078 show_diffstat = 1;
5079 break;
5080 case 'P':
5081 force_path = 1;
5082 break;
5083 case 'r':
5084 repo_path = realpath(optarg, NULL);
5085 if (repo_path == NULL)
5086 return got_error_from_errno2("realpath",
5087 optarg);
5088 got_path_strip_trailing_slashes(repo_path);
5089 rflag = 1;
5090 break;
5091 case 's':
5092 diff_staged = 1;
5093 break;
5094 case 'w':
5095 ignore_whitespace = 1;
5096 break;
5097 default:
5098 usage_diff();
5099 /* NOTREACHED */
5103 argc -= optind;
5104 argv += optind;
5106 cwd = getcwd(NULL, 0);
5107 if (cwd == NULL) {
5108 error = got_error_from_errno("getcwd");
5109 goto done;
5112 error = got_repo_pack_fds_open(&pack_fds);
5113 if (error != NULL)
5114 goto done;
5116 if (repo_path == NULL) {
5117 error = got_worktree_open(&worktree, cwd);
5118 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5119 goto done;
5120 else
5121 error = NULL;
5122 if (worktree) {
5123 repo_path =
5124 strdup(got_worktree_get_repo_path(worktree));
5125 if (repo_path == NULL) {
5126 error = got_error_from_errno("strdup");
5127 goto done;
5129 } else {
5130 repo_path = strdup(cwd);
5131 if (repo_path == NULL) {
5132 error = got_error_from_errno("strdup");
5133 goto done;
5138 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5139 free(repo_path);
5140 if (error != NULL)
5141 goto done;
5143 if (show_diffstat) {
5144 dsa.paths = &diffstat_paths;
5145 dsa.force_text = force_text_diff;
5146 dsa.ignore_ws = ignore_whitespace;
5147 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5150 if (rflag || worktree == NULL || ncommit_args > 0) {
5151 if (force_path) {
5152 error = got_error_msg(GOT_ERR_NOT_IMPL,
5153 "-P option can only be used when diffing "
5154 "a work tree");
5155 goto done;
5157 if (diff_staged) {
5158 error = got_error_msg(GOT_ERR_NOT_IMPL,
5159 "-s option can only be used when diffing "
5160 "a work tree");
5161 goto done;
5165 error = apply_unveil(got_repo_get_path(repo), 1,
5166 worktree ? got_worktree_get_root_path(worktree) : NULL);
5167 if (error)
5168 goto done;
5170 if ((!force_path && argc == 2) || ncommit_args > 0) {
5171 int obj_type = (ncommit_args > 0 ?
5172 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5173 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5174 NULL);
5175 if (error)
5176 goto done;
5177 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5178 const char *arg;
5179 if (ncommit_args > 0)
5180 arg = commit_args[i];
5181 else
5182 arg = argv[i];
5183 error = got_repo_match_object_id(&ids[i], &labels[i],
5184 arg, obj_type, &refs, repo);
5185 if (error) {
5186 if (error->code != GOT_ERR_NOT_REF &&
5187 error->code != GOT_ERR_NO_OBJ)
5188 goto done;
5189 if (ncommit_args > 0)
5190 goto done;
5191 error = NULL;
5192 break;
5197 f1 = got_opentemp();
5198 if (f1 == NULL) {
5199 error = got_error_from_errno("got_opentemp");
5200 goto done;
5203 f2 = got_opentemp();
5204 if (f2 == NULL) {
5205 error = got_error_from_errno("got_opentemp");
5206 goto done;
5209 outfile = got_opentemp();
5210 if (outfile == NULL) {
5211 error = got_error_from_errno("got_opentemp");
5212 goto done;
5215 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5216 struct print_diff_arg arg;
5217 char *id_str;
5219 if (worktree == NULL) {
5220 if (argc == 2 && ids[0] == NULL) {
5221 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5222 goto done;
5223 } else if (argc == 2 && ids[1] == NULL) {
5224 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5225 goto done;
5226 } else if (argc > 0) {
5227 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5228 "%s", "specified paths cannot be resolved");
5229 goto done;
5230 } else {
5231 error = got_error(GOT_ERR_NOT_WORKTREE);
5232 goto done;
5236 error = get_worktree_paths_from_argv(&paths, argc, argv,
5237 worktree);
5238 if (error)
5239 goto done;
5241 error = got_object_id_str(&id_str,
5242 got_worktree_get_base_commit_id(worktree));
5243 if (error)
5244 goto done;
5245 arg.repo = repo;
5246 arg.worktree = worktree;
5247 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5248 arg.diff_context = diff_context;
5249 arg.id_str = id_str;
5250 arg.header_shown = 0;
5251 arg.diff_staged = diff_staged;
5252 arg.ignore_whitespace = ignore_whitespace;
5253 arg.force_text_diff = force_text_diff;
5254 arg.diffstat = show_diffstat ? &dsa : NULL;
5255 arg.f1 = f1;
5256 arg.f2 = f2;
5257 arg.outfile = outfile;
5259 error = got_worktree_status(worktree, &paths, repo, 0,
5260 print_diff, &arg, check_cancelled, NULL);
5261 free(id_str);
5262 if (error)
5263 goto done;
5265 if (show_diffstat && dsa.nfiles > 0) {
5266 char *header;
5268 if (asprintf(&header, "diffstat %s%s",
5269 diff_staged ? "-s " : "",
5270 got_worktree_get_root_path(worktree)) == -1) {
5271 error = got_error_from_errno("asprintf");
5272 goto done;
5275 error = print_diffstat(&dsa, header);
5276 free(header);
5277 if (error)
5278 goto done;
5281 error = printfile(outfile);
5282 goto done;
5285 if (ncommit_args == 1) {
5286 struct got_commit_object *commit;
5287 error = got_object_open_as_commit(&commit, repo, ids[0]);
5288 if (error)
5289 goto done;
5291 labels[1] = labels[0];
5292 ids[1] = ids[0];
5293 if (got_object_commit_get_nparents(commit) > 0) {
5294 const struct got_object_id_queue *pids;
5295 struct got_object_qid *pid;
5296 pids = got_object_commit_get_parent_ids(commit);
5297 pid = STAILQ_FIRST(pids);
5298 ids[0] = got_object_id_dup(&pid->id);
5299 if (ids[0] == NULL) {
5300 error = got_error_from_errno(
5301 "got_object_id_dup");
5302 got_object_commit_close(commit);
5303 goto done;
5305 error = got_object_id_str(&labels[0], ids[0]);
5306 if (error) {
5307 got_object_commit_close(commit);
5308 goto done;
5310 } else {
5311 ids[0] = NULL;
5312 labels[0] = strdup("/dev/null");
5313 if (labels[0] == NULL) {
5314 error = got_error_from_errno("strdup");
5315 got_object_commit_close(commit);
5316 goto done;
5320 got_object_commit_close(commit);
5323 if (ncommit_args == 0 && argc > 2) {
5324 error = got_error_msg(GOT_ERR_BAD_PATH,
5325 "path arguments cannot be used when diffing two objects");
5326 goto done;
5329 if (ids[0]) {
5330 error = got_object_get_type(&type1, repo, ids[0]);
5331 if (error)
5332 goto done;
5335 error = got_object_get_type(&type2, repo, ids[1]);
5336 if (error)
5337 goto done;
5338 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5339 error = got_error(GOT_ERR_OBJ_TYPE);
5340 goto done;
5342 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5343 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5344 "path arguments cannot be used when diffing blobs");
5345 goto done;
5348 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5349 char *in_repo_path;
5350 struct got_pathlist_entry *new;
5351 if (worktree) {
5352 const char *prefix;
5353 char *p;
5354 error = got_worktree_resolve_path(&p, worktree,
5355 argv[i]);
5356 if (error)
5357 goto done;
5358 prefix = got_worktree_get_path_prefix(worktree);
5359 while (prefix[0] == '/')
5360 prefix++;
5361 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5362 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5363 p) == -1) {
5364 error = got_error_from_errno("asprintf");
5365 free(p);
5366 goto done;
5368 free(p);
5369 } else {
5370 char *mapped_path, *s;
5371 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5372 if (error)
5373 goto done;
5374 s = mapped_path;
5375 while (s[0] == '/')
5376 s++;
5377 in_repo_path = strdup(s);
5378 if (in_repo_path == NULL) {
5379 error = got_error_from_errno("asprintf");
5380 free(mapped_path);
5381 goto done;
5383 free(mapped_path);
5386 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5387 if (error || new == NULL /* duplicate */)
5388 free(in_repo_path);
5389 if (error)
5390 goto done;
5393 if (worktree) {
5394 /* Release work tree lock. */
5395 got_worktree_close(worktree);
5396 worktree = NULL;
5399 fd1 = got_opentempfd();
5400 if (fd1 == -1) {
5401 error = got_error_from_errno("got_opentempfd");
5402 goto done;
5405 fd2 = got_opentempfd();
5406 if (fd2 == -1) {
5407 error = got_error_from_errno("got_opentempfd");
5408 goto done;
5411 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5412 case GOT_OBJ_TYPE_BLOB:
5413 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5414 fd1, fd2, ids[0], ids[1], NULL, NULL,
5415 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5416 ignore_whitespace, force_text_diff,
5417 show_diffstat ? &dsa : NULL, repo, outfile);
5418 break;
5419 case GOT_OBJ_TYPE_TREE:
5420 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5421 ids[0], ids[1], &paths, "", "",
5422 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5423 ignore_whitespace, force_text_diff,
5424 show_diffstat ? &dsa : NULL, repo, outfile);
5425 break;
5426 case GOT_OBJ_TYPE_COMMIT:
5427 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5428 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5429 fd1, fd2, ids[0], ids[1], &paths,
5430 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5431 ignore_whitespace, force_text_diff,
5432 show_diffstat ? &dsa : NULL, repo, outfile);
5433 break;
5434 default:
5435 error = got_error(GOT_ERR_OBJ_TYPE);
5437 if (error)
5438 goto done;
5440 if (show_diffstat && dsa.nfiles > 0) {
5441 char *header = NULL;
5443 if (asprintf(&header, "diffstat %s %s",
5444 labels[0], labels[1]) == -1) {
5445 error = got_error_from_errno("asprintf");
5446 goto done;
5449 error = print_diffstat(&dsa, header);
5450 free(header);
5451 if (error)
5452 goto done;
5455 error = printfile(outfile);
5457 done:
5458 free(labels[0]);
5459 free(labels[1]);
5460 free(ids[0]);
5461 free(ids[1]);
5462 if (worktree)
5463 got_worktree_close(worktree);
5464 if (repo) {
5465 const struct got_error *close_err = got_repo_close(repo);
5466 if (error == NULL)
5467 error = close_err;
5469 if (pack_fds) {
5470 const struct got_error *pack_err =
5471 got_repo_pack_fds_close(pack_fds);
5472 if (error == NULL)
5473 error = pack_err;
5475 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5476 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5477 got_ref_list_free(&refs);
5478 if (outfile && fclose(outfile) == EOF && error == NULL)
5479 error = got_error_from_errno("fclose");
5480 if (f1 && fclose(f1) == EOF && error == NULL)
5481 error = got_error_from_errno("fclose");
5482 if (f2 && fclose(f2) == EOF && error == NULL)
5483 error = got_error_from_errno("fclose");
5484 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5485 error = got_error_from_errno("close");
5486 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5487 error = got_error_from_errno("close");
5488 return error;
5491 __dead static void
5492 usage_blame(void)
5494 fprintf(stderr,
5495 "usage: %s blame [-c commit] [-r repository-path] path\n",
5496 getprogname());
5497 exit(1);
5500 struct blame_line {
5501 int annotated;
5502 char *id_str;
5503 char *committer;
5504 char datebuf[11]; /* YYYY-MM-DD + NUL */
5507 struct blame_cb_args {
5508 struct blame_line *lines;
5509 int nlines;
5510 int nlines_prec;
5511 int lineno_cur;
5512 off_t *line_offsets;
5513 FILE *f;
5514 struct got_repository *repo;
5517 static const struct got_error *
5518 blame_cb(void *arg, int nlines, int lineno,
5519 struct got_commit_object *commit, struct got_object_id *id)
5521 const struct got_error *err = NULL;
5522 struct blame_cb_args *a = arg;
5523 struct blame_line *bline;
5524 char *line = NULL;
5525 size_t linesize = 0;
5526 off_t offset;
5527 struct tm tm;
5528 time_t committer_time;
5530 if (nlines != a->nlines ||
5531 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5532 return got_error(GOT_ERR_RANGE);
5534 if (sigint_received)
5535 return got_error(GOT_ERR_ITER_COMPLETED);
5537 if (lineno == -1)
5538 return NULL; /* no change in this commit */
5540 /* Annotate this line. */
5541 bline = &a->lines[lineno - 1];
5542 if (bline->annotated)
5543 return NULL;
5544 err = got_object_id_str(&bline->id_str, id);
5545 if (err)
5546 return err;
5548 bline->committer = strdup(got_object_commit_get_committer(commit));
5549 if (bline->committer == NULL) {
5550 err = got_error_from_errno("strdup");
5551 goto done;
5554 committer_time = got_object_commit_get_committer_time(commit);
5555 if (gmtime_r(&committer_time, &tm) == NULL)
5556 return got_error_from_errno("gmtime_r");
5557 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5558 &tm) == 0) {
5559 err = got_error(GOT_ERR_NO_SPACE);
5560 goto done;
5562 bline->annotated = 1;
5564 /* Print lines annotated so far. */
5565 bline = &a->lines[a->lineno_cur - 1];
5566 if (!bline->annotated)
5567 goto done;
5569 offset = a->line_offsets[a->lineno_cur - 1];
5570 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5571 err = got_error_from_errno("fseeko");
5572 goto done;
5575 while (a->lineno_cur <= a->nlines && bline->annotated) {
5576 char *smallerthan, *at, *nl, *committer;
5577 size_t len;
5579 if (getline(&line, &linesize, a->f) == -1) {
5580 if (ferror(a->f))
5581 err = got_error_from_errno("getline");
5582 break;
5585 committer = bline->committer;
5586 smallerthan = strchr(committer, '<');
5587 if (smallerthan && smallerthan[1] != '\0')
5588 committer = smallerthan + 1;
5589 at = strchr(committer, '@');
5590 if (at)
5591 *at = '\0';
5592 len = strlen(committer);
5593 if (len >= 9)
5594 committer[8] = '\0';
5596 nl = strchr(line, '\n');
5597 if (nl)
5598 *nl = '\0';
5599 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5600 bline->id_str, bline->datebuf, committer, line);
5602 a->lineno_cur++;
5603 bline = &a->lines[a->lineno_cur - 1];
5605 done:
5606 free(line);
5607 return err;
5610 static const struct got_error *
5611 cmd_blame(int argc, char *argv[])
5613 const struct got_error *error;
5614 struct got_repository *repo = NULL;
5615 struct got_worktree *worktree = NULL;
5616 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5617 char *link_target = NULL;
5618 struct got_object_id *obj_id = NULL;
5619 struct got_object_id *commit_id = NULL;
5620 struct got_commit_object *commit = NULL;
5621 struct got_blob_object *blob = NULL;
5622 char *commit_id_str = NULL;
5623 struct blame_cb_args bca;
5624 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5625 off_t filesize;
5626 int *pack_fds = NULL;
5627 FILE *f1 = NULL, *f2 = NULL;
5629 fd1 = got_opentempfd();
5630 if (fd1 == -1)
5631 return got_error_from_errno("got_opentempfd");
5633 memset(&bca, 0, sizeof(bca));
5635 #ifndef PROFILE
5636 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5637 NULL) == -1)
5638 err(1, "pledge");
5639 #endif
5641 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5642 switch (ch) {
5643 case 'c':
5644 commit_id_str = optarg;
5645 break;
5646 case 'r':
5647 repo_path = realpath(optarg, NULL);
5648 if (repo_path == NULL)
5649 return got_error_from_errno2("realpath",
5650 optarg);
5651 got_path_strip_trailing_slashes(repo_path);
5652 break;
5653 default:
5654 usage_blame();
5655 /* NOTREACHED */
5659 argc -= optind;
5660 argv += optind;
5662 if (argc == 1)
5663 path = argv[0];
5664 else
5665 usage_blame();
5667 cwd = getcwd(NULL, 0);
5668 if (cwd == NULL) {
5669 error = got_error_from_errno("getcwd");
5670 goto done;
5673 error = got_repo_pack_fds_open(&pack_fds);
5674 if (error != NULL)
5675 goto done;
5677 if (repo_path == NULL) {
5678 error = got_worktree_open(&worktree, cwd);
5679 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5680 goto done;
5681 else
5682 error = NULL;
5683 if (worktree) {
5684 repo_path =
5685 strdup(got_worktree_get_repo_path(worktree));
5686 if (repo_path == NULL) {
5687 error = got_error_from_errno("strdup");
5688 if (error)
5689 goto done;
5691 } else {
5692 repo_path = strdup(cwd);
5693 if (repo_path == NULL) {
5694 error = got_error_from_errno("strdup");
5695 goto done;
5700 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5701 if (error != NULL)
5702 goto done;
5704 if (worktree) {
5705 const char *prefix = got_worktree_get_path_prefix(worktree);
5706 char *p;
5708 error = got_worktree_resolve_path(&p, worktree, path);
5709 if (error)
5710 goto done;
5711 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5712 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5713 p) == -1) {
5714 error = got_error_from_errno("asprintf");
5715 free(p);
5716 goto done;
5718 free(p);
5719 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5720 } else {
5721 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5722 if (error)
5723 goto done;
5724 error = got_repo_map_path(&in_repo_path, repo, path);
5726 if (error)
5727 goto done;
5729 if (commit_id_str == NULL) {
5730 struct got_reference *head_ref;
5731 error = got_ref_open(&head_ref, repo, worktree ?
5732 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5733 if (error != NULL)
5734 goto done;
5735 error = got_ref_resolve(&commit_id, repo, head_ref);
5736 got_ref_close(head_ref);
5737 if (error != NULL)
5738 goto done;
5739 } else {
5740 struct got_reflist_head refs;
5741 TAILQ_INIT(&refs);
5742 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5743 NULL);
5744 if (error)
5745 goto done;
5746 error = got_repo_match_object_id(&commit_id, NULL,
5747 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5748 got_ref_list_free(&refs);
5749 if (error)
5750 goto done;
5753 if (worktree) {
5754 /* Release work tree lock. */
5755 got_worktree_close(worktree);
5756 worktree = NULL;
5759 error = got_object_open_as_commit(&commit, repo, commit_id);
5760 if (error)
5761 goto done;
5763 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5764 commit, repo);
5765 if (error)
5766 goto done;
5768 error = got_object_id_by_path(&obj_id, repo, commit,
5769 link_target ? link_target : in_repo_path);
5770 if (error)
5771 goto done;
5773 error = got_object_get_type(&obj_type, repo, obj_id);
5774 if (error)
5775 goto done;
5777 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5778 error = got_error_path(link_target ? link_target : in_repo_path,
5779 GOT_ERR_OBJ_TYPE);
5780 goto done;
5783 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5784 if (error)
5785 goto done;
5786 bca.f = got_opentemp();
5787 if (bca.f == NULL) {
5788 error = got_error_from_errno("got_opentemp");
5789 goto done;
5791 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5792 &bca.line_offsets, bca.f, blob);
5793 if (error || bca.nlines == 0)
5794 goto done;
5796 /* Don't include \n at EOF in the blame line count. */
5797 if (bca.line_offsets[bca.nlines - 1] == filesize)
5798 bca.nlines--;
5800 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5801 if (bca.lines == NULL) {
5802 error = got_error_from_errno("calloc");
5803 goto done;
5805 bca.lineno_cur = 1;
5806 bca.nlines_prec = 0;
5807 i = bca.nlines;
5808 while (i > 0) {
5809 i /= 10;
5810 bca.nlines_prec++;
5812 bca.repo = repo;
5814 fd2 = got_opentempfd();
5815 if (fd2 == -1) {
5816 error = got_error_from_errno("got_opentempfd");
5817 goto done;
5819 fd3 = got_opentempfd();
5820 if (fd3 == -1) {
5821 error = got_error_from_errno("got_opentempfd");
5822 goto done;
5824 f1 = got_opentemp();
5825 if (f1 == NULL) {
5826 error = got_error_from_errno("got_opentemp");
5827 goto done;
5829 f2 = got_opentemp();
5830 if (f2 == NULL) {
5831 error = got_error_from_errno("got_opentemp");
5832 goto done;
5834 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5835 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5836 check_cancelled, NULL, fd2, fd3, f1, f2);
5837 done:
5838 free(in_repo_path);
5839 free(link_target);
5840 free(repo_path);
5841 free(cwd);
5842 free(commit_id);
5843 free(obj_id);
5844 if (commit)
5845 got_object_commit_close(commit);
5847 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5848 error = got_error_from_errno("close");
5849 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5850 error = got_error_from_errno("close");
5851 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5852 error = got_error_from_errno("close");
5853 if (f1 && fclose(f1) == EOF && error == NULL)
5854 error = got_error_from_errno("fclose");
5855 if (f2 && fclose(f2) == EOF && error == NULL)
5856 error = got_error_from_errno("fclose");
5858 if (blob)
5859 got_object_blob_close(blob);
5860 if (worktree)
5861 got_worktree_close(worktree);
5862 if (repo) {
5863 const struct got_error *close_err = got_repo_close(repo);
5864 if (error == NULL)
5865 error = close_err;
5867 if (pack_fds) {
5868 const struct got_error *pack_err =
5869 got_repo_pack_fds_close(pack_fds);
5870 if (error == NULL)
5871 error = pack_err;
5873 if (bca.lines) {
5874 for (i = 0; i < bca.nlines; i++) {
5875 struct blame_line *bline = &bca.lines[i];
5876 free(bline->id_str);
5877 free(bline->committer);
5879 free(bca.lines);
5881 free(bca.line_offsets);
5882 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5883 error = got_error_from_errno("fclose");
5884 return error;
5887 __dead static void
5888 usage_tree(void)
5890 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5891 "[path]\n", getprogname());
5892 exit(1);
5895 static const struct got_error *
5896 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5897 const char *root_path, struct got_repository *repo)
5899 const struct got_error *err = NULL;
5900 int is_root_path = (strcmp(path, root_path) == 0);
5901 const char *modestr = "";
5902 mode_t mode = got_tree_entry_get_mode(te);
5903 char *link_target = NULL;
5905 path += strlen(root_path);
5906 while (path[0] == '/')
5907 path++;
5909 if (got_object_tree_entry_is_submodule(te))
5910 modestr = "$";
5911 else if (S_ISLNK(mode)) {
5912 int i;
5914 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5915 if (err)
5916 return err;
5917 for (i = 0; i < strlen(link_target); i++) {
5918 if (!isprint((unsigned char)link_target[i]))
5919 link_target[i] = '?';
5922 modestr = "@";
5924 else if (S_ISDIR(mode))
5925 modestr = "/";
5926 else if (mode & S_IXUSR)
5927 modestr = "*";
5929 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5930 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5931 link_target ? " -> ": "", link_target ? link_target : "");
5933 free(link_target);
5934 return NULL;
5937 static const struct got_error *
5938 print_tree(const char *path, struct got_commit_object *commit,
5939 int show_ids, int recurse, const char *root_path,
5940 struct got_repository *repo)
5942 const struct got_error *err = NULL;
5943 struct got_object_id *tree_id = NULL;
5944 struct got_tree_object *tree = NULL;
5945 int nentries, i;
5947 err = got_object_id_by_path(&tree_id, repo, commit, path);
5948 if (err)
5949 goto done;
5951 err = got_object_open_as_tree(&tree, repo, tree_id);
5952 if (err)
5953 goto done;
5954 nentries = got_object_tree_get_nentries(tree);
5955 for (i = 0; i < nentries; i++) {
5956 struct got_tree_entry *te;
5957 char *id = NULL;
5959 if (sigint_received || sigpipe_received)
5960 break;
5962 te = got_object_tree_get_entry(tree, i);
5963 if (show_ids) {
5964 char *id_str;
5965 err = got_object_id_str(&id_str,
5966 got_tree_entry_get_id(te));
5967 if (err)
5968 goto done;
5969 if (asprintf(&id, "%s ", id_str) == -1) {
5970 err = got_error_from_errno("asprintf");
5971 free(id_str);
5972 goto done;
5974 free(id_str);
5976 err = print_entry(te, id, path, root_path, repo);
5977 free(id);
5978 if (err)
5979 goto done;
5981 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5982 char *child_path;
5983 if (asprintf(&child_path, "%s%s%s", path,
5984 path[0] == '/' && path[1] == '\0' ? "" : "/",
5985 got_tree_entry_get_name(te)) == -1) {
5986 err = got_error_from_errno("asprintf");
5987 goto done;
5989 err = print_tree(child_path, commit, show_ids, 1,
5990 root_path, repo);
5991 free(child_path);
5992 if (err)
5993 goto done;
5996 done:
5997 if (tree)
5998 got_object_tree_close(tree);
5999 free(tree_id);
6000 return err;
6003 static const struct got_error *
6004 cmd_tree(int argc, char *argv[])
6006 const struct got_error *error;
6007 struct got_repository *repo = NULL;
6008 struct got_worktree *worktree = NULL;
6009 const char *path, *refname = NULL;
6010 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6011 struct got_object_id *commit_id = NULL;
6012 struct got_commit_object *commit = NULL;
6013 char *commit_id_str = NULL;
6014 int show_ids = 0, recurse = 0;
6015 int ch;
6016 int *pack_fds = NULL;
6018 #ifndef PROFILE
6019 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6020 NULL) == -1)
6021 err(1, "pledge");
6022 #endif
6024 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6025 switch (ch) {
6026 case 'c':
6027 commit_id_str = optarg;
6028 break;
6029 case 'i':
6030 show_ids = 1;
6031 break;
6032 case 'R':
6033 recurse = 1;
6034 break;
6035 case 'r':
6036 repo_path = realpath(optarg, NULL);
6037 if (repo_path == NULL)
6038 return got_error_from_errno2("realpath",
6039 optarg);
6040 got_path_strip_trailing_slashes(repo_path);
6041 break;
6042 default:
6043 usage_tree();
6044 /* NOTREACHED */
6048 argc -= optind;
6049 argv += optind;
6051 if (argc == 1)
6052 path = argv[0];
6053 else if (argc > 1)
6054 usage_tree();
6055 else
6056 path = NULL;
6058 cwd = getcwd(NULL, 0);
6059 if (cwd == NULL) {
6060 error = got_error_from_errno("getcwd");
6061 goto done;
6064 error = got_repo_pack_fds_open(&pack_fds);
6065 if (error != NULL)
6066 goto done;
6068 if (repo_path == NULL) {
6069 error = got_worktree_open(&worktree, cwd);
6070 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6071 goto done;
6072 else
6073 error = NULL;
6074 if (worktree) {
6075 repo_path =
6076 strdup(got_worktree_get_repo_path(worktree));
6077 if (repo_path == NULL)
6078 error = got_error_from_errno("strdup");
6079 if (error)
6080 goto done;
6081 } else {
6082 repo_path = strdup(cwd);
6083 if (repo_path == NULL) {
6084 error = got_error_from_errno("strdup");
6085 goto done;
6090 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6091 if (error != NULL)
6092 goto done;
6094 if (worktree) {
6095 const char *prefix = got_worktree_get_path_prefix(worktree);
6096 char *p;
6098 if (path == NULL)
6099 path = "";
6100 error = got_worktree_resolve_path(&p, worktree, path);
6101 if (error)
6102 goto done;
6103 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6104 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6105 p) == -1) {
6106 error = got_error_from_errno("asprintf");
6107 free(p);
6108 goto done;
6110 free(p);
6111 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6112 if (error)
6113 goto done;
6114 } else {
6115 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6116 if (error)
6117 goto done;
6118 if (path == NULL)
6119 path = "/";
6120 error = got_repo_map_path(&in_repo_path, repo, path);
6121 if (error != NULL)
6122 goto done;
6125 if (commit_id_str == NULL) {
6126 struct got_reference *head_ref;
6127 if (worktree)
6128 refname = got_worktree_get_head_ref_name(worktree);
6129 else
6130 refname = GOT_REF_HEAD;
6131 error = got_ref_open(&head_ref, repo, refname, 0);
6132 if (error != NULL)
6133 goto done;
6134 error = got_ref_resolve(&commit_id, repo, head_ref);
6135 got_ref_close(head_ref);
6136 if (error != NULL)
6137 goto done;
6138 } else {
6139 struct got_reflist_head refs;
6140 TAILQ_INIT(&refs);
6141 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6142 NULL);
6143 if (error)
6144 goto done;
6145 error = got_repo_match_object_id(&commit_id, NULL,
6146 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6147 got_ref_list_free(&refs);
6148 if (error)
6149 goto done;
6152 if (worktree) {
6153 /* Release work tree lock. */
6154 got_worktree_close(worktree);
6155 worktree = NULL;
6158 error = got_object_open_as_commit(&commit, repo, commit_id);
6159 if (error)
6160 goto done;
6162 error = print_tree(in_repo_path, commit, show_ids, recurse,
6163 in_repo_path, repo);
6164 done:
6165 free(in_repo_path);
6166 free(repo_path);
6167 free(cwd);
6168 free(commit_id);
6169 if (commit)
6170 got_object_commit_close(commit);
6171 if (worktree)
6172 got_worktree_close(worktree);
6173 if (repo) {
6174 const struct got_error *close_err = got_repo_close(repo);
6175 if (error == NULL)
6176 error = close_err;
6178 if (pack_fds) {
6179 const struct got_error *pack_err =
6180 got_repo_pack_fds_close(pack_fds);
6181 if (error == NULL)
6182 error = pack_err;
6184 return error;
6187 __dead static void
6188 usage_status(void)
6190 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6191 "[-s status-codes] [path ...]\n", getprogname());
6192 exit(1);
6195 struct got_status_arg {
6196 char *status_codes;
6197 int suppress;
6200 static const struct got_error *
6201 print_status(void *arg, unsigned char status, unsigned char staged_status,
6202 const char *path, struct got_object_id *blob_id,
6203 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6204 int dirfd, const char *de_name)
6206 struct got_status_arg *st = arg;
6208 if (status == staged_status && (status == GOT_STATUS_DELETE))
6209 status = GOT_STATUS_NO_CHANGE;
6210 if (st != NULL && st->status_codes) {
6211 size_t ncodes = strlen(st->status_codes);
6212 int i, j = 0;
6214 for (i = 0; i < ncodes ; i++) {
6215 if (st->suppress) {
6216 if (status == st->status_codes[i] ||
6217 staged_status == st->status_codes[i]) {
6218 j++;
6219 continue;
6221 } else {
6222 if (status == st->status_codes[i] ||
6223 staged_status == st->status_codes[i])
6224 break;
6228 if (st->suppress && j == 0)
6229 goto print;
6231 if (i == ncodes)
6232 return NULL;
6234 print:
6235 printf("%c%c %s\n", status, staged_status, path);
6236 return NULL;
6239 static const struct got_error *
6240 cmd_status(int argc, char *argv[])
6242 const struct got_error *error = NULL;
6243 struct got_repository *repo = NULL;
6244 struct got_worktree *worktree = NULL;
6245 struct got_status_arg st;
6246 char *cwd = NULL;
6247 struct got_pathlist_head paths;
6248 int ch, i, no_ignores = 0;
6249 int *pack_fds = NULL;
6251 TAILQ_INIT(&paths);
6253 memset(&st, 0, sizeof(st));
6254 st.status_codes = NULL;
6255 st.suppress = 0;
6257 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6258 switch (ch) {
6259 case 'I':
6260 no_ignores = 1;
6261 break;
6262 case 'S':
6263 if (st.status_codes != NULL && st.suppress == 0)
6264 option_conflict('S', 's');
6265 st.suppress = 1;
6266 /* fallthrough */
6267 case 's':
6268 for (i = 0; i < strlen(optarg); i++) {
6269 switch (optarg[i]) {
6270 case GOT_STATUS_MODIFY:
6271 case GOT_STATUS_ADD:
6272 case GOT_STATUS_DELETE:
6273 case GOT_STATUS_CONFLICT:
6274 case GOT_STATUS_MISSING:
6275 case GOT_STATUS_OBSTRUCTED:
6276 case GOT_STATUS_UNVERSIONED:
6277 case GOT_STATUS_MODE_CHANGE:
6278 case GOT_STATUS_NONEXISTENT:
6279 break;
6280 default:
6281 errx(1, "invalid status code '%c'",
6282 optarg[i]);
6285 if (ch == 's' && st.suppress)
6286 option_conflict('s', 'S');
6287 st.status_codes = optarg;
6288 break;
6289 default:
6290 usage_status();
6291 /* NOTREACHED */
6295 argc -= optind;
6296 argv += optind;
6298 #ifndef PROFILE
6299 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6300 NULL) == -1)
6301 err(1, "pledge");
6302 #endif
6303 cwd = getcwd(NULL, 0);
6304 if (cwd == NULL) {
6305 error = got_error_from_errno("getcwd");
6306 goto done;
6309 error = got_repo_pack_fds_open(&pack_fds);
6310 if (error != NULL)
6311 goto done;
6313 error = got_worktree_open(&worktree, cwd);
6314 if (error) {
6315 if (error->code == GOT_ERR_NOT_WORKTREE)
6316 error = wrap_not_worktree_error(error, "status", cwd);
6317 goto done;
6320 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6321 NULL, pack_fds);
6322 if (error != NULL)
6323 goto done;
6325 error = apply_unveil(got_repo_get_path(repo), 1,
6326 got_worktree_get_root_path(worktree));
6327 if (error)
6328 goto done;
6330 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6331 if (error)
6332 goto done;
6334 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6335 print_status, &st, check_cancelled, NULL);
6336 done:
6337 if (pack_fds) {
6338 const struct got_error *pack_err =
6339 got_repo_pack_fds_close(pack_fds);
6340 if (error == NULL)
6341 error = pack_err;
6344 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6345 free(cwd);
6346 return error;
6349 __dead static void
6350 usage_ref(void)
6352 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6353 "[-s reference] [name]\n", getprogname());
6354 exit(1);
6357 static const struct got_error *
6358 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6360 static const struct got_error *err = NULL;
6361 struct got_reflist_head refs;
6362 struct got_reflist_entry *re;
6364 TAILQ_INIT(&refs);
6365 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6366 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6367 repo);
6368 if (err)
6369 return err;
6371 TAILQ_FOREACH(re, &refs, entry) {
6372 char *refstr;
6373 refstr = got_ref_to_str(re->ref);
6374 if (refstr == NULL) {
6375 err = got_error_from_errno("got_ref_to_str");
6376 break;
6378 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6379 free(refstr);
6382 got_ref_list_free(&refs);
6383 return err;
6386 static const struct got_error *
6387 delete_ref_by_name(struct got_repository *repo, const char *refname)
6389 const struct got_error *err;
6390 struct got_reference *ref;
6392 err = got_ref_open(&ref, repo, refname, 0);
6393 if (err)
6394 return err;
6396 err = delete_ref(repo, ref);
6397 got_ref_close(ref);
6398 return err;
6401 static const struct got_error *
6402 add_ref(struct got_repository *repo, const char *refname, const char *target)
6404 const struct got_error *err = NULL;
6405 struct got_object_id *id = NULL;
6406 struct got_reference *ref = NULL;
6407 struct got_reflist_head refs;
6410 * Don't let the user create a reference name with a leading '-'.
6411 * While technically a valid reference name, this case is usually
6412 * an unintended typo.
6414 if (refname[0] == '-')
6415 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6417 TAILQ_INIT(&refs);
6418 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6419 if (err)
6420 goto done;
6421 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6422 &refs, repo);
6423 got_ref_list_free(&refs);
6424 if (err)
6425 goto done;
6427 err = got_ref_alloc(&ref, refname, id);
6428 if (err)
6429 goto done;
6431 err = got_ref_write(ref, repo);
6432 done:
6433 if (ref)
6434 got_ref_close(ref);
6435 free(id);
6436 return err;
6439 static const struct got_error *
6440 add_symref(struct got_repository *repo, const char *refname, const char *target)
6442 const struct got_error *err = NULL;
6443 struct got_reference *ref = NULL;
6444 struct got_reference *target_ref = NULL;
6447 * Don't let the user create a reference name with a leading '-'.
6448 * While technically a valid reference name, this case is usually
6449 * an unintended typo.
6451 if (refname[0] == '-')
6452 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6454 err = got_ref_open(&target_ref, repo, target, 0);
6455 if (err)
6456 return err;
6458 err = got_ref_alloc_symref(&ref, refname, target_ref);
6459 if (err)
6460 goto done;
6462 err = got_ref_write(ref, repo);
6463 done:
6464 if (target_ref)
6465 got_ref_close(target_ref);
6466 if (ref)
6467 got_ref_close(ref);
6468 return err;
6471 static const struct got_error *
6472 cmd_ref(int argc, char *argv[])
6474 const struct got_error *error = NULL;
6475 struct got_repository *repo = NULL;
6476 struct got_worktree *worktree = NULL;
6477 char *cwd = NULL, *repo_path = NULL;
6478 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6479 const char *obj_arg = NULL, *symref_target= NULL;
6480 char *refname = NULL;
6481 int *pack_fds = NULL;
6483 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6484 switch (ch) {
6485 case 'c':
6486 obj_arg = optarg;
6487 break;
6488 case 'd':
6489 do_delete = 1;
6490 break;
6491 case 'l':
6492 do_list = 1;
6493 break;
6494 case 'r':
6495 repo_path = realpath(optarg, NULL);
6496 if (repo_path == NULL)
6497 return got_error_from_errno2("realpath",
6498 optarg);
6499 got_path_strip_trailing_slashes(repo_path);
6500 break;
6501 case 's':
6502 symref_target = optarg;
6503 break;
6504 case 't':
6505 sort_by_time = 1;
6506 break;
6507 default:
6508 usage_ref();
6509 /* NOTREACHED */
6513 if (obj_arg && do_list)
6514 option_conflict('c', 'l');
6515 if (obj_arg && do_delete)
6516 option_conflict('c', 'd');
6517 if (obj_arg && symref_target)
6518 option_conflict('c', 's');
6519 if (symref_target && do_delete)
6520 option_conflict('s', 'd');
6521 if (symref_target && do_list)
6522 option_conflict('s', 'l');
6523 if (do_delete && do_list)
6524 option_conflict('d', 'l');
6525 if (sort_by_time && !do_list)
6526 errx(1, "-t option requires -l option");
6528 argc -= optind;
6529 argv += optind;
6531 if (do_list) {
6532 if (argc != 0 && argc != 1)
6533 usage_ref();
6534 if (argc == 1) {
6535 refname = strdup(argv[0]);
6536 if (refname == NULL) {
6537 error = got_error_from_errno("strdup");
6538 goto done;
6541 } else {
6542 if (argc != 1)
6543 usage_ref();
6544 refname = strdup(argv[0]);
6545 if (refname == NULL) {
6546 error = got_error_from_errno("strdup");
6547 goto done;
6551 if (refname)
6552 got_path_strip_trailing_slashes(refname);
6554 #ifndef PROFILE
6555 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6556 "sendfd unveil", NULL) == -1)
6557 err(1, "pledge");
6558 #endif
6559 cwd = getcwd(NULL, 0);
6560 if (cwd == NULL) {
6561 error = got_error_from_errno("getcwd");
6562 goto done;
6565 error = got_repo_pack_fds_open(&pack_fds);
6566 if (error != NULL)
6567 goto done;
6569 if (repo_path == NULL) {
6570 error = got_worktree_open(&worktree, cwd);
6571 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6572 goto done;
6573 else
6574 error = NULL;
6575 if (worktree) {
6576 repo_path =
6577 strdup(got_worktree_get_repo_path(worktree));
6578 if (repo_path == NULL)
6579 error = got_error_from_errno("strdup");
6580 if (error)
6581 goto done;
6582 } else {
6583 repo_path = strdup(cwd);
6584 if (repo_path == NULL) {
6585 error = got_error_from_errno("strdup");
6586 goto done;
6591 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6592 if (error != NULL)
6593 goto done;
6595 #ifndef PROFILE
6596 if (do_list) {
6597 /* Remove "cpath" promise. */
6598 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6599 NULL) == -1)
6600 err(1, "pledge");
6602 #endif
6604 error = apply_unveil(got_repo_get_path(repo), do_list,
6605 worktree ? got_worktree_get_root_path(worktree) : NULL);
6606 if (error)
6607 goto done;
6609 if (do_list)
6610 error = list_refs(repo, refname, sort_by_time);
6611 else if (do_delete)
6612 error = delete_ref_by_name(repo, refname);
6613 else if (symref_target)
6614 error = add_symref(repo, refname, symref_target);
6615 else {
6616 if (obj_arg == NULL)
6617 usage_ref();
6618 error = add_ref(repo, refname, obj_arg);
6620 done:
6621 free(refname);
6622 if (repo) {
6623 const struct got_error *close_err = got_repo_close(repo);
6624 if (error == NULL)
6625 error = close_err;
6627 if (worktree)
6628 got_worktree_close(worktree);
6629 if (pack_fds) {
6630 const struct got_error *pack_err =
6631 got_repo_pack_fds_close(pack_fds);
6632 if (error == NULL)
6633 error = pack_err;
6635 free(cwd);
6636 free(repo_path);
6637 return error;
6640 __dead static void
6641 usage_branch(void)
6643 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6644 "[-r repository-path] [name]\n", getprogname());
6645 exit(1);
6648 static const struct got_error *
6649 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6650 struct got_reference *ref)
6652 const struct got_error *err = NULL;
6653 const char *refname, *marker = " ";
6654 char *refstr;
6656 refname = got_ref_get_name(ref);
6657 if (worktree && strcmp(refname,
6658 got_worktree_get_head_ref_name(worktree)) == 0) {
6659 struct got_object_id *id = NULL;
6661 err = got_ref_resolve(&id, repo, ref);
6662 if (err)
6663 return err;
6664 if (got_object_id_cmp(id,
6665 got_worktree_get_base_commit_id(worktree)) == 0)
6666 marker = "* ";
6667 else
6668 marker = "~ ";
6669 free(id);
6672 if (strncmp(refname, "refs/heads/", 11) == 0)
6673 refname += 11;
6674 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6675 refname += 18;
6676 if (strncmp(refname, "refs/remotes/", 13) == 0)
6677 refname += 13;
6679 refstr = got_ref_to_str(ref);
6680 if (refstr == NULL)
6681 return got_error_from_errno("got_ref_to_str");
6683 printf("%s%s: %s\n", marker, refname, refstr);
6684 free(refstr);
6685 return NULL;
6688 static const struct got_error *
6689 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6691 const char *refname;
6693 if (worktree == NULL)
6694 return got_error(GOT_ERR_NOT_WORKTREE);
6696 refname = got_worktree_get_head_ref_name(worktree);
6698 if (strncmp(refname, "refs/heads/", 11) == 0)
6699 refname += 11;
6700 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6701 refname += 18;
6703 printf("%s\n", refname);
6705 return NULL;
6708 static const struct got_error *
6709 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6710 int sort_by_time)
6712 static const struct got_error *err = NULL;
6713 struct got_reflist_head refs;
6714 struct got_reflist_entry *re;
6715 struct got_reference *temp_ref = NULL;
6716 int rebase_in_progress, histedit_in_progress;
6718 TAILQ_INIT(&refs);
6720 if (worktree) {
6721 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6722 worktree);
6723 if (err)
6724 return err;
6726 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6727 worktree);
6728 if (err)
6729 return err;
6731 if (rebase_in_progress || histedit_in_progress) {
6732 err = got_ref_open(&temp_ref, repo,
6733 got_worktree_get_head_ref_name(worktree), 0);
6734 if (err)
6735 return err;
6736 list_branch(repo, worktree, temp_ref);
6737 got_ref_close(temp_ref);
6741 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6742 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6743 repo);
6744 if (err)
6745 return err;
6747 TAILQ_FOREACH(re, &refs, entry)
6748 list_branch(repo, worktree, re->ref);
6750 got_ref_list_free(&refs);
6752 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6753 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6754 repo);
6755 if (err)
6756 return err;
6758 TAILQ_FOREACH(re, &refs, entry)
6759 list_branch(repo, worktree, re->ref);
6761 got_ref_list_free(&refs);
6763 return NULL;
6766 static const struct got_error *
6767 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6768 const char *branch_name)
6770 const struct got_error *err = NULL;
6771 struct got_reference *ref = NULL;
6772 char *refname, *remote_refname = NULL;
6774 if (strncmp(branch_name, "refs/", 5) == 0)
6775 branch_name += 5;
6776 if (strncmp(branch_name, "heads/", 6) == 0)
6777 branch_name += 6;
6778 else if (strncmp(branch_name, "remotes/", 8) == 0)
6779 branch_name += 8;
6781 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6782 return got_error_from_errno("asprintf");
6784 if (asprintf(&remote_refname, "refs/remotes/%s",
6785 branch_name) == -1) {
6786 err = got_error_from_errno("asprintf");
6787 goto done;
6790 err = got_ref_open(&ref, repo, refname, 0);
6791 if (err) {
6792 const struct got_error *err2;
6793 if (err->code != GOT_ERR_NOT_REF)
6794 goto done;
6796 * Keep 'err' intact such that if neither branch exists
6797 * we report "refs/heads" rather than "refs/remotes" in
6798 * our error message.
6800 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6801 if (err2)
6802 goto done;
6803 err = NULL;
6806 if (worktree &&
6807 strcmp(got_worktree_get_head_ref_name(worktree),
6808 got_ref_get_name(ref)) == 0) {
6809 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6810 "will not delete this work tree's current branch");
6811 goto done;
6814 err = delete_ref(repo, ref);
6815 done:
6816 if (ref)
6817 got_ref_close(ref);
6818 free(refname);
6819 free(remote_refname);
6820 return err;
6823 static const struct got_error *
6824 add_branch(struct got_repository *repo, const char *branch_name,
6825 struct got_object_id *base_commit_id)
6827 const struct got_error *err = NULL;
6828 struct got_reference *ref = NULL;
6829 char *refname = NULL;
6832 * Don't let the user create a branch name with a leading '-'.
6833 * While technically a valid reference name, this case is usually
6834 * an unintended typo.
6836 if (branch_name[0] == '-')
6837 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6839 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6840 branch_name += 11;
6842 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6843 err = got_error_from_errno("asprintf");
6844 goto done;
6847 err = got_ref_open(&ref, repo, refname, 0);
6848 if (err == NULL) {
6849 err = got_error(GOT_ERR_BRANCH_EXISTS);
6850 goto done;
6851 } else if (err->code != GOT_ERR_NOT_REF)
6852 goto done;
6854 err = got_ref_alloc(&ref, refname, base_commit_id);
6855 if (err)
6856 goto done;
6858 err = got_ref_write(ref, repo);
6859 done:
6860 if (ref)
6861 got_ref_close(ref);
6862 free(refname);
6863 return err;
6866 static const struct got_error *
6867 cmd_branch(int argc, char *argv[])
6869 const struct got_error *error = NULL;
6870 struct got_repository *repo = NULL;
6871 struct got_worktree *worktree = NULL;
6872 char *cwd = NULL, *repo_path = NULL;
6873 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6874 const char *delref = NULL, *commit_id_arg = NULL;
6875 struct got_reference *ref = NULL;
6876 struct got_pathlist_head paths;
6877 struct got_object_id *commit_id = NULL;
6878 char *commit_id_str = NULL;
6879 int *pack_fds = NULL;
6881 TAILQ_INIT(&paths);
6883 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6884 switch (ch) {
6885 case 'c':
6886 commit_id_arg = optarg;
6887 break;
6888 case 'd':
6889 delref = optarg;
6890 break;
6891 case 'l':
6892 do_list = 1;
6893 break;
6894 case 'n':
6895 do_update = 0;
6896 break;
6897 case 'r':
6898 repo_path = realpath(optarg, NULL);
6899 if (repo_path == NULL)
6900 return got_error_from_errno2("realpath",
6901 optarg);
6902 got_path_strip_trailing_slashes(repo_path);
6903 break;
6904 case 't':
6905 sort_by_time = 1;
6906 break;
6907 default:
6908 usage_branch();
6909 /* NOTREACHED */
6913 if (do_list && delref)
6914 option_conflict('l', 'd');
6915 if (sort_by_time && !do_list)
6916 errx(1, "-t option requires -l option");
6918 argc -= optind;
6919 argv += optind;
6921 if (!do_list && !delref && argc == 0)
6922 do_show = 1;
6924 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6925 errx(1, "-c option can only be used when creating a branch");
6927 if (do_list || delref) {
6928 if (argc > 0)
6929 usage_branch();
6930 } else if (!do_show && argc != 1)
6931 usage_branch();
6933 #ifndef PROFILE
6934 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6935 "sendfd unveil", NULL) == -1)
6936 err(1, "pledge");
6937 #endif
6938 cwd = getcwd(NULL, 0);
6939 if (cwd == NULL) {
6940 error = got_error_from_errno("getcwd");
6941 goto done;
6944 error = got_repo_pack_fds_open(&pack_fds);
6945 if (error != NULL)
6946 goto done;
6948 if (repo_path == NULL) {
6949 error = got_worktree_open(&worktree, cwd);
6950 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6951 goto done;
6952 else
6953 error = NULL;
6954 if (worktree) {
6955 repo_path =
6956 strdup(got_worktree_get_repo_path(worktree));
6957 if (repo_path == NULL)
6958 error = got_error_from_errno("strdup");
6959 if (error)
6960 goto done;
6961 } else {
6962 repo_path = strdup(cwd);
6963 if (repo_path == NULL) {
6964 error = got_error_from_errno("strdup");
6965 goto done;
6970 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6971 if (error != NULL)
6972 goto done;
6974 #ifndef PROFILE
6975 if (do_list || do_show) {
6976 /* Remove "cpath" promise. */
6977 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6978 NULL) == -1)
6979 err(1, "pledge");
6981 #endif
6983 error = apply_unveil(got_repo_get_path(repo), do_list,
6984 worktree ? got_worktree_get_root_path(worktree) : NULL);
6985 if (error)
6986 goto done;
6988 if (do_show)
6989 error = show_current_branch(repo, worktree);
6990 else if (do_list)
6991 error = list_branches(repo, worktree, sort_by_time);
6992 else if (delref)
6993 error = delete_branch(repo, worktree, delref);
6994 else {
6995 struct got_reflist_head refs;
6996 TAILQ_INIT(&refs);
6997 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6998 NULL);
6999 if (error)
7000 goto done;
7001 if (commit_id_arg == NULL)
7002 commit_id_arg = worktree ?
7003 got_worktree_get_head_ref_name(worktree) :
7004 GOT_REF_HEAD;
7005 error = got_repo_match_object_id(&commit_id, NULL,
7006 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7007 got_ref_list_free(&refs);
7008 if (error)
7009 goto done;
7010 error = add_branch(repo, argv[0], commit_id);
7011 if (error)
7012 goto done;
7013 if (worktree && do_update) {
7014 struct got_update_progress_arg upa;
7015 char *branch_refname = NULL;
7017 error = got_object_id_str(&commit_id_str, commit_id);
7018 if (error)
7019 goto done;
7020 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7021 worktree);
7022 if (error)
7023 goto done;
7024 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7025 == -1) {
7026 error = got_error_from_errno("asprintf");
7027 goto done;
7029 error = got_ref_open(&ref, repo, branch_refname, 0);
7030 free(branch_refname);
7031 if (error)
7032 goto done;
7033 error = switch_head_ref(ref, commit_id, worktree,
7034 repo);
7035 if (error)
7036 goto done;
7037 error = got_worktree_set_base_commit_id(worktree, repo,
7038 commit_id);
7039 if (error)
7040 goto done;
7041 memset(&upa, 0, sizeof(upa));
7042 error = got_worktree_checkout_files(worktree, &paths,
7043 repo, update_progress, &upa, check_cancelled,
7044 NULL);
7045 if (error)
7046 goto done;
7047 if (upa.did_something) {
7048 printf("Updated to %s: %s\n",
7049 got_worktree_get_head_ref_name(worktree),
7050 commit_id_str);
7052 print_update_progress_stats(&upa);
7055 done:
7056 if (ref)
7057 got_ref_close(ref);
7058 if (repo) {
7059 const struct got_error *close_err = got_repo_close(repo);
7060 if (error == NULL)
7061 error = close_err;
7063 if (worktree)
7064 got_worktree_close(worktree);
7065 if (pack_fds) {
7066 const struct got_error *pack_err =
7067 got_repo_pack_fds_close(pack_fds);
7068 if (error == NULL)
7069 error = pack_err;
7071 free(cwd);
7072 free(repo_path);
7073 free(commit_id);
7074 free(commit_id_str);
7075 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7076 return error;
7080 __dead static void
7081 usage_tag(void)
7083 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7084 "[-r repository-path] [-s signer-id] name\n", getprogname());
7085 exit(1);
7088 #if 0
7089 static const struct got_error *
7090 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7092 const struct got_error *err = NULL;
7093 struct got_reflist_entry *re, *se, *new;
7094 struct got_object_id *re_id, *se_id;
7095 struct got_tag_object *re_tag, *se_tag;
7096 time_t re_time, se_time;
7098 STAILQ_FOREACH(re, tags, entry) {
7099 se = STAILQ_FIRST(sorted);
7100 if (se == NULL) {
7101 err = got_reflist_entry_dup(&new, re);
7102 if (err)
7103 return err;
7104 STAILQ_INSERT_HEAD(sorted, new, entry);
7105 continue;
7106 } else {
7107 err = got_ref_resolve(&re_id, repo, re->ref);
7108 if (err)
7109 break;
7110 err = got_object_open_as_tag(&re_tag, repo, re_id);
7111 free(re_id);
7112 if (err)
7113 break;
7114 re_time = got_object_tag_get_tagger_time(re_tag);
7115 got_object_tag_close(re_tag);
7118 while (se) {
7119 err = got_ref_resolve(&se_id, repo, re->ref);
7120 if (err)
7121 break;
7122 err = got_object_open_as_tag(&se_tag, repo, se_id);
7123 free(se_id);
7124 if (err)
7125 break;
7126 se_time = got_object_tag_get_tagger_time(se_tag);
7127 got_object_tag_close(se_tag);
7129 if (se_time > re_time) {
7130 err = got_reflist_entry_dup(&new, re);
7131 if (err)
7132 return err;
7133 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7134 break;
7136 se = STAILQ_NEXT(se, entry);
7137 continue;
7140 done:
7141 return err;
7143 #endif
7145 static const struct got_error *
7146 get_tag_refname(char **refname, const char *tag_name)
7148 const struct got_error *err;
7150 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7151 *refname = strdup(tag_name);
7152 if (*refname == NULL)
7153 return got_error_from_errno("strdup");
7154 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7155 err = got_error_from_errno("asprintf");
7156 *refname = NULL;
7157 return err;
7160 return NULL;
7163 static const struct got_error *
7164 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7165 const char *allowed_signers, const char *revoked_signers, int verbosity)
7167 static const struct got_error *err = NULL;
7168 struct got_reflist_head refs;
7169 struct got_reflist_entry *re;
7170 char *wanted_refname = NULL;
7171 int bad_sigs = 0;
7173 TAILQ_INIT(&refs);
7175 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7176 if (err)
7177 return err;
7179 if (tag_name) {
7180 struct got_reference *ref;
7181 err = get_tag_refname(&wanted_refname, tag_name);
7182 if (err)
7183 goto done;
7184 /* Wanted tag reference should exist. */
7185 err = got_ref_open(&ref, repo, wanted_refname, 0);
7186 if (err)
7187 goto done;
7188 got_ref_close(ref);
7191 TAILQ_FOREACH(re, &refs, entry) {
7192 const char *refname;
7193 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7194 char datebuf[26];
7195 const char *tagger, *ssh_sig = NULL;
7196 char *sig_msg = NULL;
7197 time_t tagger_time;
7198 struct got_object_id *id;
7199 struct got_tag_object *tag;
7200 struct got_commit_object *commit = NULL;
7202 refname = got_ref_get_name(re->ref);
7203 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7204 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7205 continue;
7206 refname += 10;
7207 refstr = got_ref_to_str(re->ref);
7208 if (refstr == NULL) {
7209 err = got_error_from_errno("got_ref_to_str");
7210 break;
7213 err = got_ref_resolve(&id, repo, re->ref);
7214 if (err)
7215 break;
7216 err = got_object_open_as_tag(&tag, repo, id);
7217 if (err) {
7218 if (err->code != GOT_ERR_OBJ_TYPE) {
7219 free(id);
7220 break;
7222 /* "lightweight" tag */
7223 err = got_object_open_as_commit(&commit, repo, id);
7224 if (err) {
7225 free(id);
7226 break;
7228 tagger = got_object_commit_get_committer(commit);
7229 tagger_time =
7230 got_object_commit_get_committer_time(commit);
7231 err = got_object_id_str(&id_str, id);
7232 free(id);
7233 if (err)
7234 break;
7235 } else {
7236 free(id);
7237 tagger = got_object_tag_get_tagger(tag);
7238 tagger_time = got_object_tag_get_tagger_time(tag);
7239 err = got_object_id_str(&id_str,
7240 got_object_tag_get_object_id(tag));
7241 if (err)
7242 break;
7245 if (tag && verify_tags) {
7246 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7247 got_object_tag_get_message(tag));
7248 if (ssh_sig && allowed_signers == NULL) {
7249 err = got_error_msg(
7250 GOT_ERR_VERIFY_TAG_SIGNATURE,
7251 "SSH signature verification requires "
7252 "setting allowed_signers in "
7253 "got.conf(5)");
7254 break;
7258 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7259 free(refstr);
7260 printf("from: %s\n", tagger);
7261 datestr = get_datestr(&tagger_time, datebuf);
7262 if (datestr)
7263 printf("date: %s UTC\n", datestr);
7264 if (commit)
7265 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7266 else {
7267 switch (got_object_tag_get_object_type(tag)) {
7268 case GOT_OBJ_TYPE_BLOB:
7269 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7270 id_str);
7271 break;
7272 case GOT_OBJ_TYPE_TREE:
7273 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7274 id_str);
7275 break;
7276 case GOT_OBJ_TYPE_COMMIT:
7277 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7278 id_str);
7279 break;
7280 case GOT_OBJ_TYPE_TAG:
7281 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7282 id_str);
7283 break;
7284 default:
7285 break;
7288 free(id_str);
7290 if (ssh_sig) {
7291 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7292 allowed_signers, revoked_signers, verbosity);
7293 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7294 bad_sigs = 1;
7295 else if (err)
7296 break;
7297 printf("signature: %s", sig_msg);
7298 free(sig_msg);
7299 sig_msg = NULL;
7302 if (commit) {
7303 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7304 if (err)
7305 break;
7306 got_object_commit_close(commit);
7307 } else {
7308 tagmsg0 = strdup(got_object_tag_get_message(tag));
7309 got_object_tag_close(tag);
7310 if (tagmsg0 == NULL) {
7311 err = got_error_from_errno("strdup");
7312 break;
7316 tagmsg = tagmsg0;
7317 do {
7318 line = strsep(&tagmsg, "\n");
7319 if (line)
7320 printf(" %s\n", line);
7321 } while (line);
7322 free(tagmsg0);
7324 done:
7325 got_ref_list_free(&refs);
7326 free(wanted_refname);
7328 if (err == NULL && bad_sigs)
7329 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7330 return err;
7333 static const struct got_error *
7334 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7335 const char *tag_name, const char *repo_path)
7337 const struct got_error *err = NULL;
7338 char *template = NULL, *initial_content = NULL;
7339 char *editor = NULL;
7340 int initial_content_len;
7341 int fd = -1;
7343 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7344 err = got_error_from_errno("asprintf");
7345 goto done;
7348 initial_content_len = asprintf(&initial_content,
7349 "\n# tagging commit %s as %s\n",
7350 commit_id_str, tag_name);
7351 if (initial_content_len == -1) {
7352 err = got_error_from_errno("asprintf");
7353 goto done;
7356 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7357 if (err)
7358 goto done;
7360 if (write(fd, initial_content, initial_content_len) == -1) {
7361 err = got_error_from_errno2("write", *tagmsg_path);
7362 goto done;
7365 err = get_editor(&editor);
7366 if (err)
7367 goto done;
7368 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7369 initial_content_len, 1);
7370 done:
7371 free(initial_content);
7372 free(template);
7373 free(editor);
7375 if (fd != -1 && close(fd) == -1 && err == NULL)
7376 err = got_error_from_errno2("close", *tagmsg_path);
7378 if (err) {
7379 free(*tagmsg);
7380 *tagmsg = NULL;
7382 return err;
7385 static const struct got_error *
7386 add_tag(struct got_repository *repo, const char *tagger,
7387 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7388 const char *signer_id, int verbosity)
7390 const struct got_error *err = NULL;
7391 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7392 char *label = NULL, *commit_id_str = NULL;
7393 struct got_reference *ref = NULL;
7394 char *refname = NULL, *tagmsg = NULL;
7395 char *tagmsg_path = NULL, *tag_id_str = NULL;
7396 int preserve_tagmsg = 0;
7397 struct got_reflist_head refs;
7399 TAILQ_INIT(&refs);
7402 * Don't let the user create a tag name with a leading '-'.
7403 * While technically a valid reference name, this case is usually
7404 * an unintended typo.
7406 if (tag_name[0] == '-')
7407 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7409 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7410 if (err)
7411 goto done;
7413 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7414 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7415 if (err)
7416 goto done;
7418 err = got_object_id_str(&commit_id_str, commit_id);
7419 if (err)
7420 goto done;
7422 err = get_tag_refname(&refname, tag_name);
7423 if (err)
7424 goto done;
7425 if (strncmp("refs/tags/", tag_name, 10) == 0)
7426 tag_name += 10;
7428 err = got_ref_open(&ref, repo, refname, 0);
7429 if (err == NULL) {
7430 err = got_error(GOT_ERR_TAG_EXISTS);
7431 goto done;
7432 } else if (err->code != GOT_ERR_NOT_REF)
7433 goto done;
7435 if (tagmsg_arg == NULL) {
7436 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7437 tag_name, got_repo_get_path(repo));
7438 if (err) {
7439 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7440 tagmsg_path != NULL)
7441 preserve_tagmsg = 1;
7442 goto done;
7444 /* Editor is done; we can now apply unveil(2) */
7445 err = got_sigs_apply_unveil();
7446 if (err)
7447 goto done;
7448 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7449 if (err)
7450 goto done;
7453 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7454 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7455 verbosity);
7456 if (err) {
7457 if (tagmsg_path)
7458 preserve_tagmsg = 1;
7459 goto done;
7462 err = got_ref_alloc(&ref, refname, tag_id);
7463 if (err) {
7464 if (tagmsg_path)
7465 preserve_tagmsg = 1;
7466 goto done;
7469 err = got_ref_write(ref, repo);
7470 if (err) {
7471 if (tagmsg_path)
7472 preserve_tagmsg = 1;
7473 goto done;
7476 err = got_object_id_str(&tag_id_str, tag_id);
7477 if (err) {
7478 if (tagmsg_path)
7479 preserve_tagmsg = 1;
7480 goto done;
7482 printf("Created tag %s\n", tag_id_str);
7483 done:
7484 if (preserve_tagmsg) {
7485 fprintf(stderr, "%s: tag message preserved in %s\n",
7486 getprogname(), tagmsg_path);
7487 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7488 err = got_error_from_errno2("unlink", tagmsg_path);
7489 free(tag_id_str);
7490 if (ref)
7491 got_ref_close(ref);
7492 free(commit_id);
7493 free(commit_id_str);
7494 free(refname);
7495 free(tagmsg);
7496 free(tagmsg_path);
7497 got_ref_list_free(&refs);
7498 return err;
7501 static const struct got_error *
7502 cmd_tag(int argc, char *argv[])
7504 const struct got_error *error = NULL;
7505 struct got_repository *repo = NULL;
7506 struct got_worktree *worktree = NULL;
7507 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7508 char *gitconfig_path = NULL, *tagger = NULL;
7509 char *allowed_signers = NULL, *revoked_signers = NULL;
7510 const char *signer_id = NULL;
7511 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7512 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7513 int *pack_fds = NULL;
7515 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7516 switch (ch) {
7517 case 'c':
7518 commit_id_arg = optarg;
7519 break;
7520 case 'l':
7521 do_list = 1;
7522 break;
7523 case 'm':
7524 tagmsg = optarg;
7525 break;
7526 case 'r':
7527 repo_path = realpath(optarg, NULL);
7528 if (repo_path == NULL) {
7529 error = got_error_from_errno2("realpath",
7530 optarg);
7531 goto done;
7533 got_path_strip_trailing_slashes(repo_path);
7534 break;
7535 case 's':
7536 signer_id = optarg;
7537 break;
7538 case 'V':
7539 verify_tags = 1;
7540 break;
7541 case 'v':
7542 if (verbosity < 0)
7543 verbosity = 0;
7544 else if (verbosity < 3)
7545 verbosity++;
7546 break;
7547 default:
7548 usage_tag();
7549 /* NOTREACHED */
7553 argc -= optind;
7554 argv += optind;
7556 if (do_list || verify_tags) {
7557 if (commit_id_arg != NULL)
7558 errx(1,
7559 "-c option can only be used when creating a tag");
7560 if (tagmsg) {
7561 if (do_list)
7562 option_conflict('l', 'm');
7563 else
7564 option_conflict('V', 'm');
7566 if (signer_id) {
7567 if (do_list)
7568 option_conflict('l', 's');
7569 else
7570 option_conflict('V', 's');
7572 if (argc > 1)
7573 usage_tag();
7574 } else if (argc != 1)
7575 usage_tag();
7577 if (argc == 1)
7578 tag_name = argv[0];
7580 #ifndef PROFILE
7581 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7582 "sendfd unveil", NULL) == -1)
7583 err(1, "pledge");
7584 #endif
7585 cwd = getcwd(NULL, 0);
7586 if (cwd == NULL) {
7587 error = got_error_from_errno("getcwd");
7588 goto done;
7591 error = got_repo_pack_fds_open(&pack_fds);
7592 if (error != NULL)
7593 goto done;
7595 if (repo_path == NULL) {
7596 error = got_worktree_open(&worktree, cwd);
7597 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7598 goto done;
7599 else
7600 error = NULL;
7601 if (worktree) {
7602 repo_path =
7603 strdup(got_worktree_get_repo_path(worktree));
7604 if (repo_path == NULL)
7605 error = got_error_from_errno("strdup");
7606 if (error)
7607 goto done;
7608 } else {
7609 repo_path = strdup(cwd);
7610 if (repo_path == NULL) {
7611 error = got_error_from_errno("strdup");
7612 goto done;
7617 if (do_list || verify_tags) {
7618 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7619 if (error != NULL)
7620 goto done;
7621 error = get_allowed_signers(&allowed_signers, repo, worktree);
7622 if (error)
7623 goto done;
7624 error = get_revoked_signers(&revoked_signers, repo, worktree);
7625 if (error)
7626 goto done;
7627 if (worktree) {
7628 /* Release work tree lock. */
7629 got_worktree_close(worktree);
7630 worktree = NULL;
7634 * Remove "cpath" promise unless needed for signature tmpfile
7635 * creation.
7637 if (verify_tags)
7638 got_sigs_apply_unveil();
7639 else {
7640 #ifndef PROFILE
7641 if (pledge("stdio rpath wpath flock proc exec sendfd "
7642 "unveil", NULL) == -1)
7643 err(1, "pledge");
7644 #endif
7646 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7647 if (error)
7648 goto done;
7649 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7650 revoked_signers, verbosity);
7651 } else {
7652 error = get_gitconfig_path(&gitconfig_path);
7653 if (error)
7654 goto done;
7655 error = got_repo_open(&repo, repo_path, gitconfig_path,
7656 pack_fds);
7657 if (error != NULL)
7658 goto done;
7660 error = get_author(&tagger, repo, worktree);
7661 if (error)
7662 goto done;
7663 if (signer_id == NULL)
7664 signer_id = get_signer_id(repo, worktree);
7666 if (tagmsg) {
7667 if (signer_id) {
7668 error = got_sigs_apply_unveil();
7669 if (error)
7670 goto done;
7672 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7673 if (error)
7674 goto done;
7677 if (commit_id_arg == NULL) {
7678 struct got_reference *head_ref;
7679 struct got_object_id *commit_id;
7680 error = got_ref_open(&head_ref, repo,
7681 worktree ? got_worktree_get_head_ref_name(worktree)
7682 : GOT_REF_HEAD, 0);
7683 if (error)
7684 goto done;
7685 error = got_ref_resolve(&commit_id, repo, head_ref);
7686 got_ref_close(head_ref);
7687 if (error)
7688 goto done;
7689 error = got_object_id_str(&commit_id_str, commit_id);
7690 free(commit_id);
7691 if (error)
7692 goto done;
7695 if (worktree) {
7696 /* Release work tree lock. */
7697 got_worktree_close(worktree);
7698 worktree = NULL;
7701 error = add_tag(repo, tagger, tag_name,
7702 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7703 signer_id, verbosity);
7705 done:
7706 if (repo) {
7707 const struct got_error *close_err = got_repo_close(repo);
7708 if (error == NULL)
7709 error = close_err;
7711 if (worktree)
7712 got_worktree_close(worktree);
7713 if (pack_fds) {
7714 const struct got_error *pack_err =
7715 got_repo_pack_fds_close(pack_fds);
7716 if (error == NULL)
7717 error = pack_err;
7719 free(cwd);
7720 free(repo_path);
7721 free(gitconfig_path);
7722 free(commit_id_str);
7723 free(tagger);
7724 free(allowed_signers);
7725 free(revoked_signers);
7726 return error;
7729 __dead static void
7730 usage_add(void)
7732 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7733 exit(1);
7736 static const struct got_error *
7737 add_progress(void *arg, unsigned char status, const char *path)
7739 while (path[0] == '/')
7740 path++;
7741 printf("%c %s\n", status, path);
7742 return NULL;
7745 static const struct got_error *
7746 cmd_add(int argc, char *argv[])
7748 const struct got_error *error = NULL;
7749 struct got_repository *repo = NULL;
7750 struct got_worktree *worktree = NULL;
7751 char *cwd = NULL;
7752 struct got_pathlist_head paths;
7753 struct got_pathlist_entry *pe;
7754 int ch, can_recurse = 0, no_ignores = 0;
7755 int *pack_fds = NULL;
7757 TAILQ_INIT(&paths);
7759 while ((ch = getopt(argc, argv, "IR")) != -1) {
7760 switch (ch) {
7761 case 'I':
7762 no_ignores = 1;
7763 break;
7764 case 'R':
7765 can_recurse = 1;
7766 break;
7767 default:
7768 usage_add();
7769 /* NOTREACHED */
7773 argc -= optind;
7774 argv += optind;
7776 #ifndef PROFILE
7777 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7778 NULL) == -1)
7779 err(1, "pledge");
7780 #endif
7781 if (argc < 1)
7782 usage_add();
7784 cwd = getcwd(NULL, 0);
7785 if (cwd == NULL) {
7786 error = got_error_from_errno("getcwd");
7787 goto done;
7790 error = got_repo_pack_fds_open(&pack_fds);
7791 if (error != NULL)
7792 goto done;
7794 error = got_worktree_open(&worktree, cwd);
7795 if (error) {
7796 if (error->code == GOT_ERR_NOT_WORKTREE)
7797 error = wrap_not_worktree_error(error, "add", cwd);
7798 goto done;
7801 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7802 NULL, pack_fds);
7803 if (error != NULL)
7804 goto done;
7806 error = apply_unveil(got_repo_get_path(repo), 1,
7807 got_worktree_get_root_path(worktree));
7808 if (error)
7809 goto done;
7811 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7812 if (error)
7813 goto done;
7815 if (!can_recurse) {
7816 char *ondisk_path;
7817 struct stat sb;
7818 TAILQ_FOREACH(pe, &paths, entry) {
7819 if (asprintf(&ondisk_path, "%s/%s",
7820 got_worktree_get_root_path(worktree),
7821 pe->path) == -1) {
7822 error = got_error_from_errno("asprintf");
7823 goto done;
7825 if (lstat(ondisk_path, &sb) == -1) {
7826 if (errno == ENOENT) {
7827 free(ondisk_path);
7828 continue;
7830 error = got_error_from_errno2("lstat",
7831 ondisk_path);
7832 free(ondisk_path);
7833 goto done;
7835 free(ondisk_path);
7836 if (S_ISDIR(sb.st_mode)) {
7837 error = got_error_msg(GOT_ERR_BAD_PATH,
7838 "adding directories requires -R option");
7839 goto done;
7844 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7845 NULL, repo, no_ignores);
7846 done:
7847 if (repo) {
7848 const struct got_error *close_err = got_repo_close(repo);
7849 if (error == NULL)
7850 error = close_err;
7852 if (worktree)
7853 got_worktree_close(worktree);
7854 if (pack_fds) {
7855 const struct got_error *pack_err =
7856 got_repo_pack_fds_close(pack_fds);
7857 if (error == NULL)
7858 error = pack_err;
7860 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7861 free(cwd);
7862 return error;
7865 __dead static void
7866 usage_remove(void)
7868 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7869 getprogname());
7870 exit(1);
7873 static const struct got_error *
7874 print_remove_status(void *arg, unsigned char status,
7875 unsigned char staged_status, const char *path)
7877 while (path[0] == '/')
7878 path++;
7879 if (status == GOT_STATUS_NONEXISTENT)
7880 return NULL;
7881 if (status == staged_status && (status == GOT_STATUS_DELETE))
7882 status = GOT_STATUS_NO_CHANGE;
7883 printf("%c%c %s\n", status, staged_status, path);
7884 return NULL;
7887 static const struct got_error *
7888 cmd_remove(int argc, char *argv[])
7890 const struct got_error *error = NULL;
7891 struct got_worktree *worktree = NULL;
7892 struct got_repository *repo = NULL;
7893 const char *status_codes = NULL;
7894 char *cwd = NULL;
7895 struct got_pathlist_head paths;
7896 struct got_pathlist_entry *pe;
7897 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7898 int ignore_missing_paths = 0;
7899 int *pack_fds = NULL;
7901 TAILQ_INIT(&paths);
7903 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7904 switch (ch) {
7905 case 'f':
7906 delete_local_mods = 1;
7907 ignore_missing_paths = 1;
7908 break;
7909 case 'k':
7910 keep_on_disk = 1;
7911 break;
7912 case 'R':
7913 can_recurse = 1;
7914 break;
7915 case 's':
7916 for (i = 0; i < strlen(optarg); i++) {
7917 switch (optarg[i]) {
7918 case GOT_STATUS_MODIFY:
7919 delete_local_mods = 1;
7920 break;
7921 case GOT_STATUS_MISSING:
7922 ignore_missing_paths = 1;
7923 break;
7924 default:
7925 errx(1, "invalid status code '%c'",
7926 optarg[i]);
7929 status_codes = optarg;
7930 break;
7931 default:
7932 usage_remove();
7933 /* NOTREACHED */
7937 argc -= optind;
7938 argv += optind;
7940 #ifndef PROFILE
7941 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7942 NULL) == -1)
7943 err(1, "pledge");
7944 #endif
7945 if (argc < 1)
7946 usage_remove();
7948 cwd = getcwd(NULL, 0);
7949 if (cwd == NULL) {
7950 error = got_error_from_errno("getcwd");
7951 goto done;
7954 error = got_repo_pack_fds_open(&pack_fds);
7955 if (error != NULL)
7956 goto done;
7958 error = got_worktree_open(&worktree, cwd);
7959 if (error) {
7960 if (error->code == GOT_ERR_NOT_WORKTREE)
7961 error = wrap_not_worktree_error(error, "remove", cwd);
7962 goto done;
7965 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7966 NULL, pack_fds);
7967 if (error)
7968 goto done;
7970 error = apply_unveil(got_repo_get_path(repo), 1,
7971 got_worktree_get_root_path(worktree));
7972 if (error)
7973 goto done;
7975 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7976 if (error)
7977 goto done;
7979 if (!can_recurse) {
7980 char *ondisk_path;
7981 struct stat sb;
7982 TAILQ_FOREACH(pe, &paths, entry) {
7983 if (asprintf(&ondisk_path, "%s/%s",
7984 got_worktree_get_root_path(worktree),
7985 pe->path) == -1) {
7986 error = got_error_from_errno("asprintf");
7987 goto done;
7989 if (lstat(ondisk_path, &sb) == -1) {
7990 if (errno == ENOENT) {
7991 free(ondisk_path);
7992 continue;
7994 error = got_error_from_errno2("lstat",
7995 ondisk_path);
7996 free(ondisk_path);
7997 goto done;
7999 free(ondisk_path);
8000 if (S_ISDIR(sb.st_mode)) {
8001 error = got_error_msg(GOT_ERR_BAD_PATH,
8002 "removing directories requires -R option");
8003 goto done;
8008 error = got_worktree_schedule_delete(worktree, &paths,
8009 delete_local_mods, status_codes, print_remove_status, NULL,
8010 repo, keep_on_disk, ignore_missing_paths);
8011 done:
8012 if (repo) {
8013 const struct got_error *close_err = got_repo_close(repo);
8014 if (error == NULL)
8015 error = close_err;
8017 if (worktree)
8018 got_worktree_close(worktree);
8019 if (pack_fds) {
8020 const struct got_error *pack_err =
8021 got_repo_pack_fds_close(pack_fds);
8022 if (error == NULL)
8023 error = pack_err;
8025 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8026 free(cwd);
8027 return error;
8030 __dead static void
8031 usage_patch(void)
8033 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8034 "[patchfile]\n", getprogname());
8035 exit(1);
8038 static const struct got_error *
8039 patch_from_stdin(int *patchfd)
8041 const struct got_error *err = NULL;
8042 ssize_t r;
8043 char buf[BUFSIZ];
8044 sig_t sighup, sigint, sigquit;
8046 *patchfd = got_opentempfd();
8047 if (*patchfd == -1)
8048 return got_error_from_errno("got_opentempfd");
8050 sighup = signal(SIGHUP, SIG_DFL);
8051 sigint = signal(SIGINT, SIG_DFL);
8052 sigquit = signal(SIGQUIT, SIG_DFL);
8054 for (;;) {
8055 r = read(0, buf, sizeof(buf));
8056 if (r == -1) {
8057 err = got_error_from_errno("read");
8058 break;
8060 if (r == 0)
8061 break;
8062 if (write(*patchfd, buf, r) == -1) {
8063 err = got_error_from_errno("write");
8064 break;
8068 signal(SIGHUP, sighup);
8069 signal(SIGINT, sigint);
8070 signal(SIGQUIT, sigquit);
8072 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8073 err = got_error_from_errno("lseek");
8075 if (err != NULL) {
8076 close(*patchfd);
8077 *patchfd = -1;
8080 return err;
8083 static const struct got_error *
8084 patch_progress(void *arg, const char *old, const char *new,
8085 unsigned char status, const struct got_error *error, int old_from,
8086 int old_lines, int new_from, int new_lines, int offset,
8087 int ws_mangled, const struct got_error *hunk_err)
8089 const char *path = new == NULL ? old : new;
8091 while (*path == '/')
8092 path++;
8094 if (status != 0)
8095 printf("%c %s\n", status, path);
8097 if (error != NULL)
8098 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8100 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8101 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8102 old_lines, new_from, new_lines);
8103 if (hunk_err != NULL)
8104 printf("%s\n", hunk_err->msg);
8105 else if (offset != 0)
8106 printf("applied with offset %d\n", offset);
8107 else
8108 printf("hunk contains mangled whitespace\n");
8111 return NULL;
8114 static const struct got_error *
8115 cmd_patch(int argc, char *argv[])
8117 const struct got_error *error = NULL, *close_error = NULL;
8118 struct got_worktree *worktree = NULL;
8119 struct got_repository *repo = NULL;
8120 struct got_reflist_head refs;
8121 struct got_object_id *commit_id = NULL;
8122 const char *commit_id_str = NULL;
8123 struct stat sb;
8124 const char *errstr;
8125 char *cwd = NULL;
8126 int ch, nop = 0, strip = -1, reverse = 0;
8127 int patchfd;
8128 int *pack_fds = NULL;
8130 TAILQ_INIT(&refs);
8132 #ifndef PROFILE
8133 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8134 "unveil", NULL) == -1)
8135 err(1, "pledge");
8136 #endif
8138 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8139 switch (ch) {
8140 case 'c':
8141 commit_id_str = optarg;
8142 break;
8143 case 'n':
8144 nop = 1;
8145 break;
8146 case 'p':
8147 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8148 if (errstr != NULL)
8149 errx(1, "pathname strip count is %s: %s",
8150 errstr, optarg);
8151 break;
8152 case 'R':
8153 reverse = 1;
8154 break;
8155 default:
8156 usage_patch();
8157 /* NOTREACHED */
8161 argc -= optind;
8162 argv += optind;
8164 if (argc == 0) {
8165 error = patch_from_stdin(&patchfd);
8166 if (error)
8167 return error;
8168 } else if (argc == 1) {
8169 patchfd = open(argv[0], O_RDONLY);
8170 if (patchfd == -1) {
8171 error = got_error_from_errno2("open", argv[0]);
8172 return error;
8174 if (fstat(patchfd, &sb) == -1) {
8175 error = got_error_from_errno2("fstat", argv[0]);
8176 goto done;
8178 if (!S_ISREG(sb.st_mode)) {
8179 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8180 goto done;
8182 } else
8183 usage_patch();
8185 if ((cwd = getcwd(NULL, 0)) == NULL) {
8186 error = got_error_from_errno("getcwd");
8187 goto done;
8190 error = got_repo_pack_fds_open(&pack_fds);
8191 if (error != NULL)
8192 goto done;
8194 error = got_worktree_open(&worktree, cwd);
8195 if (error != NULL)
8196 goto done;
8198 const char *repo_path = got_worktree_get_repo_path(worktree);
8199 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8200 if (error != NULL)
8201 goto done;
8203 error = apply_unveil(got_repo_get_path(repo), 0,
8204 got_worktree_get_root_path(worktree));
8205 if (error != NULL)
8206 goto done;
8208 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8209 if (error)
8210 goto done;
8212 if (commit_id_str != NULL) {
8213 error = got_repo_match_object_id(&commit_id, NULL,
8214 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8215 if (error)
8216 goto done;
8219 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8220 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8222 done:
8223 got_ref_list_free(&refs);
8224 free(commit_id);
8225 if (repo) {
8226 close_error = got_repo_close(repo);
8227 if (error == NULL)
8228 error = close_error;
8230 if (worktree != NULL) {
8231 close_error = got_worktree_close(worktree);
8232 if (error == NULL)
8233 error = close_error;
8235 if (pack_fds) {
8236 const struct got_error *pack_err =
8237 got_repo_pack_fds_close(pack_fds);
8238 if (error == NULL)
8239 error = pack_err;
8241 free(cwd);
8242 return error;
8245 __dead static void
8246 usage_revert(void)
8248 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8249 getprogname());
8250 exit(1);
8253 static const struct got_error *
8254 revert_progress(void *arg, unsigned char status, const char *path)
8256 if (status == GOT_STATUS_UNVERSIONED)
8257 return NULL;
8259 while (path[0] == '/')
8260 path++;
8261 printf("%c %s\n", status, path);
8262 return NULL;
8265 struct choose_patch_arg {
8266 FILE *patch_script_file;
8267 const char *action;
8270 static const struct got_error *
8271 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8272 int nchanges, const char *action)
8274 const struct got_error *err;
8275 char *line = NULL;
8276 size_t linesize = 0;
8277 ssize_t linelen;
8279 switch (status) {
8280 case GOT_STATUS_ADD:
8281 printf("A %s\n%s this addition? [y/n] ", path, action);
8282 break;
8283 case GOT_STATUS_DELETE:
8284 printf("D %s\n%s this deletion? [y/n] ", path, action);
8285 break;
8286 case GOT_STATUS_MODIFY:
8287 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8288 return got_error_from_errno("fseek");
8289 printf(GOT_COMMIT_SEP_STR);
8290 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8291 printf("%s", line);
8292 if (linelen == -1 && ferror(patch_file)) {
8293 err = got_error_from_errno("getline");
8294 free(line);
8295 return err;
8297 free(line);
8298 printf(GOT_COMMIT_SEP_STR);
8299 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8300 path, n, nchanges, action);
8301 break;
8302 default:
8303 return got_error_path(path, GOT_ERR_FILE_STATUS);
8306 fflush(stdout);
8307 return NULL;
8310 static const struct got_error *
8311 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8312 FILE *patch_file, int n, int nchanges)
8314 const struct got_error *err = NULL;
8315 char *line = NULL;
8316 size_t linesize = 0;
8317 ssize_t linelen;
8318 int resp = ' ';
8319 struct choose_patch_arg *a = arg;
8321 *choice = GOT_PATCH_CHOICE_NONE;
8323 if (a->patch_script_file) {
8324 char *nl;
8325 err = show_change(status, path, patch_file, n, nchanges,
8326 a->action);
8327 if (err)
8328 return err;
8329 linelen = getline(&line, &linesize, a->patch_script_file);
8330 if (linelen == -1) {
8331 if (ferror(a->patch_script_file))
8332 return got_error_from_errno("getline");
8333 return NULL;
8335 nl = strchr(line, '\n');
8336 if (nl)
8337 *nl = '\0';
8338 if (strcmp(line, "y") == 0) {
8339 *choice = GOT_PATCH_CHOICE_YES;
8340 printf("y\n");
8341 } else if (strcmp(line, "n") == 0) {
8342 *choice = GOT_PATCH_CHOICE_NO;
8343 printf("n\n");
8344 } else if (strcmp(line, "q") == 0 &&
8345 status == GOT_STATUS_MODIFY) {
8346 *choice = GOT_PATCH_CHOICE_QUIT;
8347 printf("q\n");
8348 } else
8349 printf("invalid response '%s'\n", line);
8350 free(line);
8351 return NULL;
8354 while (resp != 'y' && resp != 'n' && resp != 'q') {
8355 err = show_change(status, path, patch_file, n, nchanges,
8356 a->action);
8357 if (err)
8358 return err;
8359 resp = getchar();
8360 if (resp == '\n')
8361 resp = getchar();
8362 if (status == GOT_STATUS_MODIFY) {
8363 if (resp != 'y' && resp != 'n' && resp != 'q') {
8364 printf("invalid response '%c'\n", resp);
8365 resp = ' ';
8367 } else if (resp != 'y' && resp != 'n') {
8368 printf("invalid response '%c'\n", resp);
8369 resp = ' ';
8373 if (resp == 'y')
8374 *choice = GOT_PATCH_CHOICE_YES;
8375 else if (resp == 'n')
8376 *choice = GOT_PATCH_CHOICE_NO;
8377 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8378 *choice = GOT_PATCH_CHOICE_QUIT;
8380 return NULL;
8383 struct wt_commitable_path_arg {
8384 struct got_pathlist_head *commit_paths;
8385 int *has_changes;
8389 * Shortcut work tree status callback to determine if the set of paths scanned
8390 * has at least one versioned path that is being modified and, if not NULL, is
8391 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8392 * soon as a path is passed with a status that satisfies this criteria.
8394 static const struct got_error *
8395 worktree_has_commitable_path(void *arg, unsigned char status,
8396 unsigned char staged_status, const char *path,
8397 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8398 struct got_object_id *commit_id, int dirfd, const char *de_name)
8400 struct wt_commitable_path_arg *a = arg;
8402 if (status == staged_status && (status == GOT_STATUS_DELETE))
8403 status = GOT_STATUS_NO_CHANGE;
8405 if (!(status == GOT_STATUS_NO_CHANGE ||
8406 status == GOT_STATUS_UNVERSIONED) ||
8407 staged_status != GOT_STATUS_NO_CHANGE) {
8408 if (a->commit_paths != NULL) {
8409 struct got_pathlist_entry *pe;
8411 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8412 if (strncmp(path, pe->path,
8413 pe->path_len) == 0) {
8414 *a->has_changes = 1;
8415 break;
8418 } else
8419 *a->has_changes = 1;
8421 if (*a->has_changes)
8422 return got_error(GOT_ERR_FILE_MODIFIED);
8425 return NULL;
8429 * Check that the changeset of the commit identified by id is
8430 * comprised of at least one modified path that is being committed.
8432 static const struct got_error *
8433 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8434 struct got_object_id *id, struct got_worktree *worktree,
8435 struct got_repository *repo)
8437 const struct got_error *err;
8438 struct got_pathlist_head paths;
8439 struct got_commit_object *commit = NULL, *pcommit = NULL;
8440 struct got_tree_object *tree = NULL, *ptree = NULL;
8441 struct got_object_qid *pid;
8443 TAILQ_INIT(&paths);
8445 err = got_object_open_as_commit(&commit, repo, id);
8446 if (err)
8447 goto done;
8449 err = got_object_open_as_tree(&tree, repo,
8450 got_object_commit_get_tree_id(commit));
8451 if (err)
8452 goto done;
8454 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8455 if (pid != NULL) {
8456 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8457 if (err)
8458 goto done;
8460 err = got_object_open_as_tree(&ptree, repo,
8461 got_object_commit_get_tree_id(pcommit));
8462 if (err)
8463 goto done;
8466 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8467 got_diff_tree_collect_changed_paths, &paths, 0);
8468 if (err)
8469 goto done;
8471 err = got_worktree_status(worktree, &paths, repo, 0,
8472 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8473 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8475 * At least one changed path in the referenced commit is
8476 * modified in the work tree, that's all we need to know!
8478 err = NULL;
8481 done:
8482 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8483 if (commit)
8484 got_object_commit_close(commit);
8485 if (pcommit)
8486 got_object_commit_close(pcommit);
8487 if (tree)
8488 got_object_tree_close(tree);
8489 if (ptree)
8490 got_object_tree_close(ptree);
8491 return err;
8495 * Remove any "logmsg" reference comprised entirely of paths that have
8496 * been reverted in this work tree. If any path in the logmsg ref changeset
8497 * remains in a changed state in the worktree, do not remove the reference.
8499 static const struct got_error *
8500 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8502 const struct got_error *err;
8503 struct got_reflist_head refs;
8504 struct got_reflist_entry *re;
8505 struct got_commit_object *commit = NULL;
8506 struct got_object_id *commit_id = NULL;
8507 struct wt_commitable_path_arg wcpa;
8508 char *uuidstr = NULL;
8510 TAILQ_INIT(&refs);
8512 err = got_worktree_get_uuid(&uuidstr, worktree);
8513 if (err)
8514 goto done;
8516 err = got_ref_list(&refs, repo, "refs/got/worktree",
8517 got_ref_cmp_by_name, repo);
8518 if (err)
8519 goto done;
8521 TAILQ_FOREACH(re, &refs, entry) {
8522 const char *refname;
8523 int has_changes = 0;
8525 refname = got_ref_get_name(re->ref);
8527 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8528 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8529 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8530 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8531 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8532 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8533 else
8534 continue;
8536 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8537 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8538 else
8539 continue;
8541 err = got_repo_match_object_id(&commit_id, NULL, refname,
8542 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8543 if (err)
8544 goto done;
8546 err = got_object_open_as_commit(&commit, repo, commit_id);
8547 if (err)
8548 goto done;
8550 wcpa.commit_paths = NULL;
8551 wcpa.has_changes = &has_changes;
8553 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8554 worktree, repo);
8555 if (err)
8556 goto done;
8558 if (!has_changes) {
8559 err = got_ref_delete(re->ref, repo);
8560 if (err)
8561 goto done;
8564 got_object_commit_close(commit);
8565 commit = NULL;
8566 free(commit_id);
8567 commit_id = NULL;
8570 done:
8571 free(uuidstr);
8572 free(commit_id);
8573 got_ref_list_free(&refs);
8574 if (commit)
8575 got_object_commit_close(commit);
8576 return err;
8579 static const struct got_error *
8580 cmd_revert(int argc, char *argv[])
8582 const struct got_error *error = NULL;
8583 struct got_worktree *worktree = NULL;
8584 struct got_repository *repo = NULL;
8585 char *cwd = NULL, *path = NULL;
8586 struct got_pathlist_head paths;
8587 struct got_pathlist_entry *pe;
8588 int ch, can_recurse = 0, pflag = 0;
8589 FILE *patch_script_file = NULL;
8590 const char *patch_script_path = NULL;
8591 struct choose_patch_arg cpa;
8592 int *pack_fds = NULL;
8594 TAILQ_INIT(&paths);
8596 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8597 switch (ch) {
8598 case 'F':
8599 patch_script_path = optarg;
8600 break;
8601 case 'p':
8602 pflag = 1;
8603 break;
8604 case 'R':
8605 can_recurse = 1;
8606 break;
8607 default:
8608 usage_revert();
8609 /* NOTREACHED */
8613 argc -= optind;
8614 argv += optind;
8616 #ifndef PROFILE
8617 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8618 "unveil", NULL) == -1)
8619 err(1, "pledge");
8620 #endif
8621 if (argc < 1)
8622 usage_revert();
8623 if (patch_script_path && !pflag)
8624 errx(1, "-F option can only be used together with -p option");
8626 cwd = getcwd(NULL, 0);
8627 if (cwd == NULL) {
8628 error = got_error_from_errno("getcwd");
8629 goto done;
8632 error = got_repo_pack_fds_open(&pack_fds);
8633 if (error != NULL)
8634 goto done;
8636 error = got_worktree_open(&worktree, cwd);
8637 if (error) {
8638 if (error->code == GOT_ERR_NOT_WORKTREE)
8639 error = wrap_not_worktree_error(error, "revert", cwd);
8640 goto done;
8643 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8644 NULL, pack_fds);
8645 if (error != NULL)
8646 goto done;
8648 if (patch_script_path) {
8649 patch_script_file = fopen(patch_script_path, "re");
8650 if (patch_script_file == NULL) {
8651 error = got_error_from_errno2("fopen",
8652 patch_script_path);
8653 goto done;
8658 * XXX "c" perm needed on repo dir to delete merge references.
8660 error = apply_unveil(got_repo_get_path(repo), 0,
8661 got_worktree_get_root_path(worktree));
8662 if (error)
8663 goto done;
8665 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8666 if (error)
8667 goto done;
8669 if (!can_recurse) {
8670 char *ondisk_path;
8671 struct stat sb;
8672 TAILQ_FOREACH(pe, &paths, entry) {
8673 if (asprintf(&ondisk_path, "%s/%s",
8674 got_worktree_get_root_path(worktree),
8675 pe->path) == -1) {
8676 error = got_error_from_errno("asprintf");
8677 goto done;
8679 if (lstat(ondisk_path, &sb) == -1) {
8680 if (errno == ENOENT) {
8681 free(ondisk_path);
8682 continue;
8684 error = got_error_from_errno2("lstat",
8685 ondisk_path);
8686 free(ondisk_path);
8687 goto done;
8689 free(ondisk_path);
8690 if (S_ISDIR(sb.st_mode)) {
8691 error = got_error_msg(GOT_ERR_BAD_PATH,
8692 "reverting directories requires -R option");
8693 goto done;
8698 cpa.patch_script_file = patch_script_file;
8699 cpa.action = "revert";
8700 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8701 pflag ? choose_patch : NULL, &cpa, repo);
8703 error = rm_logmsg_ref(worktree, repo);
8704 done:
8705 if (patch_script_file && fclose(patch_script_file) == EOF &&
8706 error == NULL)
8707 error = got_error_from_errno2("fclose", patch_script_path);
8708 if (repo) {
8709 const struct got_error *close_err = got_repo_close(repo);
8710 if (error == NULL)
8711 error = close_err;
8713 if (worktree)
8714 got_worktree_close(worktree);
8715 if (pack_fds) {
8716 const struct got_error *pack_err =
8717 got_repo_pack_fds_close(pack_fds);
8718 if (error == NULL)
8719 error = pack_err;
8721 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8722 free(path);
8723 free(cwd);
8724 return error;
8727 __dead static void
8728 usage_commit(void)
8730 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8731 "[-m message] [path ...]\n", getprogname());
8732 exit(1);
8735 struct collect_commit_logmsg_arg {
8736 const char *cmdline_log;
8737 const char *prepared_log;
8738 const char *merged_log;
8739 int non_interactive;
8740 const char *editor;
8741 const char *worktree_path;
8742 const char *branch_name;
8743 const char *repo_path;
8744 char *logmsg_path;
8748 static const struct got_error *
8749 read_prepared_logmsg(char **logmsg, const char *path)
8751 const struct got_error *err = NULL;
8752 FILE *f = NULL;
8753 struct stat sb;
8754 size_t r;
8756 *logmsg = NULL;
8757 memset(&sb, 0, sizeof(sb));
8759 f = fopen(path, "re");
8760 if (f == NULL)
8761 return got_error_from_errno2("fopen", path);
8763 if (fstat(fileno(f), &sb) == -1) {
8764 err = got_error_from_errno2("fstat", path);
8765 goto done;
8767 if (sb.st_size == 0) {
8768 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8769 goto done;
8772 *logmsg = malloc(sb.st_size + 1);
8773 if (*logmsg == NULL) {
8774 err = got_error_from_errno("malloc");
8775 goto done;
8778 r = fread(*logmsg, 1, sb.st_size, f);
8779 if (r != sb.st_size) {
8780 if (ferror(f))
8781 err = got_error_from_errno2("fread", path);
8782 else
8783 err = got_error(GOT_ERR_IO);
8784 goto done;
8786 (*logmsg)[sb.st_size] = '\0';
8787 done:
8788 if (fclose(f) == EOF && err == NULL)
8789 err = got_error_from_errno2("fclose", path);
8790 if (err) {
8791 free(*logmsg);
8792 *logmsg = NULL;
8794 return err;
8797 static const struct got_error *
8798 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8799 const char *diff_path, char **logmsg, void *arg)
8801 char *initial_content = NULL;
8802 struct got_pathlist_entry *pe;
8803 const struct got_error *err = NULL;
8804 char *template = NULL;
8805 char *prepared_msg = NULL, *merged_msg = NULL;
8806 struct collect_commit_logmsg_arg *a = arg;
8807 int initial_content_len;
8808 int fd = -1;
8809 size_t len;
8811 /* if a message was specified on the command line, just use it */
8812 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8813 len = strlen(a->cmdline_log) + 1;
8814 *logmsg = malloc(len + 1);
8815 if (*logmsg == NULL)
8816 return got_error_from_errno("malloc");
8817 strlcpy(*logmsg, a->cmdline_log, len);
8818 return NULL;
8819 } else if (a->prepared_log != NULL && a->non_interactive)
8820 return read_prepared_logmsg(logmsg, a->prepared_log);
8822 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8823 return got_error_from_errno("asprintf");
8825 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8826 if (err)
8827 goto done;
8829 if (a->prepared_log) {
8830 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8831 if (err)
8832 goto done;
8833 } else if (a->merged_log) {
8834 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8835 if (err)
8836 goto done;
8839 initial_content_len = asprintf(&initial_content,
8840 "%s%s\n# changes to be committed on branch %s:\n",
8841 prepared_msg ? prepared_msg : "",
8842 merged_msg ? merged_msg : "", a->branch_name);
8843 if (initial_content_len == -1) {
8844 err = got_error_from_errno("asprintf");
8845 goto done;
8848 if (write(fd, initial_content, initial_content_len) == -1) {
8849 err = got_error_from_errno2("write", a->logmsg_path);
8850 goto done;
8853 TAILQ_FOREACH(pe, commitable_paths, entry) {
8854 struct got_commitable *ct = pe->data;
8855 dprintf(fd, "# %c %s\n",
8856 got_commitable_get_status(ct),
8857 got_commitable_get_path(ct));
8860 if (diff_path) {
8861 dprintf(fd, "# detailed changes can be viewed in %s\n",
8862 diff_path);
8865 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8866 initial_content_len, a->prepared_log ? 0 : 1);
8867 done:
8868 free(initial_content);
8869 free(template);
8870 free(prepared_msg);
8871 free(merged_msg);
8873 if (fd != -1 && close(fd) == -1 && err == NULL)
8874 err = got_error_from_errno2("close", a->logmsg_path);
8876 /* Editor is done; we can now apply unveil(2) */
8877 if (err == NULL)
8878 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8879 if (err) {
8880 free(*logmsg);
8881 *logmsg = NULL;
8883 return err;
8886 static const struct got_error *
8887 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8888 const char *type, int has_content)
8890 const struct got_error *err = NULL;
8891 char *logmsg = NULL;
8893 err = got_object_commit_get_logmsg(&logmsg, commit);
8894 if (err)
8895 return err;
8897 if (fprintf(f, "%s# log message of %s commit %s:%s",
8898 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8899 err = got_ferror(f, GOT_ERR_IO);
8901 free(logmsg);
8902 return err;
8906 * Lookup "logmsg" references of backed-out and cherrypicked commits
8907 * belonging to the current work tree. If found, and the worktree has
8908 * at least one modified file that was changed in the referenced commit,
8909 * add its log message to a new temporary file at *logmsg_path.
8910 * Add all refs found to matched_refs to be scheduled for removal on
8911 * successful commit.
8913 static const struct got_error *
8914 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8915 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8916 struct got_repository *repo)
8918 const struct got_error *err;
8919 struct got_commit_object *commit = NULL;
8920 struct got_object_id *id = NULL;
8921 struct got_reflist_head refs;
8922 struct got_reflist_entry *re, *re_match;
8923 FILE *f = NULL;
8924 char *uuidstr = NULL;
8925 int added_logmsg = 0;
8927 TAILQ_INIT(&refs);
8929 *logmsg_path = NULL;
8931 err = got_worktree_get_uuid(&uuidstr, worktree);
8932 if (err)
8933 goto done;
8935 err = got_ref_list(&refs, repo, "refs/got/worktree",
8936 got_ref_cmp_by_name, repo);
8937 if (err)
8938 goto done;
8940 TAILQ_FOREACH(re, &refs, entry) {
8941 const char *refname, *type;
8942 struct wt_commitable_path_arg wcpa;
8943 int add_logmsg = 0;
8945 refname = got_ref_get_name(re->ref);
8947 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8948 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8949 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8950 type = "cherrypicked";
8951 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8952 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8953 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8954 type = "backed-out";
8955 } else
8956 continue;
8958 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8959 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8960 else
8961 continue;
8963 err = got_repo_match_object_id(&id, NULL, refname,
8964 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8965 if (err)
8966 goto done;
8968 err = got_object_open_as_commit(&commit, repo, id);
8969 if (err)
8970 goto done;
8972 wcpa.commit_paths = paths;
8973 wcpa.has_changes = &add_logmsg;
8975 err = commit_path_changed_in_worktree(&wcpa, id,
8976 worktree, repo);
8977 if (err)
8978 goto done;
8980 if (add_logmsg) {
8981 if (f == NULL) {
8982 err = got_opentemp_named(logmsg_path, &f,
8983 "got-commit-logmsg", "");
8984 if (err)
8985 goto done;
8987 err = cat_logmsg(f, commit, refname, type,
8988 added_logmsg);
8989 if (err)
8990 goto done;
8991 if (!added_logmsg)
8992 ++added_logmsg;
8994 err = got_reflist_entry_dup(&re_match, re);
8995 if (err)
8996 goto done;
8997 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9000 got_object_commit_close(commit);
9001 commit = NULL;
9002 free(id);
9003 id = NULL;
9006 done:
9007 free(id);
9008 free(uuidstr);
9009 got_ref_list_free(&refs);
9010 if (commit)
9011 got_object_commit_close(commit);
9012 if (f && fclose(f) == EOF && err == NULL)
9013 err = got_error_from_errno("fclose");
9014 if (!added_logmsg) {
9015 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9016 err = got_error_from_errno2("unlink", *logmsg_path);
9017 *logmsg_path = NULL;
9019 return err;
9022 static const struct got_error *
9023 cmd_commit(int argc, char *argv[])
9025 const struct got_error *error = NULL;
9026 struct got_worktree *worktree = NULL;
9027 struct got_repository *repo = NULL;
9028 char *cwd = NULL, *id_str = NULL;
9029 struct got_object_id *id = NULL;
9030 const char *logmsg = NULL;
9031 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9032 struct collect_commit_logmsg_arg cl_arg;
9033 const char *author = NULL;
9034 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9035 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9036 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9037 int show_diff = 1;
9038 struct got_pathlist_head paths;
9039 struct got_reflist_head refs;
9040 struct got_reflist_entry *re;
9041 int *pack_fds = NULL;
9043 TAILQ_INIT(&refs);
9044 TAILQ_INIT(&paths);
9045 cl_arg.logmsg_path = NULL;
9047 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9048 switch (ch) {
9049 case 'A':
9050 author = optarg;
9051 error = valid_author(author);
9052 if (error)
9053 return error;
9054 break;
9055 case 'F':
9056 if (logmsg != NULL)
9057 option_conflict('F', 'm');
9058 prepared_logmsg = realpath(optarg, NULL);
9059 if (prepared_logmsg == NULL)
9060 return got_error_from_errno2("realpath",
9061 optarg);
9062 break;
9063 case 'm':
9064 if (prepared_logmsg)
9065 option_conflict('m', 'F');
9066 logmsg = optarg;
9067 break;
9068 case 'N':
9069 non_interactive = 1;
9070 break;
9071 case 'n':
9072 show_diff = 0;
9073 break;
9074 case 'S':
9075 allow_bad_symlinks = 1;
9076 break;
9077 default:
9078 usage_commit();
9079 /* NOTREACHED */
9083 argc -= optind;
9084 argv += optind;
9086 #ifndef PROFILE
9087 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9088 "unveil", NULL) == -1)
9089 err(1, "pledge");
9090 #endif
9091 cwd = getcwd(NULL, 0);
9092 if (cwd == NULL) {
9093 error = got_error_from_errno("getcwd");
9094 goto done;
9097 error = got_repo_pack_fds_open(&pack_fds);
9098 if (error != NULL)
9099 goto done;
9101 error = got_worktree_open(&worktree, cwd);
9102 if (error) {
9103 if (error->code == GOT_ERR_NOT_WORKTREE)
9104 error = wrap_not_worktree_error(error, "commit", cwd);
9105 goto done;
9108 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9109 if (error)
9110 goto done;
9111 if (rebase_in_progress) {
9112 error = got_error(GOT_ERR_REBASING);
9113 goto done;
9116 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9117 worktree);
9118 if (error)
9119 goto done;
9121 error = get_gitconfig_path(&gitconfig_path);
9122 if (error)
9123 goto done;
9124 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9125 gitconfig_path, pack_fds);
9126 if (error != NULL)
9127 goto done;
9129 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9130 if (error)
9131 goto done;
9132 if (merge_in_progress) {
9133 error = got_error(GOT_ERR_MERGE_BUSY);
9134 goto done;
9137 error = get_author(&committer, repo, worktree);
9138 if (error)
9139 goto done;
9141 if (author != NULL && !strcmp(committer, author)) {
9142 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9143 goto done;
9146 if (author == NULL)
9147 author = committer;
9150 * unveil(2) traverses exec(2); if an editor is used we have
9151 * to apply unveil after the log message has been written.
9153 if (logmsg == NULL || strlen(logmsg) == 0)
9154 error = get_editor(&editor);
9155 else
9156 error = apply_unveil(got_repo_get_path(repo), 0,
9157 got_worktree_get_root_path(worktree));
9158 if (error)
9159 goto done;
9161 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9162 if (error)
9163 goto done;
9165 if (prepared_logmsg == NULL) {
9166 error = lookup_logmsg_ref(&merged_logmsg,
9167 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9168 if (error)
9169 goto done;
9172 cl_arg.editor = editor;
9173 cl_arg.cmdline_log = logmsg;
9174 cl_arg.prepared_log = prepared_logmsg;
9175 cl_arg.merged_log = merged_logmsg;
9176 cl_arg.non_interactive = non_interactive;
9177 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9178 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9179 if (!histedit_in_progress) {
9180 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9181 error = got_error(GOT_ERR_COMMIT_BRANCH);
9182 goto done;
9184 cl_arg.branch_name += 11;
9186 cl_arg.repo_path = got_repo_get_path(repo);
9187 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9188 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9189 print_status, NULL, repo);
9190 if (error) {
9191 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9192 cl_arg.logmsg_path != NULL)
9193 preserve_logmsg = 1;
9194 goto done;
9197 error = got_object_id_str(&id_str, id);
9198 if (error)
9199 goto done;
9200 printf("Created commit %s\n", id_str);
9202 TAILQ_FOREACH(re, &refs, entry) {
9203 error = got_ref_delete(re->ref, repo);
9204 if (error)
9205 goto done;
9208 done:
9209 if (preserve_logmsg) {
9210 fprintf(stderr, "%s: log message preserved in %s\n",
9211 getprogname(), cl_arg.logmsg_path);
9212 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9213 error == NULL)
9214 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9215 free(cl_arg.logmsg_path);
9216 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9217 error = got_error_from_errno2("unlink", merged_logmsg);
9218 free(merged_logmsg);
9219 if (repo) {
9220 const struct got_error *close_err = got_repo_close(repo);
9221 if (error == NULL)
9222 error = close_err;
9224 if (worktree)
9225 got_worktree_close(worktree);
9226 if (pack_fds) {
9227 const struct got_error *pack_err =
9228 got_repo_pack_fds_close(pack_fds);
9229 if (error == NULL)
9230 error = pack_err;
9232 got_ref_list_free(&refs);
9233 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9234 free(cwd);
9235 free(id_str);
9236 free(gitconfig_path);
9237 free(editor);
9238 free(committer);
9239 free(prepared_logmsg);
9240 return error;
9243 __dead static void
9244 usage_send(void)
9246 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9247 "[-r repository-path] [-t tag] [remote-repository]\n",
9248 getprogname());
9249 exit(1);
9252 static void
9253 print_load_info(int print_colored, int print_found, int print_trees,
9254 int ncolored, int nfound, int ntrees)
9256 if (print_colored) {
9257 printf("%d commit%s colored", ncolored,
9258 ncolored == 1 ? "" : "s");
9260 if (print_found) {
9261 printf("%s%d object%s found",
9262 ncolored > 0 ? "; " : "",
9263 nfound, nfound == 1 ? "" : "s");
9265 if (print_trees) {
9266 printf("; %d tree%s scanned", ntrees,
9267 ntrees == 1 ? "" : "s");
9271 struct got_send_progress_arg {
9272 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9273 int verbosity;
9274 int last_ncolored;
9275 int last_nfound;
9276 int last_ntrees;
9277 int loading_done;
9278 int last_ncommits;
9279 int last_nobj_total;
9280 int last_p_deltify;
9281 int last_p_written;
9282 int last_p_sent;
9283 int printed_something;
9284 int sent_something;
9285 struct got_pathlist_head *delete_branches;
9288 static const struct got_error *
9289 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9290 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9291 int nobj_written, off_t bytes_sent, const char *refname,
9292 const char *errmsg, int success)
9294 struct got_send_progress_arg *a = arg;
9295 char scaled_packsize[FMT_SCALED_STRSIZE];
9296 char scaled_sent[FMT_SCALED_STRSIZE];
9297 int p_deltify = 0, p_written = 0, p_sent = 0;
9298 int print_colored = 0, print_found = 0, print_trees = 0;
9299 int print_searching = 0, print_total = 0;
9300 int print_deltify = 0, print_written = 0, print_sent = 0;
9302 if (a->verbosity < 0)
9303 return NULL;
9305 if (refname) {
9306 const char *status = success ? "accepted" : "rejected";
9308 if (success) {
9309 struct got_pathlist_entry *pe;
9310 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9311 const char *branchname = pe->path;
9312 if (got_path_cmp(branchname, refname,
9313 strlen(branchname), strlen(refname)) == 0) {
9314 status = "deleted";
9315 a->sent_something = 1;
9316 break;
9321 if (a->printed_something)
9322 putchar('\n');
9323 printf("Server has %s %s", status, refname);
9324 if (errmsg)
9325 printf(": %s", errmsg);
9326 a->printed_something = 1;
9327 return NULL;
9330 if (a->last_ncolored != ncolored) {
9331 print_colored = 1;
9332 a->last_ncolored = ncolored;
9335 if (a->last_nfound != nfound) {
9336 print_colored = 1;
9337 print_found = 1;
9338 a->last_nfound = nfound;
9341 if (a->last_ntrees != ntrees) {
9342 print_colored = 1;
9343 print_found = 1;
9344 print_trees = 1;
9345 a->last_ntrees = ntrees;
9348 if ((print_colored || print_found || print_trees) &&
9349 !a->loading_done) {
9350 printf("\r");
9351 print_load_info(print_colored, print_found, print_trees,
9352 ncolored, nfound, ntrees);
9353 a->printed_something = 1;
9354 fflush(stdout);
9355 return NULL;
9356 } else if (!a->loading_done) {
9357 printf("\r");
9358 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9359 printf("\n");
9360 a->loading_done = 1;
9363 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9364 return got_error_from_errno("fmt_scaled");
9365 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9366 return got_error_from_errno("fmt_scaled");
9368 if (a->last_ncommits != ncommits) {
9369 print_searching = 1;
9370 a->last_ncommits = ncommits;
9373 if (a->last_nobj_total != nobj_total) {
9374 print_searching = 1;
9375 print_total = 1;
9376 a->last_nobj_total = nobj_total;
9379 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9380 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9381 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9382 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9383 return got_error(GOT_ERR_NO_SPACE);
9386 if (nobj_deltify > 0 || nobj_written > 0) {
9387 if (nobj_deltify > 0) {
9388 p_deltify = (nobj_deltify * 100) / nobj_total;
9389 if (p_deltify != a->last_p_deltify) {
9390 a->last_p_deltify = p_deltify;
9391 print_searching = 1;
9392 print_total = 1;
9393 print_deltify = 1;
9396 if (nobj_written > 0) {
9397 p_written = (nobj_written * 100) / nobj_total;
9398 if (p_written != a->last_p_written) {
9399 a->last_p_written = p_written;
9400 print_searching = 1;
9401 print_total = 1;
9402 print_deltify = 1;
9403 print_written = 1;
9408 if (bytes_sent > 0) {
9409 p_sent = (bytes_sent * 100) / packfile_size;
9410 if (p_sent != a->last_p_sent) {
9411 a->last_p_sent = p_sent;
9412 print_searching = 1;
9413 print_total = 1;
9414 print_deltify = 1;
9415 print_written = 1;
9416 print_sent = 1;
9418 a->sent_something = 1;
9421 if (print_searching || print_total || print_deltify || print_written ||
9422 print_sent)
9423 printf("\r");
9424 if (print_searching)
9425 printf("packing %d reference%s", ncommits,
9426 ncommits == 1 ? "" : "s");
9427 if (print_total)
9428 printf("; %d object%s", nobj_total,
9429 nobj_total == 1 ? "" : "s");
9430 if (print_deltify)
9431 printf("; deltify: %d%%", p_deltify);
9432 if (print_sent)
9433 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9434 scaled_packsize, p_sent);
9435 else if (print_written)
9436 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9437 scaled_packsize, p_written);
9438 if (print_searching || print_total || print_deltify ||
9439 print_written || print_sent) {
9440 a->printed_something = 1;
9441 fflush(stdout);
9443 return NULL;
9446 static const struct got_error *
9447 cmd_send(int argc, char *argv[])
9449 const struct got_error *error = NULL;
9450 char *cwd = NULL, *repo_path = NULL;
9451 const char *remote_name;
9452 char *proto = NULL, *host = NULL, *port = NULL;
9453 char *repo_name = NULL, *server_path = NULL;
9454 const struct got_remote_repo *remotes, *remote = NULL;
9455 int nremotes, nbranches = 0, ndelete_branches = 0;
9456 struct got_repository *repo = NULL;
9457 struct got_worktree *worktree = NULL;
9458 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9459 struct got_pathlist_head branches;
9460 struct got_pathlist_head tags;
9461 struct got_reflist_head all_branches;
9462 struct got_reflist_head all_tags;
9463 struct got_pathlist_head delete_args;
9464 struct got_pathlist_head delete_branches;
9465 struct got_reflist_entry *re;
9466 struct got_pathlist_entry *pe;
9467 int i, ch, sendfd = -1, sendstatus;
9468 pid_t sendpid = -1;
9469 struct got_send_progress_arg spa;
9470 int verbosity = 0, overwrite_refs = 0;
9471 int send_all_branches = 0, send_all_tags = 0;
9472 struct got_reference *ref = NULL;
9473 int *pack_fds = NULL;
9475 TAILQ_INIT(&branches);
9476 TAILQ_INIT(&tags);
9477 TAILQ_INIT(&all_branches);
9478 TAILQ_INIT(&all_tags);
9479 TAILQ_INIT(&delete_args);
9480 TAILQ_INIT(&delete_branches);
9482 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9483 switch (ch) {
9484 case 'a':
9485 send_all_branches = 1;
9486 break;
9487 case 'b':
9488 error = got_pathlist_append(&branches, optarg, NULL);
9489 if (error)
9490 return error;
9491 nbranches++;
9492 break;
9493 case 'd':
9494 error = got_pathlist_append(&delete_args, optarg, NULL);
9495 if (error)
9496 return error;
9497 break;
9498 case 'f':
9499 overwrite_refs = 1;
9500 break;
9501 case 'q':
9502 verbosity = -1;
9503 break;
9504 case 'r':
9505 repo_path = realpath(optarg, NULL);
9506 if (repo_path == NULL)
9507 return got_error_from_errno2("realpath",
9508 optarg);
9509 got_path_strip_trailing_slashes(repo_path);
9510 break;
9511 case 'T':
9512 send_all_tags = 1;
9513 break;
9514 case 't':
9515 error = got_pathlist_append(&tags, optarg, NULL);
9516 if (error)
9517 return error;
9518 break;
9519 case 'v':
9520 if (verbosity < 0)
9521 verbosity = 0;
9522 else if (verbosity < 3)
9523 verbosity++;
9524 break;
9525 default:
9526 usage_send();
9527 /* NOTREACHED */
9530 argc -= optind;
9531 argv += optind;
9533 if (send_all_branches && !TAILQ_EMPTY(&branches))
9534 option_conflict('a', 'b');
9535 if (send_all_tags && !TAILQ_EMPTY(&tags))
9536 option_conflict('T', 't');
9539 if (argc == 0)
9540 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9541 else if (argc == 1)
9542 remote_name = argv[0];
9543 else
9544 usage_send();
9546 cwd = getcwd(NULL, 0);
9547 if (cwd == NULL) {
9548 error = got_error_from_errno("getcwd");
9549 goto done;
9552 error = got_repo_pack_fds_open(&pack_fds);
9553 if (error != NULL)
9554 goto done;
9556 if (repo_path == NULL) {
9557 error = got_worktree_open(&worktree, cwd);
9558 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9559 goto done;
9560 else
9561 error = NULL;
9562 if (worktree) {
9563 repo_path =
9564 strdup(got_worktree_get_repo_path(worktree));
9565 if (repo_path == NULL)
9566 error = got_error_from_errno("strdup");
9567 if (error)
9568 goto done;
9569 } else {
9570 repo_path = strdup(cwd);
9571 if (repo_path == NULL) {
9572 error = got_error_from_errno("strdup");
9573 goto done;
9578 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9579 if (error)
9580 goto done;
9582 if (worktree) {
9583 worktree_conf = got_worktree_get_gotconfig(worktree);
9584 if (worktree_conf) {
9585 got_gotconfig_get_remotes(&nremotes, &remotes,
9586 worktree_conf);
9587 for (i = 0; i < nremotes; i++) {
9588 if (strcmp(remotes[i].name, remote_name) == 0) {
9589 remote = &remotes[i];
9590 break;
9595 if (remote == NULL) {
9596 repo_conf = got_repo_get_gotconfig(repo);
9597 if (repo_conf) {
9598 got_gotconfig_get_remotes(&nremotes, &remotes,
9599 repo_conf);
9600 for (i = 0; i < nremotes; i++) {
9601 if (strcmp(remotes[i].name, remote_name) == 0) {
9602 remote = &remotes[i];
9603 break;
9608 if (remote == NULL) {
9609 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9610 for (i = 0; i < nremotes; i++) {
9611 if (strcmp(remotes[i].name, remote_name) == 0) {
9612 remote = &remotes[i];
9613 break;
9617 if (remote == NULL) {
9618 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9619 goto done;
9622 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9623 &repo_name, remote->send_url);
9624 if (error)
9625 goto done;
9627 if (strcmp(proto, "git") == 0) {
9628 #ifndef PROFILE
9629 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9630 "sendfd dns inet unveil", NULL) == -1)
9631 err(1, "pledge");
9632 #endif
9633 } else if (strcmp(proto, "git+ssh") == 0 ||
9634 strcmp(proto, "ssh") == 0) {
9635 #ifndef PROFILE
9636 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9637 "sendfd unveil", NULL) == -1)
9638 err(1, "pledge");
9639 #endif
9640 } else if (strcmp(proto, "http") == 0 ||
9641 strcmp(proto, "git+http") == 0) {
9642 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9643 goto done;
9644 } else {
9645 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9646 goto done;
9649 error = got_dial_apply_unveil(proto);
9650 if (error)
9651 goto done;
9653 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9654 if (error)
9655 goto done;
9657 if (send_all_branches) {
9658 error = got_ref_list(&all_branches, repo, "refs/heads",
9659 got_ref_cmp_by_name, NULL);
9660 if (error)
9661 goto done;
9662 TAILQ_FOREACH(re, &all_branches, entry) {
9663 const char *branchname = got_ref_get_name(re->ref);
9664 error = got_pathlist_append(&branches,
9665 branchname, NULL);
9666 if (error)
9667 goto done;
9668 nbranches++;
9670 } else if (nbranches == 0) {
9671 for (i = 0; i < remote->nsend_branches; i++) {
9672 error = got_pathlist_append(&branches,
9673 remote->send_branches[i], NULL);
9674 if (error)
9675 goto done;
9679 if (send_all_tags) {
9680 error = got_ref_list(&all_tags, repo, "refs/tags",
9681 got_ref_cmp_by_name, NULL);
9682 if (error)
9683 goto done;
9684 TAILQ_FOREACH(re, &all_tags, entry) {
9685 const char *tagname = got_ref_get_name(re->ref);
9686 error = got_pathlist_append(&tags,
9687 tagname, NULL);
9688 if (error)
9689 goto done;
9694 * To prevent accidents only branches in refs/heads/ can be deleted
9695 * with 'got send -d'.
9696 * Deleting anything else requires local repository access or Git.
9698 TAILQ_FOREACH(pe, &delete_args, entry) {
9699 const char *branchname = pe->path;
9700 char *s;
9701 struct got_pathlist_entry *new;
9702 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9703 s = strdup(branchname);
9704 if (s == NULL) {
9705 error = got_error_from_errno("strdup");
9706 goto done;
9708 } else {
9709 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9710 error = got_error_from_errno("asprintf");
9711 goto done;
9714 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9715 if (error || new == NULL /* duplicate */)
9716 free(s);
9717 if (error)
9718 goto done;
9719 ndelete_branches++;
9722 if (nbranches == 0 && ndelete_branches == 0) {
9723 struct got_reference *head_ref;
9724 if (worktree)
9725 error = got_ref_open(&head_ref, repo,
9726 got_worktree_get_head_ref_name(worktree), 0);
9727 else
9728 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9729 if (error)
9730 goto done;
9731 if (got_ref_is_symbolic(head_ref)) {
9732 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9733 got_ref_close(head_ref);
9734 if (error)
9735 goto done;
9736 } else
9737 ref = head_ref;
9738 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9739 NULL);
9740 if (error)
9741 goto done;
9742 nbranches++;
9745 if (verbosity >= 0) {
9746 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9747 remote->name, proto, host,
9748 port ? ":" : "", port ? port : "",
9749 *server_path == '/' ? "" : "/", server_path);
9752 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9753 server_path, verbosity);
9754 if (error)
9755 goto done;
9757 memset(&spa, 0, sizeof(spa));
9758 spa.last_scaled_packsize[0] = '\0';
9759 spa.last_p_deltify = -1;
9760 spa.last_p_written = -1;
9761 spa.verbosity = verbosity;
9762 spa.delete_branches = &delete_branches;
9763 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9764 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9765 check_cancelled, NULL);
9766 if (spa.printed_something)
9767 putchar('\n');
9768 if (error)
9769 goto done;
9770 if (!spa.sent_something && verbosity >= 0)
9771 printf("Already up-to-date\n");
9772 done:
9773 if (sendpid > 0) {
9774 if (kill(sendpid, SIGTERM) == -1)
9775 error = got_error_from_errno("kill");
9776 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9777 error = got_error_from_errno("waitpid");
9779 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9780 error = got_error_from_errno("close");
9781 if (repo) {
9782 const struct got_error *close_err = got_repo_close(repo);
9783 if (error == NULL)
9784 error = close_err;
9786 if (worktree)
9787 got_worktree_close(worktree);
9788 if (pack_fds) {
9789 const struct got_error *pack_err =
9790 got_repo_pack_fds_close(pack_fds);
9791 if (error == NULL)
9792 error = pack_err;
9794 if (ref)
9795 got_ref_close(ref);
9796 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9797 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9798 got_ref_list_free(&all_branches);
9799 got_ref_list_free(&all_tags);
9800 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9801 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9802 free(cwd);
9803 free(repo_path);
9804 free(proto);
9805 free(host);
9806 free(port);
9807 free(server_path);
9808 free(repo_name);
9809 return error;
9813 * Print and if delete is set delete all ref_prefix references.
9814 * If wanted_ref is not NULL, only print or delete this reference.
9816 static const struct got_error *
9817 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9818 const char *wanted_ref, int delete, struct got_worktree *worktree,
9819 struct got_repository *repo)
9821 const struct got_error *err;
9822 struct got_pathlist_head paths;
9823 struct got_reflist_head refs;
9824 struct got_reflist_entry *re;
9825 struct got_reflist_object_id_map *refs_idmap = NULL;
9826 struct got_commit_object *commit = NULL;
9827 struct got_object_id *id = NULL;
9828 const char *header_prefix;
9829 char *uuidstr = NULL;
9830 int found = 0;
9832 TAILQ_INIT(&refs);
9833 TAILQ_INIT(&paths);
9835 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9836 if (err)
9837 goto done;
9839 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9840 if (err)
9841 goto done;
9843 if (worktree != NULL) {
9844 err = got_worktree_get_uuid(&uuidstr, worktree);
9845 if (err)
9846 goto done;
9849 if (wanted_ref) {
9850 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9851 wanted_ref += 11;
9854 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9855 header_prefix = "backout";
9856 else
9857 header_prefix = "cherrypick";
9859 TAILQ_FOREACH(re, &refs, entry) {
9860 const char *refname, *wt;
9862 refname = got_ref_get_name(re->ref);
9864 err = check_cancelled(NULL);
9865 if (err)
9866 goto done;
9868 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9869 refname += prefix_len + 1; /* skip '-' delimiter */
9870 else
9871 continue;
9873 wt = refname;
9875 if (worktree == NULL || strncmp(refname, uuidstr,
9876 GOT_WORKTREE_UUID_STRLEN) == 0)
9877 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9878 else
9879 continue;
9881 err = got_repo_match_object_id(&id, NULL, refname,
9882 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9883 if (err)
9884 goto done;
9886 err = got_object_open_as_commit(&commit, repo, id);
9887 if (err)
9888 goto done;
9890 if (wanted_ref)
9891 found = strncmp(wanted_ref, refname,
9892 strlen(wanted_ref)) == 0;
9893 if (wanted_ref && !found) {
9894 struct got_reflist_head *ci_refs;
9896 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9897 id);
9899 if (ci_refs) {
9900 char *refs_str = NULL;
9901 char const *r = NULL;
9903 err = build_refs_str(&refs_str, ci_refs, id,
9904 repo, 1);
9905 if (err)
9906 goto done;
9908 r = refs_str;
9909 while (r) {
9910 if (strncmp(r, wanted_ref,
9911 strlen(wanted_ref)) == 0) {
9912 found = 1;
9913 break;
9915 r = strchr(r, ' ');
9916 if (r)
9917 ++r;
9919 free(refs_str);
9923 if (wanted_ref == NULL || found) {
9924 if (delete) {
9925 err = got_ref_delete(re->ref, repo);
9926 if (err)
9927 goto done;
9928 printf("Deleted: ");
9929 err = print_commit_oneline(commit, id, repo,
9930 refs_idmap);
9931 } else {
9933 * Print paths modified by commit to help
9934 * associate commits with worktree changes.
9936 err = get_changed_paths(&paths, commit,
9937 repo, NULL);
9938 if (err)
9939 goto done;
9941 err = print_commit(commit, id, repo, NULL,
9942 &paths, NULL, 0, 0, refs_idmap, NULL,
9943 header_prefix);
9944 got_pathlist_free(&paths,
9945 GOT_PATHLIST_FREE_ALL);
9947 if (worktree == NULL)
9948 printf("work tree: %.*s\n\n",
9949 GOT_WORKTREE_UUID_STRLEN, wt);
9951 if (err || found)
9952 goto done;
9955 got_object_commit_close(commit);
9956 commit = NULL;
9957 free(id);
9958 id = NULL;
9961 if (wanted_ref != NULL && !found)
9962 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9964 done:
9965 free(id);
9966 free(uuidstr);
9967 got_ref_list_free(&refs);
9968 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9969 if (refs_idmap)
9970 got_reflist_object_id_map_free(refs_idmap);
9971 if (commit)
9972 got_object_commit_close(commit);
9973 return err;
9977 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9978 * identified by id for log messages to prepopulate the editor on commit.
9980 static const struct got_error *
9981 logmsg_ref(struct got_object_id *id, const char *prefix,
9982 struct got_worktree *worktree, struct got_repository *repo)
9984 const struct got_error *err = NULL;
9985 char *idstr, *ref = NULL, *refname = NULL;
9986 int histedit_in_progress;
9987 int rebase_in_progress, merge_in_progress;
9990 * Silenty refuse to create merge reference if any histedit, merge,
9991 * or rebase operation is in progress.
9993 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9994 worktree);
9995 if (err)
9996 return err;
9997 if (histedit_in_progress)
9998 return NULL;
10000 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10001 if (err)
10002 return err;
10003 if (rebase_in_progress)
10004 return NULL;
10006 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10007 repo);
10008 if (err)
10009 return err;
10010 if (merge_in_progress)
10011 return NULL;
10013 err = got_object_id_str(&idstr, id);
10014 if (err)
10015 return err;
10017 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10018 if (err)
10019 goto done;
10021 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10022 err = got_error_from_errno("asprintf");
10023 goto done;
10026 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10027 -1, repo);
10028 done:
10029 free(ref);
10030 free(idstr);
10031 free(refname);
10032 return err;
10035 __dead static void
10036 usage_cherrypick(void)
10038 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10039 getprogname());
10040 exit(1);
10043 static const struct got_error *
10044 cmd_cherrypick(int argc, char *argv[])
10046 const struct got_error *error = NULL;
10047 struct got_worktree *worktree = NULL;
10048 struct got_repository *repo = NULL;
10049 char *cwd = NULL, *commit_id_str = NULL;
10050 struct got_object_id *commit_id = NULL;
10051 struct got_commit_object *commit = NULL;
10052 struct got_object_qid *pid;
10053 int ch, list_refs = 0, remove_refs = 0;
10054 struct got_update_progress_arg upa;
10055 int *pack_fds = NULL;
10057 while ((ch = getopt(argc, argv, "lX")) != -1) {
10058 switch (ch) {
10059 case 'l':
10060 list_refs = 1;
10061 break;
10062 case 'X':
10063 remove_refs = 1;
10064 break;
10065 default:
10066 usage_cherrypick();
10067 /* NOTREACHED */
10071 argc -= optind;
10072 argv += optind;
10074 #ifndef PROFILE
10075 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10076 "unveil", NULL) == -1)
10077 err(1, "pledge");
10078 #endif
10079 if (list_refs || remove_refs) {
10080 if (argc != 0 && argc != 1)
10081 usage_cherrypick();
10082 } else if (argc != 1)
10083 usage_cherrypick();
10084 if (list_refs && remove_refs)
10085 option_conflict('l', 'X');
10087 cwd = getcwd(NULL, 0);
10088 if (cwd == NULL) {
10089 error = got_error_from_errno("getcwd");
10090 goto done;
10093 error = got_repo_pack_fds_open(&pack_fds);
10094 if (error != NULL)
10095 goto done;
10097 error = got_worktree_open(&worktree, cwd);
10098 if (error) {
10099 if (list_refs || remove_refs) {
10100 if (error->code != GOT_ERR_NOT_WORKTREE)
10101 goto done;
10102 } else {
10103 if (error->code == GOT_ERR_NOT_WORKTREE)
10104 error = wrap_not_worktree_error(error,
10105 "cherrypick", cwd);
10106 goto done;
10110 error = got_repo_open(&repo,
10111 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10112 NULL, pack_fds);
10113 if (error != NULL)
10114 goto done;
10116 error = apply_unveil(got_repo_get_path(repo), 0,
10117 worktree ? got_worktree_get_root_path(worktree) : NULL);
10118 if (error)
10119 goto done;
10121 if (list_refs || remove_refs) {
10122 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10123 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10124 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10125 goto done;
10128 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10129 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10130 if (error)
10131 goto done;
10132 error = got_object_id_str(&commit_id_str, commit_id);
10133 if (error)
10134 goto done;
10136 error = got_object_open_as_commit(&commit, repo, commit_id);
10137 if (error)
10138 goto done;
10139 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10140 memset(&upa, 0, sizeof(upa));
10141 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10142 commit_id, repo, update_progress, &upa, check_cancelled,
10143 NULL);
10144 if (error != NULL)
10145 goto done;
10147 if (upa.did_something) {
10148 error = logmsg_ref(commit_id,
10149 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10150 if (error)
10151 goto done;
10152 printf("Merged commit %s\n", commit_id_str);
10154 print_merge_progress_stats(&upa);
10155 done:
10156 free(cwd);
10157 if (commit)
10158 got_object_commit_close(commit);
10159 free(commit_id_str);
10160 if (worktree)
10161 got_worktree_close(worktree);
10162 if (repo) {
10163 const struct got_error *close_err = got_repo_close(repo);
10164 if (error == NULL)
10165 error = close_err;
10167 if (pack_fds) {
10168 const struct got_error *pack_err =
10169 got_repo_pack_fds_close(pack_fds);
10170 if (error == NULL)
10171 error = pack_err;
10174 return error;
10177 __dead static void
10178 usage_backout(void)
10180 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10181 exit(1);
10184 static const struct got_error *
10185 cmd_backout(int argc, char *argv[])
10187 const struct got_error *error = NULL;
10188 struct got_worktree *worktree = NULL;
10189 struct got_repository *repo = NULL;
10190 char *cwd = NULL, *commit_id_str = NULL;
10191 struct got_object_id *commit_id = NULL;
10192 struct got_commit_object *commit = NULL;
10193 struct got_object_qid *pid;
10194 int ch, list_refs = 0, remove_refs = 0;
10195 struct got_update_progress_arg upa;
10196 int *pack_fds = NULL;
10198 while ((ch = getopt(argc, argv, "lX")) != -1) {
10199 switch (ch) {
10200 case 'l':
10201 list_refs = 1;
10202 break;
10203 case 'X':
10204 remove_refs = 1;
10205 break;
10206 default:
10207 usage_backout();
10208 /* NOTREACHED */
10212 argc -= optind;
10213 argv += optind;
10215 #ifndef PROFILE
10216 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10217 "unveil", NULL) == -1)
10218 err(1, "pledge");
10219 #endif
10220 if (list_refs || remove_refs) {
10221 if (argc != 0 && argc != 1)
10222 usage_backout();
10223 } else if (argc != 1)
10224 usage_backout();
10225 if (list_refs && remove_refs)
10226 option_conflict('l', 'X');
10228 cwd = getcwd(NULL, 0);
10229 if (cwd == NULL) {
10230 error = got_error_from_errno("getcwd");
10231 goto done;
10234 error = got_repo_pack_fds_open(&pack_fds);
10235 if (error != NULL)
10236 goto done;
10238 error = got_worktree_open(&worktree, cwd);
10239 if (error) {
10240 if (list_refs || remove_refs) {
10241 if (error->code != GOT_ERR_NOT_WORKTREE)
10242 goto done;
10243 } else {
10244 if (error->code == GOT_ERR_NOT_WORKTREE)
10245 error = wrap_not_worktree_error(error,
10246 "backout", cwd);
10247 goto done;
10251 error = got_repo_open(&repo,
10252 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10253 NULL, pack_fds);
10254 if (error != NULL)
10255 goto done;
10257 error = apply_unveil(got_repo_get_path(repo), 0,
10258 worktree ? got_worktree_get_root_path(worktree) : NULL);
10259 if (error)
10260 goto done;
10262 if (list_refs || remove_refs) {
10263 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10264 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10265 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10266 goto done;
10269 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10270 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10271 if (error)
10272 goto done;
10273 error = got_object_id_str(&commit_id_str, commit_id);
10274 if (error)
10275 goto done;
10277 error = got_object_open_as_commit(&commit, repo, commit_id);
10278 if (error)
10279 goto done;
10280 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10281 if (pid == NULL) {
10282 error = got_error(GOT_ERR_ROOT_COMMIT);
10283 goto done;
10286 memset(&upa, 0, sizeof(upa));
10287 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10288 repo, update_progress, &upa, check_cancelled, NULL);
10289 if (error != NULL)
10290 goto done;
10292 if (upa.did_something) {
10293 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10294 worktree, repo);
10295 if (error)
10296 goto done;
10297 printf("Backed out commit %s\n", commit_id_str);
10299 print_merge_progress_stats(&upa);
10300 done:
10301 free(cwd);
10302 if (commit)
10303 got_object_commit_close(commit);
10304 free(commit_id_str);
10305 if (worktree)
10306 got_worktree_close(worktree);
10307 if (repo) {
10308 const struct got_error *close_err = got_repo_close(repo);
10309 if (error == NULL)
10310 error = close_err;
10312 if (pack_fds) {
10313 const struct got_error *pack_err =
10314 got_repo_pack_fds_close(pack_fds);
10315 if (error == NULL)
10316 error = pack_err;
10318 return error;
10321 __dead static void
10322 usage_rebase(void)
10324 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10325 exit(1);
10328 static void
10329 trim_logmsg(char *logmsg, int limit)
10331 char *nl;
10332 size_t len;
10334 len = strlen(logmsg);
10335 if (len > limit)
10336 len = limit;
10337 logmsg[len] = '\0';
10338 nl = strchr(logmsg, '\n');
10339 if (nl)
10340 *nl = '\0';
10343 static const struct got_error *
10344 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10346 const struct got_error *err;
10347 char *logmsg0 = NULL;
10348 const char *s;
10350 err = got_object_commit_get_logmsg(&logmsg0, commit);
10351 if (err)
10352 return err;
10354 s = logmsg0;
10355 while (isspace((unsigned char)s[0]))
10356 s++;
10358 *logmsg = strdup(s);
10359 if (*logmsg == NULL) {
10360 err = got_error_from_errno("strdup");
10361 goto done;
10364 trim_logmsg(*logmsg, limit);
10365 done:
10366 free(logmsg0);
10367 return err;
10370 static const struct got_error *
10371 show_rebase_merge_conflict(struct got_object_id *id,
10372 struct got_repository *repo)
10374 const struct got_error *err;
10375 struct got_commit_object *commit = NULL;
10376 char *id_str = NULL, *logmsg = NULL;
10378 err = got_object_open_as_commit(&commit, repo, id);
10379 if (err)
10380 return err;
10382 err = got_object_id_str(&id_str, id);
10383 if (err)
10384 goto done;
10386 id_str[12] = '\0';
10388 err = get_short_logmsg(&logmsg, 42, commit);
10389 if (err)
10390 goto done;
10392 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10393 done:
10394 free(id_str);
10395 got_object_commit_close(commit);
10396 free(logmsg);
10397 return err;
10400 static const struct got_error *
10401 show_rebase_progress(struct got_commit_object *commit,
10402 struct got_object_id *old_id, struct got_object_id *new_id)
10404 const struct got_error *err;
10405 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10407 err = got_object_id_str(&old_id_str, old_id);
10408 if (err)
10409 goto done;
10411 if (new_id) {
10412 err = got_object_id_str(&new_id_str, new_id);
10413 if (err)
10414 goto done;
10417 old_id_str[12] = '\0';
10418 if (new_id_str)
10419 new_id_str[12] = '\0';
10421 err = get_short_logmsg(&logmsg, 42, commit);
10422 if (err)
10423 goto done;
10425 printf("%s -> %s: %s\n", old_id_str,
10426 new_id_str ? new_id_str : "no-op change", logmsg);
10427 done:
10428 free(old_id_str);
10429 free(new_id_str);
10430 free(logmsg);
10431 return err;
10434 static const struct got_error *
10435 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10436 struct got_reference *branch, struct got_reference *tmp_branch,
10437 struct got_repository *repo, int create_backup)
10439 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10440 return got_worktree_rebase_complete(worktree, fileindex,
10441 tmp_branch, branch, repo, create_backup);
10444 static const struct got_error *
10445 rebase_commit(struct got_pathlist_head *merged_paths,
10446 struct got_worktree *worktree, struct got_fileindex *fileindex,
10447 struct got_reference *tmp_branch, const char *committer,
10448 struct got_object_id *commit_id, struct got_repository *repo)
10450 const struct got_error *error;
10451 struct got_commit_object *commit;
10452 struct got_object_id *new_commit_id;
10454 error = got_object_open_as_commit(&commit, repo, commit_id);
10455 if (error)
10456 return error;
10458 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10459 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10460 repo);
10461 if (error) {
10462 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10463 goto done;
10464 error = show_rebase_progress(commit, commit_id, NULL);
10465 } else {
10466 error = show_rebase_progress(commit, commit_id, new_commit_id);
10467 free(new_commit_id);
10469 done:
10470 got_object_commit_close(commit);
10471 return error;
10474 struct check_path_prefix_arg {
10475 const char *path_prefix;
10476 size_t len;
10477 int errcode;
10480 static const struct got_error *
10481 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10482 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10483 struct got_object_id *id1, struct got_object_id *id2,
10484 const char *path1, const char *path2,
10485 mode_t mode1, mode_t mode2, struct got_repository *repo)
10487 struct check_path_prefix_arg *a = arg;
10489 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10490 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10491 return got_error(a->errcode);
10493 return NULL;
10496 static const struct got_error *
10497 check_path_prefix(struct got_object_id *parent_id,
10498 struct got_object_id *commit_id, const char *path_prefix,
10499 int errcode, struct got_repository *repo)
10501 const struct got_error *err;
10502 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10503 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10504 struct check_path_prefix_arg cpp_arg;
10506 if (got_path_is_root_dir(path_prefix))
10507 return NULL;
10509 err = got_object_open_as_commit(&commit, repo, commit_id);
10510 if (err)
10511 goto done;
10513 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10514 if (err)
10515 goto done;
10517 err = got_object_open_as_tree(&tree1, repo,
10518 got_object_commit_get_tree_id(parent_commit));
10519 if (err)
10520 goto done;
10522 err = got_object_open_as_tree(&tree2, repo,
10523 got_object_commit_get_tree_id(commit));
10524 if (err)
10525 goto done;
10527 cpp_arg.path_prefix = path_prefix;
10528 while (cpp_arg.path_prefix[0] == '/')
10529 cpp_arg.path_prefix++;
10530 cpp_arg.len = strlen(cpp_arg.path_prefix);
10531 cpp_arg.errcode = errcode;
10532 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10533 check_path_prefix_in_diff, &cpp_arg, 0);
10534 done:
10535 if (tree1)
10536 got_object_tree_close(tree1);
10537 if (tree2)
10538 got_object_tree_close(tree2);
10539 if (commit)
10540 got_object_commit_close(commit);
10541 if (parent_commit)
10542 got_object_commit_close(parent_commit);
10543 return err;
10546 static const struct got_error *
10547 collect_commits(struct got_object_id_queue *commits,
10548 struct got_object_id *initial_commit_id,
10549 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10550 const char *path_prefix, int path_prefix_errcode,
10551 struct got_repository *repo)
10553 const struct got_error *err = NULL;
10554 struct got_commit_graph *graph = NULL;
10555 struct got_object_id parent_id, commit_id;
10556 struct got_object_qid *qid;
10558 err = got_commit_graph_open(&graph, "/", 1);
10559 if (err)
10560 return err;
10562 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10563 check_cancelled, NULL);
10564 if (err)
10565 goto done;
10567 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10568 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10569 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10570 check_cancelled, NULL);
10571 if (err) {
10572 if (err->code == GOT_ERR_ITER_COMPLETED) {
10573 err = got_error_msg(GOT_ERR_ANCESTRY,
10574 "ran out of commits to rebase before "
10575 "youngest common ancestor commit has "
10576 "been reached?!?");
10578 goto done;
10579 } else {
10580 err = check_path_prefix(&parent_id, &commit_id,
10581 path_prefix, path_prefix_errcode, repo);
10582 if (err)
10583 goto done;
10585 err = got_object_qid_alloc(&qid, &commit_id);
10586 if (err)
10587 goto done;
10588 STAILQ_INSERT_HEAD(commits, qid, entry);
10590 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10593 done:
10594 got_commit_graph_close(graph);
10595 return err;
10598 static const struct got_error *
10599 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10601 const struct got_error *err = NULL;
10602 time_t committer_time;
10603 struct tm tm;
10604 char datebuf[11]; /* YYYY-MM-DD + NUL */
10605 char *author0 = NULL, *author, *smallerthan;
10606 char *logmsg0 = NULL, *logmsg, *newline;
10608 committer_time = got_object_commit_get_committer_time(commit);
10609 if (gmtime_r(&committer_time, &tm) == NULL)
10610 return got_error_from_errno("gmtime_r");
10611 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10612 return got_error(GOT_ERR_NO_SPACE);
10614 author0 = strdup(got_object_commit_get_author(commit));
10615 if (author0 == NULL)
10616 return got_error_from_errno("strdup");
10617 author = author0;
10618 smallerthan = strchr(author, '<');
10619 if (smallerthan && smallerthan[1] != '\0')
10620 author = smallerthan + 1;
10621 author[strcspn(author, "@>")] = '\0';
10623 err = got_object_commit_get_logmsg(&logmsg0, commit);
10624 if (err)
10625 goto done;
10626 logmsg = logmsg0;
10627 while (*logmsg == '\n')
10628 logmsg++;
10629 newline = strchr(logmsg, '\n');
10630 if (newline)
10631 *newline = '\0';
10633 if (asprintf(brief_str, "%s %s %s",
10634 datebuf, author, logmsg) == -1)
10635 err = got_error_from_errno("asprintf");
10636 done:
10637 free(author0);
10638 free(logmsg0);
10639 return err;
10642 static const struct got_error *
10643 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10644 struct got_repository *repo)
10646 const struct got_error *err;
10647 char *id_str;
10649 err = got_object_id_str(&id_str, id);
10650 if (err)
10651 return err;
10653 err = got_ref_delete(ref, repo);
10654 if (err)
10655 goto done;
10657 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10658 done:
10659 free(id_str);
10660 return err;
10663 static const struct got_error *
10664 print_backup_ref(const char *branch_name, const char *new_id_str,
10665 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10666 struct got_reflist_object_id_map *refs_idmap,
10667 struct got_repository *repo)
10669 const struct got_error *err = NULL;
10670 struct got_reflist_head *refs;
10671 char *refs_str = NULL;
10672 struct got_object_id *new_commit_id = NULL;
10673 struct got_commit_object *new_commit = NULL;
10674 char *new_commit_brief_str = NULL;
10675 struct got_object_id *yca_id = NULL;
10676 struct got_commit_object *yca_commit = NULL;
10677 char *yca_id_str = NULL, *yca_brief_str = NULL;
10678 char *custom_refs_str;
10680 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10681 return got_error_from_errno("asprintf");
10683 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10684 0, 0, refs_idmap, custom_refs_str, NULL);
10685 if (err)
10686 goto done;
10688 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10689 if (err)
10690 goto done;
10692 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10693 if (refs) {
10694 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10695 if (err)
10696 goto done;
10699 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10700 if (err)
10701 goto done;
10703 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10704 if (err)
10705 goto done;
10707 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10708 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10709 if (err)
10710 goto done;
10712 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10713 refs_str ? " (" : "", refs_str ? refs_str : "",
10714 refs_str ? ")" : "", new_commit_brief_str);
10715 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10716 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10717 free(refs_str);
10718 refs_str = NULL;
10720 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10721 if (err)
10722 goto done;
10724 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10725 if (err)
10726 goto done;
10728 err = got_object_id_str(&yca_id_str, yca_id);
10729 if (err)
10730 goto done;
10732 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10733 if (refs) {
10734 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10735 if (err)
10736 goto done;
10738 printf("history forked at %s%s%s%s\n %s\n",
10739 yca_id_str,
10740 refs_str ? " (" : "", refs_str ? refs_str : "",
10741 refs_str ? ")" : "", yca_brief_str);
10743 done:
10744 free(custom_refs_str);
10745 free(new_commit_id);
10746 free(refs_str);
10747 free(yca_id);
10748 free(yca_id_str);
10749 free(yca_brief_str);
10750 if (new_commit)
10751 got_object_commit_close(new_commit);
10752 if (yca_commit)
10753 got_object_commit_close(yca_commit);
10755 return err;
10758 static const struct got_error *
10759 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10760 struct got_repository *repo)
10762 const struct got_error *err;
10763 struct got_reflist_head refs;
10764 struct got_reflist_entry *re;
10765 char *uuidstr = NULL;
10766 static char msg[160];
10768 TAILQ_INIT(&refs);
10770 err = got_worktree_get_uuid(&uuidstr, worktree);
10771 if (err)
10772 goto done;
10774 err = got_ref_list(&refs, repo, "refs/got/worktree",
10775 got_ref_cmp_by_name, repo);
10776 if (err)
10777 goto done;
10779 TAILQ_FOREACH(re, &refs, entry) {
10780 const char *cmd, *refname, *type;
10782 refname = got_ref_get_name(re->ref);
10784 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10785 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10786 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10787 cmd = "cherrypick";
10788 type = "cherrypicked";
10789 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10790 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10791 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10792 cmd = "backout";
10793 type = "backed-out";
10794 } else
10795 continue;
10797 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10798 continue;
10800 snprintf(msg, sizeof(msg),
10801 "work tree has references created by %s commits which "
10802 "must be removed with 'got %s -X' before running the %s "
10803 "command", type, cmd, caller);
10804 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10805 goto done;
10808 done:
10809 free(uuidstr);
10810 got_ref_list_free(&refs);
10811 return err;
10814 static const struct got_error *
10815 process_backup_refs(const char *backup_ref_prefix,
10816 const char *wanted_branch_name,
10817 int delete, struct got_repository *repo)
10819 const struct got_error *err;
10820 struct got_reflist_head refs, backup_refs;
10821 struct got_reflist_entry *re;
10822 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10823 struct got_object_id *old_commit_id = NULL;
10824 char *branch_name = NULL;
10825 struct got_commit_object *old_commit = NULL;
10826 struct got_reflist_object_id_map *refs_idmap = NULL;
10827 int wanted_branch_found = 0;
10829 TAILQ_INIT(&refs);
10830 TAILQ_INIT(&backup_refs);
10832 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10833 if (err)
10834 return err;
10836 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10837 if (err)
10838 goto done;
10840 if (wanted_branch_name) {
10841 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10842 wanted_branch_name += 11;
10845 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10846 got_ref_cmp_by_commit_timestamp_descending, repo);
10847 if (err)
10848 goto done;
10850 TAILQ_FOREACH(re, &backup_refs, entry) {
10851 const char *refname = got_ref_get_name(re->ref);
10852 char *slash;
10854 err = check_cancelled(NULL);
10855 if (err)
10856 break;
10858 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10859 if (err)
10860 break;
10862 err = got_object_open_as_commit(&old_commit, repo,
10863 old_commit_id);
10864 if (err)
10865 break;
10867 if (strncmp(backup_ref_prefix, refname,
10868 backup_ref_prefix_len) == 0)
10869 refname += backup_ref_prefix_len;
10871 while (refname[0] == '/')
10872 refname++;
10874 branch_name = strdup(refname);
10875 if (branch_name == NULL) {
10876 err = got_error_from_errno("strdup");
10877 break;
10879 slash = strrchr(branch_name, '/');
10880 if (slash) {
10881 *slash = '\0';
10882 refname += strlen(branch_name) + 1;
10885 if (wanted_branch_name == NULL ||
10886 strcmp(wanted_branch_name, branch_name) == 0) {
10887 wanted_branch_found = 1;
10888 if (delete) {
10889 err = delete_backup_ref(re->ref,
10890 old_commit_id, repo);
10891 } else {
10892 err = print_backup_ref(branch_name, refname,
10893 old_commit_id, old_commit, refs_idmap,
10894 repo);
10896 if (err)
10897 break;
10900 free(old_commit_id);
10901 old_commit_id = NULL;
10902 free(branch_name);
10903 branch_name = NULL;
10904 got_object_commit_close(old_commit);
10905 old_commit = NULL;
10908 if (wanted_branch_name && !wanted_branch_found) {
10909 err = got_error_fmt(GOT_ERR_NOT_REF,
10910 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10912 done:
10913 if (refs_idmap)
10914 got_reflist_object_id_map_free(refs_idmap);
10915 got_ref_list_free(&refs);
10916 got_ref_list_free(&backup_refs);
10917 free(old_commit_id);
10918 free(branch_name);
10919 if (old_commit)
10920 got_object_commit_close(old_commit);
10921 return err;
10924 static const struct got_error *
10925 abort_progress(void *arg, unsigned char status, const char *path)
10928 * Unversioned files should not clutter progress output when
10929 * an operation is aborted.
10931 if (status == GOT_STATUS_UNVERSIONED)
10932 return NULL;
10934 return update_progress(arg, status, path);
10937 static const struct got_error *
10938 cmd_rebase(int argc, char *argv[])
10940 const struct got_error *error = NULL;
10941 struct got_worktree *worktree = NULL;
10942 struct got_repository *repo = NULL;
10943 struct got_fileindex *fileindex = NULL;
10944 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10945 struct got_reference *branch = NULL;
10946 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10947 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10948 struct got_object_id *resume_commit_id = NULL;
10949 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10950 struct got_object_id *head_commit_id = NULL;
10951 struct got_reference *head_ref = NULL;
10952 struct got_commit_object *commit = NULL;
10953 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10954 int histedit_in_progress = 0, merge_in_progress = 0;
10955 int create_backup = 1, list_backups = 0, delete_backups = 0;
10956 struct got_object_id_queue commits;
10957 struct got_pathlist_head merged_paths;
10958 const struct got_object_id_queue *parent_ids;
10959 struct got_object_qid *qid, *pid;
10960 struct got_update_progress_arg upa;
10961 int *pack_fds = NULL;
10963 STAILQ_INIT(&commits);
10964 TAILQ_INIT(&merged_paths);
10965 memset(&upa, 0, sizeof(upa));
10967 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10968 switch (ch) {
10969 case 'a':
10970 abort_rebase = 1;
10971 break;
10972 case 'c':
10973 continue_rebase = 1;
10974 break;
10975 case 'l':
10976 list_backups = 1;
10977 break;
10978 case 'X':
10979 delete_backups = 1;
10980 break;
10981 default:
10982 usage_rebase();
10983 /* NOTREACHED */
10987 argc -= optind;
10988 argv += optind;
10990 #ifndef PROFILE
10991 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10992 "unveil", NULL) == -1)
10993 err(1, "pledge");
10994 #endif
10995 if (list_backups) {
10996 if (abort_rebase)
10997 option_conflict('l', 'a');
10998 if (continue_rebase)
10999 option_conflict('l', 'c');
11000 if (delete_backups)
11001 option_conflict('l', 'X');
11002 if (argc != 0 && argc != 1)
11003 usage_rebase();
11004 } else if (delete_backups) {
11005 if (abort_rebase)
11006 option_conflict('X', 'a');
11007 if (continue_rebase)
11008 option_conflict('X', 'c');
11009 if (list_backups)
11010 option_conflict('l', 'X');
11011 if (argc != 0 && argc != 1)
11012 usage_rebase();
11013 } else {
11014 if (abort_rebase && continue_rebase)
11015 usage_rebase();
11016 else if (abort_rebase || continue_rebase) {
11017 if (argc != 0)
11018 usage_rebase();
11019 } else if (argc != 1)
11020 usage_rebase();
11023 cwd = getcwd(NULL, 0);
11024 if (cwd == NULL) {
11025 error = got_error_from_errno("getcwd");
11026 goto done;
11029 error = got_repo_pack_fds_open(&pack_fds);
11030 if (error != NULL)
11031 goto done;
11033 error = got_worktree_open(&worktree, cwd);
11034 if (error) {
11035 if (list_backups || delete_backups) {
11036 if (error->code != GOT_ERR_NOT_WORKTREE)
11037 goto done;
11038 } else {
11039 if (error->code == GOT_ERR_NOT_WORKTREE)
11040 error = wrap_not_worktree_error(error,
11041 "rebase", cwd);
11042 goto done;
11046 error = get_gitconfig_path(&gitconfig_path);
11047 if (error)
11048 goto done;
11049 error = got_repo_open(&repo,
11050 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11051 gitconfig_path, pack_fds);
11052 if (error != NULL)
11053 goto done;
11055 if (worktree != NULL && !list_backups && !delete_backups) {
11056 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11057 if (error)
11058 goto done;
11061 error = get_author(&committer, repo, worktree);
11062 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11063 goto done;
11065 error = apply_unveil(got_repo_get_path(repo), 0,
11066 worktree ? got_worktree_get_root_path(worktree) : NULL);
11067 if (error)
11068 goto done;
11070 if (list_backups || delete_backups) {
11071 error = process_backup_refs(
11072 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11073 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11074 goto done; /* nothing else to do */
11077 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11078 worktree);
11079 if (error)
11080 goto done;
11081 if (histedit_in_progress) {
11082 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11083 goto done;
11086 error = got_worktree_merge_in_progress(&merge_in_progress,
11087 worktree, repo);
11088 if (error)
11089 goto done;
11090 if (merge_in_progress) {
11091 error = got_error(GOT_ERR_MERGE_BUSY);
11092 goto done;
11095 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11096 if (error)
11097 goto done;
11099 if (abort_rebase) {
11100 if (!rebase_in_progress) {
11101 error = got_error(GOT_ERR_NOT_REBASING);
11102 goto done;
11104 error = got_worktree_rebase_continue(&resume_commit_id,
11105 &new_base_branch, &tmp_branch, &branch, &fileindex,
11106 worktree, repo);
11107 if (error)
11108 goto done;
11109 printf("Switching work tree to %s\n",
11110 got_ref_get_symref_target(new_base_branch));
11111 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11112 new_base_branch, abort_progress, &upa);
11113 if (error)
11114 goto done;
11115 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11116 print_merge_progress_stats(&upa);
11117 goto done; /* nothing else to do */
11120 if (continue_rebase) {
11121 if (!rebase_in_progress) {
11122 error = got_error(GOT_ERR_NOT_REBASING);
11123 goto done;
11125 error = got_worktree_rebase_continue(&resume_commit_id,
11126 &new_base_branch, &tmp_branch, &branch, &fileindex,
11127 worktree, repo);
11128 if (error)
11129 goto done;
11131 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11132 committer, resume_commit_id, repo);
11133 if (error)
11134 goto done;
11136 yca_id = got_object_id_dup(resume_commit_id);
11137 if (yca_id == NULL) {
11138 error = got_error_from_errno("got_object_id_dup");
11139 goto done;
11141 } else {
11142 error = got_ref_open(&branch, repo, argv[0], 0);
11143 if (error != NULL)
11144 goto done;
11145 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11146 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11147 "will not rebase a branch which lives outside "
11148 "the \"refs/heads/\" reference namespace");
11149 goto done;
11153 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11154 if (error)
11155 goto done;
11157 if (!continue_rebase) {
11158 struct got_object_id *base_commit_id;
11160 error = got_ref_open(&head_ref, repo,
11161 got_worktree_get_head_ref_name(worktree), 0);
11162 if (error)
11163 goto done;
11164 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11165 if (error)
11166 goto done;
11167 base_commit_id = got_worktree_get_base_commit_id(worktree);
11168 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11169 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11170 goto done;
11173 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11174 base_commit_id, branch_head_commit_id, 1, repo,
11175 check_cancelled, NULL);
11176 if (error) {
11177 if (error->code == GOT_ERR_ANCESTRY) {
11178 error = got_error_msg(GOT_ERR_ANCESTRY,
11179 "specified branch shares no common "
11180 "ancestry with work tree's branch");
11182 goto done;
11185 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11186 if (error) {
11187 if (error->code != GOT_ERR_ANCESTRY)
11188 goto done;
11189 error = NULL;
11190 } else {
11191 struct got_pathlist_head paths;
11192 printf("%s is already based on %s\n",
11193 got_ref_get_name(branch),
11194 got_worktree_get_head_ref_name(worktree));
11195 error = switch_head_ref(branch, branch_head_commit_id,
11196 worktree, repo);
11197 if (error)
11198 goto done;
11199 error = got_worktree_set_base_commit_id(worktree, repo,
11200 branch_head_commit_id);
11201 if (error)
11202 goto done;
11203 TAILQ_INIT(&paths);
11204 error = got_pathlist_append(&paths, "", NULL);
11205 if (error)
11206 goto done;
11207 error = got_worktree_checkout_files(worktree,
11208 &paths, repo, update_progress, &upa,
11209 check_cancelled, NULL);
11210 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11211 if (error)
11212 goto done;
11213 if (upa.did_something) {
11214 char *id_str;
11215 error = got_object_id_str(&id_str,
11216 branch_head_commit_id);
11217 if (error)
11218 goto done;
11219 printf("Updated to %s: %s\n",
11220 got_worktree_get_head_ref_name(worktree),
11221 id_str);
11222 free(id_str);
11223 } else
11224 printf("Already up-to-date\n");
11225 print_update_progress_stats(&upa);
11226 goto done;
11230 commit_id = branch_head_commit_id;
11231 error = got_object_open_as_commit(&commit, repo, commit_id);
11232 if (error)
11233 goto done;
11235 parent_ids = got_object_commit_get_parent_ids(commit);
11236 pid = STAILQ_FIRST(parent_ids);
11237 if (pid) {
11238 error = collect_commits(&commits, commit_id, &pid->id,
11239 yca_id, got_worktree_get_path_prefix(worktree),
11240 GOT_ERR_REBASE_PATH, repo);
11241 if (error)
11242 goto done;
11245 got_object_commit_close(commit);
11246 commit = NULL;
11248 if (!continue_rebase) {
11249 error = got_worktree_rebase_prepare(&new_base_branch,
11250 &tmp_branch, &fileindex, worktree, branch, repo);
11251 if (error)
11252 goto done;
11255 if (STAILQ_EMPTY(&commits)) {
11256 if (continue_rebase) {
11257 error = rebase_complete(worktree, fileindex,
11258 branch, tmp_branch, repo, create_backup);
11259 goto done;
11260 } else {
11261 /* Fast-forward the reference of the branch. */
11262 struct got_object_id *new_head_commit_id;
11263 char *id_str;
11264 error = got_ref_resolve(&new_head_commit_id, repo,
11265 new_base_branch);
11266 if (error)
11267 goto done;
11268 error = got_object_id_str(&id_str, new_head_commit_id);
11269 if (error)
11270 goto done;
11271 printf("Forwarding %s to commit %s\n",
11272 got_ref_get_name(branch), id_str);
11273 free(id_str);
11274 error = got_ref_change_ref(branch,
11275 new_head_commit_id);
11276 if (error)
11277 goto done;
11278 /* No backup needed since objects did not change. */
11279 create_backup = 0;
11283 pid = NULL;
11284 STAILQ_FOREACH(qid, &commits, entry) {
11286 commit_id = &qid->id;
11287 parent_id = pid ? &pid->id : yca_id;
11288 pid = qid;
11290 memset(&upa, 0, sizeof(upa));
11291 error = got_worktree_rebase_merge_files(&merged_paths,
11292 worktree, fileindex, parent_id, commit_id, repo,
11293 update_progress, &upa, check_cancelled, NULL);
11294 if (error)
11295 goto done;
11297 print_merge_progress_stats(&upa);
11298 if (upa.conflicts > 0 || upa.missing > 0 ||
11299 upa.not_deleted > 0 || upa.unversioned > 0) {
11300 if (upa.conflicts > 0) {
11301 error = show_rebase_merge_conflict(&qid->id,
11302 repo);
11303 if (error)
11304 goto done;
11306 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11307 break;
11310 error = rebase_commit(&merged_paths, worktree, fileindex,
11311 tmp_branch, committer, commit_id, repo);
11312 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11313 if (error)
11314 goto done;
11317 if (upa.conflicts > 0 || upa.missing > 0 ||
11318 upa.not_deleted > 0 || upa.unversioned > 0) {
11319 error = got_worktree_rebase_postpone(worktree, fileindex);
11320 if (error)
11321 goto done;
11322 if (upa.conflicts > 0 && upa.missing == 0 &&
11323 upa.not_deleted == 0 && upa.unversioned == 0) {
11324 error = got_error_msg(GOT_ERR_CONFLICTS,
11325 "conflicts must be resolved before rebasing "
11326 "can continue");
11327 } else if (upa.conflicts > 0) {
11328 error = got_error_msg(GOT_ERR_CONFLICTS,
11329 "conflicts must be resolved before rebasing "
11330 "can continue; changes destined for some "
11331 "files were not yet merged and should be "
11332 "merged manually if required before the "
11333 "rebase operation is continued");
11334 } else {
11335 error = got_error_msg(GOT_ERR_CONFLICTS,
11336 "changes destined for some files were not "
11337 "yet merged and should be merged manually "
11338 "if required before the rebase operation "
11339 "is continued");
11341 } else
11342 error = rebase_complete(worktree, fileindex, branch,
11343 tmp_branch, repo, create_backup);
11344 done:
11345 free(cwd);
11346 free(committer);
11347 free(gitconfig_path);
11348 got_object_id_queue_free(&commits);
11349 free(branch_head_commit_id);
11350 free(resume_commit_id);
11351 free(head_commit_id);
11352 free(yca_id);
11353 if (commit)
11354 got_object_commit_close(commit);
11355 if (branch)
11356 got_ref_close(branch);
11357 if (new_base_branch)
11358 got_ref_close(new_base_branch);
11359 if (tmp_branch)
11360 got_ref_close(tmp_branch);
11361 if (head_ref)
11362 got_ref_close(head_ref);
11363 if (worktree)
11364 got_worktree_close(worktree);
11365 if (repo) {
11366 const struct got_error *close_err = got_repo_close(repo);
11367 if (error == NULL)
11368 error = close_err;
11370 if (pack_fds) {
11371 const struct got_error *pack_err =
11372 got_repo_pack_fds_close(pack_fds);
11373 if (error == NULL)
11374 error = pack_err;
11376 return error;
11379 __dead static void
11380 usage_histedit(void)
11382 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11383 "[branch]\n", getprogname());
11384 exit(1);
11387 #define GOT_HISTEDIT_PICK 'p'
11388 #define GOT_HISTEDIT_EDIT 'e'
11389 #define GOT_HISTEDIT_FOLD 'f'
11390 #define GOT_HISTEDIT_DROP 'd'
11391 #define GOT_HISTEDIT_MESG 'm'
11393 static const struct got_histedit_cmd {
11394 unsigned char code;
11395 const char *name;
11396 const char *desc;
11397 } got_histedit_cmds[] = {
11398 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11399 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11400 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11401 "be used" },
11402 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11403 { GOT_HISTEDIT_MESG, "mesg",
11404 "single-line log message for commit above (open editor if empty)" },
11407 struct got_histedit_list_entry {
11408 TAILQ_ENTRY(got_histedit_list_entry) entry;
11409 struct got_object_id *commit_id;
11410 const struct got_histedit_cmd *cmd;
11411 char *logmsg;
11413 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11415 static const struct got_error *
11416 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11417 FILE *f, struct got_repository *repo)
11419 const struct got_error *err = NULL;
11420 char *logmsg = NULL, *id_str = NULL;
11421 struct got_commit_object *commit = NULL;
11422 int n;
11424 err = got_object_open_as_commit(&commit, repo, commit_id);
11425 if (err)
11426 goto done;
11428 err = get_short_logmsg(&logmsg, 34, commit);
11429 if (err)
11430 goto done;
11432 err = got_object_id_str(&id_str, commit_id);
11433 if (err)
11434 goto done;
11436 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11437 if (n < 0)
11438 err = got_ferror(f, GOT_ERR_IO);
11439 done:
11440 if (commit)
11441 got_object_commit_close(commit);
11442 free(id_str);
11443 free(logmsg);
11444 return err;
11447 static const struct got_error *
11448 histedit_write_commit_list(struct got_object_id_queue *commits,
11449 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11450 int edit_only, struct got_repository *repo)
11452 const struct got_error *err = NULL;
11453 struct got_object_qid *qid;
11454 const char *histedit_cmd = NULL;
11456 if (STAILQ_EMPTY(commits))
11457 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11459 STAILQ_FOREACH(qid, commits, entry) {
11460 histedit_cmd = got_histedit_cmds[0].name;
11461 if (drop_only)
11462 histedit_cmd = "drop";
11463 else if (edit_only)
11464 histedit_cmd = "edit";
11465 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11466 histedit_cmd = "fold";
11467 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11468 if (err)
11469 break;
11470 if (edit_logmsg_only) {
11471 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11472 if (n < 0) {
11473 err = got_ferror(f, GOT_ERR_IO);
11474 break;
11479 return err;
11482 static const struct got_error *
11483 write_cmd_list(FILE *f, const char *branch_name,
11484 struct got_object_id_queue *commits)
11486 const struct got_error *err = NULL;
11487 size_t i;
11488 int n;
11489 char *id_str;
11490 struct got_object_qid *qid;
11492 qid = STAILQ_FIRST(commits);
11493 err = got_object_id_str(&id_str, &qid->id);
11494 if (err)
11495 return err;
11497 n = fprintf(f,
11498 "# Editing the history of branch '%s' starting at\n"
11499 "# commit %s\n"
11500 "# Commits will be processed in order from top to "
11501 "bottom of this file.\n", branch_name, id_str);
11502 if (n < 0) {
11503 err = got_ferror(f, GOT_ERR_IO);
11504 goto done;
11507 n = fprintf(f, "# Available histedit commands:\n");
11508 if (n < 0) {
11509 err = got_ferror(f, GOT_ERR_IO);
11510 goto done;
11513 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11514 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11515 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11516 cmd->desc);
11517 if (n < 0) {
11518 err = got_ferror(f, GOT_ERR_IO);
11519 break;
11522 done:
11523 free(id_str);
11524 return err;
11527 static const struct got_error *
11528 histedit_syntax_error(int lineno)
11530 static char msg[42];
11531 int ret;
11533 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11534 lineno);
11535 if (ret < 0 || (size_t)ret >= sizeof(msg))
11536 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11538 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11541 static const struct got_error *
11542 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11543 char *logmsg, struct got_repository *repo)
11545 const struct got_error *err;
11546 struct got_commit_object *folded_commit = NULL;
11547 char *id_str, *folded_logmsg = NULL;
11549 err = got_object_id_str(&id_str, hle->commit_id);
11550 if (err)
11551 return err;
11553 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11554 if (err)
11555 goto done;
11557 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11558 if (err)
11559 goto done;
11560 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11561 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11562 folded_logmsg) == -1) {
11563 err = got_error_from_errno("asprintf");
11565 done:
11566 if (folded_commit)
11567 got_object_commit_close(folded_commit);
11568 free(id_str);
11569 free(folded_logmsg);
11570 return err;
11573 static struct got_histedit_list_entry *
11574 get_folded_commits(struct got_histedit_list_entry *hle)
11576 struct got_histedit_list_entry *prev, *folded = NULL;
11578 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11579 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11580 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11581 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11582 folded = prev;
11583 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11586 return folded;
11589 static const struct got_error *
11590 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11591 struct got_repository *repo)
11593 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11594 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11595 const struct got_error *err = NULL;
11596 struct got_commit_object *commit = NULL;
11597 int logmsg_len;
11598 int fd;
11599 struct got_histedit_list_entry *folded = NULL;
11601 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11602 if (err)
11603 return err;
11605 folded = get_folded_commits(hle);
11606 if (folded) {
11607 while (folded != hle) {
11608 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11609 folded = TAILQ_NEXT(folded, entry);
11610 continue;
11612 err = append_folded_commit_msg(&new_msg, folded,
11613 logmsg, repo);
11614 if (err)
11615 goto done;
11616 free(logmsg);
11617 logmsg = new_msg;
11618 folded = TAILQ_NEXT(folded, entry);
11622 err = got_object_id_str(&id_str, hle->commit_id);
11623 if (err)
11624 goto done;
11625 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11626 if (err)
11627 goto done;
11628 logmsg_len = asprintf(&new_msg,
11629 "%s\n# original log message of commit %s: %s",
11630 logmsg ? logmsg : "", id_str, orig_logmsg);
11631 if (logmsg_len == -1) {
11632 err = got_error_from_errno("asprintf");
11633 goto done;
11635 free(logmsg);
11636 logmsg = new_msg;
11638 err = got_object_id_str(&id_str, hle->commit_id);
11639 if (err)
11640 goto done;
11642 err = got_opentemp_named_fd(&logmsg_path, &fd,
11643 GOT_TMPDIR_STR "/got-logmsg", "");
11644 if (err)
11645 goto done;
11647 write(fd, logmsg, logmsg_len);
11648 close(fd);
11650 err = get_editor(&editor);
11651 if (err)
11652 goto done;
11654 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11655 logmsg_len, 0);
11656 if (err) {
11657 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11658 goto done;
11659 err = NULL;
11660 hle->logmsg = strdup(new_msg);
11661 if (hle->logmsg == NULL)
11662 err = got_error_from_errno("strdup");
11664 done:
11665 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11666 err = got_error_from_errno2("unlink", logmsg_path);
11667 free(logmsg_path);
11668 free(logmsg);
11669 free(orig_logmsg);
11670 free(editor);
11671 if (commit)
11672 got_object_commit_close(commit);
11673 return err;
11676 static const struct got_error *
11677 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11678 FILE *f, struct got_repository *repo)
11680 const struct got_error *err = NULL;
11681 char *line = NULL, *p, *end;
11682 size_t i, size;
11683 ssize_t len;
11684 int lineno = 0, lastcmd = -1;
11685 const struct got_histedit_cmd *cmd;
11686 struct got_object_id *commit_id = NULL;
11687 struct got_histedit_list_entry *hle = NULL;
11689 for (;;) {
11690 len = getline(&line, &size, f);
11691 if (len == -1) {
11692 const struct got_error *getline_err;
11693 if (feof(f))
11694 break;
11695 getline_err = got_error_from_errno("getline");
11696 err = got_ferror(f, getline_err->code);
11697 break;
11699 lineno++;
11700 p = line;
11701 while (isspace((unsigned char)p[0]))
11702 p++;
11703 if (p[0] == '#' || p[0] == '\0') {
11704 free(line);
11705 line = NULL;
11706 continue;
11708 cmd = NULL;
11709 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11710 cmd = &got_histedit_cmds[i];
11711 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11712 isspace((unsigned char)p[strlen(cmd->name)])) {
11713 p += strlen(cmd->name);
11714 break;
11716 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11717 p++;
11718 break;
11721 if (i == nitems(got_histedit_cmds)) {
11722 err = histedit_syntax_error(lineno);
11723 break;
11725 while (isspace((unsigned char)p[0]))
11726 p++;
11727 if (cmd->code == GOT_HISTEDIT_MESG) {
11728 if (lastcmd != GOT_HISTEDIT_PICK &&
11729 lastcmd != GOT_HISTEDIT_EDIT) {
11730 err = got_error(GOT_ERR_HISTEDIT_CMD);
11731 break;
11733 if (p[0] == '\0') {
11734 err = histedit_edit_logmsg(hle, repo);
11735 if (err)
11736 break;
11737 } else {
11738 hle->logmsg = strdup(p);
11739 if (hle->logmsg == NULL) {
11740 err = got_error_from_errno("strdup");
11741 break;
11744 free(line);
11745 line = NULL;
11746 lastcmd = cmd->code;
11747 continue;
11748 } else {
11749 end = p;
11750 while (end[0] && !isspace((unsigned char)end[0]))
11751 end++;
11752 *end = '\0';
11754 err = got_object_resolve_id_str(&commit_id, repo, p);
11755 if (err) {
11756 /* override error code */
11757 err = histedit_syntax_error(lineno);
11758 break;
11761 hle = malloc(sizeof(*hle));
11762 if (hle == NULL) {
11763 err = got_error_from_errno("malloc");
11764 break;
11766 hle->cmd = cmd;
11767 hle->commit_id = commit_id;
11768 hle->logmsg = NULL;
11769 commit_id = NULL;
11770 free(line);
11771 line = NULL;
11772 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11773 lastcmd = cmd->code;
11776 free(line);
11777 free(commit_id);
11778 return err;
11781 static const struct got_error *
11782 histedit_check_script(struct got_histedit_list *histedit_cmds,
11783 struct got_object_id_queue *commits, struct got_repository *repo)
11785 const struct got_error *err = NULL;
11786 struct got_object_qid *qid;
11787 struct got_histedit_list_entry *hle;
11788 static char msg[92];
11789 char *id_str;
11791 if (TAILQ_EMPTY(histedit_cmds))
11792 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11793 "histedit script contains no commands");
11794 if (STAILQ_EMPTY(commits))
11795 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11797 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11798 struct got_histedit_list_entry *hle2;
11799 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11800 if (hle == hle2)
11801 continue;
11802 if (got_object_id_cmp(hle->commit_id,
11803 hle2->commit_id) != 0)
11804 continue;
11805 err = got_object_id_str(&id_str, hle->commit_id);
11806 if (err)
11807 return err;
11808 snprintf(msg, sizeof(msg), "commit %s is listed "
11809 "more than once in histedit script", id_str);
11810 free(id_str);
11811 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11815 STAILQ_FOREACH(qid, commits, entry) {
11816 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11817 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11818 break;
11820 if (hle == NULL) {
11821 err = got_object_id_str(&id_str, &qid->id);
11822 if (err)
11823 return err;
11824 snprintf(msg, sizeof(msg),
11825 "commit %s missing from histedit script", id_str);
11826 free(id_str);
11827 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11831 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11832 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11833 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11834 "last commit in histedit script cannot be folded");
11836 return NULL;
11839 static const struct got_error *
11840 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11841 const char *path, struct got_object_id_queue *commits,
11842 struct got_repository *repo)
11844 const struct got_error *err = NULL;
11845 char *editor;
11846 FILE *f = NULL;
11848 err = get_editor(&editor);
11849 if (err)
11850 return err;
11852 if (spawn_editor(editor, path) == -1) {
11853 err = got_error_from_errno("failed spawning editor");
11854 goto done;
11857 f = fopen(path, "re");
11858 if (f == NULL) {
11859 err = got_error_from_errno("fopen");
11860 goto done;
11862 err = histedit_parse_list(histedit_cmds, f, repo);
11863 if (err)
11864 goto done;
11866 err = histedit_check_script(histedit_cmds, commits, repo);
11867 done:
11868 if (f && fclose(f) == EOF && err == NULL)
11869 err = got_error_from_errno("fclose");
11870 free(editor);
11871 return err;
11874 static const struct got_error *
11875 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11876 struct got_object_id_queue *, const char *, const char *,
11877 struct got_repository *);
11879 static const struct got_error *
11880 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11881 struct got_object_id_queue *commits, const char *branch_name,
11882 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11883 struct got_repository *repo)
11885 const struct got_error *err;
11886 FILE *f = NULL;
11887 char *path = NULL;
11889 err = got_opentemp_named(&path, &f, "got-histedit", "");
11890 if (err)
11891 return err;
11893 err = write_cmd_list(f, branch_name, commits);
11894 if (err)
11895 goto done;
11897 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11898 fold_only, drop_only, edit_only, repo);
11899 if (err)
11900 goto done;
11902 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11903 rewind(f);
11904 err = histedit_parse_list(histedit_cmds, f, repo);
11905 } else {
11906 if (fclose(f) == EOF) {
11907 err = got_error_from_errno("fclose");
11908 goto done;
11910 f = NULL;
11911 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11912 if (err) {
11913 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11914 err->code != GOT_ERR_HISTEDIT_CMD)
11915 goto done;
11916 err = histedit_edit_list_retry(histedit_cmds, err,
11917 commits, path, branch_name, repo);
11920 done:
11921 if (f && fclose(f) == EOF && err == NULL)
11922 err = got_error_from_errno("fclose");
11923 if (path && unlink(path) != 0 && err == NULL)
11924 err = got_error_from_errno2("unlink", path);
11925 free(path);
11926 return err;
11929 static const struct got_error *
11930 histedit_save_list(struct got_histedit_list *histedit_cmds,
11931 struct got_worktree *worktree, struct got_repository *repo)
11933 const struct got_error *err = NULL;
11934 char *path = NULL;
11935 FILE *f = NULL;
11936 struct got_histedit_list_entry *hle;
11937 struct got_commit_object *commit = NULL;
11939 err = got_worktree_get_histedit_script_path(&path, worktree);
11940 if (err)
11941 return err;
11943 f = fopen(path, "we");
11944 if (f == NULL) {
11945 err = got_error_from_errno2("fopen", path);
11946 goto done;
11948 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11949 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11950 repo);
11951 if (err)
11952 break;
11954 if (hle->logmsg) {
11955 int n = fprintf(f, "%c %s\n",
11956 GOT_HISTEDIT_MESG, hle->logmsg);
11957 if (n < 0) {
11958 err = got_ferror(f, GOT_ERR_IO);
11959 break;
11963 done:
11964 if (f && fclose(f) == EOF && err == NULL)
11965 err = got_error_from_errno("fclose");
11966 free(path);
11967 if (commit)
11968 got_object_commit_close(commit);
11969 return err;
11972 static void
11973 histedit_free_list(struct got_histedit_list *histedit_cmds)
11975 struct got_histedit_list_entry *hle;
11977 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11978 TAILQ_REMOVE(histedit_cmds, hle, entry);
11979 free(hle);
11983 static const struct got_error *
11984 histedit_load_list(struct got_histedit_list *histedit_cmds,
11985 const char *path, struct got_repository *repo)
11987 const struct got_error *err = NULL;
11988 FILE *f = NULL;
11990 f = fopen(path, "re");
11991 if (f == NULL) {
11992 err = got_error_from_errno2("fopen", path);
11993 goto done;
11996 err = histedit_parse_list(histedit_cmds, f, repo);
11997 done:
11998 if (f && fclose(f) == EOF && err == NULL)
11999 err = got_error_from_errno("fclose");
12000 return err;
12003 static const struct got_error *
12004 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12005 const struct got_error *edit_err, struct got_object_id_queue *commits,
12006 const char *path, const char *branch_name, struct got_repository *repo)
12008 const struct got_error *err = NULL, *prev_err = edit_err;
12009 int resp = ' ';
12011 while (resp != 'c' && resp != 'r' && resp != 'a') {
12012 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12013 "or (a)bort: ", getprogname(), prev_err->msg);
12014 resp = getchar();
12015 if (resp == '\n')
12016 resp = getchar();
12017 if (resp == 'c') {
12018 histedit_free_list(histedit_cmds);
12019 err = histedit_run_editor(histedit_cmds, path, commits,
12020 repo);
12021 if (err) {
12022 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12023 err->code != GOT_ERR_HISTEDIT_CMD)
12024 break;
12025 prev_err = err;
12026 resp = ' ';
12027 continue;
12029 break;
12030 } else if (resp == 'r') {
12031 histedit_free_list(histedit_cmds);
12032 err = histedit_edit_script(histedit_cmds,
12033 commits, branch_name, 0, 0, 0, 0, repo);
12034 if (err) {
12035 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12036 err->code != GOT_ERR_HISTEDIT_CMD)
12037 break;
12038 prev_err = err;
12039 resp = ' ';
12040 continue;
12042 break;
12043 } else if (resp == 'a') {
12044 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12045 break;
12046 } else
12047 printf("invalid response '%c'\n", resp);
12050 return err;
12053 static const struct got_error *
12054 histedit_complete(struct got_worktree *worktree,
12055 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12056 struct got_reference *branch, struct got_repository *repo)
12058 printf("Switching work tree to %s\n",
12059 got_ref_get_symref_target(branch));
12060 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12061 branch, repo);
12064 static const struct got_error *
12065 show_histedit_progress(struct got_commit_object *commit,
12066 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12068 const struct got_error *err;
12069 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12071 err = got_object_id_str(&old_id_str, hle->commit_id);
12072 if (err)
12073 goto done;
12075 if (new_id) {
12076 err = got_object_id_str(&new_id_str, new_id);
12077 if (err)
12078 goto done;
12081 old_id_str[12] = '\0';
12082 if (new_id_str)
12083 new_id_str[12] = '\0';
12085 if (hle->logmsg) {
12086 logmsg = strdup(hle->logmsg);
12087 if (logmsg == NULL) {
12088 err = got_error_from_errno("strdup");
12089 goto done;
12091 trim_logmsg(logmsg, 42);
12092 } else {
12093 err = get_short_logmsg(&logmsg, 42, commit);
12094 if (err)
12095 goto done;
12098 switch (hle->cmd->code) {
12099 case GOT_HISTEDIT_PICK:
12100 case GOT_HISTEDIT_EDIT:
12101 printf("%s -> %s: %s\n", old_id_str,
12102 new_id_str ? new_id_str : "no-op change", logmsg);
12103 break;
12104 case GOT_HISTEDIT_DROP:
12105 case GOT_HISTEDIT_FOLD:
12106 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12107 logmsg);
12108 break;
12109 default:
12110 break;
12112 done:
12113 free(old_id_str);
12114 free(new_id_str);
12115 return err;
12118 static const struct got_error *
12119 histedit_commit(struct got_pathlist_head *merged_paths,
12120 struct got_worktree *worktree, struct got_fileindex *fileindex,
12121 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12122 const char *committer, struct got_repository *repo)
12124 const struct got_error *err;
12125 struct got_commit_object *commit;
12126 struct got_object_id *new_commit_id;
12128 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12129 && hle->logmsg == NULL) {
12130 err = histedit_edit_logmsg(hle, repo);
12131 if (err)
12132 return err;
12135 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12136 if (err)
12137 return err;
12139 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12140 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12141 hle->logmsg, repo);
12142 if (err) {
12143 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12144 goto done;
12145 err = show_histedit_progress(commit, hle, NULL);
12146 } else {
12147 err = show_histedit_progress(commit, hle, new_commit_id);
12148 free(new_commit_id);
12150 done:
12151 got_object_commit_close(commit);
12152 return err;
12155 static const struct got_error *
12156 histedit_skip_commit(struct got_histedit_list_entry *hle,
12157 struct got_worktree *worktree, struct got_repository *repo)
12159 const struct got_error *error;
12160 struct got_commit_object *commit;
12162 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12163 repo);
12164 if (error)
12165 return error;
12167 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12168 if (error)
12169 return error;
12171 error = show_histedit_progress(commit, hle, NULL);
12172 got_object_commit_close(commit);
12173 return error;
12176 static const struct got_error *
12177 check_local_changes(void *arg, unsigned char status,
12178 unsigned char staged_status, const char *path,
12179 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12180 struct got_object_id *commit_id, int dirfd, const char *de_name)
12182 int *have_local_changes = arg;
12184 switch (status) {
12185 case GOT_STATUS_ADD:
12186 case GOT_STATUS_DELETE:
12187 case GOT_STATUS_MODIFY:
12188 case GOT_STATUS_CONFLICT:
12189 *have_local_changes = 1;
12190 return got_error(GOT_ERR_CANCELLED);
12191 default:
12192 break;
12195 switch (staged_status) {
12196 case GOT_STATUS_ADD:
12197 case GOT_STATUS_DELETE:
12198 case GOT_STATUS_MODIFY:
12199 *have_local_changes = 1;
12200 return got_error(GOT_ERR_CANCELLED);
12201 default:
12202 break;
12205 return NULL;
12208 static const struct got_error *
12209 cmd_histedit(int argc, char *argv[])
12211 const struct got_error *error = NULL;
12212 struct got_worktree *worktree = NULL;
12213 struct got_fileindex *fileindex = NULL;
12214 struct got_repository *repo = NULL;
12215 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12216 struct got_reference *branch = NULL;
12217 struct got_reference *tmp_branch = NULL;
12218 struct got_object_id *resume_commit_id = NULL;
12219 struct got_object_id *base_commit_id = NULL;
12220 struct got_object_id *head_commit_id = NULL;
12221 struct got_commit_object *commit = NULL;
12222 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12223 struct got_update_progress_arg upa;
12224 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12225 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12226 int list_backups = 0, delete_backups = 0;
12227 const char *edit_script_path = NULL;
12228 struct got_object_id_queue commits;
12229 struct got_pathlist_head merged_paths;
12230 const struct got_object_id_queue *parent_ids;
12231 struct got_object_qid *pid;
12232 struct got_histedit_list histedit_cmds;
12233 struct got_histedit_list_entry *hle;
12234 int *pack_fds = NULL;
12236 STAILQ_INIT(&commits);
12237 TAILQ_INIT(&histedit_cmds);
12238 TAILQ_INIT(&merged_paths);
12239 memset(&upa, 0, sizeof(upa));
12241 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12242 switch (ch) {
12243 case 'a':
12244 abort_edit = 1;
12245 break;
12246 case 'c':
12247 continue_edit = 1;
12248 break;
12249 case 'd':
12250 drop_only = 1;
12251 break;
12252 case 'e':
12253 edit_only = 1;
12254 break;
12255 case 'F':
12256 edit_script_path = optarg;
12257 break;
12258 case 'f':
12259 fold_only = 1;
12260 break;
12261 case 'l':
12262 list_backups = 1;
12263 break;
12264 case 'm':
12265 edit_logmsg_only = 1;
12266 break;
12267 case 'X':
12268 delete_backups = 1;
12269 break;
12270 default:
12271 usage_histedit();
12272 /* NOTREACHED */
12276 argc -= optind;
12277 argv += optind;
12279 #ifndef PROFILE
12280 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12281 "unveil", NULL) == -1)
12282 err(1, "pledge");
12283 #endif
12284 if (abort_edit && continue_edit)
12285 option_conflict('a', 'c');
12286 if (edit_script_path && edit_logmsg_only)
12287 option_conflict('F', 'm');
12288 if (abort_edit && edit_logmsg_only)
12289 option_conflict('a', 'm');
12290 if (continue_edit && edit_logmsg_only)
12291 option_conflict('c', 'm');
12292 if (abort_edit && fold_only)
12293 option_conflict('a', 'f');
12294 if (continue_edit && fold_only)
12295 option_conflict('c', 'f');
12296 if (fold_only && edit_logmsg_only)
12297 option_conflict('f', 'm');
12298 if (edit_script_path && fold_only)
12299 option_conflict('F', 'f');
12300 if (abort_edit && edit_only)
12301 option_conflict('a', 'e');
12302 if (continue_edit && edit_only)
12303 option_conflict('c', 'e');
12304 if (edit_only && edit_logmsg_only)
12305 option_conflict('e', 'm');
12306 if (edit_script_path && edit_only)
12307 option_conflict('F', 'e');
12308 if (fold_only && edit_only)
12309 option_conflict('f', 'e');
12310 if (drop_only && abort_edit)
12311 option_conflict('d', 'a');
12312 if (drop_only && continue_edit)
12313 option_conflict('d', 'c');
12314 if (drop_only && edit_logmsg_only)
12315 option_conflict('d', 'm');
12316 if (drop_only && edit_only)
12317 option_conflict('d', 'e');
12318 if (drop_only && edit_script_path)
12319 option_conflict('d', 'F');
12320 if (drop_only && fold_only)
12321 option_conflict('d', 'f');
12322 if (list_backups) {
12323 if (abort_edit)
12324 option_conflict('l', 'a');
12325 if (continue_edit)
12326 option_conflict('l', 'c');
12327 if (edit_script_path)
12328 option_conflict('l', 'F');
12329 if (edit_logmsg_only)
12330 option_conflict('l', 'm');
12331 if (drop_only)
12332 option_conflict('l', 'd');
12333 if (fold_only)
12334 option_conflict('l', 'f');
12335 if (edit_only)
12336 option_conflict('l', 'e');
12337 if (delete_backups)
12338 option_conflict('l', 'X');
12339 if (argc != 0 && argc != 1)
12340 usage_histedit();
12341 } else if (delete_backups) {
12342 if (abort_edit)
12343 option_conflict('X', 'a');
12344 if (continue_edit)
12345 option_conflict('X', 'c');
12346 if (drop_only)
12347 option_conflict('X', 'd');
12348 if (edit_script_path)
12349 option_conflict('X', 'F');
12350 if (edit_logmsg_only)
12351 option_conflict('X', 'm');
12352 if (fold_only)
12353 option_conflict('X', 'f');
12354 if (edit_only)
12355 option_conflict('X', 'e');
12356 if (list_backups)
12357 option_conflict('X', 'l');
12358 if (argc != 0 && argc != 1)
12359 usage_histedit();
12360 } else if (argc != 0)
12361 usage_histedit();
12364 * This command cannot apply unveil(2) in all cases because the
12365 * user may choose to run an editor to edit the histedit script
12366 * and to edit individual commit log messages.
12367 * unveil(2) traverses exec(2); if an editor is used we have to
12368 * apply unveil after edit script and log messages have been written.
12369 * XXX TODO: Make use of unveil(2) where possible.
12372 cwd = getcwd(NULL, 0);
12373 if (cwd == NULL) {
12374 error = got_error_from_errno("getcwd");
12375 goto done;
12378 error = got_repo_pack_fds_open(&pack_fds);
12379 if (error != NULL)
12380 goto done;
12382 error = got_worktree_open(&worktree, cwd);
12383 if (error) {
12384 if (list_backups || delete_backups) {
12385 if (error->code != GOT_ERR_NOT_WORKTREE)
12386 goto done;
12387 } else {
12388 if (error->code == GOT_ERR_NOT_WORKTREE)
12389 error = wrap_not_worktree_error(error,
12390 "histedit", cwd);
12391 goto done;
12395 if (list_backups || delete_backups) {
12396 error = got_repo_open(&repo,
12397 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12398 NULL, pack_fds);
12399 if (error != NULL)
12400 goto done;
12401 error = apply_unveil(got_repo_get_path(repo), 0,
12402 worktree ? got_worktree_get_root_path(worktree) : NULL);
12403 if (error)
12404 goto done;
12405 error = process_backup_refs(
12406 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12407 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12408 goto done; /* nothing else to do */
12411 error = get_gitconfig_path(&gitconfig_path);
12412 if (error)
12413 goto done;
12414 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12415 gitconfig_path, pack_fds);
12416 if (error != NULL)
12417 goto done;
12419 if (worktree != NULL && !list_backups && !delete_backups) {
12420 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12421 if (error)
12422 goto done;
12425 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12426 if (error)
12427 goto done;
12428 if (rebase_in_progress) {
12429 error = got_error(GOT_ERR_REBASING);
12430 goto done;
12433 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12434 repo);
12435 if (error)
12436 goto done;
12437 if (merge_in_progress) {
12438 error = got_error(GOT_ERR_MERGE_BUSY);
12439 goto done;
12442 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12443 if (error)
12444 goto done;
12446 if (edit_in_progress && edit_logmsg_only) {
12447 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12448 "histedit operation is in progress in this "
12449 "work tree and must be continued or aborted "
12450 "before the -m option can be used");
12451 goto done;
12453 if (edit_in_progress && drop_only) {
12454 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12455 "histedit operation is in progress in this "
12456 "work tree and must be continued or aborted "
12457 "before the -d option can be used");
12458 goto done;
12460 if (edit_in_progress && fold_only) {
12461 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12462 "histedit operation is in progress in this "
12463 "work tree and must be continued or aborted "
12464 "before the -f option can be used");
12465 goto done;
12467 if (edit_in_progress && edit_only) {
12468 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12469 "histedit operation is in progress in this "
12470 "work tree and must be continued or aborted "
12471 "before the -e option can be used");
12472 goto done;
12475 if (edit_in_progress && abort_edit) {
12476 error = got_worktree_histedit_continue(&resume_commit_id,
12477 &tmp_branch, &branch, &base_commit_id, &fileindex,
12478 worktree, repo);
12479 if (error)
12480 goto done;
12481 printf("Switching work tree to %s\n",
12482 got_ref_get_symref_target(branch));
12483 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12484 branch, base_commit_id, abort_progress, &upa);
12485 if (error)
12486 goto done;
12487 printf("Histedit of %s aborted\n",
12488 got_ref_get_symref_target(branch));
12489 print_merge_progress_stats(&upa);
12490 goto done; /* nothing else to do */
12491 } else if (abort_edit) {
12492 error = got_error(GOT_ERR_NOT_HISTEDIT);
12493 goto done;
12496 error = get_author(&committer, repo, worktree);
12497 if (error)
12498 goto done;
12500 if (continue_edit) {
12501 char *path;
12503 if (!edit_in_progress) {
12504 error = got_error(GOT_ERR_NOT_HISTEDIT);
12505 goto done;
12508 error = got_worktree_get_histedit_script_path(&path, worktree);
12509 if (error)
12510 goto done;
12512 error = histedit_load_list(&histedit_cmds, path, repo);
12513 free(path);
12514 if (error)
12515 goto done;
12517 error = got_worktree_histedit_continue(&resume_commit_id,
12518 &tmp_branch, &branch, &base_commit_id, &fileindex,
12519 worktree, repo);
12520 if (error)
12521 goto done;
12523 error = got_ref_resolve(&head_commit_id, repo, branch);
12524 if (error)
12525 goto done;
12527 error = got_object_open_as_commit(&commit, repo,
12528 head_commit_id);
12529 if (error)
12530 goto done;
12531 parent_ids = got_object_commit_get_parent_ids(commit);
12532 pid = STAILQ_FIRST(parent_ids);
12533 if (pid == NULL) {
12534 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12535 goto done;
12537 error = collect_commits(&commits, head_commit_id, &pid->id,
12538 base_commit_id, got_worktree_get_path_prefix(worktree),
12539 GOT_ERR_HISTEDIT_PATH, repo);
12540 got_object_commit_close(commit);
12541 commit = NULL;
12542 if (error)
12543 goto done;
12544 } else {
12545 if (edit_in_progress) {
12546 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12547 goto done;
12550 error = got_ref_open(&branch, repo,
12551 got_worktree_get_head_ref_name(worktree), 0);
12552 if (error != NULL)
12553 goto done;
12555 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12556 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12557 "will not edit commit history of a branch outside "
12558 "the \"refs/heads/\" reference namespace");
12559 goto done;
12562 error = got_ref_resolve(&head_commit_id, repo, branch);
12563 got_ref_close(branch);
12564 branch = NULL;
12565 if (error)
12566 goto done;
12568 error = got_object_open_as_commit(&commit, repo,
12569 head_commit_id);
12570 if (error)
12571 goto done;
12572 parent_ids = got_object_commit_get_parent_ids(commit);
12573 pid = STAILQ_FIRST(parent_ids);
12574 if (pid == NULL) {
12575 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12576 goto done;
12578 error = collect_commits(&commits, head_commit_id, &pid->id,
12579 got_worktree_get_base_commit_id(worktree),
12580 got_worktree_get_path_prefix(worktree),
12581 GOT_ERR_HISTEDIT_PATH, repo);
12582 got_object_commit_close(commit);
12583 commit = NULL;
12584 if (error)
12585 goto done;
12587 if (STAILQ_EMPTY(&commits)) {
12588 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12589 goto done;
12592 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12593 &base_commit_id, &fileindex, worktree, repo);
12594 if (error)
12595 goto done;
12597 if (edit_script_path) {
12598 error = histedit_load_list(&histedit_cmds,
12599 edit_script_path, repo);
12600 if (error) {
12601 got_worktree_histedit_abort(worktree, fileindex,
12602 repo, branch, base_commit_id,
12603 abort_progress, &upa);
12604 print_merge_progress_stats(&upa);
12605 goto done;
12607 } else {
12608 const char *branch_name;
12609 branch_name = got_ref_get_symref_target(branch);
12610 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12611 branch_name += 11;
12612 error = histedit_edit_script(&histedit_cmds, &commits,
12613 branch_name, edit_logmsg_only, fold_only,
12614 drop_only, edit_only, repo);
12615 if (error) {
12616 got_worktree_histedit_abort(worktree, fileindex,
12617 repo, branch, base_commit_id,
12618 abort_progress, &upa);
12619 print_merge_progress_stats(&upa);
12620 goto done;
12625 error = histedit_save_list(&histedit_cmds, worktree,
12626 repo);
12627 if (error) {
12628 got_worktree_histedit_abort(worktree, fileindex,
12629 repo, branch, base_commit_id,
12630 abort_progress, &upa);
12631 print_merge_progress_stats(&upa);
12632 goto done;
12637 error = histedit_check_script(&histedit_cmds, &commits, repo);
12638 if (error)
12639 goto done;
12641 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12642 if (resume_commit_id) {
12643 if (got_object_id_cmp(hle->commit_id,
12644 resume_commit_id) != 0)
12645 continue;
12647 resume_commit_id = NULL;
12648 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12649 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12650 error = histedit_skip_commit(hle, worktree,
12651 repo);
12652 if (error)
12653 goto done;
12654 } else {
12655 struct got_pathlist_head paths;
12656 int have_changes = 0;
12658 TAILQ_INIT(&paths);
12659 error = got_pathlist_append(&paths, "", NULL);
12660 if (error)
12661 goto done;
12662 error = got_worktree_status(worktree, &paths,
12663 repo, 0, check_local_changes, &have_changes,
12664 check_cancelled, NULL);
12665 got_pathlist_free(&paths,
12666 GOT_PATHLIST_FREE_NONE);
12667 if (error) {
12668 if (error->code != GOT_ERR_CANCELLED)
12669 goto done;
12670 if (sigint_received || sigpipe_received)
12671 goto done;
12673 if (have_changes) {
12674 error = histedit_commit(NULL, worktree,
12675 fileindex, tmp_branch, hle,
12676 committer, repo);
12677 if (error)
12678 goto done;
12679 } else {
12680 error = got_object_open_as_commit(
12681 &commit, repo, hle->commit_id);
12682 if (error)
12683 goto done;
12684 error = show_histedit_progress(commit,
12685 hle, NULL);
12686 got_object_commit_close(commit);
12687 commit = NULL;
12688 if (error)
12689 goto done;
12692 continue;
12695 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12696 error = histedit_skip_commit(hle, worktree, repo);
12697 if (error)
12698 goto done;
12699 continue;
12702 error = got_object_open_as_commit(&commit, repo,
12703 hle->commit_id);
12704 if (error)
12705 goto done;
12706 parent_ids = got_object_commit_get_parent_ids(commit);
12707 pid = STAILQ_FIRST(parent_ids);
12709 error = got_worktree_histedit_merge_files(&merged_paths,
12710 worktree, fileindex, &pid->id, hle->commit_id, repo,
12711 update_progress, &upa, check_cancelled, NULL);
12712 if (error)
12713 goto done;
12714 got_object_commit_close(commit);
12715 commit = NULL;
12717 print_merge_progress_stats(&upa);
12718 if (upa.conflicts > 0 || upa.missing > 0 ||
12719 upa.not_deleted > 0 || upa.unversioned > 0) {
12720 if (upa.conflicts > 0) {
12721 error = show_rebase_merge_conflict(
12722 hle->commit_id, repo);
12723 if (error)
12724 goto done;
12726 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12727 break;
12730 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12731 char *id_str;
12732 error = got_object_id_str(&id_str, hle->commit_id);
12733 if (error)
12734 goto done;
12735 printf("Stopping histedit for amending commit %s\n",
12736 id_str);
12737 free(id_str);
12738 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12739 error = got_worktree_histedit_postpone(worktree,
12740 fileindex);
12741 goto done;
12744 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12745 error = histedit_skip_commit(hle, worktree, repo);
12746 if (error)
12747 goto done;
12748 continue;
12751 error = histedit_commit(&merged_paths, worktree, fileindex,
12752 tmp_branch, hle, committer, repo);
12753 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12754 if (error)
12755 goto done;
12758 if (upa.conflicts > 0 || upa.missing > 0 ||
12759 upa.not_deleted > 0 || upa.unversioned > 0) {
12760 error = got_worktree_histedit_postpone(worktree, fileindex);
12761 if (error)
12762 goto done;
12763 if (upa.conflicts > 0 && upa.missing == 0 &&
12764 upa.not_deleted == 0 && upa.unversioned == 0) {
12765 error = got_error_msg(GOT_ERR_CONFLICTS,
12766 "conflicts must be resolved before histedit "
12767 "can continue");
12768 } else if (upa.conflicts > 0) {
12769 error = got_error_msg(GOT_ERR_CONFLICTS,
12770 "conflicts must be resolved before histedit "
12771 "can continue; changes destined for some "
12772 "files were not yet merged and should be "
12773 "merged manually if required before the "
12774 "histedit operation is continued");
12775 } else {
12776 error = got_error_msg(GOT_ERR_CONFLICTS,
12777 "changes destined for some files were not "
12778 "yet merged and should be merged manually "
12779 "if required before the histedit operation "
12780 "is continued");
12782 } else
12783 error = histedit_complete(worktree, fileindex, tmp_branch,
12784 branch, repo);
12785 done:
12786 free(cwd);
12787 free(committer);
12788 free(gitconfig_path);
12789 got_object_id_queue_free(&commits);
12790 histedit_free_list(&histedit_cmds);
12791 free(head_commit_id);
12792 free(base_commit_id);
12793 free(resume_commit_id);
12794 if (commit)
12795 got_object_commit_close(commit);
12796 if (branch)
12797 got_ref_close(branch);
12798 if (tmp_branch)
12799 got_ref_close(tmp_branch);
12800 if (worktree)
12801 got_worktree_close(worktree);
12802 if (repo) {
12803 const struct got_error *close_err = got_repo_close(repo);
12804 if (error == NULL)
12805 error = close_err;
12807 if (pack_fds) {
12808 const struct got_error *pack_err =
12809 got_repo_pack_fds_close(pack_fds);
12810 if (error == NULL)
12811 error = pack_err;
12813 return error;
12816 __dead static void
12817 usage_integrate(void)
12819 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12820 exit(1);
12823 static const struct got_error *
12824 cmd_integrate(int argc, char *argv[])
12826 const struct got_error *error = NULL;
12827 struct got_repository *repo = NULL;
12828 struct got_worktree *worktree = NULL;
12829 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12830 const char *branch_arg = NULL;
12831 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12832 struct got_fileindex *fileindex = NULL;
12833 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12834 int ch;
12835 struct got_update_progress_arg upa;
12836 int *pack_fds = NULL;
12838 while ((ch = getopt(argc, argv, "")) != -1) {
12839 switch (ch) {
12840 default:
12841 usage_integrate();
12842 /* NOTREACHED */
12846 argc -= optind;
12847 argv += optind;
12849 if (argc != 1)
12850 usage_integrate();
12851 branch_arg = argv[0];
12852 #ifndef PROFILE
12853 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12854 "unveil", NULL) == -1)
12855 err(1, "pledge");
12856 #endif
12857 cwd = getcwd(NULL, 0);
12858 if (cwd == NULL) {
12859 error = got_error_from_errno("getcwd");
12860 goto done;
12863 error = got_repo_pack_fds_open(&pack_fds);
12864 if (error != NULL)
12865 goto done;
12867 error = got_worktree_open(&worktree, cwd);
12868 if (error) {
12869 if (error->code == GOT_ERR_NOT_WORKTREE)
12870 error = wrap_not_worktree_error(error, "integrate",
12871 cwd);
12872 goto done;
12875 error = check_rebase_or_histedit_in_progress(worktree);
12876 if (error)
12877 goto done;
12879 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12880 NULL, pack_fds);
12881 if (error != NULL)
12882 goto done;
12884 error = apply_unveil(got_repo_get_path(repo), 0,
12885 got_worktree_get_root_path(worktree));
12886 if (error)
12887 goto done;
12889 error = check_merge_in_progress(worktree, repo);
12890 if (error)
12891 goto done;
12893 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12894 error = got_error_from_errno("asprintf");
12895 goto done;
12898 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12899 &base_branch_ref, worktree, refname, repo);
12900 if (error)
12901 goto done;
12903 refname = strdup(got_ref_get_name(branch_ref));
12904 if (refname == NULL) {
12905 error = got_error_from_errno("strdup");
12906 got_worktree_integrate_abort(worktree, fileindex, repo,
12907 branch_ref, base_branch_ref);
12908 goto done;
12910 base_refname = strdup(got_ref_get_name(base_branch_ref));
12911 if (base_refname == NULL) {
12912 error = got_error_from_errno("strdup");
12913 got_worktree_integrate_abort(worktree, fileindex, repo,
12914 branch_ref, base_branch_ref);
12915 goto done;
12917 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12918 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12919 got_worktree_integrate_abort(worktree, fileindex, repo,
12920 branch_ref, base_branch_ref);
12921 goto done;
12924 error = got_ref_resolve(&commit_id, repo, branch_ref);
12925 if (error)
12926 goto done;
12928 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12929 if (error)
12930 goto done;
12932 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12933 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12934 "specified branch has already been integrated");
12935 got_worktree_integrate_abort(worktree, fileindex, repo,
12936 branch_ref, base_branch_ref);
12937 goto done;
12940 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12941 if (error) {
12942 if (error->code == GOT_ERR_ANCESTRY)
12943 error = got_error(GOT_ERR_REBASE_REQUIRED);
12944 got_worktree_integrate_abort(worktree, fileindex, repo,
12945 branch_ref, base_branch_ref);
12946 goto done;
12949 memset(&upa, 0, sizeof(upa));
12950 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12951 branch_ref, base_branch_ref, update_progress, &upa,
12952 check_cancelled, NULL);
12953 if (error)
12954 goto done;
12956 printf("Integrated %s into %s\n", refname, base_refname);
12957 print_update_progress_stats(&upa);
12958 done:
12959 if (repo) {
12960 const struct got_error *close_err = got_repo_close(repo);
12961 if (error == NULL)
12962 error = close_err;
12964 if (worktree)
12965 got_worktree_close(worktree);
12966 if (pack_fds) {
12967 const struct got_error *pack_err =
12968 got_repo_pack_fds_close(pack_fds);
12969 if (error == NULL)
12970 error = pack_err;
12972 free(cwd);
12973 free(base_commit_id);
12974 free(commit_id);
12975 free(refname);
12976 free(base_refname);
12977 return error;
12980 __dead static void
12981 usage_merge(void)
12983 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12984 exit(1);
12987 static const struct got_error *
12988 cmd_merge(int argc, char *argv[])
12990 const struct got_error *error = NULL;
12991 struct got_worktree *worktree = NULL;
12992 struct got_repository *repo = NULL;
12993 struct got_fileindex *fileindex = NULL;
12994 char *cwd = NULL, *id_str = NULL, *author = NULL;
12995 struct got_reference *branch = NULL, *wt_branch = NULL;
12996 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12997 struct got_object_id *wt_branch_tip = NULL;
12998 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12999 int interrupt_merge = 0;
13000 struct got_update_progress_arg upa;
13001 struct got_object_id *merge_commit_id = NULL;
13002 char *branch_name = NULL;
13003 int *pack_fds = NULL;
13005 memset(&upa, 0, sizeof(upa));
13007 while ((ch = getopt(argc, argv, "acn")) != -1) {
13008 switch (ch) {
13009 case 'a':
13010 abort_merge = 1;
13011 break;
13012 case 'c':
13013 continue_merge = 1;
13014 break;
13015 case 'n':
13016 interrupt_merge = 1;
13017 break;
13018 default:
13019 usage_merge();
13020 /* NOTREACHED */
13024 argc -= optind;
13025 argv += optind;
13027 #ifndef PROFILE
13028 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13029 "unveil", NULL) == -1)
13030 err(1, "pledge");
13031 #endif
13033 if (abort_merge && continue_merge)
13034 option_conflict('a', 'c');
13035 if (abort_merge || continue_merge) {
13036 if (argc != 0)
13037 usage_merge();
13038 } else if (argc != 1)
13039 usage_merge();
13041 cwd = getcwd(NULL, 0);
13042 if (cwd == NULL) {
13043 error = got_error_from_errno("getcwd");
13044 goto done;
13047 error = got_repo_pack_fds_open(&pack_fds);
13048 if (error != NULL)
13049 goto done;
13051 error = got_worktree_open(&worktree, cwd);
13052 if (error) {
13053 if (error->code == GOT_ERR_NOT_WORKTREE)
13054 error = wrap_not_worktree_error(error,
13055 "merge", cwd);
13056 goto done;
13059 error = got_repo_open(&repo,
13060 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13061 pack_fds);
13062 if (error != NULL)
13063 goto done;
13065 if (worktree != NULL) {
13066 error = worktree_has_logmsg_ref("merge", worktree, repo);
13067 if (error)
13068 goto done;
13071 error = apply_unveil(got_repo_get_path(repo), 0,
13072 worktree ? got_worktree_get_root_path(worktree) : NULL);
13073 if (error)
13074 goto done;
13076 error = check_rebase_or_histedit_in_progress(worktree);
13077 if (error)
13078 goto done;
13080 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13081 repo);
13082 if (error)
13083 goto done;
13085 if (abort_merge) {
13086 if (!merge_in_progress) {
13087 error = got_error(GOT_ERR_NOT_MERGING);
13088 goto done;
13090 error = got_worktree_merge_continue(&branch_name,
13091 &branch_tip, &fileindex, worktree, repo);
13092 if (error)
13093 goto done;
13094 error = got_worktree_merge_abort(worktree, fileindex, repo,
13095 abort_progress, &upa);
13096 if (error)
13097 goto done;
13098 printf("Merge of %s aborted\n", branch_name);
13099 goto done; /* nothing else to do */
13102 error = get_author(&author, repo, worktree);
13103 if (error)
13104 goto done;
13106 if (continue_merge) {
13107 if (!merge_in_progress) {
13108 error = got_error(GOT_ERR_NOT_MERGING);
13109 goto done;
13111 error = got_worktree_merge_continue(&branch_name,
13112 &branch_tip, &fileindex, worktree, repo);
13113 if (error)
13114 goto done;
13115 } else {
13116 error = got_ref_open(&branch, repo, argv[0], 0);
13117 if (error != NULL)
13118 goto done;
13119 branch_name = strdup(got_ref_get_name(branch));
13120 if (branch_name == NULL) {
13121 error = got_error_from_errno("strdup");
13122 goto done;
13124 error = got_ref_resolve(&branch_tip, repo, branch);
13125 if (error)
13126 goto done;
13129 error = got_ref_open(&wt_branch, repo,
13130 got_worktree_get_head_ref_name(worktree), 0);
13131 if (error)
13132 goto done;
13133 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13134 if (error)
13135 goto done;
13136 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13137 wt_branch_tip, branch_tip, 0, repo,
13138 check_cancelled, NULL);
13139 if (error && error->code != GOT_ERR_ANCESTRY)
13140 goto done;
13142 if (!continue_merge) {
13143 error = check_path_prefix(wt_branch_tip, branch_tip,
13144 got_worktree_get_path_prefix(worktree),
13145 GOT_ERR_MERGE_PATH, repo);
13146 if (error)
13147 goto done;
13148 if (yca_id) {
13149 error = check_same_branch(wt_branch_tip, branch,
13150 yca_id, repo);
13151 if (error) {
13152 if (error->code != GOT_ERR_ANCESTRY)
13153 goto done;
13154 error = NULL;
13155 } else {
13156 static char msg[512];
13157 snprintf(msg, sizeof(msg),
13158 "cannot create a merge commit because "
13159 "%s is based on %s; %s can be integrated "
13160 "with 'got integrate' instead", branch_name,
13161 got_worktree_get_head_ref_name(worktree),
13162 branch_name);
13163 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13164 goto done;
13167 error = got_worktree_merge_prepare(&fileindex, worktree,
13168 branch, repo);
13169 if (error)
13170 goto done;
13172 error = got_worktree_merge_branch(worktree, fileindex,
13173 yca_id, branch_tip, repo, update_progress, &upa,
13174 check_cancelled, NULL);
13175 if (error)
13176 goto done;
13177 print_merge_progress_stats(&upa);
13178 if (!upa.did_something) {
13179 error = got_worktree_merge_abort(worktree, fileindex,
13180 repo, abort_progress, &upa);
13181 if (error)
13182 goto done;
13183 printf("Already up-to-date\n");
13184 goto done;
13188 if (interrupt_merge) {
13189 error = got_worktree_merge_postpone(worktree, fileindex);
13190 if (error)
13191 goto done;
13192 printf("Merge of %s interrupted on request\n", branch_name);
13193 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13194 upa.not_deleted > 0 || upa.unversioned > 0) {
13195 error = got_worktree_merge_postpone(worktree, fileindex);
13196 if (error)
13197 goto done;
13198 if (upa.conflicts > 0 && upa.missing == 0 &&
13199 upa.not_deleted == 0 && upa.unversioned == 0) {
13200 error = got_error_msg(GOT_ERR_CONFLICTS,
13201 "conflicts must be resolved before merging "
13202 "can continue");
13203 } else if (upa.conflicts > 0) {
13204 error = got_error_msg(GOT_ERR_CONFLICTS,
13205 "conflicts must be resolved before merging "
13206 "can continue; changes destined for some "
13207 "files were not yet merged and "
13208 "should be merged manually if required before the "
13209 "merge operation is continued");
13210 } else {
13211 error = got_error_msg(GOT_ERR_CONFLICTS,
13212 "changes destined for some "
13213 "files were not yet merged and should be "
13214 "merged manually if required before the "
13215 "merge operation is continued");
13217 goto done;
13218 } else {
13219 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13220 fileindex, author, NULL, 1, branch_tip, branch_name,
13221 repo, continue_merge ? print_status : NULL, NULL);
13222 if (error)
13223 goto done;
13224 error = got_worktree_merge_complete(worktree, fileindex, repo);
13225 if (error)
13226 goto done;
13227 error = got_object_id_str(&id_str, merge_commit_id);
13228 if (error)
13229 goto done;
13230 printf("Merged %s into %s: %s\n", branch_name,
13231 got_worktree_get_head_ref_name(worktree),
13232 id_str);
13235 done:
13236 free(id_str);
13237 free(merge_commit_id);
13238 free(author);
13239 free(branch_tip);
13240 free(branch_name);
13241 free(yca_id);
13242 if (branch)
13243 got_ref_close(branch);
13244 if (wt_branch)
13245 got_ref_close(wt_branch);
13246 if (worktree)
13247 got_worktree_close(worktree);
13248 if (repo) {
13249 const struct got_error *close_err = got_repo_close(repo);
13250 if (error == NULL)
13251 error = close_err;
13253 if (pack_fds) {
13254 const struct got_error *pack_err =
13255 got_repo_pack_fds_close(pack_fds);
13256 if (error == NULL)
13257 error = pack_err;
13259 return error;
13262 __dead static void
13263 usage_stage(void)
13265 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13266 "[path ...]\n", getprogname());
13267 exit(1);
13270 static const struct got_error *
13271 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13272 const char *path, struct got_object_id *blob_id,
13273 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13274 int dirfd, const char *de_name)
13276 const struct got_error *err = NULL;
13277 char *id_str = NULL;
13279 if (staged_status != GOT_STATUS_ADD &&
13280 staged_status != GOT_STATUS_MODIFY &&
13281 staged_status != GOT_STATUS_DELETE)
13282 return NULL;
13284 if (staged_status == GOT_STATUS_ADD ||
13285 staged_status == GOT_STATUS_MODIFY)
13286 err = got_object_id_str(&id_str, staged_blob_id);
13287 else
13288 err = got_object_id_str(&id_str, blob_id);
13289 if (err)
13290 return err;
13292 printf("%s %c %s\n", id_str, staged_status, path);
13293 free(id_str);
13294 return NULL;
13297 static const struct got_error *
13298 cmd_stage(int argc, char *argv[])
13300 const struct got_error *error = NULL;
13301 struct got_repository *repo = NULL;
13302 struct got_worktree *worktree = NULL;
13303 char *cwd = NULL;
13304 struct got_pathlist_head paths;
13305 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13306 FILE *patch_script_file = NULL;
13307 const char *patch_script_path = NULL;
13308 struct choose_patch_arg cpa;
13309 int *pack_fds = NULL;
13311 TAILQ_INIT(&paths);
13313 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13314 switch (ch) {
13315 case 'F':
13316 patch_script_path = optarg;
13317 break;
13318 case 'l':
13319 list_stage = 1;
13320 break;
13321 case 'p':
13322 pflag = 1;
13323 break;
13324 case 'S':
13325 allow_bad_symlinks = 1;
13326 break;
13327 default:
13328 usage_stage();
13329 /* NOTREACHED */
13333 argc -= optind;
13334 argv += optind;
13336 #ifndef PROFILE
13337 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13338 "unveil", NULL) == -1)
13339 err(1, "pledge");
13340 #endif
13341 if (list_stage && (pflag || patch_script_path))
13342 errx(1, "-l option cannot be used with other options");
13343 if (patch_script_path && !pflag)
13344 errx(1, "-F option can only be used together with -p option");
13346 cwd = getcwd(NULL, 0);
13347 if (cwd == NULL) {
13348 error = got_error_from_errno("getcwd");
13349 goto done;
13352 error = got_repo_pack_fds_open(&pack_fds);
13353 if (error != NULL)
13354 goto done;
13356 error = got_worktree_open(&worktree, cwd);
13357 if (error) {
13358 if (error->code == GOT_ERR_NOT_WORKTREE)
13359 error = wrap_not_worktree_error(error, "stage", cwd);
13360 goto done;
13363 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13364 NULL, pack_fds);
13365 if (error != NULL)
13366 goto done;
13368 if (patch_script_path) {
13369 patch_script_file = fopen(patch_script_path, "re");
13370 if (patch_script_file == NULL) {
13371 error = got_error_from_errno2("fopen",
13372 patch_script_path);
13373 goto done;
13376 error = apply_unveil(got_repo_get_path(repo), 0,
13377 got_worktree_get_root_path(worktree));
13378 if (error)
13379 goto done;
13381 error = check_merge_in_progress(worktree, repo);
13382 if (error)
13383 goto done;
13385 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13386 if (error)
13387 goto done;
13389 if (list_stage)
13390 error = got_worktree_status(worktree, &paths, repo, 0,
13391 print_stage, NULL, check_cancelled, NULL);
13392 else {
13393 cpa.patch_script_file = patch_script_file;
13394 cpa.action = "stage";
13395 error = got_worktree_stage(worktree, &paths,
13396 pflag ? NULL : print_status, NULL,
13397 pflag ? choose_patch : NULL, &cpa,
13398 allow_bad_symlinks, repo);
13400 done:
13401 if (patch_script_file && fclose(patch_script_file) == EOF &&
13402 error == NULL)
13403 error = got_error_from_errno2("fclose", patch_script_path);
13404 if (repo) {
13405 const struct got_error *close_err = got_repo_close(repo);
13406 if (error == NULL)
13407 error = close_err;
13409 if (worktree)
13410 got_worktree_close(worktree);
13411 if (pack_fds) {
13412 const struct got_error *pack_err =
13413 got_repo_pack_fds_close(pack_fds);
13414 if (error == NULL)
13415 error = pack_err;
13417 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13418 free(cwd);
13419 return error;
13422 __dead static void
13423 usage_unstage(void)
13425 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13426 "[path ...]\n", getprogname());
13427 exit(1);
13431 static const struct got_error *
13432 cmd_unstage(int argc, char *argv[])
13434 const struct got_error *error = NULL;
13435 struct got_repository *repo = NULL;
13436 struct got_worktree *worktree = NULL;
13437 char *cwd = NULL;
13438 struct got_pathlist_head paths;
13439 int ch, pflag = 0;
13440 struct got_update_progress_arg upa;
13441 FILE *patch_script_file = NULL;
13442 const char *patch_script_path = NULL;
13443 struct choose_patch_arg cpa;
13444 int *pack_fds = NULL;
13446 TAILQ_INIT(&paths);
13448 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13449 switch (ch) {
13450 case 'F':
13451 patch_script_path = optarg;
13452 break;
13453 case 'p':
13454 pflag = 1;
13455 break;
13456 default:
13457 usage_unstage();
13458 /* NOTREACHED */
13462 argc -= optind;
13463 argv += optind;
13465 #ifndef PROFILE
13466 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13467 "unveil", NULL) == -1)
13468 err(1, "pledge");
13469 #endif
13470 if (patch_script_path && !pflag)
13471 errx(1, "-F option can only be used together with -p option");
13473 cwd = getcwd(NULL, 0);
13474 if (cwd == NULL) {
13475 error = got_error_from_errno("getcwd");
13476 goto done;
13479 error = got_repo_pack_fds_open(&pack_fds);
13480 if (error != NULL)
13481 goto done;
13483 error = got_worktree_open(&worktree, cwd);
13484 if (error) {
13485 if (error->code == GOT_ERR_NOT_WORKTREE)
13486 error = wrap_not_worktree_error(error, "unstage", cwd);
13487 goto done;
13490 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13491 NULL, pack_fds);
13492 if (error != NULL)
13493 goto done;
13495 if (patch_script_path) {
13496 patch_script_file = fopen(patch_script_path, "re");
13497 if (patch_script_file == NULL) {
13498 error = got_error_from_errno2("fopen",
13499 patch_script_path);
13500 goto done;
13504 error = apply_unveil(got_repo_get_path(repo), 0,
13505 got_worktree_get_root_path(worktree));
13506 if (error)
13507 goto done;
13509 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13510 if (error)
13511 goto done;
13513 cpa.patch_script_file = patch_script_file;
13514 cpa.action = "unstage";
13515 memset(&upa, 0, sizeof(upa));
13516 error = got_worktree_unstage(worktree, &paths, update_progress,
13517 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13518 if (!error)
13519 print_merge_progress_stats(&upa);
13520 done:
13521 if (patch_script_file && fclose(patch_script_file) == EOF &&
13522 error == NULL)
13523 error = got_error_from_errno2("fclose", patch_script_path);
13524 if (repo) {
13525 const struct got_error *close_err = got_repo_close(repo);
13526 if (error == NULL)
13527 error = close_err;
13529 if (worktree)
13530 got_worktree_close(worktree);
13531 if (pack_fds) {
13532 const struct got_error *pack_err =
13533 got_repo_pack_fds_close(pack_fds);
13534 if (error == NULL)
13535 error = pack_err;
13537 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13538 free(cwd);
13539 return error;
13542 __dead static void
13543 usage_cat(void)
13545 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13546 "arg ...\n", getprogname());
13547 exit(1);
13550 static const struct got_error *
13551 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13553 const struct got_error *err;
13554 struct got_blob_object *blob;
13555 int fd = -1;
13557 fd = got_opentempfd();
13558 if (fd == -1)
13559 return got_error_from_errno("got_opentempfd");
13561 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13562 if (err)
13563 goto done;
13565 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13566 done:
13567 if (fd != -1 && close(fd) == -1 && err == NULL)
13568 err = got_error_from_errno("close");
13569 if (blob)
13570 got_object_blob_close(blob);
13571 return err;
13574 static const struct got_error *
13575 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13577 const struct got_error *err;
13578 struct got_tree_object *tree;
13579 int nentries, i;
13581 err = got_object_open_as_tree(&tree, repo, id);
13582 if (err)
13583 return err;
13585 nentries = got_object_tree_get_nentries(tree);
13586 for (i = 0; i < nentries; i++) {
13587 struct got_tree_entry *te;
13588 char *id_str;
13589 if (sigint_received || sigpipe_received)
13590 break;
13591 te = got_object_tree_get_entry(tree, i);
13592 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13593 if (err)
13594 break;
13595 fprintf(outfile, "%s %.7o %s\n", id_str,
13596 got_tree_entry_get_mode(te),
13597 got_tree_entry_get_name(te));
13598 free(id_str);
13601 got_object_tree_close(tree);
13602 return err;
13605 static const struct got_error *
13606 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13608 const struct got_error *err;
13609 struct got_commit_object *commit;
13610 const struct got_object_id_queue *parent_ids;
13611 struct got_object_qid *pid;
13612 char *id_str = NULL;
13613 const char *logmsg = NULL;
13614 char gmtoff[6];
13616 err = got_object_open_as_commit(&commit, repo, id);
13617 if (err)
13618 return err;
13620 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13621 if (err)
13622 goto done;
13624 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13625 parent_ids = got_object_commit_get_parent_ids(commit);
13626 fprintf(outfile, "numparents %d\n",
13627 got_object_commit_get_nparents(commit));
13628 STAILQ_FOREACH(pid, parent_ids, entry) {
13629 char *pid_str;
13630 err = got_object_id_str(&pid_str, &pid->id);
13631 if (err)
13632 goto done;
13633 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13634 free(pid_str);
13636 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13637 got_object_commit_get_author_gmtoff(commit));
13638 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13639 got_object_commit_get_author(commit),
13640 (long long)got_object_commit_get_author_time(commit),
13641 gmtoff);
13643 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13644 got_object_commit_get_committer_gmtoff(commit));
13645 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13646 got_object_commit_get_committer(commit),
13647 (long long)got_object_commit_get_committer_time(commit),
13648 gmtoff);
13650 logmsg = got_object_commit_get_logmsg_raw(commit);
13651 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13652 fprintf(outfile, "%s", logmsg);
13653 done:
13654 free(id_str);
13655 got_object_commit_close(commit);
13656 return err;
13659 static const struct got_error *
13660 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13662 const struct got_error *err;
13663 struct got_tag_object *tag;
13664 char *id_str = NULL;
13665 const char *tagmsg = NULL;
13666 char gmtoff[6];
13668 err = got_object_open_as_tag(&tag, repo, id);
13669 if (err)
13670 return err;
13672 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13673 if (err)
13674 goto done;
13676 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13678 switch (got_object_tag_get_object_type(tag)) {
13679 case GOT_OBJ_TYPE_BLOB:
13680 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13681 GOT_OBJ_LABEL_BLOB);
13682 break;
13683 case GOT_OBJ_TYPE_TREE:
13684 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13685 GOT_OBJ_LABEL_TREE);
13686 break;
13687 case GOT_OBJ_TYPE_COMMIT:
13688 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13689 GOT_OBJ_LABEL_COMMIT);
13690 break;
13691 case GOT_OBJ_TYPE_TAG:
13692 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13693 GOT_OBJ_LABEL_TAG);
13694 break;
13695 default:
13696 break;
13699 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13700 got_object_tag_get_name(tag));
13702 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13703 got_object_tag_get_tagger_gmtoff(tag));
13704 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13705 got_object_tag_get_tagger(tag),
13706 (long long)got_object_tag_get_tagger_time(tag),
13707 gmtoff);
13709 tagmsg = got_object_tag_get_message(tag);
13710 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13711 fprintf(outfile, "%s", tagmsg);
13712 done:
13713 free(id_str);
13714 got_object_tag_close(tag);
13715 return err;
13718 static const struct got_error *
13719 cmd_cat(int argc, char *argv[])
13721 const struct got_error *error;
13722 struct got_repository *repo = NULL;
13723 struct got_worktree *worktree = NULL;
13724 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13725 const char *commit_id_str = NULL;
13726 struct got_object_id *id = NULL, *commit_id = NULL;
13727 struct got_commit_object *commit = NULL;
13728 int ch, obj_type, i, force_path = 0;
13729 struct got_reflist_head refs;
13730 int *pack_fds = NULL;
13732 TAILQ_INIT(&refs);
13734 #ifndef PROFILE
13735 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13736 NULL) == -1)
13737 err(1, "pledge");
13738 #endif
13740 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13741 switch (ch) {
13742 case 'c':
13743 commit_id_str = optarg;
13744 break;
13745 case 'P':
13746 force_path = 1;
13747 break;
13748 case 'r':
13749 repo_path = realpath(optarg, NULL);
13750 if (repo_path == NULL)
13751 return got_error_from_errno2("realpath",
13752 optarg);
13753 got_path_strip_trailing_slashes(repo_path);
13754 break;
13755 default:
13756 usage_cat();
13757 /* NOTREACHED */
13761 argc -= optind;
13762 argv += optind;
13764 cwd = getcwd(NULL, 0);
13765 if (cwd == NULL) {
13766 error = got_error_from_errno("getcwd");
13767 goto done;
13770 error = got_repo_pack_fds_open(&pack_fds);
13771 if (error != NULL)
13772 goto done;
13774 if (repo_path == NULL) {
13775 error = got_worktree_open(&worktree, cwd);
13776 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13777 goto done;
13778 if (worktree) {
13779 repo_path = strdup(
13780 got_worktree_get_repo_path(worktree));
13781 if (repo_path == NULL) {
13782 error = got_error_from_errno("strdup");
13783 goto done;
13786 /* Release work tree lock. */
13787 got_worktree_close(worktree);
13788 worktree = NULL;
13792 if (repo_path == NULL) {
13793 repo_path = strdup(cwd);
13794 if (repo_path == NULL)
13795 return got_error_from_errno("strdup");
13798 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13799 free(repo_path);
13800 if (error != NULL)
13801 goto done;
13803 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13804 if (error)
13805 goto done;
13807 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13808 if (error)
13809 goto done;
13811 if (commit_id_str == NULL)
13812 commit_id_str = GOT_REF_HEAD;
13813 error = got_repo_match_object_id(&commit_id, NULL,
13814 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13815 if (error)
13816 goto done;
13818 error = got_object_open_as_commit(&commit, repo, commit_id);
13819 if (error)
13820 goto done;
13822 for (i = 0; i < argc; i++) {
13823 if (force_path) {
13824 error = got_object_id_by_path(&id, repo, commit,
13825 argv[i]);
13826 if (error)
13827 break;
13828 } else {
13829 error = got_repo_match_object_id(&id, &label, argv[i],
13830 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13831 repo);
13832 if (error) {
13833 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13834 error->code != GOT_ERR_NOT_REF)
13835 break;
13836 error = got_object_id_by_path(&id, repo,
13837 commit, argv[i]);
13838 if (error)
13839 break;
13843 error = got_object_get_type(&obj_type, repo, id);
13844 if (error)
13845 break;
13847 switch (obj_type) {
13848 case GOT_OBJ_TYPE_BLOB:
13849 error = cat_blob(id, repo, stdout);
13850 break;
13851 case GOT_OBJ_TYPE_TREE:
13852 error = cat_tree(id, repo, stdout);
13853 break;
13854 case GOT_OBJ_TYPE_COMMIT:
13855 error = cat_commit(id, repo, stdout);
13856 break;
13857 case GOT_OBJ_TYPE_TAG:
13858 error = cat_tag(id, repo, stdout);
13859 break;
13860 default:
13861 error = got_error(GOT_ERR_OBJ_TYPE);
13862 break;
13864 if (error)
13865 break;
13866 free(label);
13867 label = NULL;
13868 free(id);
13869 id = NULL;
13871 done:
13872 free(label);
13873 free(id);
13874 free(commit_id);
13875 if (commit)
13876 got_object_commit_close(commit);
13877 if (worktree)
13878 got_worktree_close(worktree);
13879 if (repo) {
13880 const struct got_error *close_err = got_repo_close(repo);
13881 if (error == NULL)
13882 error = close_err;
13884 if (pack_fds) {
13885 const struct got_error *pack_err =
13886 got_repo_pack_fds_close(pack_fds);
13887 if (error == NULL)
13888 error = pack_err;
13891 got_ref_list_free(&refs);
13892 return error;
13895 __dead static void
13896 usage_info(void)
13898 fprintf(stderr, "usage: %s info [path ...]\n",
13899 getprogname());
13900 exit(1);
13903 static const struct got_error *
13904 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13905 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13906 struct got_object_id *commit_id)
13908 const struct got_error *err = NULL;
13909 char *id_str = NULL;
13910 char datebuf[128];
13911 struct tm mytm, *tm;
13912 struct got_pathlist_head *paths = arg;
13913 struct got_pathlist_entry *pe;
13916 * Clear error indication from any of the path arguments which
13917 * would cause this file index entry to be displayed.
13919 TAILQ_FOREACH(pe, paths, entry) {
13920 if (got_path_cmp(path, pe->path, strlen(path),
13921 pe->path_len) == 0 ||
13922 got_path_is_child(path, pe->path, pe->path_len))
13923 pe->data = NULL; /* no error */
13926 printf(GOT_COMMIT_SEP_STR);
13927 if (S_ISLNK(mode))
13928 printf("symlink: %s\n", path);
13929 else if (S_ISREG(mode)) {
13930 printf("file: %s\n", path);
13931 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13932 } else if (S_ISDIR(mode))
13933 printf("directory: %s\n", path);
13934 else
13935 printf("something: %s\n", path);
13937 tm = localtime_r(&mtime, &mytm);
13938 if (tm == NULL)
13939 return NULL;
13940 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13941 return got_error(GOT_ERR_NO_SPACE);
13942 printf("timestamp: %s\n", datebuf);
13944 if (blob_id) {
13945 err = got_object_id_str(&id_str, blob_id);
13946 if (err)
13947 return err;
13948 printf("based on blob: %s\n", id_str);
13949 free(id_str);
13952 if (staged_blob_id) {
13953 err = got_object_id_str(&id_str, staged_blob_id);
13954 if (err)
13955 return err;
13956 printf("based on staged blob: %s\n", id_str);
13957 free(id_str);
13960 if (commit_id) {
13961 err = got_object_id_str(&id_str, commit_id);
13962 if (err)
13963 return err;
13964 printf("based on commit: %s\n", id_str);
13965 free(id_str);
13968 return NULL;
13971 static const struct got_error *
13972 cmd_info(int argc, char *argv[])
13974 const struct got_error *error = NULL;
13975 struct got_worktree *worktree = NULL;
13976 char *cwd = NULL, *id_str = NULL;
13977 struct got_pathlist_head paths;
13978 char *uuidstr = NULL;
13979 int ch, show_files = 0;
13981 TAILQ_INIT(&paths);
13983 while ((ch = getopt(argc, argv, "")) != -1) {
13984 switch (ch) {
13985 default:
13986 usage_info();
13987 /* NOTREACHED */
13991 argc -= optind;
13992 argv += optind;
13994 #ifndef PROFILE
13995 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13996 NULL) == -1)
13997 err(1, "pledge");
13998 #endif
13999 cwd = getcwd(NULL, 0);
14000 if (cwd == NULL) {
14001 error = got_error_from_errno("getcwd");
14002 goto done;
14005 error = got_worktree_open(&worktree, cwd);
14006 if (error) {
14007 if (error->code == GOT_ERR_NOT_WORKTREE)
14008 error = wrap_not_worktree_error(error, "info", cwd);
14009 goto done;
14012 #ifndef PROFILE
14013 /* Remove "wpath cpath proc exec sendfd" promises. */
14014 if (pledge("stdio rpath flock unveil", NULL) == -1)
14015 err(1, "pledge");
14016 #endif
14017 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14018 if (error)
14019 goto done;
14021 if (argc >= 1) {
14022 error = get_worktree_paths_from_argv(&paths, argc, argv,
14023 worktree);
14024 if (error)
14025 goto done;
14026 show_files = 1;
14029 error = got_object_id_str(&id_str,
14030 got_worktree_get_base_commit_id(worktree));
14031 if (error)
14032 goto done;
14034 error = got_worktree_get_uuid(&uuidstr, worktree);
14035 if (error)
14036 goto done;
14038 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14039 printf("work tree base commit: %s\n", id_str);
14040 printf("work tree path prefix: %s\n",
14041 got_worktree_get_path_prefix(worktree));
14042 printf("work tree branch reference: %s\n",
14043 got_worktree_get_head_ref_name(worktree));
14044 printf("work tree UUID: %s\n", uuidstr);
14045 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14047 if (show_files) {
14048 struct got_pathlist_entry *pe;
14049 TAILQ_FOREACH(pe, &paths, entry) {
14050 if (pe->path_len == 0)
14051 continue;
14053 * Assume this path will fail. This will be corrected
14054 * in print_path_info() in case the path does suceeed.
14056 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14058 error = got_worktree_path_info(worktree, &paths,
14059 print_path_info, &paths, check_cancelled, NULL);
14060 if (error)
14061 goto done;
14062 TAILQ_FOREACH(pe, &paths, entry) {
14063 if (pe->data != NULL) {
14064 const struct got_error *perr;
14066 perr = pe->data;
14067 error = got_error_fmt(perr->code, "%s",
14068 pe->path);
14069 break;
14073 done:
14074 if (worktree)
14075 got_worktree_close(worktree);
14076 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14077 free(cwd);
14078 free(id_str);
14079 free(uuidstr);
14080 return error;