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, *keyword_idstr = 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;
3135 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3136 repo, worktree);
3137 if (error != NULL)
3138 goto done;
3139 if (keyword_idstr != NULL) {
3140 free(commit_id_str);
3141 commit_id_str = keyword_idstr;
3144 error = got_repo_match_object_id(&commit_id, NULL,
3145 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3146 got_ref_list_free(&refs);
3147 if (error)
3148 goto done;
3149 error = check_linear_ancestry(commit_id,
3150 got_worktree_get_base_commit_id(worktree), 0, repo);
3151 if (error != NULL) {
3152 if (error->code == GOT_ERR_ANCESTRY) {
3153 error = checkout_ancestry_error(
3154 head_ref, commit_id_str);
3156 goto done;
3158 error = check_same_branch(commit_id, head_ref, repo);
3159 if (error) {
3160 if (error->code == GOT_ERR_ANCESTRY) {
3161 error = checkout_ancestry_error(
3162 head_ref, commit_id_str);
3164 goto done;
3166 error = got_worktree_set_base_commit_id(worktree, repo,
3167 commit_id);
3168 if (error)
3169 goto done;
3170 /* Expand potentially abbreviated commit ID string. */
3171 free(commit_id_str);
3172 error = got_object_id_str(&commit_id_str, commit_id);
3173 if (error)
3174 goto done;
3175 } else {
3176 commit_id = got_object_id_dup(
3177 got_worktree_get_base_commit_id(worktree));
3178 if (commit_id == NULL) {
3179 error = got_error_from_errno("got_object_id_dup");
3180 goto done;
3182 error = got_object_id_str(&commit_id_str, commit_id);
3183 if (error)
3184 goto done;
3187 error = got_pathlist_append(&paths, "", NULL);
3188 if (error)
3189 goto done;
3190 cpa.worktree_path = worktree_path;
3191 cpa.had_base_commit_ref_error = 0;
3192 cpa.verbosity = verbosity;
3193 error = got_worktree_checkout_files(worktree, &paths, repo,
3194 checkout_progress, &cpa, check_cancelled, NULL);
3195 if (error != NULL)
3196 goto done;
3198 if (got_ref_is_symbolic(head_ref)) {
3199 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3200 if (error)
3201 goto done;
3202 refname = got_ref_get_name(ref);
3203 } else
3204 refname = got_ref_get_name(head_ref);
3205 printf("Checked out %s: %s\n", refname, commit_id_str);
3206 printf("Now shut up and hack\n");
3207 if (cpa.had_base_commit_ref_error)
3208 show_worktree_base_ref_warning();
3209 done:
3210 if (pack_fds) {
3211 const struct got_error *pack_err =
3212 got_repo_pack_fds_close(pack_fds);
3213 if (error == NULL)
3214 error = pack_err;
3216 if (head_ref)
3217 got_ref_close(head_ref);
3218 if (ref)
3219 got_ref_close(ref);
3220 if (repo) {
3221 const struct got_error *close_err = got_repo_close(repo);
3222 if (error == NULL)
3223 error = close_err;
3225 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3226 free(commit_id_str);
3227 free(commit_id);
3228 free(repo_path);
3229 free(worktree_path);
3230 free(cwd);
3231 return error;
3234 struct got_update_progress_arg {
3235 int did_something;
3236 int conflicts;
3237 int obstructed;
3238 int not_updated;
3239 int missing;
3240 int not_deleted;
3241 int unversioned;
3242 int verbosity;
3245 static void
3246 print_update_progress_stats(struct got_update_progress_arg *upa)
3248 if (!upa->did_something)
3249 return;
3251 if (upa->conflicts > 0)
3252 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3253 if (upa->obstructed > 0)
3254 printf("File paths obstructed by a non-regular file: %d\n",
3255 upa->obstructed);
3256 if (upa->not_updated > 0)
3257 printf("Files not updated because of existing merge "
3258 "conflicts: %d\n", upa->not_updated);
3262 * The meaning of some status codes differs between merge-style operations and
3263 * update operations. For example, the ! status code means "file was missing"
3264 * if changes were merged into the work tree, and "missing file was restored"
3265 * if the work tree was updated. This function should be used by any operation
3266 * which merges changes into the work tree without updating the work tree.
3268 static void
3269 print_merge_progress_stats(struct got_update_progress_arg *upa)
3271 if (!upa->did_something)
3272 return;
3274 if (upa->conflicts > 0)
3275 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3276 if (upa->obstructed > 0)
3277 printf("File paths obstructed by a non-regular file: %d\n",
3278 upa->obstructed);
3279 if (upa->missing > 0)
3280 printf("Files which had incoming changes but could not be "
3281 "found in the work tree: %d\n", upa->missing);
3282 if (upa->not_deleted > 0)
3283 printf("Files not deleted due to differences in deleted "
3284 "content: %d\n", upa->not_deleted);
3285 if (upa->unversioned > 0)
3286 printf("Files not merged because an unversioned file was "
3287 "found in the work tree: %d\n", upa->unversioned);
3290 __dead static void
3291 usage_update(void)
3293 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3294 "[path ...]\n", getprogname());
3295 exit(1);
3298 static const struct got_error *
3299 update_progress(void *arg, unsigned char status, const char *path)
3301 struct got_update_progress_arg *upa = arg;
3303 if (status == GOT_STATUS_EXISTS ||
3304 status == GOT_STATUS_BASE_REF_ERR)
3305 return NULL;
3307 upa->did_something = 1;
3309 /* Base commit bump happens silently. */
3310 if (status == GOT_STATUS_BUMP_BASE)
3311 return NULL;
3313 if (status == GOT_STATUS_CONFLICT)
3314 upa->conflicts++;
3315 if (status == GOT_STATUS_OBSTRUCTED)
3316 upa->obstructed++;
3317 if (status == GOT_STATUS_CANNOT_UPDATE)
3318 upa->not_updated++;
3319 if (status == GOT_STATUS_MISSING)
3320 upa->missing++;
3321 if (status == GOT_STATUS_CANNOT_DELETE)
3322 upa->not_deleted++;
3323 if (status == GOT_STATUS_UNVERSIONED)
3324 upa->unversioned++;
3326 while (path[0] == '/')
3327 path++;
3328 if (upa->verbosity >= 0)
3329 printf("%c %s\n", status, path);
3331 return NULL;
3334 static const struct got_error *
3335 switch_head_ref(struct got_reference *head_ref,
3336 struct got_object_id *commit_id, struct got_worktree *worktree,
3337 struct got_repository *repo)
3339 const struct got_error *err = NULL;
3340 char *base_id_str;
3341 int ref_has_moved = 0;
3343 /* Trivial case: switching between two different references. */
3344 if (strcmp(got_ref_get_name(head_ref),
3345 got_worktree_get_head_ref_name(worktree)) != 0) {
3346 printf("Switching work tree from %s to %s\n",
3347 got_worktree_get_head_ref_name(worktree),
3348 got_ref_get_name(head_ref));
3349 return got_worktree_set_head_ref(worktree, head_ref);
3352 err = check_linear_ancestry(commit_id,
3353 got_worktree_get_base_commit_id(worktree), 0, repo);
3354 if (err) {
3355 if (err->code != GOT_ERR_ANCESTRY)
3356 return err;
3357 ref_has_moved = 1;
3359 if (!ref_has_moved)
3360 return NULL;
3362 /* Switching to a rebased branch with the same reference name. */
3363 err = got_object_id_str(&base_id_str,
3364 got_worktree_get_base_commit_id(worktree));
3365 if (err)
3366 return err;
3367 printf("Reference %s now points at a different branch\n",
3368 got_worktree_get_head_ref_name(worktree));
3369 printf("Switching work tree from %s to %s\n", base_id_str,
3370 got_worktree_get_head_ref_name(worktree));
3371 return NULL;
3374 static const struct got_error *
3375 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3377 const struct got_error *err;
3378 int in_progress;
3380 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3381 if (err)
3382 return err;
3383 if (in_progress)
3384 return got_error(GOT_ERR_REBASING);
3386 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3387 if (err)
3388 return err;
3389 if (in_progress)
3390 return got_error(GOT_ERR_HISTEDIT_BUSY);
3392 return NULL;
3395 static const struct got_error *
3396 check_merge_in_progress(struct got_worktree *worktree,
3397 struct got_repository *repo)
3399 const struct got_error *err;
3400 int in_progress;
3402 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3403 if (err)
3404 return err;
3405 if (in_progress)
3406 return got_error(GOT_ERR_MERGE_BUSY);
3408 return NULL;
3411 static const struct got_error *
3412 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3413 char *argv[], struct got_worktree *worktree)
3415 const struct got_error *err = NULL;
3416 char *path;
3417 struct got_pathlist_entry *new;
3418 int i;
3420 if (argc == 0) {
3421 path = strdup("");
3422 if (path == NULL)
3423 return got_error_from_errno("strdup");
3424 return got_pathlist_append(paths, path, NULL);
3427 for (i = 0; i < argc; i++) {
3428 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3429 if (err)
3430 break;
3431 err = got_pathlist_insert(&new, paths, path, NULL);
3432 if (err || new == NULL /* duplicate */) {
3433 free(path);
3434 if (err)
3435 break;
3439 return err;
3442 static const struct got_error *
3443 wrap_not_worktree_error(const struct got_error *orig_err,
3444 const char *cmdname, const char *path)
3446 const struct got_error *err;
3447 struct got_repository *repo;
3448 static char msg[512];
3449 int *pack_fds = NULL;
3451 err = got_repo_pack_fds_open(&pack_fds);
3452 if (err)
3453 return err;
3455 err = got_repo_open(&repo, path, NULL, pack_fds);
3456 if (err)
3457 return orig_err;
3459 snprintf(msg, sizeof(msg),
3460 "'got %s' needs a work tree in addition to a git repository\n"
3461 "Work trees can be checked out from this Git repository with "
3462 "'got checkout'.\n"
3463 "The got(1) manual page contains more information.", cmdname);
3464 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3465 if (repo) {
3466 const struct got_error *close_err = got_repo_close(repo);
3467 if (err == NULL)
3468 err = close_err;
3470 if (pack_fds) {
3471 const struct got_error *pack_err =
3472 got_repo_pack_fds_close(pack_fds);
3473 if (err == NULL)
3474 err = pack_err;
3476 return err;
3479 static const struct got_error *
3480 cmd_update(int argc, char *argv[])
3482 const struct got_error *error = NULL;
3483 struct got_repository *repo = NULL;
3484 struct got_worktree *worktree = NULL;
3485 char *worktree_path = NULL;
3486 struct got_object_id *commit_id = NULL;
3487 char *commit_id_str = NULL;
3488 const char *branch_name = NULL;
3489 struct got_reference *head_ref = NULL;
3490 struct got_pathlist_head paths;
3491 struct got_pathlist_entry *pe;
3492 int ch, verbosity = 0;
3493 struct got_update_progress_arg upa;
3494 int *pack_fds = NULL;
3496 TAILQ_INIT(&paths);
3498 #ifndef PROFILE
3499 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3500 "unveil", NULL) == -1)
3501 err(1, "pledge");
3502 #endif
3504 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3505 switch (ch) {
3506 case 'b':
3507 branch_name = optarg;
3508 break;
3509 case 'c':
3510 commit_id_str = strdup(optarg);
3511 if (commit_id_str == NULL)
3512 return got_error_from_errno("strdup");
3513 break;
3514 case 'q':
3515 verbosity = -1;
3516 break;
3517 default:
3518 usage_update();
3519 /* NOTREACHED */
3523 argc -= optind;
3524 argv += optind;
3526 worktree_path = getcwd(NULL, 0);
3527 if (worktree_path == NULL) {
3528 error = got_error_from_errno("getcwd");
3529 goto done;
3532 error = got_repo_pack_fds_open(&pack_fds);
3533 if (error != NULL)
3534 goto done;
3536 error = got_worktree_open(&worktree, worktree_path);
3537 if (error) {
3538 if (error->code == GOT_ERR_NOT_WORKTREE)
3539 error = wrap_not_worktree_error(error, "update",
3540 worktree_path);
3541 goto done;
3544 error = check_rebase_or_histedit_in_progress(worktree);
3545 if (error)
3546 goto done;
3548 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3549 NULL, pack_fds);
3550 if (error != NULL)
3551 goto done;
3553 error = apply_unveil(got_repo_get_path(repo), 0,
3554 got_worktree_get_root_path(worktree));
3555 if (error)
3556 goto done;
3558 error = check_merge_in_progress(worktree, repo);
3559 if (error)
3560 goto done;
3562 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3563 if (error)
3564 goto done;
3566 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3567 got_worktree_get_head_ref_name(worktree), 0);
3568 if (error != NULL)
3569 goto done;
3570 if (commit_id_str == NULL) {
3571 error = got_ref_resolve(&commit_id, repo, head_ref);
3572 if (error != NULL)
3573 goto done;
3574 error = got_object_id_str(&commit_id_str, commit_id);
3575 if (error != NULL)
3576 goto done;
3577 } else {
3578 struct got_reflist_head refs;
3579 char *keyword_idstr = NULL;
3581 TAILQ_INIT(&refs);
3583 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3584 NULL);
3585 if (error)
3586 goto done;
3588 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3589 repo, worktree);
3590 if (error != NULL)
3591 goto done;
3592 if (keyword_idstr != NULL) {
3593 free(commit_id_str);
3594 commit_id_str = keyword_idstr;
3597 error = got_repo_match_object_id(&commit_id, NULL,
3598 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3599 got_ref_list_free(&refs);
3600 free(commit_id_str);
3601 commit_id_str = NULL;
3602 if (error)
3603 goto done;
3604 error = got_object_id_str(&commit_id_str, commit_id);
3605 if (error)
3606 goto done;
3609 if (branch_name) {
3610 struct got_object_id *head_commit_id;
3611 TAILQ_FOREACH(pe, &paths, entry) {
3612 if (pe->path_len == 0)
3613 continue;
3614 error = got_error_msg(GOT_ERR_BAD_PATH,
3615 "switching between branches requires that "
3616 "the entire work tree gets updated");
3617 goto done;
3619 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3620 if (error)
3621 goto done;
3622 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3623 repo);
3624 free(head_commit_id);
3625 if (error != NULL)
3626 goto done;
3627 error = check_same_branch(commit_id, head_ref, repo);
3628 if (error)
3629 goto done;
3630 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3631 if (error)
3632 goto done;
3633 } else {
3634 error = check_linear_ancestry(commit_id,
3635 got_worktree_get_base_commit_id(worktree), 0, repo);
3636 if (error != NULL) {
3637 if (error->code == GOT_ERR_ANCESTRY)
3638 error = got_error(GOT_ERR_BRANCH_MOVED);
3639 goto done;
3641 error = check_same_branch(commit_id, head_ref, repo);
3642 if (error)
3643 goto done;
3646 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3647 commit_id) != 0) {
3648 error = got_worktree_set_base_commit_id(worktree, repo,
3649 commit_id);
3650 if (error)
3651 goto done;
3654 memset(&upa, 0, sizeof(upa));
3655 upa.verbosity = verbosity;
3656 error = got_worktree_checkout_files(worktree, &paths, repo,
3657 update_progress, &upa, check_cancelled, NULL);
3658 if (error != NULL)
3659 goto done;
3661 if (upa.did_something) {
3662 printf("Updated to %s: %s\n",
3663 got_worktree_get_head_ref_name(worktree), commit_id_str);
3664 } else
3665 printf("Already up-to-date\n");
3667 print_update_progress_stats(&upa);
3668 done:
3669 if (pack_fds) {
3670 const struct got_error *pack_err =
3671 got_repo_pack_fds_close(pack_fds);
3672 if (error == NULL)
3673 error = pack_err;
3675 if (repo) {
3676 const struct got_error *close_err = got_repo_close(repo);
3677 if (error == NULL)
3678 error = close_err;
3680 free(worktree_path);
3681 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3682 free(commit_id);
3683 free(commit_id_str);
3684 return error;
3687 static const struct got_error *
3688 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3689 const char *path, int diff_context, int ignore_whitespace,
3690 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3691 struct got_repository *repo, FILE *outfile)
3693 const struct got_error *err = NULL;
3694 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3695 FILE *f1 = NULL, *f2 = NULL;
3696 int fd1 = -1, fd2 = -1;
3698 fd1 = got_opentempfd();
3699 if (fd1 == -1)
3700 return got_error_from_errno("got_opentempfd");
3701 fd2 = got_opentempfd();
3702 if (fd2 == -1) {
3703 err = got_error_from_errno("got_opentempfd");
3704 goto done;
3707 if (blob_id1) {
3708 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3709 fd1);
3710 if (err)
3711 goto done;
3714 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3715 if (err)
3716 goto done;
3718 f1 = got_opentemp();
3719 if (f1 == NULL) {
3720 err = got_error_from_errno("got_opentemp");
3721 goto done;
3723 f2 = got_opentemp();
3724 if (f2 == NULL) {
3725 err = got_error_from_errno("got_opentemp");
3726 goto done;
3729 while (path[0] == '/')
3730 path++;
3731 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3732 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3733 force_text_diff, dsa, outfile);
3734 done:
3735 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3736 err = got_error_from_errno("close");
3737 if (blob1)
3738 got_object_blob_close(blob1);
3739 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3740 err = got_error_from_errno("close");
3741 if (blob2)
3742 got_object_blob_close(blob2);
3743 if (f1 && fclose(f1) == EOF && err == NULL)
3744 err = got_error_from_errno("fclose");
3745 if (f2 && fclose(f2) == EOF && err == NULL)
3746 err = got_error_from_errno("fclose");
3747 return err;
3750 static const struct got_error *
3751 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3752 const char *path, int diff_context, int ignore_whitespace,
3753 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3754 struct got_repository *repo, FILE *outfile)
3756 const struct got_error *err = NULL;
3757 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3758 struct got_diff_blob_output_unidiff_arg arg;
3759 FILE *f1 = NULL, *f2 = NULL;
3760 int fd1 = -1, fd2 = -1;
3762 if (tree_id1) {
3763 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3764 if (err)
3765 goto done;
3766 fd1 = got_opentempfd();
3767 if (fd1 == -1) {
3768 err = got_error_from_errno("got_opentempfd");
3769 goto done;
3773 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3774 if (err)
3775 goto done;
3777 f1 = got_opentemp();
3778 if (f1 == NULL) {
3779 err = got_error_from_errno("got_opentemp");
3780 goto done;
3783 f2 = got_opentemp();
3784 if (f2 == NULL) {
3785 err = got_error_from_errno("got_opentemp");
3786 goto done;
3788 fd2 = got_opentempfd();
3789 if (fd2 == -1) {
3790 err = got_error_from_errno("got_opentempfd");
3791 goto done;
3793 arg.diff_context = diff_context;
3794 arg.ignore_whitespace = ignore_whitespace;
3795 arg.force_text_diff = force_text_diff;
3796 arg.diffstat = dsa;
3797 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3798 arg.outfile = outfile;
3799 arg.lines = NULL;
3800 arg.nlines = 0;
3801 while (path[0] == '/')
3802 path++;
3803 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3804 got_diff_blob_output_unidiff, &arg, 1);
3805 done:
3806 if (tree1)
3807 got_object_tree_close(tree1);
3808 if (tree2)
3809 got_object_tree_close(tree2);
3810 if (f1 && fclose(f1) == EOF && err == NULL)
3811 err = got_error_from_errno("fclose");
3812 if (f2 && fclose(f2) == EOF && err == NULL)
3813 err = got_error_from_errno("fclose");
3814 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3815 err = got_error_from_errno("close");
3816 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3817 err = got_error_from_errno("close");
3818 return err;
3821 static const struct got_error *
3822 get_changed_paths(struct got_pathlist_head *paths,
3823 struct got_commit_object *commit, struct got_repository *repo,
3824 struct got_diffstat_cb_arg *dsa)
3826 const struct got_error *err = NULL;
3827 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3828 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3829 struct got_object_qid *qid;
3830 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3831 FILE *f1 = NULL, *f2 = NULL;
3832 int fd1 = -1, fd2 = -1;
3834 if (dsa) {
3835 cb = got_diff_tree_compute_diffstat;
3837 f1 = got_opentemp();
3838 if (f1 == NULL) {
3839 err = got_error_from_errno("got_opentemp");
3840 goto done;
3842 f2 = got_opentemp();
3843 if (f2 == NULL) {
3844 err = got_error_from_errno("got_opentemp");
3845 goto done;
3847 fd1 = got_opentempfd();
3848 if (fd1 == -1) {
3849 err = got_error_from_errno("got_opentempfd");
3850 goto done;
3852 fd2 = got_opentempfd();
3853 if (fd2 == -1) {
3854 err = got_error_from_errno("got_opentempfd");
3855 goto done;
3859 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3860 if (qid != NULL) {
3861 struct got_commit_object *pcommit;
3862 err = got_object_open_as_commit(&pcommit, repo,
3863 &qid->id);
3864 if (err)
3865 return err;
3867 tree_id1 = got_object_id_dup(
3868 got_object_commit_get_tree_id(pcommit));
3869 if (tree_id1 == NULL) {
3870 got_object_commit_close(pcommit);
3871 return got_error_from_errno("got_object_id_dup");
3873 got_object_commit_close(pcommit);
3877 if (tree_id1) {
3878 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3879 if (err)
3880 goto done;
3883 tree_id2 = got_object_commit_get_tree_id(commit);
3884 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3885 if (err)
3886 goto done;
3888 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3889 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3890 done:
3891 if (tree1)
3892 got_object_tree_close(tree1);
3893 if (tree2)
3894 got_object_tree_close(tree2);
3895 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3896 err = got_error_from_errno("close");
3897 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3898 err = got_error_from_errno("close");
3899 if (f1 && fclose(f1) == EOF && err == NULL)
3900 err = got_error_from_errno("fclose");
3901 if (f2 && fclose(f2) == EOF && err == NULL)
3902 err = got_error_from_errno("fclose");
3903 free(tree_id1);
3904 return err;
3907 static const struct got_error *
3908 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3909 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3910 struct got_repository *repo, FILE *outfile)
3912 const struct got_error *err = NULL;
3913 struct got_commit_object *pcommit = NULL;
3914 char *id_str1 = NULL, *id_str2 = NULL;
3915 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3916 struct got_object_qid *qid;
3918 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3919 if (qid != NULL) {
3920 err = got_object_open_as_commit(&pcommit, repo,
3921 &qid->id);
3922 if (err)
3923 return err;
3924 err = got_object_id_str(&id_str1, &qid->id);
3925 if (err)
3926 goto done;
3929 err = got_object_id_str(&id_str2, id);
3930 if (err)
3931 goto done;
3933 if (path && path[0] != '\0') {
3934 int obj_type;
3935 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3936 if (err)
3937 goto done;
3938 if (pcommit) {
3939 err = got_object_id_by_path(&obj_id1, repo,
3940 pcommit, path);
3941 if (err) {
3942 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3943 free(obj_id2);
3944 goto done;
3948 err = got_object_get_type(&obj_type, repo, obj_id2);
3949 if (err) {
3950 free(obj_id2);
3951 goto done;
3953 fprintf(outfile,
3954 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3955 fprintf(outfile, "commit - %s\n",
3956 id_str1 ? id_str1 : "/dev/null");
3957 fprintf(outfile, "commit + %s\n", id_str2);
3958 switch (obj_type) {
3959 case GOT_OBJ_TYPE_BLOB:
3960 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3961 0, 0, dsa, repo, outfile);
3962 break;
3963 case GOT_OBJ_TYPE_TREE:
3964 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3965 0, 0, dsa, repo, outfile);
3966 break;
3967 default:
3968 err = got_error(GOT_ERR_OBJ_TYPE);
3969 break;
3971 free(obj_id1);
3972 free(obj_id2);
3973 } else {
3974 obj_id2 = got_object_commit_get_tree_id(commit);
3975 if (pcommit)
3976 obj_id1 = got_object_commit_get_tree_id(pcommit);
3977 fprintf(outfile,
3978 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3979 fprintf(outfile, "commit - %s\n",
3980 id_str1 ? id_str1 : "/dev/null");
3981 fprintf(outfile, "commit + %s\n", id_str2);
3982 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3983 dsa, repo, outfile);
3985 done:
3986 free(id_str1);
3987 free(id_str2);
3988 if (pcommit)
3989 got_object_commit_close(pcommit);
3990 return err;
3993 static char *
3994 get_datestr(time_t *time, char *datebuf)
3996 struct tm mytm, *tm;
3997 char *p, *s;
3999 tm = gmtime_r(time, &mytm);
4000 if (tm == NULL)
4001 return NULL;
4002 s = asctime_r(tm, datebuf);
4003 if (s == NULL)
4004 return NULL;
4005 p = strchr(s, '\n');
4006 if (p)
4007 *p = '\0';
4008 return s;
4011 static const struct got_error *
4012 match_commit(int *have_match, struct got_object_id *id,
4013 struct got_commit_object *commit, regex_t *regex)
4015 const struct got_error *err = NULL;
4016 regmatch_t regmatch;
4017 char *id_str = NULL, *logmsg = NULL;
4019 *have_match = 0;
4021 err = got_object_id_str(&id_str, id);
4022 if (err)
4023 return err;
4025 err = got_object_commit_get_logmsg(&logmsg, commit);
4026 if (err)
4027 goto done;
4029 if (regexec(regex, got_object_commit_get_author(commit), 1,
4030 &regmatch, 0) == 0 ||
4031 regexec(regex, got_object_commit_get_committer(commit), 1,
4032 &regmatch, 0) == 0 ||
4033 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4034 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4035 *have_match = 1;
4036 done:
4037 free(id_str);
4038 free(logmsg);
4039 return err;
4042 static void
4043 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4044 regex_t *regex)
4046 regmatch_t regmatch;
4047 struct got_pathlist_entry *pe;
4049 *have_match = 0;
4051 TAILQ_FOREACH(pe, changed_paths, entry) {
4052 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4053 *have_match = 1;
4054 break;
4059 static const struct got_error *
4060 match_patch(int *have_match, struct got_commit_object *commit,
4061 struct got_object_id *id, const char *path, int diff_context,
4062 struct got_repository *repo, regex_t *regex, FILE *f)
4064 const struct got_error *err = NULL;
4065 char *line = NULL;
4066 size_t linesize = 0;
4067 regmatch_t regmatch;
4069 *have_match = 0;
4071 err = got_opentemp_truncate(f);
4072 if (err)
4073 return err;
4075 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4076 if (err)
4077 goto done;
4079 if (fseeko(f, 0L, SEEK_SET) == -1) {
4080 err = got_error_from_errno("fseeko");
4081 goto done;
4084 while (getline(&line, &linesize, f) != -1) {
4085 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4086 *have_match = 1;
4087 break;
4090 done:
4091 free(line);
4092 return err;
4095 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4097 static const struct got_error*
4098 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4099 struct got_object_id *id, struct got_repository *repo,
4100 int local_only)
4102 static const struct got_error *err = NULL;
4103 struct got_reflist_entry *re;
4104 char *s;
4105 const char *name;
4107 *refs_str = NULL;
4109 TAILQ_FOREACH(re, refs, entry) {
4110 struct got_tag_object *tag = NULL;
4111 struct got_object_id *ref_id;
4112 int cmp;
4114 name = got_ref_get_name(re->ref);
4115 if (strcmp(name, GOT_REF_HEAD) == 0)
4116 continue;
4117 if (strncmp(name, "refs/", 5) == 0)
4118 name += 5;
4119 if (strncmp(name, "got/", 4) == 0)
4120 continue;
4121 if (strncmp(name, "heads/", 6) == 0)
4122 name += 6;
4123 if (strncmp(name, "remotes/", 8) == 0) {
4124 if (local_only)
4125 continue;
4126 name += 8;
4127 s = strstr(name, "/" GOT_REF_HEAD);
4128 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4129 continue;
4131 err = got_ref_resolve(&ref_id, repo, re->ref);
4132 if (err)
4133 break;
4134 if (strncmp(name, "tags/", 5) == 0) {
4135 err = got_object_open_as_tag(&tag, repo, ref_id);
4136 if (err) {
4137 if (err->code != GOT_ERR_OBJ_TYPE) {
4138 free(ref_id);
4139 break;
4141 /* Ref points at something other than a tag. */
4142 err = NULL;
4143 tag = NULL;
4146 cmp = got_object_id_cmp(tag ?
4147 got_object_tag_get_object_id(tag) : ref_id, id);
4148 free(ref_id);
4149 if (tag)
4150 got_object_tag_close(tag);
4151 if (cmp != 0)
4152 continue;
4153 s = *refs_str;
4154 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4155 s ? ", " : "", name) == -1) {
4156 err = got_error_from_errno("asprintf");
4157 free(s);
4158 *refs_str = NULL;
4159 break;
4161 free(s);
4164 return err;
4167 static const struct got_error *
4168 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4169 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4171 const struct got_error *err = NULL;
4172 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4173 char *comma, *s, *nl;
4174 struct got_reflist_head *refs;
4175 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4176 struct tm tm;
4177 time_t committer_time;
4179 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4180 if (refs) {
4181 err = build_refs_str(&ref_str, refs, id, repo, 1);
4182 if (err)
4183 return err;
4185 /* Display the first matching ref only. */
4186 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4187 *comma = '\0';
4190 if (ref_str == NULL) {
4191 err = got_object_id_str(&id_str, id);
4192 if (err)
4193 return err;
4196 committer_time = got_object_commit_get_committer_time(commit);
4197 if (gmtime_r(&committer_time, &tm) == NULL) {
4198 err = got_error_from_errno("gmtime_r");
4199 goto done;
4201 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4202 err = got_error(GOT_ERR_NO_SPACE);
4203 goto done;
4206 err = got_object_commit_get_logmsg(&logmsg0, commit);
4207 if (err)
4208 goto done;
4210 s = logmsg0;
4211 while (isspace((unsigned char)s[0]))
4212 s++;
4214 nl = strchr(s, '\n');
4215 if (nl) {
4216 *nl = '\0';
4219 if (ref_str)
4220 printf("%s%-7s %s\n", datebuf, ref_str, s);
4221 else
4222 printf("%s%.7s %s\n", datebuf, id_str, s);
4224 if (fflush(stdout) != 0 && err == NULL)
4225 err = got_error_from_errno("fflush");
4226 done:
4227 free(id_str);
4228 free(ref_str);
4229 free(logmsg0);
4230 return err;
4233 static const struct got_error *
4234 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4236 struct got_pathlist_entry *pe;
4238 if (header != NULL)
4239 printf("%s\n", header);
4241 TAILQ_FOREACH(pe, dsa->paths, entry) {
4242 struct got_diff_changed_path *cp = pe->data;
4243 int pad = dsa->max_path_len - pe->path_len + 1;
4245 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4246 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4248 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4249 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4250 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4252 if (fflush(stdout) != 0)
4253 return got_error_from_errno("fflush");
4255 return NULL;
4258 static const struct got_error *
4259 printfile(FILE *f)
4261 char buf[8192];
4262 size_t r;
4264 if (fseeko(f, 0L, SEEK_SET) == -1)
4265 return got_error_from_errno("fseek");
4267 for (;;) {
4268 r = fread(buf, 1, sizeof(buf), f);
4269 if (r == 0) {
4270 if (ferror(f))
4271 return got_error_from_errno("fread");
4272 if (feof(f))
4273 break;
4275 if (fwrite(buf, 1, r, stdout) != r)
4276 return got_ferror(stdout, GOT_ERR_IO);
4279 return NULL;
4282 static const struct got_error *
4283 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4284 struct got_repository *repo, const char *path,
4285 struct got_pathlist_head *changed_paths,
4286 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4287 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4288 const char *prefix)
4290 const struct got_error *err = NULL;
4291 FILE *f = NULL;
4292 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4293 char datebuf[26];
4294 time_t committer_time;
4295 const char *author, *committer;
4296 char *refs_str = NULL;
4298 err = got_object_id_str(&id_str, id);
4299 if (err)
4300 return err;
4302 if (custom_refs_str == NULL) {
4303 struct got_reflist_head *refs;
4304 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4305 if (refs) {
4306 err = build_refs_str(&refs_str, refs, id, repo, 0);
4307 if (err)
4308 goto done;
4312 printf(GOT_COMMIT_SEP_STR);
4313 if (custom_refs_str)
4314 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4315 custom_refs_str);
4316 else
4317 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4318 refs_str ? " (" : "", refs_str ? refs_str : "",
4319 refs_str ? ")" : "");
4320 free(id_str);
4321 id_str = NULL;
4322 free(refs_str);
4323 refs_str = NULL;
4324 printf("from: %s\n", got_object_commit_get_author(commit));
4325 author = got_object_commit_get_author(commit);
4326 committer = got_object_commit_get_committer(commit);
4327 if (strcmp(author, committer) != 0)
4328 printf("via: %s\n", committer);
4329 committer_time = got_object_commit_get_committer_time(commit);
4330 datestr = get_datestr(&committer_time, datebuf);
4331 if (datestr)
4332 printf("date: %s UTC\n", datestr);
4333 if (got_object_commit_get_nparents(commit) > 1) {
4334 const struct got_object_id_queue *parent_ids;
4335 struct got_object_qid *qid;
4336 int n = 1;
4337 parent_ids = got_object_commit_get_parent_ids(commit);
4338 STAILQ_FOREACH(qid, parent_ids, entry) {
4339 err = got_object_id_str(&id_str, &qid->id);
4340 if (err)
4341 goto done;
4342 printf("parent %d: %s\n", n++, id_str);
4343 free(id_str);
4344 id_str = NULL;
4348 err = got_object_commit_get_logmsg(&logmsg0, commit);
4349 if (err)
4350 goto done;
4352 logmsg = logmsg0;
4353 do {
4354 line = strsep(&logmsg, "\n");
4355 if (line)
4356 printf(" %s\n", line);
4357 } while (line);
4358 free(logmsg0);
4360 if (changed_paths && diffstat == NULL) {
4361 struct got_pathlist_entry *pe;
4363 TAILQ_FOREACH(pe, changed_paths, entry) {
4364 struct got_diff_changed_path *cp = pe->data;
4366 printf(" %c %s\n", cp->status, pe->path);
4368 printf("\n");
4370 if (show_patch) {
4371 if (diffstat) {
4372 f = got_opentemp();
4373 if (f == NULL) {
4374 err = got_error_from_errno("got_opentemp");
4375 goto done;
4379 err = print_patch(commit, id, path, diff_context, diffstat,
4380 repo, diffstat == NULL ? stdout : f);
4381 if (err)
4382 goto done;
4384 if (diffstat) {
4385 err = print_diffstat(diffstat, NULL);
4386 if (err)
4387 goto done;
4388 if (show_patch) {
4389 err = printfile(f);
4390 if (err)
4391 goto done;
4394 if (show_patch)
4395 printf("\n");
4397 if (fflush(stdout) != 0 && err == NULL)
4398 err = got_error_from_errno("fflush");
4399 done:
4400 if (f && fclose(f) == EOF && err == NULL)
4401 err = got_error_from_errno("fclose");
4402 free(id_str);
4403 free(refs_str);
4404 return err;
4407 static const struct got_error *
4408 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4409 struct got_repository *repo, const char *path, int show_changed_paths,
4410 int show_diffstat, int show_patch, const char *search_pattern,
4411 int diff_context, int limit, int log_branches, int reverse_display_order,
4412 struct got_reflist_object_id_map *refs_idmap, int one_line,
4413 FILE *tmpfile)
4415 const struct got_error *err;
4416 struct got_commit_graph *graph;
4417 regex_t regex;
4418 int have_match;
4419 struct got_object_id_queue reversed_commits;
4420 struct got_object_qid *qid;
4421 struct got_commit_object *commit;
4422 struct got_pathlist_head changed_paths;
4424 STAILQ_INIT(&reversed_commits);
4425 TAILQ_INIT(&changed_paths);
4427 if (search_pattern && regcomp(&regex, search_pattern,
4428 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4429 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4431 err = got_commit_graph_open(&graph, path, !log_branches);
4432 if (err)
4433 return err;
4434 err = got_commit_graph_iter_start(graph, root_id, repo,
4435 check_cancelled, NULL);
4436 if (err)
4437 goto done;
4438 for (;;) {
4439 struct got_object_id id;
4440 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4441 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4443 if (sigint_received || sigpipe_received)
4444 break;
4446 err = got_commit_graph_iter_next(&id, graph, repo,
4447 check_cancelled, NULL);
4448 if (err) {
4449 if (err->code == GOT_ERR_ITER_COMPLETED)
4450 err = NULL;
4451 break;
4454 err = got_object_open_as_commit(&commit, repo, &id);
4455 if (err)
4456 break;
4458 if ((show_changed_paths || (show_diffstat && !show_patch))
4459 && !reverse_display_order) {
4460 err = get_changed_paths(&changed_paths, commit, repo,
4461 show_diffstat ? &dsa : NULL);
4462 if (err)
4463 break;
4466 if (search_pattern) {
4467 err = match_commit(&have_match, &id, commit, &regex);
4468 if (err) {
4469 got_object_commit_close(commit);
4470 break;
4472 if (have_match == 0 && show_changed_paths)
4473 match_changed_paths(&have_match,
4474 &changed_paths, &regex);
4475 if (have_match == 0 && show_patch) {
4476 err = match_patch(&have_match, commit, &id,
4477 path, diff_context, repo, &regex, tmpfile);
4478 if (err)
4479 break;
4481 if (have_match == 0) {
4482 got_object_commit_close(commit);
4483 got_pathlist_free(&changed_paths,
4484 GOT_PATHLIST_FREE_ALL);
4485 continue;
4489 if (reverse_display_order) {
4490 err = got_object_qid_alloc(&qid, &id);
4491 if (err)
4492 break;
4493 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4494 got_object_commit_close(commit);
4495 } else {
4496 if (one_line)
4497 err = print_commit_oneline(commit, &id,
4498 repo, refs_idmap);
4499 else
4500 err = print_commit(commit, &id, repo, path,
4501 (show_changed_paths || show_diffstat) ?
4502 &changed_paths : NULL,
4503 show_diffstat ? &dsa : NULL, show_patch,
4504 diff_context, refs_idmap, NULL, NULL);
4505 got_object_commit_close(commit);
4506 if (err)
4507 break;
4509 if ((limit && --limit == 0) ||
4510 (end_id && got_object_id_cmp(&id, end_id) == 0))
4511 break;
4513 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4515 if (reverse_display_order) {
4516 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4517 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4518 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4520 err = got_object_open_as_commit(&commit, repo,
4521 &qid->id);
4522 if (err)
4523 break;
4524 if (show_changed_paths ||
4525 (show_diffstat && !show_patch)) {
4526 err = get_changed_paths(&changed_paths, commit,
4527 repo, show_diffstat ? &dsa : NULL);
4528 if (err)
4529 break;
4531 if (one_line)
4532 err = print_commit_oneline(commit, &qid->id,
4533 repo, refs_idmap);
4534 else
4535 err = print_commit(commit, &qid->id, repo, path,
4536 (show_changed_paths || show_diffstat) ?
4537 &changed_paths : NULL,
4538 show_diffstat ? &dsa : NULL, show_patch,
4539 diff_context, refs_idmap, NULL, NULL);
4540 got_object_commit_close(commit);
4541 if (err)
4542 break;
4543 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4546 done:
4547 while (!STAILQ_EMPTY(&reversed_commits)) {
4548 qid = STAILQ_FIRST(&reversed_commits);
4549 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4550 got_object_qid_free(qid);
4552 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4553 if (search_pattern)
4554 regfree(&regex);
4555 got_commit_graph_close(graph);
4556 return err;
4559 __dead static void
4560 usage_log(void)
4562 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4563 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4564 "[path]\n", getprogname());
4565 exit(1);
4568 static int
4569 get_default_log_limit(void)
4571 const char *got_default_log_limit;
4572 long long n;
4573 const char *errstr;
4575 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4576 if (got_default_log_limit == NULL)
4577 return 0;
4578 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4579 if (errstr != NULL)
4580 return 0;
4581 return n;
4584 static const struct got_error *
4585 cmd_log(int argc, char *argv[])
4587 const struct got_error *error;
4588 struct got_repository *repo = NULL;
4589 struct got_worktree *worktree = NULL;
4590 struct got_object_id *start_id = NULL, *end_id = NULL;
4591 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4592 const char *start_commit = NULL, *end_commit = NULL;
4593 const char *search_pattern = NULL;
4594 int diff_context = -1, ch;
4595 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4596 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4597 const char *errstr;
4598 struct got_reflist_head refs;
4599 struct got_reflist_object_id_map *refs_idmap = NULL;
4600 FILE *tmpfile = NULL;
4601 int *pack_fds = NULL;
4603 TAILQ_INIT(&refs);
4605 #ifndef PROFILE
4606 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4607 NULL)
4608 == -1)
4609 err(1, "pledge");
4610 #endif
4612 limit = get_default_log_limit();
4614 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4615 switch (ch) {
4616 case 'b':
4617 log_branches = 1;
4618 break;
4619 case 'C':
4620 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4621 &errstr);
4622 if (errstr != NULL)
4623 errx(1, "number of context lines is %s: %s",
4624 errstr, optarg);
4625 break;
4626 case 'c':
4627 start_commit = optarg;
4628 break;
4629 case 'd':
4630 show_diffstat = 1;
4631 break;
4632 case 'l':
4633 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4634 if (errstr != NULL)
4635 errx(1, "number of commits is %s: %s",
4636 errstr, optarg);
4637 break;
4638 case 'P':
4639 show_changed_paths = 1;
4640 break;
4641 case 'p':
4642 show_patch = 1;
4643 break;
4644 case 'R':
4645 reverse_display_order = 1;
4646 break;
4647 case 'r':
4648 repo_path = realpath(optarg, NULL);
4649 if (repo_path == NULL)
4650 return got_error_from_errno2("realpath",
4651 optarg);
4652 got_path_strip_trailing_slashes(repo_path);
4653 break;
4654 case 'S':
4655 search_pattern = optarg;
4656 break;
4657 case 's':
4658 one_line = 1;
4659 break;
4660 case 'x':
4661 end_commit = optarg;
4662 break;
4663 default:
4664 usage_log();
4665 /* NOTREACHED */
4669 argc -= optind;
4670 argv += optind;
4672 if (diff_context == -1)
4673 diff_context = 3;
4674 else if (!show_patch)
4675 errx(1, "-C requires -p");
4677 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4678 errx(1, "cannot use -s with -d, -p or -P");
4680 cwd = getcwd(NULL, 0);
4681 if (cwd == NULL) {
4682 error = got_error_from_errno("getcwd");
4683 goto done;
4686 error = got_repo_pack_fds_open(&pack_fds);
4687 if (error != NULL)
4688 goto done;
4690 if (repo_path == NULL) {
4691 error = got_worktree_open(&worktree, cwd);
4692 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4693 goto done;
4694 error = NULL;
4697 if (argc == 1) {
4698 if (worktree) {
4699 error = got_worktree_resolve_path(&path, worktree,
4700 argv[0]);
4701 if (error)
4702 goto done;
4703 } else {
4704 path = strdup(argv[0]);
4705 if (path == NULL) {
4706 error = got_error_from_errno("strdup");
4707 goto done;
4710 } else if (argc != 0)
4711 usage_log();
4713 if (repo_path == NULL) {
4714 repo_path = worktree ?
4715 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4717 if (repo_path == NULL) {
4718 error = got_error_from_errno("strdup");
4719 goto done;
4722 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4723 if (error != NULL)
4724 goto done;
4726 error = apply_unveil(got_repo_get_path(repo), 1,
4727 worktree ? got_worktree_get_root_path(worktree) : NULL);
4728 if (error)
4729 goto done;
4731 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4732 if (error)
4733 goto done;
4735 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4736 if (error)
4737 goto done;
4739 if (start_commit == NULL) {
4740 struct got_reference *head_ref;
4741 struct got_commit_object *commit = NULL;
4742 error = got_ref_open(&head_ref, repo,
4743 worktree ? got_worktree_get_head_ref_name(worktree)
4744 : GOT_REF_HEAD, 0);
4745 if (error != NULL)
4746 goto done;
4747 error = got_ref_resolve(&start_id, repo, head_ref);
4748 got_ref_close(head_ref);
4749 if (error != NULL)
4750 goto done;
4751 error = got_object_open_as_commit(&commit, repo,
4752 start_id);
4753 if (error != NULL)
4754 goto done;
4755 got_object_commit_close(commit);
4756 } else {
4757 char *keyword_idstr = NULL;
4759 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4760 repo, worktree);
4761 if (error != NULL)
4762 goto done;
4763 if (keyword_idstr != NULL)
4764 start_commit = keyword_idstr;
4766 error = got_repo_match_object_id(&start_id, NULL,
4767 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4768 free(keyword_idstr);
4769 if (error != NULL)
4770 goto done;
4772 if (end_commit != NULL) {
4773 error = got_repo_match_object_id(&end_id, NULL,
4774 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4775 if (error != NULL)
4776 goto done;
4779 if (worktree) {
4781 * If a path was specified on the command line it was resolved
4782 * to a path in the work tree above. Prepend the work tree's
4783 * path prefix to obtain the corresponding in-repository path.
4785 if (path) {
4786 const char *prefix;
4787 prefix = got_worktree_get_path_prefix(worktree);
4788 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4789 (path[0] != '\0') ? "/" : "", path) == -1) {
4790 error = got_error_from_errno("asprintf");
4791 goto done;
4794 } else
4795 error = got_repo_map_path(&in_repo_path, repo,
4796 path ? path : "");
4797 if (error != NULL)
4798 goto done;
4799 if (in_repo_path) {
4800 free(path);
4801 path = in_repo_path;
4804 if (worktree) {
4805 /* Release work tree lock. */
4806 got_worktree_close(worktree);
4807 worktree = NULL;
4810 if (search_pattern && show_patch) {
4811 tmpfile = got_opentemp();
4812 if (tmpfile == NULL) {
4813 error = got_error_from_errno("got_opentemp");
4814 goto done;
4818 error = print_commits(start_id, end_id, repo, path ? path : "",
4819 show_changed_paths, show_diffstat, show_patch, search_pattern,
4820 diff_context, limit, log_branches, reverse_display_order,
4821 refs_idmap, one_line, tmpfile);
4822 done:
4823 free(path);
4824 free(repo_path);
4825 free(cwd);
4826 free(start_id);
4827 free(end_id);
4828 if (worktree)
4829 got_worktree_close(worktree);
4830 if (repo) {
4831 const struct got_error *close_err = got_repo_close(repo);
4832 if (error == NULL)
4833 error = close_err;
4835 if (pack_fds) {
4836 const struct got_error *pack_err =
4837 got_repo_pack_fds_close(pack_fds);
4838 if (error == NULL)
4839 error = pack_err;
4841 if (refs_idmap)
4842 got_reflist_object_id_map_free(refs_idmap);
4843 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4844 error = got_error_from_errno("fclose");
4845 got_ref_list_free(&refs);
4846 return error;
4849 __dead static void
4850 usage_diff(void)
4852 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4853 "[-r repository-path] [object1 object2 | path ...]\n",
4854 getprogname());
4855 exit(1);
4858 struct print_diff_arg {
4859 struct got_repository *repo;
4860 struct got_worktree *worktree;
4861 struct got_diffstat_cb_arg *diffstat;
4862 int diff_context;
4863 const char *id_str;
4864 int header_shown;
4865 int diff_staged;
4866 enum got_diff_algorithm diff_algo;
4867 int ignore_whitespace;
4868 int force_text_diff;
4869 FILE *f1;
4870 FILE *f2;
4871 FILE *outfile;
4875 * Create a file which contains the target path of a symlink so we can feed
4876 * it as content to the diff engine.
4878 static const struct got_error *
4879 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4880 const char *abspath)
4882 const struct got_error *err = NULL;
4883 char target_path[PATH_MAX];
4884 ssize_t target_len, outlen;
4886 *fd = -1;
4888 if (dirfd != -1) {
4889 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4890 if (target_len == -1)
4891 return got_error_from_errno2("readlinkat", abspath);
4892 } else {
4893 target_len = readlink(abspath, target_path, PATH_MAX);
4894 if (target_len == -1)
4895 return got_error_from_errno2("readlink", abspath);
4898 *fd = got_opentempfd();
4899 if (*fd == -1)
4900 return got_error_from_errno("got_opentempfd");
4902 outlen = write(*fd, target_path, target_len);
4903 if (outlen == -1) {
4904 err = got_error_from_errno("got_opentempfd");
4905 goto done;
4908 if (lseek(*fd, 0, SEEK_SET) == -1) {
4909 err = got_error_from_errno2("lseek", abspath);
4910 goto done;
4912 done:
4913 if (err) {
4914 close(*fd);
4915 *fd = -1;
4917 return err;
4920 static const struct got_error *
4921 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4922 const char *path, struct got_object_id *blob_id,
4923 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4924 int dirfd, const char *de_name)
4926 struct print_diff_arg *a = arg;
4927 const struct got_error *err = NULL;
4928 struct got_blob_object *blob1 = NULL;
4929 int fd = -1, fd1 = -1, fd2 = -1;
4930 FILE *f2 = NULL;
4931 char *abspath = NULL, *label1 = NULL;
4932 struct stat sb;
4933 off_t size1 = 0;
4934 int f2_exists = 0;
4936 memset(&sb, 0, sizeof(sb));
4938 if (a->diff_staged) {
4939 if (staged_status != GOT_STATUS_MODIFY &&
4940 staged_status != GOT_STATUS_ADD &&
4941 staged_status != GOT_STATUS_DELETE)
4942 return NULL;
4943 } else {
4944 if (staged_status == GOT_STATUS_DELETE)
4945 return NULL;
4946 if (status == GOT_STATUS_NONEXISTENT)
4947 return got_error_set_errno(ENOENT, path);
4948 if (status != GOT_STATUS_MODIFY &&
4949 status != GOT_STATUS_ADD &&
4950 status != GOT_STATUS_DELETE &&
4951 status != GOT_STATUS_CONFLICT)
4952 return NULL;
4955 err = got_opentemp_truncate(a->f1);
4956 if (err)
4957 return got_error_from_errno("got_opentemp_truncate");
4958 err = got_opentemp_truncate(a->f2);
4959 if (err)
4960 return got_error_from_errno("got_opentemp_truncate");
4962 if (!a->header_shown) {
4963 if (fprintf(a->outfile, "diff %s%s\n",
4964 a->diff_staged ? "-s " : "",
4965 got_worktree_get_root_path(a->worktree)) < 0) {
4966 err = got_error_from_errno("fprintf");
4967 goto done;
4969 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4970 err = got_error_from_errno("fprintf");
4971 goto done;
4973 if (fprintf(a->outfile, "path + %s%s\n",
4974 got_worktree_get_root_path(a->worktree),
4975 a->diff_staged ? " (staged changes)" : "") < 0) {
4976 err = got_error_from_errno("fprintf");
4977 goto done;
4979 a->header_shown = 1;
4982 if (a->diff_staged) {
4983 const char *label1 = NULL, *label2 = NULL;
4984 switch (staged_status) {
4985 case GOT_STATUS_MODIFY:
4986 label1 = path;
4987 label2 = path;
4988 break;
4989 case GOT_STATUS_ADD:
4990 label2 = path;
4991 break;
4992 case GOT_STATUS_DELETE:
4993 label1 = path;
4994 break;
4995 default:
4996 return got_error(GOT_ERR_FILE_STATUS);
4998 fd1 = got_opentempfd();
4999 if (fd1 == -1) {
5000 err = got_error_from_errno("got_opentempfd");
5001 goto done;
5003 fd2 = got_opentempfd();
5004 if (fd2 == -1) {
5005 err = got_error_from_errno("got_opentempfd");
5006 goto done;
5008 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5009 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5010 a->diff_algo, a->diff_context, a->ignore_whitespace,
5011 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5012 goto done;
5015 fd1 = got_opentempfd();
5016 if (fd1 == -1) {
5017 err = got_error_from_errno("got_opentempfd");
5018 goto done;
5021 if (staged_status == GOT_STATUS_ADD ||
5022 staged_status == GOT_STATUS_MODIFY) {
5023 char *id_str;
5024 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5025 8192, fd1);
5026 if (err)
5027 goto done;
5028 err = got_object_id_str(&id_str, staged_blob_id);
5029 if (err)
5030 goto done;
5031 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5032 err = got_error_from_errno("asprintf");
5033 free(id_str);
5034 goto done;
5036 free(id_str);
5037 } else if (status != GOT_STATUS_ADD) {
5038 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5039 fd1);
5040 if (err)
5041 goto done;
5044 if (status != GOT_STATUS_DELETE) {
5045 if (asprintf(&abspath, "%s/%s",
5046 got_worktree_get_root_path(a->worktree), path) == -1) {
5047 err = got_error_from_errno("asprintf");
5048 goto done;
5051 if (dirfd != -1) {
5052 fd = openat(dirfd, de_name,
5053 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5054 if (fd == -1) {
5055 if (!got_err_open_nofollow_on_symlink()) {
5056 err = got_error_from_errno2("openat",
5057 abspath);
5058 goto done;
5060 err = get_symlink_target_file(&fd, dirfd,
5061 de_name, abspath);
5062 if (err)
5063 goto done;
5065 } else {
5066 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5067 if (fd == -1) {
5068 if (!got_err_open_nofollow_on_symlink()) {
5069 err = got_error_from_errno2("open",
5070 abspath);
5071 goto done;
5073 err = get_symlink_target_file(&fd, dirfd,
5074 de_name, abspath);
5075 if (err)
5076 goto done;
5079 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5080 err = got_error_from_errno2("fstatat", abspath);
5081 goto done;
5083 f2 = fdopen(fd, "r");
5084 if (f2 == NULL) {
5085 err = got_error_from_errno2("fdopen", abspath);
5086 goto done;
5088 fd = -1;
5089 f2_exists = 1;
5092 if (blob1) {
5093 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5094 a->f1, blob1);
5095 if (err)
5096 goto done;
5099 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5100 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5101 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5102 done:
5103 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5104 err = got_error_from_errno("close");
5105 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5106 err = got_error_from_errno("close");
5107 if (blob1)
5108 got_object_blob_close(blob1);
5109 if (fd != -1 && close(fd) == -1 && err == NULL)
5110 err = got_error_from_errno("close");
5111 if (f2 && fclose(f2) == EOF && err == NULL)
5112 err = got_error_from_errno("fclose");
5113 free(abspath);
5114 return err;
5117 static const struct got_error *
5118 cmd_diff(int argc, char *argv[])
5120 const struct got_error *error;
5121 struct got_repository *repo = NULL;
5122 struct got_worktree *worktree = NULL;
5123 char *cwd = NULL, *repo_path = NULL;
5124 const char *commit_args[2] = { NULL, NULL };
5125 int ncommit_args = 0;
5126 struct got_object_id *ids[2] = { NULL, NULL };
5127 char *labels[2] = { NULL, NULL };
5128 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5129 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5130 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5131 const char *errstr;
5132 struct got_reflist_head refs;
5133 struct got_pathlist_head diffstat_paths, paths;
5134 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5135 int fd1 = -1, fd2 = -1;
5136 int *pack_fds = NULL;
5137 struct got_diffstat_cb_arg dsa;
5139 memset(&dsa, 0, sizeof(dsa));
5141 TAILQ_INIT(&refs);
5142 TAILQ_INIT(&paths);
5143 TAILQ_INIT(&diffstat_paths);
5145 #ifndef PROFILE
5146 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5147 NULL) == -1)
5148 err(1, "pledge");
5149 #endif
5151 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5152 switch (ch) {
5153 case 'a':
5154 force_text_diff = 1;
5155 break;
5156 case 'C':
5157 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5158 &errstr);
5159 if (errstr != NULL)
5160 errx(1, "number of context lines is %s: %s",
5161 errstr, optarg);
5162 break;
5163 case 'c':
5164 if (ncommit_args >= 2)
5165 errx(1, "too many -c options used");
5166 commit_args[ncommit_args++] = optarg;
5167 break;
5168 case 'd':
5169 show_diffstat = 1;
5170 break;
5171 case 'P':
5172 force_path = 1;
5173 break;
5174 case 'r':
5175 repo_path = realpath(optarg, NULL);
5176 if (repo_path == NULL)
5177 return got_error_from_errno2("realpath",
5178 optarg);
5179 got_path_strip_trailing_slashes(repo_path);
5180 rflag = 1;
5181 break;
5182 case 's':
5183 diff_staged = 1;
5184 break;
5185 case 'w':
5186 ignore_whitespace = 1;
5187 break;
5188 default:
5189 usage_diff();
5190 /* NOTREACHED */
5194 argc -= optind;
5195 argv += optind;
5197 cwd = getcwd(NULL, 0);
5198 if (cwd == NULL) {
5199 error = got_error_from_errno("getcwd");
5200 goto done;
5203 error = got_repo_pack_fds_open(&pack_fds);
5204 if (error != NULL)
5205 goto done;
5207 if (repo_path == NULL) {
5208 error = got_worktree_open(&worktree, cwd);
5209 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5210 goto done;
5211 else
5212 error = NULL;
5213 if (worktree) {
5214 repo_path =
5215 strdup(got_worktree_get_repo_path(worktree));
5216 if (repo_path == NULL) {
5217 error = got_error_from_errno("strdup");
5218 goto done;
5220 } else {
5221 repo_path = strdup(cwd);
5222 if (repo_path == NULL) {
5223 error = got_error_from_errno("strdup");
5224 goto done;
5229 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5230 free(repo_path);
5231 if (error != NULL)
5232 goto done;
5234 if (show_diffstat) {
5235 dsa.paths = &diffstat_paths;
5236 dsa.force_text = force_text_diff;
5237 dsa.ignore_ws = ignore_whitespace;
5238 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5241 if (rflag || worktree == NULL || ncommit_args > 0) {
5242 if (force_path) {
5243 error = got_error_msg(GOT_ERR_NOT_IMPL,
5244 "-P option can only be used when diffing "
5245 "a work tree");
5246 goto done;
5248 if (diff_staged) {
5249 error = got_error_msg(GOT_ERR_NOT_IMPL,
5250 "-s option can only be used when diffing "
5251 "a work tree");
5252 goto done;
5256 error = apply_unveil(got_repo_get_path(repo), 1,
5257 worktree ? got_worktree_get_root_path(worktree) : NULL);
5258 if (error)
5259 goto done;
5261 if ((!force_path && argc == 2) || ncommit_args > 0) {
5262 int obj_type = (ncommit_args > 0 ?
5263 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5264 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5265 NULL);
5266 if (error)
5267 goto done;
5268 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5269 const char *arg;
5270 char *keyword_idstr = NULL;
5272 if (ncommit_args > 0)
5273 arg = commit_args[i];
5274 else
5275 arg = argv[i];
5277 error = got_keyword_to_idstr(&keyword_idstr, arg,
5278 repo, worktree);
5279 if (error != NULL)
5280 goto done;
5281 if (keyword_idstr != NULL)
5282 arg = keyword_idstr;
5284 error = got_repo_match_object_id(&ids[i], &labels[i],
5285 arg, obj_type, &refs, repo);
5286 free(keyword_idstr);
5287 if (error) {
5288 if (error->code != GOT_ERR_NOT_REF &&
5289 error->code != GOT_ERR_NO_OBJ)
5290 goto done;
5291 if (ncommit_args > 0)
5292 goto done;
5293 error = NULL;
5294 break;
5299 f1 = got_opentemp();
5300 if (f1 == NULL) {
5301 error = got_error_from_errno("got_opentemp");
5302 goto done;
5305 f2 = got_opentemp();
5306 if (f2 == NULL) {
5307 error = got_error_from_errno("got_opentemp");
5308 goto done;
5311 outfile = got_opentemp();
5312 if (outfile == NULL) {
5313 error = got_error_from_errno("got_opentemp");
5314 goto done;
5317 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5318 struct print_diff_arg arg;
5319 char *id_str;
5321 if (worktree == NULL) {
5322 if (argc == 2 && ids[0] == NULL) {
5323 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5324 goto done;
5325 } else if (argc == 2 && ids[1] == NULL) {
5326 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5327 goto done;
5328 } else if (argc > 0) {
5329 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5330 "%s", "specified paths cannot be resolved");
5331 goto done;
5332 } else {
5333 error = got_error(GOT_ERR_NOT_WORKTREE);
5334 goto done;
5338 error = get_worktree_paths_from_argv(&paths, argc, argv,
5339 worktree);
5340 if (error)
5341 goto done;
5343 error = got_object_id_str(&id_str,
5344 got_worktree_get_base_commit_id(worktree));
5345 if (error)
5346 goto done;
5347 arg.repo = repo;
5348 arg.worktree = worktree;
5349 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5350 arg.diff_context = diff_context;
5351 arg.id_str = id_str;
5352 arg.header_shown = 0;
5353 arg.diff_staged = diff_staged;
5354 arg.ignore_whitespace = ignore_whitespace;
5355 arg.force_text_diff = force_text_diff;
5356 arg.diffstat = show_diffstat ? &dsa : NULL;
5357 arg.f1 = f1;
5358 arg.f2 = f2;
5359 arg.outfile = outfile;
5361 error = got_worktree_status(worktree, &paths, repo, 0,
5362 print_diff, &arg, check_cancelled, NULL);
5363 free(id_str);
5364 if (error)
5365 goto done;
5367 if (show_diffstat && dsa.nfiles > 0) {
5368 char *header;
5370 if (asprintf(&header, "diffstat %s%s",
5371 diff_staged ? "-s " : "",
5372 got_worktree_get_root_path(worktree)) == -1) {
5373 error = got_error_from_errno("asprintf");
5374 goto done;
5377 error = print_diffstat(&dsa, header);
5378 free(header);
5379 if (error)
5380 goto done;
5383 error = printfile(outfile);
5384 goto done;
5387 if (ncommit_args == 1) {
5388 struct got_commit_object *commit;
5389 error = got_object_open_as_commit(&commit, repo, ids[0]);
5390 if (error)
5391 goto done;
5393 labels[1] = labels[0];
5394 ids[1] = ids[0];
5395 if (got_object_commit_get_nparents(commit) > 0) {
5396 const struct got_object_id_queue *pids;
5397 struct got_object_qid *pid;
5398 pids = got_object_commit_get_parent_ids(commit);
5399 pid = STAILQ_FIRST(pids);
5400 ids[0] = got_object_id_dup(&pid->id);
5401 if (ids[0] == NULL) {
5402 error = got_error_from_errno(
5403 "got_object_id_dup");
5404 got_object_commit_close(commit);
5405 goto done;
5407 error = got_object_id_str(&labels[0], ids[0]);
5408 if (error) {
5409 got_object_commit_close(commit);
5410 goto done;
5412 } else {
5413 ids[0] = NULL;
5414 labels[0] = strdup("/dev/null");
5415 if (labels[0] == NULL) {
5416 error = got_error_from_errno("strdup");
5417 got_object_commit_close(commit);
5418 goto done;
5422 got_object_commit_close(commit);
5425 if (ncommit_args == 0 && argc > 2) {
5426 error = got_error_msg(GOT_ERR_BAD_PATH,
5427 "path arguments cannot be used when diffing two objects");
5428 goto done;
5431 if (ids[0]) {
5432 error = got_object_get_type(&type1, repo, ids[0]);
5433 if (error)
5434 goto done;
5437 error = got_object_get_type(&type2, repo, ids[1]);
5438 if (error)
5439 goto done;
5440 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5441 error = got_error(GOT_ERR_OBJ_TYPE);
5442 goto done;
5444 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5445 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5446 "path arguments cannot be used when diffing blobs");
5447 goto done;
5450 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5451 char *in_repo_path;
5452 struct got_pathlist_entry *new;
5453 if (worktree) {
5454 const char *prefix;
5455 char *p;
5456 error = got_worktree_resolve_path(&p, worktree,
5457 argv[i]);
5458 if (error)
5459 goto done;
5460 prefix = got_worktree_get_path_prefix(worktree);
5461 while (prefix[0] == '/')
5462 prefix++;
5463 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5464 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5465 p) == -1) {
5466 error = got_error_from_errno("asprintf");
5467 free(p);
5468 goto done;
5470 free(p);
5471 } else {
5472 char *mapped_path, *s;
5473 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5474 if (error)
5475 goto done;
5476 s = mapped_path;
5477 while (s[0] == '/')
5478 s++;
5479 in_repo_path = strdup(s);
5480 if (in_repo_path == NULL) {
5481 error = got_error_from_errno("asprintf");
5482 free(mapped_path);
5483 goto done;
5485 free(mapped_path);
5488 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5489 if (error || new == NULL /* duplicate */)
5490 free(in_repo_path);
5491 if (error)
5492 goto done;
5495 if (worktree) {
5496 /* Release work tree lock. */
5497 got_worktree_close(worktree);
5498 worktree = NULL;
5501 fd1 = got_opentempfd();
5502 if (fd1 == -1) {
5503 error = got_error_from_errno("got_opentempfd");
5504 goto done;
5507 fd2 = got_opentempfd();
5508 if (fd2 == -1) {
5509 error = got_error_from_errno("got_opentempfd");
5510 goto done;
5513 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5514 case GOT_OBJ_TYPE_BLOB:
5515 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5516 fd1, fd2, ids[0], ids[1], NULL, NULL,
5517 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5518 ignore_whitespace, force_text_diff,
5519 show_diffstat ? &dsa : NULL, repo, outfile);
5520 break;
5521 case GOT_OBJ_TYPE_TREE:
5522 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5523 ids[0], ids[1], &paths, "", "",
5524 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5525 ignore_whitespace, force_text_diff,
5526 show_diffstat ? &dsa : NULL, repo, outfile);
5527 break;
5528 case GOT_OBJ_TYPE_COMMIT:
5529 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5530 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5531 fd1, fd2, ids[0], ids[1], &paths,
5532 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5533 ignore_whitespace, force_text_diff,
5534 show_diffstat ? &dsa : NULL, repo, outfile);
5535 break;
5536 default:
5537 error = got_error(GOT_ERR_OBJ_TYPE);
5539 if (error)
5540 goto done;
5542 if (show_diffstat && dsa.nfiles > 0) {
5543 char *header = NULL;
5545 if (asprintf(&header, "diffstat %s %s",
5546 labels[0], labels[1]) == -1) {
5547 error = got_error_from_errno("asprintf");
5548 goto done;
5551 error = print_diffstat(&dsa, header);
5552 free(header);
5553 if (error)
5554 goto done;
5557 error = printfile(outfile);
5559 done:
5560 free(labels[0]);
5561 free(labels[1]);
5562 free(ids[0]);
5563 free(ids[1]);
5564 if (worktree)
5565 got_worktree_close(worktree);
5566 if (repo) {
5567 const struct got_error *close_err = got_repo_close(repo);
5568 if (error == NULL)
5569 error = close_err;
5571 if (pack_fds) {
5572 const struct got_error *pack_err =
5573 got_repo_pack_fds_close(pack_fds);
5574 if (error == NULL)
5575 error = pack_err;
5577 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5578 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5579 got_ref_list_free(&refs);
5580 if (outfile && fclose(outfile) == EOF && error == NULL)
5581 error = got_error_from_errno("fclose");
5582 if (f1 && fclose(f1) == EOF && error == NULL)
5583 error = got_error_from_errno("fclose");
5584 if (f2 && fclose(f2) == EOF && error == NULL)
5585 error = got_error_from_errno("fclose");
5586 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5587 error = got_error_from_errno("close");
5588 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5589 error = got_error_from_errno("close");
5590 return error;
5593 __dead static void
5594 usage_blame(void)
5596 fprintf(stderr,
5597 "usage: %s blame [-c commit] [-r repository-path] path\n",
5598 getprogname());
5599 exit(1);
5602 struct blame_line {
5603 int annotated;
5604 char *id_str;
5605 char *committer;
5606 char datebuf[11]; /* YYYY-MM-DD + NUL */
5609 struct blame_cb_args {
5610 struct blame_line *lines;
5611 int nlines;
5612 int nlines_prec;
5613 int lineno_cur;
5614 off_t *line_offsets;
5615 FILE *f;
5616 struct got_repository *repo;
5619 static const struct got_error *
5620 blame_cb(void *arg, int nlines, int lineno,
5621 struct got_commit_object *commit, struct got_object_id *id)
5623 const struct got_error *err = NULL;
5624 struct blame_cb_args *a = arg;
5625 struct blame_line *bline;
5626 char *line = NULL;
5627 size_t linesize = 0;
5628 off_t offset;
5629 struct tm tm;
5630 time_t committer_time;
5632 if (nlines != a->nlines ||
5633 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5634 return got_error(GOT_ERR_RANGE);
5636 if (sigint_received)
5637 return got_error(GOT_ERR_ITER_COMPLETED);
5639 if (lineno == -1)
5640 return NULL; /* no change in this commit */
5642 /* Annotate this line. */
5643 bline = &a->lines[lineno - 1];
5644 if (bline->annotated)
5645 return NULL;
5646 err = got_object_id_str(&bline->id_str, id);
5647 if (err)
5648 return err;
5650 bline->committer = strdup(got_object_commit_get_committer(commit));
5651 if (bline->committer == NULL) {
5652 err = got_error_from_errno("strdup");
5653 goto done;
5656 committer_time = got_object_commit_get_committer_time(commit);
5657 if (gmtime_r(&committer_time, &tm) == NULL)
5658 return got_error_from_errno("gmtime_r");
5659 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5660 &tm) == 0) {
5661 err = got_error(GOT_ERR_NO_SPACE);
5662 goto done;
5664 bline->annotated = 1;
5666 /* Print lines annotated so far. */
5667 bline = &a->lines[a->lineno_cur - 1];
5668 if (!bline->annotated)
5669 goto done;
5671 offset = a->line_offsets[a->lineno_cur - 1];
5672 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5673 err = got_error_from_errno("fseeko");
5674 goto done;
5677 while (a->lineno_cur <= a->nlines && bline->annotated) {
5678 char *smallerthan, *at, *nl, *committer;
5679 size_t len;
5681 if (getline(&line, &linesize, a->f) == -1) {
5682 if (ferror(a->f))
5683 err = got_error_from_errno("getline");
5684 break;
5687 committer = bline->committer;
5688 smallerthan = strchr(committer, '<');
5689 if (smallerthan && smallerthan[1] != '\0')
5690 committer = smallerthan + 1;
5691 at = strchr(committer, '@');
5692 if (at)
5693 *at = '\0';
5694 len = strlen(committer);
5695 if (len >= 9)
5696 committer[8] = '\0';
5698 nl = strchr(line, '\n');
5699 if (nl)
5700 *nl = '\0';
5701 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5702 bline->id_str, bline->datebuf, committer, line);
5704 a->lineno_cur++;
5705 bline = &a->lines[a->lineno_cur - 1];
5707 done:
5708 free(line);
5709 return err;
5712 static const struct got_error *
5713 cmd_blame(int argc, char *argv[])
5715 const struct got_error *error;
5716 struct got_repository *repo = NULL;
5717 struct got_worktree *worktree = NULL;
5718 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5719 char *link_target = NULL;
5720 struct got_object_id *obj_id = NULL;
5721 struct got_object_id *commit_id = NULL;
5722 struct got_commit_object *commit = NULL;
5723 struct got_blob_object *blob = NULL;
5724 char *commit_id_str = NULL, *keyword_idstr = NULL;
5725 struct blame_cb_args bca;
5726 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5727 off_t filesize;
5728 int *pack_fds = NULL;
5729 FILE *f1 = NULL, *f2 = NULL;
5731 fd1 = got_opentempfd();
5732 if (fd1 == -1)
5733 return got_error_from_errno("got_opentempfd");
5735 memset(&bca, 0, sizeof(bca));
5737 #ifndef PROFILE
5738 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5739 NULL) == -1)
5740 err(1, "pledge");
5741 #endif
5743 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5744 switch (ch) {
5745 case 'c':
5746 commit_id_str = optarg;
5747 break;
5748 case 'r':
5749 repo_path = realpath(optarg, NULL);
5750 if (repo_path == NULL)
5751 return got_error_from_errno2("realpath",
5752 optarg);
5753 got_path_strip_trailing_slashes(repo_path);
5754 break;
5755 default:
5756 usage_blame();
5757 /* NOTREACHED */
5761 argc -= optind;
5762 argv += optind;
5764 if (argc == 1)
5765 path = argv[0];
5766 else
5767 usage_blame();
5769 cwd = getcwd(NULL, 0);
5770 if (cwd == NULL) {
5771 error = got_error_from_errno("getcwd");
5772 goto done;
5775 error = got_repo_pack_fds_open(&pack_fds);
5776 if (error != NULL)
5777 goto done;
5779 if (repo_path == NULL) {
5780 error = got_worktree_open(&worktree, cwd);
5781 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5782 goto done;
5783 else
5784 error = NULL;
5785 if (worktree) {
5786 repo_path =
5787 strdup(got_worktree_get_repo_path(worktree));
5788 if (repo_path == NULL) {
5789 error = got_error_from_errno("strdup");
5790 if (error)
5791 goto done;
5793 } else {
5794 repo_path = strdup(cwd);
5795 if (repo_path == NULL) {
5796 error = got_error_from_errno("strdup");
5797 goto done;
5802 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5803 if (error != NULL)
5804 goto done;
5806 if (worktree) {
5807 const char *prefix = got_worktree_get_path_prefix(worktree);
5808 char *p;
5810 error = got_worktree_resolve_path(&p, worktree, path);
5811 if (error)
5812 goto done;
5813 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5814 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5815 p) == -1) {
5816 error = got_error_from_errno("asprintf");
5817 free(p);
5818 goto done;
5820 free(p);
5821 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5822 } else {
5823 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5824 if (error)
5825 goto done;
5826 error = got_repo_map_path(&in_repo_path, repo, path);
5828 if (error)
5829 goto done;
5831 if (commit_id_str == NULL) {
5832 struct got_reference *head_ref;
5833 error = got_ref_open(&head_ref, repo, worktree ?
5834 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5835 if (error != NULL)
5836 goto done;
5837 error = got_ref_resolve(&commit_id, repo, head_ref);
5838 got_ref_close(head_ref);
5839 if (error != NULL)
5840 goto done;
5841 } else {
5842 struct got_reflist_head refs;
5844 TAILQ_INIT(&refs);
5845 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5846 NULL);
5847 if (error)
5848 goto done;
5850 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5851 repo, worktree);
5852 if (error != NULL)
5853 goto done;
5854 if (keyword_idstr != NULL)
5855 commit_id_str = keyword_idstr;
5857 error = got_repo_match_object_id(&commit_id, NULL,
5858 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5859 got_ref_list_free(&refs);
5860 if (error)
5861 goto done;
5864 if (worktree) {
5865 /* Release work tree lock. */
5866 got_worktree_close(worktree);
5867 worktree = NULL;
5870 error = got_object_open_as_commit(&commit, repo, commit_id);
5871 if (error)
5872 goto done;
5874 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5875 commit, repo);
5876 if (error)
5877 goto done;
5879 error = got_object_id_by_path(&obj_id, repo, commit,
5880 link_target ? link_target : in_repo_path);
5881 if (error)
5882 goto done;
5884 error = got_object_get_type(&obj_type, repo, obj_id);
5885 if (error)
5886 goto done;
5888 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5889 error = got_error_path(link_target ? link_target : in_repo_path,
5890 GOT_ERR_OBJ_TYPE);
5891 goto done;
5894 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5895 if (error)
5896 goto done;
5897 bca.f = got_opentemp();
5898 if (bca.f == NULL) {
5899 error = got_error_from_errno("got_opentemp");
5900 goto done;
5902 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5903 &bca.line_offsets, bca.f, blob);
5904 if (error || bca.nlines == 0)
5905 goto done;
5907 /* Don't include \n at EOF in the blame line count. */
5908 if (bca.line_offsets[bca.nlines - 1] == filesize)
5909 bca.nlines--;
5911 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5912 if (bca.lines == NULL) {
5913 error = got_error_from_errno("calloc");
5914 goto done;
5916 bca.lineno_cur = 1;
5917 bca.nlines_prec = 0;
5918 i = bca.nlines;
5919 while (i > 0) {
5920 i /= 10;
5921 bca.nlines_prec++;
5923 bca.repo = repo;
5925 fd2 = got_opentempfd();
5926 if (fd2 == -1) {
5927 error = got_error_from_errno("got_opentempfd");
5928 goto done;
5930 fd3 = got_opentempfd();
5931 if (fd3 == -1) {
5932 error = got_error_from_errno("got_opentempfd");
5933 goto done;
5935 f1 = got_opentemp();
5936 if (f1 == NULL) {
5937 error = got_error_from_errno("got_opentemp");
5938 goto done;
5940 f2 = got_opentemp();
5941 if (f2 == NULL) {
5942 error = got_error_from_errno("got_opentemp");
5943 goto done;
5945 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5946 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5947 check_cancelled, NULL, fd2, fd3, f1, f2);
5948 done:
5949 free(keyword_idstr);
5950 free(in_repo_path);
5951 free(link_target);
5952 free(repo_path);
5953 free(cwd);
5954 free(commit_id);
5955 free(obj_id);
5956 if (commit)
5957 got_object_commit_close(commit);
5959 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5960 error = got_error_from_errno("close");
5961 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5962 error = got_error_from_errno("close");
5963 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5964 error = got_error_from_errno("close");
5965 if (f1 && fclose(f1) == EOF && error == NULL)
5966 error = got_error_from_errno("fclose");
5967 if (f2 && fclose(f2) == EOF && error == NULL)
5968 error = got_error_from_errno("fclose");
5970 if (blob)
5971 got_object_blob_close(blob);
5972 if (worktree)
5973 got_worktree_close(worktree);
5974 if (repo) {
5975 const struct got_error *close_err = got_repo_close(repo);
5976 if (error == NULL)
5977 error = close_err;
5979 if (pack_fds) {
5980 const struct got_error *pack_err =
5981 got_repo_pack_fds_close(pack_fds);
5982 if (error == NULL)
5983 error = pack_err;
5985 if (bca.lines) {
5986 for (i = 0; i < bca.nlines; i++) {
5987 struct blame_line *bline = &bca.lines[i];
5988 free(bline->id_str);
5989 free(bline->committer);
5991 free(bca.lines);
5993 free(bca.line_offsets);
5994 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5995 error = got_error_from_errno("fclose");
5996 return error;
5999 __dead static void
6000 usage_tree(void)
6002 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6003 "[path]\n", getprogname());
6004 exit(1);
6007 static const struct got_error *
6008 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6009 const char *root_path, struct got_repository *repo)
6011 const struct got_error *err = NULL;
6012 int is_root_path = (strcmp(path, root_path) == 0);
6013 const char *modestr = "";
6014 mode_t mode = got_tree_entry_get_mode(te);
6015 char *link_target = NULL;
6017 path += strlen(root_path);
6018 while (path[0] == '/')
6019 path++;
6021 if (got_object_tree_entry_is_submodule(te))
6022 modestr = "$";
6023 else if (S_ISLNK(mode)) {
6024 int i;
6026 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6027 if (err)
6028 return err;
6029 for (i = 0; link_target[i] != '\0'; i++) {
6030 if (!isprint((unsigned char)link_target[i]))
6031 link_target[i] = '?';
6034 modestr = "@";
6036 else if (S_ISDIR(mode))
6037 modestr = "/";
6038 else if (mode & S_IXUSR)
6039 modestr = "*";
6041 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6042 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6043 link_target ? " -> ": "", link_target ? link_target : "");
6045 free(link_target);
6046 return NULL;
6049 static const struct got_error *
6050 print_tree(const char *path, struct got_commit_object *commit,
6051 int show_ids, int recurse, const char *root_path,
6052 struct got_repository *repo)
6054 const struct got_error *err = NULL;
6055 struct got_object_id *tree_id = NULL;
6056 struct got_tree_object *tree = NULL;
6057 int nentries, i;
6059 err = got_object_id_by_path(&tree_id, repo, commit, path);
6060 if (err)
6061 goto done;
6063 err = got_object_open_as_tree(&tree, repo, tree_id);
6064 if (err)
6065 goto done;
6066 nentries = got_object_tree_get_nentries(tree);
6067 for (i = 0; i < nentries; i++) {
6068 struct got_tree_entry *te;
6069 char *id = NULL;
6071 if (sigint_received || sigpipe_received)
6072 break;
6074 te = got_object_tree_get_entry(tree, i);
6075 if (show_ids) {
6076 char *id_str;
6077 err = got_object_id_str(&id_str,
6078 got_tree_entry_get_id(te));
6079 if (err)
6080 goto done;
6081 if (asprintf(&id, "%s ", id_str) == -1) {
6082 err = got_error_from_errno("asprintf");
6083 free(id_str);
6084 goto done;
6086 free(id_str);
6088 err = print_entry(te, id, path, root_path, repo);
6089 free(id);
6090 if (err)
6091 goto done;
6093 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6094 char *child_path;
6095 if (asprintf(&child_path, "%s%s%s", path,
6096 path[0] == '/' && path[1] == '\0' ? "" : "/",
6097 got_tree_entry_get_name(te)) == -1) {
6098 err = got_error_from_errno("asprintf");
6099 goto done;
6101 err = print_tree(child_path, commit, show_ids, 1,
6102 root_path, repo);
6103 free(child_path);
6104 if (err)
6105 goto done;
6108 done:
6109 if (tree)
6110 got_object_tree_close(tree);
6111 free(tree_id);
6112 return err;
6115 static const struct got_error *
6116 cmd_tree(int argc, char *argv[])
6118 const struct got_error *error;
6119 struct got_repository *repo = NULL;
6120 struct got_worktree *worktree = NULL;
6121 const char *path, *refname = NULL;
6122 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6123 struct got_object_id *commit_id = NULL;
6124 struct got_commit_object *commit = NULL;
6125 char *commit_id_str = NULL, *keyword_idstr = NULL;
6126 int show_ids = 0, recurse = 0;
6127 int ch;
6128 int *pack_fds = NULL;
6130 #ifndef PROFILE
6131 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6132 NULL) == -1)
6133 err(1, "pledge");
6134 #endif
6136 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6137 switch (ch) {
6138 case 'c':
6139 commit_id_str = optarg;
6140 break;
6141 case 'i':
6142 show_ids = 1;
6143 break;
6144 case 'R':
6145 recurse = 1;
6146 break;
6147 case 'r':
6148 repo_path = realpath(optarg, NULL);
6149 if (repo_path == NULL)
6150 return got_error_from_errno2("realpath",
6151 optarg);
6152 got_path_strip_trailing_slashes(repo_path);
6153 break;
6154 default:
6155 usage_tree();
6156 /* NOTREACHED */
6160 argc -= optind;
6161 argv += optind;
6163 if (argc == 1)
6164 path = argv[0];
6165 else if (argc > 1)
6166 usage_tree();
6167 else
6168 path = NULL;
6170 cwd = getcwd(NULL, 0);
6171 if (cwd == NULL) {
6172 error = got_error_from_errno("getcwd");
6173 goto done;
6176 error = got_repo_pack_fds_open(&pack_fds);
6177 if (error != NULL)
6178 goto done;
6180 if (repo_path == NULL) {
6181 error = got_worktree_open(&worktree, cwd);
6182 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6183 goto done;
6184 else
6185 error = NULL;
6186 if (worktree) {
6187 repo_path =
6188 strdup(got_worktree_get_repo_path(worktree));
6189 if (repo_path == NULL)
6190 error = got_error_from_errno("strdup");
6191 if (error)
6192 goto done;
6193 } else {
6194 repo_path = strdup(cwd);
6195 if (repo_path == NULL) {
6196 error = got_error_from_errno("strdup");
6197 goto done;
6202 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6203 if (error != NULL)
6204 goto done;
6206 if (worktree) {
6207 const char *prefix = got_worktree_get_path_prefix(worktree);
6208 char *p;
6210 if (path == NULL || got_path_is_root_dir(path))
6211 path = "";
6212 error = got_worktree_resolve_path(&p, worktree, path);
6213 if (error)
6214 goto done;
6215 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6216 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6217 p) == -1) {
6218 error = got_error_from_errno("asprintf");
6219 free(p);
6220 goto done;
6222 free(p);
6223 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6224 if (error)
6225 goto done;
6226 } else {
6227 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6228 if (error)
6229 goto done;
6230 if (path == NULL)
6231 path = "/";
6232 error = got_repo_map_path(&in_repo_path, repo, path);
6233 if (error != NULL)
6234 goto done;
6237 if (commit_id_str == NULL) {
6238 struct got_reference *head_ref;
6239 if (worktree)
6240 refname = got_worktree_get_head_ref_name(worktree);
6241 else
6242 refname = GOT_REF_HEAD;
6243 error = got_ref_open(&head_ref, repo, refname, 0);
6244 if (error != NULL)
6245 goto done;
6246 error = got_ref_resolve(&commit_id, repo, head_ref);
6247 got_ref_close(head_ref);
6248 if (error != NULL)
6249 goto done;
6250 } else {
6251 struct got_reflist_head refs;
6253 TAILQ_INIT(&refs);
6254 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6255 NULL);
6256 if (error)
6257 goto done;
6259 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6260 repo, worktree);
6261 if (error != NULL)
6262 goto done;
6263 if (keyword_idstr != NULL)
6264 commit_id_str = keyword_idstr;
6266 error = got_repo_match_object_id(&commit_id, NULL,
6267 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6268 got_ref_list_free(&refs);
6269 if (error)
6270 goto done;
6273 if (worktree) {
6274 /* Release work tree lock. */
6275 got_worktree_close(worktree);
6276 worktree = NULL;
6279 error = got_object_open_as_commit(&commit, repo, commit_id);
6280 if (error)
6281 goto done;
6283 error = print_tree(in_repo_path, commit, show_ids, recurse,
6284 in_repo_path, repo);
6285 done:
6286 free(keyword_idstr);
6287 free(in_repo_path);
6288 free(repo_path);
6289 free(cwd);
6290 free(commit_id);
6291 if (commit)
6292 got_object_commit_close(commit);
6293 if (worktree)
6294 got_worktree_close(worktree);
6295 if (repo) {
6296 const struct got_error *close_err = got_repo_close(repo);
6297 if (error == NULL)
6298 error = close_err;
6300 if (pack_fds) {
6301 const struct got_error *pack_err =
6302 got_repo_pack_fds_close(pack_fds);
6303 if (error == NULL)
6304 error = pack_err;
6306 return error;
6309 __dead static void
6310 usage_status(void)
6312 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6313 "[-s status-codes] [path ...]\n", getprogname());
6314 exit(1);
6317 struct got_status_arg {
6318 char *status_codes;
6319 int suppress;
6322 static const struct got_error *
6323 print_status(void *arg, unsigned char status, unsigned char staged_status,
6324 const char *path, struct got_object_id *blob_id,
6325 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6326 int dirfd, const char *de_name)
6328 struct got_status_arg *st = arg;
6330 if (status == staged_status && (status == GOT_STATUS_DELETE))
6331 status = GOT_STATUS_NO_CHANGE;
6332 if (st != NULL && st->status_codes) {
6333 size_t ncodes = strlen(st->status_codes);
6334 int i, j = 0;
6336 for (i = 0; i < ncodes ; i++) {
6337 if (st->suppress) {
6338 if (status == st->status_codes[i] ||
6339 staged_status == st->status_codes[i]) {
6340 j++;
6341 continue;
6343 } else {
6344 if (status == st->status_codes[i] ||
6345 staged_status == st->status_codes[i])
6346 break;
6350 if (st->suppress && j == 0)
6351 goto print;
6353 if (i == ncodes)
6354 return NULL;
6356 print:
6357 printf("%c%c %s\n", status, staged_status, path);
6358 return NULL;
6361 static const struct got_error *
6362 cmd_status(int argc, char *argv[])
6364 const struct got_error *error = NULL;
6365 struct got_repository *repo = NULL;
6366 struct got_worktree *worktree = NULL;
6367 struct got_status_arg st;
6368 char *cwd = NULL;
6369 struct got_pathlist_head paths;
6370 int ch, i, no_ignores = 0;
6371 int *pack_fds = NULL;
6373 TAILQ_INIT(&paths);
6375 memset(&st, 0, sizeof(st));
6376 st.status_codes = NULL;
6377 st.suppress = 0;
6379 #ifndef PROFILE
6380 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6381 NULL) == -1)
6382 err(1, "pledge");
6383 #endif
6385 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6386 switch (ch) {
6387 case 'I':
6388 no_ignores = 1;
6389 break;
6390 case 'S':
6391 if (st.status_codes != NULL && st.suppress == 0)
6392 option_conflict('S', 's');
6393 st.suppress = 1;
6394 /* fallthrough */
6395 case 's':
6396 for (i = 0; optarg[i] != '\0'; i++) {
6397 switch (optarg[i]) {
6398 case GOT_STATUS_MODIFY:
6399 case GOT_STATUS_ADD:
6400 case GOT_STATUS_DELETE:
6401 case GOT_STATUS_CONFLICT:
6402 case GOT_STATUS_MISSING:
6403 case GOT_STATUS_OBSTRUCTED:
6404 case GOT_STATUS_UNVERSIONED:
6405 case GOT_STATUS_MODE_CHANGE:
6406 case GOT_STATUS_NONEXISTENT:
6407 break;
6408 default:
6409 errx(1, "invalid status code '%c'",
6410 optarg[i]);
6413 if (ch == 's' && st.suppress)
6414 option_conflict('s', 'S');
6415 st.status_codes = optarg;
6416 break;
6417 default:
6418 usage_status();
6419 /* NOTREACHED */
6423 argc -= optind;
6424 argv += optind;
6426 cwd = getcwd(NULL, 0);
6427 if (cwd == NULL) {
6428 error = got_error_from_errno("getcwd");
6429 goto done;
6432 error = got_repo_pack_fds_open(&pack_fds);
6433 if (error != NULL)
6434 goto done;
6436 error = got_worktree_open(&worktree, cwd);
6437 if (error) {
6438 if (error->code == GOT_ERR_NOT_WORKTREE)
6439 error = wrap_not_worktree_error(error, "status", cwd);
6440 goto done;
6443 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6444 NULL, pack_fds);
6445 if (error != NULL)
6446 goto done;
6448 error = apply_unveil(got_repo_get_path(repo), 1,
6449 got_worktree_get_root_path(worktree));
6450 if (error)
6451 goto done;
6453 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6454 if (error)
6455 goto done;
6457 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6458 print_status, &st, check_cancelled, NULL);
6459 done:
6460 if (pack_fds) {
6461 const struct got_error *pack_err =
6462 got_repo_pack_fds_close(pack_fds);
6463 if (error == NULL)
6464 error = pack_err;
6466 if (repo) {
6467 const struct got_error *close_err = got_repo_close(repo);
6468 if (error == NULL)
6469 error = close_err;
6472 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6473 free(cwd);
6474 return error;
6477 __dead static void
6478 usage_ref(void)
6480 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6481 "[-s reference] [name]\n", getprogname());
6482 exit(1);
6485 static const struct got_error *
6486 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6488 static const struct got_error *err = NULL;
6489 struct got_reflist_head refs;
6490 struct got_reflist_entry *re;
6492 TAILQ_INIT(&refs);
6493 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6494 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6495 repo);
6496 if (err)
6497 return err;
6499 TAILQ_FOREACH(re, &refs, entry) {
6500 char *refstr;
6501 refstr = got_ref_to_str(re->ref);
6502 if (refstr == NULL) {
6503 err = got_error_from_errno("got_ref_to_str");
6504 break;
6506 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6507 free(refstr);
6510 got_ref_list_free(&refs);
6511 return err;
6514 static const struct got_error *
6515 delete_ref_by_name(struct got_repository *repo, const char *refname)
6517 const struct got_error *err;
6518 struct got_reference *ref;
6520 err = got_ref_open(&ref, repo, refname, 0);
6521 if (err)
6522 return err;
6524 err = delete_ref(repo, ref);
6525 got_ref_close(ref);
6526 return err;
6529 static const struct got_error *
6530 add_ref(struct got_repository *repo, const char *refname, const char *target)
6532 const struct got_error *err = NULL;
6533 struct got_object_id *id = NULL;
6534 struct got_reference *ref = NULL;
6535 struct got_reflist_head refs;
6538 * Don't let the user create a reference name with a leading '-'.
6539 * While technically a valid reference name, this case is usually
6540 * an unintended typo.
6542 if (refname[0] == '-')
6543 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6545 TAILQ_INIT(&refs);
6546 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6547 if (err)
6548 goto done;
6549 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6550 &refs, repo);
6551 got_ref_list_free(&refs);
6552 if (err)
6553 goto done;
6555 err = got_ref_alloc(&ref, refname, id);
6556 if (err)
6557 goto done;
6559 err = got_ref_write(ref, repo);
6560 done:
6561 if (ref)
6562 got_ref_close(ref);
6563 free(id);
6564 return err;
6567 static const struct got_error *
6568 add_symref(struct got_repository *repo, const char *refname, const char *target)
6570 const struct got_error *err = NULL;
6571 struct got_reference *ref = NULL;
6572 struct got_reference *target_ref = NULL;
6575 * Don't let the user create a reference name with a leading '-'.
6576 * While technically a valid reference name, this case is usually
6577 * an unintended typo.
6579 if (refname[0] == '-')
6580 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6582 err = got_ref_open(&target_ref, repo, target, 0);
6583 if (err)
6584 return err;
6586 err = got_ref_alloc_symref(&ref, refname, target_ref);
6587 if (err)
6588 goto done;
6590 err = got_ref_write(ref, repo);
6591 done:
6592 if (target_ref)
6593 got_ref_close(target_ref);
6594 if (ref)
6595 got_ref_close(ref);
6596 return err;
6599 static const struct got_error *
6600 cmd_ref(int argc, char *argv[])
6602 const struct got_error *error = NULL;
6603 struct got_repository *repo = NULL;
6604 struct got_worktree *worktree = NULL;
6605 char *cwd = NULL, *repo_path = NULL;
6606 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6607 const char *obj_arg = NULL, *symref_target= NULL;
6608 char *refname = NULL, *keyword_idstr = NULL;
6609 int *pack_fds = NULL;
6611 #ifndef PROFILE
6612 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6613 "sendfd unveil", NULL) == -1)
6614 err(1, "pledge");
6615 #endif
6617 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6618 switch (ch) {
6619 case 'c':
6620 obj_arg = optarg;
6621 break;
6622 case 'd':
6623 do_delete = 1;
6624 break;
6625 case 'l':
6626 do_list = 1;
6627 break;
6628 case 'r':
6629 repo_path = realpath(optarg, NULL);
6630 if (repo_path == NULL)
6631 return got_error_from_errno2("realpath",
6632 optarg);
6633 got_path_strip_trailing_slashes(repo_path);
6634 break;
6635 case 's':
6636 symref_target = optarg;
6637 break;
6638 case 't':
6639 sort_by_time = 1;
6640 break;
6641 default:
6642 usage_ref();
6643 /* NOTREACHED */
6647 if (obj_arg && do_list)
6648 option_conflict('c', 'l');
6649 if (obj_arg && do_delete)
6650 option_conflict('c', 'd');
6651 if (obj_arg && symref_target)
6652 option_conflict('c', 's');
6653 if (symref_target && do_delete)
6654 option_conflict('s', 'd');
6655 if (symref_target && do_list)
6656 option_conflict('s', 'l');
6657 if (do_delete && do_list)
6658 option_conflict('d', 'l');
6659 if (sort_by_time && !do_list)
6660 errx(1, "-t option requires -l option");
6662 argc -= optind;
6663 argv += optind;
6665 if (do_list) {
6666 if (argc != 0 && argc != 1)
6667 usage_ref();
6668 if (argc == 1) {
6669 refname = strdup(argv[0]);
6670 if (refname == NULL) {
6671 error = got_error_from_errno("strdup");
6672 goto done;
6675 } else {
6676 if (argc != 1)
6677 usage_ref();
6678 refname = strdup(argv[0]);
6679 if (refname == NULL) {
6680 error = got_error_from_errno("strdup");
6681 goto done;
6685 if (refname)
6686 got_path_strip_trailing_slashes(refname);
6688 cwd = getcwd(NULL, 0);
6689 if (cwd == NULL) {
6690 error = got_error_from_errno("getcwd");
6691 goto done;
6694 error = got_repo_pack_fds_open(&pack_fds);
6695 if (error != NULL)
6696 goto done;
6698 if (repo_path == NULL) {
6699 error = got_worktree_open(&worktree, cwd);
6700 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6701 goto done;
6702 else
6703 error = NULL;
6704 if (worktree) {
6705 repo_path =
6706 strdup(got_worktree_get_repo_path(worktree));
6707 if (repo_path == NULL)
6708 error = got_error_from_errno("strdup");
6709 if (error)
6710 goto done;
6711 } else {
6712 repo_path = strdup(cwd);
6713 if (repo_path == NULL) {
6714 error = got_error_from_errno("strdup");
6715 goto done;
6720 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6721 if (error != NULL)
6722 goto done;
6724 #ifndef PROFILE
6725 if (do_list) {
6726 /* Remove "cpath" promise. */
6727 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6728 NULL) == -1)
6729 err(1, "pledge");
6731 #endif
6733 error = apply_unveil(got_repo_get_path(repo), do_list,
6734 worktree ? got_worktree_get_root_path(worktree) : NULL);
6735 if (error)
6736 goto done;
6738 if (do_list)
6739 error = list_refs(repo, refname, sort_by_time);
6740 else if (do_delete)
6741 error = delete_ref_by_name(repo, refname);
6742 else if (symref_target)
6743 error = add_symref(repo, refname, symref_target);
6744 else {
6745 if (obj_arg == NULL)
6746 usage_ref();
6748 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6749 repo, worktree);
6750 if (error != NULL)
6751 goto done;
6752 if (keyword_idstr != NULL)
6753 obj_arg = keyword_idstr;
6755 error = add_ref(repo, refname, obj_arg);
6757 done:
6758 free(refname);
6759 if (repo) {
6760 const struct got_error *close_err = got_repo_close(repo);
6761 if (error == NULL)
6762 error = close_err;
6764 if (worktree)
6765 got_worktree_close(worktree);
6766 if (pack_fds) {
6767 const struct got_error *pack_err =
6768 got_repo_pack_fds_close(pack_fds);
6769 if (error == NULL)
6770 error = pack_err;
6772 free(cwd);
6773 free(repo_path);
6774 free(keyword_idstr);
6775 return error;
6778 __dead static void
6779 usage_branch(void)
6781 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6782 "[-r repository-path] [name]\n", getprogname());
6783 exit(1);
6786 static const struct got_error *
6787 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6788 struct got_reference *ref)
6790 const struct got_error *err = NULL;
6791 const char *refname, *marker = " ";
6792 char *refstr;
6794 refname = got_ref_get_name(ref);
6795 if (worktree && strcmp(refname,
6796 got_worktree_get_head_ref_name(worktree)) == 0) {
6797 struct got_object_id *id = NULL;
6799 err = got_ref_resolve(&id, repo, ref);
6800 if (err)
6801 return err;
6802 if (got_object_id_cmp(id,
6803 got_worktree_get_base_commit_id(worktree)) == 0)
6804 marker = "* ";
6805 else
6806 marker = "~ ";
6807 free(id);
6810 if (strncmp(refname, "refs/heads/", 11) == 0)
6811 refname += 11;
6812 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6813 refname += 18;
6814 if (strncmp(refname, "refs/remotes/", 13) == 0)
6815 refname += 13;
6817 refstr = got_ref_to_str(ref);
6818 if (refstr == NULL)
6819 return got_error_from_errno("got_ref_to_str");
6821 printf("%s%s: %s\n", marker, refname, refstr);
6822 free(refstr);
6823 return NULL;
6826 static const struct got_error *
6827 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6829 const char *refname;
6831 if (worktree == NULL)
6832 return got_error(GOT_ERR_NOT_WORKTREE);
6834 refname = got_worktree_get_head_ref_name(worktree);
6836 if (strncmp(refname, "refs/heads/", 11) == 0)
6837 refname += 11;
6838 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6839 refname += 18;
6841 printf("%s\n", refname);
6843 return NULL;
6846 static const struct got_error *
6847 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6848 int sort_by_time)
6850 static const struct got_error *err = NULL;
6851 struct got_reflist_head refs;
6852 struct got_reflist_entry *re;
6853 struct got_reference *temp_ref = NULL;
6854 int rebase_in_progress, histedit_in_progress;
6856 TAILQ_INIT(&refs);
6858 if (worktree) {
6859 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6860 worktree);
6861 if (err)
6862 return err;
6864 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6865 worktree);
6866 if (err)
6867 return err;
6869 if (rebase_in_progress || histedit_in_progress) {
6870 err = got_ref_open(&temp_ref, repo,
6871 got_worktree_get_head_ref_name(worktree), 0);
6872 if (err)
6873 return err;
6874 list_branch(repo, worktree, temp_ref);
6875 got_ref_close(temp_ref);
6879 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6880 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6881 repo);
6882 if (err)
6883 return err;
6885 TAILQ_FOREACH(re, &refs, entry)
6886 list_branch(repo, worktree, re->ref);
6888 got_ref_list_free(&refs);
6890 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6891 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6892 repo);
6893 if (err)
6894 return err;
6896 TAILQ_FOREACH(re, &refs, entry)
6897 list_branch(repo, worktree, re->ref);
6899 got_ref_list_free(&refs);
6901 return NULL;
6904 static const struct got_error *
6905 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6906 const char *branch_name)
6908 const struct got_error *err = NULL;
6909 struct got_reference *ref = NULL;
6910 char *refname, *remote_refname = NULL;
6912 if (strncmp(branch_name, "refs/", 5) == 0)
6913 branch_name += 5;
6914 if (strncmp(branch_name, "heads/", 6) == 0)
6915 branch_name += 6;
6916 else if (strncmp(branch_name, "remotes/", 8) == 0)
6917 branch_name += 8;
6919 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6920 return got_error_from_errno("asprintf");
6922 if (asprintf(&remote_refname, "refs/remotes/%s",
6923 branch_name) == -1) {
6924 err = got_error_from_errno("asprintf");
6925 goto done;
6928 err = got_ref_open(&ref, repo, refname, 0);
6929 if (err) {
6930 const struct got_error *err2;
6931 if (err->code != GOT_ERR_NOT_REF)
6932 goto done;
6934 * Keep 'err' intact such that if neither branch exists
6935 * we report "refs/heads" rather than "refs/remotes" in
6936 * our error message.
6938 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6939 if (err2)
6940 goto done;
6941 err = NULL;
6944 if (worktree &&
6945 strcmp(got_worktree_get_head_ref_name(worktree),
6946 got_ref_get_name(ref)) == 0) {
6947 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6948 "will not delete this work tree's current branch");
6949 goto done;
6952 err = delete_ref(repo, ref);
6953 done:
6954 if (ref)
6955 got_ref_close(ref);
6956 free(refname);
6957 free(remote_refname);
6958 return err;
6961 static const struct got_error *
6962 add_branch(struct got_repository *repo, const char *branch_name,
6963 struct got_object_id *base_commit_id)
6965 const struct got_error *err = NULL;
6966 struct got_reference *ref = NULL;
6967 char *refname = NULL;
6970 * Don't let the user create a branch name with a leading '-'.
6971 * While technically a valid reference name, this case is usually
6972 * an unintended typo.
6974 if (branch_name[0] == '-')
6975 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6977 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6978 branch_name += 11;
6980 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6981 err = got_error_from_errno("asprintf");
6982 goto done;
6985 err = got_ref_open(&ref, repo, refname, 0);
6986 if (err == NULL) {
6987 err = got_error(GOT_ERR_BRANCH_EXISTS);
6988 goto done;
6989 } else if (err->code != GOT_ERR_NOT_REF)
6990 goto done;
6992 err = got_ref_alloc(&ref, refname, base_commit_id);
6993 if (err)
6994 goto done;
6996 err = got_ref_write(ref, repo);
6997 done:
6998 if (ref)
6999 got_ref_close(ref);
7000 free(refname);
7001 return err;
7004 static const struct got_error *
7005 cmd_branch(int argc, char *argv[])
7007 const struct got_error *error = NULL;
7008 struct got_repository *repo = NULL;
7009 struct got_worktree *worktree = NULL;
7010 char *cwd = NULL, *repo_path = NULL;
7011 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7012 const char *delref = NULL, *commit_id_arg = NULL;
7013 struct got_reference *ref = NULL;
7014 struct got_pathlist_head paths;
7015 struct got_object_id *commit_id = NULL;
7016 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7017 int *pack_fds = NULL;
7019 TAILQ_INIT(&paths);
7021 #ifndef PROFILE
7022 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7023 "sendfd unveil", NULL) == -1)
7024 err(1, "pledge");
7025 #endif
7027 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7028 switch (ch) {
7029 case 'c':
7030 commit_id_arg = optarg;
7031 break;
7032 case 'd':
7033 delref = optarg;
7034 break;
7035 case 'l':
7036 do_list = 1;
7037 break;
7038 case 'n':
7039 do_update = 0;
7040 break;
7041 case 'r':
7042 repo_path = realpath(optarg, NULL);
7043 if (repo_path == NULL)
7044 return got_error_from_errno2("realpath",
7045 optarg);
7046 got_path_strip_trailing_slashes(repo_path);
7047 break;
7048 case 't':
7049 sort_by_time = 1;
7050 break;
7051 default:
7052 usage_branch();
7053 /* NOTREACHED */
7057 if (do_list && delref)
7058 option_conflict('l', 'd');
7059 if (sort_by_time && !do_list)
7060 errx(1, "-t option requires -l option");
7062 argc -= optind;
7063 argv += optind;
7065 if (!do_list && !delref && argc == 0)
7066 do_show = 1;
7068 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7069 errx(1, "-c option can only be used when creating a branch");
7071 if (do_list || delref) {
7072 if (argc > 0)
7073 usage_branch();
7074 } else if (!do_show && argc != 1)
7075 usage_branch();
7077 cwd = getcwd(NULL, 0);
7078 if (cwd == NULL) {
7079 error = got_error_from_errno("getcwd");
7080 goto done;
7083 error = got_repo_pack_fds_open(&pack_fds);
7084 if (error != NULL)
7085 goto done;
7087 if (repo_path == NULL) {
7088 error = got_worktree_open(&worktree, cwd);
7089 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7090 goto done;
7091 else
7092 error = NULL;
7093 if (worktree) {
7094 repo_path =
7095 strdup(got_worktree_get_repo_path(worktree));
7096 if (repo_path == NULL)
7097 error = got_error_from_errno("strdup");
7098 if (error)
7099 goto done;
7100 } else {
7101 repo_path = strdup(cwd);
7102 if (repo_path == NULL) {
7103 error = got_error_from_errno("strdup");
7104 goto done;
7109 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7110 if (error != NULL)
7111 goto done;
7113 #ifndef PROFILE
7114 if (do_list || do_show) {
7115 /* Remove "cpath" promise. */
7116 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7117 NULL) == -1)
7118 err(1, "pledge");
7120 #endif
7122 error = apply_unveil(got_repo_get_path(repo), do_list,
7123 worktree ? got_worktree_get_root_path(worktree) : NULL);
7124 if (error)
7125 goto done;
7127 if (do_show)
7128 error = show_current_branch(repo, worktree);
7129 else if (do_list)
7130 error = list_branches(repo, worktree, sort_by_time);
7131 else if (delref)
7132 error = delete_branch(repo, worktree, delref);
7133 else {
7134 struct got_reflist_head refs;
7135 TAILQ_INIT(&refs);
7136 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7137 NULL);
7138 if (error)
7139 goto done;
7140 if (commit_id_arg == NULL)
7141 commit_id_arg = worktree ?
7142 got_worktree_get_head_ref_name(worktree) :
7143 GOT_REF_HEAD;
7144 else {
7145 error = got_keyword_to_idstr(&keyword_idstr,
7146 commit_id_arg, repo, worktree);
7147 if (error != NULL)
7148 goto done;
7149 if (keyword_idstr != NULL)
7150 commit_id_arg = keyword_idstr;
7152 error = got_repo_match_object_id(&commit_id, NULL,
7153 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7154 got_ref_list_free(&refs);
7155 if (error)
7156 goto done;
7157 error = add_branch(repo, argv[0], commit_id);
7158 if (error)
7159 goto done;
7160 if (worktree && do_update) {
7161 struct got_update_progress_arg upa;
7162 char *branch_refname = NULL;
7164 error = got_object_id_str(&commit_id_str, commit_id);
7165 if (error)
7166 goto done;
7167 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7168 worktree);
7169 if (error)
7170 goto done;
7171 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7172 == -1) {
7173 error = got_error_from_errno("asprintf");
7174 goto done;
7176 error = got_ref_open(&ref, repo, branch_refname, 0);
7177 free(branch_refname);
7178 if (error)
7179 goto done;
7180 error = switch_head_ref(ref, commit_id, worktree,
7181 repo);
7182 if (error)
7183 goto done;
7184 error = got_worktree_set_base_commit_id(worktree, repo,
7185 commit_id);
7186 if (error)
7187 goto done;
7188 memset(&upa, 0, sizeof(upa));
7189 error = got_worktree_checkout_files(worktree, &paths,
7190 repo, update_progress, &upa, check_cancelled,
7191 NULL);
7192 if (error)
7193 goto done;
7194 if (upa.did_something) {
7195 printf("Updated to %s: %s\n",
7196 got_worktree_get_head_ref_name(worktree),
7197 commit_id_str);
7199 print_update_progress_stats(&upa);
7202 done:
7203 free(keyword_idstr);
7204 if (ref)
7205 got_ref_close(ref);
7206 if (repo) {
7207 const struct got_error *close_err = got_repo_close(repo);
7208 if (error == NULL)
7209 error = close_err;
7211 if (worktree)
7212 got_worktree_close(worktree);
7213 if (pack_fds) {
7214 const struct got_error *pack_err =
7215 got_repo_pack_fds_close(pack_fds);
7216 if (error == NULL)
7217 error = pack_err;
7219 free(cwd);
7220 free(repo_path);
7221 free(commit_id);
7222 free(commit_id_str);
7223 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7224 return error;
7228 __dead static void
7229 usage_tag(void)
7231 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7232 "[-r repository-path] [-s signer-id] name\n", getprogname());
7233 exit(1);
7236 #if 0
7237 static const struct got_error *
7238 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7240 const struct got_error *err = NULL;
7241 struct got_reflist_entry *re, *se, *new;
7242 struct got_object_id *re_id, *se_id;
7243 struct got_tag_object *re_tag, *se_tag;
7244 time_t re_time, se_time;
7246 STAILQ_FOREACH(re, tags, entry) {
7247 se = STAILQ_FIRST(sorted);
7248 if (se == NULL) {
7249 err = got_reflist_entry_dup(&new, re);
7250 if (err)
7251 return err;
7252 STAILQ_INSERT_HEAD(sorted, new, entry);
7253 continue;
7254 } else {
7255 err = got_ref_resolve(&re_id, repo, re->ref);
7256 if (err)
7257 break;
7258 err = got_object_open_as_tag(&re_tag, repo, re_id);
7259 free(re_id);
7260 if (err)
7261 break;
7262 re_time = got_object_tag_get_tagger_time(re_tag);
7263 got_object_tag_close(re_tag);
7266 while (se) {
7267 err = got_ref_resolve(&se_id, repo, re->ref);
7268 if (err)
7269 break;
7270 err = got_object_open_as_tag(&se_tag, repo, se_id);
7271 free(se_id);
7272 if (err)
7273 break;
7274 se_time = got_object_tag_get_tagger_time(se_tag);
7275 got_object_tag_close(se_tag);
7277 if (se_time > re_time) {
7278 err = got_reflist_entry_dup(&new, re);
7279 if (err)
7280 return err;
7281 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7282 break;
7284 se = STAILQ_NEXT(se, entry);
7285 continue;
7288 done:
7289 return err;
7291 #endif
7293 static const struct got_error *
7294 get_tag_refname(char **refname, const char *tag_name)
7296 const struct got_error *err;
7298 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7299 *refname = strdup(tag_name);
7300 if (*refname == NULL)
7301 return got_error_from_errno("strdup");
7302 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7303 err = got_error_from_errno("asprintf");
7304 *refname = NULL;
7305 return err;
7308 return NULL;
7311 static const struct got_error *
7312 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7313 const char *allowed_signers, const char *revoked_signers, int verbosity)
7315 static const struct got_error *err = NULL;
7316 struct got_reflist_head refs;
7317 struct got_reflist_entry *re;
7318 char *wanted_refname = NULL;
7319 int bad_sigs = 0;
7321 TAILQ_INIT(&refs);
7323 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7324 if (err)
7325 return err;
7327 if (tag_name) {
7328 struct got_reference *ref;
7329 err = get_tag_refname(&wanted_refname, tag_name);
7330 if (err)
7331 goto done;
7332 /* Wanted tag reference should exist. */
7333 err = got_ref_open(&ref, repo, wanted_refname, 0);
7334 if (err)
7335 goto done;
7336 got_ref_close(ref);
7339 TAILQ_FOREACH(re, &refs, entry) {
7340 const char *refname;
7341 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7342 char datebuf[26];
7343 const char *tagger, *ssh_sig = NULL;
7344 char *sig_msg = NULL;
7345 time_t tagger_time;
7346 struct got_object_id *id;
7347 struct got_tag_object *tag;
7348 struct got_commit_object *commit = NULL;
7350 refname = got_ref_get_name(re->ref);
7351 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7352 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7353 continue;
7354 refname += 10;
7355 refstr = got_ref_to_str(re->ref);
7356 if (refstr == NULL) {
7357 err = got_error_from_errno("got_ref_to_str");
7358 break;
7361 err = got_ref_resolve(&id, repo, re->ref);
7362 if (err)
7363 break;
7364 err = got_object_open_as_tag(&tag, repo, id);
7365 if (err) {
7366 if (err->code != GOT_ERR_OBJ_TYPE) {
7367 free(id);
7368 break;
7370 /* "lightweight" tag */
7371 err = got_object_open_as_commit(&commit, repo, id);
7372 if (err) {
7373 free(id);
7374 break;
7376 tagger = got_object_commit_get_committer(commit);
7377 tagger_time =
7378 got_object_commit_get_committer_time(commit);
7379 err = got_object_id_str(&id_str, id);
7380 free(id);
7381 if (err)
7382 break;
7383 } else {
7384 free(id);
7385 tagger = got_object_tag_get_tagger(tag);
7386 tagger_time = got_object_tag_get_tagger_time(tag);
7387 err = got_object_id_str(&id_str,
7388 got_object_tag_get_object_id(tag));
7389 if (err)
7390 break;
7393 if (tag && verify_tags) {
7394 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7395 got_object_tag_get_message(tag));
7396 if (ssh_sig && allowed_signers == NULL) {
7397 err = got_error_msg(
7398 GOT_ERR_VERIFY_TAG_SIGNATURE,
7399 "SSH signature verification requires "
7400 "setting allowed_signers in "
7401 "got.conf(5)");
7402 break;
7406 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7407 free(refstr);
7408 printf("from: %s\n", tagger);
7409 datestr = get_datestr(&tagger_time, datebuf);
7410 if (datestr)
7411 printf("date: %s UTC\n", datestr);
7412 if (commit)
7413 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7414 else {
7415 switch (got_object_tag_get_object_type(tag)) {
7416 case GOT_OBJ_TYPE_BLOB:
7417 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7418 id_str);
7419 break;
7420 case GOT_OBJ_TYPE_TREE:
7421 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7422 id_str);
7423 break;
7424 case GOT_OBJ_TYPE_COMMIT:
7425 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7426 id_str);
7427 break;
7428 case GOT_OBJ_TYPE_TAG:
7429 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7430 id_str);
7431 break;
7432 default:
7433 break;
7436 free(id_str);
7438 if (ssh_sig) {
7439 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7440 allowed_signers, revoked_signers, verbosity);
7441 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7442 bad_sigs = 1;
7443 else if (err)
7444 break;
7445 printf("signature: %s", sig_msg);
7446 free(sig_msg);
7447 sig_msg = NULL;
7450 if (commit) {
7451 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7452 if (err)
7453 break;
7454 got_object_commit_close(commit);
7455 } else {
7456 tagmsg0 = strdup(got_object_tag_get_message(tag));
7457 got_object_tag_close(tag);
7458 if (tagmsg0 == NULL) {
7459 err = got_error_from_errno("strdup");
7460 break;
7464 tagmsg = tagmsg0;
7465 do {
7466 line = strsep(&tagmsg, "\n");
7467 if (line)
7468 printf(" %s\n", line);
7469 } while (line);
7470 free(tagmsg0);
7472 done:
7473 got_ref_list_free(&refs);
7474 free(wanted_refname);
7476 if (err == NULL && bad_sigs)
7477 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7478 return err;
7481 static const struct got_error *
7482 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7483 const char *tag_name, const char *repo_path)
7485 const struct got_error *err = NULL;
7486 char *template = NULL, *initial_content = NULL;
7487 char *editor = NULL;
7488 int initial_content_len;
7489 int fd = -1;
7491 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7492 err = got_error_from_errno("asprintf");
7493 goto done;
7496 initial_content_len = asprintf(&initial_content,
7497 "\n# tagging commit %s as %s\n",
7498 commit_id_str, tag_name);
7499 if (initial_content_len == -1) {
7500 err = got_error_from_errno("asprintf");
7501 goto done;
7504 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7505 if (err)
7506 goto done;
7508 if (write(fd, initial_content, initial_content_len) == -1) {
7509 err = got_error_from_errno2("write", *tagmsg_path);
7510 goto done;
7512 if (close(fd) == -1) {
7513 err = got_error_from_errno2("close", *tagmsg_path);
7514 goto done;
7516 fd = -1;
7518 err = get_editor(&editor);
7519 if (err)
7520 goto done;
7521 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7522 initial_content_len, 1);
7523 done:
7524 free(initial_content);
7525 free(template);
7526 free(editor);
7528 if (fd != -1 && close(fd) == -1 && err == NULL)
7529 err = got_error_from_errno2("close", *tagmsg_path);
7531 if (err) {
7532 free(*tagmsg);
7533 *tagmsg = NULL;
7535 return err;
7538 static const struct got_error *
7539 add_tag(struct got_repository *repo, const char *tagger,
7540 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7541 const char *signer_id, int verbosity)
7543 const struct got_error *err = NULL;
7544 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7545 char *label = NULL, *commit_id_str = NULL;
7546 struct got_reference *ref = NULL;
7547 char *refname = NULL, *tagmsg = NULL;
7548 char *tagmsg_path = NULL, *tag_id_str = NULL;
7549 int preserve_tagmsg = 0;
7550 struct got_reflist_head refs;
7552 TAILQ_INIT(&refs);
7555 * Don't let the user create a tag name with a leading '-'.
7556 * While technically a valid reference name, this case is usually
7557 * an unintended typo.
7559 if (tag_name[0] == '-')
7560 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7562 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7563 if (err)
7564 goto done;
7566 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7567 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7568 if (err)
7569 goto done;
7571 err = got_object_id_str(&commit_id_str, commit_id);
7572 if (err)
7573 goto done;
7575 err = get_tag_refname(&refname, tag_name);
7576 if (err)
7577 goto done;
7578 if (strncmp("refs/tags/", tag_name, 10) == 0)
7579 tag_name += 10;
7581 err = got_ref_open(&ref, repo, refname, 0);
7582 if (err == NULL) {
7583 err = got_error(GOT_ERR_TAG_EXISTS);
7584 goto done;
7585 } else if (err->code != GOT_ERR_NOT_REF)
7586 goto done;
7588 if (tagmsg_arg == NULL) {
7589 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7590 tag_name, got_repo_get_path(repo));
7591 if (err) {
7592 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7593 tagmsg_path != NULL)
7594 preserve_tagmsg = 1;
7595 goto done;
7597 /* Editor is done; we can now apply unveil(2) */
7598 err = got_sigs_apply_unveil();
7599 if (err)
7600 goto done;
7601 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7602 if (err)
7603 goto done;
7606 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7607 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7608 verbosity);
7609 if (err) {
7610 if (tagmsg_path)
7611 preserve_tagmsg = 1;
7612 goto done;
7615 err = got_ref_alloc(&ref, refname, tag_id);
7616 if (err) {
7617 if (tagmsg_path)
7618 preserve_tagmsg = 1;
7619 goto done;
7622 err = got_ref_write(ref, repo);
7623 if (err) {
7624 if (tagmsg_path)
7625 preserve_tagmsg = 1;
7626 goto done;
7629 err = got_object_id_str(&tag_id_str, tag_id);
7630 if (err) {
7631 if (tagmsg_path)
7632 preserve_tagmsg = 1;
7633 goto done;
7635 printf("Created tag %s\n", tag_id_str);
7636 done:
7637 if (preserve_tagmsg) {
7638 fprintf(stderr, "%s: tag message preserved in %s\n",
7639 getprogname(), tagmsg_path);
7640 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7641 err = got_error_from_errno2("unlink", tagmsg_path);
7642 free(tag_id_str);
7643 if (ref)
7644 got_ref_close(ref);
7645 free(commit_id);
7646 free(commit_id_str);
7647 free(refname);
7648 free(tagmsg);
7649 free(tagmsg_path);
7650 got_ref_list_free(&refs);
7651 return err;
7654 static const struct got_error *
7655 cmd_tag(int argc, char *argv[])
7657 const struct got_error *error = NULL;
7658 struct got_repository *repo = NULL;
7659 struct got_worktree *worktree = NULL;
7660 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7661 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7662 char *allowed_signers = NULL, *revoked_signers = NULL;
7663 const char *signer_id = NULL;
7664 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7665 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7666 int *pack_fds = NULL;
7668 #ifndef PROFILE
7669 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7670 "sendfd unveil", NULL) == -1)
7671 err(1, "pledge");
7672 #endif
7674 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7675 switch (ch) {
7676 case 'c':
7677 commit_id_arg = optarg;
7678 break;
7679 case 'l':
7680 do_list = 1;
7681 break;
7682 case 'm':
7683 tagmsg = optarg;
7684 break;
7685 case 'r':
7686 repo_path = realpath(optarg, NULL);
7687 if (repo_path == NULL) {
7688 error = got_error_from_errno2("realpath",
7689 optarg);
7690 goto done;
7692 got_path_strip_trailing_slashes(repo_path);
7693 break;
7694 case 's':
7695 signer_id = optarg;
7696 break;
7697 case 'V':
7698 verify_tags = 1;
7699 break;
7700 case 'v':
7701 if (verbosity < 0)
7702 verbosity = 0;
7703 else if (verbosity < 3)
7704 verbosity++;
7705 break;
7706 default:
7707 usage_tag();
7708 /* NOTREACHED */
7712 argc -= optind;
7713 argv += optind;
7715 if (do_list || verify_tags) {
7716 if (commit_id_arg != NULL)
7717 errx(1,
7718 "-c option can only be used when creating a tag");
7719 if (tagmsg) {
7720 if (do_list)
7721 option_conflict('l', 'm');
7722 else
7723 option_conflict('V', 'm');
7725 if (signer_id) {
7726 if (do_list)
7727 option_conflict('l', 's');
7728 else
7729 option_conflict('V', 's');
7731 if (argc > 1)
7732 usage_tag();
7733 } else if (argc != 1)
7734 usage_tag();
7736 if (argc == 1)
7737 tag_name = argv[0];
7739 cwd = getcwd(NULL, 0);
7740 if (cwd == NULL) {
7741 error = got_error_from_errno("getcwd");
7742 goto done;
7745 error = got_repo_pack_fds_open(&pack_fds);
7746 if (error != NULL)
7747 goto done;
7749 if (repo_path == NULL) {
7750 error = got_worktree_open(&worktree, cwd);
7751 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7752 goto done;
7753 else
7754 error = NULL;
7755 if (worktree) {
7756 repo_path =
7757 strdup(got_worktree_get_repo_path(worktree));
7758 if (repo_path == NULL)
7759 error = got_error_from_errno("strdup");
7760 if (error)
7761 goto done;
7762 } else {
7763 repo_path = strdup(cwd);
7764 if (repo_path == NULL) {
7765 error = got_error_from_errno("strdup");
7766 goto done;
7771 if (do_list || verify_tags) {
7772 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7773 if (error != NULL)
7774 goto done;
7775 error = get_allowed_signers(&allowed_signers, repo, worktree);
7776 if (error)
7777 goto done;
7778 error = get_revoked_signers(&revoked_signers, repo, worktree);
7779 if (error)
7780 goto done;
7781 if (worktree) {
7782 /* Release work tree lock. */
7783 got_worktree_close(worktree);
7784 worktree = NULL;
7788 * Remove "cpath" promise unless needed for signature tmpfile
7789 * creation.
7791 if (verify_tags)
7792 got_sigs_apply_unveil();
7793 else {
7794 #ifndef PROFILE
7795 if (pledge("stdio rpath wpath flock proc exec sendfd "
7796 "unveil", NULL) == -1)
7797 err(1, "pledge");
7798 #endif
7800 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7801 if (error)
7802 goto done;
7803 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7804 revoked_signers, verbosity);
7805 } else {
7806 error = get_gitconfig_path(&gitconfig_path);
7807 if (error)
7808 goto done;
7809 error = got_repo_open(&repo, repo_path, gitconfig_path,
7810 pack_fds);
7811 if (error != NULL)
7812 goto done;
7814 error = get_author(&tagger, repo, worktree);
7815 if (error)
7816 goto done;
7817 if (signer_id == NULL)
7818 signer_id = get_signer_id(repo, worktree);
7820 if (tagmsg) {
7821 if (signer_id) {
7822 error = got_sigs_apply_unveil();
7823 if (error)
7824 goto done;
7826 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7827 if (error)
7828 goto done;
7831 if (commit_id_arg == NULL) {
7832 struct got_reference *head_ref;
7833 struct got_object_id *commit_id;
7834 error = got_ref_open(&head_ref, repo,
7835 worktree ? got_worktree_get_head_ref_name(worktree)
7836 : GOT_REF_HEAD, 0);
7837 if (error)
7838 goto done;
7839 error = got_ref_resolve(&commit_id, repo, head_ref);
7840 got_ref_close(head_ref);
7841 if (error)
7842 goto done;
7843 error = got_object_id_str(&commit_id_str, commit_id);
7844 free(commit_id);
7845 if (error)
7846 goto done;
7847 } else {
7848 error = got_keyword_to_idstr(&keyword_idstr,
7849 commit_id_arg, repo, worktree);
7850 if (error != NULL)
7851 goto done;
7852 commit_id_str = keyword_idstr;
7855 if (worktree) {
7856 /* Release work tree lock. */
7857 got_worktree_close(worktree);
7858 worktree = NULL;
7861 error = add_tag(repo, tagger, tag_name,
7862 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7863 signer_id, verbosity);
7865 done:
7866 if (repo) {
7867 const struct got_error *close_err = got_repo_close(repo);
7868 if (error == NULL)
7869 error = close_err;
7871 if (worktree)
7872 got_worktree_close(worktree);
7873 if (pack_fds) {
7874 const struct got_error *pack_err =
7875 got_repo_pack_fds_close(pack_fds);
7876 if (error == NULL)
7877 error = pack_err;
7879 free(cwd);
7880 free(repo_path);
7881 free(gitconfig_path);
7882 free(commit_id_str);
7883 free(tagger);
7884 free(allowed_signers);
7885 free(revoked_signers);
7886 return error;
7889 __dead static void
7890 usage_add(void)
7892 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7893 exit(1);
7896 static const struct got_error *
7897 add_progress(void *arg, unsigned char status, const char *path)
7899 while (path[0] == '/')
7900 path++;
7901 printf("%c %s\n", status, path);
7902 return NULL;
7905 static const struct got_error *
7906 cmd_add(int argc, char *argv[])
7908 const struct got_error *error = NULL;
7909 struct got_repository *repo = NULL;
7910 struct got_worktree *worktree = NULL;
7911 char *cwd = NULL;
7912 struct got_pathlist_head paths;
7913 struct got_pathlist_entry *pe;
7914 int ch, can_recurse = 0, no_ignores = 0;
7915 int *pack_fds = NULL;
7917 TAILQ_INIT(&paths);
7919 #ifndef PROFILE
7920 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7921 NULL) == -1)
7922 err(1, "pledge");
7923 #endif
7925 while ((ch = getopt(argc, argv, "IR")) != -1) {
7926 switch (ch) {
7927 case 'I':
7928 no_ignores = 1;
7929 break;
7930 case 'R':
7931 can_recurse = 1;
7932 break;
7933 default:
7934 usage_add();
7935 /* NOTREACHED */
7939 argc -= optind;
7940 argv += optind;
7942 if (argc < 1)
7943 usage_add();
7945 cwd = getcwd(NULL, 0);
7946 if (cwd == NULL) {
7947 error = got_error_from_errno("getcwd");
7948 goto done;
7951 error = got_repo_pack_fds_open(&pack_fds);
7952 if (error != NULL)
7953 goto done;
7955 error = got_worktree_open(&worktree, cwd);
7956 if (error) {
7957 if (error->code == GOT_ERR_NOT_WORKTREE)
7958 error = wrap_not_worktree_error(error, "add", cwd);
7959 goto done;
7962 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7963 NULL, pack_fds);
7964 if (error != NULL)
7965 goto done;
7967 error = apply_unveil(got_repo_get_path(repo), 1,
7968 got_worktree_get_root_path(worktree));
7969 if (error)
7970 goto done;
7972 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7973 if (error)
7974 goto done;
7976 if (!can_recurse) {
7977 char *ondisk_path;
7978 struct stat sb;
7979 TAILQ_FOREACH(pe, &paths, entry) {
7980 if (asprintf(&ondisk_path, "%s/%s",
7981 got_worktree_get_root_path(worktree),
7982 pe->path) == -1) {
7983 error = got_error_from_errno("asprintf");
7984 goto done;
7986 if (lstat(ondisk_path, &sb) == -1) {
7987 if (errno == ENOENT) {
7988 free(ondisk_path);
7989 continue;
7991 error = got_error_from_errno2("lstat",
7992 ondisk_path);
7993 free(ondisk_path);
7994 goto done;
7996 free(ondisk_path);
7997 if (S_ISDIR(sb.st_mode)) {
7998 error = got_error_msg(GOT_ERR_BAD_PATH,
7999 "adding directories requires -R option");
8000 goto done;
8005 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8006 NULL, repo, no_ignores);
8007 done:
8008 if (repo) {
8009 const struct got_error *close_err = got_repo_close(repo);
8010 if (error == NULL)
8011 error = close_err;
8013 if (worktree)
8014 got_worktree_close(worktree);
8015 if (pack_fds) {
8016 const struct got_error *pack_err =
8017 got_repo_pack_fds_close(pack_fds);
8018 if (error == NULL)
8019 error = pack_err;
8021 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8022 free(cwd);
8023 return error;
8026 __dead static void
8027 usage_remove(void)
8029 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8030 getprogname());
8031 exit(1);
8034 static const struct got_error *
8035 print_remove_status(void *arg, unsigned char status,
8036 unsigned char staged_status, const char *path)
8038 while (path[0] == '/')
8039 path++;
8040 if (status == GOT_STATUS_NONEXISTENT)
8041 return NULL;
8042 if (status == staged_status && (status == GOT_STATUS_DELETE))
8043 status = GOT_STATUS_NO_CHANGE;
8044 printf("%c%c %s\n", status, staged_status, path);
8045 return NULL;
8048 static const struct got_error *
8049 cmd_remove(int argc, char *argv[])
8051 const struct got_error *error = NULL;
8052 struct got_worktree *worktree = NULL;
8053 struct got_repository *repo = NULL;
8054 const char *status_codes = NULL;
8055 char *cwd = NULL;
8056 struct got_pathlist_head paths;
8057 struct got_pathlist_entry *pe;
8058 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8059 int ignore_missing_paths = 0;
8060 int *pack_fds = NULL;
8062 TAILQ_INIT(&paths);
8064 #ifndef PROFILE
8065 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8066 NULL) == -1)
8067 err(1, "pledge");
8068 #endif
8070 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8071 switch (ch) {
8072 case 'f':
8073 delete_local_mods = 1;
8074 ignore_missing_paths = 1;
8075 break;
8076 case 'k':
8077 keep_on_disk = 1;
8078 break;
8079 case 'R':
8080 can_recurse = 1;
8081 break;
8082 case 's':
8083 for (i = 0; optarg[i] != '\0'; i++) {
8084 switch (optarg[i]) {
8085 case GOT_STATUS_MODIFY:
8086 delete_local_mods = 1;
8087 break;
8088 case GOT_STATUS_MISSING:
8089 ignore_missing_paths = 1;
8090 break;
8091 default:
8092 errx(1, "invalid status code '%c'",
8093 optarg[i]);
8096 status_codes = optarg;
8097 break;
8098 default:
8099 usage_remove();
8100 /* NOTREACHED */
8104 argc -= optind;
8105 argv += optind;
8107 if (argc < 1)
8108 usage_remove();
8110 cwd = getcwd(NULL, 0);
8111 if (cwd == NULL) {
8112 error = got_error_from_errno("getcwd");
8113 goto done;
8116 error = got_repo_pack_fds_open(&pack_fds);
8117 if (error != NULL)
8118 goto done;
8120 error = got_worktree_open(&worktree, cwd);
8121 if (error) {
8122 if (error->code == GOT_ERR_NOT_WORKTREE)
8123 error = wrap_not_worktree_error(error, "remove", cwd);
8124 goto done;
8127 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8128 NULL, pack_fds);
8129 if (error)
8130 goto done;
8132 error = apply_unveil(got_repo_get_path(repo), 1,
8133 got_worktree_get_root_path(worktree));
8134 if (error)
8135 goto done;
8137 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8138 if (error)
8139 goto done;
8141 if (!can_recurse) {
8142 char *ondisk_path;
8143 struct stat sb;
8144 TAILQ_FOREACH(pe, &paths, entry) {
8145 if (asprintf(&ondisk_path, "%s/%s",
8146 got_worktree_get_root_path(worktree),
8147 pe->path) == -1) {
8148 error = got_error_from_errno("asprintf");
8149 goto done;
8151 if (lstat(ondisk_path, &sb) == -1) {
8152 if (errno == ENOENT) {
8153 free(ondisk_path);
8154 continue;
8156 error = got_error_from_errno2("lstat",
8157 ondisk_path);
8158 free(ondisk_path);
8159 goto done;
8161 free(ondisk_path);
8162 if (S_ISDIR(sb.st_mode)) {
8163 error = got_error_msg(GOT_ERR_BAD_PATH,
8164 "removing directories requires -R option");
8165 goto done;
8170 error = got_worktree_schedule_delete(worktree, &paths,
8171 delete_local_mods, status_codes, print_remove_status, NULL,
8172 repo, keep_on_disk, ignore_missing_paths);
8173 done:
8174 if (repo) {
8175 const struct got_error *close_err = got_repo_close(repo);
8176 if (error == NULL)
8177 error = close_err;
8179 if (worktree)
8180 got_worktree_close(worktree);
8181 if (pack_fds) {
8182 const struct got_error *pack_err =
8183 got_repo_pack_fds_close(pack_fds);
8184 if (error == NULL)
8185 error = pack_err;
8187 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8188 free(cwd);
8189 return error;
8192 __dead static void
8193 usage_patch(void)
8195 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8196 "[patchfile]\n", getprogname());
8197 exit(1);
8200 static const struct got_error *
8201 patch_from_stdin(int *patchfd)
8203 const struct got_error *err = NULL;
8204 ssize_t r;
8205 char buf[BUFSIZ];
8206 sig_t sighup, sigint, sigquit;
8208 *patchfd = got_opentempfd();
8209 if (*patchfd == -1)
8210 return got_error_from_errno("got_opentempfd");
8212 sighup = signal(SIGHUP, SIG_DFL);
8213 sigint = signal(SIGINT, SIG_DFL);
8214 sigquit = signal(SIGQUIT, SIG_DFL);
8216 for (;;) {
8217 r = read(0, buf, sizeof(buf));
8218 if (r == -1) {
8219 err = got_error_from_errno("read");
8220 break;
8222 if (r == 0)
8223 break;
8224 if (write(*patchfd, buf, r) == -1) {
8225 err = got_error_from_errno("write");
8226 break;
8230 signal(SIGHUP, sighup);
8231 signal(SIGINT, sigint);
8232 signal(SIGQUIT, sigquit);
8234 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8235 err = got_error_from_errno("lseek");
8237 if (err != NULL) {
8238 close(*patchfd);
8239 *patchfd = -1;
8242 return err;
8245 struct got_patch_progress_arg {
8246 int did_something;
8247 int conflicts;
8248 int rejects;
8251 static const struct got_error *
8252 patch_progress(void *arg, const char *old, const char *new,
8253 unsigned char status, const struct got_error *error, int old_from,
8254 int old_lines, int new_from, int new_lines, int offset,
8255 int ws_mangled, const struct got_error *hunk_err)
8257 const char *path = new == NULL ? old : new;
8258 struct got_patch_progress_arg *a = arg;
8260 while (*path == '/')
8261 path++;
8263 if (status != GOT_STATUS_NO_CHANGE &&
8264 status != 0 /* per-hunk progress */) {
8265 printf("%c %s\n", status, path);
8266 a->did_something = 1;
8269 if (hunk_err == NULL) {
8270 if (status == GOT_STATUS_CANNOT_UPDATE)
8271 a->rejects++;
8272 else if (status == GOT_STATUS_CONFLICT)
8273 a->conflicts++;
8276 if (error != NULL)
8277 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8279 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8280 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8281 old_lines, new_from, new_lines);
8282 if (hunk_err != NULL)
8283 printf("%s\n", hunk_err->msg);
8284 else if (offset != 0)
8285 printf("applied with offset %d\n", offset);
8286 else
8287 printf("hunk contains mangled whitespace\n");
8290 return NULL;
8293 static void
8294 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8296 if (!ppa->did_something)
8297 return;
8299 if (ppa->conflicts > 0)
8300 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8302 if (ppa->rejects > 0) {
8303 printf("Files where patch failed to apply: %d\n",
8304 ppa->rejects);
8308 static const struct got_error *
8309 cmd_patch(int argc, char *argv[])
8311 const struct got_error *error = NULL, *close_error = NULL;
8312 struct got_worktree *worktree = NULL;
8313 struct got_repository *repo = NULL;
8314 struct got_reflist_head refs;
8315 struct got_object_id *commit_id = NULL;
8316 const char *commit_id_str = NULL;
8317 struct stat sb;
8318 const char *errstr;
8319 char *cwd = NULL, *keyword_idstr = NULL;
8320 int ch, nop = 0, strip = -1, reverse = 0;
8321 int patchfd;
8322 int *pack_fds = NULL;
8323 struct got_patch_progress_arg ppa;
8325 TAILQ_INIT(&refs);
8327 #ifndef PROFILE
8328 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8329 "unveil", NULL) == -1)
8330 err(1, "pledge");
8331 #endif
8333 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8334 switch (ch) {
8335 case 'c':
8336 commit_id_str = optarg;
8337 break;
8338 case 'n':
8339 nop = 1;
8340 break;
8341 case 'p':
8342 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8343 if (errstr != NULL)
8344 errx(1, "pathname strip count is %s: %s",
8345 errstr, optarg);
8346 break;
8347 case 'R':
8348 reverse = 1;
8349 break;
8350 default:
8351 usage_patch();
8352 /* NOTREACHED */
8356 argc -= optind;
8357 argv += optind;
8359 if (argc == 0) {
8360 error = patch_from_stdin(&patchfd);
8361 if (error)
8362 return error;
8363 } else if (argc == 1) {
8364 patchfd = open(argv[0], O_RDONLY);
8365 if (patchfd == -1) {
8366 error = got_error_from_errno2("open", argv[0]);
8367 return error;
8369 if (fstat(patchfd, &sb) == -1) {
8370 error = got_error_from_errno2("fstat", argv[0]);
8371 goto done;
8373 if (!S_ISREG(sb.st_mode)) {
8374 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8375 goto done;
8377 } else
8378 usage_patch();
8380 if ((cwd = getcwd(NULL, 0)) == NULL) {
8381 error = got_error_from_errno("getcwd");
8382 goto done;
8385 error = got_repo_pack_fds_open(&pack_fds);
8386 if (error != NULL)
8387 goto done;
8389 error = got_worktree_open(&worktree, cwd);
8390 if (error != NULL)
8391 goto done;
8393 const char *repo_path = got_worktree_get_repo_path(worktree);
8394 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8395 if (error != NULL)
8396 goto done;
8398 error = apply_unveil(got_repo_get_path(repo), 0,
8399 got_worktree_get_root_path(worktree));
8400 if (error != NULL)
8401 goto done;
8403 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8404 if (error)
8405 goto done;
8407 if (commit_id_str != NULL) {
8408 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8409 repo, worktree);
8410 if (error != NULL)
8411 goto done;
8413 error = got_repo_match_object_id(&commit_id, NULL,
8414 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8415 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8416 if (error)
8417 goto done;
8420 memset(&ppa, 0, sizeof(ppa));
8421 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8422 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8423 print_patch_progress_stats(&ppa);
8424 done:
8425 got_ref_list_free(&refs);
8426 free(keyword_idstr);
8427 free(commit_id);
8428 if (repo) {
8429 close_error = got_repo_close(repo);
8430 if (error == NULL)
8431 error = close_error;
8433 if (worktree != NULL) {
8434 close_error = got_worktree_close(worktree);
8435 if (error == NULL)
8436 error = close_error;
8438 if (pack_fds) {
8439 const struct got_error *pack_err =
8440 got_repo_pack_fds_close(pack_fds);
8441 if (error == NULL)
8442 error = pack_err;
8444 free(cwd);
8445 return error;
8448 __dead static void
8449 usage_revert(void)
8451 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8452 getprogname());
8453 exit(1);
8456 static const struct got_error *
8457 revert_progress(void *arg, unsigned char status, const char *path)
8459 if (status == GOT_STATUS_UNVERSIONED)
8460 return NULL;
8462 while (path[0] == '/')
8463 path++;
8464 printf("%c %s\n", status, path);
8465 return NULL;
8468 struct choose_patch_arg {
8469 FILE *patch_script_file;
8470 const char *action;
8473 static const struct got_error *
8474 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8475 int nchanges, const char *action)
8477 const struct got_error *err;
8478 char *line = NULL;
8479 size_t linesize = 0;
8480 ssize_t linelen;
8482 switch (status) {
8483 case GOT_STATUS_ADD:
8484 printf("A %s\n%s this addition? [y/n] ", path, action);
8485 break;
8486 case GOT_STATUS_DELETE:
8487 printf("D %s\n%s this deletion? [y/n] ", path, action);
8488 break;
8489 case GOT_STATUS_MODIFY:
8490 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8491 return got_error_from_errno("fseek");
8492 printf(GOT_COMMIT_SEP_STR);
8493 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8494 printf("%s", line);
8495 if (linelen == -1 && ferror(patch_file)) {
8496 err = got_error_from_errno("getline");
8497 free(line);
8498 return err;
8500 free(line);
8501 printf(GOT_COMMIT_SEP_STR);
8502 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8503 path, n, nchanges, action);
8504 break;
8505 default:
8506 return got_error_path(path, GOT_ERR_FILE_STATUS);
8509 fflush(stdout);
8510 return NULL;
8513 static const struct got_error *
8514 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8515 FILE *patch_file, int n, int nchanges)
8517 const struct got_error *err = NULL;
8518 char *line = NULL;
8519 size_t linesize = 0;
8520 ssize_t linelen;
8521 int resp = ' ';
8522 struct choose_patch_arg *a = arg;
8524 *choice = GOT_PATCH_CHOICE_NONE;
8526 if (a->patch_script_file) {
8527 char *nl;
8528 err = show_change(status, path, patch_file, n, nchanges,
8529 a->action);
8530 if (err)
8531 return err;
8532 linelen = getline(&line, &linesize, a->patch_script_file);
8533 if (linelen == -1) {
8534 if (ferror(a->patch_script_file))
8535 return got_error_from_errno("getline");
8536 return NULL;
8538 nl = strchr(line, '\n');
8539 if (nl)
8540 *nl = '\0';
8541 if (strcmp(line, "y") == 0) {
8542 *choice = GOT_PATCH_CHOICE_YES;
8543 printf("y\n");
8544 } else if (strcmp(line, "n") == 0) {
8545 *choice = GOT_PATCH_CHOICE_NO;
8546 printf("n\n");
8547 } else if (strcmp(line, "q") == 0 &&
8548 status == GOT_STATUS_MODIFY) {
8549 *choice = GOT_PATCH_CHOICE_QUIT;
8550 printf("q\n");
8551 } else
8552 printf("invalid response '%s'\n", line);
8553 free(line);
8554 return NULL;
8557 while (resp != 'y' && resp != 'n' && resp != 'q') {
8558 err = show_change(status, path, patch_file, n, nchanges,
8559 a->action);
8560 if (err)
8561 return err;
8562 resp = getchar();
8563 if (resp == '\n')
8564 resp = getchar();
8565 if (status == GOT_STATUS_MODIFY) {
8566 if (resp != 'y' && resp != 'n' && resp != 'q') {
8567 printf("invalid response '%c'\n", resp);
8568 resp = ' ';
8570 } else if (resp != 'y' && resp != 'n') {
8571 printf("invalid response '%c'\n", resp);
8572 resp = ' ';
8576 if (resp == 'y')
8577 *choice = GOT_PATCH_CHOICE_YES;
8578 else if (resp == 'n')
8579 *choice = GOT_PATCH_CHOICE_NO;
8580 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8581 *choice = GOT_PATCH_CHOICE_QUIT;
8583 return NULL;
8586 struct wt_commitable_path_arg {
8587 struct got_pathlist_head *commit_paths;
8588 int *has_changes;
8592 * Shortcut work tree status callback to determine if the set of paths scanned
8593 * has at least one versioned path that is being modified and, if not NULL, is
8594 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8595 * soon as a path is passed with a status that satisfies this criteria.
8597 static const struct got_error *
8598 worktree_has_commitable_path(void *arg, unsigned char status,
8599 unsigned char staged_status, const char *path,
8600 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8601 struct got_object_id *commit_id, int dirfd, const char *de_name)
8603 struct wt_commitable_path_arg *a = arg;
8605 if (status == staged_status && (status == GOT_STATUS_DELETE))
8606 status = GOT_STATUS_NO_CHANGE;
8608 if (!(status == GOT_STATUS_NO_CHANGE ||
8609 status == GOT_STATUS_UNVERSIONED) ||
8610 staged_status != GOT_STATUS_NO_CHANGE) {
8611 if (a->commit_paths != NULL) {
8612 struct got_pathlist_entry *pe;
8614 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8615 if (strncmp(path, pe->path,
8616 pe->path_len) == 0) {
8617 *a->has_changes = 1;
8618 break;
8621 } else
8622 *a->has_changes = 1;
8624 if (*a->has_changes)
8625 return got_error(GOT_ERR_FILE_MODIFIED);
8628 return NULL;
8632 * Check that the changeset of the commit identified by id is
8633 * comprised of at least one modified path that is being committed.
8635 static const struct got_error *
8636 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8637 struct got_object_id *id, struct got_worktree *worktree,
8638 struct got_repository *repo)
8640 const struct got_error *err;
8641 struct got_pathlist_head paths;
8642 struct got_commit_object *commit = NULL, *pcommit = NULL;
8643 struct got_tree_object *tree = NULL, *ptree = NULL;
8644 struct got_object_qid *pid;
8646 TAILQ_INIT(&paths);
8648 err = got_object_open_as_commit(&commit, repo, id);
8649 if (err)
8650 goto done;
8652 err = got_object_open_as_tree(&tree, repo,
8653 got_object_commit_get_tree_id(commit));
8654 if (err)
8655 goto done;
8657 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8658 if (pid != NULL) {
8659 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8660 if (err)
8661 goto done;
8663 err = got_object_open_as_tree(&ptree, repo,
8664 got_object_commit_get_tree_id(pcommit));
8665 if (err)
8666 goto done;
8669 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8670 got_diff_tree_collect_changed_paths, &paths, 0);
8671 if (err)
8672 goto done;
8674 err = got_worktree_status(worktree, &paths, repo, 0,
8675 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8676 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8678 * At least one changed path in the referenced commit is
8679 * modified in the work tree, that's all we need to know!
8681 err = NULL;
8684 done:
8685 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8686 if (commit)
8687 got_object_commit_close(commit);
8688 if (pcommit)
8689 got_object_commit_close(pcommit);
8690 if (tree)
8691 got_object_tree_close(tree);
8692 if (ptree)
8693 got_object_tree_close(ptree);
8694 return err;
8698 * Remove any "logmsg" reference comprised entirely of paths that have
8699 * been reverted in this work tree. If any path in the logmsg ref changeset
8700 * remains in a changed state in the worktree, do not remove the reference.
8702 static const struct got_error *
8703 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8705 const struct got_error *err;
8706 struct got_reflist_head refs;
8707 struct got_reflist_entry *re;
8708 struct got_commit_object *commit = NULL;
8709 struct got_object_id *commit_id = NULL;
8710 struct wt_commitable_path_arg wcpa;
8711 char *uuidstr = NULL;
8713 TAILQ_INIT(&refs);
8715 err = got_worktree_get_uuid(&uuidstr, worktree);
8716 if (err)
8717 goto done;
8719 err = got_ref_list(&refs, repo, "refs/got/worktree",
8720 got_ref_cmp_by_name, repo);
8721 if (err)
8722 goto done;
8724 TAILQ_FOREACH(re, &refs, entry) {
8725 const char *refname;
8726 int has_changes = 0;
8728 refname = got_ref_get_name(re->ref);
8730 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8731 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8732 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8733 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8734 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8735 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8736 else
8737 continue;
8739 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8740 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8741 else
8742 continue;
8744 err = got_repo_match_object_id(&commit_id, NULL, refname,
8745 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8746 if (err)
8747 goto done;
8749 err = got_object_open_as_commit(&commit, repo, commit_id);
8750 if (err)
8751 goto done;
8753 wcpa.commit_paths = NULL;
8754 wcpa.has_changes = &has_changes;
8756 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8757 worktree, repo);
8758 if (err)
8759 goto done;
8761 if (!has_changes) {
8762 err = got_ref_delete(re->ref, repo);
8763 if (err)
8764 goto done;
8767 got_object_commit_close(commit);
8768 commit = NULL;
8769 free(commit_id);
8770 commit_id = NULL;
8773 done:
8774 free(uuidstr);
8775 free(commit_id);
8776 got_ref_list_free(&refs);
8777 if (commit)
8778 got_object_commit_close(commit);
8779 return err;
8782 static const struct got_error *
8783 cmd_revert(int argc, char *argv[])
8785 const struct got_error *error = NULL;
8786 struct got_worktree *worktree = NULL;
8787 struct got_repository *repo = NULL;
8788 char *cwd = NULL, *path = NULL;
8789 struct got_pathlist_head paths;
8790 struct got_pathlist_entry *pe;
8791 int ch, can_recurse = 0, pflag = 0;
8792 FILE *patch_script_file = NULL;
8793 const char *patch_script_path = NULL;
8794 struct choose_patch_arg cpa;
8795 int *pack_fds = NULL;
8797 TAILQ_INIT(&paths);
8799 #ifndef PROFILE
8800 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8801 "unveil", NULL) == -1)
8802 err(1, "pledge");
8803 #endif
8805 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8806 switch (ch) {
8807 case 'F':
8808 patch_script_path = optarg;
8809 break;
8810 case 'p':
8811 pflag = 1;
8812 break;
8813 case 'R':
8814 can_recurse = 1;
8815 break;
8816 default:
8817 usage_revert();
8818 /* NOTREACHED */
8822 argc -= optind;
8823 argv += optind;
8825 if (argc < 1)
8826 usage_revert();
8827 if (patch_script_path && !pflag)
8828 errx(1, "-F option can only be used together with -p option");
8830 cwd = getcwd(NULL, 0);
8831 if (cwd == NULL) {
8832 error = got_error_from_errno("getcwd");
8833 goto done;
8836 error = got_repo_pack_fds_open(&pack_fds);
8837 if (error != NULL)
8838 goto done;
8840 error = got_worktree_open(&worktree, cwd);
8841 if (error) {
8842 if (error->code == GOT_ERR_NOT_WORKTREE)
8843 error = wrap_not_worktree_error(error, "revert", cwd);
8844 goto done;
8847 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8848 NULL, pack_fds);
8849 if (error != NULL)
8850 goto done;
8852 if (patch_script_path) {
8853 patch_script_file = fopen(patch_script_path, "re");
8854 if (patch_script_file == NULL) {
8855 error = got_error_from_errno2("fopen",
8856 patch_script_path);
8857 goto done;
8862 * XXX "c" perm needed on repo dir to delete merge references.
8864 error = apply_unveil(got_repo_get_path(repo), 0,
8865 got_worktree_get_root_path(worktree));
8866 if (error)
8867 goto done;
8869 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8870 if (error)
8871 goto done;
8873 if (!can_recurse) {
8874 char *ondisk_path;
8875 struct stat sb;
8876 TAILQ_FOREACH(pe, &paths, entry) {
8877 if (asprintf(&ondisk_path, "%s/%s",
8878 got_worktree_get_root_path(worktree),
8879 pe->path) == -1) {
8880 error = got_error_from_errno("asprintf");
8881 goto done;
8883 if (lstat(ondisk_path, &sb) == -1) {
8884 if (errno == ENOENT) {
8885 free(ondisk_path);
8886 continue;
8888 error = got_error_from_errno2("lstat",
8889 ondisk_path);
8890 free(ondisk_path);
8891 goto done;
8893 free(ondisk_path);
8894 if (S_ISDIR(sb.st_mode)) {
8895 error = got_error_msg(GOT_ERR_BAD_PATH,
8896 "reverting directories requires -R option");
8897 goto done;
8902 cpa.patch_script_file = patch_script_file;
8903 cpa.action = "revert";
8904 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8905 pflag ? choose_patch : NULL, &cpa, repo);
8907 error = rm_logmsg_ref(worktree, repo);
8908 done:
8909 if (patch_script_file && fclose(patch_script_file) == EOF &&
8910 error == NULL)
8911 error = got_error_from_errno2("fclose", patch_script_path);
8912 if (repo) {
8913 const struct got_error *close_err = got_repo_close(repo);
8914 if (error == NULL)
8915 error = close_err;
8917 if (worktree)
8918 got_worktree_close(worktree);
8919 if (pack_fds) {
8920 const struct got_error *pack_err =
8921 got_repo_pack_fds_close(pack_fds);
8922 if (error == NULL)
8923 error = pack_err;
8925 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8926 free(path);
8927 free(cwd);
8928 return error;
8931 __dead static void
8932 usage_commit(void)
8934 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8935 "[-m message] [path ...]\n", getprogname());
8936 exit(1);
8939 struct collect_commit_logmsg_arg {
8940 const char *cmdline_log;
8941 const char *prepared_log;
8942 const char *merged_log;
8943 int non_interactive;
8944 const char *editor;
8945 const char *worktree_path;
8946 const char *branch_name;
8947 const char *repo_path;
8948 char *logmsg_path;
8952 static const struct got_error *
8953 read_prepared_logmsg(char **logmsg, const char *path)
8955 const struct got_error *err = NULL;
8956 FILE *f = NULL;
8957 struct stat sb;
8958 size_t r;
8960 *logmsg = NULL;
8961 memset(&sb, 0, sizeof(sb));
8963 f = fopen(path, "re");
8964 if (f == NULL)
8965 return got_error_from_errno2("fopen", path);
8967 if (fstat(fileno(f), &sb) == -1) {
8968 err = got_error_from_errno2("fstat", path);
8969 goto done;
8971 if (sb.st_size == 0) {
8972 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8973 goto done;
8976 *logmsg = malloc(sb.st_size + 1);
8977 if (*logmsg == NULL) {
8978 err = got_error_from_errno("malloc");
8979 goto done;
8982 r = fread(*logmsg, 1, sb.st_size, f);
8983 if (r != sb.st_size) {
8984 if (ferror(f))
8985 err = got_error_from_errno2("fread", path);
8986 else
8987 err = got_error(GOT_ERR_IO);
8988 goto done;
8990 (*logmsg)[sb.st_size] = '\0';
8991 done:
8992 if (fclose(f) == EOF && err == NULL)
8993 err = got_error_from_errno2("fclose", path);
8994 if (err) {
8995 free(*logmsg);
8996 *logmsg = NULL;
8998 return err;
9001 static const struct got_error *
9002 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9003 const char *diff_path, char **logmsg, void *arg)
9005 char *initial_content = NULL;
9006 struct got_pathlist_entry *pe;
9007 const struct got_error *err = NULL;
9008 char *template = NULL;
9009 char *prepared_msg = NULL, *merged_msg = NULL;
9010 struct collect_commit_logmsg_arg *a = arg;
9011 int initial_content_len;
9012 int fd = -1;
9013 size_t len;
9015 /* if a message was specified on the command line, just use it */
9016 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9017 len = strlen(a->cmdline_log) + 1;
9018 *logmsg = malloc(len + 1);
9019 if (*logmsg == NULL)
9020 return got_error_from_errno("malloc");
9021 strlcpy(*logmsg, a->cmdline_log, len);
9022 return NULL;
9023 } else if (a->prepared_log != NULL && a->non_interactive)
9024 return read_prepared_logmsg(logmsg, a->prepared_log);
9026 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9027 return got_error_from_errno("asprintf");
9029 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9030 if (err)
9031 goto done;
9033 if (a->prepared_log) {
9034 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9035 if (err)
9036 goto done;
9037 } else if (a->merged_log) {
9038 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9039 if (err)
9040 goto done;
9043 initial_content_len = asprintf(&initial_content,
9044 "%s%s\n# changes to be committed on branch %s:\n",
9045 prepared_msg ? prepared_msg : "",
9046 merged_msg ? merged_msg : "", a->branch_name);
9047 if (initial_content_len == -1) {
9048 err = got_error_from_errno("asprintf");
9049 goto done;
9052 if (write(fd, initial_content, initial_content_len) == -1) {
9053 err = got_error_from_errno2("write", a->logmsg_path);
9054 goto done;
9057 TAILQ_FOREACH(pe, commitable_paths, entry) {
9058 struct got_commitable *ct = pe->data;
9059 dprintf(fd, "# %c %s\n",
9060 got_commitable_get_status(ct),
9061 got_commitable_get_path(ct));
9064 if (diff_path) {
9065 dprintf(fd, "# detailed changes can be viewed in %s\n",
9066 diff_path);
9069 if (close(fd) == -1) {
9070 err = got_error_from_errno2("close", a->logmsg_path);
9071 goto done;
9073 fd = -1;
9075 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9076 initial_content_len, a->prepared_log ? 0 : 1);
9077 done:
9078 free(initial_content);
9079 free(template);
9080 free(prepared_msg);
9081 free(merged_msg);
9083 if (fd != -1 && close(fd) == -1 && err == NULL)
9084 err = got_error_from_errno2("close", a->logmsg_path);
9086 /* Editor is done; we can now apply unveil(2) */
9087 if (err == NULL)
9088 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9089 if (err) {
9090 free(*logmsg);
9091 *logmsg = NULL;
9093 return err;
9096 static const struct got_error *
9097 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9098 const char *type, int has_content)
9100 const struct got_error *err = NULL;
9101 char *logmsg = NULL;
9103 err = got_object_commit_get_logmsg(&logmsg, commit);
9104 if (err)
9105 return err;
9107 if (fprintf(f, "%s# log message of %s commit %s:%s",
9108 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9109 err = got_ferror(f, GOT_ERR_IO);
9111 free(logmsg);
9112 return err;
9116 * Lookup "logmsg" references of backed-out and cherrypicked commits
9117 * belonging to the current work tree. If found, and the worktree has
9118 * at least one modified file that was changed in the referenced commit,
9119 * add its log message to a new temporary file at *logmsg_path.
9120 * Add all refs found to matched_refs to be scheduled for removal on
9121 * successful commit.
9123 static const struct got_error *
9124 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9125 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9126 struct got_repository *repo)
9128 const struct got_error *err;
9129 struct got_commit_object *commit = NULL;
9130 struct got_object_id *id = NULL;
9131 struct got_reflist_head refs;
9132 struct got_reflist_entry *re, *re_match;
9133 FILE *f = NULL;
9134 char *uuidstr = NULL;
9135 int added_logmsg = 0;
9137 TAILQ_INIT(&refs);
9139 *logmsg_path = NULL;
9141 err = got_worktree_get_uuid(&uuidstr, worktree);
9142 if (err)
9143 goto done;
9145 err = got_ref_list(&refs, repo, "refs/got/worktree",
9146 got_ref_cmp_by_name, repo);
9147 if (err)
9148 goto done;
9150 TAILQ_FOREACH(re, &refs, entry) {
9151 const char *refname, *type;
9152 struct wt_commitable_path_arg wcpa;
9153 int add_logmsg = 0;
9155 refname = got_ref_get_name(re->ref);
9157 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9158 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9159 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9160 type = "cherrypicked";
9161 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9162 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9163 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9164 type = "backed-out";
9165 } else
9166 continue;
9168 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9169 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9170 else
9171 continue;
9173 err = got_repo_match_object_id(&id, NULL, refname,
9174 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9175 if (err)
9176 goto done;
9178 err = got_object_open_as_commit(&commit, repo, id);
9179 if (err)
9180 goto done;
9182 wcpa.commit_paths = paths;
9183 wcpa.has_changes = &add_logmsg;
9185 err = commit_path_changed_in_worktree(&wcpa, id,
9186 worktree, repo);
9187 if (err)
9188 goto done;
9190 if (add_logmsg) {
9191 if (f == NULL) {
9192 err = got_opentemp_named(logmsg_path, &f,
9193 "got-commit-logmsg", "");
9194 if (err)
9195 goto done;
9197 err = cat_logmsg(f, commit, refname, type,
9198 added_logmsg);
9199 if (err)
9200 goto done;
9201 if (!added_logmsg)
9202 ++added_logmsg;
9204 err = got_reflist_entry_dup(&re_match, re);
9205 if (err)
9206 goto done;
9207 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9210 got_object_commit_close(commit);
9211 commit = NULL;
9212 free(id);
9213 id = NULL;
9216 done:
9217 free(id);
9218 free(uuidstr);
9219 got_ref_list_free(&refs);
9220 if (commit)
9221 got_object_commit_close(commit);
9222 if (f && fclose(f) == EOF && err == NULL)
9223 err = got_error_from_errno("fclose");
9224 if (!added_logmsg) {
9225 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9226 err = got_error_from_errno2("unlink", *logmsg_path);
9227 *logmsg_path = NULL;
9229 return err;
9232 static const struct got_error *
9233 cmd_commit(int argc, char *argv[])
9235 const struct got_error *error = NULL;
9236 struct got_worktree *worktree = NULL;
9237 struct got_repository *repo = NULL;
9238 char *cwd = NULL, *id_str = NULL;
9239 struct got_object_id *id = NULL;
9240 const char *logmsg = NULL;
9241 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9242 struct collect_commit_logmsg_arg cl_arg;
9243 const char *author = NULL;
9244 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9245 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9246 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9247 int show_diff = 1, commit_conflicts = 0;
9248 struct got_pathlist_head paths;
9249 struct got_reflist_head refs;
9250 struct got_reflist_entry *re;
9251 int *pack_fds = NULL;
9253 TAILQ_INIT(&refs);
9254 TAILQ_INIT(&paths);
9255 cl_arg.logmsg_path = NULL;
9257 #ifndef PROFILE
9258 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9259 "unveil", NULL) == -1)
9260 err(1, "pledge");
9261 #endif
9263 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9264 switch (ch) {
9265 case 'A':
9266 author = optarg;
9267 error = valid_author(author);
9268 if (error)
9269 return error;
9270 break;
9271 case 'C':
9272 commit_conflicts = 1;
9273 break;
9274 case 'F':
9275 if (logmsg != NULL)
9276 option_conflict('F', 'm');
9277 prepared_logmsg = realpath(optarg, NULL);
9278 if (prepared_logmsg == NULL)
9279 return got_error_from_errno2("realpath",
9280 optarg);
9281 break;
9282 case 'm':
9283 if (prepared_logmsg)
9284 option_conflict('m', 'F');
9285 logmsg = optarg;
9286 break;
9287 case 'N':
9288 non_interactive = 1;
9289 break;
9290 case 'n':
9291 show_diff = 0;
9292 break;
9293 case 'S':
9294 allow_bad_symlinks = 1;
9295 break;
9296 default:
9297 usage_commit();
9298 /* NOTREACHED */
9302 argc -= optind;
9303 argv += optind;
9305 cwd = getcwd(NULL, 0);
9306 if (cwd == NULL) {
9307 error = got_error_from_errno("getcwd");
9308 goto done;
9311 error = got_repo_pack_fds_open(&pack_fds);
9312 if (error != NULL)
9313 goto done;
9315 error = got_worktree_open(&worktree, cwd);
9316 if (error) {
9317 if (error->code == GOT_ERR_NOT_WORKTREE)
9318 error = wrap_not_worktree_error(error, "commit", cwd);
9319 goto done;
9322 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9323 if (error)
9324 goto done;
9325 if (rebase_in_progress) {
9326 error = got_error(GOT_ERR_REBASING);
9327 goto done;
9330 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9331 worktree);
9332 if (error)
9333 goto done;
9335 error = get_gitconfig_path(&gitconfig_path);
9336 if (error)
9337 goto done;
9338 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9339 gitconfig_path, pack_fds);
9340 if (error != NULL)
9341 goto done;
9343 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9344 if (error)
9345 goto done;
9346 if (merge_in_progress) {
9347 error = got_error(GOT_ERR_MERGE_BUSY);
9348 goto done;
9351 error = get_author(&committer, repo, worktree);
9352 if (error)
9353 goto done;
9355 if (author == NULL)
9356 author = committer;
9359 * unveil(2) traverses exec(2); if an editor is used we have
9360 * to apply unveil after the log message has been written.
9362 if (logmsg == NULL || strlen(logmsg) == 0)
9363 error = get_editor(&editor);
9364 else
9365 error = apply_unveil(got_repo_get_path(repo), 0,
9366 got_worktree_get_root_path(worktree));
9367 if (error)
9368 goto done;
9370 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9371 if (error)
9372 goto done;
9374 if (prepared_logmsg == NULL) {
9375 error = lookup_logmsg_ref(&merged_logmsg,
9376 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9377 if (error)
9378 goto done;
9381 cl_arg.editor = editor;
9382 cl_arg.cmdline_log = logmsg;
9383 cl_arg.prepared_log = prepared_logmsg;
9384 cl_arg.merged_log = merged_logmsg;
9385 cl_arg.non_interactive = non_interactive;
9386 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9387 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9388 if (!histedit_in_progress) {
9389 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9390 error = got_error(GOT_ERR_COMMIT_BRANCH);
9391 goto done;
9393 cl_arg.branch_name += 11;
9395 cl_arg.repo_path = got_repo_get_path(repo);
9396 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9397 allow_bad_symlinks, show_diff, commit_conflicts,
9398 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9399 if (error) {
9400 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9401 cl_arg.logmsg_path != NULL)
9402 preserve_logmsg = 1;
9403 goto done;
9406 error = got_object_id_str(&id_str, id);
9407 if (error)
9408 goto done;
9409 printf("Created commit %s\n", id_str);
9411 TAILQ_FOREACH(re, &refs, entry) {
9412 error = got_ref_delete(re->ref, repo);
9413 if (error)
9414 goto done;
9417 done:
9418 if (preserve_logmsg) {
9419 fprintf(stderr, "%s: log message preserved in %s\n",
9420 getprogname(), cl_arg.logmsg_path);
9421 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9422 error == NULL)
9423 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9424 free(cl_arg.logmsg_path);
9425 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9426 error = got_error_from_errno2("unlink", merged_logmsg);
9427 free(merged_logmsg);
9428 if (repo) {
9429 const struct got_error *close_err = got_repo_close(repo);
9430 if (error == NULL)
9431 error = close_err;
9433 if (worktree)
9434 got_worktree_close(worktree);
9435 if (pack_fds) {
9436 const struct got_error *pack_err =
9437 got_repo_pack_fds_close(pack_fds);
9438 if (error == NULL)
9439 error = pack_err;
9441 got_ref_list_free(&refs);
9442 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9443 free(cwd);
9444 free(id_str);
9445 free(gitconfig_path);
9446 free(editor);
9447 free(committer);
9448 free(prepared_logmsg);
9449 return error;
9452 __dead static void
9453 usage_send(void)
9455 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9456 "[-r repository-path] [-t tag] [remote-repository]\n",
9457 getprogname());
9458 exit(1);
9461 static void
9462 print_load_info(int print_colored, int print_found, int print_trees,
9463 int ncolored, int nfound, int ntrees)
9465 if (print_colored) {
9466 printf("%d commit%s colored", ncolored,
9467 ncolored == 1 ? "" : "s");
9469 if (print_found) {
9470 printf("%s%d object%s found",
9471 ncolored > 0 ? "; " : "",
9472 nfound, nfound == 1 ? "" : "s");
9474 if (print_trees) {
9475 printf("; %d tree%s scanned", ntrees,
9476 ntrees == 1 ? "" : "s");
9480 struct got_send_progress_arg {
9481 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9482 int verbosity;
9483 int last_ncolored;
9484 int last_nfound;
9485 int last_ntrees;
9486 int loading_done;
9487 int last_ncommits;
9488 int last_nobj_total;
9489 int last_p_deltify;
9490 int last_p_written;
9491 int last_p_sent;
9492 int printed_something;
9493 int sent_something;
9494 struct got_pathlist_head *delete_branches;
9497 static const struct got_error *
9498 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9499 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9500 int nobj_written, off_t bytes_sent, const char *refname,
9501 const char *errmsg, int success)
9503 struct got_send_progress_arg *a = arg;
9504 char scaled_packsize[FMT_SCALED_STRSIZE];
9505 char scaled_sent[FMT_SCALED_STRSIZE];
9506 int p_deltify = 0, p_written = 0, p_sent = 0;
9507 int print_colored = 0, print_found = 0, print_trees = 0;
9508 int print_searching = 0, print_total = 0;
9509 int print_deltify = 0, print_written = 0, print_sent = 0;
9511 if (a->verbosity < 0)
9512 return NULL;
9514 if (refname) {
9515 const char *status = success ? "accepted" : "rejected";
9517 if (success) {
9518 struct got_pathlist_entry *pe;
9519 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9520 const char *branchname = pe->path;
9521 if (got_path_cmp(branchname, refname,
9522 strlen(branchname), strlen(refname)) == 0) {
9523 status = "deleted";
9524 a->sent_something = 1;
9525 break;
9530 if (a->printed_something)
9531 putchar('\n');
9532 printf("Server has %s %s", status, refname);
9533 if (errmsg)
9534 printf(": %s", errmsg);
9535 a->printed_something = 1;
9536 return NULL;
9539 if (a->last_ncolored != ncolored) {
9540 print_colored = 1;
9541 a->last_ncolored = ncolored;
9544 if (a->last_nfound != nfound) {
9545 print_colored = 1;
9546 print_found = 1;
9547 a->last_nfound = nfound;
9550 if (a->last_ntrees != ntrees) {
9551 print_colored = 1;
9552 print_found = 1;
9553 print_trees = 1;
9554 a->last_ntrees = ntrees;
9557 if ((print_colored || print_found || print_trees) &&
9558 !a->loading_done) {
9559 printf("\r");
9560 print_load_info(print_colored, print_found, print_trees,
9561 ncolored, nfound, ntrees);
9562 a->printed_something = 1;
9563 fflush(stdout);
9564 return NULL;
9565 } else if (!a->loading_done) {
9566 printf("\r");
9567 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9568 printf("\n");
9569 a->loading_done = 1;
9572 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9573 return got_error_from_errno("fmt_scaled");
9574 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9575 return got_error_from_errno("fmt_scaled");
9577 if (a->last_ncommits != ncommits) {
9578 print_searching = 1;
9579 a->last_ncommits = ncommits;
9582 if (a->last_nobj_total != nobj_total) {
9583 print_searching = 1;
9584 print_total = 1;
9585 a->last_nobj_total = nobj_total;
9588 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9589 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9590 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9591 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9592 return got_error(GOT_ERR_NO_SPACE);
9595 if (nobj_deltify > 0 || nobj_written > 0) {
9596 if (nobj_deltify > 0) {
9597 p_deltify = (nobj_deltify * 100) / nobj_total;
9598 if (p_deltify != a->last_p_deltify) {
9599 a->last_p_deltify = p_deltify;
9600 print_searching = 1;
9601 print_total = 1;
9602 print_deltify = 1;
9605 if (nobj_written > 0) {
9606 p_written = (nobj_written * 100) / nobj_total;
9607 if (p_written != a->last_p_written) {
9608 a->last_p_written = p_written;
9609 print_searching = 1;
9610 print_total = 1;
9611 print_deltify = 1;
9612 print_written = 1;
9617 if (bytes_sent > 0) {
9618 p_sent = (bytes_sent * 100) / packfile_size;
9619 if (p_sent != a->last_p_sent) {
9620 a->last_p_sent = p_sent;
9621 print_searching = 1;
9622 print_total = 1;
9623 print_deltify = 1;
9624 print_written = 1;
9625 print_sent = 1;
9627 a->sent_something = 1;
9630 if (print_searching || print_total || print_deltify || print_written ||
9631 print_sent)
9632 printf("\r");
9633 if (print_searching)
9634 printf("packing %d reference%s", ncommits,
9635 ncommits == 1 ? "" : "s");
9636 if (print_total)
9637 printf("; %d object%s", nobj_total,
9638 nobj_total == 1 ? "" : "s");
9639 if (print_deltify)
9640 printf("; deltify: %d%%", p_deltify);
9641 if (print_sent)
9642 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9643 scaled_packsize, p_sent);
9644 else if (print_written)
9645 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9646 scaled_packsize, p_written);
9647 if (print_searching || print_total || print_deltify ||
9648 print_written || print_sent) {
9649 a->printed_something = 1;
9650 fflush(stdout);
9652 return NULL;
9655 static const struct got_error *
9656 cmd_send(int argc, char *argv[])
9658 const struct got_error *error = NULL;
9659 char *cwd = NULL, *repo_path = NULL;
9660 const char *remote_name;
9661 char *proto = NULL, *host = NULL, *port = NULL;
9662 char *repo_name = NULL, *server_path = NULL;
9663 const struct got_remote_repo *remotes, *remote = NULL;
9664 int nremotes, nbranches = 0, ndelete_branches = 0;
9665 struct got_repository *repo = NULL;
9666 struct got_worktree *worktree = NULL;
9667 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9668 struct got_pathlist_head branches;
9669 struct got_pathlist_head tags;
9670 struct got_reflist_head all_branches;
9671 struct got_reflist_head all_tags;
9672 struct got_pathlist_head delete_args;
9673 struct got_pathlist_head delete_branches;
9674 struct got_reflist_entry *re;
9675 struct got_pathlist_entry *pe;
9676 int i, ch, sendfd = -1, sendstatus;
9677 pid_t sendpid = -1;
9678 struct got_send_progress_arg spa;
9679 int verbosity = 0, overwrite_refs = 0;
9680 int send_all_branches = 0, send_all_tags = 0;
9681 struct got_reference *ref = NULL;
9682 int *pack_fds = NULL;
9684 TAILQ_INIT(&branches);
9685 TAILQ_INIT(&tags);
9686 TAILQ_INIT(&all_branches);
9687 TAILQ_INIT(&all_tags);
9688 TAILQ_INIT(&delete_args);
9689 TAILQ_INIT(&delete_branches);
9691 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9692 switch (ch) {
9693 case 'a':
9694 send_all_branches = 1;
9695 break;
9696 case 'b':
9697 error = got_pathlist_append(&branches, optarg, NULL);
9698 if (error)
9699 return error;
9700 nbranches++;
9701 break;
9702 case 'd':
9703 error = got_pathlist_append(&delete_args, optarg, NULL);
9704 if (error)
9705 return error;
9706 break;
9707 case 'f':
9708 overwrite_refs = 1;
9709 break;
9710 case 'q':
9711 verbosity = -1;
9712 break;
9713 case 'r':
9714 repo_path = realpath(optarg, NULL);
9715 if (repo_path == NULL)
9716 return got_error_from_errno2("realpath",
9717 optarg);
9718 got_path_strip_trailing_slashes(repo_path);
9719 break;
9720 case 'T':
9721 send_all_tags = 1;
9722 break;
9723 case 't':
9724 error = got_pathlist_append(&tags, optarg, NULL);
9725 if (error)
9726 return error;
9727 break;
9728 case 'v':
9729 if (verbosity < 0)
9730 verbosity = 0;
9731 else if (verbosity < 3)
9732 verbosity++;
9733 break;
9734 default:
9735 usage_send();
9736 /* NOTREACHED */
9739 argc -= optind;
9740 argv += optind;
9742 if (send_all_branches && !TAILQ_EMPTY(&branches))
9743 option_conflict('a', 'b');
9744 if (send_all_tags && !TAILQ_EMPTY(&tags))
9745 option_conflict('T', 't');
9748 if (argc == 0)
9749 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9750 else if (argc == 1)
9751 remote_name = argv[0];
9752 else
9753 usage_send();
9755 cwd = getcwd(NULL, 0);
9756 if (cwd == NULL) {
9757 error = got_error_from_errno("getcwd");
9758 goto done;
9761 error = got_repo_pack_fds_open(&pack_fds);
9762 if (error != NULL)
9763 goto done;
9765 if (repo_path == NULL) {
9766 error = got_worktree_open(&worktree, cwd);
9767 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9768 goto done;
9769 else
9770 error = NULL;
9771 if (worktree) {
9772 repo_path =
9773 strdup(got_worktree_get_repo_path(worktree));
9774 if (repo_path == NULL)
9775 error = got_error_from_errno("strdup");
9776 if (error)
9777 goto done;
9778 } else {
9779 repo_path = strdup(cwd);
9780 if (repo_path == NULL) {
9781 error = got_error_from_errno("strdup");
9782 goto done;
9787 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9788 if (error)
9789 goto done;
9791 if (worktree) {
9792 worktree_conf = got_worktree_get_gotconfig(worktree);
9793 if (worktree_conf) {
9794 got_gotconfig_get_remotes(&nremotes, &remotes,
9795 worktree_conf);
9796 for (i = 0; i < nremotes; i++) {
9797 if (strcmp(remotes[i].name, remote_name) == 0) {
9798 remote = &remotes[i];
9799 break;
9804 if (remote == NULL) {
9805 repo_conf = got_repo_get_gotconfig(repo);
9806 if (repo_conf) {
9807 got_gotconfig_get_remotes(&nremotes, &remotes,
9808 repo_conf);
9809 for (i = 0; i < nremotes; i++) {
9810 if (strcmp(remotes[i].name, remote_name) == 0) {
9811 remote = &remotes[i];
9812 break;
9817 if (remote == NULL) {
9818 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9819 for (i = 0; i < nremotes; i++) {
9820 if (strcmp(remotes[i].name, remote_name) == 0) {
9821 remote = &remotes[i];
9822 break;
9826 if (remote == NULL) {
9827 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9828 goto done;
9831 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9832 &repo_name, remote->send_url);
9833 if (error)
9834 goto done;
9836 if (strcmp(proto, "git") == 0) {
9837 #ifndef PROFILE
9838 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9839 "sendfd dns inet unveil", NULL) == -1)
9840 err(1, "pledge");
9841 #endif
9842 } else if (strcmp(proto, "git+ssh") == 0 ||
9843 strcmp(proto, "ssh") == 0) {
9844 #ifndef PROFILE
9845 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9846 "sendfd unveil", NULL) == -1)
9847 err(1, "pledge");
9848 #endif
9849 } else if (strcmp(proto, "http") == 0 ||
9850 strcmp(proto, "git+http") == 0) {
9851 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9852 goto done;
9853 } else {
9854 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9855 goto done;
9858 error = got_dial_apply_unveil(proto);
9859 if (error)
9860 goto done;
9862 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9863 if (error)
9864 goto done;
9866 if (send_all_branches) {
9867 error = got_ref_list(&all_branches, repo, "refs/heads",
9868 got_ref_cmp_by_name, NULL);
9869 if (error)
9870 goto done;
9871 TAILQ_FOREACH(re, &all_branches, entry) {
9872 const char *branchname = got_ref_get_name(re->ref);
9873 error = got_pathlist_append(&branches,
9874 branchname, NULL);
9875 if (error)
9876 goto done;
9877 nbranches++;
9879 } else if (nbranches == 0) {
9880 for (i = 0; i < remote->nsend_branches; i++) {
9881 error = got_pathlist_append(&branches,
9882 remote->send_branches[i], NULL);
9883 if (error)
9884 goto done;
9888 if (send_all_tags) {
9889 error = got_ref_list(&all_tags, repo, "refs/tags",
9890 got_ref_cmp_by_name, NULL);
9891 if (error)
9892 goto done;
9893 TAILQ_FOREACH(re, &all_tags, entry) {
9894 const char *tagname = got_ref_get_name(re->ref);
9895 error = got_pathlist_append(&tags,
9896 tagname, NULL);
9897 if (error)
9898 goto done;
9903 * To prevent accidents only branches in refs/heads/ can be deleted
9904 * with 'got send -d'.
9905 * Deleting anything else requires local repository access or Git.
9907 TAILQ_FOREACH(pe, &delete_args, entry) {
9908 const char *branchname = pe->path;
9909 char *s;
9910 struct got_pathlist_entry *new;
9911 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9912 s = strdup(branchname);
9913 if (s == NULL) {
9914 error = got_error_from_errno("strdup");
9915 goto done;
9917 } else {
9918 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9919 error = got_error_from_errno("asprintf");
9920 goto done;
9923 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9924 if (error || new == NULL /* duplicate */)
9925 free(s);
9926 if (error)
9927 goto done;
9928 ndelete_branches++;
9931 if (nbranches == 0 && ndelete_branches == 0) {
9932 struct got_reference *head_ref;
9933 if (worktree)
9934 error = got_ref_open(&head_ref, repo,
9935 got_worktree_get_head_ref_name(worktree), 0);
9936 else
9937 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9938 if (error)
9939 goto done;
9940 if (got_ref_is_symbolic(head_ref)) {
9941 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9942 got_ref_close(head_ref);
9943 if (error)
9944 goto done;
9945 } else
9946 ref = head_ref;
9947 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9948 NULL);
9949 if (error)
9950 goto done;
9951 nbranches++;
9954 if (verbosity >= 0) {
9955 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9956 remote->name, proto, host,
9957 port ? ":" : "", port ? port : "",
9958 *server_path == '/' ? "" : "/", server_path);
9961 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9962 server_path, verbosity);
9963 if (error)
9964 goto done;
9966 memset(&spa, 0, sizeof(spa));
9967 spa.last_scaled_packsize[0] = '\0';
9968 spa.last_p_deltify = -1;
9969 spa.last_p_written = -1;
9970 spa.verbosity = verbosity;
9971 spa.delete_branches = &delete_branches;
9972 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9973 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9974 check_cancelled, NULL);
9975 if (spa.printed_something)
9976 putchar('\n');
9977 if (error)
9978 goto done;
9979 if (!spa.sent_something && verbosity >= 0)
9980 printf("Already up-to-date\n");
9981 done:
9982 if (sendpid > 0) {
9983 if (kill(sendpid, SIGTERM) == -1)
9984 error = got_error_from_errno("kill");
9985 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9986 error = got_error_from_errno("waitpid");
9988 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9989 error = got_error_from_errno("close");
9990 if (repo) {
9991 const struct got_error *close_err = got_repo_close(repo);
9992 if (error == NULL)
9993 error = close_err;
9995 if (worktree)
9996 got_worktree_close(worktree);
9997 if (pack_fds) {
9998 const struct got_error *pack_err =
9999 got_repo_pack_fds_close(pack_fds);
10000 if (error == NULL)
10001 error = pack_err;
10003 if (ref)
10004 got_ref_close(ref);
10005 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10006 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10007 got_ref_list_free(&all_branches);
10008 got_ref_list_free(&all_tags);
10009 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10010 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10011 free(cwd);
10012 free(repo_path);
10013 free(proto);
10014 free(host);
10015 free(port);
10016 free(server_path);
10017 free(repo_name);
10018 return error;
10022 * Print and if delete is set delete all ref_prefix references.
10023 * If wanted_ref is not NULL, only print or delete this reference.
10025 static const struct got_error *
10026 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10027 const char *wanted_ref, int delete, struct got_worktree *worktree,
10028 struct got_repository *repo)
10030 const struct got_error *err;
10031 struct got_pathlist_head paths;
10032 struct got_reflist_head refs;
10033 struct got_reflist_entry *re;
10034 struct got_reflist_object_id_map *refs_idmap = NULL;
10035 struct got_commit_object *commit = NULL;
10036 struct got_object_id *id = NULL;
10037 const char *header_prefix;
10038 char *uuidstr = NULL;
10039 int found = 0;
10041 TAILQ_INIT(&refs);
10042 TAILQ_INIT(&paths);
10044 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10045 if (err)
10046 goto done;
10048 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10049 if (err)
10050 goto done;
10052 if (worktree != NULL) {
10053 err = got_worktree_get_uuid(&uuidstr, worktree);
10054 if (err)
10055 goto done;
10058 if (wanted_ref) {
10059 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10060 wanted_ref += 11;
10063 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10064 header_prefix = "backout";
10065 else
10066 header_prefix = "cherrypick";
10068 TAILQ_FOREACH(re, &refs, entry) {
10069 const char *refname, *wt;
10071 refname = got_ref_get_name(re->ref);
10073 err = check_cancelled(NULL);
10074 if (err)
10075 goto done;
10077 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10078 refname += prefix_len + 1; /* skip '-' delimiter */
10079 else
10080 continue;
10082 wt = refname;
10084 if (worktree == NULL || strncmp(refname, uuidstr,
10085 GOT_WORKTREE_UUID_STRLEN) == 0)
10086 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10087 else
10088 continue;
10090 err = got_repo_match_object_id(&id, NULL, refname,
10091 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10092 if (err)
10093 goto done;
10095 err = got_object_open_as_commit(&commit, repo, id);
10096 if (err)
10097 goto done;
10099 if (wanted_ref)
10100 found = strncmp(wanted_ref, refname,
10101 strlen(wanted_ref)) == 0;
10102 if (wanted_ref && !found) {
10103 struct got_reflist_head *ci_refs;
10105 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10106 id);
10108 if (ci_refs) {
10109 char *refs_str = NULL;
10110 char const *r = NULL;
10112 err = build_refs_str(&refs_str, ci_refs, id,
10113 repo, 1);
10114 if (err)
10115 goto done;
10117 r = refs_str;
10118 while (r) {
10119 if (strncmp(r, wanted_ref,
10120 strlen(wanted_ref)) == 0) {
10121 found = 1;
10122 break;
10124 r = strchr(r, ' ');
10125 if (r)
10126 ++r;
10128 free(refs_str);
10132 if (wanted_ref == NULL || found) {
10133 if (delete) {
10134 err = got_ref_delete(re->ref, repo);
10135 if (err)
10136 goto done;
10137 printf("Deleted: ");
10138 err = print_commit_oneline(commit, id, repo,
10139 refs_idmap);
10140 } else {
10142 * Print paths modified by commit to help
10143 * associate commits with worktree changes.
10145 err = get_changed_paths(&paths, commit,
10146 repo, NULL);
10147 if (err)
10148 goto done;
10150 err = print_commit(commit, id, repo, NULL,
10151 &paths, NULL, 0, 0, refs_idmap, NULL,
10152 header_prefix);
10153 got_pathlist_free(&paths,
10154 GOT_PATHLIST_FREE_ALL);
10156 if (worktree == NULL)
10157 printf("work tree: %.*s\n\n",
10158 GOT_WORKTREE_UUID_STRLEN, wt);
10160 if (err || found)
10161 goto done;
10164 got_object_commit_close(commit);
10165 commit = NULL;
10166 free(id);
10167 id = NULL;
10170 if (wanted_ref != NULL && !found)
10171 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10173 done:
10174 free(id);
10175 free(uuidstr);
10176 got_ref_list_free(&refs);
10177 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10178 if (refs_idmap)
10179 got_reflist_object_id_map_free(refs_idmap);
10180 if (commit)
10181 got_object_commit_close(commit);
10182 return err;
10186 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10187 * identified by id for log messages to prepopulate the editor on commit.
10189 static const struct got_error *
10190 logmsg_ref(struct got_object_id *id, const char *prefix,
10191 struct got_worktree *worktree, struct got_repository *repo)
10193 const struct got_error *err = NULL;
10194 char *idstr, *ref = NULL, *refname = NULL;
10195 int histedit_in_progress;
10196 int rebase_in_progress, merge_in_progress;
10199 * Silenty refuse to create merge reference if any histedit, merge,
10200 * or rebase operation is in progress.
10202 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10203 worktree);
10204 if (err)
10205 return err;
10206 if (histedit_in_progress)
10207 return NULL;
10209 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10210 if (err)
10211 return err;
10212 if (rebase_in_progress)
10213 return NULL;
10215 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10216 repo);
10217 if (err)
10218 return err;
10219 if (merge_in_progress)
10220 return NULL;
10222 err = got_object_id_str(&idstr, id);
10223 if (err)
10224 return err;
10226 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10227 if (err)
10228 goto done;
10230 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10231 err = got_error_from_errno("asprintf");
10232 goto done;
10235 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10236 -1, repo);
10237 done:
10238 free(ref);
10239 free(idstr);
10240 free(refname);
10241 return err;
10244 __dead static void
10245 usage_cherrypick(void)
10247 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10248 getprogname());
10249 exit(1);
10252 static const struct got_error *
10253 cmd_cherrypick(int argc, char *argv[])
10255 const struct got_error *error = NULL;
10256 struct got_worktree *worktree = NULL;
10257 struct got_repository *repo = NULL;
10258 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10259 struct got_object_id *commit_id = NULL;
10260 struct got_commit_object *commit = NULL;
10261 struct got_object_qid *pid;
10262 int ch, list_refs = 0, remove_refs = 0;
10263 struct got_update_progress_arg upa;
10264 int *pack_fds = NULL;
10266 #ifndef PROFILE
10267 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10268 "unveil", NULL) == -1)
10269 err(1, "pledge");
10270 #endif
10272 while ((ch = getopt(argc, argv, "lX")) != -1) {
10273 switch (ch) {
10274 case 'l':
10275 list_refs = 1;
10276 break;
10277 case 'X':
10278 remove_refs = 1;
10279 break;
10280 default:
10281 usage_cherrypick();
10282 /* NOTREACHED */
10286 argc -= optind;
10287 argv += optind;
10289 if (list_refs || remove_refs) {
10290 if (argc != 0 && argc != 1)
10291 usage_cherrypick();
10292 } else if (argc != 1)
10293 usage_cherrypick();
10294 if (list_refs && remove_refs)
10295 option_conflict('l', 'X');
10297 cwd = getcwd(NULL, 0);
10298 if (cwd == NULL) {
10299 error = got_error_from_errno("getcwd");
10300 goto done;
10303 error = got_repo_pack_fds_open(&pack_fds);
10304 if (error != NULL)
10305 goto done;
10307 error = got_worktree_open(&worktree, cwd);
10308 if (error) {
10309 if (list_refs || remove_refs) {
10310 if (error->code != GOT_ERR_NOT_WORKTREE)
10311 goto done;
10312 } else {
10313 if (error->code == GOT_ERR_NOT_WORKTREE)
10314 error = wrap_not_worktree_error(error,
10315 "cherrypick", cwd);
10316 goto done;
10320 error = got_repo_open(&repo,
10321 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10322 NULL, pack_fds);
10323 if (error != NULL)
10324 goto done;
10326 error = apply_unveil(got_repo_get_path(repo), 0,
10327 worktree ? got_worktree_get_root_path(worktree) : NULL);
10328 if (error)
10329 goto done;
10331 if (list_refs || remove_refs) {
10332 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10333 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10334 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10335 goto done;
10338 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10339 if (error != NULL)
10340 goto done;
10342 error = got_repo_match_object_id(&commit_id, NULL,
10343 keyword_idstr != NULL ? keyword_idstr : argv[0],
10344 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10345 if (error)
10346 goto done;
10347 error = got_object_id_str(&commit_id_str, commit_id);
10348 if (error)
10349 goto done;
10351 error = got_object_open_as_commit(&commit, repo, commit_id);
10352 if (error)
10353 goto done;
10354 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10355 memset(&upa, 0, sizeof(upa));
10356 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10357 commit_id, repo, update_progress, &upa, check_cancelled,
10358 NULL);
10359 if (error != NULL)
10360 goto done;
10362 if (upa.did_something) {
10363 error = logmsg_ref(commit_id,
10364 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10365 if (error)
10366 goto done;
10367 printf("Merged commit %s\n", commit_id_str);
10369 print_merge_progress_stats(&upa);
10370 done:
10371 free(cwd);
10372 free(keyword_idstr);
10373 if (commit)
10374 got_object_commit_close(commit);
10375 free(commit_id_str);
10376 if (worktree)
10377 got_worktree_close(worktree);
10378 if (repo) {
10379 const struct got_error *close_err = got_repo_close(repo);
10380 if (error == NULL)
10381 error = close_err;
10383 if (pack_fds) {
10384 const struct got_error *pack_err =
10385 got_repo_pack_fds_close(pack_fds);
10386 if (error == NULL)
10387 error = pack_err;
10390 return error;
10393 __dead static void
10394 usage_backout(void)
10396 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10397 exit(1);
10400 static const struct got_error *
10401 cmd_backout(int argc, char *argv[])
10403 const struct got_error *error = NULL;
10404 struct got_worktree *worktree = NULL;
10405 struct got_repository *repo = NULL;
10406 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10407 struct got_object_id *commit_id = NULL;
10408 struct got_commit_object *commit = NULL;
10409 struct got_object_qid *pid;
10410 int ch, list_refs = 0, remove_refs = 0;
10411 struct got_update_progress_arg upa;
10412 int *pack_fds = NULL;
10414 #ifndef PROFILE
10415 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10416 "unveil", NULL) == -1)
10417 err(1, "pledge");
10418 #endif
10420 while ((ch = getopt(argc, argv, "lX")) != -1) {
10421 switch (ch) {
10422 case 'l':
10423 list_refs = 1;
10424 break;
10425 case 'X':
10426 remove_refs = 1;
10427 break;
10428 default:
10429 usage_backout();
10430 /* NOTREACHED */
10434 argc -= optind;
10435 argv += optind;
10437 if (list_refs || remove_refs) {
10438 if (argc != 0 && argc != 1)
10439 usage_backout();
10440 } else if (argc != 1)
10441 usage_backout();
10442 if (list_refs && remove_refs)
10443 option_conflict('l', 'X');
10445 cwd = getcwd(NULL, 0);
10446 if (cwd == NULL) {
10447 error = got_error_from_errno("getcwd");
10448 goto done;
10451 error = got_repo_pack_fds_open(&pack_fds);
10452 if (error != NULL)
10453 goto done;
10455 error = got_worktree_open(&worktree, cwd);
10456 if (error) {
10457 if (list_refs || remove_refs) {
10458 if (error->code != GOT_ERR_NOT_WORKTREE)
10459 goto done;
10460 } else {
10461 if (error->code == GOT_ERR_NOT_WORKTREE)
10462 error = wrap_not_worktree_error(error,
10463 "backout", cwd);
10464 goto done;
10468 error = got_repo_open(&repo,
10469 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10470 NULL, pack_fds);
10471 if (error != NULL)
10472 goto done;
10474 error = apply_unveil(got_repo_get_path(repo), 0,
10475 worktree ? got_worktree_get_root_path(worktree) : NULL);
10476 if (error)
10477 goto done;
10479 if (list_refs || remove_refs) {
10480 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10481 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10482 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10483 goto done;
10486 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10487 if (error != NULL)
10488 goto done;
10490 error = got_repo_match_object_id(&commit_id, NULL,
10491 keyword_idstr != NULL ? keyword_idstr : argv[0],
10492 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10493 if (error)
10494 goto done;
10495 error = got_object_id_str(&commit_id_str, commit_id);
10496 if (error)
10497 goto done;
10499 error = got_object_open_as_commit(&commit, repo, commit_id);
10500 if (error)
10501 goto done;
10502 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10503 if (pid == NULL) {
10504 error = got_error(GOT_ERR_ROOT_COMMIT);
10505 goto done;
10508 memset(&upa, 0, sizeof(upa));
10509 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10510 repo, update_progress, &upa, check_cancelled, NULL);
10511 if (error != NULL)
10512 goto done;
10514 if (upa.did_something) {
10515 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10516 worktree, repo);
10517 if (error)
10518 goto done;
10519 printf("Backed out commit %s\n", commit_id_str);
10521 print_merge_progress_stats(&upa);
10522 done:
10523 free(cwd);
10524 free(keyword_idstr);
10525 if (commit)
10526 got_object_commit_close(commit);
10527 free(commit_id_str);
10528 if (worktree)
10529 got_worktree_close(worktree);
10530 if (repo) {
10531 const struct got_error *close_err = got_repo_close(repo);
10532 if (error == NULL)
10533 error = close_err;
10535 if (pack_fds) {
10536 const struct got_error *pack_err =
10537 got_repo_pack_fds_close(pack_fds);
10538 if (error == NULL)
10539 error = pack_err;
10541 return error;
10544 __dead static void
10545 usage_rebase(void)
10547 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10548 exit(1);
10551 static void
10552 trim_logmsg(char *logmsg, int limit)
10554 char *nl;
10555 size_t len;
10557 len = strlen(logmsg);
10558 if (len > limit)
10559 len = limit;
10560 logmsg[len] = '\0';
10561 nl = strchr(logmsg, '\n');
10562 if (nl)
10563 *nl = '\0';
10566 static const struct got_error *
10567 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10569 const struct got_error *err;
10570 char *logmsg0 = NULL;
10571 const char *s;
10573 err = got_object_commit_get_logmsg(&logmsg0, commit);
10574 if (err)
10575 return err;
10577 s = logmsg0;
10578 while (isspace((unsigned char)s[0]))
10579 s++;
10581 *logmsg = strdup(s);
10582 if (*logmsg == NULL) {
10583 err = got_error_from_errno("strdup");
10584 goto done;
10587 trim_logmsg(*logmsg, limit);
10588 done:
10589 free(logmsg0);
10590 return err;
10593 static const struct got_error *
10594 show_rebase_merge_conflict(struct got_object_id *id,
10595 struct got_repository *repo)
10597 const struct got_error *err;
10598 struct got_commit_object *commit = NULL;
10599 char *id_str = NULL, *logmsg = NULL;
10601 err = got_object_open_as_commit(&commit, repo, id);
10602 if (err)
10603 return err;
10605 err = got_object_id_str(&id_str, id);
10606 if (err)
10607 goto done;
10609 id_str[12] = '\0';
10611 err = get_short_logmsg(&logmsg, 42, commit);
10612 if (err)
10613 goto done;
10615 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10616 done:
10617 free(id_str);
10618 got_object_commit_close(commit);
10619 free(logmsg);
10620 return err;
10623 static const struct got_error *
10624 show_rebase_progress(struct got_commit_object *commit,
10625 struct got_object_id *old_id, struct got_object_id *new_id)
10627 const struct got_error *err;
10628 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10630 err = got_object_id_str(&old_id_str, old_id);
10631 if (err)
10632 goto done;
10634 if (new_id) {
10635 err = got_object_id_str(&new_id_str, new_id);
10636 if (err)
10637 goto done;
10640 old_id_str[12] = '\0';
10641 if (new_id_str)
10642 new_id_str[12] = '\0';
10644 err = get_short_logmsg(&logmsg, 42, commit);
10645 if (err)
10646 goto done;
10648 printf("%s -> %s: %s\n", old_id_str,
10649 new_id_str ? new_id_str : "no-op change", logmsg);
10650 done:
10651 free(old_id_str);
10652 free(new_id_str);
10653 free(logmsg);
10654 return err;
10657 static const struct got_error *
10658 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10659 struct got_reference *branch, struct got_reference *tmp_branch,
10660 struct got_repository *repo, int create_backup)
10662 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10663 return got_worktree_rebase_complete(worktree, fileindex,
10664 tmp_branch, branch, repo, create_backup);
10667 static const struct got_error *
10668 rebase_commit(struct got_pathlist_head *merged_paths,
10669 struct got_worktree *worktree, struct got_fileindex *fileindex,
10670 struct got_reference *tmp_branch, const char *committer,
10671 struct got_object_id *commit_id, int allow_conflict,
10672 struct got_repository *repo)
10674 const struct got_error *error;
10675 struct got_commit_object *commit;
10676 struct got_object_id *new_commit_id;
10678 error = got_object_open_as_commit(&commit, repo, commit_id);
10679 if (error)
10680 return error;
10682 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10683 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10684 allow_conflict, repo);
10685 if (error) {
10686 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10687 goto done;
10688 error = show_rebase_progress(commit, commit_id, NULL);
10689 } else {
10690 error = show_rebase_progress(commit, commit_id, new_commit_id);
10691 free(new_commit_id);
10693 done:
10694 got_object_commit_close(commit);
10695 return error;
10698 struct check_path_prefix_arg {
10699 const char *path_prefix;
10700 size_t len;
10701 int errcode;
10704 static const struct got_error *
10705 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10706 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10707 struct got_object_id *id1, struct got_object_id *id2,
10708 const char *path1, const char *path2,
10709 mode_t mode1, mode_t mode2, struct got_repository *repo)
10711 struct check_path_prefix_arg *a = arg;
10713 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10714 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10715 return got_error(a->errcode);
10717 return NULL;
10720 static const struct got_error *
10721 check_path_prefix(struct got_object_id *parent_id,
10722 struct got_object_id *commit_id, const char *path_prefix,
10723 int errcode, struct got_repository *repo)
10725 const struct got_error *err;
10726 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10727 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10728 struct check_path_prefix_arg cpp_arg;
10730 if (got_path_is_root_dir(path_prefix))
10731 return NULL;
10733 err = got_object_open_as_commit(&commit, repo, commit_id);
10734 if (err)
10735 goto done;
10737 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10738 if (err)
10739 goto done;
10741 err = got_object_open_as_tree(&tree1, repo,
10742 got_object_commit_get_tree_id(parent_commit));
10743 if (err)
10744 goto done;
10746 err = got_object_open_as_tree(&tree2, repo,
10747 got_object_commit_get_tree_id(commit));
10748 if (err)
10749 goto done;
10751 cpp_arg.path_prefix = path_prefix;
10752 while (cpp_arg.path_prefix[0] == '/')
10753 cpp_arg.path_prefix++;
10754 cpp_arg.len = strlen(cpp_arg.path_prefix);
10755 cpp_arg.errcode = errcode;
10756 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10757 check_path_prefix_in_diff, &cpp_arg, 0);
10758 done:
10759 if (tree1)
10760 got_object_tree_close(tree1);
10761 if (tree2)
10762 got_object_tree_close(tree2);
10763 if (commit)
10764 got_object_commit_close(commit);
10765 if (parent_commit)
10766 got_object_commit_close(parent_commit);
10767 return err;
10770 static const struct got_error *
10771 collect_commits(struct got_object_id_queue *commits,
10772 struct got_object_id *initial_commit_id,
10773 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10774 const char *path_prefix, int path_prefix_errcode,
10775 struct got_repository *repo)
10777 const struct got_error *err = NULL;
10778 struct got_commit_graph *graph = NULL;
10779 struct got_object_id parent_id, commit_id;
10780 struct got_object_qid *qid;
10782 err = got_commit_graph_open(&graph, "/", 1);
10783 if (err)
10784 return err;
10786 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10787 check_cancelled, NULL);
10788 if (err)
10789 goto done;
10791 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10792 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10793 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10794 check_cancelled, NULL);
10795 if (err) {
10796 if (err->code == GOT_ERR_ITER_COMPLETED) {
10797 err = got_error_msg(GOT_ERR_ANCESTRY,
10798 "ran out of commits to rebase before "
10799 "youngest common ancestor commit has "
10800 "been reached?!?");
10802 goto done;
10803 } else {
10804 err = check_path_prefix(&parent_id, &commit_id,
10805 path_prefix, path_prefix_errcode, repo);
10806 if (err)
10807 goto done;
10809 err = got_object_qid_alloc(&qid, &commit_id);
10810 if (err)
10811 goto done;
10812 STAILQ_INSERT_HEAD(commits, qid, entry);
10814 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10817 done:
10818 got_commit_graph_close(graph);
10819 return err;
10822 static const struct got_error *
10823 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10825 const struct got_error *err = NULL;
10826 time_t committer_time;
10827 struct tm tm;
10828 char datebuf[11]; /* YYYY-MM-DD + NUL */
10829 char *author0 = NULL, *author, *smallerthan;
10830 char *logmsg0 = NULL, *logmsg, *newline;
10832 committer_time = got_object_commit_get_committer_time(commit);
10833 if (gmtime_r(&committer_time, &tm) == NULL)
10834 return got_error_from_errno("gmtime_r");
10835 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10836 return got_error(GOT_ERR_NO_SPACE);
10838 author0 = strdup(got_object_commit_get_author(commit));
10839 if (author0 == NULL)
10840 return got_error_from_errno("strdup");
10841 author = author0;
10842 smallerthan = strchr(author, '<');
10843 if (smallerthan && smallerthan[1] != '\0')
10844 author = smallerthan + 1;
10845 author[strcspn(author, "@>")] = '\0';
10847 err = got_object_commit_get_logmsg(&logmsg0, commit);
10848 if (err)
10849 goto done;
10850 logmsg = logmsg0;
10851 while (*logmsg == '\n')
10852 logmsg++;
10853 newline = strchr(logmsg, '\n');
10854 if (newline)
10855 *newline = '\0';
10857 if (asprintf(brief_str, "%s %s %s",
10858 datebuf, author, logmsg) == -1)
10859 err = got_error_from_errno("asprintf");
10860 done:
10861 free(author0);
10862 free(logmsg0);
10863 return err;
10866 static const struct got_error *
10867 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10868 struct got_repository *repo)
10870 const struct got_error *err;
10871 char *id_str;
10873 err = got_object_id_str(&id_str, id);
10874 if (err)
10875 return err;
10877 err = got_ref_delete(ref, repo);
10878 if (err)
10879 goto done;
10881 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10882 done:
10883 free(id_str);
10884 return err;
10887 static const struct got_error *
10888 print_backup_ref(const char *branch_name, const char *new_id_str,
10889 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10890 struct got_reflist_object_id_map *refs_idmap,
10891 struct got_repository *repo)
10893 const struct got_error *err = NULL;
10894 struct got_reflist_head *refs;
10895 char *refs_str = NULL;
10896 struct got_object_id *new_commit_id = NULL;
10897 struct got_commit_object *new_commit = NULL;
10898 char *new_commit_brief_str = NULL;
10899 struct got_object_id *yca_id = NULL;
10900 struct got_commit_object *yca_commit = NULL;
10901 char *yca_id_str = NULL, *yca_brief_str = NULL;
10902 char *custom_refs_str;
10904 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10905 return got_error_from_errno("asprintf");
10907 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10908 0, 0, refs_idmap, custom_refs_str, NULL);
10909 if (err)
10910 goto done;
10912 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10913 if (err)
10914 goto done;
10916 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10917 if (refs) {
10918 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10919 if (err)
10920 goto done;
10923 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10924 if (err)
10925 goto done;
10927 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10928 if (err)
10929 goto done;
10931 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10932 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10933 if (err)
10934 goto done;
10936 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10937 refs_str ? " (" : "", refs_str ? refs_str : "",
10938 refs_str ? ")" : "", new_commit_brief_str);
10939 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10940 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10941 free(refs_str);
10942 refs_str = NULL;
10944 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10945 if (err)
10946 goto done;
10948 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10949 if (err)
10950 goto done;
10952 err = got_object_id_str(&yca_id_str, yca_id);
10953 if (err)
10954 goto done;
10956 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10957 if (refs) {
10958 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10959 if (err)
10960 goto done;
10962 printf("history forked at %s%s%s%s\n %s\n",
10963 yca_id_str,
10964 refs_str ? " (" : "", refs_str ? refs_str : "",
10965 refs_str ? ")" : "", yca_brief_str);
10967 done:
10968 free(custom_refs_str);
10969 free(new_commit_id);
10970 free(refs_str);
10971 free(yca_id);
10972 free(yca_id_str);
10973 free(yca_brief_str);
10974 if (new_commit)
10975 got_object_commit_close(new_commit);
10976 if (yca_commit)
10977 got_object_commit_close(yca_commit);
10979 return err;
10982 static const struct got_error *
10983 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10984 struct got_repository *repo)
10986 const struct got_error *err;
10987 struct got_reflist_head refs;
10988 struct got_reflist_entry *re;
10989 char *uuidstr = NULL;
10990 static char msg[160];
10992 TAILQ_INIT(&refs);
10994 err = got_worktree_get_uuid(&uuidstr, worktree);
10995 if (err)
10996 goto done;
10998 err = got_ref_list(&refs, repo, "refs/got/worktree",
10999 got_ref_cmp_by_name, repo);
11000 if (err)
11001 goto done;
11003 TAILQ_FOREACH(re, &refs, entry) {
11004 const char *cmd, *refname, *type;
11006 refname = got_ref_get_name(re->ref);
11008 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11009 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11010 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11011 cmd = "cherrypick";
11012 type = "cherrypicked";
11013 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11014 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11015 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11016 cmd = "backout";
11017 type = "backed-out";
11018 } else
11019 continue;
11021 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11022 continue;
11024 snprintf(msg, sizeof(msg),
11025 "work tree has references created by %s commits which "
11026 "must be removed with 'got %s -X' before running the %s "
11027 "command", type, cmd, caller);
11028 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11029 goto done;
11032 done:
11033 free(uuidstr);
11034 got_ref_list_free(&refs);
11035 return err;
11038 static const struct got_error *
11039 process_backup_refs(const char *backup_ref_prefix,
11040 const char *wanted_branch_name,
11041 int delete, struct got_repository *repo)
11043 const struct got_error *err;
11044 struct got_reflist_head refs, backup_refs;
11045 struct got_reflist_entry *re;
11046 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11047 struct got_object_id *old_commit_id = NULL;
11048 char *branch_name = NULL;
11049 struct got_commit_object *old_commit = NULL;
11050 struct got_reflist_object_id_map *refs_idmap = NULL;
11051 int wanted_branch_found = 0;
11053 TAILQ_INIT(&refs);
11054 TAILQ_INIT(&backup_refs);
11056 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11057 if (err)
11058 return err;
11060 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11061 if (err)
11062 goto done;
11064 if (wanted_branch_name) {
11065 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11066 wanted_branch_name += 11;
11069 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11070 got_ref_cmp_by_commit_timestamp_descending, repo);
11071 if (err)
11072 goto done;
11074 TAILQ_FOREACH(re, &backup_refs, entry) {
11075 const char *refname = got_ref_get_name(re->ref);
11076 char *slash;
11078 err = check_cancelled(NULL);
11079 if (err)
11080 break;
11082 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11083 if (err)
11084 break;
11086 err = got_object_open_as_commit(&old_commit, repo,
11087 old_commit_id);
11088 if (err)
11089 break;
11091 if (strncmp(backup_ref_prefix, refname,
11092 backup_ref_prefix_len) == 0)
11093 refname += backup_ref_prefix_len;
11095 while (refname[0] == '/')
11096 refname++;
11098 branch_name = strdup(refname);
11099 if (branch_name == NULL) {
11100 err = got_error_from_errno("strdup");
11101 break;
11103 slash = strrchr(branch_name, '/');
11104 if (slash) {
11105 *slash = '\0';
11106 refname += strlen(branch_name) + 1;
11109 if (wanted_branch_name == NULL ||
11110 strcmp(wanted_branch_name, branch_name) == 0) {
11111 wanted_branch_found = 1;
11112 if (delete) {
11113 err = delete_backup_ref(re->ref,
11114 old_commit_id, repo);
11115 } else {
11116 err = print_backup_ref(branch_name, refname,
11117 old_commit_id, old_commit, refs_idmap,
11118 repo);
11120 if (err)
11121 break;
11124 free(old_commit_id);
11125 old_commit_id = NULL;
11126 free(branch_name);
11127 branch_name = NULL;
11128 got_object_commit_close(old_commit);
11129 old_commit = NULL;
11132 if (wanted_branch_name && !wanted_branch_found) {
11133 err = got_error_fmt(GOT_ERR_NOT_REF,
11134 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11136 done:
11137 if (refs_idmap)
11138 got_reflist_object_id_map_free(refs_idmap);
11139 got_ref_list_free(&refs);
11140 got_ref_list_free(&backup_refs);
11141 free(old_commit_id);
11142 free(branch_name);
11143 if (old_commit)
11144 got_object_commit_close(old_commit);
11145 return err;
11148 static const struct got_error *
11149 abort_progress(void *arg, unsigned char status, const char *path)
11152 * Unversioned files should not clutter progress output when
11153 * an operation is aborted.
11155 if (status == GOT_STATUS_UNVERSIONED)
11156 return NULL;
11158 return update_progress(arg, status, path);
11161 static const struct got_error *
11162 cmd_rebase(int argc, char *argv[])
11164 const struct got_error *error = NULL;
11165 struct got_worktree *worktree = NULL;
11166 struct got_repository *repo = NULL;
11167 struct got_fileindex *fileindex = NULL;
11168 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11169 struct got_reference *branch = NULL;
11170 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11171 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11172 struct got_object_id *resume_commit_id = NULL;
11173 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11174 struct got_object_id *head_commit_id = NULL;
11175 struct got_reference *head_ref = NULL;
11176 struct got_commit_object *commit = NULL;
11177 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11178 int histedit_in_progress = 0, merge_in_progress = 0;
11179 int create_backup = 1, list_backups = 0, delete_backups = 0;
11180 int allow_conflict = 0;
11181 struct got_object_id_queue commits;
11182 struct got_pathlist_head merged_paths;
11183 const struct got_object_id_queue *parent_ids;
11184 struct got_object_qid *qid, *pid;
11185 struct got_update_progress_arg upa;
11186 int *pack_fds = NULL;
11188 STAILQ_INIT(&commits);
11189 TAILQ_INIT(&merged_paths);
11190 memset(&upa, 0, sizeof(upa));
11192 #ifndef PROFILE
11193 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11194 "unveil", NULL) == -1)
11195 err(1, "pledge");
11196 #endif
11198 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11199 switch (ch) {
11200 case 'a':
11201 abort_rebase = 1;
11202 break;
11203 case 'C':
11204 allow_conflict = 1;
11205 break;
11206 case 'c':
11207 continue_rebase = 1;
11208 break;
11209 case 'l':
11210 list_backups = 1;
11211 break;
11212 case 'X':
11213 delete_backups = 1;
11214 break;
11215 default:
11216 usage_rebase();
11217 /* NOTREACHED */
11221 argc -= optind;
11222 argv += optind;
11224 if (list_backups) {
11225 if (abort_rebase)
11226 option_conflict('l', 'a');
11227 if (allow_conflict)
11228 option_conflict('l', 'C');
11229 if (continue_rebase)
11230 option_conflict('l', 'c');
11231 if (delete_backups)
11232 option_conflict('l', 'X');
11233 if (argc != 0 && argc != 1)
11234 usage_rebase();
11235 } else if (delete_backups) {
11236 if (abort_rebase)
11237 option_conflict('X', 'a');
11238 if (allow_conflict)
11239 option_conflict('X', 'C');
11240 if (continue_rebase)
11241 option_conflict('X', 'c');
11242 if (list_backups)
11243 option_conflict('l', 'X');
11244 if (argc != 0 && argc != 1)
11245 usage_rebase();
11246 } else if (allow_conflict) {
11247 if (abort_rebase)
11248 option_conflict('C', 'a');
11249 if (!continue_rebase)
11250 errx(1, "-C option requires -c");
11251 } else {
11252 if (abort_rebase && continue_rebase)
11253 usage_rebase();
11254 else if (abort_rebase || continue_rebase) {
11255 if (argc != 0)
11256 usage_rebase();
11257 } else if (argc != 1)
11258 usage_rebase();
11261 cwd = getcwd(NULL, 0);
11262 if (cwd == NULL) {
11263 error = got_error_from_errno("getcwd");
11264 goto done;
11267 error = got_repo_pack_fds_open(&pack_fds);
11268 if (error != NULL)
11269 goto done;
11271 error = got_worktree_open(&worktree, cwd);
11272 if (error) {
11273 if (list_backups || delete_backups) {
11274 if (error->code != GOT_ERR_NOT_WORKTREE)
11275 goto done;
11276 } else {
11277 if (error->code == GOT_ERR_NOT_WORKTREE)
11278 error = wrap_not_worktree_error(error,
11279 "rebase", cwd);
11280 goto done;
11284 error = get_gitconfig_path(&gitconfig_path);
11285 if (error)
11286 goto done;
11287 error = got_repo_open(&repo,
11288 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11289 gitconfig_path, pack_fds);
11290 if (error != NULL)
11291 goto done;
11293 if (worktree != NULL && !list_backups && !delete_backups) {
11294 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11295 if (error)
11296 goto done;
11299 error = get_author(&committer, repo, worktree);
11300 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11301 goto done;
11303 error = apply_unveil(got_repo_get_path(repo), 0,
11304 worktree ? got_worktree_get_root_path(worktree) : NULL);
11305 if (error)
11306 goto done;
11308 if (list_backups || delete_backups) {
11309 error = process_backup_refs(
11310 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11311 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11312 goto done; /* nothing else to do */
11315 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11316 worktree);
11317 if (error)
11318 goto done;
11319 if (histedit_in_progress) {
11320 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11321 goto done;
11324 error = got_worktree_merge_in_progress(&merge_in_progress,
11325 worktree, repo);
11326 if (error)
11327 goto done;
11328 if (merge_in_progress) {
11329 error = got_error(GOT_ERR_MERGE_BUSY);
11330 goto done;
11333 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11334 if (error)
11335 goto done;
11337 if (abort_rebase) {
11338 if (!rebase_in_progress) {
11339 error = got_error(GOT_ERR_NOT_REBASING);
11340 goto done;
11342 error = got_worktree_rebase_continue(&resume_commit_id,
11343 &new_base_branch, &tmp_branch, &branch, &fileindex,
11344 worktree, repo);
11345 if (error)
11346 goto done;
11347 printf("Switching work tree to %s\n",
11348 got_ref_get_symref_target(new_base_branch));
11349 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11350 new_base_branch, abort_progress, &upa);
11351 if (error)
11352 goto done;
11353 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11354 print_merge_progress_stats(&upa);
11355 goto done; /* nothing else to do */
11358 if (continue_rebase) {
11359 if (!rebase_in_progress) {
11360 error = got_error(GOT_ERR_NOT_REBASING);
11361 goto done;
11363 error = got_worktree_rebase_continue(&resume_commit_id,
11364 &new_base_branch, &tmp_branch, &branch, &fileindex,
11365 worktree, repo);
11366 if (error)
11367 goto done;
11369 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11370 committer, resume_commit_id, allow_conflict, repo);
11371 if (error)
11372 goto done;
11374 yca_id = got_object_id_dup(resume_commit_id);
11375 if (yca_id == NULL) {
11376 error = got_error_from_errno("got_object_id_dup");
11377 goto done;
11379 } else {
11380 error = got_ref_open(&branch, repo, argv[0], 0);
11381 if (error != NULL)
11382 goto done;
11383 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11384 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11385 "will not rebase a branch which lives outside "
11386 "the \"refs/heads/\" reference namespace");
11387 goto done;
11391 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11392 if (error)
11393 goto done;
11395 if (!continue_rebase) {
11396 struct got_object_id *base_commit_id;
11398 error = got_ref_open(&head_ref, repo,
11399 got_worktree_get_head_ref_name(worktree), 0);
11400 if (error)
11401 goto done;
11402 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11403 if (error)
11404 goto done;
11405 base_commit_id = got_worktree_get_base_commit_id(worktree);
11406 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11407 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11408 goto done;
11411 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11412 base_commit_id, branch_head_commit_id, 1, repo,
11413 check_cancelled, NULL);
11414 if (error) {
11415 if (error->code == GOT_ERR_ANCESTRY) {
11416 error = got_error_msg(GOT_ERR_ANCESTRY,
11417 "specified branch shares no common "
11418 "ancestry with work tree's branch");
11420 goto done;
11423 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11424 struct got_pathlist_head paths;
11425 printf("%s is already based on %s\n",
11426 got_ref_get_name(branch),
11427 got_worktree_get_head_ref_name(worktree));
11428 error = switch_head_ref(branch, branch_head_commit_id,
11429 worktree, repo);
11430 if (error)
11431 goto done;
11432 error = got_worktree_set_base_commit_id(worktree, repo,
11433 branch_head_commit_id);
11434 if (error)
11435 goto done;
11436 TAILQ_INIT(&paths);
11437 error = got_pathlist_append(&paths, "", NULL);
11438 if (error)
11439 goto done;
11440 error = got_worktree_checkout_files(worktree,
11441 &paths, repo, update_progress, &upa,
11442 check_cancelled, NULL);
11443 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11444 if (error)
11445 goto done;
11446 if (upa.did_something) {
11447 char *id_str;
11448 error = got_object_id_str(&id_str,
11449 branch_head_commit_id);
11450 if (error)
11451 goto done;
11452 printf("Updated to %s: %s\n",
11453 got_worktree_get_head_ref_name(worktree),
11454 id_str);
11455 free(id_str);
11456 } else
11457 printf("Already up-to-date\n");
11458 print_update_progress_stats(&upa);
11459 goto done;
11463 commit_id = branch_head_commit_id;
11464 error = got_object_open_as_commit(&commit, repo, commit_id);
11465 if (error)
11466 goto done;
11468 parent_ids = got_object_commit_get_parent_ids(commit);
11469 pid = STAILQ_FIRST(parent_ids);
11470 if (pid) {
11471 error = collect_commits(&commits, commit_id, &pid->id,
11472 yca_id, got_worktree_get_path_prefix(worktree),
11473 GOT_ERR_REBASE_PATH, repo);
11474 if (error)
11475 goto done;
11478 got_object_commit_close(commit);
11479 commit = NULL;
11481 if (!continue_rebase) {
11482 error = got_worktree_rebase_prepare(&new_base_branch,
11483 &tmp_branch, &fileindex, worktree, branch, repo);
11484 if (error)
11485 goto done;
11488 if (STAILQ_EMPTY(&commits)) {
11489 if (continue_rebase) {
11490 error = rebase_complete(worktree, fileindex,
11491 branch, tmp_branch, repo, create_backup);
11492 goto done;
11493 } else {
11494 /* Fast-forward the reference of the branch. */
11495 struct got_object_id *new_head_commit_id;
11496 char *id_str;
11497 error = got_ref_resolve(&new_head_commit_id, repo,
11498 new_base_branch);
11499 if (error)
11500 goto done;
11501 error = got_object_id_str(&id_str, new_head_commit_id);
11502 if (error)
11503 goto done;
11504 printf("Forwarding %s to commit %s\n",
11505 got_ref_get_name(branch), id_str);
11506 free(id_str);
11507 error = got_ref_change_ref(branch,
11508 new_head_commit_id);
11509 if (error)
11510 goto done;
11511 /* No backup needed since objects did not change. */
11512 create_backup = 0;
11516 pid = NULL;
11517 STAILQ_FOREACH(qid, &commits, entry) {
11519 commit_id = &qid->id;
11520 parent_id = pid ? &pid->id : yca_id;
11521 pid = qid;
11523 memset(&upa, 0, sizeof(upa));
11524 error = got_worktree_rebase_merge_files(&merged_paths,
11525 worktree, fileindex, parent_id, commit_id, repo,
11526 update_progress, &upa, check_cancelled, NULL);
11527 if (error)
11528 goto done;
11530 print_merge_progress_stats(&upa);
11531 if (upa.conflicts > 0 || upa.missing > 0 ||
11532 upa.not_deleted > 0 || upa.unversioned > 0) {
11533 if (upa.conflicts > 0) {
11534 error = show_rebase_merge_conflict(&qid->id,
11535 repo);
11536 if (error)
11537 goto done;
11539 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11540 break;
11543 error = rebase_commit(&merged_paths, worktree, fileindex,
11544 tmp_branch, committer, commit_id, 0, repo);
11545 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11546 if (error)
11547 goto done;
11550 if (upa.conflicts > 0 || upa.missing > 0 ||
11551 upa.not_deleted > 0 || upa.unversioned > 0) {
11552 error = got_worktree_rebase_postpone(worktree, fileindex);
11553 if (error)
11554 goto done;
11555 if (upa.conflicts > 0 && upa.missing == 0 &&
11556 upa.not_deleted == 0 && upa.unversioned == 0) {
11557 error = got_error_msg(GOT_ERR_CONFLICTS,
11558 "conflicts must be resolved before rebasing "
11559 "can continue");
11560 } else if (upa.conflicts > 0) {
11561 error = got_error_msg(GOT_ERR_CONFLICTS,
11562 "conflicts must be resolved before rebasing "
11563 "can continue; changes destined for some "
11564 "files were not yet merged and should be "
11565 "merged manually if required before the "
11566 "rebase operation is continued");
11567 } else {
11568 error = got_error_msg(GOT_ERR_CONFLICTS,
11569 "changes destined for some files were not "
11570 "yet merged and should be merged manually "
11571 "if required before the rebase operation "
11572 "is continued");
11574 } else
11575 error = rebase_complete(worktree, fileindex, branch,
11576 tmp_branch, repo, create_backup);
11577 done:
11578 free(cwd);
11579 free(committer);
11580 free(gitconfig_path);
11581 got_object_id_queue_free(&commits);
11582 free(branch_head_commit_id);
11583 free(resume_commit_id);
11584 free(head_commit_id);
11585 free(yca_id);
11586 if (commit)
11587 got_object_commit_close(commit);
11588 if (branch)
11589 got_ref_close(branch);
11590 if (new_base_branch)
11591 got_ref_close(new_base_branch);
11592 if (tmp_branch)
11593 got_ref_close(tmp_branch);
11594 if (head_ref)
11595 got_ref_close(head_ref);
11596 if (worktree)
11597 got_worktree_close(worktree);
11598 if (repo) {
11599 const struct got_error *close_err = got_repo_close(repo);
11600 if (error == NULL)
11601 error = close_err;
11603 if (pack_fds) {
11604 const struct got_error *pack_err =
11605 got_repo_pack_fds_close(pack_fds);
11606 if (error == NULL)
11607 error = pack_err;
11609 return error;
11612 __dead static void
11613 usage_histedit(void)
11615 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11616 "[branch]\n", getprogname());
11617 exit(1);
11620 #define GOT_HISTEDIT_PICK 'p'
11621 #define GOT_HISTEDIT_EDIT 'e'
11622 #define GOT_HISTEDIT_FOLD 'f'
11623 #define GOT_HISTEDIT_DROP 'd'
11624 #define GOT_HISTEDIT_MESG 'm'
11626 static const struct got_histedit_cmd {
11627 unsigned char code;
11628 const char *name;
11629 const char *desc;
11630 } got_histedit_cmds[] = {
11631 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11632 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11633 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11634 "be used" },
11635 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11636 { GOT_HISTEDIT_MESG, "mesg",
11637 "single-line log message for commit above (open editor if empty)" },
11640 struct got_histedit_list_entry {
11641 TAILQ_ENTRY(got_histedit_list_entry) entry;
11642 struct got_object_id *commit_id;
11643 const struct got_histedit_cmd *cmd;
11644 char *logmsg;
11646 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11648 static const struct got_error *
11649 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11650 FILE *f, struct got_repository *repo)
11652 const struct got_error *err = NULL;
11653 char *logmsg = NULL, *id_str = NULL;
11654 struct got_commit_object *commit = NULL;
11655 int n;
11657 err = got_object_open_as_commit(&commit, repo, commit_id);
11658 if (err)
11659 goto done;
11661 err = get_short_logmsg(&logmsg, 34, commit);
11662 if (err)
11663 goto done;
11665 err = got_object_id_str(&id_str, commit_id);
11666 if (err)
11667 goto done;
11669 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11670 if (n < 0)
11671 err = got_ferror(f, GOT_ERR_IO);
11672 done:
11673 if (commit)
11674 got_object_commit_close(commit);
11675 free(id_str);
11676 free(logmsg);
11677 return err;
11680 static const struct got_error *
11681 histedit_write_commit_list(struct got_object_id_queue *commits,
11682 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11683 int edit_only, struct got_repository *repo)
11685 const struct got_error *err = NULL;
11686 struct got_object_qid *qid;
11687 const char *histedit_cmd = NULL;
11689 if (STAILQ_EMPTY(commits))
11690 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11692 STAILQ_FOREACH(qid, commits, entry) {
11693 histedit_cmd = got_histedit_cmds[0].name;
11694 if (drop_only)
11695 histedit_cmd = "drop";
11696 else if (edit_only)
11697 histedit_cmd = "edit";
11698 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11699 histedit_cmd = "fold";
11700 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11701 if (err)
11702 break;
11703 if (edit_logmsg_only) {
11704 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11705 if (n < 0) {
11706 err = got_ferror(f, GOT_ERR_IO);
11707 break;
11712 return err;
11715 static const struct got_error *
11716 write_cmd_list(FILE *f, const char *branch_name,
11717 struct got_object_id_queue *commits)
11719 const struct got_error *err = NULL;
11720 size_t i;
11721 int n;
11722 char *id_str;
11723 struct got_object_qid *qid;
11725 qid = STAILQ_FIRST(commits);
11726 err = got_object_id_str(&id_str, &qid->id);
11727 if (err)
11728 return err;
11730 n = fprintf(f,
11731 "# Editing the history of branch '%s' starting at\n"
11732 "# commit %s\n"
11733 "# Commits will be processed in order from top to "
11734 "bottom of this file.\n", branch_name, id_str);
11735 if (n < 0) {
11736 err = got_ferror(f, GOT_ERR_IO);
11737 goto done;
11740 n = fprintf(f, "# Available histedit commands:\n");
11741 if (n < 0) {
11742 err = got_ferror(f, GOT_ERR_IO);
11743 goto done;
11746 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11747 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11748 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11749 cmd->desc);
11750 if (n < 0) {
11751 err = got_ferror(f, GOT_ERR_IO);
11752 break;
11755 done:
11756 free(id_str);
11757 return err;
11760 static const struct got_error *
11761 histedit_syntax_error(int lineno)
11763 static char msg[42];
11764 int ret;
11766 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11767 lineno);
11768 if (ret < 0 || (size_t)ret >= sizeof(msg))
11769 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11771 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11774 static const struct got_error *
11775 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11776 char *logmsg, struct got_repository *repo)
11778 const struct got_error *err;
11779 struct got_commit_object *folded_commit = NULL;
11780 char *id_str, *folded_logmsg = NULL;
11782 err = got_object_id_str(&id_str, hle->commit_id);
11783 if (err)
11784 return err;
11786 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11787 if (err)
11788 goto done;
11790 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11791 if (err)
11792 goto done;
11793 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11794 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11795 folded_logmsg) == -1) {
11796 err = got_error_from_errno("asprintf");
11798 done:
11799 if (folded_commit)
11800 got_object_commit_close(folded_commit);
11801 free(id_str);
11802 free(folded_logmsg);
11803 return err;
11806 static struct got_histedit_list_entry *
11807 get_folded_commits(struct got_histedit_list_entry *hle)
11809 struct got_histedit_list_entry *prev, *folded = NULL;
11811 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11812 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11813 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11814 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11815 folded = prev;
11816 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11819 return folded;
11822 static const struct got_error *
11823 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11824 struct got_repository *repo)
11826 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11827 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11828 const struct got_error *err = NULL;
11829 struct got_commit_object *commit = NULL;
11830 int logmsg_len;
11831 int fd = -1;
11832 struct got_histedit_list_entry *folded = NULL;
11834 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11835 if (err)
11836 return err;
11838 folded = get_folded_commits(hle);
11839 if (folded) {
11840 while (folded != hle) {
11841 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11842 folded = TAILQ_NEXT(folded, entry);
11843 continue;
11845 err = append_folded_commit_msg(&new_msg, folded,
11846 logmsg, repo);
11847 if (err)
11848 goto done;
11849 free(logmsg);
11850 logmsg = new_msg;
11851 folded = TAILQ_NEXT(folded, entry);
11855 err = got_object_id_str(&id_str, hle->commit_id);
11856 if (err)
11857 goto done;
11858 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11859 if (err)
11860 goto done;
11861 logmsg_len = asprintf(&new_msg,
11862 "%s\n# original log message of commit %s: %s",
11863 logmsg ? logmsg : "", id_str, orig_logmsg);
11864 if (logmsg_len == -1) {
11865 err = got_error_from_errno("asprintf");
11866 goto done;
11868 free(logmsg);
11869 logmsg = new_msg;
11871 err = got_object_id_str(&id_str, hle->commit_id);
11872 if (err)
11873 goto done;
11875 err = got_opentemp_named_fd(&logmsg_path, &fd,
11876 GOT_TMPDIR_STR "/got-logmsg", "");
11877 if (err)
11878 goto done;
11880 if (write(fd, logmsg, logmsg_len) == -1) {
11881 err = got_error_from_errno2("write", logmsg_path);
11882 goto done;
11884 if (close(fd) == -1) {
11885 err = got_error_from_errno2("close", logmsg_path);
11886 goto done;
11888 fd = -1;
11890 err = get_editor(&editor);
11891 if (err)
11892 goto done;
11894 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11895 logmsg_len, 0);
11896 if (err) {
11897 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11898 goto done;
11899 err = NULL;
11900 hle->logmsg = strdup(new_msg);
11901 if (hle->logmsg == NULL)
11902 err = got_error_from_errno("strdup");
11904 done:
11905 if (fd != -1 && close(fd) == -1 && err == NULL)
11906 err = got_error_from_errno2("close", logmsg_path);
11907 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11908 err = got_error_from_errno2("unlink", logmsg_path);
11909 free(logmsg_path);
11910 free(logmsg);
11911 free(orig_logmsg);
11912 free(editor);
11913 if (commit)
11914 got_object_commit_close(commit);
11915 return err;
11918 static const struct got_error *
11919 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11920 FILE *f, struct got_repository *repo)
11922 const struct got_error *err = NULL;
11923 char *line = NULL, *p, *end;
11924 size_t i, linesize = 0;
11925 ssize_t linelen;
11926 int lineno = 0, lastcmd = -1;
11927 const struct got_histedit_cmd *cmd;
11928 struct got_object_id *commit_id = NULL;
11929 struct got_histedit_list_entry *hle = NULL;
11931 for (;;) {
11932 linelen = getline(&line, &linesize, f);
11933 if (linelen == -1) {
11934 const struct got_error *getline_err;
11935 if (feof(f))
11936 break;
11937 getline_err = got_error_from_errno("getline");
11938 err = got_ferror(f, getline_err->code);
11939 break;
11941 lineno++;
11942 p = line;
11943 while (isspace((unsigned char)p[0]))
11944 p++;
11945 if (p[0] == '#' || p[0] == '\0')
11946 continue;
11947 cmd = NULL;
11948 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11949 cmd = &got_histedit_cmds[i];
11950 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11951 isspace((unsigned char)p[strlen(cmd->name)])) {
11952 p += strlen(cmd->name);
11953 break;
11955 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11956 p++;
11957 break;
11960 if (i == nitems(got_histedit_cmds)) {
11961 err = histedit_syntax_error(lineno);
11962 break;
11964 while (isspace((unsigned char)p[0]))
11965 p++;
11966 if (cmd->code == GOT_HISTEDIT_MESG) {
11967 if (lastcmd != GOT_HISTEDIT_PICK &&
11968 lastcmd != GOT_HISTEDIT_EDIT) {
11969 err = got_error(GOT_ERR_HISTEDIT_CMD);
11970 break;
11972 if (p[0] == '\0') {
11973 err = histedit_edit_logmsg(hle, repo);
11974 if (err)
11975 break;
11976 } else {
11977 hle->logmsg = strdup(p);
11978 if (hle->logmsg == NULL) {
11979 err = got_error_from_errno("strdup");
11980 break;
11983 lastcmd = cmd->code;
11984 continue;
11985 } else {
11986 end = p;
11987 while (end[0] && !isspace((unsigned char)end[0]))
11988 end++;
11989 *end = '\0';
11991 err = got_object_resolve_id_str(&commit_id, repo, p);
11992 if (err) {
11993 /* override error code */
11994 err = histedit_syntax_error(lineno);
11995 break;
11998 hle = malloc(sizeof(*hle));
11999 if (hle == NULL) {
12000 err = got_error_from_errno("malloc");
12001 break;
12003 hle->cmd = cmd;
12004 hle->commit_id = commit_id;
12005 hle->logmsg = NULL;
12006 commit_id = NULL;
12007 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12008 lastcmd = cmd->code;
12011 free(line);
12012 free(commit_id);
12013 return err;
12016 static const struct got_error *
12017 histedit_check_script(struct got_histedit_list *histedit_cmds,
12018 struct got_object_id_queue *commits, struct got_repository *repo)
12020 const struct got_error *err = NULL;
12021 struct got_object_qid *qid;
12022 struct got_histedit_list_entry *hle;
12023 static char msg[92];
12024 char *id_str;
12026 if (TAILQ_EMPTY(histedit_cmds))
12027 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12028 "histedit script contains no commands");
12029 if (STAILQ_EMPTY(commits))
12030 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12032 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12033 struct got_histedit_list_entry *hle2;
12034 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12035 if (hle == hle2)
12036 continue;
12037 if (got_object_id_cmp(hle->commit_id,
12038 hle2->commit_id) != 0)
12039 continue;
12040 err = got_object_id_str(&id_str, hle->commit_id);
12041 if (err)
12042 return err;
12043 snprintf(msg, sizeof(msg), "commit %s is listed "
12044 "more than once in histedit script", id_str);
12045 free(id_str);
12046 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12050 STAILQ_FOREACH(qid, commits, entry) {
12051 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12052 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12053 break;
12055 if (hle == NULL) {
12056 err = got_object_id_str(&id_str, &qid->id);
12057 if (err)
12058 return err;
12059 snprintf(msg, sizeof(msg),
12060 "commit %s missing from histedit script", id_str);
12061 free(id_str);
12062 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12066 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12067 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12068 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12069 "last commit in histedit script cannot be folded");
12071 return NULL;
12074 static const struct got_error *
12075 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12076 const char *path, struct got_object_id_queue *commits,
12077 struct got_repository *repo)
12079 const struct got_error *err = NULL;
12080 struct stat st, st2;
12081 struct timespec timeout;
12082 char *editor;
12083 FILE *f = NULL;
12085 err = get_editor(&editor);
12086 if (err)
12087 return err;
12089 if (stat(path, &st) == -1) {
12090 err = got_error_from_errno2("stat", path);
12091 goto done;
12094 if (spawn_editor(editor, path) == -1) {
12095 err = got_error_from_errno("failed spawning editor");
12096 goto done;
12099 timeout.tv_sec = 0;
12100 timeout.tv_nsec = 1;
12101 nanosleep(&timeout, NULL);
12103 if (stat(path, &st2) == -1) {
12104 err = got_error_from_errno2("stat", path);
12105 goto done;
12108 if (st.st_size == st2.st_size &&
12109 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12110 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12111 "no changes made to histedit script, aborting");
12112 goto done;
12115 f = fopen(path, "re");
12116 if (f == NULL) {
12117 err = got_error_from_errno("fopen");
12118 goto done;
12120 err = histedit_parse_list(histedit_cmds, f, repo);
12121 if (err)
12122 goto done;
12124 err = histedit_check_script(histedit_cmds, commits, repo);
12125 done:
12126 if (f && fclose(f) == EOF && err == NULL)
12127 err = got_error_from_errno("fclose");
12128 free(editor);
12129 return err;
12132 static const struct got_error *
12133 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12134 struct got_object_id_queue *, const char *, const char *,
12135 struct got_repository *);
12137 static const struct got_error *
12138 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12139 struct got_object_id_queue *commits, const char *branch_name,
12140 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12141 struct got_repository *repo)
12143 const struct got_error *err;
12144 FILE *f = NULL;
12145 char *path = NULL;
12147 err = got_opentemp_named(&path, &f, "got-histedit", "");
12148 if (err)
12149 return err;
12151 err = write_cmd_list(f, branch_name, commits);
12152 if (err)
12153 goto done;
12155 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12156 fold_only, drop_only, edit_only, repo);
12157 if (err)
12158 goto done;
12160 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12161 rewind(f);
12162 err = histedit_parse_list(histedit_cmds, f, repo);
12163 } else {
12164 if (fclose(f) == EOF) {
12165 err = got_error_from_errno("fclose");
12166 goto done;
12168 f = NULL;
12169 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12170 if (err) {
12171 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12172 err->code != GOT_ERR_HISTEDIT_CMD)
12173 goto done;
12174 err = histedit_edit_list_retry(histedit_cmds, err,
12175 commits, path, branch_name, repo);
12178 done:
12179 if (f && fclose(f) == EOF && err == NULL)
12180 err = got_error_from_errno("fclose");
12181 if (path && unlink(path) != 0 && err == NULL)
12182 err = got_error_from_errno2("unlink", path);
12183 free(path);
12184 return err;
12187 static const struct got_error *
12188 histedit_save_list(struct got_histedit_list *histedit_cmds,
12189 struct got_worktree *worktree, struct got_repository *repo)
12191 const struct got_error *err = NULL;
12192 char *path = NULL;
12193 FILE *f = NULL;
12194 struct got_histedit_list_entry *hle;
12195 struct got_commit_object *commit = NULL;
12197 err = got_worktree_get_histedit_script_path(&path, worktree);
12198 if (err)
12199 return err;
12201 f = fopen(path, "we");
12202 if (f == NULL) {
12203 err = got_error_from_errno2("fopen", path);
12204 goto done;
12206 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12207 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12208 repo);
12209 if (err)
12210 break;
12212 if (hle->logmsg) {
12213 int n = fprintf(f, "%c %s\n",
12214 GOT_HISTEDIT_MESG, hle->logmsg);
12215 if (n < 0) {
12216 err = got_ferror(f, GOT_ERR_IO);
12217 break;
12221 done:
12222 if (f && fclose(f) == EOF && err == NULL)
12223 err = got_error_from_errno("fclose");
12224 free(path);
12225 if (commit)
12226 got_object_commit_close(commit);
12227 return err;
12230 static void
12231 histedit_free_list(struct got_histedit_list *histedit_cmds)
12233 struct got_histedit_list_entry *hle;
12235 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12236 TAILQ_REMOVE(histedit_cmds, hle, entry);
12237 free(hle);
12241 static const struct got_error *
12242 histedit_load_list(struct got_histedit_list *histedit_cmds,
12243 const char *path, struct got_repository *repo)
12245 const struct got_error *err = NULL;
12246 FILE *f = NULL;
12248 f = fopen(path, "re");
12249 if (f == NULL) {
12250 err = got_error_from_errno2("fopen", path);
12251 goto done;
12254 err = histedit_parse_list(histedit_cmds, f, repo);
12255 done:
12256 if (f && fclose(f) == EOF && err == NULL)
12257 err = got_error_from_errno("fclose");
12258 return err;
12261 static const struct got_error *
12262 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12263 const struct got_error *edit_err, struct got_object_id_queue *commits,
12264 const char *path, const char *branch_name, struct got_repository *repo)
12266 const struct got_error *err = NULL, *prev_err = edit_err;
12267 int resp = ' ';
12269 while (resp != 'c' && resp != 'r' && resp != 'a') {
12270 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12271 "or (a)bort: ", getprogname(), prev_err->msg);
12272 resp = getchar();
12273 if (resp == '\n')
12274 resp = getchar();
12275 if (resp == 'c') {
12276 histedit_free_list(histedit_cmds);
12277 err = histedit_run_editor(histedit_cmds, path, commits,
12278 repo);
12279 if (err) {
12280 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12281 err->code != GOT_ERR_HISTEDIT_CMD)
12282 break;
12283 prev_err = err;
12284 resp = ' ';
12285 continue;
12287 break;
12288 } else if (resp == 'r') {
12289 histedit_free_list(histedit_cmds);
12290 err = histedit_edit_script(histedit_cmds,
12291 commits, branch_name, 0, 0, 0, 0, repo);
12292 if (err) {
12293 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12294 err->code != GOT_ERR_HISTEDIT_CMD)
12295 break;
12296 prev_err = err;
12297 resp = ' ';
12298 continue;
12300 break;
12301 } else if (resp == 'a') {
12302 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12303 break;
12304 } else
12305 printf("invalid response '%c'\n", resp);
12308 return err;
12311 static const struct got_error *
12312 histedit_complete(struct got_worktree *worktree,
12313 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12314 struct got_reference *branch, struct got_repository *repo)
12316 printf("Switching work tree to %s\n",
12317 got_ref_get_symref_target(branch));
12318 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12319 branch, repo);
12322 static const struct got_error *
12323 show_histedit_progress(struct got_commit_object *commit,
12324 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12326 const struct got_error *err;
12327 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12329 err = got_object_id_str(&old_id_str, hle->commit_id);
12330 if (err)
12331 goto done;
12333 if (new_id) {
12334 err = got_object_id_str(&new_id_str, new_id);
12335 if (err)
12336 goto done;
12339 old_id_str[12] = '\0';
12340 if (new_id_str)
12341 new_id_str[12] = '\0';
12343 if (hle->logmsg) {
12344 logmsg = strdup(hle->logmsg);
12345 if (logmsg == NULL) {
12346 err = got_error_from_errno("strdup");
12347 goto done;
12349 trim_logmsg(logmsg, 42);
12350 } else {
12351 err = get_short_logmsg(&logmsg, 42, commit);
12352 if (err)
12353 goto done;
12356 switch (hle->cmd->code) {
12357 case GOT_HISTEDIT_PICK:
12358 case GOT_HISTEDIT_EDIT:
12359 printf("%s -> %s: %s\n", old_id_str,
12360 new_id_str ? new_id_str : "no-op change", logmsg);
12361 break;
12362 case GOT_HISTEDIT_DROP:
12363 case GOT_HISTEDIT_FOLD:
12364 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12365 logmsg);
12366 break;
12367 default:
12368 break;
12370 done:
12371 free(old_id_str);
12372 free(new_id_str);
12373 return err;
12376 static const struct got_error *
12377 histedit_commit(struct got_pathlist_head *merged_paths,
12378 struct got_worktree *worktree, struct got_fileindex *fileindex,
12379 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12380 const char *committer, int allow_conflict, struct got_repository *repo)
12382 const struct got_error *err;
12383 struct got_commit_object *commit;
12384 struct got_object_id *new_commit_id;
12386 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12387 && hle->logmsg == NULL) {
12388 err = histedit_edit_logmsg(hle, repo);
12389 if (err)
12390 return err;
12393 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12394 if (err)
12395 return err;
12397 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12398 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12399 hle->logmsg, allow_conflict, repo);
12400 if (err) {
12401 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12402 goto done;
12403 err = show_histedit_progress(commit, hle, NULL);
12404 } else {
12405 err = show_histedit_progress(commit, hle, new_commit_id);
12406 free(new_commit_id);
12408 done:
12409 got_object_commit_close(commit);
12410 return err;
12413 static const struct got_error *
12414 histedit_skip_commit(struct got_histedit_list_entry *hle,
12415 struct got_worktree *worktree, struct got_repository *repo)
12417 const struct got_error *error;
12418 struct got_commit_object *commit;
12420 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12421 repo);
12422 if (error)
12423 return error;
12425 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12426 if (error)
12427 return error;
12429 error = show_histedit_progress(commit, hle, NULL);
12430 got_object_commit_close(commit);
12431 return error;
12434 static const struct got_error *
12435 check_local_changes(void *arg, unsigned char status,
12436 unsigned char staged_status, const char *path,
12437 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12438 struct got_object_id *commit_id, int dirfd, const char *de_name)
12440 int *have_local_changes = arg;
12442 switch (status) {
12443 case GOT_STATUS_ADD:
12444 case GOT_STATUS_DELETE:
12445 case GOT_STATUS_MODIFY:
12446 case GOT_STATUS_CONFLICT:
12447 *have_local_changes = 1;
12448 return got_error(GOT_ERR_CANCELLED);
12449 default:
12450 break;
12453 switch (staged_status) {
12454 case GOT_STATUS_ADD:
12455 case GOT_STATUS_DELETE:
12456 case GOT_STATUS_MODIFY:
12457 *have_local_changes = 1;
12458 return got_error(GOT_ERR_CANCELLED);
12459 default:
12460 break;
12463 return NULL;
12466 static const struct got_error *
12467 cmd_histedit(int argc, char *argv[])
12469 const struct got_error *error = NULL;
12470 struct got_worktree *worktree = NULL;
12471 struct got_fileindex *fileindex = NULL;
12472 struct got_repository *repo = NULL;
12473 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12474 struct got_reference *branch = NULL;
12475 struct got_reference *tmp_branch = NULL;
12476 struct got_object_id *resume_commit_id = NULL;
12477 struct got_object_id *base_commit_id = NULL;
12478 struct got_object_id *head_commit_id = NULL;
12479 struct got_commit_object *commit = NULL;
12480 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12481 struct got_update_progress_arg upa;
12482 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12483 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12484 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12485 const char *edit_script_path = NULL;
12486 struct got_object_id_queue commits;
12487 struct got_pathlist_head merged_paths;
12488 const struct got_object_id_queue *parent_ids;
12489 struct got_object_qid *pid;
12490 struct got_histedit_list histedit_cmds;
12491 struct got_histedit_list_entry *hle;
12492 int *pack_fds = NULL;
12494 STAILQ_INIT(&commits);
12495 TAILQ_INIT(&histedit_cmds);
12496 TAILQ_INIT(&merged_paths);
12497 memset(&upa, 0, sizeof(upa));
12499 #ifndef PROFILE
12500 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12501 "unveil", NULL) == -1)
12502 err(1, "pledge");
12503 #endif
12505 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12506 switch (ch) {
12507 case 'a':
12508 abort_edit = 1;
12509 break;
12510 case 'C':
12511 allow_conflict = 1;
12512 break;
12513 case 'c':
12514 continue_edit = 1;
12515 break;
12516 case 'd':
12517 drop_only = 1;
12518 break;
12519 case 'e':
12520 edit_only = 1;
12521 break;
12522 case 'F':
12523 edit_script_path = optarg;
12524 break;
12525 case 'f':
12526 fold_only = 1;
12527 break;
12528 case 'l':
12529 list_backups = 1;
12530 break;
12531 case 'm':
12532 edit_logmsg_only = 1;
12533 break;
12534 case 'X':
12535 delete_backups = 1;
12536 break;
12537 default:
12538 usage_histedit();
12539 /* NOTREACHED */
12543 argc -= optind;
12544 argv += optind;
12546 if (abort_edit && allow_conflict)
12547 option_conflict('a', 'C');
12548 if (abort_edit && continue_edit)
12549 option_conflict('a', 'c');
12550 if (edit_script_path && allow_conflict)
12551 option_conflict('F', 'C');
12552 if (edit_script_path && edit_logmsg_only)
12553 option_conflict('F', 'm');
12554 if (abort_edit && edit_logmsg_only)
12555 option_conflict('a', 'm');
12556 if (edit_logmsg_only && allow_conflict)
12557 option_conflict('m', 'C');
12558 if (continue_edit && edit_logmsg_only)
12559 option_conflict('c', 'm');
12560 if (abort_edit && fold_only)
12561 option_conflict('a', 'f');
12562 if (fold_only && allow_conflict)
12563 option_conflict('f', 'C');
12564 if (continue_edit && fold_only)
12565 option_conflict('c', 'f');
12566 if (fold_only && edit_logmsg_only)
12567 option_conflict('f', 'm');
12568 if (edit_script_path && fold_only)
12569 option_conflict('F', 'f');
12570 if (abort_edit && edit_only)
12571 option_conflict('a', 'e');
12572 if (continue_edit && edit_only)
12573 option_conflict('c', 'e');
12574 if (edit_only && edit_logmsg_only)
12575 option_conflict('e', 'm');
12576 if (edit_script_path && edit_only)
12577 option_conflict('F', 'e');
12578 if (fold_only && edit_only)
12579 option_conflict('f', 'e');
12580 if (drop_only && abort_edit)
12581 option_conflict('d', 'a');
12582 if (drop_only && allow_conflict)
12583 option_conflict('d', 'C');
12584 if (drop_only && continue_edit)
12585 option_conflict('d', 'c');
12586 if (drop_only && edit_logmsg_only)
12587 option_conflict('d', 'm');
12588 if (drop_only && edit_only)
12589 option_conflict('d', 'e');
12590 if (drop_only && edit_script_path)
12591 option_conflict('d', 'F');
12592 if (drop_only && fold_only)
12593 option_conflict('d', 'f');
12594 if (list_backups) {
12595 if (abort_edit)
12596 option_conflict('l', 'a');
12597 if (allow_conflict)
12598 option_conflict('l', 'C');
12599 if (continue_edit)
12600 option_conflict('l', 'c');
12601 if (edit_script_path)
12602 option_conflict('l', 'F');
12603 if (edit_logmsg_only)
12604 option_conflict('l', 'm');
12605 if (drop_only)
12606 option_conflict('l', 'd');
12607 if (fold_only)
12608 option_conflict('l', 'f');
12609 if (edit_only)
12610 option_conflict('l', 'e');
12611 if (delete_backups)
12612 option_conflict('l', 'X');
12613 if (argc != 0 && argc != 1)
12614 usage_histedit();
12615 } else if (delete_backups) {
12616 if (abort_edit)
12617 option_conflict('X', 'a');
12618 if (allow_conflict)
12619 option_conflict('X', 'C');
12620 if (continue_edit)
12621 option_conflict('X', 'c');
12622 if (drop_only)
12623 option_conflict('X', 'd');
12624 if (edit_script_path)
12625 option_conflict('X', 'F');
12626 if (edit_logmsg_only)
12627 option_conflict('X', 'm');
12628 if (fold_only)
12629 option_conflict('X', 'f');
12630 if (edit_only)
12631 option_conflict('X', 'e');
12632 if (list_backups)
12633 option_conflict('X', 'l');
12634 if (argc != 0 && argc != 1)
12635 usage_histedit();
12636 } else if (allow_conflict && !continue_edit)
12637 errx(1, "-C option requires -c");
12638 else if (argc != 0)
12639 usage_histedit();
12642 * This command cannot apply unveil(2) in all cases because the
12643 * user may choose to run an editor to edit the histedit script
12644 * and to edit individual commit log messages.
12645 * unveil(2) traverses exec(2); if an editor is used we have to
12646 * apply unveil after edit script and log messages have been written.
12647 * XXX TODO: Make use of unveil(2) where possible.
12650 cwd = getcwd(NULL, 0);
12651 if (cwd == NULL) {
12652 error = got_error_from_errno("getcwd");
12653 goto done;
12656 error = got_repo_pack_fds_open(&pack_fds);
12657 if (error != NULL)
12658 goto done;
12660 error = got_worktree_open(&worktree, cwd);
12661 if (error) {
12662 if (list_backups || delete_backups) {
12663 if (error->code != GOT_ERR_NOT_WORKTREE)
12664 goto done;
12665 } else {
12666 if (error->code == GOT_ERR_NOT_WORKTREE)
12667 error = wrap_not_worktree_error(error,
12668 "histedit", cwd);
12669 goto done;
12673 if (list_backups || delete_backups) {
12674 error = got_repo_open(&repo,
12675 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12676 NULL, pack_fds);
12677 if (error != NULL)
12678 goto done;
12679 error = apply_unveil(got_repo_get_path(repo), 0,
12680 worktree ? got_worktree_get_root_path(worktree) : NULL);
12681 if (error)
12682 goto done;
12683 error = process_backup_refs(
12684 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12685 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12686 goto done; /* nothing else to do */
12689 error = get_gitconfig_path(&gitconfig_path);
12690 if (error)
12691 goto done;
12692 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12693 gitconfig_path, pack_fds);
12694 if (error != NULL)
12695 goto done;
12697 if (worktree != NULL && !list_backups && !delete_backups) {
12698 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12699 if (error)
12700 goto done;
12703 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12704 if (error)
12705 goto done;
12706 if (rebase_in_progress) {
12707 error = got_error(GOT_ERR_REBASING);
12708 goto done;
12711 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12712 repo);
12713 if (error)
12714 goto done;
12715 if (merge_in_progress) {
12716 error = got_error(GOT_ERR_MERGE_BUSY);
12717 goto done;
12720 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12721 if (error)
12722 goto done;
12724 if (edit_in_progress && edit_logmsg_only) {
12725 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12726 "histedit operation is in progress in this "
12727 "work tree and must be continued or aborted "
12728 "before the -m option can be used");
12729 goto done;
12731 if (edit_in_progress && drop_only) {
12732 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12733 "histedit operation is in progress in this "
12734 "work tree and must be continued or aborted "
12735 "before the -d option can be used");
12736 goto done;
12738 if (edit_in_progress && fold_only) {
12739 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12740 "histedit operation is in progress in this "
12741 "work tree and must be continued or aborted "
12742 "before the -f option can be used");
12743 goto done;
12745 if (edit_in_progress && edit_only) {
12746 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12747 "histedit operation is in progress in this "
12748 "work tree and must be continued or aborted "
12749 "before the -e option can be used");
12750 goto done;
12753 if (edit_in_progress && abort_edit) {
12754 error = got_worktree_histedit_continue(&resume_commit_id,
12755 &tmp_branch, &branch, &base_commit_id, &fileindex,
12756 worktree, repo);
12757 if (error)
12758 goto done;
12759 printf("Switching work tree to %s\n",
12760 got_ref_get_symref_target(branch));
12761 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12762 branch, base_commit_id, abort_progress, &upa);
12763 if (error)
12764 goto done;
12765 printf("Histedit of %s aborted\n",
12766 got_ref_get_symref_target(branch));
12767 print_merge_progress_stats(&upa);
12768 goto done; /* nothing else to do */
12769 } else if (abort_edit) {
12770 error = got_error(GOT_ERR_NOT_HISTEDIT);
12771 goto done;
12774 error = get_author(&committer, repo, worktree);
12775 if (error)
12776 goto done;
12778 if (continue_edit) {
12779 char *path;
12781 if (!edit_in_progress) {
12782 error = got_error(GOT_ERR_NOT_HISTEDIT);
12783 goto done;
12786 error = got_worktree_get_histedit_script_path(&path, worktree);
12787 if (error)
12788 goto done;
12790 error = histedit_load_list(&histedit_cmds, path, repo);
12791 free(path);
12792 if (error)
12793 goto done;
12795 error = got_worktree_histedit_continue(&resume_commit_id,
12796 &tmp_branch, &branch, &base_commit_id, &fileindex,
12797 worktree, repo);
12798 if (error)
12799 goto done;
12801 error = got_ref_resolve(&head_commit_id, repo, branch);
12802 if (error)
12803 goto done;
12805 error = got_object_open_as_commit(&commit, repo,
12806 head_commit_id);
12807 if (error)
12808 goto done;
12809 parent_ids = got_object_commit_get_parent_ids(commit);
12810 pid = STAILQ_FIRST(parent_ids);
12811 if (pid == NULL) {
12812 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12813 goto done;
12815 error = collect_commits(&commits, head_commit_id, &pid->id,
12816 base_commit_id, got_worktree_get_path_prefix(worktree),
12817 GOT_ERR_HISTEDIT_PATH, repo);
12818 got_object_commit_close(commit);
12819 commit = NULL;
12820 if (error)
12821 goto done;
12822 } else {
12823 if (edit_in_progress) {
12824 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12825 goto done;
12828 error = got_ref_open(&branch, repo,
12829 got_worktree_get_head_ref_name(worktree), 0);
12830 if (error != NULL)
12831 goto done;
12833 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12834 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12835 "will not edit commit history of a branch outside "
12836 "the \"refs/heads/\" reference namespace");
12837 goto done;
12840 error = got_ref_resolve(&head_commit_id, repo, branch);
12841 got_ref_close(branch);
12842 branch = NULL;
12843 if (error)
12844 goto done;
12846 error = got_object_open_as_commit(&commit, repo,
12847 head_commit_id);
12848 if (error)
12849 goto done;
12850 parent_ids = got_object_commit_get_parent_ids(commit);
12851 pid = STAILQ_FIRST(parent_ids);
12852 if (pid == NULL) {
12853 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12854 goto done;
12856 error = collect_commits(&commits, head_commit_id, &pid->id,
12857 got_worktree_get_base_commit_id(worktree),
12858 got_worktree_get_path_prefix(worktree),
12859 GOT_ERR_HISTEDIT_PATH, repo);
12860 got_object_commit_close(commit);
12861 commit = NULL;
12862 if (error)
12863 goto done;
12865 if (STAILQ_EMPTY(&commits)) {
12866 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12867 goto done;
12870 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12871 &base_commit_id, &fileindex, worktree, repo);
12872 if (error)
12873 goto done;
12875 if (edit_script_path) {
12876 error = histedit_load_list(&histedit_cmds,
12877 edit_script_path, repo);
12878 if (error) {
12879 got_worktree_histedit_abort(worktree, fileindex,
12880 repo, branch, base_commit_id,
12881 abort_progress, &upa);
12882 print_merge_progress_stats(&upa);
12883 goto done;
12885 } else {
12886 const char *branch_name;
12887 branch_name = got_ref_get_symref_target(branch);
12888 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12889 branch_name += 11;
12890 error = histedit_edit_script(&histedit_cmds, &commits,
12891 branch_name, edit_logmsg_only, fold_only,
12892 drop_only, edit_only, repo);
12893 if (error) {
12894 got_worktree_histedit_abort(worktree, fileindex,
12895 repo, branch, base_commit_id,
12896 abort_progress, &upa);
12897 print_merge_progress_stats(&upa);
12898 goto done;
12903 error = histedit_save_list(&histedit_cmds, worktree,
12904 repo);
12905 if (error) {
12906 got_worktree_histedit_abort(worktree, fileindex,
12907 repo, branch, base_commit_id,
12908 abort_progress, &upa);
12909 print_merge_progress_stats(&upa);
12910 goto done;
12915 error = histedit_check_script(&histedit_cmds, &commits, repo);
12916 if (error)
12917 goto done;
12919 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12920 if (resume_commit_id) {
12921 if (got_object_id_cmp(hle->commit_id,
12922 resume_commit_id) != 0)
12923 continue;
12925 resume_commit_id = NULL;
12926 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12927 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12928 error = histedit_skip_commit(hle, worktree,
12929 repo);
12930 if (error)
12931 goto done;
12932 } else {
12933 struct got_pathlist_head paths;
12934 int have_changes = 0;
12936 TAILQ_INIT(&paths);
12937 error = got_pathlist_append(&paths, "", NULL);
12938 if (error)
12939 goto done;
12940 error = got_worktree_status(worktree, &paths,
12941 repo, 0, check_local_changes, &have_changes,
12942 check_cancelled, NULL);
12943 got_pathlist_free(&paths,
12944 GOT_PATHLIST_FREE_NONE);
12945 if (error) {
12946 if (error->code != GOT_ERR_CANCELLED)
12947 goto done;
12948 if (sigint_received || sigpipe_received)
12949 goto done;
12951 if (have_changes) {
12952 error = histedit_commit(NULL, worktree,
12953 fileindex, tmp_branch, hle,
12954 committer, allow_conflict, repo);
12955 if (error)
12956 goto done;
12957 } else {
12958 error = got_object_open_as_commit(
12959 &commit, repo, hle->commit_id);
12960 if (error)
12961 goto done;
12962 error = show_histedit_progress(commit,
12963 hle, NULL);
12964 got_object_commit_close(commit);
12965 commit = NULL;
12966 if (error)
12967 goto done;
12970 continue;
12973 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12974 error = histedit_skip_commit(hle, worktree, repo);
12975 if (error)
12976 goto done;
12977 continue;
12980 error = got_object_open_as_commit(&commit, repo,
12981 hle->commit_id);
12982 if (error)
12983 goto done;
12984 parent_ids = got_object_commit_get_parent_ids(commit);
12985 pid = STAILQ_FIRST(parent_ids);
12987 error = got_worktree_histedit_merge_files(&merged_paths,
12988 worktree, fileindex, &pid->id, hle->commit_id, repo,
12989 update_progress, &upa, check_cancelled, NULL);
12990 if (error)
12991 goto done;
12992 got_object_commit_close(commit);
12993 commit = NULL;
12995 print_merge_progress_stats(&upa);
12996 if (upa.conflicts > 0 || upa.missing > 0 ||
12997 upa.not_deleted > 0 || upa.unversioned > 0) {
12998 if (upa.conflicts > 0) {
12999 error = show_rebase_merge_conflict(
13000 hle->commit_id, repo);
13001 if (error)
13002 goto done;
13004 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13005 break;
13008 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13009 char *id_str;
13010 error = got_object_id_str(&id_str, hle->commit_id);
13011 if (error)
13012 goto done;
13013 printf("Stopping histedit for amending commit %s\n",
13014 id_str);
13015 free(id_str);
13016 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13017 error = got_worktree_histedit_postpone(worktree,
13018 fileindex);
13019 goto done;
13022 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13023 error = histedit_skip_commit(hle, worktree, repo);
13024 if (error)
13025 goto done;
13026 continue;
13029 error = histedit_commit(&merged_paths, worktree, fileindex,
13030 tmp_branch, hle, committer, allow_conflict, repo);
13031 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13032 if (error)
13033 goto done;
13036 if (upa.conflicts > 0 || upa.missing > 0 ||
13037 upa.not_deleted > 0 || upa.unversioned > 0) {
13038 error = got_worktree_histedit_postpone(worktree, fileindex);
13039 if (error)
13040 goto done;
13041 if (upa.conflicts > 0 && upa.missing == 0 &&
13042 upa.not_deleted == 0 && upa.unversioned == 0) {
13043 error = got_error_msg(GOT_ERR_CONFLICTS,
13044 "conflicts must be resolved before histedit "
13045 "can continue");
13046 } else if (upa.conflicts > 0) {
13047 error = got_error_msg(GOT_ERR_CONFLICTS,
13048 "conflicts must be resolved before histedit "
13049 "can continue; changes destined for some "
13050 "files were not yet merged and should be "
13051 "merged manually if required before the "
13052 "histedit operation is continued");
13053 } else {
13054 error = got_error_msg(GOT_ERR_CONFLICTS,
13055 "changes destined for some files were not "
13056 "yet merged and should be merged manually "
13057 "if required before the histedit operation "
13058 "is continued");
13060 } else
13061 error = histedit_complete(worktree, fileindex, tmp_branch,
13062 branch, repo);
13063 done:
13064 free(cwd);
13065 free(committer);
13066 free(gitconfig_path);
13067 got_object_id_queue_free(&commits);
13068 histedit_free_list(&histedit_cmds);
13069 free(head_commit_id);
13070 free(base_commit_id);
13071 free(resume_commit_id);
13072 if (commit)
13073 got_object_commit_close(commit);
13074 if (branch)
13075 got_ref_close(branch);
13076 if (tmp_branch)
13077 got_ref_close(tmp_branch);
13078 if (worktree)
13079 got_worktree_close(worktree);
13080 if (repo) {
13081 const struct got_error *close_err = got_repo_close(repo);
13082 if (error == NULL)
13083 error = close_err;
13085 if (pack_fds) {
13086 const struct got_error *pack_err =
13087 got_repo_pack_fds_close(pack_fds);
13088 if (error == NULL)
13089 error = pack_err;
13091 return error;
13094 __dead static void
13095 usage_integrate(void)
13097 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13098 exit(1);
13101 static const struct got_error *
13102 cmd_integrate(int argc, char *argv[])
13104 const struct got_error *error = NULL;
13105 struct got_repository *repo = NULL;
13106 struct got_worktree *worktree = NULL;
13107 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13108 const char *branch_arg = NULL;
13109 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13110 struct got_fileindex *fileindex = NULL;
13111 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13112 int ch;
13113 struct got_update_progress_arg upa;
13114 int *pack_fds = NULL;
13116 #ifndef PROFILE
13117 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13118 "unveil", NULL) == -1)
13119 err(1, "pledge");
13120 #endif
13122 while ((ch = getopt(argc, argv, "")) != -1) {
13123 switch (ch) {
13124 default:
13125 usage_integrate();
13126 /* NOTREACHED */
13130 argc -= optind;
13131 argv += optind;
13133 if (argc != 1)
13134 usage_integrate();
13135 branch_arg = argv[0];
13137 cwd = getcwd(NULL, 0);
13138 if (cwd == NULL) {
13139 error = got_error_from_errno("getcwd");
13140 goto done;
13143 error = got_repo_pack_fds_open(&pack_fds);
13144 if (error != NULL)
13145 goto done;
13147 error = got_worktree_open(&worktree, cwd);
13148 if (error) {
13149 if (error->code == GOT_ERR_NOT_WORKTREE)
13150 error = wrap_not_worktree_error(error, "integrate",
13151 cwd);
13152 goto done;
13155 error = check_rebase_or_histedit_in_progress(worktree);
13156 if (error)
13157 goto done;
13159 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13160 NULL, pack_fds);
13161 if (error != NULL)
13162 goto done;
13164 error = apply_unveil(got_repo_get_path(repo), 0,
13165 got_worktree_get_root_path(worktree));
13166 if (error)
13167 goto done;
13169 error = check_merge_in_progress(worktree, repo);
13170 if (error)
13171 goto done;
13173 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13174 error = got_error_from_errno("asprintf");
13175 goto done;
13178 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13179 &base_branch_ref, worktree, refname, repo);
13180 if (error)
13181 goto done;
13183 refname = strdup(got_ref_get_name(branch_ref));
13184 if (refname == NULL) {
13185 error = got_error_from_errno("strdup");
13186 got_worktree_integrate_abort(worktree, fileindex, repo,
13187 branch_ref, base_branch_ref);
13188 goto done;
13190 base_refname = strdup(got_ref_get_name(base_branch_ref));
13191 if (base_refname == NULL) {
13192 error = got_error_from_errno("strdup");
13193 got_worktree_integrate_abort(worktree, fileindex, repo,
13194 branch_ref, base_branch_ref);
13195 goto done;
13197 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13198 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13199 got_worktree_integrate_abort(worktree, fileindex, repo,
13200 branch_ref, base_branch_ref);
13201 goto done;
13204 error = got_ref_resolve(&commit_id, repo, branch_ref);
13205 if (error)
13206 goto done;
13208 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13209 if (error)
13210 goto done;
13212 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13213 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13214 "specified branch has already been integrated");
13215 got_worktree_integrate_abort(worktree, fileindex, repo,
13216 branch_ref, base_branch_ref);
13217 goto done;
13220 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13221 if (error) {
13222 if (error->code == GOT_ERR_ANCESTRY)
13223 error = got_error(GOT_ERR_REBASE_REQUIRED);
13224 got_worktree_integrate_abort(worktree, fileindex, repo,
13225 branch_ref, base_branch_ref);
13226 goto done;
13229 memset(&upa, 0, sizeof(upa));
13230 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13231 branch_ref, base_branch_ref, update_progress, &upa,
13232 check_cancelled, NULL);
13233 if (error)
13234 goto done;
13236 printf("Integrated %s into %s\n", refname, base_refname);
13237 print_update_progress_stats(&upa);
13238 done:
13239 if (repo) {
13240 const struct got_error *close_err = got_repo_close(repo);
13241 if (error == NULL)
13242 error = close_err;
13244 if (worktree)
13245 got_worktree_close(worktree);
13246 if (pack_fds) {
13247 const struct got_error *pack_err =
13248 got_repo_pack_fds_close(pack_fds);
13249 if (error == NULL)
13250 error = pack_err;
13252 free(cwd);
13253 free(base_commit_id);
13254 free(commit_id);
13255 free(refname);
13256 free(base_refname);
13257 return error;
13260 __dead static void
13261 usage_merge(void)
13263 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13264 exit(1);
13267 static const struct got_error *
13268 cmd_merge(int argc, char *argv[])
13270 const struct got_error *error = NULL;
13271 struct got_worktree *worktree = NULL;
13272 struct got_repository *repo = NULL;
13273 struct got_fileindex *fileindex = NULL;
13274 char *cwd = NULL, *id_str = NULL, *author = NULL;
13275 char *gitconfig_path = NULL;
13276 struct got_reference *branch = NULL, *wt_branch = NULL;
13277 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13278 struct got_object_id *wt_branch_tip = NULL;
13279 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13280 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13281 struct got_update_progress_arg upa;
13282 struct got_object_id *merge_commit_id = NULL;
13283 char *branch_name = NULL;
13284 int *pack_fds = NULL;
13286 memset(&upa, 0, sizeof(upa));
13288 #ifndef PROFILE
13289 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13290 "unveil", NULL) == -1)
13291 err(1, "pledge");
13292 #endif
13294 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13295 switch (ch) {
13296 case 'a':
13297 abort_merge = 1;
13298 break;
13299 case 'C':
13300 allow_conflict = 1;
13301 break;
13302 case 'c':
13303 continue_merge = 1;
13304 break;
13305 case 'M':
13306 prefer_fast_forward = 0;
13307 break;
13308 case 'n':
13309 interrupt_merge = 1;
13310 break;
13311 default:
13312 usage_merge();
13313 /* NOTREACHED */
13317 argc -= optind;
13318 argv += optind;
13320 if (abort_merge) {
13321 if (continue_merge)
13322 option_conflict('a', 'c');
13323 if (!prefer_fast_forward)
13324 option_conflict('a', 'M');
13325 if (interrupt_merge)
13326 option_conflict('a', 'n');
13327 } else if (continue_merge) {
13328 if (!prefer_fast_forward)
13329 option_conflict('c', 'M');
13330 if (interrupt_merge)
13331 option_conflict('c', 'n');
13333 if (allow_conflict) {
13334 if (!continue_merge)
13335 errx(1, "-C option requires -c");
13337 if (abort_merge || continue_merge) {
13338 if (argc != 0)
13339 usage_merge();
13340 } else if (argc != 1)
13341 usage_merge();
13343 cwd = getcwd(NULL, 0);
13344 if (cwd == NULL) {
13345 error = got_error_from_errno("getcwd");
13346 goto done;
13349 error = got_repo_pack_fds_open(&pack_fds);
13350 if (error != NULL)
13351 goto done;
13353 error = got_worktree_open(&worktree, cwd);
13354 if (error) {
13355 if (error->code == GOT_ERR_NOT_WORKTREE)
13356 error = wrap_not_worktree_error(error,
13357 "merge", cwd);
13358 goto done;
13361 error = get_gitconfig_path(&gitconfig_path);
13362 if (error)
13363 goto done;
13364 error = got_repo_open(&repo,
13365 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13366 gitconfig_path, pack_fds);
13367 if (error != NULL)
13368 goto done;
13370 if (worktree != NULL) {
13371 error = worktree_has_logmsg_ref("merge", worktree, repo);
13372 if (error)
13373 goto done;
13376 error = apply_unveil(got_repo_get_path(repo), 0,
13377 worktree ? got_worktree_get_root_path(worktree) : NULL);
13378 if (error)
13379 goto done;
13381 error = check_rebase_or_histedit_in_progress(worktree);
13382 if (error)
13383 goto done;
13385 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13386 repo);
13387 if (error)
13388 goto done;
13390 if (merge_in_progress && !(abort_merge || continue_merge)) {
13391 error = got_error(GOT_ERR_MERGE_BUSY);
13392 goto done;
13395 if (!merge_in_progress && (abort_merge || continue_merge)) {
13396 error = got_error(GOT_ERR_NOT_MERGING);
13397 goto done;
13400 if (abort_merge) {
13401 error = got_worktree_merge_continue(&branch_name,
13402 &branch_tip, &fileindex, worktree, repo);
13403 if (error)
13404 goto done;
13405 error = got_worktree_merge_abort(worktree, fileindex, repo,
13406 abort_progress, &upa);
13407 if (error)
13408 goto done;
13409 printf("Merge of %s aborted\n", branch_name);
13410 goto done; /* nothing else to do */
13413 if (strncmp(got_worktree_get_head_ref_name(worktree),
13414 "refs/heads/", 11) != 0) {
13415 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13416 "work tree's current branch %s is outside the "
13417 "\"refs/heads/\" reference namespace; "
13418 "update -b required",
13419 got_worktree_get_head_ref_name(worktree));
13420 goto done;
13423 error = get_author(&author, repo, worktree);
13424 if (error)
13425 goto done;
13427 error = got_ref_open(&wt_branch, repo,
13428 got_worktree_get_head_ref_name(worktree), 0);
13429 if (error)
13430 goto done;
13431 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13432 if (error)
13433 goto done;
13435 if (continue_merge) {
13436 struct got_object_id *base_commit_id;
13437 base_commit_id = got_worktree_get_base_commit_id(worktree);
13438 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13439 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13440 goto done;
13442 error = got_worktree_merge_continue(&branch_name,
13443 &branch_tip, &fileindex, worktree, repo);
13444 if (error)
13445 goto done;
13446 } else {
13447 error = got_ref_open(&branch, repo, argv[0], 0);
13448 if (error != NULL)
13449 goto done;
13450 branch_name = strdup(got_ref_get_name(branch));
13451 if (branch_name == NULL) {
13452 error = got_error_from_errno("strdup");
13453 goto done;
13455 error = got_ref_resolve(&branch_tip, repo, branch);
13456 if (error)
13457 goto done;
13460 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13461 wt_branch_tip, branch_tip, 0, repo,
13462 check_cancelled, NULL);
13463 if (error && error->code != GOT_ERR_ANCESTRY)
13464 goto done;
13466 if (!continue_merge) {
13467 error = check_path_prefix(wt_branch_tip, branch_tip,
13468 got_worktree_get_path_prefix(worktree),
13469 GOT_ERR_MERGE_PATH, repo);
13470 if (error)
13471 goto done;
13472 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13473 if (error)
13474 goto done;
13475 if (prefer_fast_forward && yca_id &&
13476 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13477 struct got_pathlist_head paths;
13478 if (interrupt_merge) {
13479 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13480 "there are no changes to merge since %s "
13481 "is already based on %s; merge cannot be "
13482 "interrupted for amending; -n",
13483 branch_name, got_ref_get_name(wt_branch));
13484 goto done;
13486 printf("Forwarding %s to %s\n",
13487 got_ref_get_name(wt_branch), branch_name);
13488 error = got_ref_change_ref(wt_branch, branch_tip);
13489 if (error)
13490 goto done;
13491 error = got_ref_write(wt_branch, repo);
13492 if (error)
13493 goto done;
13494 error = got_worktree_set_base_commit_id(worktree, repo,
13495 branch_tip);
13496 if (error)
13497 goto done;
13498 TAILQ_INIT(&paths);
13499 error = got_pathlist_append(&paths, "", NULL);
13500 if (error)
13501 goto done;
13502 error = got_worktree_checkout_files(worktree,
13503 &paths, repo, update_progress, &upa,
13504 check_cancelled, NULL);
13505 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13506 if (error)
13507 goto done;
13508 if (upa.did_something) {
13509 char *id_str;
13510 error = got_object_id_str(&id_str, branch_tip);
13511 if (error)
13512 goto done;
13513 printf("Updated to commit %s\n", id_str);
13514 free(id_str);
13515 } else
13516 printf("Already up-to-date\n");
13517 print_update_progress_stats(&upa);
13518 goto done;
13520 error = got_worktree_merge_write_refs(worktree, branch, repo);
13521 if (error)
13522 goto done;
13524 error = got_worktree_merge_branch(worktree, fileindex,
13525 yca_id, branch_tip, repo, update_progress, &upa,
13526 check_cancelled, NULL);
13527 if (error)
13528 goto done;
13529 print_merge_progress_stats(&upa);
13530 if (!upa.did_something) {
13531 error = got_worktree_merge_abort(worktree, fileindex,
13532 repo, abort_progress, &upa);
13533 if (error)
13534 goto done;
13535 printf("Already up-to-date\n");
13536 goto done;
13540 if (interrupt_merge) {
13541 error = got_worktree_merge_postpone(worktree, fileindex);
13542 if (error)
13543 goto done;
13544 printf("Merge of %s interrupted on request\n", branch_name);
13545 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13546 upa.not_deleted > 0 || upa.unversioned > 0) {
13547 error = got_worktree_merge_postpone(worktree, fileindex);
13548 if (error)
13549 goto done;
13550 if (upa.conflicts > 0 && upa.missing == 0 &&
13551 upa.not_deleted == 0 && upa.unversioned == 0) {
13552 error = got_error_msg(GOT_ERR_CONFLICTS,
13553 "conflicts must be resolved before merging "
13554 "can continue");
13555 } else if (upa.conflicts > 0) {
13556 error = got_error_msg(GOT_ERR_CONFLICTS,
13557 "conflicts must be resolved before merging "
13558 "can continue; changes destined for some "
13559 "files were not yet merged and "
13560 "should be merged manually if required before the "
13561 "merge operation is continued");
13562 } else {
13563 error = got_error_msg(GOT_ERR_CONFLICTS,
13564 "changes destined for some "
13565 "files were not yet merged and should be "
13566 "merged manually if required before the "
13567 "merge operation is continued");
13569 goto done;
13570 } else {
13571 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13572 fileindex, author, NULL, 1, branch_tip, branch_name,
13573 allow_conflict, repo, continue_merge ? print_status : NULL,
13574 NULL);
13575 if (error)
13576 goto done;
13577 error = got_worktree_merge_complete(worktree, fileindex, repo);
13578 if (error)
13579 goto done;
13580 error = got_object_id_str(&id_str, merge_commit_id);
13581 if (error)
13582 goto done;
13583 printf("Merged %s into %s: %s\n", branch_name,
13584 got_worktree_get_head_ref_name(worktree),
13585 id_str);
13588 done:
13589 free(gitconfig_path);
13590 free(id_str);
13591 free(merge_commit_id);
13592 free(author);
13593 free(branch_tip);
13594 free(branch_name);
13595 free(yca_id);
13596 if (branch)
13597 got_ref_close(branch);
13598 if (wt_branch)
13599 got_ref_close(wt_branch);
13600 if (worktree)
13601 got_worktree_close(worktree);
13602 if (repo) {
13603 const struct got_error *close_err = got_repo_close(repo);
13604 if (error == NULL)
13605 error = close_err;
13607 if (pack_fds) {
13608 const struct got_error *pack_err =
13609 got_repo_pack_fds_close(pack_fds);
13610 if (error == NULL)
13611 error = pack_err;
13613 return error;
13616 __dead static void
13617 usage_stage(void)
13619 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13620 "[path ...]\n", getprogname());
13621 exit(1);
13624 static const struct got_error *
13625 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13626 const char *path, struct got_object_id *blob_id,
13627 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13628 int dirfd, const char *de_name)
13630 const struct got_error *err = NULL;
13631 char *id_str = NULL;
13633 if (staged_status != GOT_STATUS_ADD &&
13634 staged_status != GOT_STATUS_MODIFY &&
13635 staged_status != GOT_STATUS_DELETE)
13636 return NULL;
13638 if (staged_status == GOT_STATUS_ADD ||
13639 staged_status == GOT_STATUS_MODIFY)
13640 err = got_object_id_str(&id_str, staged_blob_id);
13641 else
13642 err = got_object_id_str(&id_str, blob_id);
13643 if (err)
13644 return err;
13646 printf("%s %c %s\n", id_str, staged_status, path);
13647 free(id_str);
13648 return NULL;
13651 static const struct got_error *
13652 cmd_stage(int argc, char *argv[])
13654 const struct got_error *error = NULL;
13655 struct got_repository *repo = NULL;
13656 struct got_worktree *worktree = NULL;
13657 char *cwd = NULL;
13658 struct got_pathlist_head paths;
13659 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13660 FILE *patch_script_file = NULL;
13661 const char *patch_script_path = NULL;
13662 struct choose_patch_arg cpa;
13663 int *pack_fds = NULL;
13665 TAILQ_INIT(&paths);
13667 #ifndef PROFILE
13668 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13669 "unveil", NULL) == -1)
13670 err(1, "pledge");
13671 #endif
13673 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13674 switch (ch) {
13675 case 'F':
13676 patch_script_path = optarg;
13677 break;
13678 case 'l':
13679 list_stage = 1;
13680 break;
13681 case 'p':
13682 pflag = 1;
13683 break;
13684 case 'S':
13685 allow_bad_symlinks = 1;
13686 break;
13687 default:
13688 usage_stage();
13689 /* NOTREACHED */
13693 argc -= optind;
13694 argv += optind;
13696 if (list_stage && (pflag || patch_script_path))
13697 errx(1, "-l option cannot be used with other options");
13698 if (patch_script_path && !pflag)
13699 errx(1, "-F option can only be used together with -p option");
13701 cwd = getcwd(NULL, 0);
13702 if (cwd == NULL) {
13703 error = got_error_from_errno("getcwd");
13704 goto done;
13707 error = got_repo_pack_fds_open(&pack_fds);
13708 if (error != NULL)
13709 goto done;
13711 error = got_worktree_open(&worktree, cwd);
13712 if (error) {
13713 if (error->code == GOT_ERR_NOT_WORKTREE)
13714 error = wrap_not_worktree_error(error, "stage", cwd);
13715 goto done;
13718 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13719 NULL, pack_fds);
13720 if (error != NULL)
13721 goto done;
13723 if (patch_script_path) {
13724 patch_script_file = fopen(patch_script_path, "re");
13725 if (patch_script_file == NULL) {
13726 error = got_error_from_errno2("fopen",
13727 patch_script_path);
13728 goto done;
13731 error = apply_unveil(got_repo_get_path(repo), 0,
13732 got_worktree_get_root_path(worktree));
13733 if (error)
13734 goto done;
13736 error = check_merge_in_progress(worktree, repo);
13737 if (error)
13738 goto done;
13740 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13741 if (error)
13742 goto done;
13744 if (list_stage)
13745 error = got_worktree_status(worktree, &paths, repo, 0,
13746 print_stage, NULL, check_cancelled, NULL);
13747 else {
13748 cpa.patch_script_file = patch_script_file;
13749 cpa.action = "stage";
13750 error = got_worktree_stage(worktree, &paths,
13751 pflag ? NULL : print_status, NULL,
13752 pflag ? choose_patch : NULL, &cpa,
13753 allow_bad_symlinks, repo);
13755 done:
13756 if (patch_script_file && fclose(patch_script_file) == EOF &&
13757 error == NULL)
13758 error = got_error_from_errno2("fclose", patch_script_path);
13759 if (repo) {
13760 const struct got_error *close_err = got_repo_close(repo);
13761 if (error == NULL)
13762 error = close_err;
13764 if (worktree)
13765 got_worktree_close(worktree);
13766 if (pack_fds) {
13767 const struct got_error *pack_err =
13768 got_repo_pack_fds_close(pack_fds);
13769 if (error == NULL)
13770 error = pack_err;
13772 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13773 free(cwd);
13774 return error;
13777 __dead static void
13778 usage_unstage(void)
13780 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13781 "[path ...]\n", getprogname());
13782 exit(1);
13786 static const struct got_error *
13787 cmd_unstage(int argc, char *argv[])
13789 const struct got_error *error = NULL;
13790 struct got_repository *repo = NULL;
13791 struct got_worktree *worktree = NULL;
13792 char *cwd = NULL;
13793 struct got_pathlist_head paths;
13794 int ch, pflag = 0;
13795 struct got_update_progress_arg upa;
13796 FILE *patch_script_file = NULL;
13797 const char *patch_script_path = NULL;
13798 struct choose_patch_arg cpa;
13799 int *pack_fds = NULL;
13801 TAILQ_INIT(&paths);
13803 #ifndef PROFILE
13804 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13805 "unveil", NULL) == -1)
13806 err(1, "pledge");
13807 #endif
13809 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13810 switch (ch) {
13811 case 'F':
13812 patch_script_path = optarg;
13813 break;
13814 case 'p':
13815 pflag = 1;
13816 break;
13817 default:
13818 usage_unstage();
13819 /* NOTREACHED */
13823 argc -= optind;
13824 argv += optind;
13826 if (patch_script_path && !pflag)
13827 errx(1, "-F option can only be used together with -p option");
13829 cwd = getcwd(NULL, 0);
13830 if (cwd == NULL) {
13831 error = got_error_from_errno("getcwd");
13832 goto done;
13835 error = got_repo_pack_fds_open(&pack_fds);
13836 if (error != NULL)
13837 goto done;
13839 error = got_worktree_open(&worktree, cwd);
13840 if (error) {
13841 if (error->code == GOT_ERR_NOT_WORKTREE)
13842 error = wrap_not_worktree_error(error, "unstage", cwd);
13843 goto done;
13846 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13847 NULL, pack_fds);
13848 if (error != NULL)
13849 goto done;
13851 if (patch_script_path) {
13852 patch_script_file = fopen(patch_script_path, "re");
13853 if (patch_script_file == NULL) {
13854 error = got_error_from_errno2("fopen",
13855 patch_script_path);
13856 goto done;
13860 error = apply_unveil(got_repo_get_path(repo), 0,
13861 got_worktree_get_root_path(worktree));
13862 if (error)
13863 goto done;
13865 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13866 if (error)
13867 goto done;
13869 cpa.patch_script_file = patch_script_file;
13870 cpa.action = "unstage";
13871 memset(&upa, 0, sizeof(upa));
13872 error = got_worktree_unstage(worktree, &paths, update_progress,
13873 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13874 if (!error)
13875 print_merge_progress_stats(&upa);
13876 done:
13877 if (patch_script_file && fclose(patch_script_file) == EOF &&
13878 error == NULL)
13879 error = got_error_from_errno2("fclose", patch_script_path);
13880 if (repo) {
13881 const struct got_error *close_err = got_repo_close(repo);
13882 if (error == NULL)
13883 error = close_err;
13885 if (worktree)
13886 got_worktree_close(worktree);
13887 if (pack_fds) {
13888 const struct got_error *pack_err =
13889 got_repo_pack_fds_close(pack_fds);
13890 if (error == NULL)
13891 error = pack_err;
13893 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13894 free(cwd);
13895 return error;
13898 __dead static void
13899 usage_cat(void)
13901 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13902 "arg ...\n", getprogname());
13903 exit(1);
13906 static const struct got_error *
13907 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13909 const struct got_error *err;
13910 struct got_blob_object *blob;
13911 int fd = -1;
13913 fd = got_opentempfd();
13914 if (fd == -1)
13915 return got_error_from_errno("got_opentempfd");
13917 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13918 if (err)
13919 goto done;
13921 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13922 done:
13923 if (fd != -1 && close(fd) == -1 && err == NULL)
13924 err = got_error_from_errno("close");
13925 if (blob)
13926 got_object_blob_close(blob);
13927 return err;
13930 static const struct got_error *
13931 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13933 const struct got_error *err;
13934 struct got_tree_object *tree;
13935 int nentries, i;
13937 err = got_object_open_as_tree(&tree, repo, id);
13938 if (err)
13939 return err;
13941 nentries = got_object_tree_get_nentries(tree);
13942 for (i = 0; i < nentries; i++) {
13943 struct got_tree_entry *te;
13944 char *id_str;
13945 if (sigint_received || sigpipe_received)
13946 break;
13947 te = got_object_tree_get_entry(tree, i);
13948 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13949 if (err)
13950 break;
13951 fprintf(outfile, "%s %.7o %s\n", id_str,
13952 got_tree_entry_get_mode(te),
13953 got_tree_entry_get_name(te));
13954 free(id_str);
13957 got_object_tree_close(tree);
13958 return err;
13961 static const struct got_error *
13962 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13964 const struct got_error *err;
13965 struct got_commit_object *commit;
13966 const struct got_object_id_queue *parent_ids;
13967 struct got_object_qid *pid;
13968 char *id_str = NULL;
13969 const char *logmsg = NULL;
13970 char gmtoff[6];
13972 err = got_object_open_as_commit(&commit, repo, id);
13973 if (err)
13974 return err;
13976 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13977 if (err)
13978 goto done;
13980 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13981 parent_ids = got_object_commit_get_parent_ids(commit);
13982 fprintf(outfile, "numparents %d\n",
13983 got_object_commit_get_nparents(commit));
13984 STAILQ_FOREACH(pid, parent_ids, entry) {
13985 char *pid_str;
13986 err = got_object_id_str(&pid_str, &pid->id);
13987 if (err)
13988 goto done;
13989 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13990 free(pid_str);
13992 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13993 got_object_commit_get_author_gmtoff(commit));
13994 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13995 got_object_commit_get_author(commit),
13996 (long long)got_object_commit_get_author_time(commit),
13997 gmtoff);
13999 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14000 got_object_commit_get_committer_gmtoff(commit));
14001 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14002 got_object_commit_get_committer(commit),
14003 (long long)got_object_commit_get_committer_time(commit),
14004 gmtoff);
14006 logmsg = got_object_commit_get_logmsg_raw(commit);
14007 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14008 fprintf(outfile, "%s", logmsg);
14009 done:
14010 free(id_str);
14011 got_object_commit_close(commit);
14012 return err;
14015 static const struct got_error *
14016 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14018 const struct got_error *err;
14019 struct got_tag_object *tag;
14020 char *id_str = NULL;
14021 const char *tagmsg = NULL;
14022 char gmtoff[6];
14024 err = got_object_open_as_tag(&tag, repo, id);
14025 if (err)
14026 return err;
14028 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14029 if (err)
14030 goto done;
14032 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14034 switch (got_object_tag_get_object_type(tag)) {
14035 case GOT_OBJ_TYPE_BLOB:
14036 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14037 GOT_OBJ_LABEL_BLOB);
14038 break;
14039 case GOT_OBJ_TYPE_TREE:
14040 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14041 GOT_OBJ_LABEL_TREE);
14042 break;
14043 case GOT_OBJ_TYPE_COMMIT:
14044 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14045 GOT_OBJ_LABEL_COMMIT);
14046 break;
14047 case GOT_OBJ_TYPE_TAG:
14048 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14049 GOT_OBJ_LABEL_TAG);
14050 break;
14051 default:
14052 break;
14055 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14056 got_object_tag_get_name(tag));
14058 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14059 got_object_tag_get_tagger_gmtoff(tag));
14060 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14061 got_object_tag_get_tagger(tag),
14062 (long long)got_object_tag_get_tagger_time(tag),
14063 gmtoff);
14065 tagmsg = got_object_tag_get_message(tag);
14066 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14067 fprintf(outfile, "%s", tagmsg);
14068 done:
14069 free(id_str);
14070 got_object_tag_close(tag);
14071 return err;
14074 static const struct got_error *
14075 cmd_cat(int argc, char *argv[])
14077 const struct got_error *error;
14078 struct got_repository *repo = NULL;
14079 struct got_worktree *worktree = NULL;
14080 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14081 char *keyword_idstr = NULL;
14082 const char *commit_id_str = NULL;
14083 struct got_object_id *id = NULL, *commit_id = NULL;
14084 struct got_commit_object *commit = NULL;
14085 int ch, obj_type, i, force_path = 0;
14086 struct got_reflist_head refs;
14087 int *pack_fds = NULL;
14089 TAILQ_INIT(&refs);
14091 #ifndef PROFILE
14092 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14093 NULL) == -1)
14094 err(1, "pledge");
14095 #endif
14097 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14098 switch (ch) {
14099 case 'c':
14100 commit_id_str = optarg;
14101 break;
14102 case 'P':
14103 force_path = 1;
14104 break;
14105 case 'r':
14106 repo_path = realpath(optarg, NULL);
14107 if (repo_path == NULL)
14108 return got_error_from_errno2("realpath",
14109 optarg);
14110 got_path_strip_trailing_slashes(repo_path);
14111 break;
14112 default:
14113 usage_cat();
14114 /* NOTREACHED */
14118 argc -= optind;
14119 argv += optind;
14121 cwd = getcwd(NULL, 0);
14122 if (cwd == NULL) {
14123 error = got_error_from_errno("getcwd");
14124 goto done;
14127 error = got_repo_pack_fds_open(&pack_fds);
14128 if (error != NULL)
14129 goto done;
14131 if (repo_path == NULL) {
14132 error = got_worktree_open(&worktree, cwd);
14133 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14134 goto done;
14135 if (worktree) {
14136 repo_path = strdup(
14137 got_worktree_get_repo_path(worktree));
14138 if (repo_path == NULL) {
14139 error = got_error_from_errno("strdup");
14140 goto done;
14143 if (commit_id_str == NULL) {
14144 /* Release work tree lock. */
14145 got_worktree_close(worktree);
14146 worktree = NULL;
14151 if (repo_path == NULL) {
14152 repo_path = strdup(cwd);
14153 if (repo_path == NULL)
14154 return got_error_from_errno("strdup");
14157 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14158 free(repo_path);
14159 if (error != NULL)
14160 goto done;
14162 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14163 if (error)
14164 goto done;
14166 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14167 if (error)
14168 goto done;
14170 if (commit_id_str != NULL) {
14171 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14172 repo, worktree);
14173 if (error != NULL)
14174 goto done;
14175 if (keyword_idstr != NULL)
14176 commit_id_str = keyword_idstr;
14177 if (worktree != NULL) {
14178 got_worktree_close(worktree);
14179 worktree = NULL;
14181 } else
14182 commit_id_str = GOT_REF_HEAD;
14183 error = got_repo_match_object_id(&commit_id, NULL,
14184 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14185 if (error)
14186 goto done;
14188 error = got_object_open_as_commit(&commit, repo, commit_id);
14189 if (error)
14190 goto done;
14192 for (i = 0; i < argc; i++) {
14193 if (force_path) {
14194 error = got_object_id_by_path(&id, repo, commit,
14195 argv[i]);
14196 if (error)
14197 break;
14198 } else {
14199 error = got_repo_match_object_id(&id, &label, argv[i],
14200 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14201 repo);
14202 if (error) {
14203 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14204 error->code != GOT_ERR_NOT_REF)
14205 break;
14206 error = got_object_id_by_path(&id, repo,
14207 commit, argv[i]);
14208 if (error)
14209 break;
14213 error = got_object_get_type(&obj_type, repo, id);
14214 if (error)
14215 break;
14217 switch (obj_type) {
14218 case GOT_OBJ_TYPE_BLOB:
14219 error = cat_blob(id, repo, stdout);
14220 break;
14221 case GOT_OBJ_TYPE_TREE:
14222 error = cat_tree(id, repo, stdout);
14223 break;
14224 case GOT_OBJ_TYPE_COMMIT:
14225 error = cat_commit(id, repo, stdout);
14226 break;
14227 case GOT_OBJ_TYPE_TAG:
14228 error = cat_tag(id, repo, stdout);
14229 break;
14230 default:
14231 error = got_error(GOT_ERR_OBJ_TYPE);
14232 break;
14234 if (error)
14235 break;
14236 free(label);
14237 label = NULL;
14238 free(id);
14239 id = NULL;
14241 done:
14242 free(label);
14243 free(id);
14244 free(commit_id);
14245 free(keyword_idstr);
14246 if (commit)
14247 got_object_commit_close(commit);
14248 if (worktree)
14249 got_worktree_close(worktree);
14250 if (repo) {
14251 const struct got_error *close_err = got_repo_close(repo);
14252 if (error == NULL)
14253 error = close_err;
14255 if (pack_fds) {
14256 const struct got_error *pack_err =
14257 got_repo_pack_fds_close(pack_fds);
14258 if (error == NULL)
14259 error = pack_err;
14262 got_ref_list_free(&refs);
14263 return error;
14266 __dead static void
14267 usage_info(void)
14269 fprintf(stderr, "usage: %s info [path ...]\n",
14270 getprogname());
14271 exit(1);
14274 static const struct got_error *
14275 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14276 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14277 struct got_object_id *commit_id)
14279 const struct got_error *err = NULL;
14280 char *id_str = NULL;
14281 char datebuf[128];
14282 struct tm mytm, *tm;
14283 struct got_pathlist_head *paths = arg;
14284 struct got_pathlist_entry *pe;
14287 * Clear error indication from any of the path arguments which
14288 * would cause this file index entry to be displayed.
14290 TAILQ_FOREACH(pe, paths, entry) {
14291 if (got_path_cmp(path, pe->path, strlen(path),
14292 pe->path_len) == 0 ||
14293 got_path_is_child(path, pe->path, pe->path_len))
14294 pe->data = NULL; /* no error */
14297 printf(GOT_COMMIT_SEP_STR);
14298 if (S_ISLNK(mode))
14299 printf("symlink: %s\n", path);
14300 else if (S_ISREG(mode)) {
14301 printf("file: %s\n", path);
14302 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14303 } else if (S_ISDIR(mode))
14304 printf("directory: %s\n", path);
14305 else
14306 printf("something: %s\n", path);
14308 tm = localtime_r(&mtime, &mytm);
14309 if (tm == NULL)
14310 return NULL;
14311 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14312 return got_error(GOT_ERR_NO_SPACE);
14313 printf("timestamp: %s\n", datebuf);
14315 if (blob_id) {
14316 err = got_object_id_str(&id_str, blob_id);
14317 if (err)
14318 return err;
14319 printf("based on blob: %s\n", id_str);
14320 free(id_str);
14323 if (staged_blob_id) {
14324 err = got_object_id_str(&id_str, staged_blob_id);
14325 if (err)
14326 return err;
14327 printf("based on staged blob: %s\n", id_str);
14328 free(id_str);
14331 if (commit_id) {
14332 err = got_object_id_str(&id_str, commit_id);
14333 if (err)
14334 return err;
14335 printf("based on commit: %s\n", id_str);
14336 free(id_str);
14339 return NULL;
14342 static const struct got_error *
14343 cmd_info(int argc, char *argv[])
14345 const struct got_error *error = NULL;
14346 struct got_worktree *worktree = NULL;
14347 char *cwd = NULL, *id_str = NULL;
14348 struct got_pathlist_head paths;
14349 char *uuidstr = NULL;
14350 int ch, show_files = 0;
14352 TAILQ_INIT(&paths);
14354 #ifndef PROFILE
14355 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14356 NULL) == -1)
14357 err(1, "pledge");
14358 #endif
14360 while ((ch = getopt(argc, argv, "")) != -1) {
14361 switch (ch) {
14362 default:
14363 usage_info();
14364 /* NOTREACHED */
14368 argc -= optind;
14369 argv += optind;
14371 cwd = getcwd(NULL, 0);
14372 if (cwd == NULL) {
14373 error = got_error_from_errno("getcwd");
14374 goto done;
14377 error = got_worktree_open(&worktree, cwd);
14378 if (error) {
14379 if (error->code == GOT_ERR_NOT_WORKTREE)
14380 error = wrap_not_worktree_error(error, "info", cwd);
14381 goto done;
14384 #ifndef PROFILE
14385 /* Remove "wpath cpath proc exec sendfd" promises. */
14386 if (pledge("stdio rpath flock unveil", NULL) == -1)
14387 err(1, "pledge");
14388 #endif
14389 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14390 if (error)
14391 goto done;
14393 if (argc >= 1) {
14394 error = get_worktree_paths_from_argv(&paths, argc, argv,
14395 worktree);
14396 if (error)
14397 goto done;
14398 show_files = 1;
14401 error = got_object_id_str(&id_str,
14402 got_worktree_get_base_commit_id(worktree));
14403 if (error)
14404 goto done;
14406 error = got_worktree_get_uuid(&uuidstr, worktree);
14407 if (error)
14408 goto done;
14410 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14411 printf("work tree base commit: %s\n", id_str);
14412 printf("work tree path prefix: %s\n",
14413 got_worktree_get_path_prefix(worktree));
14414 printf("work tree branch reference: %s\n",
14415 got_worktree_get_head_ref_name(worktree));
14416 printf("work tree UUID: %s\n", uuidstr);
14417 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14419 if (show_files) {
14420 struct got_pathlist_entry *pe;
14421 TAILQ_FOREACH(pe, &paths, entry) {
14422 if (pe->path_len == 0)
14423 continue;
14425 * Assume this path will fail. This will be corrected
14426 * in print_path_info() in case the path does suceeed.
14428 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14430 error = got_worktree_path_info(worktree, &paths,
14431 print_path_info, &paths, check_cancelled, NULL);
14432 if (error)
14433 goto done;
14434 TAILQ_FOREACH(pe, &paths, entry) {
14435 if (pe->data != NULL) {
14436 const struct got_error *perr;
14438 perr = pe->data;
14439 error = got_error_fmt(perr->code, "%s",
14440 pe->path);
14441 break;
14445 done:
14446 if (worktree)
14447 got_worktree_close(worktree);
14448 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14449 free(cwd);
14450 free(id_str);
14451 free(uuidstr);
14452 return error;