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"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 static volatile sig_atomic_t sigint_received;
72 static volatile sig_atomic_t sigpipe_received;
74 static void
75 catch_sigint(int signo)
76 {
77 sigint_received = 1;
78 }
80 static void
81 catch_sigpipe(int signo)
82 {
83 sigpipe_received = 1;
84 }
87 struct got_cmd {
88 const char *cmd_name;
89 const struct got_error *(*cmd_main)(int, char *[]);
90 void (*cmd_usage)(void);
91 const char *cmd_alias;
92 };
94 __dead static void usage(int, int);
95 __dead static void usage_import(void);
96 __dead static void usage_clone(void);
97 __dead static void usage_fetch(void);
98 __dead static void usage_checkout(void);
99 __dead static void usage_update(void);
100 __dead static void usage_log(void);
101 __dead static void usage_diff(void);
102 __dead static void usage_blame(void);
103 __dead static void usage_tree(void);
104 __dead static void usage_status(void);
105 __dead static void usage_ref(void);
106 __dead static void usage_branch(void);
107 __dead static void usage_tag(void);
108 __dead static void usage_add(void);
109 __dead static void usage_remove(void);
110 __dead static void usage_patch(void);
111 __dead static void usage_revert(void);
112 __dead static void usage_commit(void);
113 __dead static void usage_send(void);
114 __dead static void usage_cherrypick(void);
115 __dead static void usage_backout(void);
116 __dead static void usage_rebase(void);
117 __dead static void usage_histedit(void);
118 __dead static void usage_integrate(void);
119 __dead static void usage_merge(void);
120 __dead static void usage_stage(void);
121 __dead static void usage_unstage(void);
122 __dead static void usage_cat(void);
123 __dead static void usage_info(void);
125 static const struct got_error* cmd_import(int, char *[]);
126 static const struct got_error* cmd_clone(int, char *[]);
127 static const struct got_error* cmd_fetch(int, char *[]);
128 static const struct got_error* cmd_checkout(int, char *[]);
129 static const struct got_error* cmd_update(int, char *[]);
130 static const struct got_error* cmd_log(int, char *[]);
131 static const struct got_error* cmd_diff(int, char *[]);
132 static const struct got_error* cmd_blame(int, char *[]);
133 static const struct got_error* cmd_tree(int, char *[]);
134 static const struct got_error* cmd_status(int, char *[]);
135 static const struct got_error* cmd_ref(int, char *[]);
136 static const struct got_error* cmd_branch(int, char *[]);
137 static const struct got_error* cmd_tag(int, char *[]);
138 static const struct got_error* cmd_add(int, char *[]);
139 static const struct got_error* cmd_remove(int, char *[]);
140 static const struct got_error* cmd_patch(int, char *[]);
141 static const struct got_error* cmd_revert(int, char *[]);
142 static const struct got_error* cmd_commit(int, char *[]);
143 static const struct got_error* cmd_send(int, char *[]);
144 static const struct got_error* cmd_cherrypick(int, char *[]);
145 static const struct got_error* cmd_backout(int, char *[]);
146 static const struct got_error* cmd_rebase(int, char *[]);
147 static const struct got_error* cmd_histedit(int, char *[]);
148 static const struct got_error* cmd_integrate(int, char *[]);
149 static const struct got_error* cmd_merge(int, char *[]);
150 static const struct got_error* cmd_stage(int, char *[]);
151 static const struct got_error* cmd_unstage(int, char *[]);
152 static const struct got_error* cmd_cat(int, char *[]);
153 static const struct got_error* cmd_info(int, char *[]);
155 static const struct got_cmd got_commands[] = {
156 { "import", cmd_import, usage_import, "im" },
157 { "clone", cmd_clone, usage_clone, "cl" },
158 { "fetch", cmd_fetch, usage_fetch, "fe" },
159 { "checkout", cmd_checkout, usage_checkout, "co" },
160 { "update", cmd_update, usage_update, "up" },
161 { "log", cmd_log, usage_log, "" },
162 { "diff", cmd_diff, usage_diff, "di" },
163 { "blame", cmd_blame, usage_blame, "bl" },
164 { "tree", cmd_tree, usage_tree, "tr" },
165 { "status", cmd_status, usage_status, "st" },
166 { "ref", cmd_ref, usage_ref, "" },
167 { "branch", cmd_branch, usage_branch, "br" },
168 { "tag", cmd_tag, usage_tag, "" },
169 { "add", cmd_add, usage_add, "" },
170 { "remove", cmd_remove, usage_remove, "rm" },
171 { "patch", cmd_patch, usage_patch, "pa" },
172 { "revert", cmd_revert, usage_revert, "rv" },
173 { "commit", cmd_commit, usage_commit, "ci" },
174 { "send", cmd_send, usage_send, "se" },
175 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
176 { "backout", cmd_backout, usage_backout, "bo" },
177 { "rebase", cmd_rebase, usage_rebase, "rb" },
178 { "histedit", cmd_histedit, usage_histedit, "he" },
179 { "integrate", cmd_integrate, usage_integrate,"ig" },
180 { "merge", cmd_merge, usage_merge, "mg" },
181 { "stage", cmd_stage, usage_stage, "sg" },
182 { "unstage", cmd_unstage, usage_unstage, "ug" },
183 { "cat", cmd_cat, usage_cat, "" },
184 { "info", cmd_info, usage_info, "" },
185 };
187 static void
188 list_commands(FILE *fp)
190 size_t i;
192 fprintf(fp, "commands:");
193 for (i = 0; i < nitems(got_commands); i++) {
194 const struct got_cmd *cmd = &got_commands[i];
195 fprintf(fp, " %s", cmd->cmd_name);
197 fputc('\n', fp);
200 __dead static void
201 option_conflict(char a, char b)
203 errx(1, "-%c and -%c options are mutually exclusive", a, b);
206 int
207 main(int argc, char *argv[])
209 const struct got_cmd *cmd;
210 size_t i;
211 int ch;
212 int hflag = 0, Vflag = 0;
213 static const struct option longopts[] = {
214 { "version", no_argument, NULL, 'V' },
215 { NULL, 0, NULL, 0 }
216 };
218 setlocale(LC_CTYPE, "");
220 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
221 switch (ch) {
222 case 'h':
223 hflag = 1;
224 break;
225 case 'V':
226 Vflag = 1;
227 break;
228 default:
229 usage(hflag, 1);
230 /* NOTREACHED */
234 argc -= optind;
235 argv += optind;
236 optind = 1;
237 optreset = 1;
239 if (Vflag) {
240 got_version_print_str();
241 return 0;
244 if (argc <= 0)
245 usage(hflag, hflag ? 0 : 1);
247 signal(SIGINT, catch_sigint);
248 signal(SIGPIPE, catch_sigpipe);
250 for (i = 0; i < nitems(got_commands); i++) {
251 const struct got_error *error;
253 cmd = &got_commands[i];
255 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
256 strcmp(cmd->cmd_alias, argv[0]) != 0)
257 continue;
259 if (hflag)
260 cmd->cmd_usage();
262 error = cmd->cmd_main(argc, argv);
263 if (error && error->code != GOT_ERR_CANCELLED &&
264 error->code != GOT_ERR_PRIVSEP_EXIT &&
265 !(sigpipe_received &&
266 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
267 !(sigint_received &&
268 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
269 fflush(stdout);
270 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
271 return 1;
274 return 0;
277 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
278 list_commands(stderr);
279 return 1;
282 __dead static void
283 usage(int hflag, int status)
285 FILE *fp = (status == 0) ? stdout : stderr;
287 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
288 getprogname());
289 if (hflag)
290 list_commands(fp);
291 exit(status);
294 static const struct got_error *
295 get_editor(char **abspath)
297 const struct got_error *err = NULL;
298 const char *editor;
300 *abspath = NULL;
302 editor = getenv("VISUAL");
303 if (editor == NULL)
304 editor = getenv("EDITOR");
306 if (editor) {
307 err = got_path_find_prog(abspath, editor);
308 if (err)
309 return err;
312 if (*abspath == NULL) {
313 *abspath = strdup("/usr/bin/vi");
314 if (*abspath == NULL)
315 return got_error_from_errno("strdup");
318 return NULL;
321 static const struct got_error *
322 apply_unveil(const char *repo_path, int repo_read_only,
323 const char *worktree_path)
325 const struct got_error *err;
327 #ifdef PROFILE
328 if (unveil("gmon.out", "rwc") != 0)
329 return got_error_from_errno2("unveil", "gmon.out");
330 #endif
331 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
332 return got_error_from_errno2("unveil", repo_path);
334 if (worktree_path && unveil(worktree_path, "rwc") != 0)
335 return got_error_from_errno2("unveil", worktree_path);
337 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
338 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
340 err = got_privsep_unveil_exec_helpers();
341 if (err != NULL)
342 return err;
344 if (unveil(NULL, NULL) != 0)
345 return got_error_from_errno("unveil");
347 return NULL;
350 __dead static void
351 usage_import(void)
353 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
354 "[-r repository-path] directory\n", getprogname());
355 exit(1);
358 static int
359 spawn_editor(const char *editor, const char *file)
361 pid_t pid;
362 sig_t sighup, sigint, sigquit;
363 int st = -1;
365 sighup = signal(SIGHUP, SIG_IGN);
366 sigint = signal(SIGINT, SIG_IGN);
367 sigquit = signal(SIGQUIT, SIG_IGN);
369 switch (pid = fork()) {
370 case -1:
371 goto doneediting;
372 case 0:
373 execl(editor, editor, file, (char *)NULL);
374 _exit(127);
377 while (waitpid(pid, &st, 0) == -1)
378 if (errno != EINTR)
379 break;
381 doneediting:
382 (void)signal(SIGHUP, sighup);
383 (void)signal(SIGINT, sigint);
384 (void)signal(SIGQUIT, sigquit);
386 if (!WIFEXITED(st)) {
387 errno = EINTR;
388 return -1;
391 return WEXITSTATUS(st);
394 static const struct got_error *
395 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
397 const struct got_error *err = NULL;
398 char *line = NULL;
399 size_t linesize = 0;
401 *logmsg = NULL;
402 *len = 0;
404 if (fseeko(fp, 0L, SEEK_SET) == -1)
405 return got_error_from_errno("fseeko");
407 *logmsg = malloc(filesize + 1);
408 if (*logmsg == NULL)
409 return got_error_from_errno("malloc");
410 (*logmsg)[0] = '\0';
412 while (getline(&line, &linesize, fp) != -1) {
413 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
414 continue; /* remove comments and leading empty lines */
415 *len = strlcat(*logmsg, line, filesize + 1);
416 if (*len >= filesize + 1) {
417 err = got_error(GOT_ERR_NO_SPACE);
418 goto done;
421 if (ferror(fp)) {
422 err = got_ferror(fp, GOT_ERR_IO);
423 goto done;
426 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
427 (*logmsg)[*len - 1] = '\0';
428 (*len)--;
430 done:
431 free(line);
432 if (err) {
433 free(*logmsg);
434 *logmsg = NULL;
435 *len = 0;
437 return err;
440 static const struct got_error *
441 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
442 const char *initial_content, size_t initial_content_len,
443 int require_modification)
445 const struct got_error *err = NULL;
446 struct stat st, st2;
447 FILE *fp = NULL;
448 size_t logmsg_len;
450 *logmsg = NULL;
452 if (stat(logmsg_path, &st) == -1)
453 return got_error_from_errno2("stat", logmsg_path);
455 if (spawn_editor(editor, logmsg_path) == -1)
456 return got_error_from_errno("failed spawning editor");
458 if (require_modification) {
459 struct timespec timeout;
461 timeout.tv_sec = 0;
462 timeout.tv_nsec = 1;
463 nanosleep(&timeout, NULL);
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno2("stat", logmsg_path);
469 if (require_modification && st.st_size == st2.st_size &&
470 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 fp = fopen(logmsg_path, "re");
475 if (fp == NULL) {
476 err = got_error_from_errno("fopen");
477 goto done;
480 /* strip comments and leading/trailing newlines */
481 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
482 if (err)
483 goto done;
484 if (logmsg_len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 done:
490 if (fp && fclose(fp) == EOF && err == NULL)
491 err = got_error_from_errno("fclose");
492 if (err) {
493 free(*logmsg);
494 *logmsg = NULL;
496 return err;
499 static const struct got_error *
500 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
501 const char *path_dir, const char *branch_name)
503 char *initial_content = NULL;
504 const struct got_error *err = NULL;
505 int initial_content_len;
506 int fd = -1;
508 initial_content_len = asprintf(&initial_content,
509 "\n# %s to be imported to branch %s\n", path_dir,
510 branch_name);
511 if (initial_content_len == -1)
512 return got_error_from_errno("asprintf");
514 err = got_opentemp_named_fd(logmsg_path, &fd,
515 GOT_TMPDIR_STR "/got-importmsg", "");
516 if (err)
517 goto done;
519 if (write(fd, initial_content, initial_content_len) == -1) {
520 err = got_error_from_errno2("write", *logmsg_path);
521 goto done;
523 if (close(fd) == -1) {
524 err = got_error_from_errno2("close", *logmsg_path);
525 goto done;
527 fd = -1;
529 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
530 initial_content_len, 1);
531 done:
532 if (fd != -1 && close(fd) == -1 && err == NULL)
533 err = got_error_from_errno2("close", *logmsg_path);
534 free(initial_content);
535 if (err) {
536 free(*logmsg_path);
537 *logmsg_path = NULL;
539 return err;
542 static const struct got_error *
543 import_progress(void *arg, const char *path)
545 printf("A %s\n", path);
546 return NULL;
549 static const struct got_error *
550 valid_author(const char *author)
552 const char *email = author;
554 /*
555 * Git' expects the author (or committer) to be in the form
556 * "name <email>", which are mostly free form (see the
557 * "committer" description in git-fast-import(1)). We're only
558 * doing this to avoid git's object parser breaking on commits
559 * we create.
560 */
562 while (*author && *author != '\n' && *author != '<' && *author != '>')
563 author++;
564 if (author != email && *author == '<' && *(author - 1) != ' ')
565 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
566 "between author name and email required", email);
567 if (*author++ != '<')
568 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
569 while (*author && *author != '\n' && *author != '<' && *author != '>')
570 author++;
571 if (strcmp(author, ">") != 0)
572 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
573 return NULL;
576 static const struct got_error *
577 get_author(char **author, struct got_repository *repo,
578 struct got_worktree *worktree)
580 const struct got_error *err = NULL;
581 const char *got_author = NULL, *name, *email;
582 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
584 *author = NULL;
586 if (worktree)
587 worktree_conf = got_worktree_get_gotconfig(worktree);
588 repo_conf = got_repo_get_gotconfig(repo);
590 /*
591 * Priority of potential author information sources, from most
592 * significant to least significant:
593 * 1) work tree's .got/got.conf file
594 * 2) repository's got.conf file
595 * 3) repository's git config file
596 * 4) environment variables
597 * 5) global git config files (in user's home directory or /etc)
598 */
600 if (worktree_conf)
601 got_author = got_gotconfig_get_author(worktree_conf);
602 if (got_author == NULL)
603 got_author = got_gotconfig_get_author(repo_conf);
604 if (got_author == NULL) {
605 name = got_repo_get_gitconfig_author_name(repo);
606 email = got_repo_get_gitconfig_author_email(repo);
607 if (name && email) {
608 if (asprintf(author, "%s <%s>", name, email) == -1)
609 return got_error_from_errno("asprintf");
610 return NULL;
613 got_author = getenv("GOT_AUTHOR");
614 if (got_author == NULL) {
615 name = got_repo_get_global_gitconfig_author_name(repo);
616 email = got_repo_get_global_gitconfig_author_email(
617 repo);
618 if (name && email) {
619 if (asprintf(author, "%s <%s>", name, email)
620 == -1)
621 return got_error_from_errno("asprintf");
622 return NULL;
624 /* TODO: Look up user in password database? */
625 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
629 *author = strdup(got_author);
630 if (*author == NULL)
631 return got_error_from_errno("strdup");
633 err = valid_author(*author);
634 if (err) {
635 free(*author);
636 *author = NULL;
638 return err;
641 static const struct got_error *
642 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
643 struct got_worktree *worktree)
645 const char *got_allowed_signers = NULL;
646 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
648 *allowed_signers = NULL;
650 if (worktree)
651 worktree_conf = got_worktree_get_gotconfig(worktree);
652 repo_conf = got_repo_get_gotconfig(repo);
654 /*
655 * Priority of potential author information sources, from most
656 * significant to least significant:
657 * 1) work tree's .got/got.conf file
658 * 2) repository's got.conf file
659 */
661 if (worktree_conf)
662 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
663 worktree_conf);
664 if (got_allowed_signers == NULL)
665 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
666 repo_conf);
668 if (got_allowed_signers) {
669 *allowed_signers = strdup(got_allowed_signers);
670 if (*allowed_signers == NULL)
671 return got_error_from_errno("strdup");
673 return NULL;
676 static const struct got_error *
677 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
678 struct got_worktree *worktree)
680 const char *got_revoked_signers = NULL;
681 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
683 *revoked_signers = NULL;
685 if (worktree)
686 worktree_conf = got_worktree_get_gotconfig(worktree);
687 repo_conf = got_repo_get_gotconfig(repo);
689 /*
690 * Priority of potential author information sources, from most
691 * significant to least significant:
692 * 1) work tree's .got/got.conf file
693 * 2) repository's got.conf file
694 */
696 if (worktree_conf)
697 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
698 worktree_conf);
699 if (got_revoked_signers == NULL)
700 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
701 repo_conf);
703 if (got_revoked_signers) {
704 *revoked_signers = strdup(got_revoked_signers);
705 if (*revoked_signers == NULL)
706 return got_error_from_errno("strdup");
708 return NULL;
711 static const char *
712 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
714 const char *got_signer_id = NULL;
715 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
717 if (worktree)
718 worktree_conf = got_worktree_get_gotconfig(worktree);
719 repo_conf = got_repo_get_gotconfig(repo);
721 /*
722 * Priority of potential author information sources, from most
723 * significant to least significant:
724 * 1) work tree's .got/got.conf file
725 * 2) repository's got.conf file
726 */
728 if (worktree_conf)
729 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
730 if (got_signer_id == NULL)
731 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
733 return got_signer_id;
736 static const struct got_error *
737 get_gitconfig_path(char **gitconfig_path)
739 const char *homedir = getenv("HOME");
741 *gitconfig_path = NULL;
742 if (homedir) {
743 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
744 return got_error_from_errno("asprintf");
747 return NULL;
750 static const struct got_error *
751 cmd_import(int argc, char *argv[])
753 const struct got_error *error = NULL;
754 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
755 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
756 const char *branch_name = NULL;
757 char *id_str = NULL, *logmsg_path = NULL;
758 char refname[PATH_MAX] = "refs/heads/";
759 struct got_repository *repo = NULL;
760 struct got_reference *branch_ref = NULL, *head_ref = NULL;
761 struct got_object_id *new_commit_id = NULL;
762 int ch, n = 0;
763 struct got_pathlist_head ignores;
764 struct got_pathlist_entry *pe;
765 int preserve_logmsg = 0;
766 int *pack_fds = NULL;
768 TAILQ_INIT(&ignores);
770 #ifndef PROFILE
771 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
772 "unveil",
773 NULL) == -1)
774 err(1, "pledge");
775 #endif
777 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
778 switch (ch) {
779 case 'b':
780 branch_name = optarg;
781 break;
782 case 'I':
783 if (optarg[0] == '\0')
784 break;
785 error = got_pathlist_insert(&pe, &ignores, optarg,
786 NULL);
787 if (error)
788 goto done;
789 break;
790 case 'm':
791 logmsg = strdup(optarg);
792 if (logmsg == NULL) {
793 error = got_error_from_errno("strdup");
794 goto done;
796 break;
797 case 'r':
798 repo_path = realpath(optarg, NULL);
799 if (repo_path == NULL) {
800 error = got_error_from_errno2("realpath",
801 optarg);
802 goto done;
804 break;
805 default:
806 usage_import();
807 /* NOTREACHED */
811 argc -= optind;
812 argv += optind;
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name && branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
846 if (error && error->code != GOT_ERR_NOT_REF)
847 goto done;
849 if (branch_name)
850 n = strlcat(refname, branch_name, sizeof(refname));
851 else if (head_ref && got_ref_is_symbolic(head_ref))
852 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
853 sizeof(refname));
854 else
855 n = strlcat(refname, "main", sizeof(refname));
856 if (n >= sizeof(refname)) {
857 error = got_error(GOT_ERR_NO_SPACE);
858 goto done;
861 error = got_ref_open(&branch_ref, repo, refname, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF)
864 goto done;
865 } else {
866 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
867 "import target branch already exists");
868 goto done;
871 path_dir = realpath(argv[0], NULL);
872 if (path_dir == NULL) {
873 error = got_error_from_errno2("realpath", argv[0]);
874 goto done;
876 got_path_strip_trailing_slashes(path_dir);
878 /*
879 * unveil(2) traverses exec(2); if an editor is used we have
880 * to apply unveil after the log message has been written.
881 */
882 if (logmsg == NULL || *logmsg == '\0') {
883 error = get_editor(&editor);
884 if (error)
885 goto done;
886 free(logmsg);
887 error = collect_import_msg(&logmsg, &logmsg_path, editor,
888 path_dir, refname);
889 if (error) {
890 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
891 logmsg_path != NULL)
892 preserve_logmsg = 1;
893 goto done;
897 if (unveil(path_dir, "r") != 0) {
898 error = got_error_from_errno2("unveil", path_dir);
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_repo_import(&new_commit_id, path_dir, logmsg,
912 author, &ignores, repo, import_progress, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_write(branch_ref, repo);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_object_id_str(&id_str, new_commit_id);
934 if (error) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
941 if (error) {
942 if (error->code != GOT_ERR_NOT_REF) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
949 branch_ref);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_write(head_ref, repo);
957 if (error) {
958 if (logmsg_path)
959 preserve_logmsg = 1;
960 goto done;
964 printf("Created branch %s with commit %s\n",
965 got_ref_get_name(branch_ref), id_str);
966 done:
967 if (pack_fds) {
968 const struct got_error *pack_err =
969 got_repo_pack_fds_close(pack_fds);
970 if (error == NULL)
971 error = pack_err;
973 if (repo) {
974 const struct got_error *close_err = got_repo_close(repo);
975 if (error == NULL)
976 error = close_err;
978 if (preserve_logmsg) {
979 fprintf(stderr, "%s: log message preserved in %s\n",
980 getprogname(), logmsg_path);
981 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
982 error = got_error_from_errno2("unlink", logmsg_path);
983 free(logmsg);
984 free(logmsg_path);
985 free(repo_path);
986 free(editor);
987 free(new_commit_id);
988 free(id_str);
989 free(author);
990 free(gitconfig_path);
991 if (branch_ref)
992 got_ref_close(branch_ref);
993 if (head_ref)
994 got_ref_close(head_ref);
995 return error;
998 __dead static void
999 usage_clone(void)
1001 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1002 "repository-URL [directory]\n", getprogname());
1003 exit(1);
1006 struct got_fetch_progress_arg {
1007 char last_scaled_size[FMT_SCALED_STRSIZE];
1008 int last_p_indexed;
1009 int last_p_resolved;
1010 int verbosity;
1012 struct got_repository *repo;
1014 int create_configs;
1015 int configs_created;
1016 struct {
1017 struct got_pathlist_head *symrefs;
1018 struct got_pathlist_head *wanted_branches;
1019 struct got_pathlist_head *wanted_refs;
1020 const char *proto;
1021 const char *host;
1022 const char *port;
1023 const char *remote_repo_path;
1024 const char *git_url;
1025 int fetch_all_branches;
1026 int mirror_references;
1027 } config_info;
1030 /* XXX forward declaration */
1031 static const struct got_error *
1032 create_config_files(const char *proto, const char *host, const char *port,
1033 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1034 int mirror_references, struct got_pathlist_head *symrefs,
1035 struct got_pathlist_head *wanted_branches,
1036 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1038 static const struct got_error *
1039 fetch_progress(void *arg, const char *message, off_t packfile_size,
1040 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1042 const struct got_error *err = NULL;
1043 struct got_fetch_progress_arg *a = arg;
1044 char scaled_size[FMT_SCALED_STRSIZE];
1045 int p_indexed, p_resolved;
1046 int print_size = 0, print_indexed = 0, print_resolved = 0;
1049 * In order to allow a failed clone to be resumed with 'got fetch'
1050 * we try to create configuration files as soon as possible.
1051 * Once the server has sent information about its default branch
1052 * we have all required information.
1054 if (a->create_configs && !a->configs_created &&
1055 !TAILQ_EMPTY(a->config_info.symrefs)) {
1056 err = create_config_files(a->config_info.proto,
1057 a->config_info.host, a->config_info.port,
1058 a->config_info.remote_repo_path,
1059 a->config_info.git_url,
1060 a->config_info.fetch_all_branches,
1061 a->config_info.mirror_references,
1062 a->config_info.symrefs,
1063 a->config_info.wanted_branches,
1064 a->config_info.wanted_refs, a->repo);
1065 if (err)
1066 return err;
1067 a->configs_created = 1;
1070 if (a->verbosity < 0)
1071 return NULL;
1073 if (message && message[0] != '\0') {
1074 printf("\rserver: %s", message);
1075 fflush(stdout);
1076 return NULL;
1079 if (packfile_size > 0 || nobj_indexed > 0) {
1080 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1081 (a->last_scaled_size[0] == '\0' ||
1082 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1083 print_size = 1;
1084 if (strlcpy(a->last_scaled_size, scaled_size,
1085 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1086 return got_error(GOT_ERR_NO_SPACE);
1088 if (nobj_indexed > 0) {
1089 p_indexed = (nobj_indexed * 100) / nobj_total;
1090 if (p_indexed != a->last_p_indexed) {
1091 a->last_p_indexed = p_indexed;
1092 print_indexed = 1;
1093 print_size = 1;
1096 if (nobj_resolved > 0) {
1097 p_resolved = (nobj_resolved * 100) /
1098 (nobj_total - nobj_loose);
1099 if (p_resolved != a->last_p_resolved) {
1100 a->last_p_resolved = p_resolved;
1101 print_resolved = 1;
1102 print_indexed = 1;
1103 print_size = 1;
1108 if (print_size || print_indexed || print_resolved)
1109 printf("\r");
1110 if (print_size)
1111 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1112 if (print_indexed)
1113 printf("; indexing %d%%", p_indexed);
1114 if (print_resolved)
1115 printf("; resolving deltas %d%%", p_resolved);
1116 if (print_size || print_indexed || print_resolved)
1117 fflush(stdout);
1119 return NULL;
1122 static const struct got_error *
1123 create_symref(const char *refname, struct got_reference *target_ref,
1124 int verbosity, struct got_repository *repo)
1126 const struct got_error *err;
1127 struct got_reference *head_symref;
1129 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1130 if (err)
1131 return err;
1133 err = got_ref_write(head_symref, repo);
1134 if (err == NULL && verbosity > 0) {
1135 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1136 got_ref_get_name(target_ref));
1138 got_ref_close(head_symref);
1139 return err;
1142 static const struct got_error *
1143 list_remote_refs(struct got_pathlist_head *symrefs,
1144 struct got_pathlist_head *refs)
1146 const struct got_error *err;
1147 struct got_pathlist_entry *pe;
1149 TAILQ_FOREACH(pe, symrefs, entry) {
1150 const char *refname = pe->path;
1151 const char *targetref = pe->data;
1153 printf("%s: %s\n", refname, targetref);
1156 TAILQ_FOREACH(pe, refs, entry) {
1157 const char *refname = pe->path;
1158 struct got_object_id *id = pe->data;
1159 char *id_str;
1161 err = got_object_id_str(&id_str, id);
1162 if (err)
1163 return err;
1164 printf("%s: %s\n", refname, id_str);
1165 free(id_str);
1168 return NULL;
1171 static const struct got_error *
1172 create_ref(const char *refname, struct got_object_id *id,
1173 int verbosity, struct got_repository *repo)
1175 const struct got_error *err = NULL;
1176 struct got_reference *ref;
1177 char *id_str;
1179 err = got_object_id_str(&id_str, id);
1180 if (err)
1181 return err;
1183 err = got_ref_alloc(&ref, refname, id);
1184 if (err)
1185 goto done;
1187 err = got_ref_write(ref, repo);
1188 got_ref_close(ref);
1190 if (err == NULL && verbosity >= 0)
1191 printf("Created reference %s: %s\n", refname, id_str);
1192 done:
1193 free(id_str);
1194 return err;
1197 static int
1198 match_wanted_ref(const char *refname, const char *wanted_ref)
1200 if (strncmp(refname, "refs/", 5) != 0)
1201 return 0;
1202 refname += 5;
1205 * Prevent fetching of references that won't make any
1206 * sense outside of the remote repository's context.
1208 if (strncmp(refname, "got/", 4) == 0)
1209 return 0;
1210 if (strncmp(refname, "remotes/", 8) == 0)
1211 return 0;
1213 if (strncmp(wanted_ref, "refs/", 5) == 0)
1214 wanted_ref += 5;
1216 /* Allow prefix match. */
1217 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1218 return 1;
1220 /* Allow exact match. */
1221 return (strcmp(refname, wanted_ref) == 0);
1224 static int
1225 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1227 struct got_pathlist_entry *pe;
1229 TAILQ_FOREACH(pe, wanted_refs, entry) {
1230 if (match_wanted_ref(refname, pe->path))
1231 return 1;
1234 return 0;
1237 static const struct got_error *
1238 create_wanted_ref(const char *refname, struct got_object_id *id,
1239 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1241 const struct got_error *err;
1242 char *remote_refname;
1244 if (strncmp("refs/", refname, 5) == 0)
1245 refname += 5;
1247 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1248 remote_repo_name, refname) == -1)
1249 return got_error_from_errno("asprintf");
1251 err = create_ref(remote_refname, id, verbosity, repo);
1252 free(remote_refname);
1253 return err;
1256 static const struct got_error *
1257 create_gotconfig(const char *proto, const char *host, const char *port,
1258 const char *remote_repo_path, const char *default_branch,
1259 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1260 struct got_pathlist_head *wanted_refs, int mirror_references,
1261 struct got_repository *repo)
1263 const struct got_error *err = NULL;
1264 char *gotconfig_path = NULL;
1265 char *gotconfig = NULL;
1266 FILE *gotconfig_file = NULL;
1267 const char *branchname = NULL;
1268 char *branches = NULL, *refs = NULL;
1269 ssize_t n;
1271 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1272 struct got_pathlist_entry *pe;
1273 TAILQ_FOREACH(pe, wanted_branches, entry) {
1274 char *s;
1275 branchname = pe->path;
1276 if (strncmp(branchname, "refs/heads/", 11) == 0)
1277 branchname += 11;
1278 if (asprintf(&s, "%s\"%s\" ",
1279 branches ? branches : "", branchname) == -1) {
1280 err = got_error_from_errno("asprintf");
1281 goto done;
1283 free(branches);
1284 branches = s;
1286 } else if (!fetch_all_branches && default_branch) {
1287 branchname = default_branch;
1288 if (strncmp(branchname, "refs/heads/", 11) == 0)
1289 branchname += 11;
1290 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1291 err = got_error_from_errno("asprintf");
1292 goto done;
1295 if (!TAILQ_EMPTY(wanted_refs)) {
1296 struct got_pathlist_entry *pe;
1297 TAILQ_FOREACH(pe, wanted_refs, entry) {
1298 char *s;
1299 const char *refname = pe->path;
1300 if (strncmp(refname, "refs/", 5) == 0)
1301 branchname += 5;
1302 if (asprintf(&s, "%s\"%s\" ",
1303 refs ? refs : "", refname) == -1) {
1304 err = got_error_from_errno("asprintf");
1305 goto done;
1307 free(refs);
1308 refs = s;
1312 /* Create got.conf(5). */
1313 gotconfig_path = got_repo_get_path_gotconfig(repo);
1314 if (gotconfig_path == NULL) {
1315 err = got_error_from_errno("got_repo_get_path_gotconfig");
1316 goto done;
1318 gotconfig_file = fopen(gotconfig_path, "ae");
1319 if (gotconfig_file == NULL) {
1320 err = got_error_from_errno2("fopen", gotconfig_path);
1321 goto done;
1323 if (asprintf(&gotconfig,
1324 "remote \"%s\" {\n"
1325 "\tserver %s\n"
1326 "\tprotocol %s\n"
1327 "%s%s%s"
1328 "\trepository \"%s\"\n"
1329 "%s%s%s"
1330 "%s%s%s"
1331 "%s"
1332 "%s"
1333 "}\n",
1334 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1335 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1336 remote_repo_path, branches ? "\tbranch { " : "",
1337 branches ? branches : "", branches ? "}\n" : "",
1338 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1339 mirror_references ? "\tmirror_references yes\n" : "",
1340 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1345 if (n != strlen(gotconfig)) {
1346 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1347 goto done;
1350 done:
1351 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1352 err = got_error_from_errno2("fclose", gotconfig_path);
1353 free(gotconfig_path);
1354 free(branches);
1355 return err;
1358 static const struct got_error *
1359 create_gitconfig(const char *git_url, const char *default_branch,
1360 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1361 struct got_pathlist_head *wanted_refs, int mirror_references,
1362 struct got_repository *repo)
1364 const struct got_error *err = NULL;
1365 char *gitconfig_path = NULL;
1366 char *gitconfig = NULL;
1367 FILE *gitconfig_file = NULL;
1368 char *branches = NULL, *refs = NULL;
1369 const char *branchname;
1370 ssize_t n;
1372 /* Create a config file Git can understand. */
1373 gitconfig_path = got_repo_get_path_gitconfig(repo);
1374 if (gitconfig_path == NULL) {
1375 err = got_error_from_errno("got_repo_get_path_gitconfig");
1376 goto done;
1378 gitconfig_file = fopen(gitconfig_path, "ae");
1379 if (gitconfig_file == NULL) {
1380 err = got_error_from_errno2("fopen", gitconfig_path);
1381 goto done;
1383 if (fetch_all_branches) {
1384 if (mirror_references) {
1385 if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1387 err = got_error_from_errno("asprintf");
1388 goto done;
1390 } else if (asprintf(&branches,
1391 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1392 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 } else if (!TAILQ_EMPTY(wanted_branches)) {
1397 struct got_pathlist_entry *pe;
1398 TAILQ_FOREACH(pe, wanted_branches, entry) {
1399 char *s;
1400 branchname = pe->path;
1401 if (strncmp(branchname, "refs/heads/", 11) == 0)
1402 branchname += 11;
1403 if (mirror_references) {
1404 if (asprintf(&s,
1405 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1406 branches ? branches : "",
1407 branchname, branchname) == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 } else if (asprintf(&s,
1412 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1413 branches ? branches : "",
1414 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1415 branchname) == -1) {
1416 err = got_error_from_errno("asprintf");
1417 goto done;
1419 free(branches);
1420 branches = s;
1422 } else {
1424 * If the server specified a default branch, use just that one.
1425 * Otherwise fall back to fetching all branches on next fetch.
1427 if (default_branch) {
1428 branchname = default_branch;
1429 if (strncmp(branchname, "refs/heads/", 11) == 0)
1430 branchname += 11;
1431 } else
1432 branchname = "*"; /* fall back to all branches */
1433 if (mirror_references) {
1434 if (asprintf(&branches,
1435 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1436 branchname, branchname) == -1) {
1437 err = got_error_from_errno("asprintf");
1438 goto done;
1440 } else if (asprintf(&branches,
1441 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1442 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1443 branchname) == -1) {
1444 err = got_error_from_errno("asprintf");
1445 goto done;
1448 if (!TAILQ_EMPTY(wanted_refs)) {
1449 struct got_pathlist_entry *pe;
1450 TAILQ_FOREACH(pe, wanted_refs, entry) {
1451 char *s;
1452 const char *refname = pe->path;
1453 if (strncmp(refname, "refs/", 5) == 0)
1454 refname += 5;
1455 if (mirror_references) {
1456 if (asprintf(&s,
1457 "%s\tfetch = refs/%s:refs/%s\n",
1458 refs ? refs : "", refname, refname) == -1) {
1459 err = got_error_from_errno("asprintf");
1460 goto done;
1462 } else if (asprintf(&s,
1463 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1464 refs ? refs : "",
1465 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1466 refname) == -1) {
1467 err = got_error_from_errno("asprintf");
1468 goto done;
1470 free(refs);
1471 refs = s;
1475 if (asprintf(&gitconfig,
1476 "[remote \"%s\"]\n"
1477 "\turl = %s\n"
1478 "%s"
1479 "%s"
1480 "\tfetch = refs/tags/*:refs/tags/*\n",
1481 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1482 refs ? refs : "") == -1) {
1483 err = got_error_from_errno("asprintf");
1484 goto done;
1486 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1487 if (n != strlen(gitconfig)) {
1488 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1489 goto done;
1491 done:
1492 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1493 err = got_error_from_errno2("fclose", gitconfig_path);
1494 free(gitconfig_path);
1495 free(branches);
1496 return err;
1499 static const struct got_error *
1500 create_config_files(const char *proto, const char *host, const char *port,
1501 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1502 int mirror_references, struct got_pathlist_head *symrefs,
1503 struct got_pathlist_head *wanted_branches,
1504 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1506 const struct got_error *err = NULL;
1507 const char *default_branch = NULL;
1508 struct got_pathlist_entry *pe;
1511 * If we asked for a set of wanted branches then use the first
1512 * one of those.
1514 if (!TAILQ_EMPTY(wanted_branches)) {
1515 pe = TAILQ_FIRST(wanted_branches);
1516 default_branch = pe->path;
1517 } else {
1518 /* First HEAD ref listed by server is the default branch. */
1519 TAILQ_FOREACH(pe, symrefs, entry) {
1520 const char *refname = pe->path;
1521 const char *target = pe->data;
1523 if (strcmp(refname, GOT_REF_HEAD) != 0)
1524 continue;
1526 default_branch = target;
1527 break;
1531 /* Create got.conf(5). */
1532 err = create_gotconfig(proto, host, port, remote_repo_path,
1533 default_branch, fetch_all_branches, wanted_branches,
1534 wanted_refs, mirror_references, repo);
1535 if (err)
1536 return err;
1538 /* Create a config file Git can understand. */
1539 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1540 wanted_branches, wanted_refs, mirror_references, repo);
1543 static const struct got_error *
1544 cmd_clone(int argc, char *argv[])
1546 const struct got_error *error = NULL;
1547 const char *uri, *dirname;
1548 char *proto, *host, *port, *repo_name, *server_path;
1549 char *default_destdir = NULL, *id_str = NULL;
1550 const char *repo_path;
1551 struct got_repository *repo = NULL;
1552 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1553 struct got_pathlist_entry *pe;
1554 struct got_object_id *pack_hash = NULL;
1555 int ch, fetchfd = -1, fetchstatus;
1556 pid_t fetchpid = -1;
1557 struct got_fetch_progress_arg fpa;
1558 char *git_url = NULL;
1559 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1560 int bflag = 0, list_refs_only = 0;
1561 int *pack_fds = NULL;
1563 TAILQ_INIT(&refs);
1564 TAILQ_INIT(&symrefs);
1565 TAILQ_INIT(&wanted_branches);
1566 TAILQ_INIT(&wanted_refs);
1568 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1569 switch (ch) {
1570 case 'a':
1571 fetch_all_branches = 1;
1572 break;
1573 case 'b':
1574 error = got_pathlist_append(&wanted_branches,
1575 optarg, NULL);
1576 if (error)
1577 return error;
1578 bflag = 1;
1579 break;
1580 case 'l':
1581 list_refs_only = 1;
1582 break;
1583 case 'm':
1584 mirror_references = 1;
1585 break;
1586 case 'q':
1587 verbosity = -1;
1588 break;
1589 case 'R':
1590 error = got_pathlist_append(&wanted_refs,
1591 optarg, NULL);
1592 if (error)
1593 return error;
1594 break;
1595 case 'v':
1596 if (verbosity < 0)
1597 verbosity = 0;
1598 else if (verbosity < 3)
1599 verbosity++;
1600 break;
1601 default:
1602 usage_clone();
1603 break;
1606 argc -= optind;
1607 argv += optind;
1609 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1610 option_conflict('a', 'b');
1611 if (list_refs_only) {
1612 if (!TAILQ_EMPTY(&wanted_branches))
1613 option_conflict('l', 'b');
1614 if (fetch_all_branches)
1615 option_conflict('l', 'a');
1616 if (mirror_references)
1617 option_conflict('l', 'm');
1618 if (!TAILQ_EMPTY(&wanted_refs))
1619 option_conflict('l', 'R');
1622 uri = argv[0];
1624 if (argc == 1)
1625 dirname = NULL;
1626 else if (argc == 2)
1627 dirname = argv[1];
1628 else
1629 usage_clone();
1631 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1632 &repo_name, uri);
1633 if (error)
1634 goto done;
1636 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1637 host, port ? ":" : "", port ? port : "",
1638 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1639 error = got_error_from_errno("asprintf");
1640 goto done;
1643 if (strcmp(proto, "git") == 0) {
1644 #ifndef PROFILE
1645 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1646 "sendfd dns inet unveil", NULL) == -1)
1647 err(1, "pledge");
1648 #endif
1649 } else if (strcmp(proto, "git+ssh") == 0 ||
1650 strcmp(proto, "ssh") == 0) {
1651 #ifndef PROFILE
1652 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1653 "sendfd unveil", NULL) == -1)
1654 err(1, "pledge");
1655 #endif
1656 } else if (strcmp(proto, "http") == 0 ||
1657 strcmp(proto, "git+http") == 0) {
1658 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1659 goto done;
1660 } else {
1661 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1662 goto done;
1664 if (dirname == NULL) {
1665 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1666 error = got_error_from_errno("asprintf");
1667 goto done;
1669 repo_path = default_destdir;
1670 } else
1671 repo_path = dirname;
1673 if (!list_refs_only) {
1674 error = got_path_mkdir(repo_path);
1675 if (error &&
1676 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1677 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1678 goto done;
1679 if (!got_path_dir_is_empty(repo_path)) {
1680 error = got_error_path(repo_path,
1681 GOT_ERR_DIR_NOT_EMPTY);
1682 goto done;
1686 error = got_dial_apply_unveil(proto);
1687 if (error)
1688 goto done;
1690 error = apply_unveil(repo_path, 0, NULL);
1691 if (error)
1692 goto done;
1694 if (verbosity >= 0)
1695 printf("Connecting to %s\n", git_url);
1697 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1698 server_path, verbosity);
1699 if (error)
1700 goto done;
1702 if (!list_refs_only) {
1703 error = got_repo_init(repo_path, NULL);
1704 if (error)
1705 goto done;
1706 error = got_repo_pack_fds_open(&pack_fds);
1707 if (error != NULL)
1708 goto done;
1709 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1710 if (error)
1711 goto done;
1714 fpa.last_scaled_size[0] = '\0';
1715 fpa.last_p_indexed = -1;
1716 fpa.last_p_resolved = -1;
1717 fpa.verbosity = verbosity;
1718 fpa.create_configs = 1;
1719 fpa.configs_created = 0;
1720 fpa.repo = repo;
1721 fpa.config_info.symrefs = &symrefs;
1722 fpa.config_info.wanted_branches = &wanted_branches;
1723 fpa.config_info.wanted_refs = &wanted_refs;
1724 fpa.config_info.proto = proto;
1725 fpa.config_info.host = host;
1726 fpa.config_info.port = port;
1727 fpa.config_info.remote_repo_path = server_path;
1728 fpa.config_info.git_url = git_url;
1729 fpa.config_info.fetch_all_branches = fetch_all_branches;
1730 fpa.config_info.mirror_references = mirror_references;
1731 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1732 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1733 fetch_all_branches, &wanted_branches, &wanted_refs,
1734 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1735 fetch_progress, &fpa);
1736 if (error)
1737 goto done;
1739 if (list_refs_only) {
1740 error = list_remote_refs(&symrefs, &refs);
1741 goto done;
1744 if (pack_hash == NULL) {
1745 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1746 "server sent an empty pack file");
1747 goto done;
1749 error = got_object_id_str(&id_str, pack_hash);
1750 if (error)
1751 goto done;
1752 if (verbosity >= 0)
1753 printf("\nFetched %s.pack\n", id_str);
1754 free(id_str);
1756 /* Set up references provided with the pack file. */
1757 TAILQ_FOREACH(pe, &refs, entry) {
1758 const char *refname = pe->path;
1759 struct got_object_id *id = pe->data;
1760 char *remote_refname;
1762 if (is_wanted_ref(&wanted_refs, refname) &&
1763 !mirror_references) {
1764 error = create_wanted_ref(refname, id,
1765 GOT_FETCH_DEFAULT_REMOTE_NAME,
1766 verbosity - 1, repo);
1767 if (error)
1768 goto done;
1769 continue;
1772 error = create_ref(refname, id, verbosity - 1, repo);
1773 if (error)
1774 goto done;
1776 if (mirror_references)
1777 continue;
1779 if (strncmp("refs/heads/", refname, 11) != 0)
1780 continue;
1782 if (asprintf(&remote_refname,
1783 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1784 refname + 11) == -1) {
1785 error = got_error_from_errno("asprintf");
1786 goto done;
1788 error = create_ref(remote_refname, id, verbosity - 1, repo);
1789 free(remote_refname);
1790 if (error)
1791 goto done;
1794 /* Set the HEAD reference if the server provided one. */
1795 TAILQ_FOREACH(pe, &symrefs, entry) {
1796 struct got_reference *target_ref;
1797 const char *refname = pe->path;
1798 const char *target = pe->data;
1799 char *remote_refname = NULL, *remote_target = NULL;
1801 if (strcmp(refname, GOT_REF_HEAD) != 0)
1802 continue;
1804 error = got_ref_open(&target_ref, repo, target, 0);
1805 if (error) {
1806 if (error->code == GOT_ERR_NOT_REF) {
1807 error = NULL;
1808 continue;
1810 goto done;
1813 error = create_symref(refname, target_ref, verbosity, repo);
1814 got_ref_close(target_ref);
1815 if (error)
1816 goto done;
1818 if (mirror_references)
1819 continue;
1821 if (strncmp("refs/heads/", target, 11) != 0)
1822 continue;
1824 if (asprintf(&remote_refname,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 refname) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 goto done;
1830 if (asprintf(&remote_target,
1831 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1832 target + 11) == -1) {
1833 error = got_error_from_errno("asprintf");
1834 free(remote_refname);
1835 goto done;
1837 error = got_ref_open(&target_ref, repo, remote_target, 0);
1838 if (error) {
1839 free(remote_refname);
1840 free(remote_target);
1841 if (error->code == GOT_ERR_NOT_REF) {
1842 error = NULL;
1843 continue;
1845 goto done;
1847 error = create_symref(remote_refname, target_ref,
1848 verbosity - 1, repo);
1849 free(remote_refname);
1850 free(remote_target);
1851 got_ref_close(target_ref);
1852 if (error)
1853 goto done;
1855 if (pe == NULL) {
1857 * We failed to set the HEAD reference. If we asked for
1858 * a set of wanted branches use the first of one of those
1859 * which could be fetched instead.
1861 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1862 const char *target = pe->path;
1863 struct got_reference *target_ref;
1865 error = got_ref_open(&target_ref, repo, target, 0);
1866 if (error) {
1867 if (error->code == GOT_ERR_NOT_REF) {
1868 error = NULL;
1869 continue;
1871 goto done;
1874 error = create_symref(GOT_REF_HEAD, target_ref,
1875 verbosity, repo);
1876 got_ref_close(target_ref);
1877 if (error)
1878 goto done;
1879 break;
1882 if (!fpa.configs_created && pe != NULL) {
1883 error = create_config_files(fpa.config_info.proto,
1884 fpa.config_info.host, fpa.config_info.port,
1885 fpa.config_info.remote_repo_path,
1886 fpa.config_info.git_url,
1887 fpa.config_info.fetch_all_branches,
1888 fpa.config_info.mirror_references,
1889 fpa.config_info.symrefs,
1890 fpa.config_info.wanted_branches,
1891 fpa.config_info.wanted_refs, fpa.repo);
1892 if (error)
1893 goto done;
1897 if (verbosity >= 0)
1898 printf("Created %s repository '%s'\n",
1899 mirror_references ? "mirrored" : "cloned", repo_path);
1900 done:
1901 if (pack_fds) {
1902 const struct got_error *pack_err =
1903 got_repo_pack_fds_close(pack_fds);
1904 if (error == NULL)
1905 error = pack_err;
1907 if (fetchpid > 0) {
1908 if (kill(fetchpid, SIGTERM) == -1)
1909 error = got_error_from_errno("kill");
1910 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1911 error = got_error_from_errno("waitpid");
1913 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1914 error = got_error_from_errno("close");
1915 if (repo) {
1916 const struct got_error *close_err = got_repo_close(repo);
1917 if (error == NULL)
1918 error = close_err;
1920 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1922 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1923 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1924 free(pack_hash);
1925 free(proto);
1926 free(host);
1927 free(port);
1928 free(server_path);
1929 free(repo_name);
1930 free(default_destdir);
1931 free(git_url);
1932 return error;
1935 static const struct got_error *
1936 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1937 int replace_tags, int verbosity, struct got_repository *repo)
1939 const struct got_error *err = NULL;
1940 char *new_id_str = NULL;
1941 struct got_object_id *old_id = NULL;
1943 err = got_object_id_str(&new_id_str, new_id);
1944 if (err)
1945 goto done;
1947 if (!replace_tags &&
1948 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1949 err = got_ref_resolve(&old_id, repo, ref);
1950 if (err)
1951 goto done;
1952 if (got_object_id_cmp(old_id, new_id) == 0)
1953 goto done;
1954 if (verbosity >= 0) {
1955 printf("Rejecting update of existing tag %s: %s\n",
1956 got_ref_get_name(ref), new_id_str);
1958 goto done;
1961 if (got_ref_is_symbolic(ref)) {
1962 if (verbosity >= 0) {
1963 printf("Replacing reference %s: %s\n",
1964 got_ref_get_name(ref),
1965 got_ref_get_symref_target(ref));
1967 err = got_ref_change_symref_to_ref(ref, new_id);
1968 if (err)
1969 goto done;
1970 err = got_ref_write(ref, repo);
1971 if (err)
1972 goto done;
1973 } else {
1974 err = got_ref_resolve(&old_id, repo, ref);
1975 if (err)
1976 goto done;
1977 if (got_object_id_cmp(old_id, new_id) == 0)
1978 goto done;
1980 err = got_ref_change_ref(ref, new_id);
1981 if (err)
1982 goto done;
1983 err = got_ref_write(ref, repo);
1984 if (err)
1985 goto done;
1988 if (verbosity >= 0)
1989 printf("Updated %s: %s\n", got_ref_get_name(ref),
1990 new_id_str);
1991 done:
1992 free(old_id);
1993 free(new_id_str);
1994 return err;
1997 static const struct got_error *
1998 update_symref(const char *refname, struct got_reference *target_ref,
1999 int verbosity, struct got_repository *repo)
2001 const struct got_error *err = NULL, *unlock_err;
2002 struct got_reference *symref;
2003 int symref_is_locked = 0;
2005 err = got_ref_open(&symref, repo, refname, 1);
2006 if (err) {
2007 if (err->code != GOT_ERR_NOT_REF)
2008 return err;
2009 err = got_ref_alloc_symref(&symref, refname, target_ref);
2010 if (err)
2011 goto done;
2013 err = got_ref_write(symref, repo);
2014 if (err)
2015 goto done;
2017 if (verbosity >= 0)
2018 printf("Created reference %s: %s\n",
2019 got_ref_get_name(symref),
2020 got_ref_get_symref_target(symref));
2021 } else {
2022 symref_is_locked = 1;
2024 if (strcmp(got_ref_get_symref_target(symref),
2025 got_ref_get_name(target_ref)) == 0)
2026 goto done;
2028 err = got_ref_change_symref(symref,
2029 got_ref_get_name(target_ref));
2030 if (err)
2031 goto done;
2033 err = got_ref_write(symref, repo);
2034 if (err)
2035 goto done;
2037 if (verbosity >= 0)
2038 printf("Updated %s: %s\n", got_ref_get_name(symref),
2039 got_ref_get_symref_target(symref));
2042 done:
2043 if (symref_is_locked) {
2044 unlock_err = got_ref_unlock(symref);
2045 if (unlock_err && err == NULL)
2046 err = unlock_err;
2048 got_ref_close(symref);
2049 return err;
2052 __dead static void
2053 usage_fetch(void)
2055 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2056 "[-R reference] [-r repository-path] [remote-repository]\n",
2057 getprogname());
2058 exit(1);
2061 static const struct got_error *
2062 delete_missing_ref(struct got_reference *ref,
2063 int verbosity, struct got_repository *repo)
2065 const struct got_error *err = NULL;
2066 struct got_object_id *id = NULL;
2067 char *id_str = NULL;
2069 if (got_ref_is_symbolic(ref)) {
2070 err = got_ref_delete(ref, repo);
2071 if (err)
2072 return err;
2073 if (verbosity >= 0) {
2074 printf("Deleted %s: %s\n",
2075 got_ref_get_name(ref),
2076 got_ref_get_symref_target(ref));
2078 } else {
2079 err = got_ref_resolve(&id, repo, ref);
2080 if (err)
2081 return err;
2082 err = got_object_id_str(&id_str, id);
2083 if (err)
2084 goto done;
2086 err = got_ref_delete(ref, repo);
2087 if (err)
2088 goto done;
2089 if (verbosity >= 0) {
2090 printf("Deleted %s: %s\n",
2091 got_ref_get_name(ref), id_str);
2094 done:
2095 free(id);
2096 free(id_str);
2097 return err;
2100 static const struct got_error *
2101 delete_missing_refs(struct got_pathlist_head *their_refs,
2102 struct got_pathlist_head *their_symrefs,
2103 const struct got_remote_repo *remote,
2104 int verbosity, struct got_repository *repo)
2106 const struct got_error *err = NULL, *unlock_err;
2107 struct got_reflist_head my_refs;
2108 struct got_reflist_entry *re;
2109 struct got_pathlist_entry *pe;
2110 char *remote_namespace = NULL;
2111 char *local_refname = NULL;
2113 TAILQ_INIT(&my_refs);
2115 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2116 == -1)
2117 return got_error_from_errno("asprintf");
2119 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2120 if (err)
2121 goto done;
2123 TAILQ_FOREACH(re, &my_refs, entry) {
2124 const char *refname = got_ref_get_name(re->ref);
2125 const char *their_refname;
2127 if (remote->mirror_references) {
2128 their_refname = refname;
2129 } else {
2130 if (strncmp(refname, remote_namespace,
2131 strlen(remote_namespace)) == 0) {
2132 if (strcmp(refname + strlen(remote_namespace),
2133 GOT_REF_HEAD) == 0)
2134 continue;
2135 if (asprintf(&local_refname, "refs/heads/%s",
2136 refname + strlen(remote_namespace)) == -1) {
2137 err = got_error_from_errno("asprintf");
2138 goto done;
2140 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2141 continue;
2143 their_refname = local_refname;
2146 TAILQ_FOREACH(pe, their_refs, entry) {
2147 if (strcmp(their_refname, pe->path) == 0)
2148 break;
2150 if (pe != NULL)
2151 continue;
2153 TAILQ_FOREACH(pe, their_symrefs, entry) {
2154 if (strcmp(their_refname, pe->path) == 0)
2155 break;
2157 if (pe != NULL)
2158 continue;
2160 err = delete_missing_ref(re->ref, verbosity, repo);
2161 if (err)
2162 break;
2164 if (local_refname) {
2165 struct got_reference *ref;
2166 err = got_ref_open(&ref, repo, local_refname, 1);
2167 if (err) {
2168 if (err->code != GOT_ERR_NOT_REF)
2169 break;
2170 free(local_refname);
2171 local_refname = NULL;
2172 continue;
2174 err = delete_missing_ref(ref, verbosity, repo);
2175 if (err)
2176 break;
2177 unlock_err = got_ref_unlock(ref);
2178 got_ref_close(ref);
2179 if (unlock_err && err == NULL) {
2180 err = unlock_err;
2181 break;
2184 free(local_refname);
2185 local_refname = NULL;
2188 done:
2189 got_ref_list_free(&my_refs);
2190 free(remote_namespace);
2191 free(local_refname);
2192 return err;
2195 static const struct got_error *
2196 update_wanted_ref(const char *refname, struct got_object_id *id,
2197 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2199 const struct got_error *err, *unlock_err;
2200 char *remote_refname;
2201 struct got_reference *ref;
2203 if (strncmp("refs/", refname, 5) == 0)
2204 refname += 5;
2206 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2207 remote_repo_name, refname) == -1)
2208 return got_error_from_errno("asprintf");
2210 err = got_ref_open(&ref, repo, remote_refname, 1);
2211 if (err) {
2212 if (err->code != GOT_ERR_NOT_REF)
2213 goto done;
2214 err = create_ref(remote_refname, id, verbosity, repo);
2215 } else {
2216 err = update_ref(ref, id, 0, verbosity, repo);
2217 unlock_err = got_ref_unlock(ref);
2218 if (unlock_err && err == NULL)
2219 err = unlock_err;
2220 got_ref_close(ref);
2222 done:
2223 free(remote_refname);
2224 return err;
2227 static const struct got_error *
2228 delete_ref(struct got_repository *repo, struct got_reference *ref)
2230 const struct got_error *err = NULL;
2231 struct got_object_id *id = NULL;
2232 char *id_str = NULL;
2233 const char *target;
2235 if (got_ref_is_symbolic(ref)) {
2236 target = got_ref_get_symref_target(ref);
2237 } else {
2238 err = got_ref_resolve(&id, repo, ref);
2239 if (err)
2240 goto done;
2241 err = got_object_id_str(&id_str, id);
2242 if (err)
2243 goto done;
2244 target = id_str;
2247 err = got_ref_delete(ref, repo);
2248 if (err)
2249 goto done;
2251 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2252 done:
2253 free(id);
2254 free(id_str);
2255 return err;
2258 static const struct got_error *
2259 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2261 const struct got_error *err = NULL;
2262 struct got_reflist_head refs;
2263 struct got_reflist_entry *re;
2264 char *prefix;
2266 TAILQ_INIT(&refs);
2268 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2269 err = got_error_from_errno("asprintf");
2270 goto done;
2272 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2273 if (err)
2274 goto done;
2276 TAILQ_FOREACH(re, &refs, entry)
2277 delete_ref(repo, re->ref);
2278 done:
2279 got_ref_list_free(&refs);
2280 return err;
2283 static const struct got_error *
2284 cmd_fetch(int argc, char *argv[])
2286 const struct got_error *error = NULL, *unlock_err;
2287 char *cwd = NULL, *repo_path = NULL;
2288 const char *remote_name;
2289 char *proto = NULL, *host = NULL, *port = NULL;
2290 char *repo_name = NULL, *server_path = NULL;
2291 const struct got_remote_repo *remotes, *remote = NULL;
2292 int nremotes;
2293 char *id_str = NULL;
2294 struct got_repository *repo = NULL;
2295 struct got_worktree *worktree = NULL;
2296 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2297 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2298 struct got_pathlist_entry *pe;
2299 struct got_reflist_head remote_refs;
2300 struct got_reflist_entry *re;
2301 struct got_object_id *pack_hash = NULL;
2302 int i, ch, fetchfd = -1, fetchstatus;
2303 pid_t fetchpid = -1;
2304 struct got_fetch_progress_arg fpa;
2305 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2306 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2307 int *pack_fds = NULL, have_bflag = 0;
2308 const char *remote_head = NULL, *worktree_branch = NULL;
2310 TAILQ_INIT(&refs);
2311 TAILQ_INIT(&symrefs);
2312 TAILQ_INIT(&remote_refs);
2313 TAILQ_INIT(&wanted_branches);
2314 TAILQ_INIT(&wanted_refs);
2316 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2317 switch (ch) {
2318 case 'a':
2319 fetch_all_branches = 1;
2320 break;
2321 case 'b':
2322 error = got_pathlist_append(&wanted_branches,
2323 optarg, NULL);
2324 if (error)
2325 return error;
2326 have_bflag = 1;
2327 break;
2328 case 'd':
2329 delete_refs = 1;
2330 break;
2331 case 'l':
2332 list_refs_only = 1;
2333 break;
2334 case 'q':
2335 verbosity = -1;
2336 break;
2337 case 'R':
2338 error = got_pathlist_append(&wanted_refs,
2339 optarg, NULL);
2340 if (error)
2341 return error;
2342 break;
2343 case 'r':
2344 repo_path = realpath(optarg, NULL);
2345 if (repo_path == NULL)
2346 return got_error_from_errno2("realpath",
2347 optarg);
2348 got_path_strip_trailing_slashes(repo_path);
2349 break;
2350 case 't':
2351 replace_tags = 1;
2352 break;
2353 case 'v':
2354 if (verbosity < 0)
2355 verbosity = 0;
2356 else if (verbosity < 3)
2357 verbosity++;
2358 break;
2359 case 'X':
2360 delete_remote = 1;
2361 break;
2362 default:
2363 usage_fetch();
2364 break;
2367 argc -= optind;
2368 argv += optind;
2370 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('a', 'b');
2372 if (list_refs_only) {
2373 if (!TAILQ_EMPTY(&wanted_branches))
2374 option_conflict('l', 'b');
2375 if (fetch_all_branches)
2376 option_conflict('l', 'a');
2377 if (delete_refs)
2378 option_conflict('l', 'd');
2379 if (delete_remote)
2380 option_conflict('l', 'X');
2382 if (delete_remote) {
2383 if (fetch_all_branches)
2384 option_conflict('X', 'a');
2385 if (!TAILQ_EMPTY(&wanted_branches))
2386 option_conflict('X', 'b');
2387 if (delete_refs)
2388 option_conflict('X', 'd');
2389 if (replace_tags)
2390 option_conflict('X', 't');
2391 if (!TAILQ_EMPTY(&wanted_refs))
2392 option_conflict('X', 'R');
2395 if (argc == 0) {
2396 if (delete_remote)
2397 errx(1, "-X option requires a remote name");
2398 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2399 } else if (argc == 1)
2400 remote_name = argv[0];
2401 else
2402 usage_fetch();
2404 cwd = getcwd(NULL, 0);
2405 if (cwd == NULL) {
2406 error = got_error_from_errno("getcwd");
2407 goto done;
2410 error = got_repo_pack_fds_open(&pack_fds);
2411 if (error != NULL)
2412 goto done;
2414 if (repo_path == NULL) {
2415 error = got_worktree_open(&worktree, cwd);
2416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2417 goto done;
2418 else
2419 error = NULL;
2420 if (worktree) {
2421 repo_path =
2422 strdup(got_worktree_get_repo_path(worktree));
2423 if (repo_path == NULL)
2424 error = got_error_from_errno("strdup");
2425 if (error)
2426 goto done;
2427 } else {
2428 repo_path = strdup(cwd);
2429 if (repo_path == NULL) {
2430 error = got_error_from_errno("strdup");
2431 goto done;
2436 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2437 if (error)
2438 goto done;
2440 if (delete_remote) {
2441 error = delete_refs_for_remote(repo, remote_name);
2442 goto done; /* nothing else to do */
2445 if (worktree) {
2446 worktree_conf = got_worktree_get_gotconfig(worktree);
2447 if (worktree_conf) {
2448 got_gotconfig_get_remotes(&nremotes, &remotes,
2449 worktree_conf);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 remote = &remotes[i];
2453 break;
2458 if (remote == NULL) {
2459 repo_conf = got_repo_get_gotconfig(repo);
2460 if (repo_conf) {
2461 got_gotconfig_get_remotes(&nremotes, &remotes,
2462 repo_conf);
2463 for (i = 0; i < nremotes; i++) {
2464 if (strcmp(remotes[i].name, remote_name) == 0) {
2465 remote = &remotes[i];
2466 break;
2471 if (remote == NULL) {
2472 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2473 for (i = 0; i < nremotes; i++) {
2474 if (strcmp(remotes[i].name, remote_name) == 0) {
2475 remote = &remotes[i];
2476 break;
2480 if (remote == NULL) {
2481 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2482 goto done;
2485 if (TAILQ_EMPTY(&wanted_branches)) {
2486 if (!fetch_all_branches)
2487 fetch_all_branches = remote->fetch_all_branches;
2488 for (i = 0; i < remote->nfetch_branches; i++) {
2489 error = got_pathlist_append(&wanted_branches,
2490 remote->fetch_branches[i], NULL);
2491 if (error)
2492 goto done;
2495 if (TAILQ_EMPTY(&wanted_refs)) {
2496 for (i = 0; i < remote->nfetch_refs; i++) {
2497 error = got_pathlist_append(&wanted_refs,
2498 remote->fetch_refs[i], NULL);
2499 if (error)
2500 goto done;
2504 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2505 &repo_name, remote->fetch_url);
2506 if (error)
2507 goto done;
2509 if (strcmp(proto, "git") == 0) {
2510 #ifndef PROFILE
2511 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2512 "sendfd dns inet unveil", NULL) == -1)
2513 err(1, "pledge");
2514 #endif
2515 } else if (strcmp(proto, "git+ssh") == 0 ||
2516 strcmp(proto, "ssh") == 0) {
2517 #ifndef PROFILE
2518 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2519 "sendfd unveil", NULL) == -1)
2520 err(1, "pledge");
2521 #endif
2522 } else if (strcmp(proto, "http") == 0 ||
2523 strcmp(proto, "git+http") == 0) {
2524 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2525 goto done;
2526 } else {
2527 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2528 goto done;
2531 error = got_dial_apply_unveil(proto);
2532 if (error)
2533 goto done;
2535 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2536 if (error)
2537 goto done;
2539 if (verbosity >= 0) {
2540 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2541 remote->name, proto, host,
2542 port ? ":" : "", port ? port : "",
2543 *server_path == '/' ? "" : "/", server_path);
2546 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2547 server_path, verbosity);
2548 if (error)
2549 goto done;
2551 if (!have_bflag) {
2553 * If set, get this remote's HEAD ref target so
2554 * if it has changed on the server we can fetch it.
2556 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2557 got_ref_cmp_by_name, repo);
2558 if (error)
2559 goto done;
2561 TAILQ_FOREACH(re, &remote_refs, entry) {
2562 const char *remote_refname, *remote_target;
2563 size_t remote_name_len;
2565 if (!got_ref_is_symbolic(re->ref))
2566 continue;
2568 remote_name_len = strlen(remote->name);
2569 remote_refname = got_ref_get_name(re->ref);
2571 /* we only want refs/remotes/$remote->name/HEAD */
2572 if (strncmp(remote_refname + 13, remote->name,
2573 remote_name_len) != 0)
2574 continue;
2576 if (strcmp(remote_refname + remote_name_len + 14,
2577 GOT_REF_HEAD) != 0)
2578 continue;
2581 * Take the name itself because we already
2582 * only match with refs/heads/ in fetch_pack().
2584 remote_target = got_ref_get_symref_target(re->ref);
2585 remote_head = remote_target + remote_name_len + 14;
2586 break;
2589 if (worktree) {
2590 const char *refname;
2592 refname = got_worktree_get_head_ref_name(worktree);
2593 if (strncmp(refname, "refs/heads/", 11) == 0)
2594 worktree_branch = refname;
2598 fpa.last_scaled_size[0] = '\0';
2599 fpa.last_p_indexed = -1;
2600 fpa.last_p_resolved = -1;
2601 fpa.verbosity = verbosity;
2602 fpa.repo = repo;
2603 fpa.create_configs = 0;
2604 fpa.configs_created = 0;
2605 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2607 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2608 remote->mirror_references, fetch_all_branches, &wanted_branches,
2609 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2610 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2611 if (error)
2612 goto done;
2614 if (list_refs_only) {
2615 error = list_remote_refs(&symrefs, &refs);
2616 goto done;
2619 if (pack_hash == NULL) {
2620 if (verbosity >= 0)
2621 printf("Already up-to-date\n");
2622 } else if (verbosity >= 0) {
2623 error = got_object_id_str(&id_str, pack_hash);
2624 if (error)
2625 goto done;
2626 printf("\nFetched %s.pack\n", id_str);
2627 free(id_str);
2628 id_str = NULL;
2631 /* Update references provided with the pack file. */
2632 TAILQ_FOREACH(pe, &refs, entry) {
2633 const char *refname = pe->path;
2634 struct got_object_id *id = pe->data;
2635 struct got_reference *ref;
2636 char *remote_refname;
2638 if (is_wanted_ref(&wanted_refs, refname) &&
2639 !remote->mirror_references) {
2640 error = update_wanted_ref(refname, id,
2641 remote->name, verbosity, repo);
2642 if (error)
2643 goto done;
2644 continue;
2647 if (remote->mirror_references ||
2648 strncmp("refs/tags/", refname, 10) == 0) {
2649 error = got_ref_open(&ref, repo, refname, 1);
2650 if (error) {
2651 if (error->code != GOT_ERR_NOT_REF)
2652 goto done;
2653 error = create_ref(refname, id, verbosity,
2654 repo);
2655 if (error)
2656 goto done;
2657 } else {
2658 error = update_ref(ref, id, replace_tags,
2659 verbosity, repo);
2660 unlock_err = got_ref_unlock(ref);
2661 if (unlock_err && error == NULL)
2662 error = unlock_err;
2663 got_ref_close(ref);
2664 if (error)
2665 goto done;
2667 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2668 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2669 remote_name, refname + 11) == -1) {
2670 error = got_error_from_errno("asprintf");
2671 goto done;
2674 error = got_ref_open(&ref, repo, remote_refname, 1);
2675 if (error) {
2676 if (error->code != GOT_ERR_NOT_REF)
2677 goto done;
2678 error = create_ref(remote_refname, id,
2679 verbosity, repo);
2680 if (error)
2681 goto done;
2682 } else {
2683 error = update_ref(ref, id, replace_tags,
2684 verbosity, repo);
2685 unlock_err = got_ref_unlock(ref);
2686 if (unlock_err && error == NULL)
2687 error = unlock_err;
2688 got_ref_close(ref);
2689 if (error)
2690 goto done;
2693 /* Also create a local branch if none exists yet. */
2694 error = got_ref_open(&ref, repo, refname, 1);
2695 if (error) {
2696 if (error->code != GOT_ERR_NOT_REF)
2697 goto done;
2698 error = create_ref(refname, id, verbosity,
2699 repo);
2700 if (error)
2701 goto done;
2702 } else {
2703 unlock_err = got_ref_unlock(ref);
2704 if (unlock_err && error == NULL)
2705 error = unlock_err;
2706 got_ref_close(ref);
2710 if (delete_refs) {
2711 error = delete_missing_refs(&refs, &symrefs, remote,
2712 verbosity, repo);
2713 if (error)
2714 goto done;
2717 if (!remote->mirror_references) {
2718 /* Update remote HEAD reference if the server provided one. */
2719 TAILQ_FOREACH(pe, &symrefs, entry) {
2720 struct got_reference *target_ref;
2721 const char *refname = pe->path;
2722 const char *target = pe->data;
2723 char *remote_refname = NULL, *remote_target = NULL;
2725 if (strcmp(refname, GOT_REF_HEAD) != 0)
2726 continue;
2728 if (strncmp("refs/heads/", target, 11) != 0)
2729 continue;
2731 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2732 remote->name, refname) == -1) {
2733 error = got_error_from_errno("asprintf");
2734 goto done;
2736 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2737 remote->name, target + 11) == -1) {
2738 error = got_error_from_errno("asprintf");
2739 free(remote_refname);
2740 goto done;
2743 error = got_ref_open(&target_ref, repo, remote_target,
2744 0);
2745 if (error) {
2746 free(remote_refname);
2747 free(remote_target);
2748 if (error->code == GOT_ERR_NOT_REF) {
2749 error = NULL;
2750 continue;
2752 goto done;
2754 error = update_symref(remote_refname, target_ref,
2755 verbosity, repo);
2756 free(remote_refname);
2757 free(remote_target);
2758 got_ref_close(target_ref);
2759 if (error)
2760 goto done;
2763 done:
2764 if (fetchpid > 0) {
2765 if (kill(fetchpid, SIGTERM) == -1)
2766 error = got_error_from_errno("kill");
2767 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2768 error = got_error_from_errno("waitpid");
2770 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2771 error = got_error_from_errno("close");
2772 if (repo) {
2773 const struct got_error *close_err = got_repo_close(repo);
2774 if (error == NULL)
2775 error = close_err;
2777 if (worktree)
2778 got_worktree_close(worktree);
2779 if (pack_fds) {
2780 const struct got_error *pack_err =
2781 got_repo_pack_fds_close(pack_fds);
2782 if (error == NULL)
2783 error = pack_err;
2785 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2787 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2788 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2789 got_ref_list_free(&remote_refs);
2790 free(id_str);
2791 free(cwd);
2792 free(repo_path);
2793 free(pack_hash);
2794 free(proto);
2795 free(host);
2796 free(port);
2797 free(server_path);
2798 free(repo_name);
2799 return error;
2803 __dead static void
2804 usage_checkout(void)
2806 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2807 "[-p path-prefix] repository-path [work-tree-path]\n",
2808 getprogname());
2809 exit(1);
2812 static void
2813 show_worktree_base_ref_warning(void)
2815 fprintf(stderr, "%s: warning: could not create a reference "
2816 "to the work tree's base commit; the commit could be "
2817 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2818 "repository writable and running 'got update' will prevent this\n",
2819 getprogname());
2822 struct got_checkout_progress_arg {
2823 const char *worktree_path;
2824 int had_base_commit_ref_error;
2825 int verbosity;
2828 static const struct got_error *
2829 checkout_progress(void *arg, unsigned char status, const char *path)
2831 struct got_checkout_progress_arg *a = arg;
2833 /* Base commit bump happens silently. */
2834 if (status == GOT_STATUS_BUMP_BASE)
2835 return NULL;
2837 if (status == GOT_STATUS_BASE_REF_ERR) {
2838 a->had_base_commit_ref_error = 1;
2839 return NULL;
2842 while (path[0] == '/')
2843 path++;
2845 if (a->verbosity >= 0)
2846 printf("%c %s/%s\n", status, a->worktree_path, path);
2848 return NULL;
2851 static const struct got_error *
2852 check_cancelled(void *arg)
2854 if (sigint_received || sigpipe_received)
2855 return got_error(GOT_ERR_CANCELLED);
2856 return NULL;
2859 static const struct got_error *
2860 check_linear_ancestry(struct got_object_id *commit_id,
2861 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2862 struct got_repository *repo)
2864 const struct got_error *err = NULL;
2865 struct got_object_id *yca_id;
2867 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2868 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2869 if (err)
2870 return err;
2872 if (yca_id == NULL)
2873 return got_error(GOT_ERR_ANCESTRY);
2876 * Require a straight line of history between the target commit
2877 * and the work tree's base commit.
2879 * Non-linear situations such as this require a rebase:
2881 * (commit) D F (base_commit)
2882 * \ /
2883 * C E
2884 * \ /
2885 * B (yca)
2886 * |
2887 * A
2889 * 'got update' only handles linear cases:
2890 * Update forwards in time: A (base/yca) - B - C - D (commit)
2891 * Update backwards in time: D (base) - C - B - A (commit/yca)
2893 if (allow_forwards_in_time_only) {
2894 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2895 return got_error(GOT_ERR_ANCESTRY);
2896 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2897 got_object_id_cmp(base_commit_id, yca_id) != 0)
2898 return got_error(GOT_ERR_ANCESTRY);
2900 free(yca_id);
2901 return NULL;
2904 static const struct got_error *
2905 check_same_branch(struct got_object_id *commit_id,
2906 struct got_reference *head_ref, struct got_repository *repo)
2908 const struct got_error *err = NULL;
2909 struct got_commit_graph *graph = NULL;
2910 struct got_object_id *head_commit_id = NULL;
2912 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2913 if (err)
2914 goto done;
2916 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2917 goto done;
2919 err = got_commit_graph_open(&graph, "/", 1);
2920 if (err)
2921 goto done;
2923 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2924 check_cancelled, NULL);
2925 if (err)
2926 goto done;
2928 for (;;) {
2929 struct got_object_id id;
2931 err = got_commit_graph_iter_next(&id, graph, repo,
2932 check_cancelled, NULL);
2933 if (err) {
2934 if (err->code == GOT_ERR_ITER_COMPLETED)
2935 err = got_error(GOT_ERR_ANCESTRY);
2936 break;
2939 if (got_object_id_cmp(&id, commit_id) == 0)
2940 break;
2942 done:
2943 if (graph)
2944 got_commit_graph_close(graph);
2945 free(head_commit_id);
2946 return err;
2949 static const struct got_error *
2950 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2952 static char msg[512];
2953 const char *branch_name;
2955 if (got_ref_is_symbolic(ref))
2956 branch_name = got_ref_get_symref_target(ref);
2957 else
2958 branch_name = got_ref_get_name(ref);
2960 if (strncmp("refs/heads/", branch_name, 11) == 0)
2961 branch_name += 11;
2963 snprintf(msg, sizeof(msg),
2964 "target commit is not contained in branch '%s'; "
2965 "the branch to use must be specified with -b; "
2966 "if necessary a new branch can be created for "
2967 "this commit with 'got branch -c %s BRANCH_NAME'",
2968 branch_name, commit_id_str);
2970 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2973 static const struct got_error *
2974 cmd_checkout(int argc, char *argv[])
2976 const struct got_error *error = NULL;
2977 struct got_repository *repo = NULL;
2978 struct got_reference *head_ref = NULL, *ref = NULL;
2979 struct got_worktree *worktree = NULL;
2980 char *repo_path = NULL;
2981 char *worktree_path = NULL;
2982 const char *path_prefix = "";
2983 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2984 char *commit_id_str = NULL;
2985 struct got_object_id *commit_id = NULL;
2986 char *cwd = NULL;
2987 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2988 struct got_pathlist_head paths;
2989 struct got_checkout_progress_arg cpa;
2990 int *pack_fds = NULL;
2992 TAILQ_INIT(&paths);
2994 #ifndef PROFILE
2995 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2996 "unveil", NULL) == -1)
2997 err(1, "pledge");
2998 #endif
3000 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3001 switch (ch) {
3002 case 'b':
3003 branch_name = optarg;
3004 break;
3005 case 'c':
3006 commit_id_str = strdup(optarg);
3007 if (commit_id_str == NULL)
3008 return got_error_from_errno("strdup");
3009 break;
3010 case 'E':
3011 allow_nonempty = 1;
3012 break;
3013 case 'p':
3014 path_prefix = optarg;
3015 break;
3016 case 'q':
3017 verbosity = -1;
3018 break;
3019 default:
3020 usage_checkout();
3021 /* NOTREACHED */
3025 argc -= optind;
3026 argv += optind;
3028 if (argc == 1) {
3029 char *base, *dotgit;
3030 const char *path;
3031 repo_path = realpath(argv[0], NULL);
3032 if (repo_path == NULL)
3033 return got_error_from_errno2("realpath", argv[0]);
3034 cwd = getcwd(NULL, 0);
3035 if (cwd == NULL) {
3036 error = got_error_from_errno("getcwd");
3037 goto done;
3039 if (path_prefix[0])
3040 path = path_prefix;
3041 else
3042 path = repo_path;
3043 error = got_path_basename(&base, path);
3044 if (error)
3045 goto done;
3046 dotgit = strstr(base, ".git");
3047 if (dotgit)
3048 *dotgit = '\0';
3049 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3050 error = got_error_from_errno("asprintf");
3051 free(base);
3052 goto done;
3054 free(base);
3055 } else if (argc == 2) {
3056 repo_path = realpath(argv[0], NULL);
3057 if (repo_path == NULL) {
3058 error = got_error_from_errno2("realpath", argv[0]);
3059 goto done;
3061 worktree_path = realpath(argv[1], NULL);
3062 if (worktree_path == NULL) {
3063 if (errno != ENOENT) {
3064 error = got_error_from_errno2("realpath",
3065 argv[1]);
3066 goto done;
3068 worktree_path = strdup(argv[1]);
3069 if (worktree_path == NULL) {
3070 error = got_error_from_errno("strdup");
3071 goto done;
3074 } else
3075 usage_checkout();
3077 got_path_strip_trailing_slashes(repo_path);
3078 got_path_strip_trailing_slashes(worktree_path);
3080 error = got_repo_pack_fds_open(&pack_fds);
3081 if (error != NULL)
3082 goto done;
3084 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3085 if (error != NULL)
3086 goto done;
3088 /* Pre-create work tree path for unveil(2) */
3089 error = got_path_mkdir(worktree_path);
3090 if (error) {
3091 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3092 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3093 goto done;
3094 if (!allow_nonempty &&
3095 !got_path_dir_is_empty(worktree_path)) {
3096 error = got_error_path(worktree_path,
3097 GOT_ERR_DIR_NOT_EMPTY);
3098 goto done;
3102 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3103 if (error)
3104 goto done;
3106 error = got_ref_open(&head_ref, repo, branch_name, 0);
3107 if (error != NULL)
3108 goto done;
3110 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3111 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3112 goto done;
3114 error = got_worktree_open(&worktree, worktree_path);
3115 if (error != NULL)
3116 goto done;
3118 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3119 path_prefix);
3120 if (error != NULL)
3121 goto done;
3122 if (!same_path_prefix) {
3123 error = got_error(GOT_ERR_PATH_PREFIX);
3124 goto done;
3127 if (commit_id_str) {
3128 struct got_reflist_head refs;
3129 TAILQ_INIT(&refs);
3130 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3131 NULL);
3132 if (error)
3133 goto done;
3134 error = got_repo_match_object_id(&commit_id, NULL,
3135 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3136 got_ref_list_free(&refs);
3137 if (error)
3138 goto done;
3139 error = check_linear_ancestry(commit_id,
3140 got_worktree_get_base_commit_id(worktree), 0, repo);
3141 if (error != NULL) {
3142 if (error->code == GOT_ERR_ANCESTRY) {
3143 error = checkout_ancestry_error(
3144 head_ref, commit_id_str);
3146 goto done;
3148 error = check_same_branch(commit_id, head_ref, repo);
3149 if (error) {
3150 if (error->code == GOT_ERR_ANCESTRY) {
3151 error = checkout_ancestry_error(
3152 head_ref, commit_id_str);
3154 goto done;
3156 error = got_worktree_set_base_commit_id(worktree, repo,
3157 commit_id);
3158 if (error)
3159 goto done;
3160 /* Expand potentially abbreviated commit ID string. */
3161 free(commit_id_str);
3162 error = got_object_id_str(&commit_id_str, commit_id);
3163 if (error)
3164 goto done;
3165 } else {
3166 commit_id = got_object_id_dup(
3167 got_worktree_get_base_commit_id(worktree));
3168 if (commit_id == NULL) {
3169 error = got_error_from_errno("got_object_id_dup");
3170 goto done;
3172 error = got_object_id_str(&commit_id_str, commit_id);
3173 if (error)
3174 goto done;
3177 error = got_pathlist_append(&paths, "", NULL);
3178 if (error)
3179 goto done;
3180 cpa.worktree_path = worktree_path;
3181 cpa.had_base_commit_ref_error = 0;
3182 cpa.verbosity = verbosity;
3183 error = got_worktree_checkout_files(worktree, &paths, repo,
3184 checkout_progress, &cpa, check_cancelled, NULL);
3185 if (error != NULL)
3186 goto done;
3188 if (got_ref_is_symbolic(head_ref)) {
3189 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3190 if (error)
3191 goto done;
3192 refname = got_ref_get_name(ref);
3193 } else
3194 refname = got_ref_get_name(head_ref);
3195 printf("Checked out %s: %s\n", refname, commit_id_str);
3196 printf("Now shut up and hack\n");
3197 if (cpa.had_base_commit_ref_error)
3198 show_worktree_base_ref_warning();
3199 done:
3200 if (pack_fds) {
3201 const struct got_error *pack_err =
3202 got_repo_pack_fds_close(pack_fds);
3203 if (error == NULL)
3204 error = pack_err;
3206 if (head_ref)
3207 got_ref_close(head_ref);
3208 if (ref)
3209 got_ref_close(ref);
3210 if (repo) {
3211 const struct got_error *close_err = got_repo_close(repo);
3212 if (error == NULL)
3213 error = close_err;
3215 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3216 free(commit_id_str);
3217 free(commit_id);
3218 free(repo_path);
3219 free(worktree_path);
3220 free(cwd);
3221 return error;
3224 struct got_update_progress_arg {
3225 int did_something;
3226 int conflicts;
3227 int obstructed;
3228 int not_updated;
3229 int missing;
3230 int not_deleted;
3231 int unversioned;
3232 int verbosity;
3235 static void
3236 print_update_progress_stats(struct got_update_progress_arg *upa)
3238 if (!upa->did_something)
3239 return;
3241 if (upa->conflicts > 0)
3242 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3243 if (upa->obstructed > 0)
3244 printf("File paths obstructed by a non-regular file: %d\n",
3245 upa->obstructed);
3246 if (upa->not_updated > 0)
3247 printf("Files not updated because of existing merge "
3248 "conflicts: %d\n", upa->not_updated);
3252 * The meaning of some status codes differs between merge-style operations and
3253 * update operations. For example, the ! status code means "file was missing"
3254 * if changes were merged into the work tree, and "missing file was restored"
3255 * if the work tree was updated. This function should be used by any operation
3256 * which merges changes into the work tree without updating the work tree.
3258 static void
3259 print_merge_progress_stats(struct got_update_progress_arg *upa)
3261 if (!upa->did_something)
3262 return;
3264 if (upa->conflicts > 0)
3265 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3266 if (upa->obstructed > 0)
3267 printf("File paths obstructed by a non-regular file: %d\n",
3268 upa->obstructed);
3269 if (upa->missing > 0)
3270 printf("Files which had incoming changes but could not be "
3271 "found in the work tree: %d\n", upa->missing);
3272 if (upa->not_deleted > 0)
3273 printf("Files not deleted due to differences in deleted "
3274 "content: %d\n", upa->not_deleted);
3275 if (upa->unversioned > 0)
3276 printf("Files not merged because an unversioned file was "
3277 "found in the work tree: %d\n", upa->unversioned);
3280 __dead static void
3281 usage_update(void)
3283 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3284 "[path ...]\n", getprogname());
3285 exit(1);
3288 static const struct got_error *
3289 update_progress(void *arg, unsigned char status, const char *path)
3291 struct got_update_progress_arg *upa = arg;
3293 if (status == GOT_STATUS_EXISTS ||
3294 status == GOT_STATUS_BASE_REF_ERR)
3295 return NULL;
3297 upa->did_something = 1;
3299 /* Base commit bump happens silently. */
3300 if (status == GOT_STATUS_BUMP_BASE)
3301 return NULL;
3303 if (status == GOT_STATUS_CONFLICT)
3304 upa->conflicts++;
3305 if (status == GOT_STATUS_OBSTRUCTED)
3306 upa->obstructed++;
3307 if (status == GOT_STATUS_CANNOT_UPDATE)
3308 upa->not_updated++;
3309 if (status == GOT_STATUS_MISSING)
3310 upa->missing++;
3311 if (status == GOT_STATUS_CANNOT_DELETE)
3312 upa->not_deleted++;
3313 if (status == GOT_STATUS_UNVERSIONED)
3314 upa->unversioned++;
3316 while (path[0] == '/')
3317 path++;
3318 if (upa->verbosity >= 0)
3319 printf("%c %s\n", status, path);
3321 return NULL;
3324 static const struct got_error *
3325 switch_head_ref(struct got_reference *head_ref,
3326 struct got_object_id *commit_id, struct got_worktree *worktree,
3327 struct got_repository *repo)
3329 const struct got_error *err = NULL;
3330 char *base_id_str;
3331 int ref_has_moved = 0;
3333 /* Trivial case: switching between two different references. */
3334 if (strcmp(got_ref_get_name(head_ref),
3335 got_worktree_get_head_ref_name(worktree)) != 0) {
3336 printf("Switching work tree from %s to %s\n",
3337 got_worktree_get_head_ref_name(worktree),
3338 got_ref_get_name(head_ref));
3339 return got_worktree_set_head_ref(worktree, head_ref);
3342 err = check_linear_ancestry(commit_id,
3343 got_worktree_get_base_commit_id(worktree), 0, repo);
3344 if (err) {
3345 if (err->code != GOT_ERR_ANCESTRY)
3346 return err;
3347 ref_has_moved = 1;
3349 if (!ref_has_moved)
3350 return NULL;
3352 /* Switching to a rebased branch with the same reference name. */
3353 err = got_object_id_str(&base_id_str,
3354 got_worktree_get_base_commit_id(worktree));
3355 if (err)
3356 return err;
3357 printf("Reference %s now points at a different branch\n",
3358 got_worktree_get_head_ref_name(worktree));
3359 printf("Switching work tree from %s to %s\n", base_id_str,
3360 got_worktree_get_head_ref_name(worktree));
3361 return NULL;
3364 static const struct got_error *
3365 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3367 const struct got_error *err;
3368 int in_progress;
3370 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3371 if (err)
3372 return err;
3373 if (in_progress)
3374 return got_error(GOT_ERR_REBASING);
3376 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3377 if (err)
3378 return err;
3379 if (in_progress)
3380 return got_error(GOT_ERR_HISTEDIT_BUSY);
3382 return NULL;
3385 static const struct got_error *
3386 check_merge_in_progress(struct got_worktree *worktree,
3387 struct got_repository *repo)
3389 const struct got_error *err;
3390 int in_progress;
3392 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3393 if (err)
3394 return err;
3395 if (in_progress)
3396 return got_error(GOT_ERR_MERGE_BUSY);
3398 return NULL;
3401 static const struct got_error *
3402 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3403 char *argv[], struct got_worktree *worktree)
3405 const struct got_error *err = NULL;
3406 char *path;
3407 struct got_pathlist_entry *new;
3408 int i;
3410 if (argc == 0) {
3411 path = strdup("");
3412 if (path == NULL)
3413 return got_error_from_errno("strdup");
3414 return got_pathlist_append(paths, path, NULL);
3417 for (i = 0; i < argc; i++) {
3418 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3419 if (err)
3420 break;
3421 err = got_pathlist_insert(&new, paths, path, NULL);
3422 if (err || new == NULL /* duplicate */) {
3423 free(path);
3424 if (err)
3425 break;
3429 return err;
3432 static const struct got_error *
3433 wrap_not_worktree_error(const struct got_error *orig_err,
3434 const char *cmdname, const char *path)
3436 const struct got_error *err;
3437 struct got_repository *repo;
3438 static char msg[512];
3439 int *pack_fds = NULL;
3441 err = got_repo_pack_fds_open(&pack_fds);
3442 if (err)
3443 return err;
3445 err = got_repo_open(&repo, path, NULL, pack_fds);
3446 if (err)
3447 return orig_err;
3449 snprintf(msg, sizeof(msg),
3450 "'got %s' needs a work tree in addition to a git repository\n"
3451 "Work trees can be checked out from this Git repository with "
3452 "'got checkout'.\n"
3453 "The got(1) manual page contains more information.", cmdname);
3454 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3455 if (repo) {
3456 const struct got_error *close_err = got_repo_close(repo);
3457 if (err == NULL)
3458 err = close_err;
3460 if (pack_fds) {
3461 const struct got_error *pack_err =
3462 got_repo_pack_fds_close(pack_fds);
3463 if (err == NULL)
3464 err = pack_err;
3466 return err;
3469 static const struct got_error *
3470 cmd_update(int argc, char *argv[])
3472 const struct got_error *error = NULL;
3473 struct got_repository *repo = NULL;
3474 struct got_worktree *worktree = NULL;
3475 char *worktree_path = NULL;
3476 struct got_object_id *commit_id = NULL;
3477 char *commit_id_str = NULL;
3478 const char *branch_name = NULL;
3479 struct got_reference *head_ref = NULL;
3480 struct got_pathlist_head paths;
3481 struct got_pathlist_entry *pe;
3482 int ch, verbosity = 0;
3483 struct got_update_progress_arg upa;
3484 int *pack_fds = NULL;
3486 TAILQ_INIT(&paths);
3488 #ifndef PROFILE
3489 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3490 "unveil", NULL) == -1)
3491 err(1, "pledge");
3492 #endif
3494 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3495 switch (ch) {
3496 case 'b':
3497 branch_name = optarg;
3498 break;
3499 case 'c':
3500 commit_id_str = strdup(optarg);
3501 if (commit_id_str == NULL)
3502 return got_error_from_errno("strdup");
3503 break;
3504 case 'q':
3505 verbosity = -1;
3506 break;
3507 default:
3508 usage_update();
3509 /* NOTREACHED */
3513 argc -= optind;
3514 argv += optind;
3516 worktree_path = getcwd(NULL, 0);
3517 if (worktree_path == NULL) {
3518 error = got_error_from_errno("getcwd");
3519 goto done;
3522 error = got_repo_pack_fds_open(&pack_fds);
3523 if (error != NULL)
3524 goto done;
3526 error = got_worktree_open(&worktree, worktree_path);
3527 if (error) {
3528 if (error->code == GOT_ERR_NOT_WORKTREE)
3529 error = wrap_not_worktree_error(error, "update",
3530 worktree_path);
3531 goto done;
3534 error = check_rebase_or_histedit_in_progress(worktree);
3535 if (error)
3536 goto done;
3538 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3539 NULL, pack_fds);
3540 if (error != NULL)
3541 goto done;
3543 error = apply_unveil(got_repo_get_path(repo), 0,
3544 got_worktree_get_root_path(worktree));
3545 if (error)
3546 goto done;
3548 error = check_merge_in_progress(worktree, repo);
3549 if (error)
3550 goto done;
3552 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3553 if (error)
3554 goto done;
3556 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3557 got_worktree_get_head_ref_name(worktree), 0);
3558 if (error != NULL)
3559 goto done;
3560 if (commit_id_str == NULL) {
3561 error = got_ref_resolve(&commit_id, repo, head_ref);
3562 if (error != NULL)
3563 goto done;
3564 error = got_object_id_str(&commit_id_str, commit_id);
3565 if (error != NULL)
3566 goto done;
3567 } else {
3568 struct got_reflist_head refs;
3569 char *keyword_idstr = NULL;
3571 TAILQ_INIT(&refs);
3573 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3574 NULL);
3575 if (error)
3576 goto done;
3578 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3579 repo, worktree);
3580 if (error != NULL)
3581 goto done;
3582 if (keyword_idstr != NULL) {
3583 free(commit_id_str);
3584 commit_id_str = keyword_idstr;
3587 error = got_repo_match_object_id(&commit_id, NULL,
3588 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3589 got_ref_list_free(&refs);
3590 free(commit_id_str);
3591 commit_id_str = NULL;
3592 if (error)
3593 goto done;
3594 error = got_object_id_str(&commit_id_str, commit_id);
3595 if (error)
3596 goto done;
3599 if (branch_name) {
3600 struct got_object_id *head_commit_id;
3601 TAILQ_FOREACH(pe, &paths, entry) {
3602 if (pe->path_len == 0)
3603 continue;
3604 error = got_error_msg(GOT_ERR_BAD_PATH,
3605 "switching between branches requires that "
3606 "the entire work tree gets updated");
3607 goto done;
3609 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3610 if (error)
3611 goto done;
3612 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3613 repo);
3614 free(head_commit_id);
3615 if (error != NULL)
3616 goto done;
3617 error = check_same_branch(commit_id, head_ref, repo);
3618 if (error)
3619 goto done;
3620 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3621 if (error)
3622 goto done;
3623 } else {
3624 error = check_linear_ancestry(commit_id,
3625 got_worktree_get_base_commit_id(worktree), 0, repo);
3626 if (error != NULL) {
3627 if (error->code == GOT_ERR_ANCESTRY)
3628 error = got_error(GOT_ERR_BRANCH_MOVED);
3629 goto done;
3631 error = check_same_branch(commit_id, head_ref, repo);
3632 if (error)
3633 goto done;
3636 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3637 commit_id) != 0) {
3638 error = got_worktree_set_base_commit_id(worktree, repo,
3639 commit_id);
3640 if (error)
3641 goto done;
3644 memset(&upa, 0, sizeof(upa));
3645 upa.verbosity = verbosity;
3646 error = got_worktree_checkout_files(worktree, &paths, repo,
3647 update_progress, &upa, check_cancelled, NULL);
3648 if (error != NULL)
3649 goto done;
3651 if (upa.did_something) {
3652 printf("Updated to %s: %s\n",
3653 got_worktree_get_head_ref_name(worktree), commit_id_str);
3654 } else
3655 printf("Already up-to-date\n");
3657 print_update_progress_stats(&upa);
3658 done:
3659 if (pack_fds) {
3660 const struct got_error *pack_err =
3661 got_repo_pack_fds_close(pack_fds);
3662 if (error == NULL)
3663 error = pack_err;
3665 if (repo) {
3666 const struct got_error *close_err = got_repo_close(repo);
3667 if (error == NULL)
3668 error = close_err;
3670 free(worktree_path);
3671 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3672 free(commit_id);
3673 free(commit_id_str);
3674 return error;
3677 static const struct got_error *
3678 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3679 const char *path, int diff_context, int ignore_whitespace,
3680 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3681 struct got_repository *repo, FILE *outfile)
3683 const struct got_error *err = NULL;
3684 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3685 FILE *f1 = NULL, *f2 = NULL;
3686 int fd1 = -1, fd2 = -1;
3688 fd1 = got_opentempfd();
3689 if (fd1 == -1)
3690 return got_error_from_errno("got_opentempfd");
3691 fd2 = got_opentempfd();
3692 if (fd2 == -1) {
3693 err = got_error_from_errno("got_opentempfd");
3694 goto done;
3697 if (blob_id1) {
3698 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3699 fd1);
3700 if (err)
3701 goto done;
3704 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3705 if (err)
3706 goto done;
3708 f1 = got_opentemp();
3709 if (f1 == NULL) {
3710 err = got_error_from_errno("got_opentemp");
3711 goto done;
3713 f2 = got_opentemp();
3714 if (f2 == NULL) {
3715 err = got_error_from_errno("got_opentemp");
3716 goto done;
3719 while (path[0] == '/')
3720 path++;
3721 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3722 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3723 force_text_diff, dsa, outfile);
3724 done:
3725 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3726 err = got_error_from_errno("close");
3727 if (blob1)
3728 got_object_blob_close(blob1);
3729 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3730 err = got_error_from_errno("close");
3731 if (blob2)
3732 got_object_blob_close(blob2);
3733 if (f1 && fclose(f1) == EOF && err == NULL)
3734 err = got_error_from_errno("fclose");
3735 if (f2 && fclose(f2) == EOF && err == NULL)
3736 err = got_error_from_errno("fclose");
3737 return err;
3740 static const struct got_error *
3741 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3742 const char *path, int diff_context, int ignore_whitespace,
3743 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3744 struct got_repository *repo, FILE *outfile)
3746 const struct got_error *err = NULL;
3747 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3748 struct got_diff_blob_output_unidiff_arg arg;
3749 FILE *f1 = NULL, *f2 = NULL;
3750 int fd1 = -1, fd2 = -1;
3752 if (tree_id1) {
3753 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3754 if (err)
3755 goto done;
3756 fd1 = got_opentempfd();
3757 if (fd1 == -1) {
3758 err = got_error_from_errno("got_opentempfd");
3759 goto done;
3763 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3764 if (err)
3765 goto done;
3767 f1 = got_opentemp();
3768 if (f1 == NULL) {
3769 err = got_error_from_errno("got_opentemp");
3770 goto done;
3773 f2 = got_opentemp();
3774 if (f2 == NULL) {
3775 err = got_error_from_errno("got_opentemp");
3776 goto done;
3778 fd2 = got_opentempfd();
3779 if (fd2 == -1) {
3780 err = got_error_from_errno("got_opentempfd");
3781 goto done;
3783 arg.diff_context = diff_context;
3784 arg.ignore_whitespace = ignore_whitespace;
3785 arg.force_text_diff = force_text_diff;
3786 arg.diffstat = dsa;
3787 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3788 arg.outfile = outfile;
3789 arg.lines = NULL;
3790 arg.nlines = 0;
3791 while (path[0] == '/')
3792 path++;
3793 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3794 got_diff_blob_output_unidiff, &arg, 1);
3795 done:
3796 if (tree1)
3797 got_object_tree_close(tree1);
3798 if (tree2)
3799 got_object_tree_close(tree2);
3800 if (f1 && fclose(f1) == EOF && err == NULL)
3801 err = got_error_from_errno("fclose");
3802 if (f2 && fclose(f2) == EOF && err == NULL)
3803 err = got_error_from_errno("fclose");
3804 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3805 err = got_error_from_errno("close");
3806 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3807 err = got_error_from_errno("close");
3808 return err;
3811 static const struct got_error *
3812 get_changed_paths(struct got_pathlist_head *paths,
3813 struct got_commit_object *commit, struct got_repository *repo,
3814 struct got_diffstat_cb_arg *dsa)
3816 const struct got_error *err = NULL;
3817 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3818 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3819 struct got_object_qid *qid;
3820 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3821 FILE *f1 = NULL, *f2 = NULL;
3822 int fd1 = -1, fd2 = -1;
3824 if (dsa) {
3825 cb = got_diff_tree_compute_diffstat;
3827 f1 = got_opentemp();
3828 if (f1 == NULL) {
3829 err = got_error_from_errno("got_opentemp");
3830 goto done;
3832 f2 = got_opentemp();
3833 if (f2 == NULL) {
3834 err = got_error_from_errno("got_opentemp");
3835 goto done;
3837 fd1 = got_opentempfd();
3838 if (fd1 == -1) {
3839 err = got_error_from_errno("got_opentempfd");
3840 goto done;
3842 fd2 = got_opentempfd();
3843 if (fd2 == -1) {
3844 err = got_error_from_errno("got_opentempfd");
3845 goto done;
3849 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3850 if (qid != NULL) {
3851 struct got_commit_object *pcommit;
3852 err = got_object_open_as_commit(&pcommit, repo,
3853 &qid->id);
3854 if (err)
3855 return err;
3857 tree_id1 = got_object_id_dup(
3858 got_object_commit_get_tree_id(pcommit));
3859 if (tree_id1 == NULL) {
3860 got_object_commit_close(pcommit);
3861 return got_error_from_errno("got_object_id_dup");
3863 got_object_commit_close(pcommit);
3867 if (tree_id1) {
3868 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3869 if (err)
3870 goto done;
3873 tree_id2 = got_object_commit_get_tree_id(commit);
3874 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3875 if (err)
3876 goto done;
3878 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3879 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3880 done:
3881 if (tree1)
3882 got_object_tree_close(tree1);
3883 if (tree2)
3884 got_object_tree_close(tree2);
3885 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3886 err = got_error_from_errno("close");
3887 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3888 err = got_error_from_errno("close");
3889 if (f1 && fclose(f1) == EOF && err == NULL)
3890 err = got_error_from_errno("fclose");
3891 if (f2 && fclose(f2) == EOF && err == NULL)
3892 err = got_error_from_errno("fclose");
3893 free(tree_id1);
3894 return err;
3897 static const struct got_error *
3898 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3899 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3900 struct got_repository *repo, FILE *outfile)
3902 const struct got_error *err = NULL;
3903 struct got_commit_object *pcommit = NULL;
3904 char *id_str1 = NULL, *id_str2 = NULL;
3905 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3906 struct got_object_qid *qid;
3908 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3909 if (qid != NULL) {
3910 err = got_object_open_as_commit(&pcommit, repo,
3911 &qid->id);
3912 if (err)
3913 return err;
3914 err = got_object_id_str(&id_str1, &qid->id);
3915 if (err)
3916 goto done;
3919 err = got_object_id_str(&id_str2, id);
3920 if (err)
3921 goto done;
3923 if (path && path[0] != '\0') {
3924 int obj_type;
3925 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3926 if (err)
3927 goto done;
3928 if (pcommit) {
3929 err = got_object_id_by_path(&obj_id1, repo,
3930 pcommit, path);
3931 if (err) {
3932 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3933 free(obj_id2);
3934 goto done;
3938 err = got_object_get_type(&obj_type, repo, obj_id2);
3939 if (err) {
3940 free(obj_id2);
3941 goto done;
3943 fprintf(outfile,
3944 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3945 fprintf(outfile, "commit - %s\n",
3946 id_str1 ? id_str1 : "/dev/null");
3947 fprintf(outfile, "commit + %s\n", id_str2);
3948 switch (obj_type) {
3949 case GOT_OBJ_TYPE_BLOB:
3950 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3951 0, 0, dsa, repo, outfile);
3952 break;
3953 case GOT_OBJ_TYPE_TREE:
3954 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3955 0, 0, dsa, repo, outfile);
3956 break;
3957 default:
3958 err = got_error(GOT_ERR_OBJ_TYPE);
3959 break;
3961 free(obj_id1);
3962 free(obj_id2);
3963 } else {
3964 obj_id2 = got_object_commit_get_tree_id(commit);
3965 if (pcommit)
3966 obj_id1 = got_object_commit_get_tree_id(pcommit);
3967 fprintf(outfile,
3968 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3969 fprintf(outfile, "commit - %s\n",
3970 id_str1 ? id_str1 : "/dev/null");
3971 fprintf(outfile, "commit + %s\n", id_str2);
3972 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3973 dsa, repo, outfile);
3975 done:
3976 free(id_str1);
3977 free(id_str2);
3978 if (pcommit)
3979 got_object_commit_close(pcommit);
3980 return err;
3983 static char *
3984 get_datestr(time_t *time, char *datebuf)
3986 struct tm mytm, *tm;
3987 char *p, *s;
3989 tm = gmtime_r(time, &mytm);
3990 if (tm == NULL)
3991 return NULL;
3992 s = asctime_r(tm, datebuf);
3993 if (s == NULL)
3994 return NULL;
3995 p = strchr(s, '\n');
3996 if (p)
3997 *p = '\0';
3998 return s;
4001 static const struct got_error *
4002 match_commit(int *have_match, struct got_object_id *id,
4003 struct got_commit_object *commit, regex_t *regex)
4005 const struct got_error *err = NULL;
4006 regmatch_t regmatch;
4007 char *id_str = NULL, *logmsg = NULL;
4009 *have_match = 0;
4011 err = got_object_id_str(&id_str, id);
4012 if (err)
4013 return err;
4015 err = got_object_commit_get_logmsg(&logmsg, commit);
4016 if (err)
4017 goto done;
4019 if (regexec(regex, got_object_commit_get_author(commit), 1,
4020 &regmatch, 0) == 0 ||
4021 regexec(regex, got_object_commit_get_committer(commit), 1,
4022 &regmatch, 0) == 0 ||
4023 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4024 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4025 *have_match = 1;
4026 done:
4027 free(id_str);
4028 free(logmsg);
4029 return err;
4032 static void
4033 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4034 regex_t *regex)
4036 regmatch_t regmatch;
4037 struct got_pathlist_entry *pe;
4039 *have_match = 0;
4041 TAILQ_FOREACH(pe, changed_paths, entry) {
4042 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4043 *have_match = 1;
4044 break;
4049 static const struct got_error *
4050 match_patch(int *have_match, struct got_commit_object *commit,
4051 struct got_object_id *id, const char *path, int diff_context,
4052 struct got_repository *repo, regex_t *regex, FILE *f)
4054 const struct got_error *err = NULL;
4055 char *line = NULL;
4056 size_t linesize = 0;
4057 regmatch_t regmatch;
4059 *have_match = 0;
4061 err = got_opentemp_truncate(f);
4062 if (err)
4063 return err;
4065 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4066 if (err)
4067 goto done;
4069 if (fseeko(f, 0L, SEEK_SET) == -1) {
4070 err = got_error_from_errno("fseeko");
4071 goto done;
4074 while (getline(&line, &linesize, f) != -1) {
4075 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4076 *have_match = 1;
4077 break;
4080 done:
4081 free(line);
4082 return err;
4085 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4087 static const struct got_error*
4088 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4089 struct got_object_id *id, struct got_repository *repo,
4090 int local_only)
4092 static const struct got_error *err = NULL;
4093 struct got_reflist_entry *re;
4094 char *s;
4095 const char *name;
4097 *refs_str = NULL;
4099 TAILQ_FOREACH(re, refs, entry) {
4100 struct got_tag_object *tag = NULL;
4101 struct got_object_id *ref_id;
4102 int cmp;
4104 name = got_ref_get_name(re->ref);
4105 if (strcmp(name, GOT_REF_HEAD) == 0)
4106 continue;
4107 if (strncmp(name, "refs/", 5) == 0)
4108 name += 5;
4109 if (strncmp(name, "got/", 4) == 0)
4110 continue;
4111 if (strncmp(name, "heads/", 6) == 0)
4112 name += 6;
4113 if (strncmp(name, "remotes/", 8) == 0) {
4114 if (local_only)
4115 continue;
4116 name += 8;
4117 s = strstr(name, "/" GOT_REF_HEAD);
4118 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4119 continue;
4121 err = got_ref_resolve(&ref_id, repo, re->ref);
4122 if (err)
4123 break;
4124 if (strncmp(name, "tags/", 5) == 0) {
4125 err = got_object_open_as_tag(&tag, repo, ref_id);
4126 if (err) {
4127 if (err->code != GOT_ERR_OBJ_TYPE) {
4128 free(ref_id);
4129 break;
4131 /* Ref points at something other than a tag. */
4132 err = NULL;
4133 tag = NULL;
4136 cmp = got_object_id_cmp(tag ?
4137 got_object_tag_get_object_id(tag) : ref_id, id);
4138 free(ref_id);
4139 if (tag)
4140 got_object_tag_close(tag);
4141 if (cmp != 0)
4142 continue;
4143 s = *refs_str;
4144 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4145 s ? ", " : "", name) == -1) {
4146 err = got_error_from_errno("asprintf");
4147 free(s);
4148 *refs_str = NULL;
4149 break;
4151 free(s);
4154 return err;
4157 static const struct got_error *
4158 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4159 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4161 const struct got_error *err = NULL;
4162 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4163 char *comma, *s, *nl;
4164 struct got_reflist_head *refs;
4165 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4166 struct tm tm;
4167 time_t committer_time;
4169 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4170 if (refs) {
4171 err = build_refs_str(&ref_str, refs, id, repo, 1);
4172 if (err)
4173 return err;
4175 /* Display the first matching ref only. */
4176 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4177 *comma = '\0';
4180 if (ref_str == NULL) {
4181 err = got_object_id_str(&id_str, id);
4182 if (err)
4183 return err;
4186 committer_time = got_object_commit_get_committer_time(commit);
4187 if (gmtime_r(&committer_time, &tm) == NULL) {
4188 err = got_error_from_errno("gmtime_r");
4189 goto done;
4191 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4192 err = got_error(GOT_ERR_NO_SPACE);
4193 goto done;
4196 err = got_object_commit_get_logmsg(&logmsg0, commit);
4197 if (err)
4198 goto done;
4200 s = logmsg0;
4201 while (isspace((unsigned char)s[0]))
4202 s++;
4204 nl = strchr(s, '\n');
4205 if (nl) {
4206 *nl = '\0';
4209 if (ref_str)
4210 printf("%s%-7s %s\n", datebuf, ref_str, s);
4211 else
4212 printf("%s%.7s %s\n", datebuf, id_str, s);
4214 if (fflush(stdout) != 0 && err == NULL)
4215 err = got_error_from_errno("fflush");
4216 done:
4217 free(id_str);
4218 free(ref_str);
4219 free(logmsg0);
4220 return err;
4223 static const struct got_error *
4224 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4226 struct got_pathlist_entry *pe;
4228 if (header != NULL)
4229 printf("%s\n", header);
4231 TAILQ_FOREACH(pe, dsa->paths, entry) {
4232 struct got_diff_changed_path *cp = pe->data;
4233 int pad = dsa->max_path_len - pe->path_len + 1;
4235 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4236 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4238 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4239 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4240 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4242 if (fflush(stdout) != 0)
4243 return got_error_from_errno("fflush");
4245 return NULL;
4248 static const struct got_error *
4249 printfile(FILE *f)
4251 char buf[8192];
4252 size_t r;
4254 if (fseeko(f, 0L, SEEK_SET) == -1)
4255 return got_error_from_errno("fseek");
4257 for (;;) {
4258 r = fread(buf, 1, sizeof(buf), f);
4259 if (r == 0) {
4260 if (ferror(f))
4261 return got_error_from_errno("fread");
4262 if (feof(f))
4263 break;
4265 if (fwrite(buf, 1, r, stdout) != r)
4266 return got_ferror(stdout, GOT_ERR_IO);
4269 return NULL;
4272 static const struct got_error *
4273 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4274 struct got_repository *repo, const char *path,
4275 struct got_pathlist_head *changed_paths,
4276 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4277 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4278 const char *prefix)
4280 const struct got_error *err = NULL;
4281 FILE *f = NULL;
4282 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4283 char datebuf[26];
4284 time_t committer_time;
4285 const char *author, *committer;
4286 char *refs_str = NULL;
4288 err = got_object_id_str(&id_str, id);
4289 if (err)
4290 return err;
4292 if (custom_refs_str == NULL) {
4293 struct got_reflist_head *refs;
4294 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4295 if (refs) {
4296 err = build_refs_str(&refs_str, refs, id, repo, 0);
4297 if (err)
4298 goto done;
4302 printf(GOT_COMMIT_SEP_STR);
4303 if (custom_refs_str)
4304 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4305 custom_refs_str);
4306 else
4307 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4308 refs_str ? " (" : "", refs_str ? refs_str : "",
4309 refs_str ? ")" : "");
4310 free(id_str);
4311 id_str = NULL;
4312 free(refs_str);
4313 refs_str = NULL;
4314 printf("from: %s\n", got_object_commit_get_author(commit));
4315 author = got_object_commit_get_author(commit);
4316 committer = got_object_commit_get_committer(commit);
4317 if (strcmp(author, committer) != 0)
4318 printf("via: %s\n", committer);
4319 committer_time = got_object_commit_get_committer_time(commit);
4320 datestr = get_datestr(&committer_time, datebuf);
4321 if (datestr)
4322 printf("date: %s UTC\n", datestr);
4323 if (got_object_commit_get_nparents(commit) > 1) {
4324 const struct got_object_id_queue *parent_ids;
4325 struct got_object_qid *qid;
4326 int n = 1;
4327 parent_ids = got_object_commit_get_parent_ids(commit);
4328 STAILQ_FOREACH(qid, parent_ids, entry) {
4329 err = got_object_id_str(&id_str, &qid->id);
4330 if (err)
4331 goto done;
4332 printf("parent %d: %s\n", n++, id_str);
4333 free(id_str);
4334 id_str = NULL;
4338 err = got_object_commit_get_logmsg(&logmsg0, commit);
4339 if (err)
4340 goto done;
4342 logmsg = logmsg0;
4343 do {
4344 line = strsep(&logmsg, "\n");
4345 if (line)
4346 printf(" %s\n", line);
4347 } while (line);
4348 free(logmsg0);
4350 if (changed_paths && diffstat == NULL) {
4351 struct got_pathlist_entry *pe;
4353 TAILQ_FOREACH(pe, changed_paths, entry) {
4354 struct got_diff_changed_path *cp = pe->data;
4356 printf(" %c %s\n", cp->status, pe->path);
4358 printf("\n");
4360 if (show_patch) {
4361 if (diffstat) {
4362 f = got_opentemp();
4363 if (f == NULL) {
4364 err = got_error_from_errno("got_opentemp");
4365 goto done;
4369 err = print_patch(commit, id, path, diff_context, diffstat,
4370 repo, diffstat == NULL ? stdout : f);
4371 if (err)
4372 goto done;
4374 if (diffstat) {
4375 err = print_diffstat(diffstat, NULL);
4376 if (err)
4377 goto done;
4378 if (show_patch) {
4379 err = printfile(f);
4380 if (err)
4381 goto done;
4384 if (show_patch)
4385 printf("\n");
4387 if (fflush(stdout) != 0 && err == NULL)
4388 err = got_error_from_errno("fflush");
4389 done:
4390 if (f && fclose(f) == EOF && err == NULL)
4391 err = got_error_from_errno("fclose");
4392 free(id_str);
4393 free(refs_str);
4394 return err;
4397 static const struct got_error *
4398 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4399 struct got_repository *repo, const char *path, int show_changed_paths,
4400 int show_diffstat, int show_patch, const char *search_pattern,
4401 int diff_context, int limit, int log_branches, int reverse_display_order,
4402 struct got_reflist_object_id_map *refs_idmap, int one_line,
4403 FILE *tmpfile)
4405 const struct got_error *err;
4406 struct got_commit_graph *graph;
4407 regex_t regex;
4408 int have_match;
4409 struct got_object_id_queue reversed_commits;
4410 struct got_object_qid *qid;
4411 struct got_commit_object *commit;
4412 struct got_pathlist_head changed_paths;
4414 STAILQ_INIT(&reversed_commits);
4415 TAILQ_INIT(&changed_paths);
4417 if (search_pattern && regcomp(&regex, search_pattern,
4418 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4419 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4421 err = got_commit_graph_open(&graph, path, !log_branches);
4422 if (err)
4423 return err;
4424 err = got_commit_graph_iter_start(graph, root_id, repo,
4425 check_cancelled, NULL);
4426 if (err)
4427 goto done;
4428 for (;;) {
4429 struct got_object_id id;
4430 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4431 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4433 if (sigint_received || sigpipe_received)
4434 break;
4436 err = got_commit_graph_iter_next(&id, graph, repo,
4437 check_cancelled, NULL);
4438 if (err) {
4439 if (err->code == GOT_ERR_ITER_COMPLETED)
4440 err = NULL;
4441 break;
4444 err = got_object_open_as_commit(&commit, repo, &id);
4445 if (err)
4446 break;
4448 if ((show_changed_paths || (show_diffstat && !show_patch))
4449 && !reverse_display_order) {
4450 err = get_changed_paths(&changed_paths, commit, repo,
4451 show_diffstat ? &dsa : NULL);
4452 if (err)
4453 break;
4456 if (search_pattern) {
4457 err = match_commit(&have_match, &id, commit, &regex);
4458 if (err) {
4459 got_object_commit_close(commit);
4460 break;
4462 if (have_match == 0 && show_changed_paths)
4463 match_changed_paths(&have_match,
4464 &changed_paths, &regex);
4465 if (have_match == 0 && show_patch) {
4466 err = match_patch(&have_match, commit, &id,
4467 path, diff_context, repo, &regex, tmpfile);
4468 if (err)
4469 break;
4471 if (have_match == 0) {
4472 got_object_commit_close(commit);
4473 got_pathlist_free(&changed_paths,
4474 GOT_PATHLIST_FREE_ALL);
4475 continue;
4479 if (reverse_display_order) {
4480 err = got_object_qid_alloc(&qid, &id);
4481 if (err)
4482 break;
4483 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4484 got_object_commit_close(commit);
4485 } else {
4486 if (one_line)
4487 err = print_commit_oneline(commit, &id,
4488 repo, refs_idmap);
4489 else
4490 err = print_commit(commit, &id, repo, path,
4491 (show_changed_paths || show_diffstat) ?
4492 &changed_paths : NULL,
4493 show_diffstat ? &dsa : NULL, show_patch,
4494 diff_context, refs_idmap, NULL, NULL);
4495 got_object_commit_close(commit);
4496 if (err)
4497 break;
4499 if ((limit && --limit == 0) ||
4500 (end_id && got_object_id_cmp(&id, end_id) == 0))
4501 break;
4503 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4505 if (reverse_display_order) {
4506 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4507 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4508 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4510 err = got_object_open_as_commit(&commit, repo,
4511 &qid->id);
4512 if (err)
4513 break;
4514 if (show_changed_paths ||
4515 (show_diffstat && !show_patch)) {
4516 err = get_changed_paths(&changed_paths, commit,
4517 repo, show_diffstat ? &dsa : NULL);
4518 if (err)
4519 break;
4521 if (one_line)
4522 err = print_commit_oneline(commit, &qid->id,
4523 repo, refs_idmap);
4524 else
4525 err = print_commit(commit, &qid->id, repo, path,
4526 (show_changed_paths || show_diffstat) ?
4527 &changed_paths : NULL,
4528 show_diffstat ? &dsa : NULL, show_patch,
4529 diff_context, refs_idmap, NULL, NULL);
4530 got_object_commit_close(commit);
4531 if (err)
4532 break;
4533 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4536 done:
4537 while (!STAILQ_EMPTY(&reversed_commits)) {
4538 qid = STAILQ_FIRST(&reversed_commits);
4539 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4540 got_object_qid_free(qid);
4542 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4543 if (search_pattern)
4544 regfree(&regex);
4545 got_commit_graph_close(graph);
4546 return err;
4549 __dead static void
4550 usage_log(void)
4552 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4553 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4554 "[path]\n", getprogname());
4555 exit(1);
4558 static int
4559 get_default_log_limit(void)
4561 const char *got_default_log_limit;
4562 long long n;
4563 const char *errstr;
4565 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4566 if (got_default_log_limit == NULL)
4567 return 0;
4568 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4569 if (errstr != NULL)
4570 return 0;
4571 return n;
4574 static const struct got_error *
4575 cmd_log(int argc, char *argv[])
4577 const struct got_error *error;
4578 struct got_repository *repo = NULL;
4579 struct got_worktree *worktree = NULL;
4580 struct got_object_id *start_id = NULL, *end_id = NULL;
4581 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4582 const char *start_commit = NULL, *end_commit = NULL;
4583 const char *search_pattern = NULL;
4584 int diff_context = -1, ch;
4585 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4586 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4587 const char *errstr;
4588 struct got_reflist_head refs;
4589 struct got_reflist_object_id_map *refs_idmap = NULL;
4590 FILE *tmpfile = NULL;
4591 int *pack_fds = NULL;
4593 TAILQ_INIT(&refs);
4595 #ifndef PROFILE
4596 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4597 NULL)
4598 == -1)
4599 err(1, "pledge");
4600 #endif
4602 limit = get_default_log_limit();
4604 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4605 switch (ch) {
4606 case 'b':
4607 log_branches = 1;
4608 break;
4609 case 'C':
4610 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4611 &errstr);
4612 if (errstr != NULL)
4613 errx(1, "number of context lines is %s: %s",
4614 errstr, optarg);
4615 break;
4616 case 'c':
4617 start_commit = optarg;
4618 break;
4619 case 'd':
4620 show_diffstat = 1;
4621 break;
4622 case 'l':
4623 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4624 if (errstr != NULL)
4625 errx(1, "number of commits is %s: %s",
4626 errstr, optarg);
4627 break;
4628 case 'P':
4629 show_changed_paths = 1;
4630 break;
4631 case 'p':
4632 show_patch = 1;
4633 break;
4634 case 'R':
4635 reverse_display_order = 1;
4636 break;
4637 case 'r':
4638 repo_path = realpath(optarg, NULL);
4639 if (repo_path == NULL)
4640 return got_error_from_errno2("realpath",
4641 optarg);
4642 got_path_strip_trailing_slashes(repo_path);
4643 break;
4644 case 'S':
4645 search_pattern = optarg;
4646 break;
4647 case 's':
4648 one_line = 1;
4649 break;
4650 case 'x':
4651 end_commit = optarg;
4652 break;
4653 default:
4654 usage_log();
4655 /* NOTREACHED */
4659 argc -= optind;
4660 argv += optind;
4662 if (diff_context == -1)
4663 diff_context = 3;
4664 else if (!show_patch)
4665 errx(1, "-C requires -p");
4667 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4668 errx(1, "cannot use -s with -d, -p or -P");
4670 cwd = getcwd(NULL, 0);
4671 if (cwd == NULL) {
4672 error = got_error_from_errno("getcwd");
4673 goto done;
4676 error = got_repo_pack_fds_open(&pack_fds);
4677 if (error != NULL)
4678 goto done;
4680 if (repo_path == NULL) {
4681 error = got_worktree_open(&worktree, cwd);
4682 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4683 goto done;
4684 error = NULL;
4687 if (argc == 1) {
4688 if (worktree) {
4689 error = got_worktree_resolve_path(&path, worktree,
4690 argv[0]);
4691 if (error)
4692 goto done;
4693 } else {
4694 path = strdup(argv[0]);
4695 if (path == NULL) {
4696 error = got_error_from_errno("strdup");
4697 goto done;
4700 } else if (argc != 0)
4701 usage_log();
4703 if (repo_path == NULL) {
4704 repo_path = worktree ?
4705 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4707 if (repo_path == NULL) {
4708 error = got_error_from_errno("strdup");
4709 goto done;
4712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4713 if (error != NULL)
4714 goto done;
4716 error = apply_unveil(got_repo_get_path(repo), 1,
4717 worktree ? got_worktree_get_root_path(worktree) : NULL);
4718 if (error)
4719 goto done;
4721 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4722 if (error)
4723 goto done;
4725 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4726 if (error)
4727 goto done;
4729 if (start_commit == NULL) {
4730 struct got_reference *head_ref;
4731 struct got_commit_object *commit = NULL;
4732 error = got_ref_open(&head_ref, repo,
4733 worktree ? got_worktree_get_head_ref_name(worktree)
4734 : GOT_REF_HEAD, 0);
4735 if (error != NULL)
4736 goto done;
4737 error = got_ref_resolve(&start_id, repo, head_ref);
4738 got_ref_close(head_ref);
4739 if (error != NULL)
4740 goto done;
4741 error = got_object_open_as_commit(&commit, repo,
4742 start_id);
4743 if (error != NULL)
4744 goto done;
4745 got_object_commit_close(commit);
4746 } else {
4747 char *keyword_idstr = NULL;
4749 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4750 repo, worktree);
4751 if (error != NULL)
4752 goto done;
4753 if (keyword_idstr != NULL)
4754 start_commit = keyword_idstr;
4756 error = got_repo_match_object_id(&start_id, NULL,
4757 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4758 free(keyword_idstr);
4759 if (error != NULL)
4760 goto done;
4762 if (end_commit != NULL) {
4763 error = got_repo_match_object_id(&end_id, NULL,
4764 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4765 if (error != NULL)
4766 goto done;
4769 if (worktree) {
4771 * If a path was specified on the command line it was resolved
4772 * to a path in the work tree above. Prepend the work tree's
4773 * path prefix to obtain the corresponding in-repository path.
4775 if (path) {
4776 const char *prefix;
4777 prefix = got_worktree_get_path_prefix(worktree);
4778 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4779 (path[0] != '\0') ? "/" : "", path) == -1) {
4780 error = got_error_from_errno("asprintf");
4781 goto done;
4784 } else
4785 error = got_repo_map_path(&in_repo_path, repo,
4786 path ? path : "");
4787 if (error != NULL)
4788 goto done;
4789 if (in_repo_path) {
4790 free(path);
4791 path = in_repo_path;
4794 if (worktree) {
4795 /* Release work tree lock. */
4796 got_worktree_close(worktree);
4797 worktree = NULL;
4800 if (search_pattern && show_patch) {
4801 tmpfile = got_opentemp();
4802 if (tmpfile == NULL) {
4803 error = got_error_from_errno("got_opentemp");
4804 goto done;
4808 error = print_commits(start_id, end_id, repo, path ? path : "",
4809 show_changed_paths, show_diffstat, show_patch, search_pattern,
4810 diff_context, limit, log_branches, reverse_display_order,
4811 refs_idmap, one_line, tmpfile);
4812 done:
4813 free(path);
4814 free(repo_path);
4815 free(cwd);
4816 free(start_id);
4817 free(end_id);
4818 if (worktree)
4819 got_worktree_close(worktree);
4820 if (repo) {
4821 const struct got_error *close_err = got_repo_close(repo);
4822 if (error == NULL)
4823 error = close_err;
4825 if (pack_fds) {
4826 const struct got_error *pack_err =
4827 got_repo_pack_fds_close(pack_fds);
4828 if (error == NULL)
4829 error = pack_err;
4831 if (refs_idmap)
4832 got_reflist_object_id_map_free(refs_idmap);
4833 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4834 error = got_error_from_errno("fclose");
4835 got_ref_list_free(&refs);
4836 return error;
4839 __dead static void
4840 usage_diff(void)
4842 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4843 "[-r repository-path] [object1 object2 | path ...]\n",
4844 getprogname());
4845 exit(1);
4848 struct print_diff_arg {
4849 struct got_repository *repo;
4850 struct got_worktree *worktree;
4851 struct got_diffstat_cb_arg *diffstat;
4852 int diff_context;
4853 const char *id_str;
4854 int header_shown;
4855 int diff_staged;
4856 enum got_diff_algorithm diff_algo;
4857 int ignore_whitespace;
4858 int force_text_diff;
4859 FILE *f1;
4860 FILE *f2;
4861 FILE *outfile;
4865 * Create a file which contains the target path of a symlink so we can feed
4866 * it as content to the diff engine.
4868 static const struct got_error *
4869 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4870 const char *abspath)
4872 const struct got_error *err = NULL;
4873 char target_path[PATH_MAX];
4874 ssize_t target_len, outlen;
4876 *fd = -1;
4878 if (dirfd != -1) {
4879 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4880 if (target_len == -1)
4881 return got_error_from_errno2("readlinkat", abspath);
4882 } else {
4883 target_len = readlink(abspath, target_path, PATH_MAX);
4884 if (target_len == -1)
4885 return got_error_from_errno2("readlink", abspath);
4888 *fd = got_opentempfd();
4889 if (*fd == -1)
4890 return got_error_from_errno("got_opentempfd");
4892 outlen = write(*fd, target_path, target_len);
4893 if (outlen == -1) {
4894 err = got_error_from_errno("got_opentempfd");
4895 goto done;
4898 if (lseek(*fd, 0, SEEK_SET) == -1) {
4899 err = got_error_from_errno2("lseek", abspath);
4900 goto done;
4902 done:
4903 if (err) {
4904 close(*fd);
4905 *fd = -1;
4907 return err;
4910 static const struct got_error *
4911 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4912 const char *path, struct got_object_id *blob_id,
4913 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4914 int dirfd, const char *de_name)
4916 struct print_diff_arg *a = arg;
4917 const struct got_error *err = NULL;
4918 struct got_blob_object *blob1 = NULL;
4919 int fd = -1, fd1 = -1, fd2 = -1;
4920 FILE *f2 = NULL;
4921 char *abspath = NULL, *label1 = NULL;
4922 struct stat sb;
4923 off_t size1 = 0;
4924 int f2_exists = 0;
4926 memset(&sb, 0, sizeof(sb));
4928 if (a->diff_staged) {
4929 if (staged_status != GOT_STATUS_MODIFY &&
4930 staged_status != GOT_STATUS_ADD &&
4931 staged_status != GOT_STATUS_DELETE)
4932 return NULL;
4933 } else {
4934 if (staged_status == GOT_STATUS_DELETE)
4935 return NULL;
4936 if (status == GOT_STATUS_NONEXISTENT)
4937 return got_error_set_errno(ENOENT, path);
4938 if (status != GOT_STATUS_MODIFY &&
4939 status != GOT_STATUS_ADD &&
4940 status != GOT_STATUS_DELETE &&
4941 status != GOT_STATUS_CONFLICT)
4942 return NULL;
4945 err = got_opentemp_truncate(a->f1);
4946 if (err)
4947 return got_error_from_errno("got_opentemp_truncate");
4948 err = got_opentemp_truncate(a->f2);
4949 if (err)
4950 return got_error_from_errno("got_opentemp_truncate");
4952 if (!a->header_shown) {
4953 if (fprintf(a->outfile, "diff %s%s\n",
4954 a->diff_staged ? "-s " : "",
4955 got_worktree_get_root_path(a->worktree)) < 0) {
4956 err = got_error_from_errno("fprintf");
4957 goto done;
4959 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4960 err = got_error_from_errno("fprintf");
4961 goto done;
4963 if (fprintf(a->outfile, "path + %s%s\n",
4964 got_worktree_get_root_path(a->worktree),
4965 a->diff_staged ? " (staged changes)" : "") < 0) {
4966 err = got_error_from_errno("fprintf");
4967 goto done;
4969 a->header_shown = 1;
4972 if (a->diff_staged) {
4973 const char *label1 = NULL, *label2 = NULL;
4974 switch (staged_status) {
4975 case GOT_STATUS_MODIFY:
4976 label1 = path;
4977 label2 = path;
4978 break;
4979 case GOT_STATUS_ADD:
4980 label2 = path;
4981 break;
4982 case GOT_STATUS_DELETE:
4983 label1 = path;
4984 break;
4985 default:
4986 return got_error(GOT_ERR_FILE_STATUS);
4988 fd1 = got_opentempfd();
4989 if (fd1 == -1) {
4990 err = got_error_from_errno("got_opentempfd");
4991 goto done;
4993 fd2 = got_opentempfd();
4994 if (fd2 == -1) {
4995 err = got_error_from_errno("got_opentempfd");
4996 goto done;
4998 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4999 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5000 a->diff_algo, a->diff_context, a->ignore_whitespace,
5001 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5002 goto done;
5005 fd1 = got_opentempfd();
5006 if (fd1 == -1) {
5007 err = got_error_from_errno("got_opentempfd");
5008 goto done;
5011 if (staged_status == GOT_STATUS_ADD ||
5012 staged_status == GOT_STATUS_MODIFY) {
5013 char *id_str;
5014 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5015 8192, fd1);
5016 if (err)
5017 goto done;
5018 err = got_object_id_str(&id_str, staged_blob_id);
5019 if (err)
5020 goto done;
5021 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5022 err = got_error_from_errno("asprintf");
5023 free(id_str);
5024 goto done;
5026 free(id_str);
5027 } else if (status != GOT_STATUS_ADD) {
5028 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5029 fd1);
5030 if (err)
5031 goto done;
5034 if (status != GOT_STATUS_DELETE) {
5035 if (asprintf(&abspath, "%s/%s",
5036 got_worktree_get_root_path(a->worktree), path) == -1) {
5037 err = got_error_from_errno("asprintf");
5038 goto done;
5041 if (dirfd != -1) {
5042 fd = openat(dirfd, de_name,
5043 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5044 if (fd == -1) {
5045 if (!got_err_open_nofollow_on_symlink()) {
5046 err = got_error_from_errno2("openat",
5047 abspath);
5048 goto done;
5050 err = get_symlink_target_file(&fd, dirfd,
5051 de_name, abspath);
5052 if (err)
5053 goto done;
5055 } else {
5056 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5057 if (fd == -1) {
5058 if (!got_err_open_nofollow_on_symlink()) {
5059 err = got_error_from_errno2("open",
5060 abspath);
5061 goto done;
5063 err = get_symlink_target_file(&fd, dirfd,
5064 de_name, abspath);
5065 if (err)
5066 goto done;
5069 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5070 err = got_error_from_errno2("fstatat", abspath);
5071 goto done;
5073 f2 = fdopen(fd, "r");
5074 if (f2 == NULL) {
5075 err = got_error_from_errno2("fdopen", abspath);
5076 goto done;
5078 fd = -1;
5079 f2_exists = 1;
5082 if (blob1) {
5083 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5084 a->f1, blob1);
5085 if (err)
5086 goto done;
5089 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5090 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5091 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5092 done:
5093 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5094 err = got_error_from_errno("close");
5095 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5096 err = got_error_from_errno("close");
5097 if (blob1)
5098 got_object_blob_close(blob1);
5099 if (fd != -1 && close(fd) == -1 && err == NULL)
5100 err = got_error_from_errno("close");
5101 if (f2 && fclose(f2) == EOF && err == NULL)
5102 err = got_error_from_errno("fclose");
5103 free(abspath);
5104 return err;
5107 static const struct got_error *
5108 cmd_diff(int argc, char *argv[])
5110 const struct got_error *error;
5111 struct got_repository *repo = NULL;
5112 struct got_worktree *worktree = NULL;
5113 char *cwd = NULL, *repo_path = NULL;
5114 const char *commit_args[2] = { NULL, NULL };
5115 int ncommit_args = 0;
5116 struct got_object_id *ids[2] = { NULL, NULL };
5117 char *labels[2] = { NULL, NULL };
5118 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5119 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5120 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5121 const char *errstr;
5122 struct got_reflist_head refs;
5123 struct got_pathlist_head diffstat_paths, paths;
5124 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5125 int fd1 = -1, fd2 = -1;
5126 int *pack_fds = NULL;
5127 struct got_diffstat_cb_arg dsa;
5129 memset(&dsa, 0, sizeof(dsa));
5131 TAILQ_INIT(&refs);
5132 TAILQ_INIT(&paths);
5133 TAILQ_INIT(&diffstat_paths);
5135 #ifndef PROFILE
5136 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5137 NULL) == -1)
5138 err(1, "pledge");
5139 #endif
5141 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5142 switch (ch) {
5143 case 'a':
5144 force_text_diff = 1;
5145 break;
5146 case 'C':
5147 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5148 &errstr);
5149 if (errstr != NULL)
5150 errx(1, "number of context lines is %s: %s",
5151 errstr, optarg);
5152 break;
5153 case 'c':
5154 if (ncommit_args >= 2)
5155 errx(1, "too many -c options used");
5156 commit_args[ncommit_args++] = optarg;
5157 break;
5158 case 'd':
5159 show_diffstat = 1;
5160 break;
5161 case 'P':
5162 force_path = 1;
5163 break;
5164 case 'r':
5165 repo_path = realpath(optarg, NULL);
5166 if (repo_path == NULL)
5167 return got_error_from_errno2("realpath",
5168 optarg);
5169 got_path_strip_trailing_slashes(repo_path);
5170 rflag = 1;
5171 break;
5172 case 's':
5173 diff_staged = 1;
5174 break;
5175 case 'w':
5176 ignore_whitespace = 1;
5177 break;
5178 default:
5179 usage_diff();
5180 /* NOTREACHED */
5184 argc -= optind;
5185 argv += optind;
5187 cwd = getcwd(NULL, 0);
5188 if (cwd == NULL) {
5189 error = got_error_from_errno("getcwd");
5190 goto done;
5193 error = got_repo_pack_fds_open(&pack_fds);
5194 if (error != NULL)
5195 goto done;
5197 if (repo_path == NULL) {
5198 error = got_worktree_open(&worktree, cwd);
5199 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5200 goto done;
5201 else
5202 error = NULL;
5203 if (worktree) {
5204 repo_path =
5205 strdup(got_worktree_get_repo_path(worktree));
5206 if (repo_path == NULL) {
5207 error = got_error_from_errno("strdup");
5208 goto done;
5210 } else {
5211 repo_path = strdup(cwd);
5212 if (repo_path == NULL) {
5213 error = got_error_from_errno("strdup");
5214 goto done;
5219 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5220 free(repo_path);
5221 if (error != NULL)
5222 goto done;
5224 if (show_diffstat) {
5225 dsa.paths = &diffstat_paths;
5226 dsa.force_text = force_text_diff;
5227 dsa.ignore_ws = ignore_whitespace;
5228 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5231 if (rflag || worktree == NULL || ncommit_args > 0) {
5232 if (force_path) {
5233 error = got_error_msg(GOT_ERR_NOT_IMPL,
5234 "-P option can only be used when diffing "
5235 "a work tree");
5236 goto done;
5238 if (diff_staged) {
5239 error = got_error_msg(GOT_ERR_NOT_IMPL,
5240 "-s option can only be used when diffing "
5241 "a work tree");
5242 goto done;
5246 error = apply_unveil(got_repo_get_path(repo), 1,
5247 worktree ? got_worktree_get_root_path(worktree) : NULL);
5248 if (error)
5249 goto done;
5251 if ((!force_path && argc == 2) || ncommit_args > 0) {
5252 int obj_type = (ncommit_args > 0 ?
5253 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5254 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5255 NULL);
5256 if (error)
5257 goto done;
5258 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5259 const char *arg;
5260 char *keyword_idstr = NULL;
5262 if (ncommit_args > 0)
5263 arg = commit_args[i];
5264 else
5265 arg = argv[i];
5267 error = got_keyword_to_idstr(&keyword_idstr, arg,
5268 repo, worktree);
5269 if (error != NULL)
5270 goto done;
5271 if (keyword_idstr != NULL)
5272 arg = keyword_idstr;
5274 error = got_repo_match_object_id(&ids[i], &labels[i],
5275 arg, obj_type, &refs, repo);
5276 free(keyword_idstr);
5277 if (error) {
5278 if (error->code != GOT_ERR_NOT_REF &&
5279 error->code != GOT_ERR_NO_OBJ)
5280 goto done;
5281 if (ncommit_args > 0)
5282 goto done;
5283 error = NULL;
5284 break;
5289 f1 = got_opentemp();
5290 if (f1 == NULL) {
5291 error = got_error_from_errno("got_opentemp");
5292 goto done;
5295 f2 = got_opentemp();
5296 if (f2 == NULL) {
5297 error = got_error_from_errno("got_opentemp");
5298 goto done;
5301 outfile = got_opentemp();
5302 if (outfile == NULL) {
5303 error = got_error_from_errno("got_opentemp");
5304 goto done;
5307 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5308 struct print_diff_arg arg;
5309 char *id_str;
5311 if (worktree == NULL) {
5312 if (argc == 2 && ids[0] == NULL) {
5313 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5314 goto done;
5315 } else if (argc == 2 && ids[1] == NULL) {
5316 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5317 goto done;
5318 } else if (argc > 0) {
5319 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5320 "%s", "specified paths cannot be resolved");
5321 goto done;
5322 } else {
5323 error = got_error(GOT_ERR_NOT_WORKTREE);
5324 goto done;
5328 error = get_worktree_paths_from_argv(&paths, argc, argv,
5329 worktree);
5330 if (error)
5331 goto done;
5333 error = got_object_id_str(&id_str,
5334 got_worktree_get_base_commit_id(worktree));
5335 if (error)
5336 goto done;
5337 arg.repo = repo;
5338 arg.worktree = worktree;
5339 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5340 arg.diff_context = diff_context;
5341 arg.id_str = id_str;
5342 arg.header_shown = 0;
5343 arg.diff_staged = diff_staged;
5344 arg.ignore_whitespace = ignore_whitespace;
5345 arg.force_text_diff = force_text_diff;
5346 arg.diffstat = show_diffstat ? &dsa : NULL;
5347 arg.f1 = f1;
5348 arg.f2 = f2;
5349 arg.outfile = outfile;
5351 error = got_worktree_status(worktree, &paths, repo, 0,
5352 print_diff, &arg, check_cancelled, NULL);
5353 free(id_str);
5354 if (error)
5355 goto done;
5357 if (show_diffstat && dsa.nfiles > 0) {
5358 char *header;
5360 if (asprintf(&header, "diffstat %s%s",
5361 diff_staged ? "-s " : "",
5362 got_worktree_get_root_path(worktree)) == -1) {
5363 error = got_error_from_errno("asprintf");
5364 goto done;
5367 error = print_diffstat(&dsa, header);
5368 free(header);
5369 if (error)
5370 goto done;
5373 error = printfile(outfile);
5374 goto done;
5377 if (ncommit_args == 1) {
5378 struct got_commit_object *commit;
5379 error = got_object_open_as_commit(&commit, repo, ids[0]);
5380 if (error)
5381 goto done;
5383 labels[1] = labels[0];
5384 ids[1] = ids[0];
5385 if (got_object_commit_get_nparents(commit) > 0) {
5386 const struct got_object_id_queue *pids;
5387 struct got_object_qid *pid;
5388 pids = got_object_commit_get_parent_ids(commit);
5389 pid = STAILQ_FIRST(pids);
5390 ids[0] = got_object_id_dup(&pid->id);
5391 if (ids[0] == NULL) {
5392 error = got_error_from_errno(
5393 "got_object_id_dup");
5394 got_object_commit_close(commit);
5395 goto done;
5397 error = got_object_id_str(&labels[0], ids[0]);
5398 if (error) {
5399 got_object_commit_close(commit);
5400 goto done;
5402 } else {
5403 ids[0] = NULL;
5404 labels[0] = strdup("/dev/null");
5405 if (labels[0] == NULL) {
5406 error = got_error_from_errno("strdup");
5407 got_object_commit_close(commit);
5408 goto done;
5412 got_object_commit_close(commit);
5415 if (ncommit_args == 0 && argc > 2) {
5416 error = got_error_msg(GOT_ERR_BAD_PATH,
5417 "path arguments cannot be used when diffing two objects");
5418 goto done;
5421 if (ids[0]) {
5422 error = got_object_get_type(&type1, repo, ids[0]);
5423 if (error)
5424 goto done;
5427 error = got_object_get_type(&type2, repo, ids[1]);
5428 if (error)
5429 goto done;
5430 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5431 error = got_error(GOT_ERR_OBJ_TYPE);
5432 goto done;
5434 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5435 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5436 "path arguments cannot be used when diffing blobs");
5437 goto done;
5440 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5441 char *in_repo_path;
5442 struct got_pathlist_entry *new;
5443 if (worktree) {
5444 const char *prefix;
5445 char *p;
5446 error = got_worktree_resolve_path(&p, worktree,
5447 argv[i]);
5448 if (error)
5449 goto done;
5450 prefix = got_worktree_get_path_prefix(worktree);
5451 while (prefix[0] == '/')
5452 prefix++;
5453 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5454 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5455 p) == -1) {
5456 error = got_error_from_errno("asprintf");
5457 free(p);
5458 goto done;
5460 free(p);
5461 } else {
5462 char *mapped_path, *s;
5463 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5464 if (error)
5465 goto done;
5466 s = mapped_path;
5467 while (s[0] == '/')
5468 s++;
5469 in_repo_path = strdup(s);
5470 if (in_repo_path == NULL) {
5471 error = got_error_from_errno("asprintf");
5472 free(mapped_path);
5473 goto done;
5475 free(mapped_path);
5478 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5479 if (error || new == NULL /* duplicate */)
5480 free(in_repo_path);
5481 if (error)
5482 goto done;
5485 if (worktree) {
5486 /* Release work tree lock. */
5487 got_worktree_close(worktree);
5488 worktree = NULL;
5491 fd1 = got_opentempfd();
5492 if (fd1 == -1) {
5493 error = got_error_from_errno("got_opentempfd");
5494 goto done;
5497 fd2 = got_opentempfd();
5498 if (fd2 == -1) {
5499 error = got_error_from_errno("got_opentempfd");
5500 goto done;
5503 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5504 case GOT_OBJ_TYPE_BLOB:
5505 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5506 fd1, fd2, ids[0], ids[1], NULL, NULL,
5507 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5508 ignore_whitespace, force_text_diff,
5509 show_diffstat ? &dsa : NULL, repo, outfile);
5510 break;
5511 case GOT_OBJ_TYPE_TREE:
5512 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5513 ids[0], ids[1], &paths, "", "",
5514 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5515 ignore_whitespace, force_text_diff,
5516 show_diffstat ? &dsa : NULL, repo, outfile);
5517 break;
5518 case GOT_OBJ_TYPE_COMMIT:
5519 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5520 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5521 fd1, fd2, ids[0], ids[1], &paths,
5522 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5523 ignore_whitespace, force_text_diff,
5524 show_diffstat ? &dsa : NULL, repo, outfile);
5525 break;
5526 default:
5527 error = got_error(GOT_ERR_OBJ_TYPE);
5529 if (error)
5530 goto done;
5532 if (show_diffstat && dsa.nfiles > 0) {
5533 char *header = NULL;
5535 if (asprintf(&header, "diffstat %s %s",
5536 labels[0], labels[1]) == -1) {
5537 error = got_error_from_errno("asprintf");
5538 goto done;
5541 error = print_diffstat(&dsa, header);
5542 free(header);
5543 if (error)
5544 goto done;
5547 error = printfile(outfile);
5549 done:
5550 free(labels[0]);
5551 free(labels[1]);
5552 free(ids[0]);
5553 free(ids[1]);
5554 if (worktree)
5555 got_worktree_close(worktree);
5556 if (repo) {
5557 const struct got_error *close_err = got_repo_close(repo);
5558 if (error == NULL)
5559 error = close_err;
5561 if (pack_fds) {
5562 const struct got_error *pack_err =
5563 got_repo_pack_fds_close(pack_fds);
5564 if (error == NULL)
5565 error = pack_err;
5567 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5568 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5569 got_ref_list_free(&refs);
5570 if (outfile && fclose(outfile) == EOF && error == NULL)
5571 error = got_error_from_errno("fclose");
5572 if (f1 && fclose(f1) == EOF && error == NULL)
5573 error = got_error_from_errno("fclose");
5574 if (f2 && fclose(f2) == EOF && error == NULL)
5575 error = got_error_from_errno("fclose");
5576 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5577 error = got_error_from_errno("close");
5578 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5579 error = got_error_from_errno("close");
5580 return error;
5583 __dead static void
5584 usage_blame(void)
5586 fprintf(stderr,
5587 "usage: %s blame [-c commit] [-r repository-path] path\n",
5588 getprogname());
5589 exit(1);
5592 struct blame_line {
5593 int annotated;
5594 char *id_str;
5595 char *committer;
5596 char datebuf[11]; /* YYYY-MM-DD + NUL */
5599 struct blame_cb_args {
5600 struct blame_line *lines;
5601 int nlines;
5602 int nlines_prec;
5603 int lineno_cur;
5604 off_t *line_offsets;
5605 FILE *f;
5606 struct got_repository *repo;
5609 static const struct got_error *
5610 blame_cb(void *arg, int nlines, int lineno,
5611 struct got_commit_object *commit, struct got_object_id *id)
5613 const struct got_error *err = NULL;
5614 struct blame_cb_args *a = arg;
5615 struct blame_line *bline;
5616 char *line = NULL;
5617 size_t linesize = 0;
5618 off_t offset;
5619 struct tm tm;
5620 time_t committer_time;
5622 if (nlines != a->nlines ||
5623 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5624 return got_error(GOT_ERR_RANGE);
5626 if (sigint_received)
5627 return got_error(GOT_ERR_ITER_COMPLETED);
5629 if (lineno == -1)
5630 return NULL; /* no change in this commit */
5632 /* Annotate this line. */
5633 bline = &a->lines[lineno - 1];
5634 if (bline->annotated)
5635 return NULL;
5636 err = got_object_id_str(&bline->id_str, id);
5637 if (err)
5638 return err;
5640 bline->committer = strdup(got_object_commit_get_committer(commit));
5641 if (bline->committer == NULL) {
5642 err = got_error_from_errno("strdup");
5643 goto done;
5646 committer_time = got_object_commit_get_committer_time(commit);
5647 if (gmtime_r(&committer_time, &tm) == NULL)
5648 return got_error_from_errno("gmtime_r");
5649 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5650 &tm) == 0) {
5651 err = got_error(GOT_ERR_NO_SPACE);
5652 goto done;
5654 bline->annotated = 1;
5656 /* Print lines annotated so far. */
5657 bline = &a->lines[a->lineno_cur - 1];
5658 if (!bline->annotated)
5659 goto done;
5661 offset = a->line_offsets[a->lineno_cur - 1];
5662 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5663 err = got_error_from_errno("fseeko");
5664 goto done;
5667 while (a->lineno_cur <= a->nlines && bline->annotated) {
5668 char *smallerthan, *at, *nl, *committer;
5669 size_t len;
5671 if (getline(&line, &linesize, a->f) == -1) {
5672 if (ferror(a->f))
5673 err = got_error_from_errno("getline");
5674 break;
5677 committer = bline->committer;
5678 smallerthan = strchr(committer, '<');
5679 if (smallerthan && smallerthan[1] != '\0')
5680 committer = smallerthan + 1;
5681 at = strchr(committer, '@');
5682 if (at)
5683 *at = '\0';
5684 len = strlen(committer);
5685 if (len >= 9)
5686 committer[8] = '\0';
5688 nl = strchr(line, '\n');
5689 if (nl)
5690 *nl = '\0';
5691 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5692 bline->id_str, bline->datebuf, committer, line);
5694 a->lineno_cur++;
5695 bline = &a->lines[a->lineno_cur - 1];
5697 done:
5698 free(line);
5699 return err;
5702 static const struct got_error *
5703 cmd_blame(int argc, char *argv[])
5705 const struct got_error *error;
5706 struct got_repository *repo = NULL;
5707 struct got_worktree *worktree = NULL;
5708 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5709 char *link_target = NULL;
5710 struct got_object_id *obj_id = NULL;
5711 struct got_object_id *commit_id = NULL;
5712 struct got_commit_object *commit = NULL;
5713 struct got_blob_object *blob = NULL;
5714 char *commit_id_str = NULL;
5715 struct blame_cb_args bca;
5716 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5717 off_t filesize;
5718 int *pack_fds = NULL;
5719 FILE *f1 = NULL, *f2 = NULL;
5721 fd1 = got_opentempfd();
5722 if (fd1 == -1)
5723 return got_error_from_errno("got_opentempfd");
5725 memset(&bca, 0, sizeof(bca));
5727 #ifndef PROFILE
5728 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5729 NULL) == -1)
5730 err(1, "pledge");
5731 #endif
5733 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5734 switch (ch) {
5735 case 'c':
5736 commit_id_str = optarg;
5737 break;
5738 case 'r':
5739 repo_path = realpath(optarg, NULL);
5740 if (repo_path == NULL)
5741 return got_error_from_errno2("realpath",
5742 optarg);
5743 got_path_strip_trailing_slashes(repo_path);
5744 break;
5745 default:
5746 usage_blame();
5747 /* NOTREACHED */
5751 argc -= optind;
5752 argv += optind;
5754 if (argc == 1)
5755 path = argv[0];
5756 else
5757 usage_blame();
5759 cwd = getcwd(NULL, 0);
5760 if (cwd == NULL) {
5761 error = got_error_from_errno("getcwd");
5762 goto done;
5765 error = got_repo_pack_fds_open(&pack_fds);
5766 if (error != NULL)
5767 goto done;
5769 if (repo_path == NULL) {
5770 error = got_worktree_open(&worktree, cwd);
5771 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5772 goto done;
5773 else
5774 error = NULL;
5775 if (worktree) {
5776 repo_path =
5777 strdup(got_worktree_get_repo_path(worktree));
5778 if (repo_path == NULL) {
5779 error = got_error_from_errno("strdup");
5780 if (error)
5781 goto done;
5783 } else {
5784 repo_path = strdup(cwd);
5785 if (repo_path == NULL) {
5786 error = got_error_from_errno("strdup");
5787 goto done;
5792 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5793 if (error != NULL)
5794 goto done;
5796 if (worktree) {
5797 const char *prefix = got_worktree_get_path_prefix(worktree);
5798 char *p;
5800 error = got_worktree_resolve_path(&p, worktree, path);
5801 if (error)
5802 goto done;
5803 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5804 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5805 p) == -1) {
5806 error = got_error_from_errno("asprintf");
5807 free(p);
5808 goto done;
5810 free(p);
5811 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5812 } else {
5813 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5814 if (error)
5815 goto done;
5816 error = got_repo_map_path(&in_repo_path, repo, path);
5818 if (error)
5819 goto done;
5821 if (commit_id_str == NULL) {
5822 struct got_reference *head_ref;
5823 error = got_ref_open(&head_ref, repo, worktree ?
5824 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5825 if (error != NULL)
5826 goto done;
5827 error = got_ref_resolve(&commit_id, repo, head_ref);
5828 got_ref_close(head_ref);
5829 if (error != NULL)
5830 goto done;
5831 } else {
5832 struct got_reflist_head refs;
5833 TAILQ_INIT(&refs);
5834 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5835 NULL);
5836 if (error)
5837 goto done;
5838 error = got_repo_match_object_id(&commit_id, NULL,
5839 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5840 got_ref_list_free(&refs);
5841 if (error)
5842 goto done;
5845 if (worktree) {
5846 /* Release work tree lock. */
5847 got_worktree_close(worktree);
5848 worktree = NULL;
5851 error = got_object_open_as_commit(&commit, repo, commit_id);
5852 if (error)
5853 goto done;
5855 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5856 commit, repo);
5857 if (error)
5858 goto done;
5860 error = got_object_id_by_path(&obj_id, repo, commit,
5861 link_target ? link_target : in_repo_path);
5862 if (error)
5863 goto done;
5865 error = got_object_get_type(&obj_type, repo, obj_id);
5866 if (error)
5867 goto done;
5869 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5870 error = got_error_path(link_target ? link_target : in_repo_path,
5871 GOT_ERR_OBJ_TYPE);
5872 goto done;
5875 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5876 if (error)
5877 goto done;
5878 bca.f = got_opentemp();
5879 if (bca.f == NULL) {
5880 error = got_error_from_errno("got_opentemp");
5881 goto done;
5883 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5884 &bca.line_offsets, bca.f, blob);
5885 if (error || bca.nlines == 0)
5886 goto done;
5888 /* Don't include \n at EOF in the blame line count. */
5889 if (bca.line_offsets[bca.nlines - 1] == filesize)
5890 bca.nlines--;
5892 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5893 if (bca.lines == NULL) {
5894 error = got_error_from_errno("calloc");
5895 goto done;
5897 bca.lineno_cur = 1;
5898 bca.nlines_prec = 0;
5899 i = bca.nlines;
5900 while (i > 0) {
5901 i /= 10;
5902 bca.nlines_prec++;
5904 bca.repo = repo;
5906 fd2 = got_opentempfd();
5907 if (fd2 == -1) {
5908 error = got_error_from_errno("got_opentempfd");
5909 goto done;
5911 fd3 = got_opentempfd();
5912 if (fd3 == -1) {
5913 error = got_error_from_errno("got_opentempfd");
5914 goto done;
5916 f1 = got_opentemp();
5917 if (f1 == NULL) {
5918 error = got_error_from_errno("got_opentemp");
5919 goto done;
5921 f2 = got_opentemp();
5922 if (f2 == NULL) {
5923 error = got_error_from_errno("got_opentemp");
5924 goto done;
5926 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5927 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5928 check_cancelled, NULL, fd2, fd3, f1, f2);
5929 done:
5930 free(in_repo_path);
5931 free(link_target);
5932 free(repo_path);
5933 free(cwd);
5934 free(commit_id);
5935 free(obj_id);
5936 if (commit)
5937 got_object_commit_close(commit);
5939 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5940 error = got_error_from_errno("close");
5941 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5942 error = got_error_from_errno("close");
5943 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5944 error = got_error_from_errno("close");
5945 if (f1 && fclose(f1) == EOF && error == NULL)
5946 error = got_error_from_errno("fclose");
5947 if (f2 && fclose(f2) == EOF && error == NULL)
5948 error = got_error_from_errno("fclose");
5950 if (blob)
5951 got_object_blob_close(blob);
5952 if (worktree)
5953 got_worktree_close(worktree);
5954 if (repo) {
5955 const struct got_error *close_err = got_repo_close(repo);
5956 if (error == NULL)
5957 error = close_err;
5959 if (pack_fds) {
5960 const struct got_error *pack_err =
5961 got_repo_pack_fds_close(pack_fds);
5962 if (error == NULL)
5963 error = pack_err;
5965 if (bca.lines) {
5966 for (i = 0; i < bca.nlines; i++) {
5967 struct blame_line *bline = &bca.lines[i];
5968 free(bline->id_str);
5969 free(bline->committer);
5971 free(bca.lines);
5973 free(bca.line_offsets);
5974 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5975 error = got_error_from_errno("fclose");
5976 return error;
5979 __dead static void
5980 usage_tree(void)
5982 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5983 "[path]\n", getprogname());
5984 exit(1);
5987 static const struct got_error *
5988 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5989 const char *root_path, struct got_repository *repo)
5991 const struct got_error *err = NULL;
5992 int is_root_path = (strcmp(path, root_path) == 0);
5993 const char *modestr = "";
5994 mode_t mode = got_tree_entry_get_mode(te);
5995 char *link_target = NULL;
5997 path += strlen(root_path);
5998 while (path[0] == '/')
5999 path++;
6001 if (got_object_tree_entry_is_submodule(te))
6002 modestr = "$";
6003 else if (S_ISLNK(mode)) {
6004 int i;
6006 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6007 if (err)
6008 return err;
6009 for (i = 0; link_target[i] != '\0'; i++) {
6010 if (!isprint((unsigned char)link_target[i]))
6011 link_target[i] = '?';
6014 modestr = "@";
6016 else if (S_ISDIR(mode))
6017 modestr = "/";
6018 else if (mode & S_IXUSR)
6019 modestr = "*";
6021 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6022 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6023 link_target ? " -> ": "", link_target ? link_target : "");
6025 free(link_target);
6026 return NULL;
6029 static const struct got_error *
6030 print_tree(const char *path, struct got_commit_object *commit,
6031 int show_ids, int recurse, const char *root_path,
6032 struct got_repository *repo)
6034 const struct got_error *err = NULL;
6035 struct got_object_id *tree_id = NULL;
6036 struct got_tree_object *tree = NULL;
6037 int nentries, i;
6039 err = got_object_id_by_path(&tree_id, repo, commit, path);
6040 if (err)
6041 goto done;
6043 err = got_object_open_as_tree(&tree, repo, tree_id);
6044 if (err)
6045 goto done;
6046 nentries = got_object_tree_get_nentries(tree);
6047 for (i = 0; i < nentries; i++) {
6048 struct got_tree_entry *te;
6049 char *id = NULL;
6051 if (sigint_received || sigpipe_received)
6052 break;
6054 te = got_object_tree_get_entry(tree, i);
6055 if (show_ids) {
6056 char *id_str;
6057 err = got_object_id_str(&id_str,
6058 got_tree_entry_get_id(te));
6059 if (err)
6060 goto done;
6061 if (asprintf(&id, "%s ", id_str) == -1) {
6062 err = got_error_from_errno("asprintf");
6063 free(id_str);
6064 goto done;
6066 free(id_str);
6068 err = print_entry(te, id, path, root_path, repo);
6069 free(id);
6070 if (err)
6071 goto done;
6073 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6074 char *child_path;
6075 if (asprintf(&child_path, "%s%s%s", path,
6076 path[0] == '/' && path[1] == '\0' ? "" : "/",
6077 got_tree_entry_get_name(te)) == -1) {
6078 err = got_error_from_errno("asprintf");
6079 goto done;
6081 err = print_tree(child_path, commit, show_ids, 1,
6082 root_path, repo);
6083 free(child_path);
6084 if (err)
6085 goto done;
6088 done:
6089 if (tree)
6090 got_object_tree_close(tree);
6091 free(tree_id);
6092 return err;
6095 static const struct got_error *
6096 cmd_tree(int argc, char *argv[])
6098 const struct got_error *error;
6099 struct got_repository *repo = NULL;
6100 struct got_worktree *worktree = NULL;
6101 const char *path, *refname = NULL;
6102 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6103 struct got_object_id *commit_id = NULL;
6104 struct got_commit_object *commit = NULL;
6105 char *commit_id_str = NULL;
6106 int show_ids = 0, recurse = 0;
6107 int ch;
6108 int *pack_fds = NULL;
6110 #ifndef PROFILE
6111 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6112 NULL) == -1)
6113 err(1, "pledge");
6114 #endif
6116 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6117 switch (ch) {
6118 case 'c':
6119 commit_id_str = optarg;
6120 break;
6121 case 'i':
6122 show_ids = 1;
6123 break;
6124 case 'R':
6125 recurse = 1;
6126 break;
6127 case 'r':
6128 repo_path = realpath(optarg, NULL);
6129 if (repo_path == NULL)
6130 return got_error_from_errno2("realpath",
6131 optarg);
6132 got_path_strip_trailing_slashes(repo_path);
6133 break;
6134 default:
6135 usage_tree();
6136 /* NOTREACHED */
6140 argc -= optind;
6141 argv += optind;
6143 if (argc == 1)
6144 path = argv[0];
6145 else if (argc > 1)
6146 usage_tree();
6147 else
6148 path = NULL;
6150 cwd = getcwd(NULL, 0);
6151 if (cwd == NULL) {
6152 error = got_error_from_errno("getcwd");
6153 goto done;
6156 error = got_repo_pack_fds_open(&pack_fds);
6157 if (error != NULL)
6158 goto done;
6160 if (repo_path == NULL) {
6161 error = got_worktree_open(&worktree, cwd);
6162 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6163 goto done;
6164 else
6165 error = NULL;
6166 if (worktree) {
6167 repo_path =
6168 strdup(got_worktree_get_repo_path(worktree));
6169 if (repo_path == NULL)
6170 error = got_error_from_errno("strdup");
6171 if (error)
6172 goto done;
6173 } else {
6174 repo_path = strdup(cwd);
6175 if (repo_path == NULL) {
6176 error = got_error_from_errno("strdup");
6177 goto done;
6182 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6183 if (error != NULL)
6184 goto done;
6186 if (worktree) {
6187 const char *prefix = got_worktree_get_path_prefix(worktree);
6188 char *p;
6190 if (path == NULL || got_path_is_root_dir(path))
6191 path = "";
6192 error = got_worktree_resolve_path(&p, worktree, path);
6193 if (error)
6194 goto done;
6195 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6196 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6197 p) == -1) {
6198 error = got_error_from_errno("asprintf");
6199 free(p);
6200 goto done;
6202 free(p);
6203 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6204 if (error)
6205 goto done;
6206 } else {
6207 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6208 if (error)
6209 goto done;
6210 if (path == NULL)
6211 path = "/";
6212 error = got_repo_map_path(&in_repo_path, repo, path);
6213 if (error != NULL)
6214 goto done;
6217 if (commit_id_str == NULL) {
6218 struct got_reference *head_ref;
6219 if (worktree)
6220 refname = got_worktree_get_head_ref_name(worktree);
6221 else
6222 refname = GOT_REF_HEAD;
6223 error = got_ref_open(&head_ref, repo, refname, 0);
6224 if (error != NULL)
6225 goto done;
6226 error = got_ref_resolve(&commit_id, repo, head_ref);
6227 got_ref_close(head_ref);
6228 if (error != NULL)
6229 goto done;
6230 } else {
6231 struct got_reflist_head refs;
6232 TAILQ_INIT(&refs);
6233 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6234 NULL);
6235 if (error)
6236 goto done;
6237 error = got_repo_match_object_id(&commit_id, NULL,
6238 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6239 got_ref_list_free(&refs);
6240 if (error)
6241 goto done;
6244 if (worktree) {
6245 /* Release work tree lock. */
6246 got_worktree_close(worktree);
6247 worktree = NULL;
6250 error = got_object_open_as_commit(&commit, repo, commit_id);
6251 if (error)
6252 goto done;
6254 error = print_tree(in_repo_path, commit, show_ids, recurse,
6255 in_repo_path, repo);
6256 done:
6257 free(in_repo_path);
6258 free(repo_path);
6259 free(cwd);
6260 free(commit_id);
6261 if (commit)
6262 got_object_commit_close(commit);
6263 if (worktree)
6264 got_worktree_close(worktree);
6265 if (repo) {
6266 const struct got_error *close_err = got_repo_close(repo);
6267 if (error == NULL)
6268 error = close_err;
6270 if (pack_fds) {
6271 const struct got_error *pack_err =
6272 got_repo_pack_fds_close(pack_fds);
6273 if (error == NULL)
6274 error = pack_err;
6276 return error;
6279 __dead static void
6280 usage_status(void)
6282 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6283 "[-s status-codes] [path ...]\n", getprogname());
6284 exit(1);
6287 struct got_status_arg {
6288 char *status_codes;
6289 int suppress;
6292 static const struct got_error *
6293 print_status(void *arg, unsigned char status, unsigned char staged_status,
6294 const char *path, struct got_object_id *blob_id,
6295 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6296 int dirfd, const char *de_name)
6298 struct got_status_arg *st = arg;
6300 if (status == staged_status && (status == GOT_STATUS_DELETE))
6301 status = GOT_STATUS_NO_CHANGE;
6302 if (st != NULL && st->status_codes) {
6303 size_t ncodes = strlen(st->status_codes);
6304 int i, j = 0;
6306 for (i = 0; i < ncodes ; i++) {
6307 if (st->suppress) {
6308 if (status == st->status_codes[i] ||
6309 staged_status == st->status_codes[i]) {
6310 j++;
6311 continue;
6313 } else {
6314 if (status == st->status_codes[i] ||
6315 staged_status == st->status_codes[i])
6316 break;
6320 if (st->suppress && j == 0)
6321 goto print;
6323 if (i == ncodes)
6324 return NULL;
6326 print:
6327 printf("%c%c %s\n", status, staged_status, path);
6328 return NULL;
6331 static const struct got_error *
6332 cmd_status(int argc, char *argv[])
6334 const struct got_error *error = NULL;
6335 struct got_repository *repo = NULL;
6336 struct got_worktree *worktree = NULL;
6337 struct got_status_arg st;
6338 char *cwd = NULL;
6339 struct got_pathlist_head paths;
6340 int ch, i, no_ignores = 0;
6341 int *pack_fds = NULL;
6343 TAILQ_INIT(&paths);
6345 memset(&st, 0, sizeof(st));
6346 st.status_codes = NULL;
6347 st.suppress = 0;
6349 #ifndef PROFILE
6350 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6351 NULL) == -1)
6352 err(1, "pledge");
6353 #endif
6355 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6356 switch (ch) {
6357 case 'I':
6358 no_ignores = 1;
6359 break;
6360 case 'S':
6361 if (st.status_codes != NULL && st.suppress == 0)
6362 option_conflict('S', 's');
6363 st.suppress = 1;
6364 /* fallthrough */
6365 case 's':
6366 for (i = 0; optarg[i] != '\0'; i++) {
6367 switch (optarg[i]) {
6368 case GOT_STATUS_MODIFY:
6369 case GOT_STATUS_ADD:
6370 case GOT_STATUS_DELETE:
6371 case GOT_STATUS_CONFLICT:
6372 case GOT_STATUS_MISSING:
6373 case GOT_STATUS_OBSTRUCTED:
6374 case GOT_STATUS_UNVERSIONED:
6375 case GOT_STATUS_MODE_CHANGE:
6376 case GOT_STATUS_NONEXISTENT:
6377 break;
6378 default:
6379 errx(1, "invalid status code '%c'",
6380 optarg[i]);
6383 if (ch == 's' && st.suppress)
6384 option_conflict('s', 'S');
6385 st.status_codes = optarg;
6386 break;
6387 default:
6388 usage_status();
6389 /* NOTREACHED */
6393 argc -= optind;
6394 argv += optind;
6396 cwd = getcwd(NULL, 0);
6397 if (cwd == NULL) {
6398 error = got_error_from_errno("getcwd");
6399 goto done;
6402 error = got_repo_pack_fds_open(&pack_fds);
6403 if (error != NULL)
6404 goto done;
6406 error = got_worktree_open(&worktree, cwd);
6407 if (error) {
6408 if (error->code == GOT_ERR_NOT_WORKTREE)
6409 error = wrap_not_worktree_error(error, "status", cwd);
6410 goto done;
6413 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6414 NULL, pack_fds);
6415 if (error != NULL)
6416 goto done;
6418 error = apply_unveil(got_repo_get_path(repo), 1,
6419 got_worktree_get_root_path(worktree));
6420 if (error)
6421 goto done;
6423 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6424 if (error)
6425 goto done;
6427 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6428 print_status, &st, check_cancelled, NULL);
6429 done:
6430 if (pack_fds) {
6431 const struct got_error *pack_err =
6432 got_repo_pack_fds_close(pack_fds);
6433 if (error == NULL)
6434 error = pack_err;
6436 if (repo) {
6437 const struct got_error *close_err = got_repo_close(repo);
6438 if (error == NULL)
6439 error = close_err;
6442 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6443 free(cwd);
6444 return error;
6447 __dead static void
6448 usage_ref(void)
6450 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6451 "[-s reference] [name]\n", getprogname());
6452 exit(1);
6455 static const struct got_error *
6456 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6458 static const struct got_error *err = NULL;
6459 struct got_reflist_head refs;
6460 struct got_reflist_entry *re;
6462 TAILQ_INIT(&refs);
6463 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6464 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6465 repo);
6466 if (err)
6467 return err;
6469 TAILQ_FOREACH(re, &refs, entry) {
6470 char *refstr;
6471 refstr = got_ref_to_str(re->ref);
6472 if (refstr == NULL) {
6473 err = got_error_from_errno("got_ref_to_str");
6474 break;
6476 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6477 free(refstr);
6480 got_ref_list_free(&refs);
6481 return err;
6484 static const struct got_error *
6485 delete_ref_by_name(struct got_repository *repo, const char *refname)
6487 const struct got_error *err;
6488 struct got_reference *ref;
6490 err = got_ref_open(&ref, repo, refname, 0);
6491 if (err)
6492 return err;
6494 err = delete_ref(repo, ref);
6495 got_ref_close(ref);
6496 return err;
6499 static const struct got_error *
6500 add_ref(struct got_repository *repo, const char *refname, const char *target)
6502 const struct got_error *err = NULL;
6503 struct got_object_id *id = NULL;
6504 struct got_reference *ref = NULL;
6505 struct got_reflist_head refs;
6508 * Don't let the user create a reference name with a leading '-'.
6509 * While technically a valid reference name, this case is usually
6510 * an unintended typo.
6512 if (refname[0] == '-')
6513 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6515 TAILQ_INIT(&refs);
6516 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6517 if (err)
6518 goto done;
6519 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6520 &refs, repo);
6521 got_ref_list_free(&refs);
6522 if (err)
6523 goto done;
6525 err = got_ref_alloc(&ref, refname, id);
6526 if (err)
6527 goto done;
6529 err = got_ref_write(ref, repo);
6530 done:
6531 if (ref)
6532 got_ref_close(ref);
6533 free(id);
6534 return err;
6537 static const struct got_error *
6538 add_symref(struct got_repository *repo, const char *refname, const char *target)
6540 const struct got_error *err = NULL;
6541 struct got_reference *ref = NULL;
6542 struct got_reference *target_ref = NULL;
6545 * Don't let the user create a reference name with a leading '-'.
6546 * While technically a valid reference name, this case is usually
6547 * an unintended typo.
6549 if (refname[0] == '-')
6550 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6552 err = got_ref_open(&target_ref, repo, target, 0);
6553 if (err)
6554 return err;
6556 err = got_ref_alloc_symref(&ref, refname, target_ref);
6557 if (err)
6558 goto done;
6560 err = got_ref_write(ref, repo);
6561 done:
6562 if (target_ref)
6563 got_ref_close(target_ref);
6564 if (ref)
6565 got_ref_close(ref);
6566 return err;
6569 static const struct got_error *
6570 cmd_ref(int argc, char *argv[])
6572 const struct got_error *error = NULL;
6573 struct got_repository *repo = NULL;
6574 struct got_worktree *worktree = NULL;
6575 char *cwd = NULL, *repo_path = NULL;
6576 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6577 const char *obj_arg = NULL, *symref_target= NULL;
6578 char *refname = NULL;
6579 int *pack_fds = NULL;
6581 #ifndef PROFILE
6582 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6583 "sendfd unveil", NULL) == -1)
6584 err(1, "pledge");
6585 #endif
6587 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6588 switch (ch) {
6589 case 'c':
6590 obj_arg = optarg;
6591 break;
6592 case 'd':
6593 do_delete = 1;
6594 break;
6595 case 'l':
6596 do_list = 1;
6597 break;
6598 case 'r':
6599 repo_path = realpath(optarg, NULL);
6600 if (repo_path == NULL)
6601 return got_error_from_errno2("realpath",
6602 optarg);
6603 got_path_strip_trailing_slashes(repo_path);
6604 break;
6605 case 's':
6606 symref_target = optarg;
6607 break;
6608 case 't':
6609 sort_by_time = 1;
6610 break;
6611 default:
6612 usage_ref();
6613 /* NOTREACHED */
6617 if (obj_arg && do_list)
6618 option_conflict('c', 'l');
6619 if (obj_arg && do_delete)
6620 option_conflict('c', 'd');
6621 if (obj_arg && symref_target)
6622 option_conflict('c', 's');
6623 if (symref_target && do_delete)
6624 option_conflict('s', 'd');
6625 if (symref_target && do_list)
6626 option_conflict('s', 'l');
6627 if (do_delete && do_list)
6628 option_conflict('d', 'l');
6629 if (sort_by_time && !do_list)
6630 errx(1, "-t option requires -l option");
6632 argc -= optind;
6633 argv += optind;
6635 if (do_list) {
6636 if (argc != 0 && argc != 1)
6637 usage_ref();
6638 if (argc == 1) {
6639 refname = strdup(argv[0]);
6640 if (refname == NULL) {
6641 error = got_error_from_errno("strdup");
6642 goto done;
6645 } else {
6646 if (argc != 1)
6647 usage_ref();
6648 refname = strdup(argv[0]);
6649 if (refname == NULL) {
6650 error = got_error_from_errno("strdup");
6651 goto done;
6655 if (refname)
6656 got_path_strip_trailing_slashes(refname);
6658 cwd = getcwd(NULL, 0);
6659 if (cwd == NULL) {
6660 error = got_error_from_errno("getcwd");
6661 goto done;
6664 error = got_repo_pack_fds_open(&pack_fds);
6665 if (error != NULL)
6666 goto done;
6668 if (repo_path == NULL) {
6669 error = got_worktree_open(&worktree, cwd);
6670 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6671 goto done;
6672 else
6673 error = NULL;
6674 if (worktree) {
6675 repo_path =
6676 strdup(got_worktree_get_repo_path(worktree));
6677 if (repo_path == NULL)
6678 error = got_error_from_errno("strdup");
6679 if (error)
6680 goto done;
6681 } else {
6682 repo_path = strdup(cwd);
6683 if (repo_path == NULL) {
6684 error = got_error_from_errno("strdup");
6685 goto done;
6690 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6691 if (error != NULL)
6692 goto done;
6694 #ifndef PROFILE
6695 if (do_list) {
6696 /* Remove "cpath" promise. */
6697 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6698 NULL) == -1)
6699 err(1, "pledge");
6701 #endif
6703 error = apply_unveil(got_repo_get_path(repo), do_list,
6704 worktree ? got_worktree_get_root_path(worktree) : NULL);
6705 if (error)
6706 goto done;
6708 if (do_list)
6709 error = list_refs(repo, refname, sort_by_time);
6710 else if (do_delete)
6711 error = delete_ref_by_name(repo, refname);
6712 else if (symref_target)
6713 error = add_symref(repo, refname, symref_target);
6714 else {
6715 if (obj_arg == NULL)
6716 usage_ref();
6717 error = add_ref(repo, refname, obj_arg);
6719 done:
6720 free(refname);
6721 if (repo) {
6722 const struct got_error *close_err = got_repo_close(repo);
6723 if (error == NULL)
6724 error = close_err;
6726 if (worktree)
6727 got_worktree_close(worktree);
6728 if (pack_fds) {
6729 const struct got_error *pack_err =
6730 got_repo_pack_fds_close(pack_fds);
6731 if (error == NULL)
6732 error = pack_err;
6734 free(cwd);
6735 free(repo_path);
6736 return error;
6739 __dead static void
6740 usage_branch(void)
6742 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6743 "[-r repository-path] [name]\n", getprogname());
6744 exit(1);
6747 static const struct got_error *
6748 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6749 struct got_reference *ref)
6751 const struct got_error *err = NULL;
6752 const char *refname, *marker = " ";
6753 char *refstr;
6755 refname = got_ref_get_name(ref);
6756 if (worktree && strcmp(refname,
6757 got_worktree_get_head_ref_name(worktree)) == 0) {
6758 struct got_object_id *id = NULL;
6760 err = got_ref_resolve(&id, repo, ref);
6761 if (err)
6762 return err;
6763 if (got_object_id_cmp(id,
6764 got_worktree_get_base_commit_id(worktree)) == 0)
6765 marker = "* ";
6766 else
6767 marker = "~ ";
6768 free(id);
6771 if (strncmp(refname, "refs/heads/", 11) == 0)
6772 refname += 11;
6773 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6774 refname += 18;
6775 if (strncmp(refname, "refs/remotes/", 13) == 0)
6776 refname += 13;
6778 refstr = got_ref_to_str(ref);
6779 if (refstr == NULL)
6780 return got_error_from_errno("got_ref_to_str");
6782 printf("%s%s: %s\n", marker, refname, refstr);
6783 free(refstr);
6784 return NULL;
6787 static const struct got_error *
6788 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6790 const char *refname;
6792 if (worktree == NULL)
6793 return got_error(GOT_ERR_NOT_WORKTREE);
6795 refname = got_worktree_get_head_ref_name(worktree);
6797 if (strncmp(refname, "refs/heads/", 11) == 0)
6798 refname += 11;
6799 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6800 refname += 18;
6802 printf("%s\n", refname);
6804 return NULL;
6807 static const struct got_error *
6808 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6809 int sort_by_time)
6811 static const struct got_error *err = NULL;
6812 struct got_reflist_head refs;
6813 struct got_reflist_entry *re;
6814 struct got_reference *temp_ref = NULL;
6815 int rebase_in_progress, histedit_in_progress;
6817 TAILQ_INIT(&refs);
6819 if (worktree) {
6820 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6821 worktree);
6822 if (err)
6823 return err;
6825 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6826 worktree);
6827 if (err)
6828 return err;
6830 if (rebase_in_progress || histedit_in_progress) {
6831 err = got_ref_open(&temp_ref, repo,
6832 got_worktree_get_head_ref_name(worktree), 0);
6833 if (err)
6834 return err;
6835 list_branch(repo, worktree, temp_ref);
6836 got_ref_close(temp_ref);
6840 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6841 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6842 repo);
6843 if (err)
6844 return err;
6846 TAILQ_FOREACH(re, &refs, entry)
6847 list_branch(repo, worktree, re->ref);
6849 got_ref_list_free(&refs);
6851 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6852 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6853 repo);
6854 if (err)
6855 return err;
6857 TAILQ_FOREACH(re, &refs, entry)
6858 list_branch(repo, worktree, re->ref);
6860 got_ref_list_free(&refs);
6862 return NULL;
6865 static const struct got_error *
6866 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6867 const char *branch_name)
6869 const struct got_error *err = NULL;
6870 struct got_reference *ref = NULL;
6871 char *refname, *remote_refname = NULL;
6873 if (strncmp(branch_name, "refs/", 5) == 0)
6874 branch_name += 5;
6875 if (strncmp(branch_name, "heads/", 6) == 0)
6876 branch_name += 6;
6877 else if (strncmp(branch_name, "remotes/", 8) == 0)
6878 branch_name += 8;
6880 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6881 return got_error_from_errno("asprintf");
6883 if (asprintf(&remote_refname, "refs/remotes/%s",
6884 branch_name) == -1) {
6885 err = got_error_from_errno("asprintf");
6886 goto done;
6889 err = got_ref_open(&ref, repo, refname, 0);
6890 if (err) {
6891 const struct got_error *err2;
6892 if (err->code != GOT_ERR_NOT_REF)
6893 goto done;
6895 * Keep 'err' intact such that if neither branch exists
6896 * we report "refs/heads" rather than "refs/remotes" in
6897 * our error message.
6899 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6900 if (err2)
6901 goto done;
6902 err = NULL;
6905 if (worktree &&
6906 strcmp(got_worktree_get_head_ref_name(worktree),
6907 got_ref_get_name(ref)) == 0) {
6908 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6909 "will not delete this work tree's current branch");
6910 goto done;
6913 err = delete_ref(repo, ref);
6914 done:
6915 if (ref)
6916 got_ref_close(ref);
6917 free(refname);
6918 free(remote_refname);
6919 return err;
6922 static const struct got_error *
6923 add_branch(struct got_repository *repo, const char *branch_name,
6924 struct got_object_id *base_commit_id)
6926 const struct got_error *err = NULL;
6927 struct got_reference *ref = NULL;
6928 char *refname = NULL;
6931 * Don't let the user create a branch name with a leading '-'.
6932 * While technically a valid reference name, this case is usually
6933 * an unintended typo.
6935 if (branch_name[0] == '-')
6936 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6938 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6939 branch_name += 11;
6941 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6942 err = got_error_from_errno("asprintf");
6943 goto done;
6946 err = got_ref_open(&ref, repo, refname, 0);
6947 if (err == NULL) {
6948 err = got_error(GOT_ERR_BRANCH_EXISTS);
6949 goto done;
6950 } else if (err->code != GOT_ERR_NOT_REF)
6951 goto done;
6953 err = got_ref_alloc(&ref, refname, base_commit_id);
6954 if (err)
6955 goto done;
6957 err = got_ref_write(ref, repo);
6958 done:
6959 if (ref)
6960 got_ref_close(ref);
6961 free(refname);
6962 return err;
6965 static const struct got_error *
6966 cmd_branch(int argc, char *argv[])
6968 const struct got_error *error = NULL;
6969 struct got_repository *repo = NULL;
6970 struct got_worktree *worktree = NULL;
6971 char *cwd = NULL, *repo_path = NULL;
6972 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6973 const char *delref = NULL, *commit_id_arg = NULL;
6974 struct got_reference *ref = NULL;
6975 struct got_pathlist_head paths;
6976 struct got_object_id *commit_id = NULL;
6977 char *commit_id_str = NULL;
6978 int *pack_fds = NULL;
6980 TAILQ_INIT(&paths);
6982 #ifndef PROFILE
6983 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6984 "sendfd unveil", NULL) == -1)
6985 err(1, "pledge");
6986 #endif
6988 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6989 switch (ch) {
6990 case 'c':
6991 commit_id_arg = optarg;
6992 break;
6993 case 'd':
6994 delref = optarg;
6995 break;
6996 case 'l':
6997 do_list = 1;
6998 break;
6999 case 'n':
7000 do_update = 0;
7001 break;
7002 case 'r':
7003 repo_path = realpath(optarg, NULL);
7004 if (repo_path == NULL)
7005 return got_error_from_errno2("realpath",
7006 optarg);
7007 got_path_strip_trailing_slashes(repo_path);
7008 break;
7009 case 't':
7010 sort_by_time = 1;
7011 break;
7012 default:
7013 usage_branch();
7014 /* NOTREACHED */
7018 if (do_list && delref)
7019 option_conflict('l', 'd');
7020 if (sort_by_time && !do_list)
7021 errx(1, "-t option requires -l option");
7023 argc -= optind;
7024 argv += optind;
7026 if (!do_list && !delref && argc == 0)
7027 do_show = 1;
7029 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7030 errx(1, "-c option can only be used when creating a branch");
7032 if (do_list || delref) {
7033 if (argc > 0)
7034 usage_branch();
7035 } else if (!do_show && argc != 1)
7036 usage_branch();
7038 cwd = getcwd(NULL, 0);
7039 if (cwd == NULL) {
7040 error = got_error_from_errno("getcwd");
7041 goto done;
7044 error = got_repo_pack_fds_open(&pack_fds);
7045 if (error != NULL)
7046 goto done;
7048 if (repo_path == NULL) {
7049 error = got_worktree_open(&worktree, cwd);
7050 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7051 goto done;
7052 else
7053 error = NULL;
7054 if (worktree) {
7055 repo_path =
7056 strdup(got_worktree_get_repo_path(worktree));
7057 if (repo_path == NULL)
7058 error = got_error_from_errno("strdup");
7059 if (error)
7060 goto done;
7061 } else {
7062 repo_path = strdup(cwd);
7063 if (repo_path == NULL) {
7064 error = got_error_from_errno("strdup");
7065 goto done;
7070 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7071 if (error != NULL)
7072 goto done;
7074 #ifndef PROFILE
7075 if (do_list || do_show) {
7076 /* Remove "cpath" promise. */
7077 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7078 NULL) == -1)
7079 err(1, "pledge");
7081 #endif
7083 error = apply_unveil(got_repo_get_path(repo), do_list,
7084 worktree ? got_worktree_get_root_path(worktree) : NULL);
7085 if (error)
7086 goto done;
7088 if (do_show)
7089 error = show_current_branch(repo, worktree);
7090 else if (do_list)
7091 error = list_branches(repo, worktree, sort_by_time);
7092 else if (delref)
7093 error = delete_branch(repo, worktree, delref);
7094 else {
7095 struct got_reflist_head refs;
7096 TAILQ_INIT(&refs);
7097 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7098 NULL);
7099 if (error)
7100 goto done;
7101 if (commit_id_arg == NULL)
7102 commit_id_arg = worktree ?
7103 got_worktree_get_head_ref_name(worktree) :
7104 GOT_REF_HEAD;
7105 error = got_repo_match_object_id(&commit_id, NULL,
7106 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7107 got_ref_list_free(&refs);
7108 if (error)
7109 goto done;
7110 error = add_branch(repo, argv[0], commit_id);
7111 if (error)
7112 goto done;
7113 if (worktree && do_update) {
7114 struct got_update_progress_arg upa;
7115 char *branch_refname = NULL;
7117 error = got_object_id_str(&commit_id_str, commit_id);
7118 if (error)
7119 goto done;
7120 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7121 worktree);
7122 if (error)
7123 goto done;
7124 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7125 == -1) {
7126 error = got_error_from_errno("asprintf");
7127 goto done;
7129 error = got_ref_open(&ref, repo, branch_refname, 0);
7130 free(branch_refname);
7131 if (error)
7132 goto done;
7133 error = switch_head_ref(ref, commit_id, worktree,
7134 repo);
7135 if (error)
7136 goto done;
7137 error = got_worktree_set_base_commit_id(worktree, repo,
7138 commit_id);
7139 if (error)
7140 goto done;
7141 memset(&upa, 0, sizeof(upa));
7142 error = got_worktree_checkout_files(worktree, &paths,
7143 repo, update_progress, &upa, check_cancelled,
7144 NULL);
7145 if (error)
7146 goto done;
7147 if (upa.did_something) {
7148 printf("Updated to %s: %s\n",
7149 got_worktree_get_head_ref_name(worktree),
7150 commit_id_str);
7152 print_update_progress_stats(&upa);
7155 done:
7156 if (ref)
7157 got_ref_close(ref);
7158 if (repo) {
7159 const struct got_error *close_err = got_repo_close(repo);
7160 if (error == NULL)
7161 error = close_err;
7163 if (worktree)
7164 got_worktree_close(worktree);
7165 if (pack_fds) {
7166 const struct got_error *pack_err =
7167 got_repo_pack_fds_close(pack_fds);
7168 if (error == NULL)
7169 error = pack_err;
7171 free(cwd);
7172 free(repo_path);
7173 free(commit_id);
7174 free(commit_id_str);
7175 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7176 return error;
7180 __dead static void
7181 usage_tag(void)
7183 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7184 "[-r repository-path] [-s signer-id] name\n", getprogname());
7185 exit(1);
7188 #if 0
7189 static const struct got_error *
7190 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7192 const struct got_error *err = NULL;
7193 struct got_reflist_entry *re, *se, *new;
7194 struct got_object_id *re_id, *se_id;
7195 struct got_tag_object *re_tag, *se_tag;
7196 time_t re_time, se_time;
7198 STAILQ_FOREACH(re, tags, entry) {
7199 se = STAILQ_FIRST(sorted);
7200 if (se == NULL) {
7201 err = got_reflist_entry_dup(&new, re);
7202 if (err)
7203 return err;
7204 STAILQ_INSERT_HEAD(sorted, new, entry);
7205 continue;
7206 } else {
7207 err = got_ref_resolve(&re_id, repo, re->ref);
7208 if (err)
7209 break;
7210 err = got_object_open_as_tag(&re_tag, repo, re_id);
7211 free(re_id);
7212 if (err)
7213 break;
7214 re_time = got_object_tag_get_tagger_time(re_tag);
7215 got_object_tag_close(re_tag);
7218 while (se) {
7219 err = got_ref_resolve(&se_id, repo, re->ref);
7220 if (err)
7221 break;
7222 err = got_object_open_as_tag(&se_tag, repo, se_id);
7223 free(se_id);
7224 if (err)
7225 break;
7226 se_time = got_object_tag_get_tagger_time(se_tag);
7227 got_object_tag_close(se_tag);
7229 if (se_time > re_time) {
7230 err = got_reflist_entry_dup(&new, re);
7231 if (err)
7232 return err;
7233 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7234 break;
7236 se = STAILQ_NEXT(se, entry);
7237 continue;
7240 done:
7241 return err;
7243 #endif
7245 static const struct got_error *
7246 get_tag_refname(char **refname, const char *tag_name)
7248 const struct got_error *err;
7250 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7251 *refname = strdup(tag_name);
7252 if (*refname == NULL)
7253 return got_error_from_errno("strdup");
7254 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7255 err = got_error_from_errno("asprintf");
7256 *refname = NULL;
7257 return err;
7260 return NULL;
7263 static const struct got_error *
7264 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7265 const char *allowed_signers, const char *revoked_signers, int verbosity)
7267 static const struct got_error *err = NULL;
7268 struct got_reflist_head refs;
7269 struct got_reflist_entry *re;
7270 char *wanted_refname = NULL;
7271 int bad_sigs = 0;
7273 TAILQ_INIT(&refs);
7275 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7276 if (err)
7277 return err;
7279 if (tag_name) {
7280 struct got_reference *ref;
7281 err = get_tag_refname(&wanted_refname, tag_name);
7282 if (err)
7283 goto done;
7284 /* Wanted tag reference should exist. */
7285 err = got_ref_open(&ref, repo, wanted_refname, 0);
7286 if (err)
7287 goto done;
7288 got_ref_close(ref);
7291 TAILQ_FOREACH(re, &refs, entry) {
7292 const char *refname;
7293 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7294 char datebuf[26];
7295 const char *tagger, *ssh_sig = NULL;
7296 char *sig_msg = NULL;
7297 time_t tagger_time;
7298 struct got_object_id *id;
7299 struct got_tag_object *tag;
7300 struct got_commit_object *commit = NULL;
7302 refname = got_ref_get_name(re->ref);
7303 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7304 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7305 continue;
7306 refname += 10;
7307 refstr = got_ref_to_str(re->ref);
7308 if (refstr == NULL) {
7309 err = got_error_from_errno("got_ref_to_str");
7310 break;
7313 err = got_ref_resolve(&id, repo, re->ref);
7314 if (err)
7315 break;
7316 err = got_object_open_as_tag(&tag, repo, id);
7317 if (err) {
7318 if (err->code != GOT_ERR_OBJ_TYPE) {
7319 free(id);
7320 break;
7322 /* "lightweight" tag */
7323 err = got_object_open_as_commit(&commit, repo, id);
7324 if (err) {
7325 free(id);
7326 break;
7328 tagger = got_object_commit_get_committer(commit);
7329 tagger_time =
7330 got_object_commit_get_committer_time(commit);
7331 err = got_object_id_str(&id_str, id);
7332 free(id);
7333 if (err)
7334 break;
7335 } else {
7336 free(id);
7337 tagger = got_object_tag_get_tagger(tag);
7338 tagger_time = got_object_tag_get_tagger_time(tag);
7339 err = got_object_id_str(&id_str,
7340 got_object_tag_get_object_id(tag));
7341 if (err)
7342 break;
7345 if (tag && verify_tags) {
7346 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7347 got_object_tag_get_message(tag));
7348 if (ssh_sig && allowed_signers == NULL) {
7349 err = got_error_msg(
7350 GOT_ERR_VERIFY_TAG_SIGNATURE,
7351 "SSH signature verification requires "
7352 "setting allowed_signers in "
7353 "got.conf(5)");
7354 break;
7358 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7359 free(refstr);
7360 printf("from: %s\n", tagger);
7361 datestr = get_datestr(&tagger_time, datebuf);
7362 if (datestr)
7363 printf("date: %s UTC\n", datestr);
7364 if (commit)
7365 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7366 else {
7367 switch (got_object_tag_get_object_type(tag)) {
7368 case GOT_OBJ_TYPE_BLOB:
7369 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7370 id_str);
7371 break;
7372 case GOT_OBJ_TYPE_TREE:
7373 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7374 id_str);
7375 break;
7376 case GOT_OBJ_TYPE_COMMIT:
7377 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7378 id_str);
7379 break;
7380 case GOT_OBJ_TYPE_TAG:
7381 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7382 id_str);
7383 break;
7384 default:
7385 break;
7388 free(id_str);
7390 if (ssh_sig) {
7391 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7392 allowed_signers, revoked_signers, verbosity);
7393 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7394 bad_sigs = 1;
7395 else if (err)
7396 break;
7397 printf("signature: %s", sig_msg);
7398 free(sig_msg);
7399 sig_msg = NULL;
7402 if (commit) {
7403 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7404 if (err)
7405 break;
7406 got_object_commit_close(commit);
7407 } else {
7408 tagmsg0 = strdup(got_object_tag_get_message(tag));
7409 got_object_tag_close(tag);
7410 if (tagmsg0 == NULL) {
7411 err = got_error_from_errno("strdup");
7412 break;
7416 tagmsg = tagmsg0;
7417 do {
7418 line = strsep(&tagmsg, "\n");
7419 if (line)
7420 printf(" %s\n", line);
7421 } while (line);
7422 free(tagmsg0);
7424 done:
7425 got_ref_list_free(&refs);
7426 free(wanted_refname);
7428 if (err == NULL && bad_sigs)
7429 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7430 return err;
7433 static const struct got_error *
7434 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7435 const char *tag_name, const char *repo_path)
7437 const struct got_error *err = NULL;
7438 char *template = NULL, *initial_content = NULL;
7439 char *editor = NULL;
7440 int initial_content_len;
7441 int fd = -1;
7443 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7444 err = got_error_from_errno("asprintf");
7445 goto done;
7448 initial_content_len = asprintf(&initial_content,
7449 "\n# tagging commit %s as %s\n",
7450 commit_id_str, tag_name);
7451 if (initial_content_len == -1) {
7452 err = got_error_from_errno("asprintf");
7453 goto done;
7456 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7457 if (err)
7458 goto done;
7460 if (write(fd, initial_content, initial_content_len) == -1) {
7461 err = got_error_from_errno2("write", *tagmsg_path);
7462 goto done;
7464 if (close(fd) == -1) {
7465 err = got_error_from_errno2("close", *tagmsg_path);
7466 goto done;
7468 fd = -1;
7470 err = get_editor(&editor);
7471 if (err)
7472 goto done;
7473 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7474 initial_content_len, 1);
7475 done:
7476 free(initial_content);
7477 free(template);
7478 free(editor);
7480 if (fd != -1 && close(fd) == -1 && err == NULL)
7481 err = got_error_from_errno2("close", *tagmsg_path);
7483 if (err) {
7484 free(*tagmsg);
7485 *tagmsg = NULL;
7487 return err;
7490 static const struct got_error *
7491 add_tag(struct got_repository *repo, const char *tagger,
7492 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7493 const char *signer_id, int verbosity)
7495 const struct got_error *err = NULL;
7496 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7497 char *label = NULL, *commit_id_str = NULL;
7498 struct got_reference *ref = NULL;
7499 char *refname = NULL, *tagmsg = NULL;
7500 char *tagmsg_path = NULL, *tag_id_str = NULL;
7501 int preserve_tagmsg = 0;
7502 struct got_reflist_head refs;
7504 TAILQ_INIT(&refs);
7507 * Don't let the user create a tag name with a leading '-'.
7508 * While technically a valid reference name, this case is usually
7509 * an unintended typo.
7511 if (tag_name[0] == '-')
7512 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7514 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7515 if (err)
7516 goto done;
7518 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7519 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7520 if (err)
7521 goto done;
7523 err = got_object_id_str(&commit_id_str, commit_id);
7524 if (err)
7525 goto done;
7527 err = get_tag_refname(&refname, tag_name);
7528 if (err)
7529 goto done;
7530 if (strncmp("refs/tags/", tag_name, 10) == 0)
7531 tag_name += 10;
7533 err = got_ref_open(&ref, repo, refname, 0);
7534 if (err == NULL) {
7535 err = got_error(GOT_ERR_TAG_EXISTS);
7536 goto done;
7537 } else if (err->code != GOT_ERR_NOT_REF)
7538 goto done;
7540 if (tagmsg_arg == NULL) {
7541 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7542 tag_name, got_repo_get_path(repo));
7543 if (err) {
7544 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7545 tagmsg_path != NULL)
7546 preserve_tagmsg = 1;
7547 goto done;
7549 /* Editor is done; we can now apply unveil(2) */
7550 err = got_sigs_apply_unveil();
7551 if (err)
7552 goto done;
7553 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7554 if (err)
7555 goto done;
7558 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7559 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7560 verbosity);
7561 if (err) {
7562 if (tagmsg_path)
7563 preserve_tagmsg = 1;
7564 goto done;
7567 err = got_ref_alloc(&ref, refname, tag_id);
7568 if (err) {
7569 if (tagmsg_path)
7570 preserve_tagmsg = 1;
7571 goto done;
7574 err = got_ref_write(ref, repo);
7575 if (err) {
7576 if (tagmsg_path)
7577 preserve_tagmsg = 1;
7578 goto done;
7581 err = got_object_id_str(&tag_id_str, tag_id);
7582 if (err) {
7583 if (tagmsg_path)
7584 preserve_tagmsg = 1;
7585 goto done;
7587 printf("Created tag %s\n", tag_id_str);
7588 done:
7589 if (preserve_tagmsg) {
7590 fprintf(stderr, "%s: tag message preserved in %s\n",
7591 getprogname(), tagmsg_path);
7592 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7593 err = got_error_from_errno2("unlink", tagmsg_path);
7594 free(tag_id_str);
7595 if (ref)
7596 got_ref_close(ref);
7597 free(commit_id);
7598 free(commit_id_str);
7599 free(refname);
7600 free(tagmsg);
7601 free(tagmsg_path);
7602 got_ref_list_free(&refs);
7603 return err;
7606 static const struct got_error *
7607 cmd_tag(int argc, char *argv[])
7609 const struct got_error *error = NULL;
7610 struct got_repository *repo = NULL;
7611 struct got_worktree *worktree = NULL;
7612 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7613 char *gitconfig_path = NULL, *tagger = NULL;
7614 char *allowed_signers = NULL, *revoked_signers = NULL;
7615 const char *signer_id = NULL;
7616 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7617 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7618 int *pack_fds = NULL;
7620 #ifndef PROFILE
7621 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7622 "sendfd unveil", NULL) == -1)
7623 err(1, "pledge");
7624 #endif
7626 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7627 switch (ch) {
7628 case 'c':
7629 commit_id_arg = optarg;
7630 break;
7631 case 'l':
7632 do_list = 1;
7633 break;
7634 case 'm':
7635 tagmsg = optarg;
7636 break;
7637 case 'r':
7638 repo_path = realpath(optarg, NULL);
7639 if (repo_path == NULL) {
7640 error = got_error_from_errno2("realpath",
7641 optarg);
7642 goto done;
7644 got_path_strip_trailing_slashes(repo_path);
7645 break;
7646 case 's':
7647 signer_id = optarg;
7648 break;
7649 case 'V':
7650 verify_tags = 1;
7651 break;
7652 case 'v':
7653 if (verbosity < 0)
7654 verbosity = 0;
7655 else if (verbosity < 3)
7656 verbosity++;
7657 break;
7658 default:
7659 usage_tag();
7660 /* NOTREACHED */
7664 argc -= optind;
7665 argv += optind;
7667 if (do_list || verify_tags) {
7668 if (commit_id_arg != NULL)
7669 errx(1,
7670 "-c option can only be used when creating a tag");
7671 if (tagmsg) {
7672 if (do_list)
7673 option_conflict('l', 'm');
7674 else
7675 option_conflict('V', 'm');
7677 if (signer_id) {
7678 if (do_list)
7679 option_conflict('l', 's');
7680 else
7681 option_conflict('V', 's');
7683 if (argc > 1)
7684 usage_tag();
7685 } else if (argc != 1)
7686 usage_tag();
7688 if (argc == 1)
7689 tag_name = argv[0];
7691 cwd = getcwd(NULL, 0);
7692 if (cwd == NULL) {
7693 error = got_error_from_errno("getcwd");
7694 goto done;
7697 error = got_repo_pack_fds_open(&pack_fds);
7698 if (error != NULL)
7699 goto done;
7701 if (repo_path == NULL) {
7702 error = got_worktree_open(&worktree, cwd);
7703 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7704 goto done;
7705 else
7706 error = NULL;
7707 if (worktree) {
7708 repo_path =
7709 strdup(got_worktree_get_repo_path(worktree));
7710 if (repo_path == NULL)
7711 error = got_error_from_errno("strdup");
7712 if (error)
7713 goto done;
7714 } else {
7715 repo_path = strdup(cwd);
7716 if (repo_path == NULL) {
7717 error = got_error_from_errno("strdup");
7718 goto done;
7723 if (do_list || verify_tags) {
7724 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7725 if (error != NULL)
7726 goto done;
7727 error = get_allowed_signers(&allowed_signers, repo, worktree);
7728 if (error)
7729 goto done;
7730 error = get_revoked_signers(&revoked_signers, repo, worktree);
7731 if (error)
7732 goto done;
7733 if (worktree) {
7734 /* Release work tree lock. */
7735 got_worktree_close(worktree);
7736 worktree = NULL;
7740 * Remove "cpath" promise unless needed for signature tmpfile
7741 * creation.
7743 if (verify_tags)
7744 got_sigs_apply_unveil();
7745 else {
7746 #ifndef PROFILE
7747 if (pledge("stdio rpath wpath flock proc exec sendfd "
7748 "unveil", NULL) == -1)
7749 err(1, "pledge");
7750 #endif
7752 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7753 if (error)
7754 goto done;
7755 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7756 revoked_signers, verbosity);
7757 } else {
7758 error = get_gitconfig_path(&gitconfig_path);
7759 if (error)
7760 goto done;
7761 error = got_repo_open(&repo, repo_path, gitconfig_path,
7762 pack_fds);
7763 if (error != NULL)
7764 goto done;
7766 error = get_author(&tagger, repo, worktree);
7767 if (error)
7768 goto done;
7769 if (signer_id == NULL)
7770 signer_id = get_signer_id(repo, worktree);
7772 if (tagmsg) {
7773 if (signer_id) {
7774 error = got_sigs_apply_unveil();
7775 if (error)
7776 goto done;
7778 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7779 if (error)
7780 goto done;
7783 if (commit_id_arg == NULL) {
7784 struct got_reference *head_ref;
7785 struct got_object_id *commit_id;
7786 error = got_ref_open(&head_ref, repo,
7787 worktree ? got_worktree_get_head_ref_name(worktree)
7788 : GOT_REF_HEAD, 0);
7789 if (error)
7790 goto done;
7791 error = got_ref_resolve(&commit_id, repo, head_ref);
7792 got_ref_close(head_ref);
7793 if (error)
7794 goto done;
7795 error = got_object_id_str(&commit_id_str, commit_id);
7796 free(commit_id);
7797 if (error)
7798 goto done;
7801 if (worktree) {
7802 /* Release work tree lock. */
7803 got_worktree_close(worktree);
7804 worktree = NULL;
7807 error = add_tag(repo, tagger, tag_name,
7808 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7809 signer_id, verbosity);
7811 done:
7812 if (repo) {
7813 const struct got_error *close_err = got_repo_close(repo);
7814 if (error == NULL)
7815 error = close_err;
7817 if (worktree)
7818 got_worktree_close(worktree);
7819 if (pack_fds) {
7820 const struct got_error *pack_err =
7821 got_repo_pack_fds_close(pack_fds);
7822 if (error == NULL)
7823 error = pack_err;
7825 free(cwd);
7826 free(repo_path);
7827 free(gitconfig_path);
7828 free(commit_id_str);
7829 free(tagger);
7830 free(allowed_signers);
7831 free(revoked_signers);
7832 return error;
7835 __dead static void
7836 usage_add(void)
7838 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7839 exit(1);
7842 static const struct got_error *
7843 add_progress(void *arg, unsigned char status, const char *path)
7845 while (path[0] == '/')
7846 path++;
7847 printf("%c %s\n", status, path);
7848 return NULL;
7851 static const struct got_error *
7852 cmd_add(int argc, char *argv[])
7854 const struct got_error *error = NULL;
7855 struct got_repository *repo = NULL;
7856 struct got_worktree *worktree = NULL;
7857 char *cwd = NULL;
7858 struct got_pathlist_head paths;
7859 struct got_pathlist_entry *pe;
7860 int ch, can_recurse = 0, no_ignores = 0;
7861 int *pack_fds = NULL;
7863 TAILQ_INIT(&paths);
7865 #ifndef PROFILE
7866 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7867 NULL) == -1)
7868 err(1, "pledge");
7869 #endif
7871 while ((ch = getopt(argc, argv, "IR")) != -1) {
7872 switch (ch) {
7873 case 'I':
7874 no_ignores = 1;
7875 break;
7876 case 'R':
7877 can_recurse = 1;
7878 break;
7879 default:
7880 usage_add();
7881 /* NOTREACHED */
7885 argc -= optind;
7886 argv += optind;
7888 if (argc < 1)
7889 usage_add();
7891 cwd = getcwd(NULL, 0);
7892 if (cwd == NULL) {
7893 error = got_error_from_errno("getcwd");
7894 goto done;
7897 error = got_repo_pack_fds_open(&pack_fds);
7898 if (error != NULL)
7899 goto done;
7901 error = got_worktree_open(&worktree, cwd);
7902 if (error) {
7903 if (error->code == GOT_ERR_NOT_WORKTREE)
7904 error = wrap_not_worktree_error(error, "add", cwd);
7905 goto done;
7908 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7909 NULL, pack_fds);
7910 if (error != NULL)
7911 goto done;
7913 error = apply_unveil(got_repo_get_path(repo), 1,
7914 got_worktree_get_root_path(worktree));
7915 if (error)
7916 goto done;
7918 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7919 if (error)
7920 goto done;
7922 if (!can_recurse) {
7923 char *ondisk_path;
7924 struct stat sb;
7925 TAILQ_FOREACH(pe, &paths, entry) {
7926 if (asprintf(&ondisk_path, "%s/%s",
7927 got_worktree_get_root_path(worktree),
7928 pe->path) == -1) {
7929 error = got_error_from_errno("asprintf");
7930 goto done;
7932 if (lstat(ondisk_path, &sb) == -1) {
7933 if (errno == ENOENT) {
7934 free(ondisk_path);
7935 continue;
7937 error = got_error_from_errno2("lstat",
7938 ondisk_path);
7939 free(ondisk_path);
7940 goto done;
7942 free(ondisk_path);
7943 if (S_ISDIR(sb.st_mode)) {
7944 error = got_error_msg(GOT_ERR_BAD_PATH,
7945 "adding directories requires -R option");
7946 goto done;
7951 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7952 NULL, repo, no_ignores);
7953 done:
7954 if (repo) {
7955 const struct got_error *close_err = got_repo_close(repo);
7956 if (error == NULL)
7957 error = close_err;
7959 if (worktree)
7960 got_worktree_close(worktree);
7961 if (pack_fds) {
7962 const struct got_error *pack_err =
7963 got_repo_pack_fds_close(pack_fds);
7964 if (error == NULL)
7965 error = pack_err;
7967 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7968 free(cwd);
7969 return error;
7972 __dead static void
7973 usage_remove(void)
7975 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7976 getprogname());
7977 exit(1);
7980 static const struct got_error *
7981 print_remove_status(void *arg, unsigned char status,
7982 unsigned char staged_status, const char *path)
7984 while (path[0] == '/')
7985 path++;
7986 if (status == GOT_STATUS_NONEXISTENT)
7987 return NULL;
7988 if (status == staged_status && (status == GOT_STATUS_DELETE))
7989 status = GOT_STATUS_NO_CHANGE;
7990 printf("%c%c %s\n", status, staged_status, path);
7991 return NULL;
7994 static const struct got_error *
7995 cmd_remove(int argc, char *argv[])
7997 const struct got_error *error = NULL;
7998 struct got_worktree *worktree = NULL;
7999 struct got_repository *repo = NULL;
8000 const char *status_codes = NULL;
8001 char *cwd = NULL;
8002 struct got_pathlist_head paths;
8003 struct got_pathlist_entry *pe;
8004 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8005 int ignore_missing_paths = 0;
8006 int *pack_fds = NULL;
8008 TAILQ_INIT(&paths);
8010 #ifndef PROFILE
8011 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8012 NULL) == -1)
8013 err(1, "pledge");
8014 #endif
8016 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8017 switch (ch) {
8018 case 'f':
8019 delete_local_mods = 1;
8020 ignore_missing_paths = 1;
8021 break;
8022 case 'k':
8023 keep_on_disk = 1;
8024 break;
8025 case 'R':
8026 can_recurse = 1;
8027 break;
8028 case 's':
8029 for (i = 0; optarg[i] != '\0'; i++) {
8030 switch (optarg[i]) {
8031 case GOT_STATUS_MODIFY:
8032 delete_local_mods = 1;
8033 break;
8034 case GOT_STATUS_MISSING:
8035 ignore_missing_paths = 1;
8036 break;
8037 default:
8038 errx(1, "invalid status code '%c'",
8039 optarg[i]);
8042 status_codes = optarg;
8043 break;
8044 default:
8045 usage_remove();
8046 /* NOTREACHED */
8050 argc -= optind;
8051 argv += optind;
8053 if (argc < 1)
8054 usage_remove();
8056 cwd = getcwd(NULL, 0);
8057 if (cwd == NULL) {
8058 error = got_error_from_errno("getcwd");
8059 goto done;
8062 error = got_repo_pack_fds_open(&pack_fds);
8063 if (error != NULL)
8064 goto done;
8066 error = got_worktree_open(&worktree, cwd);
8067 if (error) {
8068 if (error->code == GOT_ERR_NOT_WORKTREE)
8069 error = wrap_not_worktree_error(error, "remove", cwd);
8070 goto done;
8073 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8074 NULL, pack_fds);
8075 if (error)
8076 goto done;
8078 error = apply_unveil(got_repo_get_path(repo), 1,
8079 got_worktree_get_root_path(worktree));
8080 if (error)
8081 goto done;
8083 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8084 if (error)
8085 goto done;
8087 if (!can_recurse) {
8088 char *ondisk_path;
8089 struct stat sb;
8090 TAILQ_FOREACH(pe, &paths, entry) {
8091 if (asprintf(&ondisk_path, "%s/%s",
8092 got_worktree_get_root_path(worktree),
8093 pe->path) == -1) {
8094 error = got_error_from_errno("asprintf");
8095 goto done;
8097 if (lstat(ondisk_path, &sb) == -1) {
8098 if (errno == ENOENT) {
8099 free(ondisk_path);
8100 continue;
8102 error = got_error_from_errno2("lstat",
8103 ondisk_path);
8104 free(ondisk_path);
8105 goto done;
8107 free(ondisk_path);
8108 if (S_ISDIR(sb.st_mode)) {
8109 error = got_error_msg(GOT_ERR_BAD_PATH,
8110 "removing directories requires -R option");
8111 goto done;
8116 error = got_worktree_schedule_delete(worktree, &paths,
8117 delete_local_mods, status_codes, print_remove_status, NULL,
8118 repo, keep_on_disk, ignore_missing_paths);
8119 done:
8120 if (repo) {
8121 const struct got_error *close_err = got_repo_close(repo);
8122 if (error == NULL)
8123 error = close_err;
8125 if (worktree)
8126 got_worktree_close(worktree);
8127 if (pack_fds) {
8128 const struct got_error *pack_err =
8129 got_repo_pack_fds_close(pack_fds);
8130 if (error == NULL)
8131 error = pack_err;
8133 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8134 free(cwd);
8135 return error;
8138 __dead static void
8139 usage_patch(void)
8141 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8142 "[patchfile]\n", getprogname());
8143 exit(1);
8146 static const struct got_error *
8147 patch_from_stdin(int *patchfd)
8149 const struct got_error *err = NULL;
8150 ssize_t r;
8151 char buf[BUFSIZ];
8152 sig_t sighup, sigint, sigquit;
8154 *patchfd = got_opentempfd();
8155 if (*patchfd == -1)
8156 return got_error_from_errno("got_opentempfd");
8158 sighup = signal(SIGHUP, SIG_DFL);
8159 sigint = signal(SIGINT, SIG_DFL);
8160 sigquit = signal(SIGQUIT, SIG_DFL);
8162 for (;;) {
8163 r = read(0, buf, sizeof(buf));
8164 if (r == -1) {
8165 err = got_error_from_errno("read");
8166 break;
8168 if (r == 0)
8169 break;
8170 if (write(*patchfd, buf, r) == -1) {
8171 err = got_error_from_errno("write");
8172 break;
8176 signal(SIGHUP, sighup);
8177 signal(SIGINT, sigint);
8178 signal(SIGQUIT, sigquit);
8180 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8181 err = got_error_from_errno("lseek");
8183 if (err != NULL) {
8184 close(*patchfd);
8185 *patchfd = -1;
8188 return err;
8191 struct got_patch_progress_arg {
8192 int did_something;
8193 int conflicts;
8194 int rejects;
8197 static const struct got_error *
8198 patch_progress(void *arg, const char *old, const char *new,
8199 unsigned char status, const struct got_error *error, int old_from,
8200 int old_lines, int new_from, int new_lines, int offset,
8201 int ws_mangled, const struct got_error *hunk_err)
8203 const char *path = new == NULL ? old : new;
8204 struct got_patch_progress_arg *a = arg;
8206 while (*path == '/')
8207 path++;
8209 if (status != GOT_STATUS_NO_CHANGE &&
8210 status != 0 /* per-hunk progress */) {
8211 printf("%c %s\n", status, path);
8212 a->did_something = 1;
8215 if (hunk_err == NULL) {
8216 if (status == GOT_STATUS_CANNOT_UPDATE)
8217 a->rejects++;
8218 else if (status == GOT_STATUS_CONFLICT)
8219 a->conflicts++;
8222 if (error != NULL)
8223 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8225 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8226 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8227 old_lines, new_from, new_lines);
8228 if (hunk_err != NULL)
8229 printf("%s\n", hunk_err->msg);
8230 else if (offset != 0)
8231 printf("applied with offset %d\n", offset);
8232 else
8233 printf("hunk contains mangled whitespace\n");
8236 return NULL;
8239 static void
8240 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8242 if (!ppa->did_something)
8243 return;
8245 if (ppa->conflicts > 0)
8246 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8248 if (ppa->rejects > 0) {
8249 printf("Files where patch failed to apply: %d\n",
8250 ppa->rejects);
8254 static const struct got_error *
8255 cmd_patch(int argc, char *argv[])
8257 const struct got_error *error = NULL, *close_error = NULL;
8258 struct got_worktree *worktree = NULL;
8259 struct got_repository *repo = NULL;
8260 struct got_reflist_head refs;
8261 struct got_object_id *commit_id = NULL;
8262 const char *commit_id_str = NULL;
8263 struct stat sb;
8264 const char *errstr;
8265 char *cwd = NULL;
8266 int ch, nop = 0, strip = -1, reverse = 0;
8267 int patchfd;
8268 int *pack_fds = NULL;
8269 struct got_patch_progress_arg ppa;
8271 TAILQ_INIT(&refs);
8273 #ifndef PROFILE
8274 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8275 "unveil", NULL) == -1)
8276 err(1, "pledge");
8277 #endif
8279 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8280 switch (ch) {
8281 case 'c':
8282 commit_id_str = optarg;
8283 break;
8284 case 'n':
8285 nop = 1;
8286 break;
8287 case 'p':
8288 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8289 if (errstr != NULL)
8290 errx(1, "pathname strip count is %s: %s",
8291 errstr, optarg);
8292 break;
8293 case 'R':
8294 reverse = 1;
8295 break;
8296 default:
8297 usage_patch();
8298 /* NOTREACHED */
8302 argc -= optind;
8303 argv += optind;
8305 if (argc == 0) {
8306 error = patch_from_stdin(&patchfd);
8307 if (error)
8308 return error;
8309 } else if (argc == 1) {
8310 patchfd = open(argv[0], O_RDONLY);
8311 if (patchfd == -1) {
8312 error = got_error_from_errno2("open", argv[0]);
8313 return error;
8315 if (fstat(patchfd, &sb) == -1) {
8316 error = got_error_from_errno2("fstat", argv[0]);
8317 goto done;
8319 if (!S_ISREG(sb.st_mode)) {
8320 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8321 goto done;
8323 } else
8324 usage_patch();
8326 if ((cwd = getcwd(NULL, 0)) == NULL) {
8327 error = got_error_from_errno("getcwd");
8328 goto done;
8331 error = got_repo_pack_fds_open(&pack_fds);
8332 if (error != NULL)
8333 goto done;
8335 error = got_worktree_open(&worktree, cwd);
8336 if (error != NULL)
8337 goto done;
8339 const char *repo_path = got_worktree_get_repo_path(worktree);
8340 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8341 if (error != NULL)
8342 goto done;
8344 error = apply_unveil(got_repo_get_path(repo), 0,
8345 got_worktree_get_root_path(worktree));
8346 if (error != NULL)
8347 goto done;
8349 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8350 if (error)
8351 goto done;
8353 if (commit_id_str != NULL) {
8354 error = got_repo_match_object_id(&commit_id, NULL,
8355 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8356 if (error)
8357 goto done;
8360 memset(&ppa, 0, sizeof(ppa));
8361 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8362 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8363 print_patch_progress_stats(&ppa);
8364 done:
8365 got_ref_list_free(&refs);
8366 free(commit_id);
8367 if (repo) {
8368 close_error = got_repo_close(repo);
8369 if (error == NULL)
8370 error = close_error;
8372 if (worktree != NULL) {
8373 close_error = got_worktree_close(worktree);
8374 if (error == NULL)
8375 error = close_error;
8377 if (pack_fds) {
8378 const struct got_error *pack_err =
8379 got_repo_pack_fds_close(pack_fds);
8380 if (error == NULL)
8381 error = pack_err;
8383 free(cwd);
8384 return error;
8387 __dead static void
8388 usage_revert(void)
8390 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8391 getprogname());
8392 exit(1);
8395 static const struct got_error *
8396 revert_progress(void *arg, unsigned char status, const char *path)
8398 if (status == GOT_STATUS_UNVERSIONED)
8399 return NULL;
8401 while (path[0] == '/')
8402 path++;
8403 printf("%c %s\n", status, path);
8404 return NULL;
8407 struct choose_patch_arg {
8408 FILE *patch_script_file;
8409 const char *action;
8412 static const struct got_error *
8413 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8414 int nchanges, const char *action)
8416 const struct got_error *err;
8417 char *line = NULL;
8418 size_t linesize = 0;
8419 ssize_t linelen;
8421 switch (status) {
8422 case GOT_STATUS_ADD:
8423 printf("A %s\n%s this addition? [y/n] ", path, action);
8424 break;
8425 case GOT_STATUS_DELETE:
8426 printf("D %s\n%s this deletion? [y/n] ", path, action);
8427 break;
8428 case GOT_STATUS_MODIFY:
8429 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8430 return got_error_from_errno("fseek");
8431 printf(GOT_COMMIT_SEP_STR);
8432 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8433 printf("%s", line);
8434 if (linelen == -1 && ferror(patch_file)) {
8435 err = got_error_from_errno("getline");
8436 free(line);
8437 return err;
8439 free(line);
8440 printf(GOT_COMMIT_SEP_STR);
8441 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8442 path, n, nchanges, action);
8443 break;
8444 default:
8445 return got_error_path(path, GOT_ERR_FILE_STATUS);
8448 fflush(stdout);
8449 return NULL;
8452 static const struct got_error *
8453 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8454 FILE *patch_file, int n, int nchanges)
8456 const struct got_error *err = NULL;
8457 char *line = NULL;
8458 size_t linesize = 0;
8459 ssize_t linelen;
8460 int resp = ' ';
8461 struct choose_patch_arg *a = arg;
8463 *choice = GOT_PATCH_CHOICE_NONE;
8465 if (a->patch_script_file) {
8466 char *nl;
8467 err = show_change(status, path, patch_file, n, nchanges,
8468 a->action);
8469 if (err)
8470 return err;
8471 linelen = getline(&line, &linesize, a->patch_script_file);
8472 if (linelen == -1) {
8473 if (ferror(a->patch_script_file))
8474 return got_error_from_errno("getline");
8475 return NULL;
8477 nl = strchr(line, '\n');
8478 if (nl)
8479 *nl = '\0';
8480 if (strcmp(line, "y") == 0) {
8481 *choice = GOT_PATCH_CHOICE_YES;
8482 printf("y\n");
8483 } else if (strcmp(line, "n") == 0) {
8484 *choice = GOT_PATCH_CHOICE_NO;
8485 printf("n\n");
8486 } else if (strcmp(line, "q") == 0 &&
8487 status == GOT_STATUS_MODIFY) {
8488 *choice = GOT_PATCH_CHOICE_QUIT;
8489 printf("q\n");
8490 } else
8491 printf("invalid response '%s'\n", line);
8492 free(line);
8493 return NULL;
8496 while (resp != 'y' && resp != 'n' && resp != 'q') {
8497 err = show_change(status, path, patch_file, n, nchanges,
8498 a->action);
8499 if (err)
8500 return err;
8501 resp = getchar();
8502 if (resp == '\n')
8503 resp = getchar();
8504 if (status == GOT_STATUS_MODIFY) {
8505 if (resp != 'y' && resp != 'n' && resp != 'q') {
8506 printf("invalid response '%c'\n", resp);
8507 resp = ' ';
8509 } else if (resp != 'y' && resp != 'n') {
8510 printf("invalid response '%c'\n", resp);
8511 resp = ' ';
8515 if (resp == 'y')
8516 *choice = GOT_PATCH_CHOICE_YES;
8517 else if (resp == 'n')
8518 *choice = GOT_PATCH_CHOICE_NO;
8519 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8520 *choice = GOT_PATCH_CHOICE_QUIT;
8522 return NULL;
8525 struct wt_commitable_path_arg {
8526 struct got_pathlist_head *commit_paths;
8527 int *has_changes;
8531 * Shortcut work tree status callback to determine if the set of paths scanned
8532 * has at least one versioned path that is being modified and, if not NULL, is
8533 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8534 * soon as a path is passed with a status that satisfies this criteria.
8536 static const struct got_error *
8537 worktree_has_commitable_path(void *arg, unsigned char status,
8538 unsigned char staged_status, const char *path,
8539 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8540 struct got_object_id *commit_id, int dirfd, const char *de_name)
8542 struct wt_commitable_path_arg *a = arg;
8544 if (status == staged_status && (status == GOT_STATUS_DELETE))
8545 status = GOT_STATUS_NO_CHANGE;
8547 if (!(status == GOT_STATUS_NO_CHANGE ||
8548 status == GOT_STATUS_UNVERSIONED) ||
8549 staged_status != GOT_STATUS_NO_CHANGE) {
8550 if (a->commit_paths != NULL) {
8551 struct got_pathlist_entry *pe;
8553 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8554 if (strncmp(path, pe->path,
8555 pe->path_len) == 0) {
8556 *a->has_changes = 1;
8557 break;
8560 } else
8561 *a->has_changes = 1;
8563 if (*a->has_changes)
8564 return got_error(GOT_ERR_FILE_MODIFIED);
8567 return NULL;
8571 * Check that the changeset of the commit identified by id is
8572 * comprised of at least one modified path that is being committed.
8574 static const struct got_error *
8575 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8576 struct got_object_id *id, struct got_worktree *worktree,
8577 struct got_repository *repo)
8579 const struct got_error *err;
8580 struct got_pathlist_head paths;
8581 struct got_commit_object *commit = NULL, *pcommit = NULL;
8582 struct got_tree_object *tree = NULL, *ptree = NULL;
8583 struct got_object_qid *pid;
8585 TAILQ_INIT(&paths);
8587 err = got_object_open_as_commit(&commit, repo, id);
8588 if (err)
8589 goto done;
8591 err = got_object_open_as_tree(&tree, repo,
8592 got_object_commit_get_tree_id(commit));
8593 if (err)
8594 goto done;
8596 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8597 if (pid != NULL) {
8598 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8599 if (err)
8600 goto done;
8602 err = got_object_open_as_tree(&ptree, repo,
8603 got_object_commit_get_tree_id(pcommit));
8604 if (err)
8605 goto done;
8608 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8609 got_diff_tree_collect_changed_paths, &paths, 0);
8610 if (err)
8611 goto done;
8613 err = got_worktree_status(worktree, &paths, repo, 0,
8614 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8615 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8617 * At least one changed path in the referenced commit is
8618 * modified in the work tree, that's all we need to know!
8620 err = NULL;
8623 done:
8624 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8625 if (commit)
8626 got_object_commit_close(commit);
8627 if (pcommit)
8628 got_object_commit_close(pcommit);
8629 if (tree)
8630 got_object_tree_close(tree);
8631 if (ptree)
8632 got_object_tree_close(ptree);
8633 return err;
8637 * Remove any "logmsg" reference comprised entirely of paths that have
8638 * been reverted in this work tree. If any path in the logmsg ref changeset
8639 * remains in a changed state in the worktree, do not remove the reference.
8641 static const struct got_error *
8642 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8644 const struct got_error *err;
8645 struct got_reflist_head refs;
8646 struct got_reflist_entry *re;
8647 struct got_commit_object *commit = NULL;
8648 struct got_object_id *commit_id = NULL;
8649 struct wt_commitable_path_arg wcpa;
8650 char *uuidstr = NULL;
8652 TAILQ_INIT(&refs);
8654 err = got_worktree_get_uuid(&uuidstr, worktree);
8655 if (err)
8656 goto done;
8658 err = got_ref_list(&refs, repo, "refs/got/worktree",
8659 got_ref_cmp_by_name, repo);
8660 if (err)
8661 goto done;
8663 TAILQ_FOREACH(re, &refs, entry) {
8664 const char *refname;
8665 int has_changes = 0;
8667 refname = got_ref_get_name(re->ref);
8669 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8670 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8671 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8672 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8673 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8674 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8675 else
8676 continue;
8678 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8679 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8680 else
8681 continue;
8683 err = got_repo_match_object_id(&commit_id, NULL, refname,
8684 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8685 if (err)
8686 goto done;
8688 err = got_object_open_as_commit(&commit, repo, commit_id);
8689 if (err)
8690 goto done;
8692 wcpa.commit_paths = NULL;
8693 wcpa.has_changes = &has_changes;
8695 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8696 worktree, repo);
8697 if (err)
8698 goto done;
8700 if (!has_changes) {
8701 err = got_ref_delete(re->ref, repo);
8702 if (err)
8703 goto done;
8706 got_object_commit_close(commit);
8707 commit = NULL;
8708 free(commit_id);
8709 commit_id = NULL;
8712 done:
8713 free(uuidstr);
8714 free(commit_id);
8715 got_ref_list_free(&refs);
8716 if (commit)
8717 got_object_commit_close(commit);
8718 return err;
8721 static const struct got_error *
8722 cmd_revert(int argc, char *argv[])
8724 const struct got_error *error = NULL;
8725 struct got_worktree *worktree = NULL;
8726 struct got_repository *repo = NULL;
8727 char *cwd = NULL, *path = NULL;
8728 struct got_pathlist_head paths;
8729 struct got_pathlist_entry *pe;
8730 int ch, can_recurse = 0, pflag = 0;
8731 FILE *patch_script_file = NULL;
8732 const char *patch_script_path = NULL;
8733 struct choose_patch_arg cpa;
8734 int *pack_fds = NULL;
8736 TAILQ_INIT(&paths);
8738 #ifndef PROFILE
8739 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8740 "unveil", NULL) == -1)
8741 err(1, "pledge");
8742 #endif
8744 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8745 switch (ch) {
8746 case 'F':
8747 patch_script_path = optarg;
8748 break;
8749 case 'p':
8750 pflag = 1;
8751 break;
8752 case 'R':
8753 can_recurse = 1;
8754 break;
8755 default:
8756 usage_revert();
8757 /* NOTREACHED */
8761 argc -= optind;
8762 argv += optind;
8764 if (argc < 1)
8765 usage_revert();
8766 if (patch_script_path && !pflag)
8767 errx(1, "-F option can only be used together with -p option");
8769 cwd = getcwd(NULL, 0);
8770 if (cwd == NULL) {
8771 error = got_error_from_errno("getcwd");
8772 goto done;
8775 error = got_repo_pack_fds_open(&pack_fds);
8776 if (error != NULL)
8777 goto done;
8779 error = got_worktree_open(&worktree, cwd);
8780 if (error) {
8781 if (error->code == GOT_ERR_NOT_WORKTREE)
8782 error = wrap_not_worktree_error(error, "revert", cwd);
8783 goto done;
8786 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8787 NULL, pack_fds);
8788 if (error != NULL)
8789 goto done;
8791 if (patch_script_path) {
8792 patch_script_file = fopen(patch_script_path, "re");
8793 if (patch_script_file == NULL) {
8794 error = got_error_from_errno2("fopen",
8795 patch_script_path);
8796 goto done;
8801 * XXX "c" perm needed on repo dir to delete merge references.
8803 error = apply_unveil(got_repo_get_path(repo), 0,
8804 got_worktree_get_root_path(worktree));
8805 if (error)
8806 goto done;
8808 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8809 if (error)
8810 goto done;
8812 if (!can_recurse) {
8813 char *ondisk_path;
8814 struct stat sb;
8815 TAILQ_FOREACH(pe, &paths, entry) {
8816 if (asprintf(&ondisk_path, "%s/%s",
8817 got_worktree_get_root_path(worktree),
8818 pe->path) == -1) {
8819 error = got_error_from_errno("asprintf");
8820 goto done;
8822 if (lstat(ondisk_path, &sb) == -1) {
8823 if (errno == ENOENT) {
8824 free(ondisk_path);
8825 continue;
8827 error = got_error_from_errno2("lstat",
8828 ondisk_path);
8829 free(ondisk_path);
8830 goto done;
8832 free(ondisk_path);
8833 if (S_ISDIR(sb.st_mode)) {
8834 error = got_error_msg(GOT_ERR_BAD_PATH,
8835 "reverting directories requires -R option");
8836 goto done;
8841 cpa.patch_script_file = patch_script_file;
8842 cpa.action = "revert";
8843 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8844 pflag ? choose_patch : NULL, &cpa, repo);
8846 error = rm_logmsg_ref(worktree, repo);
8847 done:
8848 if (patch_script_file && fclose(patch_script_file) == EOF &&
8849 error == NULL)
8850 error = got_error_from_errno2("fclose", patch_script_path);
8851 if (repo) {
8852 const struct got_error *close_err = got_repo_close(repo);
8853 if (error == NULL)
8854 error = close_err;
8856 if (worktree)
8857 got_worktree_close(worktree);
8858 if (pack_fds) {
8859 const struct got_error *pack_err =
8860 got_repo_pack_fds_close(pack_fds);
8861 if (error == NULL)
8862 error = pack_err;
8864 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8865 free(path);
8866 free(cwd);
8867 return error;
8870 __dead static void
8871 usage_commit(void)
8873 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8874 "[-m message] [path ...]\n", getprogname());
8875 exit(1);
8878 struct collect_commit_logmsg_arg {
8879 const char *cmdline_log;
8880 const char *prepared_log;
8881 const char *merged_log;
8882 int non_interactive;
8883 const char *editor;
8884 const char *worktree_path;
8885 const char *branch_name;
8886 const char *repo_path;
8887 char *logmsg_path;
8891 static const struct got_error *
8892 read_prepared_logmsg(char **logmsg, const char *path)
8894 const struct got_error *err = NULL;
8895 FILE *f = NULL;
8896 struct stat sb;
8897 size_t r;
8899 *logmsg = NULL;
8900 memset(&sb, 0, sizeof(sb));
8902 f = fopen(path, "re");
8903 if (f == NULL)
8904 return got_error_from_errno2("fopen", path);
8906 if (fstat(fileno(f), &sb) == -1) {
8907 err = got_error_from_errno2("fstat", path);
8908 goto done;
8910 if (sb.st_size == 0) {
8911 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8912 goto done;
8915 *logmsg = malloc(sb.st_size + 1);
8916 if (*logmsg == NULL) {
8917 err = got_error_from_errno("malloc");
8918 goto done;
8921 r = fread(*logmsg, 1, sb.st_size, f);
8922 if (r != sb.st_size) {
8923 if (ferror(f))
8924 err = got_error_from_errno2("fread", path);
8925 else
8926 err = got_error(GOT_ERR_IO);
8927 goto done;
8929 (*logmsg)[sb.st_size] = '\0';
8930 done:
8931 if (fclose(f) == EOF && err == NULL)
8932 err = got_error_from_errno2("fclose", path);
8933 if (err) {
8934 free(*logmsg);
8935 *logmsg = NULL;
8937 return err;
8940 static const struct got_error *
8941 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8942 const char *diff_path, char **logmsg, void *arg)
8944 char *initial_content = NULL;
8945 struct got_pathlist_entry *pe;
8946 const struct got_error *err = NULL;
8947 char *template = NULL;
8948 char *prepared_msg = NULL, *merged_msg = NULL;
8949 struct collect_commit_logmsg_arg *a = arg;
8950 int initial_content_len;
8951 int fd = -1;
8952 size_t len;
8954 /* if a message was specified on the command line, just use it */
8955 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
8956 len = strlen(a->cmdline_log) + 1;
8957 *logmsg = malloc(len + 1);
8958 if (*logmsg == NULL)
8959 return got_error_from_errno("malloc");
8960 strlcpy(*logmsg, a->cmdline_log, len);
8961 return NULL;
8962 } else if (a->prepared_log != NULL && a->non_interactive)
8963 return read_prepared_logmsg(logmsg, a->prepared_log);
8965 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8966 return got_error_from_errno("asprintf");
8968 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8969 if (err)
8970 goto done;
8972 if (a->prepared_log) {
8973 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8974 if (err)
8975 goto done;
8976 } else if (a->merged_log) {
8977 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8978 if (err)
8979 goto done;
8982 initial_content_len = asprintf(&initial_content,
8983 "%s%s\n# changes to be committed on branch %s:\n",
8984 prepared_msg ? prepared_msg : "",
8985 merged_msg ? merged_msg : "", a->branch_name);
8986 if (initial_content_len == -1) {
8987 err = got_error_from_errno("asprintf");
8988 goto done;
8991 if (write(fd, initial_content, initial_content_len) == -1) {
8992 err = got_error_from_errno2("write", a->logmsg_path);
8993 goto done;
8996 TAILQ_FOREACH(pe, commitable_paths, entry) {
8997 struct got_commitable *ct = pe->data;
8998 dprintf(fd, "# %c %s\n",
8999 got_commitable_get_status(ct),
9000 got_commitable_get_path(ct));
9003 if (diff_path) {
9004 dprintf(fd, "# detailed changes can be viewed in %s\n",
9005 diff_path);
9008 if (close(fd) == -1) {
9009 err = got_error_from_errno2("close", a->logmsg_path);
9010 goto done;
9012 fd = -1;
9014 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9015 initial_content_len, a->prepared_log ? 0 : 1);
9016 done:
9017 free(initial_content);
9018 free(template);
9019 free(prepared_msg);
9020 free(merged_msg);
9022 if (fd != -1 && close(fd) == -1 && err == NULL)
9023 err = got_error_from_errno2("close", a->logmsg_path);
9025 /* Editor is done; we can now apply unveil(2) */
9026 if (err == NULL)
9027 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9028 if (err) {
9029 free(*logmsg);
9030 *logmsg = NULL;
9032 return err;
9035 static const struct got_error *
9036 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9037 const char *type, int has_content)
9039 const struct got_error *err = NULL;
9040 char *logmsg = NULL;
9042 err = got_object_commit_get_logmsg(&logmsg, commit);
9043 if (err)
9044 return err;
9046 if (fprintf(f, "%s# log message of %s commit %s:%s",
9047 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9048 err = got_ferror(f, GOT_ERR_IO);
9050 free(logmsg);
9051 return err;
9055 * Lookup "logmsg" references of backed-out and cherrypicked commits
9056 * belonging to the current work tree. If found, and the worktree has
9057 * at least one modified file that was changed in the referenced commit,
9058 * add its log message to a new temporary file at *logmsg_path.
9059 * Add all refs found to matched_refs to be scheduled for removal on
9060 * successful commit.
9062 static const struct got_error *
9063 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9064 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9065 struct got_repository *repo)
9067 const struct got_error *err;
9068 struct got_commit_object *commit = NULL;
9069 struct got_object_id *id = NULL;
9070 struct got_reflist_head refs;
9071 struct got_reflist_entry *re, *re_match;
9072 FILE *f = NULL;
9073 char *uuidstr = NULL;
9074 int added_logmsg = 0;
9076 TAILQ_INIT(&refs);
9078 *logmsg_path = NULL;
9080 err = got_worktree_get_uuid(&uuidstr, worktree);
9081 if (err)
9082 goto done;
9084 err = got_ref_list(&refs, repo, "refs/got/worktree",
9085 got_ref_cmp_by_name, repo);
9086 if (err)
9087 goto done;
9089 TAILQ_FOREACH(re, &refs, entry) {
9090 const char *refname, *type;
9091 struct wt_commitable_path_arg wcpa;
9092 int add_logmsg = 0;
9094 refname = got_ref_get_name(re->ref);
9096 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9097 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9098 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9099 type = "cherrypicked";
9100 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9101 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9102 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9103 type = "backed-out";
9104 } else
9105 continue;
9107 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9108 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9109 else
9110 continue;
9112 err = got_repo_match_object_id(&id, NULL, refname,
9113 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9114 if (err)
9115 goto done;
9117 err = got_object_open_as_commit(&commit, repo, id);
9118 if (err)
9119 goto done;
9121 wcpa.commit_paths = paths;
9122 wcpa.has_changes = &add_logmsg;
9124 err = commit_path_changed_in_worktree(&wcpa, id,
9125 worktree, repo);
9126 if (err)
9127 goto done;
9129 if (add_logmsg) {
9130 if (f == NULL) {
9131 err = got_opentemp_named(logmsg_path, &f,
9132 "got-commit-logmsg", "");
9133 if (err)
9134 goto done;
9136 err = cat_logmsg(f, commit, refname, type,
9137 added_logmsg);
9138 if (err)
9139 goto done;
9140 if (!added_logmsg)
9141 ++added_logmsg;
9143 err = got_reflist_entry_dup(&re_match, re);
9144 if (err)
9145 goto done;
9146 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9149 got_object_commit_close(commit);
9150 commit = NULL;
9151 free(id);
9152 id = NULL;
9155 done:
9156 free(id);
9157 free(uuidstr);
9158 got_ref_list_free(&refs);
9159 if (commit)
9160 got_object_commit_close(commit);
9161 if (f && fclose(f) == EOF && err == NULL)
9162 err = got_error_from_errno("fclose");
9163 if (!added_logmsg) {
9164 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9165 err = got_error_from_errno2("unlink", *logmsg_path);
9166 *logmsg_path = NULL;
9168 return err;
9171 static const struct got_error *
9172 cmd_commit(int argc, char *argv[])
9174 const struct got_error *error = NULL;
9175 struct got_worktree *worktree = NULL;
9176 struct got_repository *repo = NULL;
9177 char *cwd = NULL, *id_str = NULL;
9178 struct got_object_id *id = NULL;
9179 const char *logmsg = NULL;
9180 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9181 struct collect_commit_logmsg_arg cl_arg;
9182 const char *author = NULL;
9183 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9184 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9185 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9186 int show_diff = 1, commit_conflicts = 0;
9187 struct got_pathlist_head paths;
9188 struct got_reflist_head refs;
9189 struct got_reflist_entry *re;
9190 int *pack_fds = NULL;
9192 TAILQ_INIT(&refs);
9193 TAILQ_INIT(&paths);
9194 cl_arg.logmsg_path = NULL;
9196 #ifndef PROFILE
9197 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9198 "unveil", NULL) == -1)
9199 err(1, "pledge");
9200 #endif
9202 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9203 switch (ch) {
9204 case 'A':
9205 author = optarg;
9206 error = valid_author(author);
9207 if (error)
9208 return error;
9209 break;
9210 case 'C':
9211 commit_conflicts = 1;
9212 break;
9213 case 'F':
9214 if (logmsg != NULL)
9215 option_conflict('F', 'm');
9216 prepared_logmsg = realpath(optarg, NULL);
9217 if (prepared_logmsg == NULL)
9218 return got_error_from_errno2("realpath",
9219 optarg);
9220 break;
9221 case 'm':
9222 if (prepared_logmsg)
9223 option_conflict('m', 'F');
9224 logmsg = optarg;
9225 break;
9226 case 'N':
9227 non_interactive = 1;
9228 break;
9229 case 'n':
9230 show_diff = 0;
9231 break;
9232 case 'S':
9233 allow_bad_symlinks = 1;
9234 break;
9235 default:
9236 usage_commit();
9237 /* NOTREACHED */
9241 argc -= optind;
9242 argv += optind;
9244 cwd = getcwd(NULL, 0);
9245 if (cwd == NULL) {
9246 error = got_error_from_errno("getcwd");
9247 goto done;
9250 error = got_repo_pack_fds_open(&pack_fds);
9251 if (error != NULL)
9252 goto done;
9254 error = got_worktree_open(&worktree, cwd);
9255 if (error) {
9256 if (error->code == GOT_ERR_NOT_WORKTREE)
9257 error = wrap_not_worktree_error(error, "commit", cwd);
9258 goto done;
9261 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9262 if (error)
9263 goto done;
9264 if (rebase_in_progress) {
9265 error = got_error(GOT_ERR_REBASING);
9266 goto done;
9269 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9270 worktree);
9271 if (error)
9272 goto done;
9274 error = get_gitconfig_path(&gitconfig_path);
9275 if (error)
9276 goto done;
9277 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9278 gitconfig_path, pack_fds);
9279 if (error != NULL)
9280 goto done;
9282 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9283 if (error)
9284 goto done;
9285 if (merge_in_progress) {
9286 error = got_error(GOT_ERR_MERGE_BUSY);
9287 goto done;
9290 error = get_author(&committer, repo, worktree);
9291 if (error)
9292 goto done;
9294 if (author == NULL)
9295 author = committer;
9298 * unveil(2) traverses exec(2); if an editor is used we have
9299 * to apply unveil after the log message has been written.
9301 if (logmsg == NULL || strlen(logmsg) == 0)
9302 error = get_editor(&editor);
9303 else
9304 error = apply_unveil(got_repo_get_path(repo), 0,
9305 got_worktree_get_root_path(worktree));
9306 if (error)
9307 goto done;
9309 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9310 if (error)
9311 goto done;
9313 if (prepared_logmsg == NULL) {
9314 error = lookup_logmsg_ref(&merged_logmsg,
9315 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9316 if (error)
9317 goto done;
9320 cl_arg.editor = editor;
9321 cl_arg.cmdline_log = logmsg;
9322 cl_arg.prepared_log = prepared_logmsg;
9323 cl_arg.merged_log = merged_logmsg;
9324 cl_arg.non_interactive = non_interactive;
9325 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9326 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9327 if (!histedit_in_progress) {
9328 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9329 error = got_error(GOT_ERR_COMMIT_BRANCH);
9330 goto done;
9332 cl_arg.branch_name += 11;
9334 cl_arg.repo_path = got_repo_get_path(repo);
9335 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9336 allow_bad_symlinks, show_diff, commit_conflicts,
9337 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9338 if (error) {
9339 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9340 cl_arg.logmsg_path != NULL)
9341 preserve_logmsg = 1;
9342 goto done;
9345 error = got_object_id_str(&id_str, id);
9346 if (error)
9347 goto done;
9348 printf("Created commit %s\n", id_str);
9350 TAILQ_FOREACH(re, &refs, entry) {
9351 error = got_ref_delete(re->ref, repo);
9352 if (error)
9353 goto done;
9356 done:
9357 if (preserve_logmsg) {
9358 fprintf(stderr, "%s: log message preserved in %s\n",
9359 getprogname(), cl_arg.logmsg_path);
9360 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9361 error == NULL)
9362 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9363 free(cl_arg.logmsg_path);
9364 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9365 error = got_error_from_errno2("unlink", merged_logmsg);
9366 free(merged_logmsg);
9367 if (repo) {
9368 const struct got_error *close_err = got_repo_close(repo);
9369 if (error == NULL)
9370 error = close_err;
9372 if (worktree)
9373 got_worktree_close(worktree);
9374 if (pack_fds) {
9375 const struct got_error *pack_err =
9376 got_repo_pack_fds_close(pack_fds);
9377 if (error == NULL)
9378 error = pack_err;
9380 got_ref_list_free(&refs);
9381 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9382 free(cwd);
9383 free(id_str);
9384 free(gitconfig_path);
9385 free(editor);
9386 free(committer);
9387 free(prepared_logmsg);
9388 return error;
9391 __dead static void
9392 usage_send(void)
9394 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9395 "[-r repository-path] [-t tag] [remote-repository]\n",
9396 getprogname());
9397 exit(1);
9400 static void
9401 print_load_info(int print_colored, int print_found, int print_trees,
9402 int ncolored, int nfound, int ntrees)
9404 if (print_colored) {
9405 printf("%d commit%s colored", ncolored,
9406 ncolored == 1 ? "" : "s");
9408 if (print_found) {
9409 printf("%s%d object%s found",
9410 ncolored > 0 ? "; " : "",
9411 nfound, nfound == 1 ? "" : "s");
9413 if (print_trees) {
9414 printf("; %d tree%s scanned", ntrees,
9415 ntrees == 1 ? "" : "s");
9419 struct got_send_progress_arg {
9420 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9421 int verbosity;
9422 int last_ncolored;
9423 int last_nfound;
9424 int last_ntrees;
9425 int loading_done;
9426 int last_ncommits;
9427 int last_nobj_total;
9428 int last_p_deltify;
9429 int last_p_written;
9430 int last_p_sent;
9431 int printed_something;
9432 int sent_something;
9433 struct got_pathlist_head *delete_branches;
9436 static const struct got_error *
9437 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9438 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9439 int nobj_written, off_t bytes_sent, const char *refname,
9440 const char *errmsg, int success)
9442 struct got_send_progress_arg *a = arg;
9443 char scaled_packsize[FMT_SCALED_STRSIZE];
9444 char scaled_sent[FMT_SCALED_STRSIZE];
9445 int p_deltify = 0, p_written = 0, p_sent = 0;
9446 int print_colored = 0, print_found = 0, print_trees = 0;
9447 int print_searching = 0, print_total = 0;
9448 int print_deltify = 0, print_written = 0, print_sent = 0;
9450 if (a->verbosity < 0)
9451 return NULL;
9453 if (refname) {
9454 const char *status = success ? "accepted" : "rejected";
9456 if (success) {
9457 struct got_pathlist_entry *pe;
9458 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9459 const char *branchname = pe->path;
9460 if (got_path_cmp(branchname, refname,
9461 strlen(branchname), strlen(refname)) == 0) {
9462 status = "deleted";
9463 a->sent_something = 1;
9464 break;
9469 if (a->printed_something)
9470 putchar('\n');
9471 printf("Server has %s %s", status, refname);
9472 if (errmsg)
9473 printf(": %s", errmsg);
9474 a->printed_something = 1;
9475 return NULL;
9478 if (a->last_ncolored != ncolored) {
9479 print_colored = 1;
9480 a->last_ncolored = ncolored;
9483 if (a->last_nfound != nfound) {
9484 print_colored = 1;
9485 print_found = 1;
9486 a->last_nfound = nfound;
9489 if (a->last_ntrees != ntrees) {
9490 print_colored = 1;
9491 print_found = 1;
9492 print_trees = 1;
9493 a->last_ntrees = ntrees;
9496 if ((print_colored || print_found || print_trees) &&
9497 !a->loading_done) {
9498 printf("\r");
9499 print_load_info(print_colored, print_found, print_trees,
9500 ncolored, nfound, ntrees);
9501 a->printed_something = 1;
9502 fflush(stdout);
9503 return NULL;
9504 } else if (!a->loading_done) {
9505 printf("\r");
9506 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9507 printf("\n");
9508 a->loading_done = 1;
9511 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9512 return got_error_from_errno("fmt_scaled");
9513 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9514 return got_error_from_errno("fmt_scaled");
9516 if (a->last_ncommits != ncommits) {
9517 print_searching = 1;
9518 a->last_ncommits = ncommits;
9521 if (a->last_nobj_total != nobj_total) {
9522 print_searching = 1;
9523 print_total = 1;
9524 a->last_nobj_total = nobj_total;
9527 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9528 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9529 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9530 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9531 return got_error(GOT_ERR_NO_SPACE);
9534 if (nobj_deltify > 0 || nobj_written > 0) {
9535 if (nobj_deltify > 0) {
9536 p_deltify = (nobj_deltify * 100) / nobj_total;
9537 if (p_deltify != a->last_p_deltify) {
9538 a->last_p_deltify = p_deltify;
9539 print_searching = 1;
9540 print_total = 1;
9541 print_deltify = 1;
9544 if (nobj_written > 0) {
9545 p_written = (nobj_written * 100) / nobj_total;
9546 if (p_written != a->last_p_written) {
9547 a->last_p_written = p_written;
9548 print_searching = 1;
9549 print_total = 1;
9550 print_deltify = 1;
9551 print_written = 1;
9556 if (bytes_sent > 0) {
9557 p_sent = (bytes_sent * 100) / packfile_size;
9558 if (p_sent != a->last_p_sent) {
9559 a->last_p_sent = p_sent;
9560 print_searching = 1;
9561 print_total = 1;
9562 print_deltify = 1;
9563 print_written = 1;
9564 print_sent = 1;
9566 a->sent_something = 1;
9569 if (print_searching || print_total || print_deltify || print_written ||
9570 print_sent)
9571 printf("\r");
9572 if (print_searching)
9573 printf("packing %d reference%s", ncommits,
9574 ncommits == 1 ? "" : "s");
9575 if (print_total)
9576 printf("; %d object%s", nobj_total,
9577 nobj_total == 1 ? "" : "s");
9578 if (print_deltify)
9579 printf("; deltify: %d%%", p_deltify);
9580 if (print_sent)
9581 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9582 scaled_packsize, p_sent);
9583 else if (print_written)
9584 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9585 scaled_packsize, p_written);
9586 if (print_searching || print_total || print_deltify ||
9587 print_written || print_sent) {
9588 a->printed_something = 1;
9589 fflush(stdout);
9591 return NULL;
9594 static const struct got_error *
9595 cmd_send(int argc, char *argv[])
9597 const struct got_error *error = NULL;
9598 char *cwd = NULL, *repo_path = NULL;
9599 const char *remote_name;
9600 char *proto = NULL, *host = NULL, *port = NULL;
9601 char *repo_name = NULL, *server_path = NULL;
9602 const struct got_remote_repo *remotes, *remote = NULL;
9603 int nremotes, nbranches = 0, ndelete_branches = 0;
9604 struct got_repository *repo = NULL;
9605 struct got_worktree *worktree = NULL;
9606 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9607 struct got_pathlist_head branches;
9608 struct got_pathlist_head tags;
9609 struct got_reflist_head all_branches;
9610 struct got_reflist_head all_tags;
9611 struct got_pathlist_head delete_args;
9612 struct got_pathlist_head delete_branches;
9613 struct got_reflist_entry *re;
9614 struct got_pathlist_entry *pe;
9615 int i, ch, sendfd = -1, sendstatus;
9616 pid_t sendpid = -1;
9617 struct got_send_progress_arg spa;
9618 int verbosity = 0, overwrite_refs = 0;
9619 int send_all_branches = 0, send_all_tags = 0;
9620 struct got_reference *ref = NULL;
9621 int *pack_fds = NULL;
9623 TAILQ_INIT(&branches);
9624 TAILQ_INIT(&tags);
9625 TAILQ_INIT(&all_branches);
9626 TAILQ_INIT(&all_tags);
9627 TAILQ_INIT(&delete_args);
9628 TAILQ_INIT(&delete_branches);
9630 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9631 switch (ch) {
9632 case 'a':
9633 send_all_branches = 1;
9634 break;
9635 case 'b':
9636 error = got_pathlist_append(&branches, optarg, NULL);
9637 if (error)
9638 return error;
9639 nbranches++;
9640 break;
9641 case 'd':
9642 error = got_pathlist_append(&delete_args, optarg, NULL);
9643 if (error)
9644 return error;
9645 break;
9646 case 'f':
9647 overwrite_refs = 1;
9648 break;
9649 case 'q':
9650 verbosity = -1;
9651 break;
9652 case 'r':
9653 repo_path = realpath(optarg, NULL);
9654 if (repo_path == NULL)
9655 return got_error_from_errno2("realpath",
9656 optarg);
9657 got_path_strip_trailing_slashes(repo_path);
9658 break;
9659 case 'T':
9660 send_all_tags = 1;
9661 break;
9662 case 't':
9663 error = got_pathlist_append(&tags, optarg, NULL);
9664 if (error)
9665 return error;
9666 break;
9667 case 'v':
9668 if (verbosity < 0)
9669 verbosity = 0;
9670 else if (verbosity < 3)
9671 verbosity++;
9672 break;
9673 default:
9674 usage_send();
9675 /* NOTREACHED */
9678 argc -= optind;
9679 argv += optind;
9681 if (send_all_branches && !TAILQ_EMPTY(&branches))
9682 option_conflict('a', 'b');
9683 if (send_all_tags && !TAILQ_EMPTY(&tags))
9684 option_conflict('T', 't');
9687 if (argc == 0)
9688 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9689 else if (argc == 1)
9690 remote_name = argv[0];
9691 else
9692 usage_send();
9694 cwd = getcwd(NULL, 0);
9695 if (cwd == NULL) {
9696 error = got_error_from_errno("getcwd");
9697 goto done;
9700 error = got_repo_pack_fds_open(&pack_fds);
9701 if (error != NULL)
9702 goto done;
9704 if (repo_path == NULL) {
9705 error = got_worktree_open(&worktree, cwd);
9706 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9707 goto done;
9708 else
9709 error = NULL;
9710 if (worktree) {
9711 repo_path =
9712 strdup(got_worktree_get_repo_path(worktree));
9713 if (repo_path == NULL)
9714 error = got_error_from_errno("strdup");
9715 if (error)
9716 goto done;
9717 } else {
9718 repo_path = strdup(cwd);
9719 if (repo_path == NULL) {
9720 error = got_error_from_errno("strdup");
9721 goto done;
9726 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9727 if (error)
9728 goto done;
9730 if (worktree) {
9731 worktree_conf = got_worktree_get_gotconfig(worktree);
9732 if (worktree_conf) {
9733 got_gotconfig_get_remotes(&nremotes, &remotes,
9734 worktree_conf);
9735 for (i = 0; i < nremotes; i++) {
9736 if (strcmp(remotes[i].name, remote_name) == 0) {
9737 remote = &remotes[i];
9738 break;
9743 if (remote == NULL) {
9744 repo_conf = got_repo_get_gotconfig(repo);
9745 if (repo_conf) {
9746 got_gotconfig_get_remotes(&nremotes, &remotes,
9747 repo_conf);
9748 for (i = 0; i < nremotes; i++) {
9749 if (strcmp(remotes[i].name, remote_name) == 0) {
9750 remote = &remotes[i];
9751 break;
9756 if (remote == NULL) {
9757 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9758 for (i = 0; i < nremotes; i++) {
9759 if (strcmp(remotes[i].name, remote_name) == 0) {
9760 remote = &remotes[i];
9761 break;
9765 if (remote == NULL) {
9766 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9767 goto done;
9770 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9771 &repo_name, remote->send_url);
9772 if (error)
9773 goto done;
9775 if (strcmp(proto, "git") == 0) {
9776 #ifndef PROFILE
9777 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9778 "sendfd dns inet unveil", NULL) == -1)
9779 err(1, "pledge");
9780 #endif
9781 } else if (strcmp(proto, "git+ssh") == 0 ||
9782 strcmp(proto, "ssh") == 0) {
9783 #ifndef PROFILE
9784 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9785 "sendfd unveil", NULL) == -1)
9786 err(1, "pledge");
9787 #endif
9788 } else if (strcmp(proto, "http") == 0 ||
9789 strcmp(proto, "git+http") == 0) {
9790 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9791 goto done;
9792 } else {
9793 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9794 goto done;
9797 error = got_dial_apply_unveil(proto);
9798 if (error)
9799 goto done;
9801 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9802 if (error)
9803 goto done;
9805 if (send_all_branches) {
9806 error = got_ref_list(&all_branches, repo, "refs/heads",
9807 got_ref_cmp_by_name, NULL);
9808 if (error)
9809 goto done;
9810 TAILQ_FOREACH(re, &all_branches, entry) {
9811 const char *branchname = got_ref_get_name(re->ref);
9812 error = got_pathlist_append(&branches,
9813 branchname, NULL);
9814 if (error)
9815 goto done;
9816 nbranches++;
9818 } else if (nbranches == 0) {
9819 for (i = 0; i < remote->nsend_branches; i++) {
9820 error = got_pathlist_append(&branches,
9821 remote->send_branches[i], NULL);
9822 if (error)
9823 goto done;
9827 if (send_all_tags) {
9828 error = got_ref_list(&all_tags, repo, "refs/tags",
9829 got_ref_cmp_by_name, NULL);
9830 if (error)
9831 goto done;
9832 TAILQ_FOREACH(re, &all_tags, entry) {
9833 const char *tagname = got_ref_get_name(re->ref);
9834 error = got_pathlist_append(&tags,
9835 tagname, NULL);
9836 if (error)
9837 goto done;
9842 * To prevent accidents only branches in refs/heads/ can be deleted
9843 * with 'got send -d'.
9844 * Deleting anything else requires local repository access or Git.
9846 TAILQ_FOREACH(pe, &delete_args, entry) {
9847 const char *branchname = pe->path;
9848 char *s;
9849 struct got_pathlist_entry *new;
9850 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9851 s = strdup(branchname);
9852 if (s == NULL) {
9853 error = got_error_from_errno("strdup");
9854 goto done;
9856 } else {
9857 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9858 error = got_error_from_errno("asprintf");
9859 goto done;
9862 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9863 if (error || new == NULL /* duplicate */)
9864 free(s);
9865 if (error)
9866 goto done;
9867 ndelete_branches++;
9870 if (nbranches == 0 && ndelete_branches == 0) {
9871 struct got_reference *head_ref;
9872 if (worktree)
9873 error = got_ref_open(&head_ref, repo,
9874 got_worktree_get_head_ref_name(worktree), 0);
9875 else
9876 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9877 if (error)
9878 goto done;
9879 if (got_ref_is_symbolic(head_ref)) {
9880 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9881 got_ref_close(head_ref);
9882 if (error)
9883 goto done;
9884 } else
9885 ref = head_ref;
9886 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9887 NULL);
9888 if (error)
9889 goto done;
9890 nbranches++;
9893 if (verbosity >= 0) {
9894 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9895 remote->name, proto, host,
9896 port ? ":" : "", port ? port : "",
9897 *server_path == '/' ? "" : "/", server_path);
9900 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9901 server_path, verbosity);
9902 if (error)
9903 goto done;
9905 memset(&spa, 0, sizeof(spa));
9906 spa.last_scaled_packsize[0] = '\0';
9907 spa.last_p_deltify = -1;
9908 spa.last_p_written = -1;
9909 spa.verbosity = verbosity;
9910 spa.delete_branches = &delete_branches;
9911 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9912 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9913 check_cancelled, NULL);
9914 if (spa.printed_something)
9915 putchar('\n');
9916 if (error)
9917 goto done;
9918 if (!spa.sent_something && verbosity >= 0)
9919 printf("Already up-to-date\n");
9920 done:
9921 if (sendpid > 0) {
9922 if (kill(sendpid, SIGTERM) == -1)
9923 error = got_error_from_errno("kill");
9924 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9925 error = got_error_from_errno("waitpid");
9927 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9928 error = got_error_from_errno("close");
9929 if (repo) {
9930 const struct got_error *close_err = got_repo_close(repo);
9931 if (error == NULL)
9932 error = close_err;
9934 if (worktree)
9935 got_worktree_close(worktree);
9936 if (pack_fds) {
9937 const struct got_error *pack_err =
9938 got_repo_pack_fds_close(pack_fds);
9939 if (error == NULL)
9940 error = pack_err;
9942 if (ref)
9943 got_ref_close(ref);
9944 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9945 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9946 got_ref_list_free(&all_branches);
9947 got_ref_list_free(&all_tags);
9948 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9949 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9950 free(cwd);
9951 free(repo_path);
9952 free(proto);
9953 free(host);
9954 free(port);
9955 free(server_path);
9956 free(repo_name);
9957 return error;
9961 * Print and if delete is set delete all ref_prefix references.
9962 * If wanted_ref is not NULL, only print or delete this reference.
9964 static const struct got_error *
9965 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9966 const char *wanted_ref, int delete, struct got_worktree *worktree,
9967 struct got_repository *repo)
9969 const struct got_error *err;
9970 struct got_pathlist_head paths;
9971 struct got_reflist_head refs;
9972 struct got_reflist_entry *re;
9973 struct got_reflist_object_id_map *refs_idmap = NULL;
9974 struct got_commit_object *commit = NULL;
9975 struct got_object_id *id = NULL;
9976 const char *header_prefix;
9977 char *uuidstr = NULL;
9978 int found = 0;
9980 TAILQ_INIT(&refs);
9981 TAILQ_INIT(&paths);
9983 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9984 if (err)
9985 goto done;
9987 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9988 if (err)
9989 goto done;
9991 if (worktree != NULL) {
9992 err = got_worktree_get_uuid(&uuidstr, worktree);
9993 if (err)
9994 goto done;
9997 if (wanted_ref) {
9998 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9999 wanted_ref += 11;
10002 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10003 header_prefix = "backout";
10004 else
10005 header_prefix = "cherrypick";
10007 TAILQ_FOREACH(re, &refs, entry) {
10008 const char *refname, *wt;
10010 refname = got_ref_get_name(re->ref);
10012 err = check_cancelled(NULL);
10013 if (err)
10014 goto done;
10016 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10017 refname += prefix_len + 1; /* skip '-' delimiter */
10018 else
10019 continue;
10021 wt = refname;
10023 if (worktree == NULL || strncmp(refname, uuidstr,
10024 GOT_WORKTREE_UUID_STRLEN) == 0)
10025 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10026 else
10027 continue;
10029 err = got_repo_match_object_id(&id, NULL, refname,
10030 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10031 if (err)
10032 goto done;
10034 err = got_object_open_as_commit(&commit, repo, id);
10035 if (err)
10036 goto done;
10038 if (wanted_ref)
10039 found = strncmp(wanted_ref, refname,
10040 strlen(wanted_ref)) == 0;
10041 if (wanted_ref && !found) {
10042 struct got_reflist_head *ci_refs;
10044 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10045 id);
10047 if (ci_refs) {
10048 char *refs_str = NULL;
10049 char const *r = NULL;
10051 err = build_refs_str(&refs_str, ci_refs, id,
10052 repo, 1);
10053 if (err)
10054 goto done;
10056 r = refs_str;
10057 while (r) {
10058 if (strncmp(r, wanted_ref,
10059 strlen(wanted_ref)) == 0) {
10060 found = 1;
10061 break;
10063 r = strchr(r, ' ');
10064 if (r)
10065 ++r;
10067 free(refs_str);
10071 if (wanted_ref == NULL || found) {
10072 if (delete) {
10073 err = got_ref_delete(re->ref, repo);
10074 if (err)
10075 goto done;
10076 printf("Deleted: ");
10077 err = print_commit_oneline(commit, id, repo,
10078 refs_idmap);
10079 } else {
10081 * Print paths modified by commit to help
10082 * associate commits with worktree changes.
10084 err = get_changed_paths(&paths, commit,
10085 repo, NULL);
10086 if (err)
10087 goto done;
10089 err = print_commit(commit, id, repo, NULL,
10090 &paths, NULL, 0, 0, refs_idmap, NULL,
10091 header_prefix);
10092 got_pathlist_free(&paths,
10093 GOT_PATHLIST_FREE_ALL);
10095 if (worktree == NULL)
10096 printf("work tree: %.*s\n\n",
10097 GOT_WORKTREE_UUID_STRLEN, wt);
10099 if (err || found)
10100 goto done;
10103 got_object_commit_close(commit);
10104 commit = NULL;
10105 free(id);
10106 id = NULL;
10109 if (wanted_ref != NULL && !found)
10110 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10112 done:
10113 free(id);
10114 free(uuidstr);
10115 got_ref_list_free(&refs);
10116 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10117 if (refs_idmap)
10118 got_reflist_object_id_map_free(refs_idmap);
10119 if (commit)
10120 got_object_commit_close(commit);
10121 return err;
10125 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10126 * identified by id for log messages to prepopulate the editor on commit.
10128 static const struct got_error *
10129 logmsg_ref(struct got_object_id *id, const char *prefix,
10130 struct got_worktree *worktree, struct got_repository *repo)
10132 const struct got_error *err = NULL;
10133 char *idstr, *ref = NULL, *refname = NULL;
10134 int histedit_in_progress;
10135 int rebase_in_progress, merge_in_progress;
10138 * Silenty refuse to create merge reference if any histedit, merge,
10139 * or rebase operation is in progress.
10141 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10142 worktree);
10143 if (err)
10144 return err;
10145 if (histedit_in_progress)
10146 return NULL;
10148 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10149 if (err)
10150 return err;
10151 if (rebase_in_progress)
10152 return NULL;
10154 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10155 repo);
10156 if (err)
10157 return err;
10158 if (merge_in_progress)
10159 return NULL;
10161 err = got_object_id_str(&idstr, id);
10162 if (err)
10163 return err;
10165 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10166 if (err)
10167 goto done;
10169 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10170 err = got_error_from_errno("asprintf");
10171 goto done;
10174 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10175 -1, repo);
10176 done:
10177 free(ref);
10178 free(idstr);
10179 free(refname);
10180 return err;
10183 __dead static void
10184 usage_cherrypick(void)
10186 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10187 getprogname());
10188 exit(1);
10191 static const struct got_error *
10192 cmd_cherrypick(int argc, char *argv[])
10194 const struct got_error *error = NULL;
10195 struct got_worktree *worktree = NULL;
10196 struct got_repository *repo = NULL;
10197 char *cwd = NULL, *commit_id_str = NULL;
10198 struct got_object_id *commit_id = NULL;
10199 struct got_commit_object *commit = NULL;
10200 struct got_object_qid *pid;
10201 int ch, list_refs = 0, remove_refs = 0;
10202 struct got_update_progress_arg upa;
10203 int *pack_fds = NULL;
10205 #ifndef PROFILE
10206 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10207 "unveil", NULL) == -1)
10208 err(1, "pledge");
10209 #endif
10211 while ((ch = getopt(argc, argv, "lX")) != -1) {
10212 switch (ch) {
10213 case 'l':
10214 list_refs = 1;
10215 break;
10216 case 'X':
10217 remove_refs = 1;
10218 break;
10219 default:
10220 usage_cherrypick();
10221 /* NOTREACHED */
10225 argc -= optind;
10226 argv += optind;
10228 if (list_refs || remove_refs) {
10229 if (argc != 0 && argc != 1)
10230 usage_cherrypick();
10231 } else if (argc != 1)
10232 usage_cherrypick();
10233 if (list_refs && remove_refs)
10234 option_conflict('l', 'X');
10236 cwd = getcwd(NULL, 0);
10237 if (cwd == NULL) {
10238 error = got_error_from_errno("getcwd");
10239 goto done;
10242 error = got_repo_pack_fds_open(&pack_fds);
10243 if (error != NULL)
10244 goto done;
10246 error = got_worktree_open(&worktree, cwd);
10247 if (error) {
10248 if (list_refs || remove_refs) {
10249 if (error->code != GOT_ERR_NOT_WORKTREE)
10250 goto done;
10251 } else {
10252 if (error->code == GOT_ERR_NOT_WORKTREE)
10253 error = wrap_not_worktree_error(error,
10254 "cherrypick", cwd);
10255 goto done;
10259 error = got_repo_open(&repo,
10260 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10261 NULL, pack_fds);
10262 if (error != NULL)
10263 goto done;
10265 error = apply_unveil(got_repo_get_path(repo), 0,
10266 worktree ? got_worktree_get_root_path(worktree) : NULL);
10267 if (error)
10268 goto done;
10270 if (list_refs || remove_refs) {
10271 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10272 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10273 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10274 goto done;
10277 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10278 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10279 if (error)
10280 goto done;
10281 error = got_object_id_str(&commit_id_str, commit_id);
10282 if (error)
10283 goto done;
10285 error = got_object_open_as_commit(&commit, repo, commit_id);
10286 if (error)
10287 goto done;
10288 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10289 memset(&upa, 0, sizeof(upa));
10290 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10291 commit_id, repo, update_progress, &upa, check_cancelled,
10292 NULL);
10293 if (error != NULL)
10294 goto done;
10296 if (upa.did_something) {
10297 error = logmsg_ref(commit_id,
10298 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10299 if (error)
10300 goto done;
10301 printf("Merged commit %s\n", commit_id_str);
10303 print_merge_progress_stats(&upa);
10304 done:
10305 free(cwd);
10306 if (commit)
10307 got_object_commit_close(commit);
10308 free(commit_id_str);
10309 if (worktree)
10310 got_worktree_close(worktree);
10311 if (repo) {
10312 const struct got_error *close_err = got_repo_close(repo);
10313 if (error == NULL)
10314 error = close_err;
10316 if (pack_fds) {
10317 const struct got_error *pack_err =
10318 got_repo_pack_fds_close(pack_fds);
10319 if (error == NULL)
10320 error = pack_err;
10323 return error;
10326 __dead static void
10327 usage_backout(void)
10329 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10330 exit(1);
10333 static const struct got_error *
10334 cmd_backout(int argc, char *argv[])
10336 const struct got_error *error = NULL;
10337 struct got_worktree *worktree = NULL;
10338 struct got_repository *repo = NULL;
10339 char *cwd = NULL, *commit_id_str = NULL;
10340 struct got_object_id *commit_id = NULL;
10341 struct got_commit_object *commit = NULL;
10342 struct got_object_qid *pid;
10343 int ch, list_refs = 0, remove_refs = 0;
10344 struct got_update_progress_arg upa;
10345 int *pack_fds = NULL;
10347 #ifndef PROFILE
10348 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10349 "unveil", NULL) == -1)
10350 err(1, "pledge");
10351 #endif
10353 while ((ch = getopt(argc, argv, "lX")) != -1) {
10354 switch (ch) {
10355 case 'l':
10356 list_refs = 1;
10357 break;
10358 case 'X':
10359 remove_refs = 1;
10360 break;
10361 default:
10362 usage_backout();
10363 /* NOTREACHED */
10367 argc -= optind;
10368 argv += optind;
10370 if (list_refs || remove_refs) {
10371 if (argc != 0 && argc != 1)
10372 usage_backout();
10373 } else if (argc != 1)
10374 usage_backout();
10375 if (list_refs && remove_refs)
10376 option_conflict('l', 'X');
10378 cwd = getcwd(NULL, 0);
10379 if (cwd == NULL) {
10380 error = got_error_from_errno("getcwd");
10381 goto done;
10384 error = got_repo_pack_fds_open(&pack_fds);
10385 if (error != NULL)
10386 goto done;
10388 error = got_worktree_open(&worktree, cwd);
10389 if (error) {
10390 if (list_refs || remove_refs) {
10391 if (error->code != GOT_ERR_NOT_WORKTREE)
10392 goto done;
10393 } else {
10394 if (error->code == GOT_ERR_NOT_WORKTREE)
10395 error = wrap_not_worktree_error(error,
10396 "backout", cwd);
10397 goto done;
10401 error = got_repo_open(&repo,
10402 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10403 NULL, pack_fds);
10404 if (error != NULL)
10405 goto done;
10407 error = apply_unveil(got_repo_get_path(repo), 0,
10408 worktree ? got_worktree_get_root_path(worktree) : NULL);
10409 if (error)
10410 goto done;
10412 if (list_refs || remove_refs) {
10413 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10414 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10415 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10416 goto done;
10419 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10420 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10421 if (error)
10422 goto done;
10423 error = got_object_id_str(&commit_id_str, commit_id);
10424 if (error)
10425 goto done;
10427 error = got_object_open_as_commit(&commit, repo, commit_id);
10428 if (error)
10429 goto done;
10430 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10431 if (pid == NULL) {
10432 error = got_error(GOT_ERR_ROOT_COMMIT);
10433 goto done;
10436 memset(&upa, 0, sizeof(upa));
10437 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10438 repo, update_progress, &upa, check_cancelled, NULL);
10439 if (error != NULL)
10440 goto done;
10442 if (upa.did_something) {
10443 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10444 worktree, repo);
10445 if (error)
10446 goto done;
10447 printf("Backed out commit %s\n", commit_id_str);
10449 print_merge_progress_stats(&upa);
10450 done:
10451 free(cwd);
10452 if (commit)
10453 got_object_commit_close(commit);
10454 free(commit_id_str);
10455 if (worktree)
10456 got_worktree_close(worktree);
10457 if (repo) {
10458 const struct got_error *close_err = got_repo_close(repo);
10459 if (error == NULL)
10460 error = close_err;
10462 if (pack_fds) {
10463 const struct got_error *pack_err =
10464 got_repo_pack_fds_close(pack_fds);
10465 if (error == NULL)
10466 error = pack_err;
10468 return error;
10471 __dead static void
10472 usage_rebase(void)
10474 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10475 exit(1);
10478 static void
10479 trim_logmsg(char *logmsg, int limit)
10481 char *nl;
10482 size_t len;
10484 len = strlen(logmsg);
10485 if (len > limit)
10486 len = limit;
10487 logmsg[len] = '\0';
10488 nl = strchr(logmsg, '\n');
10489 if (nl)
10490 *nl = '\0';
10493 static const struct got_error *
10494 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10496 const struct got_error *err;
10497 char *logmsg0 = NULL;
10498 const char *s;
10500 err = got_object_commit_get_logmsg(&logmsg0, commit);
10501 if (err)
10502 return err;
10504 s = logmsg0;
10505 while (isspace((unsigned char)s[0]))
10506 s++;
10508 *logmsg = strdup(s);
10509 if (*logmsg == NULL) {
10510 err = got_error_from_errno("strdup");
10511 goto done;
10514 trim_logmsg(*logmsg, limit);
10515 done:
10516 free(logmsg0);
10517 return err;
10520 static const struct got_error *
10521 show_rebase_merge_conflict(struct got_object_id *id,
10522 struct got_repository *repo)
10524 const struct got_error *err;
10525 struct got_commit_object *commit = NULL;
10526 char *id_str = NULL, *logmsg = NULL;
10528 err = got_object_open_as_commit(&commit, repo, id);
10529 if (err)
10530 return err;
10532 err = got_object_id_str(&id_str, id);
10533 if (err)
10534 goto done;
10536 id_str[12] = '\0';
10538 err = get_short_logmsg(&logmsg, 42, commit);
10539 if (err)
10540 goto done;
10542 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10543 done:
10544 free(id_str);
10545 got_object_commit_close(commit);
10546 free(logmsg);
10547 return err;
10550 static const struct got_error *
10551 show_rebase_progress(struct got_commit_object *commit,
10552 struct got_object_id *old_id, struct got_object_id *new_id)
10554 const struct got_error *err;
10555 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10557 err = got_object_id_str(&old_id_str, old_id);
10558 if (err)
10559 goto done;
10561 if (new_id) {
10562 err = got_object_id_str(&new_id_str, new_id);
10563 if (err)
10564 goto done;
10567 old_id_str[12] = '\0';
10568 if (new_id_str)
10569 new_id_str[12] = '\0';
10571 err = get_short_logmsg(&logmsg, 42, commit);
10572 if (err)
10573 goto done;
10575 printf("%s -> %s: %s\n", old_id_str,
10576 new_id_str ? new_id_str : "no-op change", logmsg);
10577 done:
10578 free(old_id_str);
10579 free(new_id_str);
10580 free(logmsg);
10581 return err;
10584 static const struct got_error *
10585 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10586 struct got_reference *branch, struct got_reference *tmp_branch,
10587 struct got_repository *repo, int create_backup)
10589 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10590 return got_worktree_rebase_complete(worktree, fileindex,
10591 tmp_branch, branch, repo, create_backup);
10594 static const struct got_error *
10595 rebase_commit(struct got_pathlist_head *merged_paths,
10596 struct got_worktree *worktree, struct got_fileindex *fileindex,
10597 struct got_reference *tmp_branch, const char *committer,
10598 struct got_object_id *commit_id, int allow_conflict,
10599 struct got_repository *repo)
10601 const struct got_error *error;
10602 struct got_commit_object *commit;
10603 struct got_object_id *new_commit_id;
10605 error = got_object_open_as_commit(&commit, repo, commit_id);
10606 if (error)
10607 return error;
10609 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10610 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10611 allow_conflict, repo);
10612 if (error) {
10613 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10614 goto done;
10615 error = show_rebase_progress(commit, commit_id, NULL);
10616 } else {
10617 error = show_rebase_progress(commit, commit_id, new_commit_id);
10618 free(new_commit_id);
10620 done:
10621 got_object_commit_close(commit);
10622 return error;
10625 struct check_path_prefix_arg {
10626 const char *path_prefix;
10627 size_t len;
10628 int errcode;
10631 static const struct got_error *
10632 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10633 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10634 struct got_object_id *id1, struct got_object_id *id2,
10635 const char *path1, const char *path2,
10636 mode_t mode1, mode_t mode2, struct got_repository *repo)
10638 struct check_path_prefix_arg *a = arg;
10640 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10641 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10642 return got_error(a->errcode);
10644 return NULL;
10647 static const struct got_error *
10648 check_path_prefix(struct got_object_id *parent_id,
10649 struct got_object_id *commit_id, const char *path_prefix,
10650 int errcode, struct got_repository *repo)
10652 const struct got_error *err;
10653 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10654 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10655 struct check_path_prefix_arg cpp_arg;
10657 if (got_path_is_root_dir(path_prefix))
10658 return NULL;
10660 err = got_object_open_as_commit(&commit, repo, commit_id);
10661 if (err)
10662 goto done;
10664 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10665 if (err)
10666 goto done;
10668 err = got_object_open_as_tree(&tree1, repo,
10669 got_object_commit_get_tree_id(parent_commit));
10670 if (err)
10671 goto done;
10673 err = got_object_open_as_tree(&tree2, repo,
10674 got_object_commit_get_tree_id(commit));
10675 if (err)
10676 goto done;
10678 cpp_arg.path_prefix = path_prefix;
10679 while (cpp_arg.path_prefix[0] == '/')
10680 cpp_arg.path_prefix++;
10681 cpp_arg.len = strlen(cpp_arg.path_prefix);
10682 cpp_arg.errcode = errcode;
10683 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10684 check_path_prefix_in_diff, &cpp_arg, 0);
10685 done:
10686 if (tree1)
10687 got_object_tree_close(tree1);
10688 if (tree2)
10689 got_object_tree_close(tree2);
10690 if (commit)
10691 got_object_commit_close(commit);
10692 if (parent_commit)
10693 got_object_commit_close(parent_commit);
10694 return err;
10697 static const struct got_error *
10698 collect_commits(struct got_object_id_queue *commits,
10699 struct got_object_id *initial_commit_id,
10700 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10701 const char *path_prefix, int path_prefix_errcode,
10702 struct got_repository *repo)
10704 const struct got_error *err = NULL;
10705 struct got_commit_graph *graph = NULL;
10706 struct got_object_id parent_id, commit_id;
10707 struct got_object_qid *qid;
10709 err = got_commit_graph_open(&graph, "/", 1);
10710 if (err)
10711 return err;
10713 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10714 check_cancelled, NULL);
10715 if (err)
10716 goto done;
10718 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10719 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10720 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10721 check_cancelled, NULL);
10722 if (err) {
10723 if (err->code == GOT_ERR_ITER_COMPLETED) {
10724 err = got_error_msg(GOT_ERR_ANCESTRY,
10725 "ran out of commits to rebase before "
10726 "youngest common ancestor commit has "
10727 "been reached?!?");
10729 goto done;
10730 } else {
10731 err = check_path_prefix(&parent_id, &commit_id,
10732 path_prefix, path_prefix_errcode, repo);
10733 if (err)
10734 goto done;
10736 err = got_object_qid_alloc(&qid, &commit_id);
10737 if (err)
10738 goto done;
10739 STAILQ_INSERT_HEAD(commits, qid, entry);
10741 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10744 done:
10745 got_commit_graph_close(graph);
10746 return err;
10749 static const struct got_error *
10750 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10752 const struct got_error *err = NULL;
10753 time_t committer_time;
10754 struct tm tm;
10755 char datebuf[11]; /* YYYY-MM-DD + NUL */
10756 char *author0 = NULL, *author, *smallerthan;
10757 char *logmsg0 = NULL, *logmsg, *newline;
10759 committer_time = got_object_commit_get_committer_time(commit);
10760 if (gmtime_r(&committer_time, &tm) == NULL)
10761 return got_error_from_errno("gmtime_r");
10762 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10763 return got_error(GOT_ERR_NO_SPACE);
10765 author0 = strdup(got_object_commit_get_author(commit));
10766 if (author0 == NULL)
10767 return got_error_from_errno("strdup");
10768 author = author0;
10769 smallerthan = strchr(author, '<');
10770 if (smallerthan && smallerthan[1] != '\0')
10771 author = smallerthan + 1;
10772 author[strcspn(author, "@>")] = '\0';
10774 err = got_object_commit_get_logmsg(&logmsg0, commit);
10775 if (err)
10776 goto done;
10777 logmsg = logmsg0;
10778 while (*logmsg == '\n')
10779 logmsg++;
10780 newline = strchr(logmsg, '\n');
10781 if (newline)
10782 *newline = '\0';
10784 if (asprintf(brief_str, "%s %s %s",
10785 datebuf, author, logmsg) == -1)
10786 err = got_error_from_errno("asprintf");
10787 done:
10788 free(author0);
10789 free(logmsg0);
10790 return err;
10793 static const struct got_error *
10794 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10795 struct got_repository *repo)
10797 const struct got_error *err;
10798 char *id_str;
10800 err = got_object_id_str(&id_str, id);
10801 if (err)
10802 return err;
10804 err = got_ref_delete(ref, repo);
10805 if (err)
10806 goto done;
10808 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10809 done:
10810 free(id_str);
10811 return err;
10814 static const struct got_error *
10815 print_backup_ref(const char *branch_name, const char *new_id_str,
10816 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10817 struct got_reflist_object_id_map *refs_idmap,
10818 struct got_repository *repo)
10820 const struct got_error *err = NULL;
10821 struct got_reflist_head *refs;
10822 char *refs_str = NULL;
10823 struct got_object_id *new_commit_id = NULL;
10824 struct got_commit_object *new_commit = NULL;
10825 char *new_commit_brief_str = NULL;
10826 struct got_object_id *yca_id = NULL;
10827 struct got_commit_object *yca_commit = NULL;
10828 char *yca_id_str = NULL, *yca_brief_str = NULL;
10829 char *custom_refs_str;
10831 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10832 return got_error_from_errno("asprintf");
10834 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10835 0, 0, refs_idmap, custom_refs_str, NULL);
10836 if (err)
10837 goto done;
10839 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10840 if (err)
10841 goto done;
10843 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10844 if (refs) {
10845 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10846 if (err)
10847 goto done;
10850 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10851 if (err)
10852 goto done;
10854 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10855 if (err)
10856 goto done;
10858 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10859 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10860 if (err)
10861 goto done;
10863 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10864 refs_str ? " (" : "", refs_str ? refs_str : "",
10865 refs_str ? ")" : "", new_commit_brief_str);
10866 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10867 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10868 free(refs_str);
10869 refs_str = NULL;
10871 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10872 if (err)
10873 goto done;
10875 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10876 if (err)
10877 goto done;
10879 err = got_object_id_str(&yca_id_str, yca_id);
10880 if (err)
10881 goto done;
10883 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10884 if (refs) {
10885 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10886 if (err)
10887 goto done;
10889 printf("history forked at %s%s%s%s\n %s\n",
10890 yca_id_str,
10891 refs_str ? " (" : "", refs_str ? refs_str : "",
10892 refs_str ? ")" : "", yca_brief_str);
10894 done:
10895 free(custom_refs_str);
10896 free(new_commit_id);
10897 free(refs_str);
10898 free(yca_id);
10899 free(yca_id_str);
10900 free(yca_brief_str);
10901 if (new_commit)
10902 got_object_commit_close(new_commit);
10903 if (yca_commit)
10904 got_object_commit_close(yca_commit);
10906 return err;
10909 static const struct got_error *
10910 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10911 struct got_repository *repo)
10913 const struct got_error *err;
10914 struct got_reflist_head refs;
10915 struct got_reflist_entry *re;
10916 char *uuidstr = NULL;
10917 static char msg[160];
10919 TAILQ_INIT(&refs);
10921 err = got_worktree_get_uuid(&uuidstr, worktree);
10922 if (err)
10923 goto done;
10925 err = got_ref_list(&refs, repo, "refs/got/worktree",
10926 got_ref_cmp_by_name, repo);
10927 if (err)
10928 goto done;
10930 TAILQ_FOREACH(re, &refs, entry) {
10931 const char *cmd, *refname, *type;
10933 refname = got_ref_get_name(re->ref);
10935 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10936 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10937 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10938 cmd = "cherrypick";
10939 type = "cherrypicked";
10940 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10941 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10942 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10943 cmd = "backout";
10944 type = "backed-out";
10945 } else
10946 continue;
10948 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10949 continue;
10951 snprintf(msg, sizeof(msg),
10952 "work tree has references created by %s commits which "
10953 "must be removed with 'got %s -X' before running the %s "
10954 "command", type, cmd, caller);
10955 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10956 goto done;
10959 done:
10960 free(uuidstr);
10961 got_ref_list_free(&refs);
10962 return err;
10965 static const struct got_error *
10966 process_backup_refs(const char *backup_ref_prefix,
10967 const char *wanted_branch_name,
10968 int delete, struct got_repository *repo)
10970 const struct got_error *err;
10971 struct got_reflist_head refs, backup_refs;
10972 struct got_reflist_entry *re;
10973 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10974 struct got_object_id *old_commit_id = NULL;
10975 char *branch_name = NULL;
10976 struct got_commit_object *old_commit = NULL;
10977 struct got_reflist_object_id_map *refs_idmap = NULL;
10978 int wanted_branch_found = 0;
10980 TAILQ_INIT(&refs);
10981 TAILQ_INIT(&backup_refs);
10983 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10984 if (err)
10985 return err;
10987 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10988 if (err)
10989 goto done;
10991 if (wanted_branch_name) {
10992 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10993 wanted_branch_name += 11;
10996 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10997 got_ref_cmp_by_commit_timestamp_descending, repo);
10998 if (err)
10999 goto done;
11001 TAILQ_FOREACH(re, &backup_refs, entry) {
11002 const char *refname = got_ref_get_name(re->ref);
11003 char *slash;
11005 err = check_cancelled(NULL);
11006 if (err)
11007 break;
11009 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11010 if (err)
11011 break;
11013 err = got_object_open_as_commit(&old_commit, repo,
11014 old_commit_id);
11015 if (err)
11016 break;
11018 if (strncmp(backup_ref_prefix, refname,
11019 backup_ref_prefix_len) == 0)
11020 refname += backup_ref_prefix_len;
11022 while (refname[0] == '/')
11023 refname++;
11025 branch_name = strdup(refname);
11026 if (branch_name == NULL) {
11027 err = got_error_from_errno("strdup");
11028 break;
11030 slash = strrchr(branch_name, '/');
11031 if (slash) {
11032 *slash = '\0';
11033 refname += strlen(branch_name) + 1;
11036 if (wanted_branch_name == NULL ||
11037 strcmp(wanted_branch_name, branch_name) == 0) {
11038 wanted_branch_found = 1;
11039 if (delete) {
11040 err = delete_backup_ref(re->ref,
11041 old_commit_id, repo);
11042 } else {
11043 err = print_backup_ref(branch_name, refname,
11044 old_commit_id, old_commit, refs_idmap,
11045 repo);
11047 if (err)
11048 break;
11051 free(old_commit_id);
11052 old_commit_id = NULL;
11053 free(branch_name);
11054 branch_name = NULL;
11055 got_object_commit_close(old_commit);
11056 old_commit = NULL;
11059 if (wanted_branch_name && !wanted_branch_found) {
11060 err = got_error_fmt(GOT_ERR_NOT_REF,
11061 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11063 done:
11064 if (refs_idmap)
11065 got_reflist_object_id_map_free(refs_idmap);
11066 got_ref_list_free(&refs);
11067 got_ref_list_free(&backup_refs);
11068 free(old_commit_id);
11069 free(branch_name);
11070 if (old_commit)
11071 got_object_commit_close(old_commit);
11072 return err;
11075 static const struct got_error *
11076 abort_progress(void *arg, unsigned char status, const char *path)
11079 * Unversioned files should not clutter progress output when
11080 * an operation is aborted.
11082 if (status == GOT_STATUS_UNVERSIONED)
11083 return NULL;
11085 return update_progress(arg, status, path);
11088 static const struct got_error *
11089 cmd_rebase(int argc, char *argv[])
11091 const struct got_error *error = NULL;
11092 struct got_worktree *worktree = NULL;
11093 struct got_repository *repo = NULL;
11094 struct got_fileindex *fileindex = NULL;
11095 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11096 struct got_reference *branch = NULL;
11097 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11098 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11099 struct got_object_id *resume_commit_id = NULL;
11100 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11101 struct got_object_id *head_commit_id = NULL;
11102 struct got_reference *head_ref = NULL;
11103 struct got_commit_object *commit = NULL;
11104 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11105 int histedit_in_progress = 0, merge_in_progress = 0;
11106 int create_backup = 1, list_backups = 0, delete_backups = 0;
11107 int allow_conflict = 0;
11108 struct got_object_id_queue commits;
11109 struct got_pathlist_head merged_paths;
11110 const struct got_object_id_queue *parent_ids;
11111 struct got_object_qid *qid, *pid;
11112 struct got_update_progress_arg upa;
11113 int *pack_fds = NULL;
11115 STAILQ_INIT(&commits);
11116 TAILQ_INIT(&merged_paths);
11117 memset(&upa, 0, sizeof(upa));
11119 #ifndef PROFILE
11120 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11121 "unveil", NULL) == -1)
11122 err(1, "pledge");
11123 #endif
11125 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11126 switch (ch) {
11127 case 'a':
11128 abort_rebase = 1;
11129 break;
11130 case 'C':
11131 allow_conflict = 1;
11132 break;
11133 case 'c':
11134 continue_rebase = 1;
11135 break;
11136 case 'l':
11137 list_backups = 1;
11138 break;
11139 case 'X':
11140 delete_backups = 1;
11141 break;
11142 default:
11143 usage_rebase();
11144 /* NOTREACHED */
11148 argc -= optind;
11149 argv += optind;
11151 if (list_backups) {
11152 if (abort_rebase)
11153 option_conflict('l', 'a');
11154 if (allow_conflict)
11155 option_conflict('l', 'C');
11156 if (continue_rebase)
11157 option_conflict('l', 'c');
11158 if (delete_backups)
11159 option_conflict('l', 'X');
11160 if (argc != 0 && argc != 1)
11161 usage_rebase();
11162 } else if (delete_backups) {
11163 if (abort_rebase)
11164 option_conflict('X', 'a');
11165 if (allow_conflict)
11166 option_conflict('X', 'C');
11167 if (continue_rebase)
11168 option_conflict('X', 'c');
11169 if (list_backups)
11170 option_conflict('l', 'X');
11171 if (argc != 0 && argc != 1)
11172 usage_rebase();
11173 } else if (allow_conflict) {
11174 if (abort_rebase)
11175 option_conflict('C', 'a');
11176 if (!continue_rebase)
11177 errx(1, "-C option requires -c");
11178 } else {
11179 if (abort_rebase && continue_rebase)
11180 usage_rebase();
11181 else if (abort_rebase || continue_rebase) {
11182 if (argc != 0)
11183 usage_rebase();
11184 } else if (argc != 1)
11185 usage_rebase();
11188 cwd = getcwd(NULL, 0);
11189 if (cwd == NULL) {
11190 error = got_error_from_errno("getcwd");
11191 goto done;
11194 error = got_repo_pack_fds_open(&pack_fds);
11195 if (error != NULL)
11196 goto done;
11198 error = got_worktree_open(&worktree, cwd);
11199 if (error) {
11200 if (list_backups || delete_backups) {
11201 if (error->code != GOT_ERR_NOT_WORKTREE)
11202 goto done;
11203 } else {
11204 if (error->code == GOT_ERR_NOT_WORKTREE)
11205 error = wrap_not_worktree_error(error,
11206 "rebase", cwd);
11207 goto done;
11211 error = get_gitconfig_path(&gitconfig_path);
11212 if (error)
11213 goto done;
11214 error = got_repo_open(&repo,
11215 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11216 gitconfig_path, pack_fds);
11217 if (error != NULL)
11218 goto done;
11220 if (worktree != NULL && !list_backups && !delete_backups) {
11221 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11222 if (error)
11223 goto done;
11226 error = get_author(&committer, repo, worktree);
11227 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11228 goto done;
11230 error = apply_unveil(got_repo_get_path(repo), 0,
11231 worktree ? got_worktree_get_root_path(worktree) : NULL);
11232 if (error)
11233 goto done;
11235 if (list_backups || delete_backups) {
11236 error = process_backup_refs(
11237 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11238 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11239 goto done; /* nothing else to do */
11242 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11243 worktree);
11244 if (error)
11245 goto done;
11246 if (histedit_in_progress) {
11247 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11248 goto done;
11251 error = got_worktree_merge_in_progress(&merge_in_progress,
11252 worktree, repo);
11253 if (error)
11254 goto done;
11255 if (merge_in_progress) {
11256 error = got_error(GOT_ERR_MERGE_BUSY);
11257 goto done;
11260 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11261 if (error)
11262 goto done;
11264 if (abort_rebase) {
11265 if (!rebase_in_progress) {
11266 error = got_error(GOT_ERR_NOT_REBASING);
11267 goto done;
11269 error = got_worktree_rebase_continue(&resume_commit_id,
11270 &new_base_branch, &tmp_branch, &branch, &fileindex,
11271 worktree, repo);
11272 if (error)
11273 goto done;
11274 printf("Switching work tree to %s\n",
11275 got_ref_get_symref_target(new_base_branch));
11276 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11277 new_base_branch, abort_progress, &upa);
11278 if (error)
11279 goto done;
11280 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11281 print_merge_progress_stats(&upa);
11282 goto done; /* nothing else to do */
11285 if (continue_rebase) {
11286 if (!rebase_in_progress) {
11287 error = got_error(GOT_ERR_NOT_REBASING);
11288 goto done;
11290 error = got_worktree_rebase_continue(&resume_commit_id,
11291 &new_base_branch, &tmp_branch, &branch, &fileindex,
11292 worktree, repo);
11293 if (error)
11294 goto done;
11296 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11297 committer, resume_commit_id, allow_conflict, repo);
11298 if (error)
11299 goto done;
11301 yca_id = got_object_id_dup(resume_commit_id);
11302 if (yca_id == NULL) {
11303 error = got_error_from_errno("got_object_id_dup");
11304 goto done;
11306 } else {
11307 error = got_ref_open(&branch, repo, argv[0], 0);
11308 if (error != NULL)
11309 goto done;
11310 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11311 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11312 "will not rebase a branch which lives outside "
11313 "the \"refs/heads/\" reference namespace");
11314 goto done;
11318 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11319 if (error)
11320 goto done;
11322 if (!continue_rebase) {
11323 struct got_object_id *base_commit_id;
11325 error = got_ref_open(&head_ref, repo,
11326 got_worktree_get_head_ref_name(worktree), 0);
11327 if (error)
11328 goto done;
11329 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11330 if (error)
11331 goto done;
11332 base_commit_id = got_worktree_get_base_commit_id(worktree);
11333 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11334 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11335 goto done;
11338 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11339 base_commit_id, branch_head_commit_id, 1, repo,
11340 check_cancelled, NULL);
11341 if (error) {
11342 if (error->code == GOT_ERR_ANCESTRY) {
11343 error = got_error_msg(GOT_ERR_ANCESTRY,
11344 "specified branch shares no common "
11345 "ancestry with work tree's branch");
11347 goto done;
11350 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11351 struct got_pathlist_head paths;
11352 printf("%s is already based on %s\n",
11353 got_ref_get_name(branch),
11354 got_worktree_get_head_ref_name(worktree));
11355 error = switch_head_ref(branch, branch_head_commit_id,
11356 worktree, repo);
11357 if (error)
11358 goto done;
11359 error = got_worktree_set_base_commit_id(worktree, repo,
11360 branch_head_commit_id);
11361 if (error)
11362 goto done;
11363 TAILQ_INIT(&paths);
11364 error = got_pathlist_append(&paths, "", NULL);
11365 if (error)
11366 goto done;
11367 error = got_worktree_checkout_files(worktree,
11368 &paths, repo, update_progress, &upa,
11369 check_cancelled, NULL);
11370 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11371 if (error)
11372 goto done;
11373 if (upa.did_something) {
11374 char *id_str;
11375 error = got_object_id_str(&id_str,
11376 branch_head_commit_id);
11377 if (error)
11378 goto done;
11379 printf("Updated to %s: %s\n",
11380 got_worktree_get_head_ref_name(worktree),
11381 id_str);
11382 free(id_str);
11383 } else
11384 printf("Already up-to-date\n");
11385 print_update_progress_stats(&upa);
11386 goto done;
11390 commit_id = branch_head_commit_id;
11391 error = got_object_open_as_commit(&commit, repo, commit_id);
11392 if (error)
11393 goto done;
11395 parent_ids = got_object_commit_get_parent_ids(commit);
11396 pid = STAILQ_FIRST(parent_ids);
11397 if (pid) {
11398 error = collect_commits(&commits, commit_id, &pid->id,
11399 yca_id, got_worktree_get_path_prefix(worktree),
11400 GOT_ERR_REBASE_PATH, repo);
11401 if (error)
11402 goto done;
11405 got_object_commit_close(commit);
11406 commit = NULL;
11408 if (!continue_rebase) {
11409 error = got_worktree_rebase_prepare(&new_base_branch,
11410 &tmp_branch, &fileindex, worktree, branch, repo);
11411 if (error)
11412 goto done;
11415 if (STAILQ_EMPTY(&commits)) {
11416 if (continue_rebase) {
11417 error = rebase_complete(worktree, fileindex,
11418 branch, tmp_branch, repo, create_backup);
11419 goto done;
11420 } else {
11421 /* Fast-forward the reference of the branch. */
11422 struct got_object_id *new_head_commit_id;
11423 char *id_str;
11424 error = got_ref_resolve(&new_head_commit_id, repo,
11425 new_base_branch);
11426 if (error)
11427 goto done;
11428 error = got_object_id_str(&id_str, new_head_commit_id);
11429 if (error)
11430 goto done;
11431 printf("Forwarding %s to commit %s\n",
11432 got_ref_get_name(branch), id_str);
11433 free(id_str);
11434 error = got_ref_change_ref(branch,
11435 new_head_commit_id);
11436 if (error)
11437 goto done;
11438 /* No backup needed since objects did not change. */
11439 create_backup = 0;
11443 pid = NULL;
11444 STAILQ_FOREACH(qid, &commits, entry) {
11446 commit_id = &qid->id;
11447 parent_id = pid ? &pid->id : yca_id;
11448 pid = qid;
11450 memset(&upa, 0, sizeof(upa));
11451 error = got_worktree_rebase_merge_files(&merged_paths,
11452 worktree, fileindex, parent_id, commit_id, repo,
11453 update_progress, &upa, check_cancelled, NULL);
11454 if (error)
11455 goto done;
11457 print_merge_progress_stats(&upa);
11458 if (upa.conflicts > 0 || upa.missing > 0 ||
11459 upa.not_deleted > 0 || upa.unversioned > 0) {
11460 if (upa.conflicts > 0) {
11461 error = show_rebase_merge_conflict(&qid->id,
11462 repo);
11463 if (error)
11464 goto done;
11466 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11467 break;
11470 error = rebase_commit(&merged_paths, worktree, fileindex,
11471 tmp_branch, committer, commit_id, 0, repo);
11472 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11473 if (error)
11474 goto done;
11477 if (upa.conflicts > 0 || upa.missing > 0 ||
11478 upa.not_deleted > 0 || upa.unversioned > 0) {
11479 error = got_worktree_rebase_postpone(worktree, fileindex);
11480 if (error)
11481 goto done;
11482 if (upa.conflicts > 0 && upa.missing == 0 &&
11483 upa.not_deleted == 0 && upa.unversioned == 0) {
11484 error = got_error_msg(GOT_ERR_CONFLICTS,
11485 "conflicts must be resolved before rebasing "
11486 "can continue");
11487 } else if (upa.conflicts > 0) {
11488 error = got_error_msg(GOT_ERR_CONFLICTS,
11489 "conflicts must be resolved before rebasing "
11490 "can continue; changes destined for some "
11491 "files were not yet merged and should be "
11492 "merged manually if required before the "
11493 "rebase operation is continued");
11494 } else {
11495 error = got_error_msg(GOT_ERR_CONFLICTS,
11496 "changes destined for some files were not "
11497 "yet merged and should be merged manually "
11498 "if required before the rebase operation "
11499 "is continued");
11501 } else
11502 error = rebase_complete(worktree, fileindex, branch,
11503 tmp_branch, repo, create_backup);
11504 done:
11505 free(cwd);
11506 free(committer);
11507 free(gitconfig_path);
11508 got_object_id_queue_free(&commits);
11509 free(branch_head_commit_id);
11510 free(resume_commit_id);
11511 free(head_commit_id);
11512 free(yca_id);
11513 if (commit)
11514 got_object_commit_close(commit);
11515 if (branch)
11516 got_ref_close(branch);
11517 if (new_base_branch)
11518 got_ref_close(new_base_branch);
11519 if (tmp_branch)
11520 got_ref_close(tmp_branch);
11521 if (head_ref)
11522 got_ref_close(head_ref);
11523 if (worktree)
11524 got_worktree_close(worktree);
11525 if (repo) {
11526 const struct got_error *close_err = got_repo_close(repo);
11527 if (error == NULL)
11528 error = close_err;
11530 if (pack_fds) {
11531 const struct got_error *pack_err =
11532 got_repo_pack_fds_close(pack_fds);
11533 if (error == NULL)
11534 error = pack_err;
11536 return error;
11539 __dead static void
11540 usage_histedit(void)
11542 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11543 "[branch]\n", getprogname());
11544 exit(1);
11547 #define GOT_HISTEDIT_PICK 'p'
11548 #define GOT_HISTEDIT_EDIT 'e'
11549 #define GOT_HISTEDIT_FOLD 'f'
11550 #define GOT_HISTEDIT_DROP 'd'
11551 #define GOT_HISTEDIT_MESG 'm'
11553 static const struct got_histedit_cmd {
11554 unsigned char code;
11555 const char *name;
11556 const char *desc;
11557 } got_histedit_cmds[] = {
11558 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11559 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11560 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11561 "be used" },
11562 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11563 { GOT_HISTEDIT_MESG, "mesg",
11564 "single-line log message for commit above (open editor if empty)" },
11567 struct got_histedit_list_entry {
11568 TAILQ_ENTRY(got_histedit_list_entry) entry;
11569 struct got_object_id *commit_id;
11570 const struct got_histedit_cmd *cmd;
11571 char *logmsg;
11573 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11575 static const struct got_error *
11576 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11577 FILE *f, struct got_repository *repo)
11579 const struct got_error *err = NULL;
11580 char *logmsg = NULL, *id_str = NULL;
11581 struct got_commit_object *commit = NULL;
11582 int n;
11584 err = got_object_open_as_commit(&commit, repo, commit_id);
11585 if (err)
11586 goto done;
11588 err = get_short_logmsg(&logmsg, 34, commit);
11589 if (err)
11590 goto done;
11592 err = got_object_id_str(&id_str, commit_id);
11593 if (err)
11594 goto done;
11596 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11597 if (n < 0)
11598 err = got_ferror(f, GOT_ERR_IO);
11599 done:
11600 if (commit)
11601 got_object_commit_close(commit);
11602 free(id_str);
11603 free(logmsg);
11604 return err;
11607 static const struct got_error *
11608 histedit_write_commit_list(struct got_object_id_queue *commits,
11609 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11610 int edit_only, struct got_repository *repo)
11612 const struct got_error *err = NULL;
11613 struct got_object_qid *qid;
11614 const char *histedit_cmd = NULL;
11616 if (STAILQ_EMPTY(commits))
11617 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11619 STAILQ_FOREACH(qid, commits, entry) {
11620 histedit_cmd = got_histedit_cmds[0].name;
11621 if (drop_only)
11622 histedit_cmd = "drop";
11623 else if (edit_only)
11624 histedit_cmd = "edit";
11625 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11626 histedit_cmd = "fold";
11627 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11628 if (err)
11629 break;
11630 if (edit_logmsg_only) {
11631 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11632 if (n < 0) {
11633 err = got_ferror(f, GOT_ERR_IO);
11634 break;
11639 return err;
11642 static const struct got_error *
11643 write_cmd_list(FILE *f, const char *branch_name,
11644 struct got_object_id_queue *commits)
11646 const struct got_error *err = NULL;
11647 size_t i;
11648 int n;
11649 char *id_str;
11650 struct got_object_qid *qid;
11652 qid = STAILQ_FIRST(commits);
11653 err = got_object_id_str(&id_str, &qid->id);
11654 if (err)
11655 return err;
11657 n = fprintf(f,
11658 "# Editing the history of branch '%s' starting at\n"
11659 "# commit %s\n"
11660 "# Commits will be processed in order from top to "
11661 "bottom of this file.\n", branch_name, id_str);
11662 if (n < 0) {
11663 err = got_ferror(f, GOT_ERR_IO);
11664 goto done;
11667 n = fprintf(f, "# Available histedit commands:\n");
11668 if (n < 0) {
11669 err = got_ferror(f, GOT_ERR_IO);
11670 goto done;
11673 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11674 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11675 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11676 cmd->desc);
11677 if (n < 0) {
11678 err = got_ferror(f, GOT_ERR_IO);
11679 break;
11682 done:
11683 free(id_str);
11684 return err;
11687 static const struct got_error *
11688 histedit_syntax_error(int lineno)
11690 static char msg[42];
11691 int ret;
11693 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11694 lineno);
11695 if (ret < 0 || (size_t)ret >= sizeof(msg))
11696 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11698 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11701 static const struct got_error *
11702 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11703 char *logmsg, struct got_repository *repo)
11705 const struct got_error *err;
11706 struct got_commit_object *folded_commit = NULL;
11707 char *id_str, *folded_logmsg = NULL;
11709 err = got_object_id_str(&id_str, hle->commit_id);
11710 if (err)
11711 return err;
11713 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11714 if (err)
11715 goto done;
11717 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11718 if (err)
11719 goto done;
11720 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11721 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11722 folded_logmsg) == -1) {
11723 err = got_error_from_errno("asprintf");
11725 done:
11726 if (folded_commit)
11727 got_object_commit_close(folded_commit);
11728 free(id_str);
11729 free(folded_logmsg);
11730 return err;
11733 static struct got_histedit_list_entry *
11734 get_folded_commits(struct got_histedit_list_entry *hle)
11736 struct got_histedit_list_entry *prev, *folded = NULL;
11738 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11739 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11740 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11741 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11742 folded = prev;
11743 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11746 return folded;
11749 static const struct got_error *
11750 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11751 struct got_repository *repo)
11753 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11754 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11755 const struct got_error *err = NULL;
11756 struct got_commit_object *commit = NULL;
11757 int logmsg_len;
11758 int fd = -1;
11759 struct got_histedit_list_entry *folded = NULL;
11761 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11762 if (err)
11763 return err;
11765 folded = get_folded_commits(hle);
11766 if (folded) {
11767 while (folded != hle) {
11768 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11769 folded = TAILQ_NEXT(folded, entry);
11770 continue;
11772 err = append_folded_commit_msg(&new_msg, folded,
11773 logmsg, repo);
11774 if (err)
11775 goto done;
11776 free(logmsg);
11777 logmsg = new_msg;
11778 folded = TAILQ_NEXT(folded, entry);
11782 err = got_object_id_str(&id_str, hle->commit_id);
11783 if (err)
11784 goto done;
11785 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11786 if (err)
11787 goto done;
11788 logmsg_len = asprintf(&new_msg,
11789 "%s\n# original log message of commit %s: %s",
11790 logmsg ? logmsg : "", id_str, orig_logmsg);
11791 if (logmsg_len == -1) {
11792 err = got_error_from_errno("asprintf");
11793 goto done;
11795 free(logmsg);
11796 logmsg = new_msg;
11798 err = got_object_id_str(&id_str, hle->commit_id);
11799 if (err)
11800 goto done;
11802 err = got_opentemp_named_fd(&logmsg_path, &fd,
11803 GOT_TMPDIR_STR "/got-logmsg", "");
11804 if (err)
11805 goto done;
11807 if (write(fd, logmsg, logmsg_len) == -1) {
11808 err = got_error_from_errno2("write", logmsg_path);
11809 goto done;
11811 if (close(fd) == -1) {
11812 err = got_error_from_errno2("close", logmsg_path);
11813 goto done;
11815 fd = -1;
11817 err = get_editor(&editor);
11818 if (err)
11819 goto done;
11821 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11822 logmsg_len, 0);
11823 if (err) {
11824 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11825 goto done;
11826 err = NULL;
11827 hle->logmsg = strdup(new_msg);
11828 if (hle->logmsg == NULL)
11829 err = got_error_from_errno("strdup");
11831 done:
11832 if (fd != -1 && close(fd) == -1 && err == NULL)
11833 err = got_error_from_errno2("close", logmsg_path);
11834 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11835 err = got_error_from_errno2("unlink", logmsg_path);
11836 free(logmsg_path);
11837 free(logmsg);
11838 free(orig_logmsg);
11839 free(editor);
11840 if (commit)
11841 got_object_commit_close(commit);
11842 return err;
11845 static const struct got_error *
11846 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11847 FILE *f, struct got_repository *repo)
11849 const struct got_error *err = NULL;
11850 char *line = NULL, *p, *end;
11851 size_t i, linesize = 0;
11852 ssize_t linelen;
11853 int lineno = 0, lastcmd = -1;
11854 const struct got_histedit_cmd *cmd;
11855 struct got_object_id *commit_id = NULL;
11856 struct got_histedit_list_entry *hle = NULL;
11858 for (;;) {
11859 linelen = getline(&line, &linesize, f);
11860 if (linelen == -1) {
11861 const struct got_error *getline_err;
11862 if (feof(f))
11863 break;
11864 getline_err = got_error_from_errno("getline");
11865 err = got_ferror(f, getline_err->code);
11866 break;
11868 lineno++;
11869 p = line;
11870 while (isspace((unsigned char)p[0]))
11871 p++;
11872 if (p[0] == '#' || p[0] == '\0')
11873 continue;
11874 cmd = NULL;
11875 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11876 cmd = &got_histedit_cmds[i];
11877 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11878 isspace((unsigned char)p[strlen(cmd->name)])) {
11879 p += strlen(cmd->name);
11880 break;
11882 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11883 p++;
11884 break;
11887 if (i == nitems(got_histedit_cmds)) {
11888 err = histedit_syntax_error(lineno);
11889 break;
11891 while (isspace((unsigned char)p[0]))
11892 p++;
11893 if (cmd->code == GOT_HISTEDIT_MESG) {
11894 if (lastcmd != GOT_HISTEDIT_PICK &&
11895 lastcmd != GOT_HISTEDIT_EDIT) {
11896 err = got_error(GOT_ERR_HISTEDIT_CMD);
11897 break;
11899 if (p[0] == '\0') {
11900 err = histedit_edit_logmsg(hle, repo);
11901 if (err)
11902 break;
11903 } else {
11904 hle->logmsg = strdup(p);
11905 if (hle->logmsg == NULL) {
11906 err = got_error_from_errno("strdup");
11907 break;
11910 lastcmd = cmd->code;
11911 continue;
11912 } else {
11913 end = p;
11914 while (end[0] && !isspace((unsigned char)end[0]))
11915 end++;
11916 *end = '\0';
11918 err = got_object_resolve_id_str(&commit_id, repo, p);
11919 if (err) {
11920 /* override error code */
11921 err = histedit_syntax_error(lineno);
11922 break;
11925 hle = malloc(sizeof(*hle));
11926 if (hle == NULL) {
11927 err = got_error_from_errno("malloc");
11928 break;
11930 hle->cmd = cmd;
11931 hle->commit_id = commit_id;
11932 hle->logmsg = NULL;
11933 commit_id = NULL;
11934 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11935 lastcmd = cmd->code;
11938 free(line);
11939 free(commit_id);
11940 return err;
11943 static const struct got_error *
11944 histedit_check_script(struct got_histedit_list *histedit_cmds,
11945 struct got_object_id_queue *commits, struct got_repository *repo)
11947 const struct got_error *err = NULL;
11948 struct got_object_qid *qid;
11949 struct got_histedit_list_entry *hle;
11950 static char msg[92];
11951 char *id_str;
11953 if (TAILQ_EMPTY(histedit_cmds))
11954 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11955 "histedit script contains no commands");
11956 if (STAILQ_EMPTY(commits))
11957 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11959 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11960 struct got_histedit_list_entry *hle2;
11961 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11962 if (hle == hle2)
11963 continue;
11964 if (got_object_id_cmp(hle->commit_id,
11965 hle2->commit_id) != 0)
11966 continue;
11967 err = got_object_id_str(&id_str, hle->commit_id);
11968 if (err)
11969 return err;
11970 snprintf(msg, sizeof(msg), "commit %s is listed "
11971 "more than once in histedit script", id_str);
11972 free(id_str);
11973 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11977 STAILQ_FOREACH(qid, commits, entry) {
11978 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11979 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11980 break;
11982 if (hle == NULL) {
11983 err = got_object_id_str(&id_str, &qid->id);
11984 if (err)
11985 return err;
11986 snprintf(msg, sizeof(msg),
11987 "commit %s missing from histedit script", id_str);
11988 free(id_str);
11989 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11993 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11994 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11995 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11996 "last commit in histedit script cannot be folded");
11998 return NULL;
12001 static const struct got_error *
12002 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12003 const char *path, struct got_object_id_queue *commits,
12004 struct got_repository *repo)
12006 const struct got_error *err = NULL;
12007 struct stat st, st2;
12008 struct timespec timeout;
12009 char *editor;
12010 FILE *f = NULL;
12012 err = get_editor(&editor);
12013 if (err)
12014 return err;
12016 if (stat(path, &st) == -1) {
12017 err = got_error_from_errno2("stat", path);
12018 goto done;
12021 if (spawn_editor(editor, path) == -1) {
12022 err = got_error_from_errno("failed spawning editor");
12023 goto done;
12026 timeout.tv_sec = 0;
12027 timeout.tv_nsec = 1;
12028 nanosleep(&timeout, NULL);
12030 if (stat(path, &st2) == -1) {
12031 err = got_error_from_errno2("stat", path);
12032 goto done;
12035 if (st.st_size == st2.st_size &&
12036 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12037 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12038 "no changes made to histedit script, aborting");
12039 goto done;
12042 f = fopen(path, "re");
12043 if (f == NULL) {
12044 err = got_error_from_errno("fopen");
12045 goto done;
12047 err = histedit_parse_list(histedit_cmds, f, repo);
12048 if (err)
12049 goto done;
12051 err = histedit_check_script(histedit_cmds, commits, repo);
12052 done:
12053 if (f && fclose(f) == EOF && err == NULL)
12054 err = got_error_from_errno("fclose");
12055 free(editor);
12056 return err;
12059 static const struct got_error *
12060 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12061 struct got_object_id_queue *, const char *, const char *,
12062 struct got_repository *);
12064 static const struct got_error *
12065 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12066 struct got_object_id_queue *commits, const char *branch_name,
12067 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12068 struct got_repository *repo)
12070 const struct got_error *err;
12071 FILE *f = NULL;
12072 char *path = NULL;
12074 err = got_opentemp_named(&path, &f, "got-histedit", "");
12075 if (err)
12076 return err;
12078 err = write_cmd_list(f, branch_name, commits);
12079 if (err)
12080 goto done;
12082 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12083 fold_only, drop_only, edit_only, repo);
12084 if (err)
12085 goto done;
12087 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12088 rewind(f);
12089 err = histedit_parse_list(histedit_cmds, f, repo);
12090 } else {
12091 if (fclose(f) == EOF) {
12092 err = got_error_from_errno("fclose");
12093 goto done;
12095 f = NULL;
12096 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12097 if (err) {
12098 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12099 err->code != GOT_ERR_HISTEDIT_CMD)
12100 goto done;
12101 err = histedit_edit_list_retry(histedit_cmds, err,
12102 commits, path, branch_name, repo);
12105 done:
12106 if (f && fclose(f) == EOF && err == NULL)
12107 err = got_error_from_errno("fclose");
12108 if (path && unlink(path) != 0 && err == NULL)
12109 err = got_error_from_errno2("unlink", path);
12110 free(path);
12111 return err;
12114 static const struct got_error *
12115 histedit_save_list(struct got_histedit_list *histedit_cmds,
12116 struct got_worktree *worktree, struct got_repository *repo)
12118 const struct got_error *err = NULL;
12119 char *path = NULL;
12120 FILE *f = NULL;
12121 struct got_histedit_list_entry *hle;
12122 struct got_commit_object *commit = NULL;
12124 err = got_worktree_get_histedit_script_path(&path, worktree);
12125 if (err)
12126 return err;
12128 f = fopen(path, "we");
12129 if (f == NULL) {
12130 err = got_error_from_errno2("fopen", path);
12131 goto done;
12133 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12134 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12135 repo);
12136 if (err)
12137 break;
12139 if (hle->logmsg) {
12140 int n = fprintf(f, "%c %s\n",
12141 GOT_HISTEDIT_MESG, hle->logmsg);
12142 if (n < 0) {
12143 err = got_ferror(f, GOT_ERR_IO);
12144 break;
12148 done:
12149 if (f && fclose(f) == EOF && err == NULL)
12150 err = got_error_from_errno("fclose");
12151 free(path);
12152 if (commit)
12153 got_object_commit_close(commit);
12154 return err;
12157 static void
12158 histedit_free_list(struct got_histedit_list *histedit_cmds)
12160 struct got_histedit_list_entry *hle;
12162 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12163 TAILQ_REMOVE(histedit_cmds, hle, entry);
12164 free(hle);
12168 static const struct got_error *
12169 histedit_load_list(struct got_histedit_list *histedit_cmds,
12170 const char *path, struct got_repository *repo)
12172 const struct got_error *err = NULL;
12173 FILE *f = NULL;
12175 f = fopen(path, "re");
12176 if (f == NULL) {
12177 err = got_error_from_errno2("fopen", path);
12178 goto done;
12181 err = histedit_parse_list(histedit_cmds, f, repo);
12182 done:
12183 if (f && fclose(f) == EOF && err == NULL)
12184 err = got_error_from_errno("fclose");
12185 return err;
12188 static const struct got_error *
12189 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12190 const struct got_error *edit_err, struct got_object_id_queue *commits,
12191 const char *path, const char *branch_name, struct got_repository *repo)
12193 const struct got_error *err = NULL, *prev_err = edit_err;
12194 int resp = ' ';
12196 while (resp != 'c' && resp != 'r' && resp != 'a') {
12197 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12198 "or (a)bort: ", getprogname(), prev_err->msg);
12199 resp = getchar();
12200 if (resp == '\n')
12201 resp = getchar();
12202 if (resp == 'c') {
12203 histedit_free_list(histedit_cmds);
12204 err = histedit_run_editor(histedit_cmds, path, commits,
12205 repo);
12206 if (err) {
12207 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12208 err->code != GOT_ERR_HISTEDIT_CMD)
12209 break;
12210 prev_err = err;
12211 resp = ' ';
12212 continue;
12214 break;
12215 } else if (resp == 'r') {
12216 histedit_free_list(histedit_cmds);
12217 err = histedit_edit_script(histedit_cmds,
12218 commits, branch_name, 0, 0, 0, 0, repo);
12219 if (err) {
12220 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12221 err->code != GOT_ERR_HISTEDIT_CMD)
12222 break;
12223 prev_err = err;
12224 resp = ' ';
12225 continue;
12227 break;
12228 } else if (resp == 'a') {
12229 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12230 break;
12231 } else
12232 printf("invalid response '%c'\n", resp);
12235 return err;
12238 static const struct got_error *
12239 histedit_complete(struct got_worktree *worktree,
12240 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12241 struct got_reference *branch, struct got_repository *repo)
12243 printf("Switching work tree to %s\n",
12244 got_ref_get_symref_target(branch));
12245 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12246 branch, repo);
12249 static const struct got_error *
12250 show_histedit_progress(struct got_commit_object *commit,
12251 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12253 const struct got_error *err;
12254 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12256 err = got_object_id_str(&old_id_str, hle->commit_id);
12257 if (err)
12258 goto done;
12260 if (new_id) {
12261 err = got_object_id_str(&new_id_str, new_id);
12262 if (err)
12263 goto done;
12266 old_id_str[12] = '\0';
12267 if (new_id_str)
12268 new_id_str[12] = '\0';
12270 if (hle->logmsg) {
12271 logmsg = strdup(hle->logmsg);
12272 if (logmsg == NULL) {
12273 err = got_error_from_errno("strdup");
12274 goto done;
12276 trim_logmsg(logmsg, 42);
12277 } else {
12278 err = get_short_logmsg(&logmsg, 42, commit);
12279 if (err)
12280 goto done;
12283 switch (hle->cmd->code) {
12284 case GOT_HISTEDIT_PICK:
12285 case GOT_HISTEDIT_EDIT:
12286 printf("%s -> %s: %s\n", old_id_str,
12287 new_id_str ? new_id_str : "no-op change", logmsg);
12288 break;
12289 case GOT_HISTEDIT_DROP:
12290 case GOT_HISTEDIT_FOLD:
12291 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12292 logmsg);
12293 break;
12294 default:
12295 break;
12297 done:
12298 free(old_id_str);
12299 free(new_id_str);
12300 return err;
12303 static const struct got_error *
12304 histedit_commit(struct got_pathlist_head *merged_paths,
12305 struct got_worktree *worktree, struct got_fileindex *fileindex,
12306 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12307 const char *committer, int allow_conflict, struct got_repository *repo)
12309 const struct got_error *err;
12310 struct got_commit_object *commit;
12311 struct got_object_id *new_commit_id;
12313 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12314 && hle->logmsg == NULL) {
12315 err = histedit_edit_logmsg(hle, repo);
12316 if (err)
12317 return err;
12320 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12321 if (err)
12322 return err;
12324 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12325 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12326 hle->logmsg, allow_conflict, repo);
12327 if (err) {
12328 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12329 goto done;
12330 err = show_histedit_progress(commit, hle, NULL);
12331 } else {
12332 err = show_histedit_progress(commit, hle, new_commit_id);
12333 free(new_commit_id);
12335 done:
12336 got_object_commit_close(commit);
12337 return err;
12340 static const struct got_error *
12341 histedit_skip_commit(struct got_histedit_list_entry *hle,
12342 struct got_worktree *worktree, struct got_repository *repo)
12344 const struct got_error *error;
12345 struct got_commit_object *commit;
12347 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12348 repo);
12349 if (error)
12350 return error;
12352 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12353 if (error)
12354 return error;
12356 error = show_histedit_progress(commit, hle, NULL);
12357 got_object_commit_close(commit);
12358 return error;
12361 static const struct got_error *
12362 check_local_changes(void *arg, unsigned char status,
12363 unsigned char staged_status, const char *path,
12364 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12365 struct got_object_id *commit_id, int dirfd, const char *de_name)
12367 int *have_local_changes = arg;
12369 switch (status) {
12370 case GOT_STATUS_ADD:
12371 case GOT_STATUS_DELETE:
12372 case GOT_STATUS_MODIFY:
12373 case GOT_STATUS_CONFLICT:
12374 *have_local_changes = 1;
12375 return got_error(GOT_ERR_CANCELLED);
12376 default:
12377 break;
12380 switch (staged_status) {
12381 case GOT_STATUS_ADD:
12382 case GOT_STATUS_DELETE:
12383 case GOT_STATUS_MODIFY:
12384 *have_local_changes = 1;
12385 return got_error(GOT_ERR_CANCELLED);
12386 default:
12387 break;
12390 return NULL;
12393 static const struct got_error *
12394 cmd_histedit(int argc, char *argv[])
12396 const struct got_error *error = NULL;
12397 struct got_worktree *worktree = NULL;
12398 struct got_fileindex *fileindex = NULL;
12399 struct got_repository *repo = NULL;
12400 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12401 struct got_reference *branch = NULL;
12402 struct got_reference *tmp_branch = NULL;
12403 struct got_object_id *resume_commit_id = NULL;
12404 struct got_object_id *base_commit_id = NULL;
12405 struct got_object_id *head_commit_id = NULL;
12406 struct got_commit_object *commit = NULL;
12407 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12408 struct got_update_progress_arg upa;
12409 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12410 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12411 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12412 const char *edit_script_path = NULL;
12413 struct got_object_id_queue commits;
12414 struct got_pathlist_head merged_paths;
12415 const struct got_object_id_queue *parent_ids;
12416 struct got_object_qid *pid;
12417 struct got_histedit_list histedit_cmds;
12418 struct got_histedit_list_entry *hle;
12419 int *pack_fds = NULL;
12421 STAILQ_INIT(&commits);
12422 TAILQ_INIT(&histedit_cmds);
12423 TAILQ_INIT(&merged_paths);
12424 memset(&upa, 0, sizeof(upa));
12426 #ifndef PROFILE
12427 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12428 "unveil", NULL) == -1)
12429 err(1, "pledge");
12430 #endif
12432 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12433 switch (ch) {
12434 case 'a':
12435 abort_edit = 1;
12436 break;
12437 case 'C':
12438 allow_conflict = 1;
12439 break;
12440 case 'c':
12441 continue_edit = 1;
12442 break;
12443 case 'd':
12444 drop_only = 1;
12445 break;
12446 case 'e':
12447 edit_only = 1;
12448 break;
12449 case 'F':
12450 edit_script_path = optarg;
12451 break;
12452 case 'f':
12453 fold_only = 1;
12454 break;
12455 case 'l':
12456 list_backups = 1;
12457 break;
12458 case 'm':
12459 edit_logmsg_only = 1;
12460 break;
12461 case 'X':
12462 delete_backups = 1;
12463 break;
12464 default:
12465 usage_histedit();
12466 /* NOTREACHED */
12470 argc -= optind;
12471 argv += optind;
12473 if (abort_edit && allow_conflict)
12474 option_conflict('a', 'C');
12475 if (abort_edit && continue_edit)
12476 option_conflict('a', 'c');
12477 if (edit_script_path && allow_conflict)
12478 option_conflict('F', 'C');
12479 if (edit_script_path && edit_logmsg_only)
12480 option_conflict('F', 'm');
12481 if (abort_edit && edit_logmsg_only)
12482 option_conflict('a', 'm');
12483 if (edit_logmsg_only && allow_conflict)
12484 option_conflict('m', 'C');
12485 if (continue_edit && edit_logmsg_only)
12486 option_conflict('c', 'm');
12487 if (abort_edit && fold_only)
12488 option_conflict('a', 'f');
12489 if (fold_only && allow_conflict)
12490 option_conflict('f', 'C');
12491 if (continue_edit && fold_only)
12492 option_conflict('c', 'f');
12493 if (fold_only && edit_logmsg_only)
12494 option_conflict('f', 'm');
12495 if (edit_script_path && fold_only)
12496 option_conflict('F', 'f');
12497 if (abort_edit && edit_only)
12498 option_conflict('a', 'e');
12499 if (continue_edit && edit_only)
12500 option_conflict('c', 'e');
12501 if (edit_only && edit_logmsg_only)
12502 option_conflict('e', 'm');
12503 if (edit_script_path && edit_only)
12504 option_conflict('F', 'e');
12505 if (fold_only && edit_only)
12506 option_conflict('f', 'e');
12507 if (drop_only && abort_edit)
12508 option_conflict('d', 'a');
12509 if (drop_only && allow_conflict)
12510 option_conflict('d', 'C');
12511 if (drop_only && continue_edit)
12512 option_conflict('d', 'c');
12513 if (drop_only && edit_logmsg_only)
12514 option_conflict('d', 'm');
12515 if (drop_only && edit_only)
12516 option_conflict('d', 'e');
12517 if (drop_only && edit_script_path)
12518 option_conflict('d', 'F');
12519 if (drop_only && fold_only)
12520 option_conflict('d', 'f');
12521 if (list_backups) {
12522 if (abort_edit)
12523 option_conflict('l', 'a');
12524 if (allow_conflict)
12525 option_conflict('l', 'C');
12526 if (continue_edit)
12527 option_conflict('l', 'c');
12528 if (edit_script_path)
12529 option_conflict('l', 'F');
12530 if (edit_logmsg_only)
12531 option_conflict('l', 'm');
12532 if (drop_only)
12533 option_conflict('l', 'd');
12534 if (fold_only)
12535 option_conflict('l', 'f');
12536 if (edit_only)
12537 option_conflict('l', 'e');
12538 if (delete_backups)
12539 option_conflict('l', 'X');
12540 if (argc != 0 && argc != 1)
12541 usage_histedit();
12542 } else if (delete_backups) {
12543 if (abort_edit)
12544 option_conflict('X', 'a');
12545 if (allow_conflict)
12546 option_conflict('X', 'C');
12547 if (continue_edit)
12548 option_conflict('X', 'c');
12549 if (drop_only)
12550 option_conflict('X', 'd');
12551 if (edit_script_path)
12552 option_conflict('X', 'F');
12553 if (edit_logmsg_only)
12554 option_conflict('X', 'm');
12555 if (fold_only)
12556 option_conflict('X', 'f');
12557 if (edit_only)
12558 option_conflict('X', 'e');
12559 if (list_backups)
12560 option_conflict('X', 'l');
12561 if (argc != 0 && argc != 1)
12562 usage_histedit();
12563 } else if (allow_conflict && !continue_edit)
12564 errx(1, "-C option requires -c");
12565 else if (argc != 0)
12566 usage_histedit();
12569 * This command cannot apply unveil(2) in all cases because the
12570 * user may choose to run an editor to edit the histedit script
12571 * and to edit individual commit log messages.
12572 * unveil(2) traverses exec(2); if an editor is used we have to
12573 * apply unveil after edit script and log messages have been written.
12574 * XXX TODO: Make use of unveil(2) where possible.
12577 cwd = getcwd(NULL, 0);
12578 if (cwd == NULL) {
12579 error = got_error_from_errno("getcwd");
12580 goto done;
12583 error = got_repo_pack_fds_open(&pack_fds);
12584 if (error != NULL)
12585 goto done;
12587 error = got_worktree_open(&worktree, cwd);
12588 if (error) {
12589 if (list_backups || delete_backups) {
12590 if (error->code != GOT_ERR_NOT_WORKTREE)
12591 goto done;
12592 } else {
12593 if (error->code == GOT_ERR_NOT_WORKTREE)
12594 error = wrap_not_worktree_error(error,
12595 "histedit", cwd);
12596 goto done;
12600 if (list_backups || delete_backups) {
12601 error = got_repo_open(&repo,
12602 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12603 NULL, pack_fds);
12604 if (error != NULL)
12605 goto done;
12606 error = apply_unveil(got_repo_get_path(repo), 0,
12607 worktree ? got_worktree_get_root_path(worktree) : NULL);
12608 if (error)
12609 goto done;
12610 error = process_backup_refs(
12611 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12612 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12613 goto done; /* nothing else to do */
12616 error = get_gitconfig_path(&gitconfig_path);
12617 if (error)
12618 goto done;
12619 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12620 gitconfig_path, pack_fds);
12621 if (error != NULL)
12622 goto done;
12624 if (worktree != NULL && !list_backups && !delete_backups) {
12625 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12626 if (error)
12627 goto done;
12630 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12631 if (error)
12632 goto done;
12633 if (rebase_in_progress) {
12634 error = got_error(GOT_ERR_REBASING);
12635 goto done;
12638 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12639 repo);
12640 if (error)
12641 goto done;
12642 if (merge_in_progress) {
12643 error = got_error(GOT_ERR_MERGE_BUSY);
12644 goto done;
12647 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12648 if (error)
12649 goto done;
12651 if (edit_in_progress && edit_logmsg_only) {
12652 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12653 "histedit operation is in progress in this "
12654 "work tree and must be continued or aborted "
12655 "before the -m option can be used");
12656 goto done;
12658 if (edit_in_progress && drop_only) {
12659 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12660 "histedit operation is in progress in this "
12661 "work tree and must be continued or aborted "
12662 "before the -d option can be used");
12663 goto done;
12665 if (edit_in_progress && fold_only) {
12666 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12667 "histedit operation is in progress in this "
12668 "work tree and must be continued or aborted "
12669 "before the -f option can be used");
12670 goto done;
12672 if (edit_in_progress && edit_only) {
12673 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12674 "histedit operation is in progress in this "
12675 "work tree and must be continued or aborted "
12676 "before the -e option can be used");
12677 goto done;
12680 if (edit_in_progress && abort_edit) {
12681 error = got_worktree_histedit_continue(&resume_commit_id,
12682 &tmp_branch, &branch, &base_commit_id, &fileindex,
12683 worktree, repo);
12684 if (error)
12685 goto done;
12686 printf("Switching work tree to %s\n",
12687 got_ref_get_symref_target(branch));
12688 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12689 branch, base_commit_id, abort_progress, &upa);
12690 if (error)
12691 goto done;
12692 printf("Histedit of %s aborted\n",
12693 got_ref_get_symref_target(branch));
12694 print_merge_progress_stats(&upa);
12695 goto done; /* nothing else to do */
12696 } else if (abort_edit) {
12697 error = got_error(GOT_ERR_NOT_HISTEDIT);
12698 goto done;
12701 error = get_author(&committer, repo, worktree);
12702 if (error)
12703 goto done;
12705 if (continue_edit) {
12706 char *path;
12708 if (!edit_in_progress) {
12709 error = got_error(GOT_ERR_NOT_HISTEDIT);
12710 goto done;
12713 error = got_worktree_get_histedit_script_path(&path, worktree);
12714 if (error)
12715 goto done;
12717 error = histedit_load_list(&histedit_cmds, path, repo);
12718 free(path);
12719 if (error)
12720 goto done;
12722 error = got_worktree_histedit_continue(&resume_commit_id,
12723 &tmp_branch, &branch, &base_commit_id, &fileindex,
12724 worktree, repo);
12725 if (error)
12726 goto done;
12728 error = got_ref_resolve(&head_commit_id, repo, branch);
12729 if (error)
12730 goto done;
12732 error = got_object_open_as_commit(&commit, repo,
12733 head_commit_id);
12734 if (error)
12735 goto done;
12736 parent_ids = got_object_commit_get_parent_ids(commit);
12737 pid = STAILQ_FIRST(parent_ids);
12738 if (pid == NULL) {
12739 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12740 goto done;
12742 error = collect_commits(&commits, head_commit_id, &pid->id,
12743 base_commit_id, got_worktree_get_path_prefix(worktree),
12744 GOT_ERR_HISTEDIT_PATH, repo);
12745 got_object_commit_close(commit);
12746 commit = NULL;
12747 if (error)
12748 goto done;
12749 } else {
12750 if (edit_in_progress) {
12751 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12752 goto done;
12755 error = got_ref_open(&branch, repo,
12756 got_worktree_get_head_ref_name(worktree), 0);
12757 if (error != NULL)
12758 goto done;
12760 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12761 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12762 "will not edit commit history of a branch outside "
12763 "the \"refs/heads/\" reference namespace");
12764 goto done;
12767 error = got_ref_resolve(&head_commit_id, repo, branch);
12768 got_ref_close(branch);
12769 branch = NULL;
12770 if (error)
12771 goto done;
12773 error = got_object_open_as_commit(&commit, repo,
12774 head_commit_id);
12775 if (error)
12776 goto done;
12777 parent_ids = got_object_commit_get_parent_ids(commit);
12778 pid = STAILQ_FIRST(parent_ids);
12779 if (pid == NULL) {
12780 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12781 goto done;
12783 error = collect_commits(&commits, head_commit_id, &pid->id,
12784 got_worktree_get_base_commit_id(worktree),
12785 got_worktree_get_path_prefix(worktree),
12786 GOT_ERR_HISTEDIT_PATH, repo);
12787 got_object_commit_close(commit);
12788 commit = NULL;
12789 if (error)
12790 goto done;
12792 if (STAILQ_EMPTY(&commits)) {
12793 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12794 goto done;
12797 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12798 &base_commit_id, &fileindex, worktree, repo);
12799 if (error)
12800 goto done;
12802 if (edit_script_path) {
12803 error = histedit_load_list(&histedit_cmds,
12804 edit_script_path, repo);
12805 if (error) {
12806 got_worktree_histedit_abort(worktree, fileindex,
12807 repo, branch, base_commit_id,
12808 abort_progress, &upa);
12809 print_merge_progress_stats(&upa);
12810 goto done;
12812 } else {
12813 const char *branch_name;
12814 branch_name = got_ref_get_symref_target(branch);
12815 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12816 branch_name += 11;
12817 error = histedit_edit_script(&histedit_cmds, &commits,
12818 branch_name, edit_logmsg_only, fold_only,
12819 drop_only, edit_only, repo);
12820 if (error) {
12821 got_worktree_histedit_abort(worktree, fileindex,
12822 repo, branch, base_commit_id,
12823 abort_progress, &upa);
12824 print_merge_progress_stats(&upa);
12825 goto done;
12830 error = histedit_save_list(&histedit_cmds, worktree,
12831 repo);
12832 if (error) {
12833 got_worktree_histedit_abort(worktree, fileindex,
12834 repo, branch, base_commit_id,
12835 abort_progress, &upa);
12836 print_merge_progress_stats(&upa);
12837 goto done;
12842 error = histedit_check_script(&histedit_cmds, &commits, repo);
12843 if (error)
12844 goto done;
12846 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12847 if (resume_commit_id) {
12848 if (got_object_id_cmp(hle->commit_id,
12849 resume_commit_id) != 0)
12850 continue;
12852 resume_commit_id = NULL;
12853 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12854 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12855 error = histedit_skip_commit(hle, worktree,
12856 repo);
12857 if (error)
12858 goto done;
12859 } else {
12860 struct got_pathlist_head paths;
12861 int have_changes = 0;
12863 TAILQ_INIT(&paths);
12864 error = got_pathlist_append(&paths, "", NULL);
12865 if (error)
12866 goto done;
12867 error = got_worktree_status(worktree, &paths,
12868 repo, 0, check_local_changes, &have_changes,
12869 check_cancelled, NULL);
12870 got_pathlist_free(&paths,
12871 GOT_PATHLIST_FREE_NONE);
12872 if (error) {
12873 if (error->code != GOT_ERR_CANCELLED)
12874 goto done;
12875 if (sigint_received || sigpipe_received)
12876 goto done;
12878 if (have_changes) {
12879 error = histedit_commit(NULL, worktree,
12880 fileindex, tmp_branch, hle,
12881 committer, allow_conflict, repo);
12882 if (error)
12883 goto done;
12884 } else {
12885 error = got_object_open_as_commit(
12886 &commit, repo, hle->commit_id);
12887 if (error)
12888 goto done;
12889 error = show_histedit_progress(commit,
12890 hle, NULL);
12891 got_object_commit_close(commit);
12892 commit = NULL;
12893 if (error)
12894 goto done;
12897 continue;
12900 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12901 error = histedit_skip_commit(hle, worktree, repo);
12902 if (error)
12903 goto done;
12904 continue;
12907 error = got_object_open_as_commit(&commit, repo,
12908 hle->commit_id);
12909 if (error)
12910 goto done;
12911 parent_ids = got_object_commit_get_parent_ids(commit);
12912 pid = STAILQ_FIRST(parent_ids);
12914 error = got_worktree_histedit_merge_files(&merged_paths,
12915 worktree, fileindex, &pid->id, hle->commit_id, repo,
12916 update_progress, &upa, check_cancelled, NULL);
12917 if (error)
12918 goto done;
12919 got_object_commit_close(commit);
12920 commit = NULL;
12922 print_merge_progress_stats(&upa);
12923 if (upa.conflicts > 0 || upa.missing > 0 ||
12924 upa.not_deleted > 0 || upa.unversioned > 0) {
12925 if (upa.conflicts > 0) {
12926 error = show_rebase_merge_conflict(
12927 hle->commit_id, repo);
12928 if (error)
12929 goto done;
12931 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12932 break;
12935 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12936 char *id_str;
12937 error = got_object_id_str(&id_str, hle->commit_id);
12938 if (error)
12939 goto done;
12940 printf("Stopping histedit for amending commit %s\n",
12941 id_str);
12942 free(id_str);
12943 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12944 error = got_worktree_histedit_postpone(worktree,
12945 fileindex);
12946 goto done;
12949 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12950 error = histedit_skip_commit(hle, worktree, repo);
12951 if (error)
12952 goto done;
12953 continue;
12956 error = histedit_commit(&merged_paths, worktree, fileindex,
12957 tmp_branch, hle, committer, allow_conflict, repo);
12958 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12959 if (error)
12960 goto done;
12963 if (upa.conflicts > 0 || upa.missing > 0 ||
12964 upa.not_deleted > 0 || upa.unversioned > 0) {
12965 error = got_worktree_histedit_postpone(worktree, fileindex);
12966 if (error)
12967 goto done;
12968 if (upa.conflicts > 0 && upa.missing == 0 &&
12969 upa.not_deleted == 0 && upa.unversioned == 0) {
12970 error = got_error_msg(GOT_ERR_CONFLICTS,
12971 "conflicts must be resolved before histedit "
12972 "can continue");
12973 } else if (upa.conflicts > 0) {
12974 error = got_error_msg(GOT_ERR_CONFLICTS,
12975 "conflicts must be resolved before histedit "
12976 "can continue; changes destined for some "
12977 "files were not yet merged and should be "
12978 "merged manually if required before the "
12979 "histedit operation is continued");
12980 } else {
12981 error = got_error_msg(GOT_ERR_CONFLICTS,
12982 "changes destined for some files were not "
12983 "yet merged and should be merged manually "
12984 "if required before the histedit operation "
12985 "is continued");
12987 } else
12988 error = histedit_complete(worktree, fileindex, tmp_branch,
12989 branch, repo);
12990 done:
12991 free(cwd);
12992 free(committer);
12993 free(gitconfig_path);
12994 got_object_id_queue_free(&commits);
12995 histedit_free_list(&histedit_cmds);
12996 free(head_commit_id);
12997 free(base_commit_id);
12998 free(resume_commit_id);
12999 if (commit)
13000 got_object_commit_close(commit);
13001 if (branch)
13002 got_ref_close(branch);
13003 if (tmp_branch)
13004 got_ref_close(tmp_branch);
13005 if (worktree)
13006 got_worktree_close(worktree);
13007 if (repo) {
13008 const struct got_error *close_err = got_repo_close(repo);
13009 if (error == NULL)
13010 error = close_err;
13012 if (pack_fds) {
13013 const struct got_error *pack_err =
13014 got_repo_pack_fds_close(pack_fds);
13015 if (error == NULL)
13016 error = pack_err;
13018 return error;
13021 __dead static void
13022 usage_integrate(void)
13024 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13025 exit(1);
13028 static const struct got_error *
13029 cmd_integrate(int argc, char *argv[])
13031 const struct got_error *error = NULL;
13032 struct got_repository *repo = NULL;
13033 struct got_worktree *worktree = NULL;
13034 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13035 const char *branch_arg = NULL;
13036 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13037 struct got_fileindex *fileindex = NULL;
13038 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13039 int ch;
13040 struct got_update_progress_arg upa;
13041 int *pack_fds = NULL;
13043 #ifndef PROFILE
13044 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13045 "unveil", NULL) == -1)
13046 err(1, "pledge");
13047 #endif
13049 while ((ch = getopt(argc, argv, "")) != -1) {
13050 switch (ch) {
13051 default:
13052 usage_integrate();
13053 /* NOTREACHED */
13057 argc -= optind;
13058 argv += optind;
13060 if (argc != 1)
13061 usage_integrate();
13062 branch_arg = argv[0];
13064 cwd = getcwd(NULL, 0);
13065 if (cwd == NULL) {
13066 error = got_error_from_errno("getcwd");
13067 goto done;
13070 error = got_repo_pack_fds_open(&pack_fds);
13071 if (error != NULL)
13072 goto done;
13074 error = got_worktree_open(&worktree, cwd);
13075 if (error) {
13076 if (error->code == GOT_ERR_NOT_WORKTREE)
13077 error = wrap_not_worktree_error(error, "integrate",
13078 cwd);
13079 goto done;
13082 error = check_rebase_or_histedit_in_progress(worktree);
13083 if (error)
13084 goto done;
13086 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13087 NULL, pack_fds);
13088 if (error != NULL)
13089 goto done;
13091 error = apply_unveil(got_repo_get_path(repo), 0,
13092 got_worktree_get_root_path(worktree));
13093 if (error)
13094 goto done;
13096 error = check_merge_in_progress(worktree, repo);
13097 if (error)
13098 goto done;
13100 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13101 error = got_error_from_errno("asprintf");
13102 goto done;
13105 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13106 &base_branch_ref, worktree, refname, repo);
13107 if (error)
13108 goto done;
13110 refname = strdup(got_ref_get_name(branch_ref));
13111 if (refname == NULL) {
13112 error = got_error_from_errno("strdup");
13113 got_worktree_integrate_abort(worktree, fileindex, repo,
13114 branch_ref, base_branch_ref);
13115 goto done;
13117 base_refname = strdup(got_ref_get_name(base_branch_ref));
13118 if (base_refname == NULL) {
13119 error = got_error_from_errno("strdup");
13120 got_worktree_integrate_abort(worktree, fileindex, repo,
13121 branch_ref, base_branch_ref);
13122 goto done;
13124 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13125 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13126 got_worktree_integrate_abort(worktree, fileindex, repo,
13127 branch_ref, base_branch_ref);
13128 goto done;
13131 error = got_ref_resolve(&commit_id, repo, branch_ref);
13132 if (error)
13133 goto done;
13135 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13136 if (error)
13137 goto done;
13139 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13140 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13141 "specified branch has already been integrated");
13142 got_worktree_integrate_abort(worktree, fileindex, repo,
13143 branch_ref, base_branch_ref);
13144 goto done;
13147 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13148 if (error) {
13149 if (error->code == GOT_ERR_ANCESTRY)
13150 error = got_error(GOT_ERR_REBASE_REQUIRED);
13151 got_worktree_integrate_abort(worktree, fileindex, repo,
13152 branch_ref, base_branch_ref);
13153 goto done;
13156 memset(&upa, 0, sizeof(upa));
13157 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13158 branch_ref, base_branch_ref, update_progress, &upa,
13159 check_cancelled, NULL);
13160 if (error)
13161 goto done;
13163 printf("Integrated %s into %s\n", refname, base_refname);
13164 print_update_progress_stats(&upa);
13165 done:
13166 if (repo) {
13167 const struct got_error *close_err = got_repo_close(repo);
13168 if (error == NULL)
13169 error = close_err;
13171 if (worktree)
13172 got_worktree_close(worktree);
13173 if (pack_fds) {
13174 const struct got_error *pack_err =
13175 got_repo_pack_fds_close(pack_fds);
13176 if (error == NULL)
13177 error = pack_err;
13179 free(cwd);
13180 free(base_commit_id);
13181 free(commit_id);
13182 free(refname);
13183 free(base_refname);
13184 return error;
13187 __dead static void
13188 usage_merge(void)
13190 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13191 exit(1);
13194 static const struct got_error *
13195 cmd_merge(int argc, char *argv[])
13197 const struct got_error *error = NULL;
13198 struct got_worktree *worktree = NULL;
13199 struct got_repository *repo = NULL;
13200 struct got_fileindex *fileindex = NULL;
13201 char *cwd = NULL, *id_str = NULL, *author = NULL;
13202 char *gitconfig_path = NULL;
13203 struct got_reference *branch = NULL, *wt_branch = NULL;
13204 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13205 struct got_object_id *wt_branch_tip = NULL;
13206 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13207 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13208 struct got_update_progress_arg upa;
13209 struct got_object_id *merge_commit_id = NULL;
13210 char *branch_name = NULL;
13211 int *pack_fds = NULL;
13213 memset(&upa, 0, sizeof(upa));
13215 #ifndef PROFILE
13216 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13217 "unveil", NULL) == -1)
13218 err(1, "pledge");
13219 #endif
13221 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13222 switch (ch) {
13223 case 'a':
13224 abort_merge = 1;
13225 break;
13226 case 'C':
13227 allow_conflict = 1;
13228 break;
13229 case 'c':
13230 continue_merge = 1;
13231 break;
13232 case 'M':
13233 prefer_fast_forward = 0;
13234 break;
13235 case 'n':
13236 interrupt_merge = 1;
13237 break;
13238 default:
13239 usage_merge();
13240 /* NOTREACHED */
13244 argc -= optind;
13245 argv += optind;
13247 if (abort_merge) {
13248 if (continue_merge)
13249 option_conflict('a', 'c');
13250 if (!prefer_fast_forward)
13251 option_conflict('a', 'M');
13252 if (interrupt_merge)
13253 option_conflict('a', 'n');
13254 } else if (continue_merge) {
13255 if (!prefer_fast_forward)
13256 option_conflict('c', 'M');
13257 if (interrupt_merge)
13258 option_conflict('c', 'n');
13260 if (allow_conflict) {
13261 if (!continue_merge)
13262 errx(1, "-C option requires -c");
13264 if (abort_merge || continue_merge) {
13265 if (argc != 0)
13266 usage_merge();
13267 } else if (argc != 1)
13268 usage_merge();
13270 cwd = getcwd(NULL, 0);
13271 if (cwd == NULL) {
13272 error = got_error_from_errno("getcwd");
13273 goto done;
13276 error = got_repo_pack_fds_open(&pack_fds);
13277 if (error != NULL)
13278 goto done;
13280 error = got_worktree_open(&worktree, cwd);
13281 if (error) {
13282 if (error->code == GOT_ERR_NOT_WORKTREE)
13283 error = wrap_not_worktree_error(error,
13284 "merge", cwd);
13285 goto done;
13288 error = get_gitconfig_path(&gitconfig_path);
13289 if (error)
13290 goto done;
13291 error = got_repo_open(&repo,
13292 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13293 gitconfig_path, pack_fds);
13294 if (error != NULL)
13295 goto done;
13297 if (worktree != NULL) {
13298 error = worktree_has_logmsg_ref("merge", worktree, repo);
13299 if (error)
13300 goto done;
13303 error = apply_unveil(got_repo_get_path(repo), 0,
13304 worktree ? got_worktree_get_root_path(worktree) : NULL);
13305 if (error)
13306 goto done;
13308 error = check_rebase_or_histedit_in_progress(worktree);
13309 if (error)
13310 goto done;
13312 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13313 repo);
13314 if (error)
13315 goto done;
13317 if (merge_in_progress && !(abort_merge || continue_merge)) {
13318 error = got_error(GOT_ERR_MERGE_BUSY);
13319 goto done;
13322 if (!merge_in_progress && (abort_merge || continue_merge)) {
13323 error = got_error(GOT_ERR_NOT_MERGING);
13324 goto done;
13327 if (abort_merge) {
13328 error = got_worktree_merge_continue(&branch_name,
13329 &branch_tip, &fileindex, worktree, repo);
13330 if (error)
13331 goto done;
13332 error = got_worktree_merge_abort(worktree, fileindex, repo,
13333 abort_progress, &upa);
13334 if (error)
13335 goto done;
13336 printf("Merge of %s aborted\n", branch_name);
13337 goto done; /* nothing else to do */
13340 if (strncmp(got_worktree_get_head_ref_name(worktree),
13341 "refs/heads/", 11) != 0) {
13342 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13343 "work tree's current branch %s is outside the "
13344 "\"refs/heads/\" reference namespace; "
13345 "update -b required",
13346 got_worktree_get_head_ref_name(worktree));
13347 goto done;
13350 error = get_author(&author, repo, worktree);
13351 if (error)
13352 goto done;
13354 error = got_ref_open(&wt_branch, repo,
13355 got_worktree_get_head_ref_name(worktree), 0);
13356 if (error)
13357 goto done;
13358 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13359 if (error)
13360 goto done;
13362 if (continue_merge) {
13363 struct got_object_id *base_commit_id;
13364 base_commit_id = got_worktree_get_base_commit_id(worktree);
13365 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13366 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13367 goto done;
13369 error = got_worktree_merge_continue(&branch_name,
13370 &branch_tip, &fileindex, worktree, repo);
13371 if (error)
13372 goto done;
13373 } else {
13374 error = got_ref_open(&branch, repo, argv[0], 0);
13375 if (error != NULL)
13376 goto done;
13377 branch_name = strdup(got_ref_get_name(branch));
13378 if (branch_name == NULL) {
13379 error = got_error_from_errno("strdup");
13380 goto done;
13382 error = got_ref_resolve(&branch_tip, repo, branch);
13383 if (error)
13384 goto done;
13387 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13388 wt_branch_tip, branch_tip, 0, repo,
13389 check_cancelled, NULL);
13390 if (error && error->code != GOT_ERR_ANCESTRY)
13391 goto done;
13393 if (!continue_merge) {
13394 error = check_path_prefix(wt_branch_tip, branch_tip,
13395 got_worktree_get_path_prefix(worktree),
13396 GOT_ERR_MERGE_PATH, repo);
13397 if (error)
13398 goto done;
13399 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13400 if (error)
13401 goto done;
13402 if (prefer_fast_forward && yca_id &&
13403 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13404 struct got_pathlist_head paths;
13405 if (interrupt_merge) {
13406 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13407 "there are no changes to merge since %s "
13408 "is already based on %s; merge cannot be "
13409 "interrupted for amending; -n",
13410 branch_name, got_ref_get_name(wt_branch));
13411 goto done;
13413 printf("Forwarding %s to %s\n",
13414 got_ref_get_name(wt_branch), branch_name);
13415 error = got_ref_change_ref(wt_branch, branch_tip);
13416 if (error)
13417 goto done;
13418 error = got_ref_write(wt_branch, repo);
13419 if (error)
13420 goto done;
13421 error = got_worktree_set_base_commit_id(worktree, repo,
13422 branch_tip);
13423 if (error)
13424 goto done;
13425 TAILQ_INIT(&paths);
13426 error = got_pathlist_append(&paths, "", NULL);
13427 if (error)
13428 goto done;
13429 error = got_worktree_checkout_files(worktree,
13430 &paths, repo, update_progress, &upa,
13431 check_cancelled, NULL);
13432 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13433 if (error)
13434 goto done;
13435 if (upa.did_something) {
13436 char *id_str;
13437 error = got_object_id_str(&id_str, branch_tip);
13438 if (error)
13439 goto done;
13440 printf("Updated to commit %s\n", id_str);
13441 free(id_str);
13442 } else
13443 printf("Already up-to-date\n");
13444 print_update_progress_stats(&upa);
13445 goto done;
13447 error = got_worktree_merge_write_refs(worktree, branch, repo);
13448 if (error)
13449 goto done;
13451 error = got_worktree_merge_branch(worktree, fileindex,
13452 yca_id, branch_tip, repo, update_progress, &upa,
13453 check_cancelled, NULL);
13454 if (error)
13455 goto done;
13456 print_merge_progress_stats(&upa);
13457 if (!upa.did_something) {
13458 error = got_worktree_merge_abort(worktree, fileindex,
13459 repo, abort_progress, &upa);
13460 if (error)
13461 goto done;
13462 printf("Already up-to-date\n");
13463 goto done;
13467 if (interrupt_merge) {
13468 error = got_worktree_merge_postpone(worktree, fileindex);
13469 if (error)
13470 goto done;
13471 printf("Merge of %s interrupted on request\n", branch_name);
13472 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13473 upa.not_deleted > 0 || upa.unversioned > 0) {
13474 error = got_worktree_merge_postpone(worktree, fileindex);
13475 if (error)
13476 goto done;
13477 if (upa.conflicts > 0 && upa.missing == 0 &&
13478 upa.not_deleted == 0 && upa.unversioned == 0) {
13479 error = got_error_msg(GOT_ERR_CONFLICTS,
13480 "conflicts must be resolved before merging "
13481 "can continue");
13482 } else if (upa.conflicts > 0) {
13483 error = got_error_msg(GOT_ERR_CONFLICTS,
13484 "conflicts must be resolved before merging "
13485 "can continue; changes destined for some "
13486 "files were not yet merged and "
13487 "should be merged manually if required before the "
13488 "merge operation is continued");
13489 } else {
13490 error = got_error_msg(GOT_ERR_CONFLICTS,
13491 "changes destined for some "
13492 "files were not yet merged and should be "
13493 "merged manually if required before the "
13494 "merge operation is continued");
13496 goto done;
13497 } else {
13498 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13499 fileindex, author, NULL, 1, branch_tip, branch_name,
13500 allow_conflict, repo, continue_merge ? print_status : NULL,
13501 NULL);
13502 if (error)
13503 goto done;
13504 error = got_worktree_merge_complete(worktree, fileindex, repo);
13505 if (error)
13506 goto done;
13507 error = got_object_id_str(&id_str, merge_commit_id);
13508 if (error)
13509 goto done;
13510 printf("Merged %s into %s: %s\n", branch_name,
13511 got_worktree_get_head_ref_name(worktree),
13512 id_str);
13515 done:
13516 free(gitconfig_path);
13517 free(id_str);
13518 free(merge_commit_id);
13519 free(author);
13520 free(branch_tip);
13521 free(branch_name);
13522 free(yca_id);
13523 if (branch)
13524 got_ref_close(branch);
13525 if (wt_branch)
13526 got_ref_close(wt_branch);
13527 if (worktree)
13528 got_worktree_close(worktree);
13529 if (repo) {
13530 const struct got_error *close_err = got_repo_close(repo);
13531 if (error == NULL)
13532 error = close_err;
13534 if (pack_fds) {
13535 const struct got_error *pack_err =
13536 got_repo_pack_fds_close(pack_fds);
13537 if (error == NULL)
13538 error = pack_err;
13540 return error;
13543 __dead static void
13544 usage_stage(void)
13546 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13547 "[path ...]\n", getprogname());
13548 exit(1);
13551 static const struct got_error *
13552 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13553 const char *path, struct got_object_id *blob_id,
13554 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13555 int dirfd, const char *de_name)
13557 const struct got_error *err = NULL;
13558 char *id_str = NULL;
13560 if (staged_status != GOT_STATUS_ADD &&
13561 staged_status != GOT_STATUS_MODIFY &&
13562 staged_status != GOT_STATUS_DELETE)
13563 return NULL;
13565 if (staged_status == GOT_STATUS_ADD ||
13566 staged_status == GOT_STATUS_MODIFY)
13567 err = got_object_id_str(&id_str, staged_blob_id);
13568 else
13569 err = got_object_id_str(&id_str, blob_id);
13570 if (err)
13571 return err;
13573 printf("%s %c %s\n", id_str, staged_status, path);
13574 free(id_str);
13575 return NULL;
13578 static const struct got_error *
13579 cmd_stage(int argc, char *argv[])
13581 const struct got_error *error = NULL;
13582 struct got_repository *repo = NULL;
13583 struct got_worktree *worktree = NULL;
13584 char *cwd = NULL;
13585 struct got_pathlist_head paths;
13586 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13587 FILE *patch_script_file = NULL;
13588 const char *patch_script_path = NULL;
13589 struct choose_patch_arg cpa;
13590 int *pack_fds = NULL;
13592 TAILQ_INIT(&paths);
13594 #ifndef PROFILE
13595 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13596 "unveil", NULL) == -1)
13597 err(1, "pledge");
13598 #endif
13600 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13601 switch (ch) {
13602 case 'F':
13603 patch_script_path = optarg;
13604 break;
13605 case 'l':
13606 list_stage = 1;
13607 break;
13608 case 'p':
13609 pflag = 1;
13610 break;
13611 case 'S':
13612 allow_bad_symlinks = 1;
13613 break;
13614 default:
13615 usage_stage();
13616 /* NOTREACHED */
13620 argc -= optind;
13621 argv += optind;
13623 if (list_stage && (pflag || patch_script_path))
13624 errx(1, "-l option cannot be used with other options");
13625 if (patch_script_path && !pflag)
13626 errx(1, "-F option can only be used together with -p option");
13628 cwd = getcwd(NULL, 0);
13629 if (cwd == NULL) {
13630 error = got_error_from_errno("getcwd");
13631 goto done;
13634 error = got_repo_pack_fds_open(&pack_fds);
13635 if (error != NULL)
13636 goto done;
13638 error = got_worktree_open(&worktree, cwd);
13639 if (error) {
13640 if (error->code == GOT_ERR_NOT_WORKTREE)
13641 error = wrap_not_worktree_error(error, "stage", cwd);
13642 goto done;
13645 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13646 NULL, pack_fds);
13647 if (error != NULL)
13648 goto done;
13650 if (patch_script_path) {
13651 patch_script_file = fopen(patch_script_path, "re");
13652 if (patch_script_file == NULL) {
13653 error = got_error_from_errno2("fopen",
13654 patch_script_path);
13655 goto done;
13658 error = apply_unveil(got_repo_get_path(repo), 0,
13659 got_worktree_get_root_path(worktree));
13660 if (error)
13661 goto done;
13663 error = check_merge_in_progress(worktree, repo);
13664 if (error)
13665 goto done;
13667 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13668 if (error)
13669 goto done;
13671 if (list_stage)
13672 error = got_worktree_status(worktree, &paths, repo, 0,
13673 print_stage, NULL, check_cancelled, NULL);
13674 else {
13675 cpa.patch_script_file = patch_script_file;
13676 cpa.action = "stage";
13677 error = got_worktree_stage(worktree, &paths,
13678 pflag ? NULL : print_status, NULL,
13679 pflag ? choose_patch : NULL, &cpa,
13680 allow_bad_symlinks, repo);
13682 done:
13683 if (patch_script_file && fclose(patch_script_file) == EOF &&
13684 error == NULL)
13685 error = got_error_from_errno2("fclose", patch_script_path);
13686 if (repo) {
13687 const struct got_error *close_err = got_repo_close(repo);
13688 if (error == NULL)
13689 error = close_err;
13691 if (worktree)
13692 got_worktree_close(worktree);
13693 if (pack_fds) {
13694 const struct got_error *pack_err =
13695 got_repo_pack_fds_close(pack_fds);
13696 if (error == NULL)
13697 error = pack_err;
13699 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13700 free(cwd);
13701 return error;
13704 __dead static void
13705 usage_unstage(void)
13707 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13708 "[path ...]\n", getprogname());
13709 exit(1);
13713 static const struct got_error *
13714 cmd_unstage(int argc, char *argv[])
13716 const struct got_error *error = NULL;
13717 struct got_repository *repo = NULL;
13718 struct got_worktree *worktree = NULL;
13719 char *cwd = NULL;
13720 struct got_pathlist_head paths;
13721 int ch, pflag = 0;
13722 struct got_update_progress_arg upa;
13723 FILE *patch_script_file = NULL;
13724 const char *patch_script_path = NULL;
13725 struct choose_patch_arg cpa;
13726 int *pack_fds = NULL;
13728 TAILQ_INIT(&paths);
13730 #ifndef PROFILE
13731 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13732 "unveil", NULL) == -1)
13733 err(1, "pledge");
13734 #endif
13736 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13737 switch (ch) {
13738 case 'F':
13739 patch_script_path = optarg;
13740 break;
13741 case 'p':
13742 pflag = 1;
13743 break;
13744 default:
13745 usage_unstage();
13746 /* NOTREACHED */
13750 argc -= optind;
13751 argv += optind;
13753 if (patch_script_path && !pflag)
13754 errx(1, "-F option can only be used together with -p option");
13756 cwd = getcwd(NULL, 0);
13757 if (cwd == NULL) {
13758 error = got_error_from_errno("getcwd");
13759 goto done;
13762 error = got_repo_pack_fds_open(&pack_fds);
13763 if (error != NULL)
13764 goto done;
13766 error = got_worktree_open(&worktree, cwd);
13767 if (error) {
13768 if (error->code == GOT_ERR_NOT_WORKTREE)
13769 error = wrap_not_worktree_error(error, "unstage", cwd);
13770 goto done;
13773 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13774 NULL, pack_fds);
13775 if (error != NULL)
13776 goto done;
13778 if (patch_script_path) {
13779 patch_script_file = fopen(patch_script_path, "re");
13780 if (patch_script_file == NULL) {
13781 error = got_error_from_errno2("fopen",
13782 patch_script_path);
13783 goto done;
13787 error = apply_unveil(got_repo_get_path(repo), 0,
13788 got_worktree_get_root_path(worktree));
13789 if (error)
13790 goto done;
13792 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13793 if (error)
13794 goto done;
13796 cpa.patch_script_file = patch_script_file;
13797 cpa.action = "unstage";
13798 memset(&upa, 0, sizeof(upa));
13799 error = got_worktree_unstage(worktree, &paths, update_progress,
13800 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13801 if (!error)
13802 print_merge_progress_stats(&upa);
13803 done:
13804 if (patch_script_file && fclose(patch_script_file) == EOF &&
13805 error == NULL)
13806 error = got_error_from_errno2("fclose", patch_script_path);
13807 if (repo) {
13808 const struct got_error *close_err = got_repo_close(repo);
13809 if (error == NULL)
13810 error = close_err;
13812 if (worktree)
13813 got_worktree_close(worktree);
13814 if (pack_fds) {
13815 const struct got_error *pack_err =
13816 got_repo_pack_fds_close(pack_fds);
13817 if (error == NULL)
13818 error = pack_err;
13820 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13821 free(cwd);
13822 return error;
13825 __dead static void
13826 usage_cat(void)
13828 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13829 "arg ...\n", getprogname());
13830 exit(1);
13833 static const struct got_error *
13834 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13836 const struct got_error *err;
13837 struct got_blob_object *blob;
13838 int fd = -1;
13840 fd = got_opentempfd();
13841 if (fd == -1)
13842 return got_error_from_errno("got_opentempfd");
13844 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13845 if (err)
13846 goto done;
13848 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13849 done:
13850 if (fd != -1 && close(fd) == -1 && err == NULL)
13851 err = got_error_from_errno("close");
13852 if (blob)
13853 got_object_blob_close(blob);
13854 return err;
13857 static const struct got_error *
13858 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13860 const struct got_error *err;
13861 struct got_tree_object *tree;
13862 int nentries, i;
13864 err = got_object_open_as_tree(&tree, repo, id);
13865 if (err)
13866 return err;
13868 nentries = got_object_tree_get_nentries(tree);
13869 for (i = 0; i < nentries; i++) {
13870 struct got_tree_entry *te;
13871 char *id_str;
13872 if (sigint_received || sigpipe_received)
13873 break;
13874 te = got_object_tree_get_entry(tree, i);
13875 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13876 if (err)
13877 break;
13878 fprintf(outfile, "%s %.7o %s\n", id_str,
13879 got_tree_entry_get_mode(te),
13880 got_tree_entry_get_name(te));
13881 free(id_str);
13884 got_object_tree_close(tree);
13885 return err;
13888 static const struct got_error *
13889 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13891 const struct got_error *err;
13892 struct got_commit_object *commit;
13893 const struct got_object_id_queue *parent_ids;
13894 struct got_object_qid *pid;
13895 char *id_str = NULL;
13896 const char *logmsg = NULL;
13897 char gmtoff[6];
13899 err = got_object_open_as_commit(&commit, repo, id);
13900 if (err)
13901 return err;
13903 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13904 if (err)
13905 goto done;
13907 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13908 parent_ids = got_object_commit_get_parent_ids(commit);
13909 fprintf(outfile, "numparents %d\n",
13910 got_object_commit_get_nparents(commit));
13911 STAILQ_FOREACH(pid, parent_ids, entry) {
13912 char *pid_str;
13913 err = got_object_id_str(&pid_str, &pid->id);
13914 if (err)
13915 goto done;
13916 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13917 free(pid_str);
13919 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13920 got_object_commit_get_author_gmtoff(commit));
13921 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13922 got_object_commit_get_author(commit),
13923 (long long)got_object_commit_get_author_time(commit),
13924 gmtoff);
13926 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13927 got_object_commit_get_committer_gmtoff(commit));
13928 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13929 got_object_commit_get_committer(commit),
13930 (long long)got_object_commit_get_committer_time(commit),
13931 gmtoff);
13933 logmsg = got_object_commit_get_logmsg_raw(commit);
13934 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13935 fprintf(outfile, "%s", logmsg);
13936 done:
13937 free(id_str);
13938 got_object_commit_close(commit);
13939 return err;
13942 static const struct got_error *
13943 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13945 const struct got_error *err;
13946 struct got_tag_object *tag;
13947 char *id_str = NULL;
13948 const char *tagmsg = NULL;
13949 char gmtoff[6];
13951 err = got_object_open_as_tag(&tag, repo, id);
13952 if (err)
13953 return err;
13955 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13956 if (err)
13957 goto done;
13959 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13961 switch (got_object_tag_get_object_type(tag)) {
13962 case GOT_OBJ_TYPE_BLOB:
13963 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13964 GOT_OBJ_LABEL_BLOB);
13965 break;
13966 case GOT_OBJ_TYPE_TREE:
13967 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13968 GOT_OBJ_LABEL_TREE);
13969 break;
13970 case GOT_OBJ_TYPE_COMMIT:
13971 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13972 GOT_OBJ_LABEL_COMMIT);
13973 break;
13974 case GOT_OBJ_TYPE_TAG:
13975 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13976 GOT_OBJ_LABEL_TAG);
13977 break;
13978 default:
13979 break;
13982 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13983 got_object_tag_get_name(tag));
13985 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13986 got_object_tag_get_tagger_gmtoff(tag));
13987 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13988 got_object_tag_get_tagger(tag),
13989 (long long)got_object_tag_get_tagger_time(tag),
13990 gmtoff);
13992 tagmsg = got_object_tag_get_message(tag);
13993 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13994 fprintf(outfile, "%s", tagmsg);
13995 done:
13996 free(id_str);
13997 got_object_tag_close(tag);
13998 return err;
14001 static const struct got_error *
14002 cmd_cat(int argc, char *argv[])
14004 const struct got_error *error;
14005 struct got_repository *repo = NULL;
14006 struct got_worktree *worktree = NULL;
14007 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14008 const char *commit_id_str = NULL;
14009 struct got_object_id *id = NULL, *commit_id = NULL;
14010 struct got_commit_object *commit = NULL;
14011 int ch, obj_type, i, force_path = 0;
14012 struct got_reflist_head refs;
14013 int *pack_fds = NULL;
14015 TAILQ_INIT(&refs);
14017 #ifndef PROFILE
14018 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14019 NULL) == -1)
14020 err(1, "pledge");
14021 #endif
14023 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14024 switch (ch) {
14025 case 'c':
14026 commit_id_str = optarg;
14027 break;
14028 case 'P':
14029 force_path = 1;
14030 break;
14031 case 'r':
14032 repo_path = realpath(optarg, NULL);
14033 if (repo_path == NULL)
14034 return got_error_from_errno2("realpath",
14035 optarg);
14036 got_path_strip_trailing_slashes(repo_path);
14037 break;
14038 default:
14039 usage_cat();
14040 /* NOTREACHED */
14044 argc -= optind;
14045 argv += optind;
14047 cwd = getcwd(NULL, 0);
14048 if (cwd == NULL) {
14049 error = got_error_from_errno("getcwd");
14050 goto done;
14053 error = got_repo_pack_fds_open(&pack_fds);
14054 if (error != NULL)
14055 goto done;
14057 if (repo_path == NULL) {
14058 error = got_worktree_open(&worktree, cwd);
14059 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14060 goto done;
14061 if (worktree) {
14062 repo_path = strdup(
14063 got_worktree_get_repo_path(worktree));
14064 if (repo_path == NULL) {
14065 error = got_error_from_errno("strdup");
14066 goto done;
14069 /* Release work tree lock. */
14070 got_worktree_close(worktree);
14071 worktree = NULL;
14075 if (repo_path == NULL) {
14076 repo_path = strdup(cwd);
14077 if (repo_path == NULL)
14078 return got_error_from_errno("strdup");
14081 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14082 free(repo_path);
14083 if (error != NULL)
14084 goto done;
14086 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14087 if (error)
14088 goto done;
14090 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14091 if (error)
14092 goto done;
14094 if (commit_id_str == NULL)
14095 commit_id_str = GOT_REF_HEAD;
14096 error = got_repo_match_object_id(&commit_id, NULL,
14097 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14098 if (error)
14099 goto done;
14101 error = got_object_open_as_commit(&commit, repo, commit_id);
14102 if (error)
14103 goto done;
14105 for (i = 0; i < argc; i++) {
14106 if (force_path) {
14107 error = got_object_id_by_path(&id, repo, commit,
14108 argv[i]);
14109 if (error)
14110 break;
14111 } else {
14112 error = got_repo_match_object_id(&id, &label, argv[i],
14113 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14114 repo);
14115 if (error) {
14116 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14117 error->code != GOT_ERR_NOT_REF)
14118 break;
14119 error = got_object_id_by_path(&id, repo,
14120 commit, argv[i]);
14121 if (error)
14122 break;
14126 error = got_object_get_type(&obj_type, repo, id);
14127 if (error)
14128 break;
14130 switch (obj_type) {
14131 case GOT_OBJ_TYPE_BLOB:
14132 error = cat_blob(id, repo, stdout);
14133 break;
14134 case GOT_OBJ_TYPE_TREE:
14135 error = cat_tree(id, repo, stdout);
14136 break;
14137 case GOT_OBJ_TYPE_COMMIT:
14138 error = cat_commit(id, repo, stdout);
14139 break;
14140 case GOT_OBJ_TYPE_TAG:
14141 error = cat_tag(id, repo, stdout);
14142 break;
14143 default:
14144 error = got_error(GOT_ERR_OBJ_TYPE);
14145 break;
14147 if (error)
14148 break;
14149 free(label);
14150 label = NULL;
14151 free(id);
14152 id = NULL;
14154 done:
14155 free(label);
14156 free(id);
14157 free(commit_id);
14158 if (commit)
14159 got_object_commit_close(commit);
14160 if (worktree)
14161 got_worktree_close(worktree);
14162 if (repo) {
14163 const struct got_error *close_err = got_repo_close(repo);
14164 if (error == NULL)
14165 error = close_err;
14167 if (pack_fds) {
14168 const struct got_error *pack_err =
14169 got_repo_pack_fds_close(pack_fds);
14170 if (error == NULL)
14171 error = pack_err;
14174 got_ref_list_free(&refs);
14175 return error;
14178 __dead static void
14179 usage_info(void)
14181 fprintf(stderr, "usage: %s info [path ...]\n",
14182 getprogname());
14183 exit(1);
14186 static const struct got_error *
14187 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14188 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14189 struct got_object_id *commit_id)
14191 const struct got_error *err = NULL;
14192 char *id_str = NULL;
14193 char datebuf[128];
14194 struct tm mytm, *tm;
14195 struct got_pathlist_head *paths = arg;
14196 struct got_pathlist_entry *pe;
14199 * Clear error indication from any of the path arguments which
14200 * would cause this file index entry to be displayed.
14202 TAILQ_FOREACH(pe, paths, entry) {
14203 if (got_path_cmp(path, pe->path, strlen(path),
14204 pe->path_len) == 0 ||
14205 got_path_is_child(path, pe->path, pe->path_len))
14206 pe->data = NULL; /* no error */
14209 printf(GOT_COMMIT_SEP_STR);
14210 if (S_ISLNK(mode))
14211 printf("symlink: %s\n", path);
14212 else if (S_ISREG(mode)) {
14213 printf("file: %s\n", path);
14214 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14215 } else if (S_ISDIR(mode))
14216 printf("directory: %s\n", path);
14217 else
14218 printf("something: %s\n", path);
14220 tm = localtime_r(&mtime, &mytm);
14221 if (tm == NULL)
14222 return NULL;
14223 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14224 return got_error(GOT_ERR_NO_SPACE);
14225 printf("timestamp: %s\n", datebuf);
14227 if (blob_id) {
14228 err = got_object_id_str(&id_str, blob_id);
14229 if (err)
14230 return err;
14231 printf("based on blob: %s\n", id_str);
14232 free(id_str);
14235 if (staged_blob_id) {
14236 err = got_object_id_str(&id_str, staged_blob_id);
14237 if (err)
14238 return err;
14239 printf("based on staged blob: %s\n", id_str);
14240 free(id_str);
14243 if (commit_id) {
14244 err = got_object_id_str(&id_str, commit_id);
14245 if (err)
14246 return err;
14247 printf("based on commit: %s\n", id_str);
14248 free(id_str);
14251 return NULL;
14254 static const struct got_error *
14255 cmd_info(int argc, char *argv[])
14257 const struct got_error *error = NULL;
14258 struct got_worktree *worktree = NULL;
14259 char *cwd = NULL, *id_str = NULL;
14260 struct got_pathlist_head paths;
14261 char *uuidstr = NULL;
14262 int ch, show_files = 0;
14264 TAILQ_INIT(&paths);
14266 #ifndef PROFILE
14267 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14268 NULL) == -1)
14269 err(1, "pledge");
14270 #endif
14272 while ((ch = getopt(argc, argv, "")) != -1) {
14273 switch (ch) {
14274 default:
14275 usage_info();
14276 /* NOTREACHED */
14280 argc -= optind;
14281 argv += optind;
14283 cwd = getcwd(NULL, 0);
14284 if (cwd == NULL) {
14285 error = got_error_from_errno("getcwd");
14286 goto done;
14289 error = got_worktree_open(&worktree, cwd);
14290 if (error) {
14291 if (error->code == GOT_ERR_NOT_WORKTREE)
14292 error = wrap_not_worktree_error(error, "info", cwd);
14293 goto done;
14296 #ifndef PROFILE
14297 /* Remove "wpath cpath proc exec sendfd" promises. */
14298 if (pledge("stdio rpath flock unveil", NULL) == -1)
14299 err(1, "pledge");
14300 #endif
14301 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14302 if (error)
14303 goto done;
14305 if (argc >= 1) {
14306 error = get_worktree_paths_from_argv(&paths, argc, argv,
14307 worktree);
14308 if (error)
14309 goto done;
14310 show_files = 1;
14313 error = got_object_id_str(&id_str,
14314 got_worktree_get_base_commit_id(worktree));
14315 if (error)
14316 goto done;
14318 error = got_worktree_get_uuid(&uuidstr, worktree);
14319 if (error)
14320 goto done;
14322 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14323 printf("work tree base commit: %s\n", id_str);
14324 printf("work tree path prefix: %s\n",
14325 got_worktree_get_path_prefix(worktree));
14326 printf("work tree branch reference: %s\n",
14327 got_worktree_get_head_ref_name(worktree));
14328 printf("work tree UUID: %s\n", uuidstr);
14329 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14331 if (show_files) {
14332 struct got_pathlist_entry *pe;
14333 TAILQ_FOREACH(pe, &paths, entry) {
14334 if (pe->path_len == 0)
14335 continue;
14337 * Assume this path will fail. This will be corrected
14338 * in print_path_info() in case the path does suceeed.
14340 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14342 error = got_worktree_path_info(worktree, &paths,
14343 print_path_info, &paths, check_cancelled, NULL);
14344 if (error)
14345 goto done;
14346 TAILQ_FOREACH(pe, &paths, entry) {
14347 if (pe->data != NULL) {
14348 const struct got_error *perr;
14350 perr = pe->data;
14351 error = got_error_fmt(perr->code, "%s",
14352 pe->path);
14353 break;
14357 done:
14358 if (worktree)
14359 got_worktree_close(worktree);
14360 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14361 free(cwd);
14362 free(id_str);
14363 free(uuidstr);
14364 return error;