Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
269 return 1;
272 return 0;
275 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
276 list_commands(stderr);
277 return 1;
280 __dead static void
281 usage(int hflag, int status)
283 FILE *fp = (status == 0) ? stdout : stderr;
285 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
286 getprogname());
287 if (hflag)
288 list_commands(fp);
289 exit(status);
292 static const struct got_error *
293 get_editor(char **abspath)
295 const struct got_error *err = NULL;
296 const char *editor;
298 *abspath = NULL;
300 editor = getenv("VISUAL");
301 if (editor == NULL)
302 editor = getenv("EDITOR");
304 if (editor) {
305 err = got_path_find_prog(abspath, editor);
306 if (err)
307 return err;
310 if (*abspath == NULL) {
311 *abspath = strdup("/usr/bin/vi");
312 if (*abspath == NULL)
313 return got_error_from_errno("strdup");
316 return NULL;
319 static const struct got_error *
320 apply_unveil(const char *repo_path, int repo_read_only,
321 const char *worktree_path)
323 const struct got_error *err;
325 #ifdef PROFILE
326 if (unveil("gmon.out", "rwc") != 0)
327 return got_error_from_errno2("unveil", "gmon.out");
328 #endif
329 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
330 return got_error_from_errno2("unveil", repo_path);
332 if (worktree_path && unveil(worktree_path, "rwc") != 0)
333 return got_error_from_errno2("unveil", worktree_path);
335 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
336 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
338 err = got_privsep_unveil_exec_helpers();
339 if (err != NULL)
340 return err;
342 if (unveil(NULL, NULL) != 0)
343 return got_error_from_errno("unveil");
345 return NULL;
348 __dead static void
349 usage_import(void)
351 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
352 "[-r repository-path] directory\n", getprogname());
353 exit(1);
356 static int
357 spawn_editor(const char *editor, const char *file)
359 pid_t pid;
360 sig_t sighup, sigint, sigquit;
361 int st = -1;
363 sighup = signal(SIGHUP, SIG_IGN);
364 sigint = signal(SIGINT, SIG_IGN);
365 sigquit = signal(SIGQUIT, SIG_IGN);
367 switch (pid = fork()) {
368 case -1:
369 goto doneediting;
370 case 0:
371 execl(editor, editor, file, (char *)NULL);
372 _exit(127);
375 while (waitpid(pid, &st, 0) == -1)
376 if (errno != EINTR)
377 break;
379 doneediting:
380 (void)signal(SIGHUP, sighup);
381 (void)signal(SIGINT, sigint);
382 (void)signal(SIGQUIT, sigquit);
384 if (!WIFEXITED(st)) {
385 errno = EINTR;
386 return -1;
389 return WEXITSTATUS(st);
392 static const struct got_error *
393 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
395 const struct got_error *err = NULL;
396 char *line = NULL;
397 size_t linesize = 0;
399 *logmsg = NULL;
400 *len = 0;
402 if (fseeko(fp, 0L, SEEK_SET) == -1)
403 return got_error_from_errno("fseeko");
405 *logmsg = malloc(filesize + 1);
406 if (*logmsg == NULL)
407 return got_error_from_errno("malloc");
408 (*logmsg)[0] = '\0';
410 while (getline(&line, &linesize, fp) != -1) {
411 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
412 continue; /* remove comments and leading empty lines */
413 *len = strlcat(*logmsg, line, filesize + 1);
414 if (*len >= filesize + 1) {
415 err = got_error(GOT_ERR_NO_SPACE);
416 goto done;
419 if (ferror(fp)) {
420 err = got_ferror(fp, GOT_ERR_IO);
421 goto done;
424 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
425 (*logmsg)[*len - 1] = '\0';
426 (*len)--;
428 done:
429 free(line);
430 if (err) {
431 free(*logmsg);
432 *logmsg = NULL;
433 *len = 0;
435 return err;
438 static const struct got_error *
439 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
440 const char *initial_content, size_t initial_content_len,
441 int require_modification)
443 const struct got_error *err = NULL;
444 struct stat st, st2;
445 FILE *fp = NULL;
446 size_t logmsg_len;
448 *logmsg = NULL;
450 if (stat(logmsg_path, &st) == -1)
451 return got_error_from_errno2("stat", logmsg_path);
453 if (spawn_editor(editor, logmsg_path) == -1)
454 return got_error_from_errno("failed spawning editor");
456 if (require_modification) {
457 struct timespec timeout;
459 timeout.tv_sec = 0;
460 timeout.tv_nsec = 1;
461 nanosleep(&timeout, NULL);
464 if (stat(logmsg_path, &st2) == -1)
465 return got_error_from_errno("stat");
467 if (require_modification && st.st_size == st2.st_size &&
468 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
469 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
470 "no changes made to commit message, aborting");
472 fp = fopen(logmsg_path, "re");
473 if (fp == NULL) {
474 err = got_error_from_errno("fopen");
475 goto done;
478 /* strip comments and leading/trailing newlines */
479 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
480 if (err)
481 goto done;
482 if (logmsg_len == 0) {
483 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
484 "commit message cannot be empty, aborting");
485 goto done;
487 done:
488 if (fp && fclose(fp) == EOF && err == NULL)
489 err = got_error_from_errno("fclose");
490 if (err) {
491 free(*logmsg);
492 *logmsg = NULL;
494 return err;
497 static const struct got_error *
498 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
499 const char *path_dir, const char *branch_name)
501 char *initial_content = NULL;
502 const struct got_error *err = NULL;
503 int initial_content_len;
504 int fd = -1;
506 initial_content_len = asprintf(&initial_content,
507 "\n# %s to be imported to branch %s\n", path_dir,
508 branch_name);
509 if (initial_content_len == -1)
510 return got_error_from_errno("asprintf");
512 err = got_opentemp_named_fd(logmsg_path, &fd,
513 GOT_TMPDIR_STR "/got-importmsg", "");
514 if (err)
515 goto done;
517 if (write(fd, initial_content, initial_content_len) == -1) {
518 err = got_error_from_errno2("write", *logmsg_path);
519 goto done;
522 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
523 initial_content_len, 1);
524 done:
525 if (fd != -1 && close(fd) == -1 && err == NULL)
526 err = got_error_from_errno2("close", *logmsg_path);
527 free(initial_content);
528 if (err) {
529 free(*logmsg_path);
530 *logmsg_path = NULL;
532 return err;
535 static const struct got_error *
536 import_progress(void *arg, const char *path)
538 printf("A %s\n", path);
539 return NULL;
542 static const struct got_error *
543 valid_author(const char *author)
545 const char *email = author;
547 /*
548 * Git' expects the author (or committer) to be in the form
549 * "name <email>", which are mostly free form (see the
550 * "committer" description in git-fast-import(1)). We're only
551 * doing this to avoid git's object parser breaking on commits
552 * we create.
553 */
555 while (*author && *author != '\n' && *author != '<' && *author != '>')
556 author++;
557 if (author != email && *author == '<' && *(author - 1) != ' ')
558 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
559 "between author name and email required", email);
560 if (*author++ != '<')
561 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
562 while (*author && *author != '\n' && *author != '<' && *author != '>')
563 author++;
564 if (strcmp(author, ">") != 0)
565 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
566 return NULL;
569 static const struct got_error *
570 get_author(char **author, struct got_repository *repo,
571 struct got_worktree *worktree)
573 const struct got_error *err = NULL;
574 const char *got_author = NULL, *name, *email;
575 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
577 *author = NULL;
579 if (worktree)
580 worktree_conf = got_worktree_get_gotconfig(worktree);
581 repo_conf = got_repo_get_gotconfig(repo);
583 /*
584 * Priority of potential author information sources, from most
585 * significant to least significant:
586 * 1) work tree's .got/got.conf file
587 * 2) repository's got.conf file
588 * 3) repository's git config file
589 * 4) environment variables
590 * 5) global git config files (in user's home directory or /etc)
591 */
593 if (worktree_conf)
594 got_author = got_gotconfig_get_author(worktree_conf);
595 if (got_author == NULL)
596 got_author = got_gotconfig_get_author(repo_conf);
597 if (got_author == NULL) {
598 name = got_repo_get_gitconfig_author_name(repo);
599 email = got_repo_get_gitconfig_author_email(repo);
600 if (name && email) {
601 if (asprintf(author, "%s <%s>", name, email) == -1)
602 return got_error_from_errno("asprintf");
603 return NULL;
606 got_author = getenv("GOT_AUTHOR");
607 if (got_author == NULL) {
608 name = got_repo_get_global_gitconfig_author_name(repo);
609 email = got_repo_get_global_gitconfig_author_email(
610 repo);
611 if (name && email) {
612 if (asprintf(author, "%s <%s>", name, email)
613 == -1)
614 return got_error_from_errno("asprintf");
615 return NULL;
617 /* TODO: Look up user in password database? */
618 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
622 *author = strdup(got_author);
623 if (*author == NULL)
624 return got_error_from_errno("strdup");
626 err = valid_author(*author);
627 if (err) {
628 free(*author);
629 *author = NULL;
631 return err;
634 static const struct got_error *
635 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
636 struct got_worktree *worktree)
638 const char *got_allowed_signers = NULL;
639 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
641 *allowed_signers = NULL;
643 if (worktree)
644 worktree_conf = got_worktree_get_gotconfig(worktree);
645 repo_conf = got_repo_get_gotconfig(repo);
647 /*
648 * Priority of potential author information sources, from most
649 * significant to least significant:
650 * 1) work tree's .got/got.conf file
651 * 2) repository's got.conf file
652 */
654 if (worktree_conf)
655 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
656 worktree_conf);
657 if (got_allowed_signers == NULL)
658 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
659 repo_conf);
661 if (got_allowed_signers) {
662 *allowed_signers = strdup(got_allowed_signers);
663 if (*allowed_signers == NULL)
664 return got_error_from_errno("strdup");
666 return NULL;
669 static const struct got_error *
670 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
671 struct got_worktree *worktree)
673 const char *got_revoked_signers = NULL;
674 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
676 *revoked_signers = NULL;
678 if (worktree)
679 worktree_conf = got_worktree_get_gotconfig(worktree);
680 repo_conf = got_repo_get_gotconfig(repo);
682 /*
683 * Priority of potential author information sources, from most
684 * significant to least significant:
685 * 1) work tree's .got/got.conf file
686 * 2) repository's got.conf file
687 */
689 if (worktree_conf)
690 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
691 worktree_conf);
692 if (got_revoked_signers == NULL)
693 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
694 repo_conf);
696 if (got_revoked_signers) {
697 *revoked_signers = strdup(got_revoked_signers);
698 if (*revoked_signers == NULL)
699 return got_error_from_errno("strdup");
701 return NULL;
704 static const char *
705 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
707 const char *got_signer_id = NULL;
708 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
710 if (worktree)
711 worktree_conf = got_worktree_get_gotconfig(worktree);
712 repo_conf = got_repo_get_gotconfig(repo);
714 /*
715 * Priority of potential author information sources, from most
716 * significant to least significant:
717 * 1) work tree's .got/got.conf file
718 * 2) repository's got.conf file
719 */
721 if (worktree_conf)
722 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
723 if (got_signer_id == NULL)
724 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
726 return got_signer_id;
729 static const struct got_error *
730 get_gitconfig_path(char **gitconfig_path)
732 const char *homedir = getenv("HOME");
734 *gitconfig_path = NULL;
735 if (homedir) {
736 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
737 return got_error_from_errno("asprintf");
740 return NULL;
743 static const struct got_error *
744 cmd_import(int argc, char *argv[])
746 const struct got_error *error = NULL;
747 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
748 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
749 const char *branch_name = NULL;
750 char *id_str = NULL, *logmsg_path = NULL;
751 char refname[PATH_MAX] = "refs/heads/";
752 struct got_repository *repo = NULL;
753 struct got_reference *branch_ref = NULL, *head_ref = NULL;
754 struct got_object_id *new_commit_id = NULL;
755 int ch, n = 0;
756 struct got_pathlist_head ignores;
757 struct got_pathlist_entry *pe;
758 int preserve_logmsg = 0;
759 int *pack_fds = NULL;
761 TAILQ_INIT(&ignores);
763 #ifndef PROFILE
764 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
765 "unveil",
766 NULL) == -1)
767 err(1, "pledge");
768 #endif
770 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
771 switch (ch) {
772 case 'b':
773 branch_name = optarg;
774 break;
775 case 'I':
776 if (optarg[0] == '\0')
777 break;
778 error = got_pathlist_insert(&pe, &ignores, optarg,
779 NULL);
780 if (error)
781 goto done;
782 break;
783 case 'm':
784 logmsg = strdup(optarg);
785 if (logmsg == NULL) {
786 error = got_error_from_errno("strdup");
787 goto done;
789 break;
790 case 'r':
791 repo_path = realpath(optarg, NULL);
792 if (repo_path == NULL) {
793 error = got_error_from_errno2("realpath",
794 optarg);
795 goto done;
797 break;
798 default:
799 usage_import();
800 /* NOTREACHED */
804 argc -= optind;
805 argv += optind;
807 if (argc != 1)
808 usage_import();
810 if (repo_path == NULL) {
811 repo_path = getcwd(NULL, 0);
812 if (repo_path == NULL)
813 return got_error_from_errno("getcwd");
815 got_path_strip_trailing_slashes(repo_path);
816 error = get_gitconfig_path(&gitconfig_path);
817 if (error)
818 goto done;
819 error = got_repo_pack_fds_open(&pack_fds);
820 if (error != NULL)
821 goto done;
822 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
823 if (error)
824 goto done;
826 error = get_author(&author, repo, NULL);
827 if (error)
828 return error;
830 /*
831 * Don't let the user create a branch name with a leading '-'.
832 * While technically a valid reference name, this case is usually
833 * an unintended typo.
834 */
835 if (branch_name && branch_name[0] == '-')
836 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
838 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
839 if (error && error->code != GOT_ERR_NOT_REF)
840 goto done;
842 if (branch_name)
843 n = strlcat(refname, branch_name, sizeof(refname));
844 else if (head_ref && got_ref_is_symbolic(head_ref))
845 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
846 sizeof(refname));
847 else
848 n = strlcat(refname, "main", sizeof(refname));
849 if (n >= sizeof(refname)) {
850 error = got_error(GOT_ERR_NO_SPACE);
851 goto done;
854 error = got_ref_open(&branch_ref, repo, refname, 0);
855 if (error) {
856 if (error->code != GOT_ERR_NOT_REF)
857 goto done;
858 } else {
859 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
860 "import target branch already exists");
861 goto done;
864 path_dir = realpath(argv[0], NULL);
865 if (path_dir == NULL) {
866 error = got_error_from_errno2("realpath", argv[0]);
867 goto done;
869 got_path_strip_trailing_slashes(path_dir);
871 /*
872 * unveil(2) traverses exec(2); if an editor is used we have
873 * to apply unveil after the log message has been written.
874 */
875 if (logmsg == NULL || strlen(logmsg) == 0) {
876 error = get_editor(&editor);
877 if (error)
878 goto done;
879 free(logmsg);
880 error = collect_import_msg(&logmsg, &logmsg_path, editor,
881 path_dir, refname);
882 if (error) {
883 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
884 logmsg_path != NULL)
885 preserve_logmsg = 1;
886 goto done;
890 if (unveil(path_dir, "r") != 0) {
891 error = got_error_from_errno2("unveil", path_dir);
892 if (logmsg_path)
893 preserve_logmsg = 1;
894 goto done;
897 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
898 if (error) {
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = got_repo_import(&new_commit_id, path_dir, logmsg,
905 author, &ignores, repo, import_progress, NULL);
906 if (error) {
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_write(branch_ref, repo);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_object_id_str(&id_str, new_commit_id);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
934 if (error) {
935 if (error->code != GOT_ERR_NOT_REF) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
942 branch_ref);
943 if (error) {
944 if (logmsg_path)
945 preserve_logmsg = 1;
946 goto done;
949 error = got_ref_write(head_ref, repo);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
957 printf("Created branch %s with commit %s\n",
958 got_ref_get_name(branch_ref), id_str);
959 done:
960 if (pack_fds) {
961 const struct got_error *pack_err =
962 got_repo_pack_fds_close(pack_fds);
963 if (error == NULL)
964 error = pack_err;
966 if (preserve_logmsg) {
967 fprintf(stderr, "%s: log message preserved in %s\n",
968 getprogname(), logmsg_path);
969 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
970 error = got_error_from_errno2("unlink", logmsg_path);
971 free(logmsg);
972 free(logmsg_path);
973 free(repo_path);
974 free(editor);
975 free(new_commit_id);
976 free(id_str);
977 free(author);
978 free(gitconfig_path);
979 if (branch_ref)
980 got_ref_close(branch_ref);
981 if (head_ref)
982 got_ref_close(head_ref);
983 return error;
986 __dead static void
987 usage_clone(void)
989 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
990 "repository-URL [directory]\n", getprogname());
991 exit(1);
994 struct got_fetch_progress_arg {
995 char last_scaled_size[FMT_SCALED_STRSIZE];
996 int last_p_indexed;
997 int last_p_resolved;
998 int verbosity;
1000 struct got_repository *repo;
1002 int create_configs;
1003 int configs_created;
1004 struct {
1005 struct got_pathlist_head *symrefs;
1006 struct got_pathlist_head *wanted_branches;
1007 struct got_pathlist_head *wanted_refs;
1008 const char *proto;
1009 const char *host;
1010 const char *port;
1011 const char *remote_repo_path;
1012 const char *git_url;
1013 int fetch_all_branches;
1014 int mirror_references;
1015 } config_info;
1018 /* XXX forward declaration */
1019 static const struct got_error *
1020 create_config_files(const char *proto, const char *host, const char *port,
1021 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1022 int mirror_references, struct got_pathlist_head *symrefs,
1023 struct got_pathlist_head *wanted_branches,
1024 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1026 static const struct got_error *
1027 fetch_progress(void *arg, const char *message, off_t packfile_size,
1028 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1030 const struct got_error *err = NULL;
1031 struct got_fetch_progress_arg *a = arg;
1032 char scaled_size[FMT_SCALED_STRSIZE];
1033 int p_indexed, p_resolved;
1034 int print_size = 0, print_indexed = 0, print_resolved = 0;
1037 * In order to allow a failed clone to be resumed with 'got fetch'
1038 * we try to create configuration files as soon as possible.
1039 * Once the server has sent information about its default branch
1040 * we have all required information.
1042 if (a->create_configs && !a->configs_created &&
1043 !TAILQ_EMPTY(a->config_info.symrefs)) {
1044 err = create_config_files(a->config_info.proto,
1045 a->config_info.host, a->config_info.port,
1046 a->config_info.remote_repo_path,
1047 a->config_info.git_url,
1048 a->config_info.fetch_all_branches,
1049 a->config_info.mirror_references,
1050 a->config_info.symrefs,
1051 a->config_info.wanted_branches,
1052 a->config_info.wanted_refs, a->repo);
1053 if (err)
1054 return err;
1055 a->configs_created = 1;
1058 if (a->verbosity < 0)
1059 return NULL;
1061 if (message && message[0] != '\0') {
1062 printf("\rserver: %s", message);
1063 fflush(stdout);
1064 return NULL;
1067 if (packfile_size > 0 || nobj_indexed > 0) {
1068 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1069 (a->last_scaled_size[0] == '\0' ||
1070 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1071 print_size = 1;
1072 if (strlcpy(a->last_scaled_size, scaled_size,
1073 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1074 return got_error(GOT_ERR_NO_SPACE);
1076 if (nobj_indexed > 0) {
1077 p_indexed = (nobj_indexed * 100) / nobj_total;
1078 if (p_indexed != a->last_p_indexed) {
1079 a->last_p_indexed = p_indexed;
1080 print_indexed = 1;
1081 print_size = 1;
1084 if (nobj_resolved > 0) {
1085 p_resolved = (nobj_resolved * 100) /
1086 (nobj_total - nobj_loose);
1087 if (p_resolved != a->last_p_resolved) {
1088 a->last_p_resolved = p_resolved;
1089 print_resolved = 1;
1090 print_indexed = 1;
1091 print_size = 1;
1096 if (print_size || print_indexed || print_resolved)
1097 printf("\r");
1098 if (print_size)
1099 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1100 if (print_indexed)
1101 printf("; indexing %d%%", p_indexed);
1102 if (print_resolved)
1103 printf("; resolving deltas %d%%", p_resolved);
1104 if (print_size || print_indexed || print_resolved)
1105 fflush(stdout);
1107 return NULL;
1110 static const struct got_error *
1111 create_symref(const char *refname, struct got_reference *target_ref,
1112 int verbosity, struct got_repository *repo)
1114 const struct got_error *err;
1115 struct got_reference *head_symref;
1117 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1118 if (err)
1119 return err;
1121 err = got_ref_write(head_symref, repo);
1122 if (err == NULL && verbosity > 0) {
1123 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1124 got_ref_get_name(target_ref));
1126 got_ref_close(head_symref);
1127 return err;
1130 static const struct got_error *
1131 list_remote_refs(struct got_pathlist_head *symrefs,
1132 struct got_pathlist_head *refs)
1134 const struct got_error *err;
1135 struct got_pathlist_entry *pe;
1137 TAILQ_FOREACH(pe, symrefs, entry) {
1138 const char *refname = pe->path;
1139 const char *targetref = pe->data;
1141 printf("%s: %s\n", refname, targetref);
1144 TAILQ_FOREACH(pe, refs, entry) {
1145 const char *refname = pe->path;
1146 struct got_object_id *id = pe->data;
1147 char *id_str;
1149 err = got_object_id_str(&id_str, id);
1150 if (err)
1151 return err;
1152 printf("%s: %s\n", refname, id_str);
1153 free(id_str);
1156 return NULL;
1159 static const struct got_error *
1160 create_ref(const char *refname, struct got_object_id *id,
1161 int verbosity, struct got_repository *repo)
1163 const struct got_error *err = NULL;
1164 struct got_reference *ref;
1165 char *id_str;
1167 err = got_object_id_str(&id_str, id);
1168 if (err)
1169 return err;
1171 err = got_ref_alloc(&ref, refname, id);
1172 if (err)
1173 goto done;
1175 err = got_ref_write(ref, repo);
1176 got_ref_close(ref);
1178 if (err == NULL && verbosity >= 0)
1179 printf("Created reference %s: %s\n", refname, id_str);
1180 done:
1181 free(id_str);
1182 return err;
1185 static int
1186 match_wanted_ref(const char *refname, const char *wanted_ref)
1188 if (strncmp(refname, "refs/", 5) != 0)
1189 return 0;
1190 refname += 5;
1193 * Prevent fetching of references that won't make any
1194 * sense outside of the remote repository's context.
1196 if (strncmp(refname, "got/", 4) == 0)
1197 return 0;
1198 if (strncmp(refname, "remotes/", 8) == 0)
1199 return 0;
1201 if (strncmp(wanted_ref, "refs/", 5) == 0)
1202 wanted_ref += 5;
1204 /* Allow prefix match. */
1205 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1206 return 1;
1208 /* Allow exact match. */
1209 return (strcmp(refname, wanted_ref) == 0);
1212 static int
1213 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1215 struct got_pathlist_entry *pe;
1217 TAILQ_FOREACH(pe, wanted_refs, entry) {
1218 if (match_wanted_ref(refname, pe->path))
1219 return 1;
1222 return 0;
1225 static const struct got_error *
1226 create_wanted_ref(const char *refname, struct got_object_id *id,
1227 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1229 const struct got_error *err;
1230 char *remote_refname;
1232 if (strncmp("refs/", refname, 5) == 0)
1233 refname += 5;
1235 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1236 remote_repo_name, refname) == -1)
1237 return got_error_from_errno("asprintf");
1239 err = create_ref(remote_refname, id, verbosity, repo);
1240 free(remote_refname);
1241 return err;
1244 static const struct got_error *
1245 create_gotconfig(const char *proto, const char *host, const char *port,
1246 const char *remote_repo_path, const char *default_branch,
1247 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1248 struct got_pathlist_head *wanted_refs, int mirror_references,
1249 struct got_repository *repo)
1251 const struct got_error *err = NULL;
1252 char *gotconfig_path = NULL;
1253 char *gotconfig = NULL;
1254 FILE *gotconfig_file = NULL;
1255 const char *branchname = NULL;
1256 char *branches = NULL, *refs = NULL;
1257 ssize_t n;
1259 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1260 struct got_pathlist_entry *pe;
1261 TAILQ_FOREACH(pe, wanted_branches, entry) {
1262 char *s;
1263 branchname = pe->path;
1264 if (strncmp(branchname, "refs/heads/", 11) == 0)
1265 branchname += 11;
1266 if (asprintf(&s, "%s\"%s\" ",
1267 branches ? branches : "", branchname) == -1) {
1268 err = got_error_from_errno("asprintf");
1269 goto done;
1271 free(branches);
1272 branches = s;
1274 } else if (!fetch_all_branches && default_branch) {
1275 branchname = default_branch;
1276 if (strncmp(branchname, "refs/heads/", 11) == 0)
1277 branchname += 11;
1278 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1283 if (!TAILQ_EMPTY(wanted_refs)) {
1284 struct got_pathlist_entry *pe;
1285 TAILQ_FOREACH(pe, wanted_refs, entry) {
1286 char *s;
1287 const char *refname = pe->path;
1288 if (strncmp(refname, "refs/", 5) == 0)
1289 branchname += 5;
1290 if (asprintf(&s, "%s\"%s\" ",
1291 refs ? refs : "", refname) == -1) {
1292 err = got_error_from_errno("asprintf");
1293 goto done;
1295 free(refs);
1296 refs = s;
1300 /* Create got.conf(5). */
1301 gotconfig_path = got_repo_get_path_gotconfig(repo);
1302 if (gotconfig_path == NULL) {
1303 err = got_error_from_errno("got_repo_get_path_gotconfig");
1304 goto done;
1306 gotconfig_file = fopen(gotconfig_path, "ae");
1307 if (gotconfig_file == NULL) {
1308 err = got_error_from_errno2("fopen", gotconfig_path);
1309 goto done;
1311 if (asprintf(&gotconfig,
1312 "remote \"%s\" {\n"
1313 "\tserver %s\n"
1314 "\tprotocol %s\n"
1315 "%s%s%s"
1316 "\trepository \"%s\"\n"
1317 "%s%s%s"
1318 "%s%s%s"
1319 "%s"
1320 "%s"
1321 "}\n",
1322 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1323 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1324 remote_repo_path, branches ? "\tbranch { " : "",
1325 branches ? branches : "", branches ? "}\n" : "",
1326 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1327 mirror_references ? "\tmirror_references yes\n" : "",
1328 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1329 err = got_error_from_errno("asprintf");
1330 goto done;
1332 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1333 if (n != strlen(gotconfig)) {
1334 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1335 goto done;
1338 done:
1339 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1340 err = got_error_from_errno2("fclose", gotconfig_path);
1341 free(gotconfig_path);
1342 free(branches);
1343 return err;
1346 static const struct got_error *
1347 create_gitconfig(const char *git_url, const char *default_branch,
1348 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1349 struct got_pathlist_head *wanted_refs, int mirror_references,
1350 struct got_repository *repo)
1352 const struct got_error *err = NULL;
1353 char *gitconfig_path = NULL;
1354 char *gitconfig = NULL;
1355 FILE *gitconfig_file = NULL;
1356 char *branches = NULL, *refs = NULL;
1357 const char *branchname;
1358 ssize_t n;
1360 /* Create a config file Git can understand. */
1361 gitconfig_path = got_repo_get_path_gitconfig(repo);
1362 if (gitconfig_path == NULL) {
1363 err = got_error_from_errno("got_repo_get_path_gitconfig");
1364 goto done;
1366 gitconfig_file = fopen(gitconfig_path, "ae");
1367 if (gitconfig_file == NULL) {
1368 err = got_error_from_errno2("fopen", gitconfig_path);
1369 goto done;
1371 if (fetch_all_branches) {
1372 if (mirror_references) {
1373 if (asprintf(&branches,
1374 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1375 err = got_error_from_errno("asprintf");
1376 goto done;
1378 } else if (asprintf(&branches,
1379 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1380 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1381 err = got_error_from_errno("asprintf");
1382 goto done;
1384 } else if (!TAILQ_EMPTY(wanted_branches)) {
1385 struct got_pathlist_entry *pe;
1386 TAILQ_FOREACH(pe, wanted_branches, entry) {
1387 char *s;
1388 branchname = pe->path;
1389 if (strncmp(branchname, "refs/heads/", 11) == 0)
1390 branchname += 11;
1391 if (mirror_references) {
1392 if (asprintf(&s,
1393 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1394 branches ? branches : "",
1395 branchname, branchname) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (asprintf(&s,
1400 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1401 branches ? branches : "",
1402 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1403 branchname) == -1) {
1404 err = got_error_from_errno("asprintf");
1405 goto done;
1407 free(branches);
1408 branches = s;
1410 } else {
1412 * If the server specified a default branch, use just that one.
1413 * Otherwise fall back to fetching all branches on next fetch.
1415 if (default_branch) {
1416 branchname = default_branch;
1417 if (strncmp(branchname, "refs/heads/", 11) == 0)
1418 branchname += 11;
1419 } else
1420 branchname = "*"; /* fall back to all branches */
1421 if (mirror_references) {
1422 if (asprintf(&branches,
1423 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1424 branchname, branchname) == -1) {
1425 err = got_error_from_errno("asprintf");
1426 goto done;
1428 } else if (asprintf(&branches,
1429 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1430 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1431 branchname) == -1) {
1432 err = got_error_from_errno("asprintf");
1433 goto done;
1436 if (!TAILQ_EMPTY(wanted_refs)) {
1437 struct got_pathlist_entry *pe;
1438 TAILQ_FOREACH(pe, wanted_refs, entry) {
1439 char *s;
1440 const char *refname = pe->path;
1441 if (strncmp(refname, "refs/", 5) == 0)
1442 refname += 5;
1443 if (mirror_references) {
1444 if (asprintf(&s,
1445 "%s\tfetch = refs/%s:refs/%s\n",
1446 refs ? refs : "", refname, refname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1450 } else if (asprintf(&s,
1451 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1452 refs ? refs : "",
1453 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1454 refname) == -1) {
1455 err = got_error_from_errno("asprintf");
1456 goto done;
1458 free(refs);
1459 refs = s;
1463 if (asprintf(&gitconfig,
1464 "[remote \"%s\"]\n"
1465 "\turl = %s\n"
1466 "%s"
1467 "%s"
1468 "\tfetch = refs/tags/*:refs/tags/*\n",
1469 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1470 refs ? refs : "") == -1) {
1471 err = got_error_from_errno("asprintf");
1472 goto done;
1474 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1475 if (n != strlen(gitconfig)) {
1476 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1477 goto done;
1479 done:
1480 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1481 err = got_error_from_errno2("fclose", gitconfig_path);
1482 free(gitconfig_path);
1483 free(branches);
1484 return err;
1487 static const struct got_error *
1488 create_config_files(const char *proto, const char *host, const char *port,
1489 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1490 int mirror_references, struct got_pathlist_head *symrefs,
1491 struct got_pathlist_head *wanted_branches,
1492 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1494 const struct got_error *err = NULL;
1495 const char *default_branch = NULL;
1496 struct got_pathlist_entry *pe;
1499 * If we asked for a set of wanted branches then use the first
1500 * one of those.
1502 if (!TAILQ_EMPTY(wanted_branches)) {
1503 pe = TAILQ_FIRST(wanted_branches);
1504 default_branch = pe->path;
1505 } else {
1506 /* First HEAD ref listed by server is the default branch. */
1507 TAILQ_FOREACH(pe, symrefs, entry) {
1508 const char *refname = pe->path;
1509 const char *target = pe->data;
1511 if (strcmp(refname, GOT_REF_HEAD) != 0)
1512 continue;
1514 default_branch = target;
1515 break;
1519 /* Create got.conf(5). */
1520 err = create_gotconfig(proto, host, port, remote_repo_path,
1521 default_branch, fetch_all_branches, wanted_branches,
1522 wanted_refs, mirror_references, repo);
1523 if (err)
1524 return err;
1526 /* Create a config file Git can understand. */
1527 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1528 wanted_branches, wanted_refs, mirror_references, repo);
1531 static const struct got_error *
1532 cmd_clone(int argc, char *argv[])
1534 const struct got_error *error = NULL;
1535 const char *uri, *dirname;
1536 char *proto, *host, *port, *repo_name, *server_path;
1537 char *default_destdir = NULL, *id_str = NULL;
1538 const char *repo_path;
1539 struct got_repository *repo = NULL;
1540 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1541 struct got_pathlist_entry *pe;
1542 struct got_object_id *pack_hash = NULL;
1543 int ch, fetchfd = -1, fetchstatus;
1544 pid_t fetchpid = -1;
1545 struct got_fetch_progress_arg fpa;
1546 char *git_url = NULL;
1547 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1548 int bflag = 0, list_refs_only = 0;
1549 int *pack_fds = NULL;
1551 TAILQ_INIT(&refs);
1552 TAILQ_INIT(&symrefs);
1553 TAILQ_INIT(&wanted_branches);
1554 TAILQ_INIT(&wanted_refs);
1556 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1557 switch (ch) {
1558 case 'a':
1559 fetch_all_branches = 1;
1560 break;
1561 case 'b':
1562 error = got_pathlist_append(&wanted_branches,
1563 optarg, NULL);
1564 if (error)
1565 return error;
1566 bflag = 1;
1567 break;
1568 case 'l':
1569 list_refs_only = 1;
1570 break;
1571 case 'm':
1572 mirror_references = 1;
1573 break;
1574 case 'q':
1575 verbosity = -1;
1576 break;
1577 case 'R':
1578 error = got_pathlist_append(&wanted_refs,
1579 optarg, NULL);
1580 if (error)
1581 return error;
1582 break;
1583 case 'v':
1584 if (verbosity < 0)
1585 verbosity = 0;
1586 else if (verbosity < 3)
1587 verbosity++;
1588 break;
1589 default:
1590 usage_clone();
1591 break;
1594 argc -= optind;
1595 argv += optind;
1597 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1598 option_conflict('a', 'b');
1599 if (list_refs_only) {
1600 if (!TAILQ_EMPTY(&wanted_branches))
1601 option_conflict('l', 'b');
1602 if (fetch_all_branches)
1603 option_conflict('l', 'a');
1604 if (mirror_references)
1605 option_conflict('l', 'm');
1606 if (!TAILQ_EMPTY(&wanted_refs))
1607 option_conflict('l', 'R');
1610 uri = argv[0];
1612 if (argc == 1)
1613 dirname = NULL;
1614 else if (argc == 2)
1615 dirname = argv[1];
1616 else
1617 usage_clone();
1619 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1620 &repo_name, uri);
1621 if (error)
1622 goto done;
1624 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1625 host, port ? ":" : "", port ? port : "",
1626 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1627 error = got_error_from_errno("asprintf");
1628 goto done;
1631 if (strcmp(proto, "git") == 0) {
1632 #ifndef PROFILE
1633 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1634 "sendfd dns inet unveil", NULL) == -1)
1635 err(1, "pledge");
1636 #endif
1637 } else if (strcmp(proto, "git+ssh") == 0 ||
1638 strcmp(proto, "ssh") == 0) {
1639 #ifndef PROFILE
1640 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1641 "sendfd unveil", NULL) == -1)
1642 err(1, "pledge");
1643 #endif
1644 } else if (strcmp(proto, "http") == 0 ||
1645 strcmp(proto, "git+http") == 0) {
1646 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1647 goto done;
1648 } else {
1649 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1650 goto done;
1652 if (dirname == NULL) {
1653 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1654 error = got_error_from_errno("asprintf");
1655 goto done;
1657 repo_path = default_destdir;
1658 } else
1659 repo_path = dirname;
1661 if (!list_refs_only) {
1662 error = got_path_mkdir(repo_path);
1663 if (error &&
1664 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1665 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1666 goto done;
1667 if (!got_path_dir_is_empty(repo_path)) {
1668 error = got_error_path(repo_path,
1669 GOT_ERR_DIR_NOT_EMPTY);
1670 goto done;
1674 error = got_dial_apply_unveil(proto);
1675 if (error)
1676 goto done;
1678 error = apply_unveil(repo_path, 0, NULL);
1679 if (error)
1680 goto done;
1682 if (verbosity >= 0)
1683 printf("Connecting to %s\n", git_url);
1685 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1686 server_path, verbosity);
1687 if (error)
1688 goto done;
1690 if (!list_refs_only) {
1691 error = got_repo_init(repo_path, NULL);
1692 if (error)
1693 goto done;
1694 error = got_repo_pack_fds_open(&pack_fds);
1695 if (error != NULL)
1696 goto done;
1697 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1698 if (error)
1699 goto done;
1702 fpa.last_scaled_size[0] = '\0';
1703 fpa.last_p_indexed = -1;
1704 fpa.last_p_resolved = -1;
1705 fpa.verbosity = verbosity;
1706 fpa.create_configs = 1;
1707 fpa.configs_created = 0;
1708 fpa.repo = repo;
1709 fpa.config_info.symrefs = &symrefs;
1710 fpa.config_info.wanted_branches = &wanted_branches;
1711 fpa.config_info.wanted_refs = &wanted_refs;
1712 fpa.config_info.proto = proto;
1713 fpa.config_info.host = host;
1714 fpa.config_info.port = port;
1715 fpa.config_info.remote_repo_path = server_path;
1716 fpa.config_info.git_url = git_url;
1717 fpa.config_info.fetch_all_branches = fetch_all_branches;
1718 fpa.config_info.mirror_references = mirror_references;
1719 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1720 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1721 fetch_all_branches, &wanted_branches, &wanted_refs,
1722 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1723 fetch_progress, &fpa);
1724 if (error)
1725 goto done;
1727 if (list_refs_only) {
1728 error = list_remote_refs(&symrefs, &refs);
1729 goto done;
1732 if (pack_hash == NULL) {
1733 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1734 "server sent an empty pack file");
1735 goto done;
1737 error = got_object_id_str(&id_str, pack_hash);
1738 if (error)
1739 goto done;
1740 if (verbosity >= 0)
1741 printf("\nFetched %s.pack\n", id_str);
1742 free(id_str);
1744 /* Set up references provided with the pack file. */
1745 TAILQ_FOREACH(pe, &refs, entry) {
1746 const char *refname = pe->path;
1747 struct got_object_id *id = pe->data;
1748 char *remote_refname;
1750 if (is_wanted_ref(&wanted_refs, refname) &&
1751 !mirror_references) {
1752 error = create_wanted_ref(refname, id,
1753 GOT_FETCH_DEFAULT_REMOTE_NAME,
1754 verbosity - 1, repo);
1755 if (error)
1756 goto done;
1757 continue;
1760 error = create_ref(refname, id, verbosity - 1, repo);
1761 if (error)
1762 goto done;
1764 if (mirror_references)
1765 continue;
1767 if (strncmp("refs/heads/", refname, 11) != 0)
1768 continue;
1770 if (asprintf(&remote_refname,
1771 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1772 refname + 11) == -1) {
1773 error = got_error_from_errno("asprintf");
1774 goto done;
1776 error = create_ref(remote_refname, id, verbosity - 1, repo);
1777 free(remote_refname);
1778 if (error)
1779 goto done;
1782 /* Set the HEAD reference if the server provided one. */
1783 TAILQ_FOREACH(pe, &symrefs, entry) {
1784 struct got_reference *target_ref;
1785 const char *refname = pe->path;
1786 const char *target = pe->data;
1787 char *remote_refname = NULL, *remote_target = NULL;
1789 if (strcmp(refname, GOT_REF_HEAD) != 0)
1790 continue;
1792 error = got_ref_open(&target_ref, repo, target, 0);
1793 if (error) {
1794 if (error->code == GOT_ERR_NOT_REF) {
1795 error = NULL;
1796 continue;
1798 goto done;
1801 error = create_symref(refname, target_ref, verbosity, repo);
1802 got_ref_close(target_ref);
1803 if (error)
1804 goto done;
1806 if (mirror_references)
1807 continue;
1809 if (strncmp("refs/heads/", target, 11) != 0)
1810 continue;
1812 if (asprintf(&remote_refname,
1813 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1814 refname) == -1) {
1815 error = got_error_from_errno("asprintf");
1816 goto done;
1818 if (asprintf(&remote_target,
1819 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1820 target + 11) == -1) {
1821 error = got_error_from_errno("asprintf");
1822 free(remote_refname);
1823 goto done;
1825 error = got_ref_open(&target_ref, repo, remote_target, 0);
1826 if (error) {
1827 free(remote_refname);
1828 free(remote_target);
1829 if (error->code == GOT_ERR_NOT_REF) {
1830 error = NULL;
1831 continue;
1833 goto done;
1835 error = create_symref(remote_refname, target_ref,
1836 verbosity - 1, repo);
1837 free(remote_refname);
1838 free(remote_target);
1839 got_ref_close(target_ref);
1840 if (error)
1841 goto done;
1843 if (pe == NULL) {
1845 * We failed to set the HEAD reference. If we asked for
1846 * a set of wanted branches use the first of one of those
1847 * which could be fetched instead.
1849 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1850 const char *target = pe->path;
1851 struct got_reference *target_ref;
1853 error = got_ref_open(&target_ref, repo, target, 0);
1854 if (error) {
1855 if (error->code == GOT_ERR_NOT_REF) {
1856 error = NULL;
1857 continue;
1859 goto done;
1862 error = create_symref(GOT_REF_HEAD, target_ref,
1863 verbosity, repo);
1864 got_ref_close(target_ref);
1865 if (error)
1866 goto done;
1867 break;
1870 if (!fpa.configs_created && pe != NULL) {
1871 error = create_config_files(fpa.config_info.proto,
1872 fpa.config_info.host, fpa.config_info.port,
1873 fpa.config_info.remote_repo_path,
1874 fpa.config_info.git_url,
1875 fpa.config_info.fetch_all_branches,
1876 fpa.config_info.mirror_references,
1877 fpa.config_info.symrefs,
1878 fpa.config_info.wanted_branches,
1879 fpa.config_info.wanted_refs, fpa.repo);
1880 if (error)
1881 goto done;
1885 if (verbosity >= 0)
1886 printf("Created %s repository '%s'\n",
1887 mirror_references ? "mirrored" : "cloned", repo_path);
1888 done:
1889 if (pack_fds) {
1890 const struct got_error *pack_err =
1891 got_repo_pack_fds_close(pack_fds);
1892 if (error == NULL)
1893 error = pack_err;
1895 if (fetchpid > 0) {
1896 if (kill(fetchpid, SIGTERM) == -1)
1897 error = got_error_from_errno("kill");
1898 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1899 error = got_error_from_errno("waitpid");
1901 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1902 error = got_error_from_errno("close");
1903 if (repo) {
1904 const struct got_error *close_err = got_repo_close(repo);
1905 if (error == NULL)
1906 error = close_err;
1908 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1909 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1910 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1911 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1912 free(pack_hash);
1913 free(proto);
1914 free(host);
1915 free(port);
1916 free(server_path);
1917 free(repo_name);
1918 free(default_destdir);
1919 free(git_url);
1920 return error;
1923 static const struct got_error *
1924 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1925 int replace_tags, int verbosity, struct got_repository *repo)
1927 const struct got_error *err = NULL;
1928 char *new_id_str = NULL;
1929 struct got_object_id *old_id = NULL;
1931 err = got_object_id_str(&new_id_str, new_id);
1932 if (err)
1933 goto done;
1935 if (!replace_tags &&
1936 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1937 err = got_ref_resolve(&old_id, repo, ref);
1938 if (err)
1939 goto done;
1940 if (got_object_id_cmp(old_id, new_id) == 0)
1941 goto done;
1942 if (verbosity >= 0) {
1943 printf("Rejecting update of existing tag %s: %s\n",
1944 got_ref_get_name(ref), new_id_str);
1946 goto done;
1949 if (got_ref_is_symbolic(ref)) {
1950 if (verbosity >= 0) {
1951 printf("Replacing reference %s: %s\n",
1952 got_ref_get_name(ref),
1953 got_ref_get_symref_target(ref));
1955 err = got_ref_change_symref_to_ref(ref, new_id);
1956 if (err)
1957 goto done;
1958 err = got_ref_write(ref, repo);
1959 if (err)
1960 goto done;
1961 } else {
1962 err = got_ref_resolve(&old_id, repo, ref);
1963 if (err)
1964 goto done;
1965 if (got_object_id_cmp(old_id, new_id) == 0)
1966 goto done;
1968 err = got_ref_change_ref(ref, new_id);
1969 if (err)
1970 goto done;
1971 err = got_ref_write(ref, repo);
1972 if (err)
1973 goto done;
1976 if (verbosity >= 0)
1977 printf("Updated %s: %s\n", got_ref_get_name(ref),
1978 new_id_str);
1979 done:
1980 free(old_id);
1981 free(new_id_str);
1982 return err;
1985 static const struct got_error *
1986 update_symref(const char *refname, struct got_reference *target_ref,
1987 int verbosity, struct got_repository *repo)
1989 const struct got_error *err = NULL, *unlock_err;
1990 struct got_reference *symref;
1991 int symref_is_locked = 0;
1993 err = got_ref_open(&symref, repo, refname, 1);
1994 if (err) {
1995 if (err->code != GOT_ERR_NOT_REF)
1996 return err;
1997 err = got_ref_alloc_symref(&symref, refname, target_ref);
1998 if (err)
1999 goto done;
2001 err = got_ref_write(symref, repo);
2002 if (err)
2003 goto done;
2005 if (verbosity >= 0)
2006 printf("Created reference %s: %s\n",
2007 got_ref_get_name(symref),
2008 got_ref_get_symref_target(symref));
2009 } else {
2010 symref_is_locked = 1;
2012 if (strcmp(got_ref_get_symref_target(symref),
2013 got_ref_get_name(target_ref)) == 0)
2014 goto done;
2016 err = got_ref_change_symref(symref,
2017 got_ref_get_name(target_ref));
2018 if (err)
2019 goto done;
2021 err = got_ref_write(symref, repo);
2022 if (err)
2023 goto done;
2025 if (verbosity >= 0)
2026 printf("Updated %s: %s\n", got_ref_get_name(symref),
2027 got_ref_get_symref_target(symref));
2030 done:
2031 if (symref_is_locked) {
2032 unlock_err = got_ref_unlock(symref);
2033 if (unlock_err && err == NULL)
2034 err = unlock_err;
2036 got_ref_close(symref);
2037 return err;
2040 __dead static void
2041 usage_fetch(void)
2043 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2044 "[-R reference] [-r repository-path] [remote-repository]\n",
2045 getprogname());
2046 exit(1);
2049 static const struct got_error *
2050 delete_missing_ref(struct got_reference *ref,
2051 int verbosity, struct got_repository *repo)
2053 const struct got_error *err = NULL;
2054 struct got_object_id *id = NULL;
2055 char *id_str = NULL;
2057 if (got_ref_is_symbolic(ref)) {
2058 err = got_ref_delete(ref, repo);
2059 if (err)
2060 return err;
2061 if (verbosity >= 0) {
2062 printf("Deleted %s: %s\n",
2063 got_ref_get_name(ref),
2064 got_ref_get_symref_target(ref));
2066 } else {
2067 err = got_ref_resolve(&id, repo, ref);
2068 if (err)
2069 return err;
2070 err = got_object_id_str(&id_str, id);
2071 if (err)
2072 goto done;
2074 err = got_ref_delete(ref, repo);
2075 if (err)
2076 goto done;
2077 if (verbosity >= 0) {
2078 printf("Deleted %s: %s\n",
2079 got_ref_get_name(ref), id_str);
2082 done:
2083 free(id);
2084 free(id_str);
2085 return err;
2088 static const struct got_error *
2089 delete_missing_refs(struct got_pathlist_head *their_refs,
2090 struct got_pathlist_head *their_symrefs,
2091 const struct got_remote_repo *remote,
2092 int verbosity, struct got_repository *repo)
2094 const struct got_error *err = NULL, *unlock_err;
2095 struct got_reflist_head my_refs;
2096 struct got_reflist_entry *re;
2097 struct got_pathlist_entry *pe;
2098 char *remote_namespace = NULL;
2099 char *local_refname = NULL;
2101 TAILQ_INIT(&my_refs);
2103 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2104 == -1)
2105 return got_error_from_errno("asprintf");
2107 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2108 if (err)
2109 goto done;
2111 TAILQ_FOREACH(re, &my_refs, entry) {
2112 const char *refname = got_ref_get_name(re->ref);
2113 const char *their_refname;
2115 if (remote->mirror_references) {
2116 their_refname = refname;
2117 } else {
2118 if (strncmp(refname, remote_namespace,
2119 strlen(remote_namespace)) == 0) {
2120 if (strcmp(refname + strlen(remote_namespace),
2121 GOT_REF_HEAD) == 0)
2122 continue;
2123 if (asprintf(&local_refname, "refs/heads/%s",
2124 refname + strlen(remote_namespace)) == -1) {
2125 err = got_error_from_errno("asprintf");
2126 goto done;
2128 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2129 continue;
2131 their_refname = local_refname;
2134 TAILQ_FOREACH(pe, their_refs, entry) {
2135 if (strcmp(their_refname, pe->path) == 0)
2136 break;
2138 if (pe != NULL)
2139 continue;
2141 TAILQ_FOREACH(pe, their_symrefs, entry) {
2142 if (strcmp(their_refname, pe->path) == 0)
2143 break;
2145 if (pe != NULL)
2146 continue;
2148 err = delete_missing_ref(re->ref, verbosity, repo);
2149 if (err)
2150 break;
2152 if (local_refname) {
2153 struct got_reference *ref;
2154 err = got_ref_open(&ref, repo, local_refname, 1);
2155 if (err) {
2156 if (err->code != GOT_ERR_NOT_REF)
2157 break;
2158 free(local_refname);
2159 local_refname = NULL;
2160 continue;
2162 err = delete_missing_ref(ref, verbosity, repo);
2163 if (err)
2164 break;
2165 unlock_err = got_ref_unlock(ref);
2166 got_ref_close(ref);
2167 if (unlock_err && err == NULL) {
2168 err = unlock_err;
2169 break;
2172 free(local_refname);
2173 local_refname = NULL;
2176 done:
2177 got_ref_list_free(&my_refs);
2178 free(remote_namespace);
2179 free(local_refname);
2180 return err;
2183 static const struct got_error *
2184 update_wanted_ref(const char *refname, struct got_object_id *id,
2185 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2187 const struct got_error *err, *unlock_err;
2188 char *remote_refname;
2189 struct got_reference *ref;
2191 if (strncmp("refs/", refname, 5) == 0)
2192 refname += 5;
2194 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2195 remote_repo_name, refname) == -1)
2196 return got_error_from_errno("asprintf");
2198 err = got_ref_open(&ref, repo, remote_refname, 1);
2199 if (err) {
2200 if (err->code != GOT_ERR_NOT_REF)
2201 goto done;
2202 err = create_ref(remote_refname, id, verbosity, repo);
2203 } else {
2204 err = update_ref(ref, id, 0, verbosity, repo);
2205 unlock_err = got_ref_unlock(ref);
2206 if (unlock_err && err == NULL)
2207 err = unlock_err;
2208 got_ref_close(ref);
2210 done:
2211 free(remote_refname);
2212 return err;
2215 static const struct got_error *
2216 delete_ref(struct got_repository *repo, struct got_reference *ref)
2218 const struct got_error *err = NULL;
2219 struct got_object_id *id = NULL;
2220 char *id_str = NULL;
2221 const char *target;
2223 if (got_ref_is_symbolic(ref)) {
2224 target = got_ref_get_symref_target(ref);
2225 } else {
2226 err = got_ref_resolve(&id, repo, ref);
2227 if (err)
2228 goto done;
2229 err = got_object_id_str(&id_str, id);
2230 if (err)
2231 goto done;
2232 target = id_str;
2235 err = got_ref_delete(ref, repo);
2236 if (err)
2237 goto done;
2239 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2240 done:
2241 free(id);
2242 free(id_str);
2243 return err;
2246 static const struct got_error *
2247 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2249 const struct got_error *err = NULL;
2250 struct got_reflist_head refs;
2251 struct got_reflist_entry *re;
2252 char *prefix;
2254 TAILQ_INIT(&refs);
2256 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2257 err = got_error_from_errno("asprintf");
2258 goto done;
2260 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2261 if (err)
2262 goto done;
2264 TAILQ_FOREACH(re, &refs, entry)
2265 delete_ref(repo, re->ref);
2266 done:
2267 got_ref_list_free(&refs);
2268 return err;
2271 static const struct got_error *
2272 cmd_fetch(int argc, char *argv[])
2274 const struct got_error *error = NULL, *unlock_err;
2275 char *cwd = NULL, *repo_path = NULL;
2276 const char *remote_name;
2277 char *proto = NULL, *host = NULL, *port = NULL;
2278 char *repo_name = NULL, *server_path = NULL;
2279 const struct got_remote_repo *remotes, *remote = NULL;
2280 int nremotes;
2281 char *id_str = NULL;
2282 struct got_repository *repo = NULL;
2283 struct got_worktree *worktree = NULL;
2284 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2285 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2286 struct got_pathlist_entry *pe;
2287 struct got_reflist_head remote_refs;
2288 struct got_reflist_entry *re;
2289 struct got_object_id *pack_hash = NULL;
2290 int i, ch, fetchfd = -1, fetchstatus;
2291 pid_t fetchpid = -1;
2292 struct got_fetch_progress_arg fpa;
2293 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2294 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2295 int *pack_fds = NULL, have_bflag = 0;
2296 const char *remote_head = NULL, *worktree_branch = NULL;
2298 TAILQ_INIT(&refs);
2299 TAILQ_INIT(&symrefs);
2300 TAILQ_INIT(&remote_refs);
2301 TAILQ_INIT(&wanted_branches);
2302 TAILQ_INIT(&wanted_refs);
2304 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2305 switch (ch) {
2306 case 'a':
2307 fetch_all_branches = 1;
2308 break;
2309 case 'b':
2310 error = got_pathlist_append(&wanted_branches,
2311 optarg, NULL);
2312 if (error)
2313 return error;
2314 have_bflag = 1;
2315 break;
2316 case 'd':
2317 delete_refs = 1;
2318 break;
2319 case 'l':
2320 list_refs_only = 1;
2321 break;
2322 case 'q':
2323 verbosity = -1;
2324 break;
2325 case 'R':
2326 error = got_pathlist_append(&wanted_refs,
2327 optarg, NULL);
2328 if (error)
2329 return error;
2330 break;
2331 case 'r':
2332 repo_path = realpath(optarg, NULL);
2333 if (repo_path == NULL)
2334 return got_error_from_errno2("realpath",
2335 optarg);
2336 got_path_strip_trailing_slashes(repo_path);
2337 break;
2338 case 't':
2339 replace_tags = 1;
2340 break;
2341 case 'v':
2342 if (verbosity < 0)
2343 verbosity = 0;
2344 else if (verbosity < 3)
2345 verbosity++;
2346 break;
2347 case 'X':
2348 delete_remote = 1;
2349 break;
2350 default:
2351 usage_fetch();
2352 break;
2355 argc -= optind;
2356 argv += optind;
2358 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2359 option_conflict('a', 'b');
2360 if (list_refs_only) {
2361 if (!TAILQ_EMPTY(&wanted_branches))
2362 option_conflict('l', 'b');
2363 if (fetch_all_branches)
2364 option_conflict('l', 'a');
2365 if (delete_refs)
2366 option_conflict('l', 'd');
2367 if (delete_remote)
2368 option_conflict('l', 'X');
2370 if (delete_remote) {
2371 if (fetch_all_branches)
2372 option_conflict('X', 'a');
2373 if (!TAILQ_EMPTY(&wanted_branches))
2374 option_conflict('X', 'b');
2375 if (delete_refs)
2376 option_conflict('X', 'd');
2377 if (replace_tags)
2378 option_conflict('X', 't');
2379 if (!TAILQ_EMPTY(&wanted_refs))
2380 option_conflict('X', 'R');
2383 if (argc == 0) {
2384 if (delete_remote)
2385 errx(1, "-X option requires a remote name");
2386 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2387 } else if (argc == 1)
2388 remote_name = argv[0];
2389 else
2390 usage_fetch();
2392 cwd = getcwd(NULL, 0);
2393 if (cwd == NULL) {
2394 error = got_error_from_errno("getcwd");
2395 goto done;
2398 error = got_repo_pack_fds_open(&pack_fds);
2399 if (error != NULL)
2400 goto done;
2402 if (repo_path == NULL) {
2403 error = got_worktree_open(&worktree, cwd);
2404 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2405 goto done;
2406 else
2407 error = NULL;
2408 if (worktree) {
2409 repo_path =
2410 strdup(got_worktree_get_repo_path(worktree));
2411 if (repo_path == NULL)
2412 error = got_error_from_errno("strdup");
2413 if (error)
2414 goto done;
2415 } else {
2416 repo_path = strdup(cwd);
2417 if (repo_path == NULL) {
2418 error = got_error_from_errno("strdup");
2419 goto done;
2424 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2425 if (error)
2426 goto done;
2428 if (delete_remote) {
2429 error = delete_refs_for_remote(repo, remote_name);
2430 goto done; /* nothing else to do */
2433 if (worktree) {
2434 worktree_conf = got_worktree_get_gotconfig(worktree);
2435 if (worktree_conf) {
2436 got_gotconfig_get_remotes(&nremotes, &remotes,
2437 worktree_conf);
2438 for (i = 0; i < nremotes; i++) {
2439 if (strcmp(remotes[i].name, remote_name) == 0) {
2440 remote = &remotes[i];
2441 break;
2446 if (remote == NULL) {
2447 repo_conf = got_repo_get_gotconfig(repo);
2448 if (repo_conf) {
2449 got_gotconfig_get_remotes(&nremotes, &remotes,
2450 repo_conf);
2451 for (i = 0; i < nremotes; i++) {
2452 if (strcmp(remotes[i].name, remote_name) == 0) {
2453 remote = &remotes[i];
2454 break;
2459 if (remote == NULL) {
2460 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2461 for (i = 0; i < nremotes; i++) {
2462 if (strcmp(remotes[i].name, remote_name) == 0) {
2463 remote = &remotes[i];
2464 break;
2468 if (remote == NULL) {
2469 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2470 goto done;
2473 if (TAILQ_EMPTY(&wanted_branches)) {
2474 if (!fetch_all_branches)
2475 fetch_all_branches = remote->fetch_all_branches;
2476 for (i = 0; i < remote->nfetch_branches; i++) {
2477 error = got_pathlist_append(&wanted_branches,
2478 remote->fetch_branches[i], NULL);
2479 if (error)
2480 goto done;
2483 if (TAILQ_EMPTY(&wanted_refs)) {
2484 for (i = 0; i < remote->nfetch_refs; i++) {
2485 error = got_pathlist_append(&wanted_refs,
2486 remote->fetch_refs[i], NULL);
2487 if (error)
2488 goto done;
2492 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2493 &repo_name, remote->fetch_url);
2494 if (error)
2495 goto done;
2497 if (strcmp(proto, "git") == 0) {
2498 #ifndef PROFILE
2499 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2500 "sendfd dns inet unveil", NULL) == -1)
2501 err(1, "pledge");
2502 #endif
2503 } else if (strcmp(proto, "git+ssh") == 0 ||
2504 strcmp(proto, "ssh") == 0) {
2505 #ifndef PROFILE
2506 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2507 "sendfd unveil", NULL) == -1)
2508 err(1, "pledge");
2509 #endif
2510 } else if (strcmp(proto, "http") == 0 ||
2511 strcmp(proto, "git+http") == 0) {
2512 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2513 goto done;
2514 } else {
2515 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2516 goto done;
2519 error = got_dial_apply_unveil(proto);
2520 if (error)
2521 goto done;
2523 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2524 if (error)
2525 goto done;
2527 if (verbosity >= 0) {
2528 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2529 remote->name, proto, host,
2530 port ? ":" : "", port ? port : "",
2531 *server_path == '/' ? "" : "/", server_path);
2534 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2535 server_path, verbosity);
2536 if (error)
2537 goto done;
2539 if (!have_bflag) {
2541 * If set, get this remote's HEAD ref target so
2542 * if it has changed on the server we can fetch it.
2544 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2545 got_ref_cmp_by_name, repo);
2546 if (error)
2547 goto done;
2549 TAILQ_FOREACH(re, &remote_refs, entry) {
2550 const char *remote_refname, *remote_target;
2551 size_t remote_name_len;
2553 if (!got_ref_is_symbolic(re->ref))
2554 continue;
2556 remote_name_len = strlen(remote->name);
2557 remote_refname = got_ref_get_name(re->ref);
2559 /* we only want refs/remotes/$remote->name/HEAD */
2560 if (strncmp(remote_refname + 13, remote->name,
2561 remote_name_len) != 0)
2562 continue;
2564 if (strcmp(remote_refname + remote_name_len + 14,
2565 GOT_REF_HEAD) != 0)
2566 continue;
2569 * Take the name itself because we already
2570 * only match with refs/heads/ in fetch_pack().
2572 remote_target = got_ref_get_symref_target(re->ref);
2573 remote_head = remote_target + remote_name_len + 14;
2574 break;
2577 if (worktree) {
2578 const char *refname;
2580 refname = got_worktree_get_head_ref_name(worktree);
2581 if (strncmp(refname, "refs/heads/", 11) == 0)
2582 worktree_branch = refname;
2586 fpa.last_scaled_size[0] = '\0';
2587 fpa.last_p_indexed = -1;
2588 fpa.last_p_resolved = -1;
2589 fpa.verbosity = verbosity;
2590 fpa.repo = repo;
2591 fpa.create_configs = 0;
2592 fpa.configs_created = 0;
2593 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2595 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2596 remote->mirror_references, fetch_all_branches, &wanted_branches,
2597 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2598 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2599 if (error)
2600 goto done;
2602 if (list_refs_only) {
2603 error = list_remote_refs(&symrefs, &refs);
2604 goto done;
2607 if (pack_hash == NULL) {
2608 if (verbosity >= 0)
2609 printf("Already up-to-date\n");
2610 } else if (verbosity >= 0) {
2611 error = got_object_id_str(&id_str, pack_hash);
2612 if (error)
2613 goto done;
2614 printf("\nFetched %s.pack\n", id_str);
2615 free(id_str);
2616 id_str = NULL;
2619 /* Update references provided with the pack file. */
2620 TAILQ_FOREACH(pe, &refs, entry) {
2621 const char *refname = pe->path;
2622 struct got_object_id *id = pe->data;
2623 struct got_reference *ref;
2624 char *remote_refname;
2626 if (is_wanted_ref(&wanted_refs, refname) &&
2627 !remote->mirror_references) {
2628 error = update_wanted_ref(refname, id,
2629 remote->name, verbosity, repo);
2630 if (error)
2631 goto done;
2632 continue;
2635 if (remote->mirror_references ||
2636 strncmp("refs/tags/", refname, 10) == 0) {
2637 error = got_ref_open(&ref, repo, refname, 1);
2638 if (error) {
2639 if (error->code != GOT_ERR_NOT_REF)
2640 goto done;
2641 error = create_ref(refname, id, verbosity,
2642 repo);
2643 if (error)
2644 goto done;
2645 } else {
2646 error = update_ref(ref, id, replace_tags,
2647 verbosity, repo);
2648 unlock_err = got_ref_unlock(ref);
2649 if (unlock_err && error == NULL)
2650 error = unlock_err;
2651 got_ref_close(ref);
2652 if (error)
2653 goto done;
2655 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2656 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2657 remote_name, refname + 11) == -1) {
2658 error = got_error_from_errno("asprintf");
2659 goto done;
2662 error = got_ref_open(&ref, repo, remote_refname, 1);
2663 if (error) {
2664 if (error->code != GOT_ERR_NOT_REF)
2665 goto done;
2666 error = create_ref(remote_refname, id,
2667 verbosity, repo);
2668 if (error)
2669 goto done;
2670 } else {
2671 error = update_ref(ref, id, replace_tags,
2672 verbosity, repo);
2673 unlock_err = got_ref_unlock(ref);
2674 if (unlock_err && error == NULL)
2675 error = unlock_err;
2676 got_ref_close(ref);
2677 if (error)
2678 goto done;
2681 /* Also create a local branch if none exists yet. */
2682 error = got_ref_open(&ref, repo, refname, 1);
2683 if (error) {
2684 if (error->code != GOT_ERR_NOT_REF)
2685 goto done;
2686 error = create_ref(refname, id, verbosity,
2687 repo);
2688 if (error)
2689 goto done;
2690 } else {
2691 unlock_err = got_ref_unlock(ref);
2692 if (unlock_err && error == NULL)
2693 error = unlock_err;
2694 got_ref_close(ref);
2698 if (delete_refs) {
2699 error = delete_missing_refs(&refs, &symrefs, remote,
2700 verbosity, repo);
2701 if (error)
2702 goto done;
2705 if (!remote->mirror_references) {
2706 /* Update remote HEAD reference if the server provided one. */
2707 TAILQ_FOREACH(pe, &symrefs, entry) {
2708 struct got_reference *target_ref;
2709 const char *refname = pe->path;
2710 const char *target = pe->data;
2711 char *remote_refname = NULL, *remote_target = NULL;
2713 if (strcmp(refname, GOT_REF_HEAD) != 0)
2714 continue;
2716 if (strncmp("refs/heads/", target, 11) != 0)
2717 continue;
2719 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2720 remote->name, refname) == -1) {
2721 error = got_error_from_errno("asprintf");
2722 goto done;
2724 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2725 remote->name, target + 11) == -1) {
2726 error = got_error_from_errno("asprintf");
2727 free(remote_refname);
2728 goto done;
2731 error = got_ref_open(&target_ref, repo, remote_target,
2732 0);
2733 if (error) {
2734 free(remote_refname);
2735 free(remote_target);
2736 if (error->code == GOT_ERR_NOT_REF) {
2737 error = NULL;
2738 continue;
2740 goto done;
2742 error = update_symref(remote_refname, target_ref,
2743 verbosity, repo);
2744 free(remote_refname);
2745 free(remote_target);
2746 got_ref_close(target_ref);
2747 if (error)
2748 goto done;
2751 done:
2752 if (fetchpid > 0) {
2753 if (kill(fetchpid, SIGTERM) == -1)
2754 error = got_error_from_errno("kill");
2755 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2756 error = got_error_from_errno("waitpid");
2758 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2759 error = got_error_from_errno("close");
2760 if (repo) {
2761 const struct got_error *close_err = got_repo_close(repo);
2762 if (error == NULL)
2763 error = close_err;
2765 if (worktree)
2766 got_worktree_close(worktree);
2767 if (pack_fds) {
2768 const struct got_error *pack_err =
2769 got_repo_pack_fds_close(pack_fds);
2770 if (error == NULL)
2771 error = pack_err;
2773 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2774 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2775 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2776 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2777 got_ref_list_free(&remote_refs);
2778 free(id_str);
2779 free(cwd);
2780 free(repo_path);
2781 free(pack_hash);
2782 free(proto);
2783 free(host);
2784 free(port);
2785 free(server_path);
2786 free(repo_name);
2787 return error;
2791 __dead static void
2792 usage_checkout(void)
2794 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2795 "[-p path-prefix] repository-path [work-tree-path]\n",
2796 getprogname());
2797 exit(1);
2800 static void
2801 show_worktree_base_ref_warning(void)
2803 fprintf(stderr, "%s: warning: could not create a reference "
2804 "to the work tree's base commit; the commit could be "
2805 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2806 "repository writable and running 'got update' will prevent this\n",
2807 getprogname());
2810 struct got_checkout_progress_arg {
2811 const char *worktree_path;
2812 int had_base_commit_ref_error;
2813 int verbosity;
2816 static const struct got_error *
2817 checkout_progress(void *arg, unsigned char status, const char *path)
2819 struct got_checkout_progress_arg *a = arg;
2821 /* Base commit bump happens silently. */
2822 if (status == GOT_STATUS_BUMP_BASE)
2823 return NULL;
2825 if (status == GOT_STATUS_BASE_REF_ERR) {
2826 a->had_base_commit_ref_error = 1;
2827 return NULL;
2830 while (path[0] == '/')
2831 path++;
2833 if (a->verbosity >= 0)
2834 printf("%c %s/%s\n", status, a->worktree_path, path);
2836 return NULL;
2839 static const struct got_error *
2840 check_cancelled(void *arg)
2842 if (sigint_received || sigpipe_received)
2843 return got_error(GOT_ERR_CANCELLED);
2844 return NULL;
2847 static const struct got_error *
2848 check_linear_ancestry(struct got_object_id *commit_id,
2849 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2850 struct got_repository *repo)
2852 const struct got_error *err = NULL;
2853 struct got_object_id *yca_id;
2855 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2856 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2857 if (err)
2858 return err;
2860 if (yca_id == NULL)
2861 return got_error(GOT_ERR_ANCESTRY);
2864 * Require a straight line of history between the target commit
2865 * and the work tree's base commit.
2867 * Non-linear situations such as this require a rebase:
2869 * (commit) D F (base_commit)
2870 * \ /
2871 * C E
2872 * \ /
2873 * B (yca)
2874 * |
2875 * A
2877 * 'got update' only handles linear cases:
2878 * Update forwards in time: A (base/yca) - B - C - D (commit)
2879 * Update backwards in time: D (base) - C - B - A (commit/yca)
2881 if (allow_forwards_in_time_only) {
2882 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2883 return got_error(GOT_ERR_ANCESTRY);
2884 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2885 got_object_id_cmp(base_commit_id, yca_id) != 0)
2886 return got_error(GOT_ERR_ANCESTRY);
2888 free(yca_id);
2889 return NULL;
2892 static const struct got_error *
2893 check_same_branch(struct got_object_id *commit_id,
2894 struct got_reference *head_ref, struct got_object_id *yca_id,
2895 struct got_repository *repo)
2897 const struct got_error *err = NULL;
2898 struct got_commit_graph *graph = NULL;
2899 struct got_object_id *head_commit_id = NULL;
2900 int is_same_branch = 0;
2902 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2903 if (err)
2904 goto done;
2906 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2907 is_same_branch = 1;
2908 goto done;
2910 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2911 is_same_branch = 1;
2912 goto done;
2915 err = got_commit_graph_open(&graph, "/", 1);
2916 if (err)
2917 goto done;
2919 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2920 check_cancelled, NULL);
2921 if (err)
2922 goto done;
2924 for (;;) {
2925 struct got_object_id id;
2927 err = got_commit_graph_iter_next(&id, graph, repo,
2928 check_cancelled, NULL);
2929 if (err) {
2930 if (err->code == GOT_ERR_ITER_COMPLETED)
2931 err = NULL;
2932 break;
2935 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2936 break;
2937 if (got_object_id_cmp(&id, commit_id) == 0) {
2938 is_same_branch = 1;
2939 break;
2942 done:
2943 if (graph)
2944 got_commit_graph_close(graph);
2945 free(head_commit_id);
2946 if (!err && !is_same_branch)
2947 err = got_error(GOT_ERR_ANCESTRY);
2948 return err;
2951 static const struct got_error *
2952 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2954 static char msg[512];
2955 const char *branch_name;
2957 if (got_ref_is_symbolic(ref))
2958 branch_name = got_ref_get_symref_target(ref);
2959 else
2960 branch_name = got_ref_get_name(ref);
2962 if (strncmp("refs/heads/", branch_name, 11) == 0)
2963 branch_name += 11;
2965 snprintf(msg, sizeof(msg),
2966 "target commit is not contained in branch '%s'; "
2967 "the branch to use must be specified with -b; "
2968 "if necessary a new branch can be created for "
2969 "this commit with 'got branch -c %s BRANCH_NAME'",
2970 branch_name, commit_id_str);
2972 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2975 static const struct got_error *
2976 cmd_checkout(int argc, char *argv[])
2978 const struct got_error *error = NULL;
2979 struct got_repository *repo = NULL;
2980 struct got_reference *head_ref = NULL, *ref = NULL;
2981 struct got_worktree *worktree = NULL;
2982 char *repo_path = NULL;
2983 char *worktree_path = NULL;
2984 const char *path_prefix = "";
2985 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2986 char *commit_id_str = NULL;
2987 struct got_object_id *commit_id = NULL;
2988 char *cwd = NULL;
2989 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2990 struct got_pathlist_head paths;
2991 struct got_checkout_progress_arg cpa;
2992 int *pack_fds = NULL;
2994 TAILQ_INIT(&paths);
2996 #ifndef PROFILE
2997 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2998 "unveil", NULL) == -1)
2999 err(1, "pledge");
3000 #endif
3002 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3003 switch (ch) {
3004 case 'b':
3005 branch_name = optarg;
3006 break;
3007 case 'c':
3008 commit_id_str = strdup(optarg);
3009 if (commit_id_str == NULL)
3010 return got_error_from_errno("strdup");
3011 break;
3012 case 'E':
3013 allow_nonempty = 1;
3014 break;
3015 case 'p':
3016 path_prefix = optarg;
3017 break;
3018 case 'q':
3019 verbosity = -1;
3020 break;
3021 default:
3022 usage_checkout();
3023 /* NOTREACHED */
3027 argc -= optind;
3028 argv += optind;
3030 if (argc == 1) {
3031 char *base, *dotgit;
3032 const char *path;
3033 repo_path = realpath(argv[0], NULL);
3034 if (repo_path == NULL)
3035 return got_error_from_errno2("realpath", argv[0]);
3036 cwd = getcwd(NULL, 0);
3037 if (cwd == NULL) {
3038 error = got_error_from_errno("getcwd");
3039 goto done;
3041 if (path_prefix[0])
3042 path = path_prefix;
3043 else
3044 path = repo_path;
3045 error = got_path_basename(&base, path);
3046 if (error)
3047 goto done;
3048 dotgit = strstr(base, ".git");
3049 if (dotgit)
3050 *dotgit = '\0';
3051 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3052 error = got_error_from_errno("asprintf");
3053 free(base);
3054 goto done;
3056 free(base);
3057 } else if (argc == 2) {
3058 repo_path = realpath(argv[0], NULL);
3059 if (repo_path == NULL) {
3060 error = got_error_from_errno2("realpath", argv[0]);
3061 goto done;
3063 worktree_path = realpath(argv[1], NULL);
3064 if (worktree_path == NULL) {
3065 if (errno != ENOENT) {
3066 error = got_error_from_errno2("realpath",
3067 argv[1]);
3068 goto done;
3070 worktree_path = strdup(argv[1]);
3071 if (worktree_path == NULL) {
3072 error = got_error_from_errno("strdup");
3073 goto done;
3076 } else
3077 usage_checkout();
3079 got_path_strip_trailing_slashes(repo_path);
3080 got_path_strip_trailing_slashes(worktree_path);
3082 error = got_repo_pack_fds_open(&pack_fds);
3083 if (error != NULL)
3084 goto done;
3086 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3087 if (error != NULL)
3088 goto done;
3090 /* Pre-create work tree path for unveil(2) */
3091 error = got_path_mkdir(worktree_path);
3092 if (error) {
3093 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3094 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3095 goto done;
3096 if (!allow_nonempty &&
3097 !got_path_dir_is_empty(worktree_path)) {
3098 error = got_error_path(worktree_path,
3099 GOT_ERR_DIR_NOT_EMPTY);
3100 goto done;
3104 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3105 if (error)
3106 goto done;
3108 error = got_ref_open(&head_ref, repo, branch_name, 0);
3109 if (error != NULL)
3110 goto done;
3112 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3113 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3114 goto done;
3116 error = got_worktree_open(&worktree, worktree_path);
3117 if (error != NULL)
3118 goto done;
3120 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3121 path_prefix);
3122 if (error != NULL)
3123 goto done;
3124 if (!same_path_prefix) {
3125 error = got_error(GOT_ERR_PATH_PREFIX);
3126 goto done;
3129 if (commit_id_str) {
3130 struct got_reflist_head refs;
3131 TAILQ_INIT(&refs);
3132 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3133 NULL);
3134 if (error)
3135 goto done;
3136 error = got_repo_match_object_id(&commit_id, NULL,
3137 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3138 got_ref_list_free(&refs);
3139 if (error)
3140 goto done;
3141 error = check_linear_ancestry(commit_id,
3142 got_worktree_get_base_commit_id(worktree), 0, repo);
3143 if (error != NULL) {
3144 if (error->code == GOT_ERR_ANCESTRY) {
3145 error = checkout_ancestry_error(
3146 head_ref, commit_id_str);
3148 goto done;
3150 error = check_same_branch(commit_id, head_ref, NULL, repo);
3151 if (error) {
3152 if (error->code == GOT_ERR_ANCESTRY) {
3153 error = checkout_ancestry_error(
3154 head_ref, commit_id_str);
3156 goto done;
3158 error = got_worktree_set_base_commit_id(worktree, repo,
3159 commit_id);
3160 if (error)
3161 goto done;
3162 /* Expand potentially abbreviated commit ID string. */
3163 free(commit_id_str);
3164 error = got_object_id_str(&commit_id_str, commit_id);
3165 if (error)
3166 goto done;
3167 } else {
3168 commit_id = got_object_id_dup(
3169 got_worktree_get_base_commit_id(worktree));
3170 if (commit_id == NULL) {
3171 error = got_error_from_errno("got_object_id_dup");
3172 goto done;
3174 error = got_object_id_str(&commit_id_str, commit_id);
3175 if (error)
3176 goto done;
3179 error = got_pathlist_append(&paths, "", NULL);
3180 if (error)
3181 goto done;
3182 cpa.worktree_path = worktree_path;
3183 cpa.had_base_commit_ref_error = 0;
3184 cpa.verbosity = verbosity;
3185 error = got_worktree_checkout_files(worktree, &paths, repo,
3186 checkout_progress, &cpa, check_cancelled, NULL);
3187 if (error != NULL)
3188 goto done;
3190 if (got_ref_is_symbolic(head_ref)) {
3191 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3192 if (error)
3193 goto done;
3194 refname = got_ref_get_name(ref);
3195 } else
3196 refname = got_ref_get_name(head_ref);
3197 printf("Checked out %s: %s\n", refname, commit_id_str);
3198 printf("Now shut up and hack\n");
3199 if (cpa.had_base_commit_ref_error)
3200 show_worktree_base_ref_warning();
3201 done:
3202 if (pack_fds) {
3203 const struct got_error *pack_err =
3204 got_repo_pack_fds_close(pack_fds);
3205 if (error == NULL)
3206 error = pack_err;
3208 if (head_ref)
3209 got_ref_close(head_ref);
3210 if (ref)
3211 got_ref_close(ref);
3212 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3213 free(commit_id_str);
3214 free(commit_id);
3215 free(repo_path);
3216 free(worktree_path);
3217 free(cwd);
3218 return error;
3221 struct got_update_progress_arg {
3222 int did_something;
3223 int conflicts;
3224 int obstructed;
3225 int not_updated;
3226 int missing;
3227 int not_deleted;
3228 int unversioned;
3229 int verbosity;
3232 static void
3233 print_update_progress_stats(struct got_update_progress_arg *upa)
3235 if (!upa->did_something)
3236 return;
3238 if (upa->conflicts > 0)
3239 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3240 if (upa->obstructed > 0)
3241 printf("File paths obstructed by a non-regular file: %d\n",
3242 upa->obstructed);
3243 if (upa->not_updated > 0)
3244 printf("Files not updated because of existing merge "
3245 "conflicts: %d\n", upa->not_updated);
3249 * The meaning of some status codes differs between merge-style operations and
3250 * update operations. For example, the ! status code means "file was missing"
3251 * if changes were merged into the work tree, and "missing file was restored"
3252 * if the work tree was updated. This function should be used by any operation
3253 * which merges changes into the work tree without updating the work tree.
3255 static void
3256 print_merge_progress_stats(struct got_update_progress_arg *upa)
3258 if (!upa->did_something)
3259 return;
3261 if (upa->conflicts > 0)
3262 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3263 if (upa->obstructed > 0)
3264 printf("File paths obstructed by a non-regular file: %d\n",
3265 upa->obstructed);
3266 if (upa->missing > 0)
3267 printf("Files which had incoming changes but could not be "
3268 "found in the work tree: %d\n", upa->missing);
3269 if (upa->not_deleted > 0)
3270 printf("Files not deleted due to differences in deleted "
3271 "content: %d\n", upa->not_deleted);
3272 if (upa->unversioned > 0)
3273 printf("Files not merged because an unversioned file was "
3274 "found in the work tree: %d\n", upa->unversioned);
3277 __dead static void
3278 usage_update(void)
3280 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3281 "[path ...]\n", getprogname());
3282 exit(1);
3285 static const struct got_error *
3286 update_progress(void *arg, unsigned char status, const char *path)
3288 struct got_update_progress_arg *upa = arg;
3290 if (status == GOT_STATUS_EXISTS ||
3291 status == GOT_STATUS_BASE_REF_ERR)
3292 return NULL;
3294 upa->did_something = 1;
3296 /* Base commit bump happens silently. */
3297 if (status == GOT_STATUS_BUMP_BASE)
3298 return NULL;
3300 if (status == GOT_STATUS_CONFLICT)
3301 upa->conflicts++;
3302 if (status == GOT_STATUS_OBSTRUCTED)
3303 upa->obstructed++;
3304 if (status == GOT_STATUS_CANNOT_UPDATE)
3305 upa->not_updated++;
3306 if (status == GOT_STATUS_MISSING)
3307 upa->missing++;
3308 if (status == GOT_STATUS_CANNOT_DELETE)
3309 upa->not_deleted++;
3310 if (status == GOT_STATUS_UNVERSIONED)
3311 upa->unversioned++;
3313 while (path[0] == '/')
3314 path++;
3315 if (upa->verbosity >= 0)
3316 printf("%c %s\n", status, path);
3318 return NULL;
3321 static const struct got_error *
3322 switch_head_ref(struct got_reference *head_ref,
3323 struct got_object_id *commit_id, struct got_worktree *worktree,
3324 struct got_repository *repo)
3326 const struct got_error *err = NULL;
3327 char *base_id_str;
3328 int ref_has_moved = 0;
3330 /* Trivial case: switching between two different references. */
3331 if (strcmp(got_ref_get_name(head_ref),
3332 got_worktree_get_head_ref_name(worktree)) != 0) {
3333 printf("Switching work tree from %s to %s\n",
3334 got_worktree_get_head_ref_name(worktree),
3335 got_ref_get_name(head_ref));
3336 return got_worktree_set_head_ref(worktree, head_ref);
3339 err = check_linear_ancestry(commit_id,
3340 got_worktree_get_base_commit_id(worktree), 0, repo);
3341 if (err) {
3342 if (err->code != GOT_ERR_ANCESTRY)
3343 return err;
3344 ref_has_moved = 1;
3346 if (!ref_has_moved)
3347 return NULL;
3349 /* Switching to a rebased branch with the same reference name. */
3350 err = got_object_id_str(&base_id_str,
3351 got_worktree_get_base_commit_id(worktree));
3352 if (err)
3353 return err;
3354 printf("Reference %s now points at a different branch\n",
3355 got_worktree_get_head_ref_name(worktree));
3356 printf("Switching work tree from %s to %s\n", base_id_str,
3357 got_worktree_get_head_ref_name(worktree));
3358 return NULL;
3361 static const struct got_error *
3362 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3364 const struct got_error *err;
3365 int in_progress;
3367 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3368 if (err)
3369 return err;
3370 if (in_progress)
3371 return got_error(GOT_ERR_REBASING);
3373 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3374 if (err)
3375 return err;
3376 if (in_progress)
3377 return got_error(GOT_ERR_HISTEDIT_BUSY);
3379 return NULL;
3382 static const struct got_error *
3383 check_merge_in_progress(struct got_worktree *worktree,
3384 struct got_repository *repo)
3386 const struct got_error *err;
3387 int in_progress;
3389 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3390 if (err)
3391 return err;
3392 if (in_progress)
3393 return got_error(GOT_ERR_MERGE_BUSY);
3395 return NULL;
3398 static const struct got_error *
3399 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3400 char *argv[], struct got_worktree *worktree)
3402 const struct got_error *err = NULL;
3403 char *path;
3404 struct got_pathlist_entry *new;
3405 int i;
3407 if (argc == 0) {
3408 path = strdup("");
3409 if (path == NULL)
3410 return got_error_from_errno("strdup");
3411 return got_pathlist_append(paths, path, NULL);
3414 for (i = 0; i < argc; i++) {
3415 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3416 if (err)
3417 break;
3418 err = got_pathlist_insert(&new, paths, path, NULL);
3419 if (err || new == NULL /* duplicate */) {
3420 free(path);
3421 if (err)
3422 break;
3426 return err;
3429 static const struct got_error *
3430 wrap_not_worktree_error(const struct got_error *orig_err,
3431 const char *cmdname, const char *path)
3433 const struct got_error *err;
3434 struct got_repository *repo;
3435 static char msg[512];
3436 int *pack_fds = NULL;
3438 err = got_repo_pack_fds_open(&pack_fds);
3439 if (err)
3440 return err;
3442 err = got_repo_open(&repo, path, NULL, pack_fds);
3443 if (err)
3444 return orig_err;
3446 snprintf(msg, sizeof(msg),
3447 "'got %s' needs a work tree in addition to a git repository\n"
3448 "Work trees can be checked out from this Git repository with "
3449 "'got checkout'.\n"
3450 "The got(1) manual page contains more information.", cmdname);
3451 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3452 got_repo_close(repo);
3453 if (pack_fds) {
3454 const struct got_error *pack_err =
3455 got_repo_pack_fds_close(pack_fds);
3456 if (err == NULL)
3457 err = pack_err;
3459 return err;
3462 static const struct got_error *
3463 cmd_update(int argc, char *argv[])
3465 const struct got_error *error = NULL;
3466 struct got_repository *repo = NULL;
3467 struct got_worktree *worktree = NULL;
3468 char *worktree_path = NULL;
3469 struct got_object_id *commit_id = NULL;
3470 char *commit_id_str = NULL;
3471 const char *branch_name = NULL;
3472 struct got_reference *head_ref = NULL;
3473 struct got_pathlist_head paths;
3474 struct got_pathlist_entry *pe;
3475 int ch, verbosity = 0;
3476 struct got_update_progress_arg upa;
3477 int *pack_fds = NULL;
3479 TAILQ_INIT(&paths);
3481 #ifndef PROFILE
3482 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3483 "unveil", NULL) == -1)
3484 err(1, "pledge");
3485 #endif
3487 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3488 switch (ch) {
3489 case 'b':
3490 branch_name = optarg;
3491 break;
3492 case 'c':
3493 commit_id_str = strdup(optarg);
3494 if (commit_id_str == NULL)
3495 return got_error_from_errno("strdup");
3496 break;
3497 case 'q':
3498 verbosity = -1;
3499 break;
3500 default:
3501 usage_update();
3502 /* NOTREACHED */
3506 argc -= optind;
3507 argv += optind;
3509 worktree_path = getcwd(NULL, 0);
3510 if (worktree_path == NULL) {
3511 error = got_error_from_errno("getcwd");
3512 goto done;
3515 error = got_repo_pack_fds_open(&pack_fds);
3516 if (error != NULL)
3517 goto done;
3519 error = got_worktree_open(&worktree, worktree_path);
3520 if (error) {
3521 if (error->code == GOT_ERR_NOT_WORKTREE)
3522 error = wrap_not_worktree_error(error, "update",
3523 worktree_path);
3524 goto done;
3527 error = check_rebase_or_histedit_in_progress(worktree);
3528 if (error)
3529 goto done;
3531 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3532 NULL, pack_fds);
3533 if (error != NULL)
3534 goto done;
3536 error = apply_unveil(got_repo_get_path(repo), 0,
3537 got_worktree_get_root_path(worktree));
3538 if (error)
3539 goto done;
3541 error = check_merge_in_progress(worktree, repo);
3542 if (error)
3543 goto done;
3545 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3546 if (error)
3547 goto done;
3549 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3550 got_worktree_get_head_ref_name(worktree), 0);
3551 if (error != NULL)
3552 goto done;
3553 if (commit_id_str == NULL) {
3554 error = got_ref_resolve(&commit_id, repo, head_ref);
3555 if (error != NULL)
3556 goto done;
3557 error = got_object_id_str(&commit_id_str, commit_id);
3558 if (error != NULL)
3559 goto done;
3560 } else {
3561 struct got_reflist_head refs;
3562 TAILQ_INIT(&refs);
3563 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3564 NULL);
3565 if (error)
3566 goto done;
3567 error = got_repo_match_object_id(&commit_id, NULL,
3568 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3569 got_ref_list_free(&refs);
3570 free(commit_id_str);
3571 commit_id_str = NULL;
3572 if (error)
3573 goto done;
3574 error = got_object_id_str(&commit_id_str, commit_id);
3575 if (error)
3576 goto done;
3579 if (branch_name) {
3580 struct got_object_id *head_commit_id;
3581 TAILQ_FOREACH(pe, &paths, entry) {
3582 if (pe->path_len == 0)
3583 continue;
3584 error = got_error_msg(GOT_ERR_BAD_PATH,
3585 "switching between branches requires that "
3586 "the entire work tree gets updated");
3587 goto done;
3589 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3590 if (error)
3591 goto done;
3592 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3593 repo);
3594 free(head_commit_id);
3595 if (error != NULL)
3596 goto done;
3597 error = check_same_branch(commit_id, head_ref, NULL, repo);
3598 if (error)
3599 goto done;
3600 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3601 if (error)
3602 goto done;
3603 } else {
3604 error = check_linear_ancestry(commit_id,
3605 got_worktree_get_base_commit_id(worktree), 0, repo);
3606 if (error != NULL) {
3607 if (error->code == GOT_ERR_ANCESTRY)
3608 error = got_error(GOT_ERR_BRANCH_MOVED);
3609 goto done;
3611 error = check_same_branch(commit_id, head_ref, NULL, repo);
3612 if (error)
3613 goto done;
3616 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3617 commit_id) != 0) {
3618 error = got_worktree_set_base_commit_id(worktree, repo,
3619 commit_id);
3620 if (error)
3621 goto done;
3624 memset(&upa, 0, sizeof(upa));
3625 upa.verbosity = verbosity;
3626 error = got_worktree_checkout_files(worktree, &paths, repo,
3627 update_progress, &upa, check_cancelled, NULL);
3628 if (error != NULL)
3629 goto done;
3631 if (upa.did_something) {
3632 printf("Updated to %s: %s\n",
3633 got_worktree_get_head_ref_name(worktree), commit_id_str);
3634 } else
3635 printf("Already up-to-date\n");
3637 print_update_progress_stats(&upa);
3638 done:
3639 if (pack_fds) {
3640 const struct got_error *pack_err =
3641 got_repo_pack_fds_close(pack_fds);
3642 if (error == NULL)
3643 error = pack_err;
3645 free(worktree_path);
3646 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3647 free(commit_id);
3648 free(commit_id_str);
3649 return error;
3652 static const struct got_error *
3653 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3654 const char *path, int diff_context, int ignore_whitespace,
3655 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3656 struct got_repository *repo, FILE *outfile)
3658 const struct got_error *err = NULL;
3659 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3660 FILE *f1 = NULL, *f2 = NULL;
3661 int fd1 = -1, fd2 = -1;
3663 fd1 = got_opentempfd();
3664 if (fd1 == -1)
3665 return got_error_from_errno("got_opentempfd");
3666 fd2 = got_opentempfd();
3667 if (fd2 == -1) {
3668 err = got_error_from_errno("got_opentempfd");
3669 goto done;
3672 if (blob_id1) {
3673 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3674 fd1);
3675 if (err)
3676 goto done;
3679 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3680 if (err)
3681 goto done;
3683 f1 = got_opentemp();
3684 if (f1 == NULL) {
3685 err = got_error_from_errno("got_opentemp");
3686 goto done;
3688 f2 = got_opentemp();
3689 if (f2 == NULL) {
3690 err = got_error_from_errno("got_opentemp");
3691 goto done;
3694 while (path[0] == '/')
3695 path++;
3696 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3697 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3698 force_text_diff, dsa, outfile);
3699 done:
3700 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3701 err = got_error_from_errno("close");
3702 if (blob1)
3703 got_object_blob_close(blob1);
3704 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3705 err = got_error_from_errno("close");
3706 got_object_blob_close(blob2);
3707 if (f1 && fclose(f1) == EOF && err == NULL)
3708 err = got_error_from_errno("fclose");
3709 if (f2 && fclose(f2) == EOF && err == NULL)
3710 err = got_error_from_errno("fclose");
3711 return err;
3714 static const struct got_error *
3715 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3716 const char *path, int diff_context, int ignore_whitespace,
3717 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3718 struct got_repository *repo, FILE *outfile)
3720 const struct got_error *err = NULL;
3721 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3722 struct got_diff_blob_output_unidiff_arg arg;
3723 FILE *f1 = NULL, *f2 = NULL;
3724 int fd1 = -1, fd2 = -1;
3726 if (tree_id1) {
3727 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3728 if (err)
3729 goto done;
3730 fd1 = got_opentempfd();
3731 if (fd1 == -1) {
3732 err = got_error_from_errno("got_opentempfd");
3733 goto done;
3737 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3738 if (err)
3739 goto done;
3741 f1 = got_opentemp();
3742 if (f1 == NULL) {
3743 err = got_error_from_errno("got_opentemp");
3744 goto done;
3747 f2 = got_opentemp();
3748 if (f2 == NULL) {
3749 err = got_error_from_errno("got_opentemp");
3750 goto done;
3752 fd2 = got_opentempfd();
3753 if (fd2 == -1) {
3754 err = got_error_from_errno("got_opentempfd");
3755 goto done;
3757 arg.diff_context = diff_context;
3758 arg.ignore_whitespace = ignore_whitespace;
3759 arg.force_text_diff = force_text_diff;
3760 arg.diffstat = dsa;
3761 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3762 arg.outfile = outfile;
3763 arg.lines = NULL;
3764 arg.nlines = 0;
3765 while (path[0] == '/')
3766 path++;
3767 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3768 got_diff_blob_output_unidiff, &arg, 1);
3769 done:
3770 if (tree1)
3771 got_object_tree_close(tree1);
3772 if (tree2)
3773 got_object_tree_close(tree2);
3774 if (f1 && fclose(f1) == EOF && err == NULL)
3775 err = got_error_from_errno("fclose");
3776 if (f2 && fclose(f2) == EOF && err == NULL)
3777 err = got_error_from_errno("fclose");
3778 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3779 err = got_error_from_errno("close");
3780 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3781 err = got_error_from_errno("close");
3782 return err;
3785 static const struct got_error *
3786 get_changed_paths(struct got_pathlist_head *paths,
3787 struct got_commit_object *commit, struct got_repository *repo,
3788 struct got_diffstat_cb_arg *dsa)
3790 const struct got_error *err = NULL;
3791 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3792 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3793 struct got_object_qid *qid;
3794 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3795 FILE *f1 = NULL, *f2 = NULL;
3796 int fd1 = -1, fd2 = -1;
3798 if (dsa) {
3799 cb = got_diff_tree_compute_diffstat;
3801 f1 = got_opentemp();
3802 if (f1 == NULL) {
3803 err = got_error_from_errno("got_opentemp");
3804 goto done;
3806 f2 = got_opentemp();
3807 if (f2 == NULL) {
3808 err = got_error_from_errno("got_opentemp");
3809 goto done;
3811 fd1 = got_opentempfd();
3812 if (fd1 == -1) {
3813 err = got_error_from_errno("got_opentempfd");
3814 goto done;
3816 fd2 = got_opentempfd();
3817 if (fd2 == -1) {
3818 err = got_error_from_errno("got_opentempfd");
3819 goto done;
3823 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3824 if (qid != NULL) {
3825 struct got_commit_object *pcommit;
3826 err = got_object_open_as_commit(&pcommit, repo,
3827 &qid->id);
3828 if (err)
3829 return err;
3831 tree_id1 = got_object_id_dup(
3832 got_object_commit_get_tree_id(pcommit));
3833 if (tree_id1 == NULL) {
3834 got_object_commit_close(pcommit);
3835 return got_error_from_errno("got_object_id_dup");
3837 got_object_commit_close(pcommit);
3841 if (tree_id1) {
3842 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3843 if (err)
3844 goto done;
3847 tree_id2 = got_object_commit_get_tree_id(commit);
3848 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3849 if (err)
3850 goto done;
3852 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3853 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3854 done:
3855 if (tree1)
3856 got_object_tree_close(tree1);
3857 if (tree2)
3858 got_object_tree_close(tree2);
3859 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3860 err = got_error_from_errno("close");
3861 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3862 err = got_error_from_errno("close");
3863 if (f1 && fclose(f1) == EOF && err == NULL)
3864 err = got_error_from_errno("fclose");
3865 if (f2 && fclose(f2) == EOF && err == NULL)
3866 err = got_error_from_errno("fclose");
3867 free(tree_id1);
3868 return err;
3871 static const struct got_error *
3872 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3873 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3874 struct got_repository *repo, FILE *outfile)
3876 const struct got_error *err = NULL;
3877 struct got_commit_object *pcommit = NULL;
3878 char *id_str1 = NULL, *id_str2 = NULL;
3879 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3880 struct got_object_qid *qid;
3882 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3883 if (qid != NULL) {
3884 err = got_object_open_as_commit(&pcommit, repo,
3885 &qid->id);
3886 if (err)
3887 return err;
3888 err = got_object_id_str(&id_str1, &qid->id);
3889 if (err)
3890 goto done;
3893 err = got_object_id_str(&id_str2, id);
3894 if (err)
3895 goto done;
3897 if (path && path[0] != '\0') {
3898 int obj_type;
3899 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3900 if (err)
3901 goto done;
3902 if (pcommit) {
3903 err = got_object_id_by_path(&obj_id1, repo,
3904 pcommit, path);
3905 if (err) {
3906 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3907 free(obj_id2);
3908 goto done;
3912 err = got_object_get_type(&obj_type, repo, obj_id2);
3913 if (err) {
3914 free(obj_id2);
3915 goto done;
3917 fprintf(outfile,
3918 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3919 fprintf(outfile, "commit - %s\n",
3920 id_str1 ? id_str1 : "/dev/null");
3921 fprintf(outfile, "commit + %s\n", id_str2);
3922 switch (obj_type) {
3923 case GOT_OBJ_TYPE_BLOB:
3924 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3925 0, 0, dsa, repo, outfile);
3926 break;
3927 case GOT_OBJ_TYPE_TREE:
3928 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3929 0, 0, dsa, repo, outfile);
3930 break;
3931 default:
3932 err = got_error(GOT_ERR_OBJ_TYPE);
3933 break;
3935 free(obj_id1);
3936 free(obj_id2);
3937 } else {
3938 obj_id2 = got_object_commit_get_tree_id(commit);
3939 if (pcommit)
3940 obj_id1 = got_object_commit_get_tree_id(pcommit);
3941 fprintf(outfile,
3942 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3943 fprintf(outfile, "commit - %s\n",
3944 id_str1 ? id_str1 : "/dev/null");
3945 fprintf(outfile, "commit + %s\n", id_str2);
3946 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3947 dsa, repo, outfile);
3949 done:
3950 free(id_str1);
3951 free(id_str2);
3952 if (pcommit)
3953 got_object_commit_close(pcommit);
3954 return err;
3957 static char *
3958 get_datestr(time_t *time, char *datebuf)
3960 struct tm mytm, *tm;
3961 char *p, *s;
3963 tm = gmtime_r(time, &mytm);
3964 if (tm == NULL)
3965 return NULL;
3966 s = asctime_r(tm, datebuf);
3967 if (s == NULL)
3968 return NULL;
3969 p = strchr(s, '\n');
3970 if (p)
3971 *p = '\0';
3972 return s;
3975 static const struct got_error *
3976 match_commit(int *have_match, struct got_object_id *id,
3977 struct got_commit_object *commit, regex_t *regex)
3979 const struct got_error *err = NULL;
3980 regmatch_t regmatch;
3981 char *id_str = NULL, *logmsg = NULL;
3983 *have_match = 0;
3985 err = got_object_id_str(&id_str, id);
3986 if (err)
3987 return err;
3989 err = got_object_commit_get_logmsg(&logmsg, commit);
3990 if (err)
3991 goto done;
3993 if (regexec(regex, got_object_commit_get_author(commit), 1,
3994 &regmatch, 0) == 0 ||
3995 regexec(regex, got_object_commit_get_committer(commit), 1,
3996 &regmatch, 0) == 0 ||
3997 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3998 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3999 *have_match = 1;
4000 done:
4001 free(id_str);
4002 free(logmsg);
4003 return err;
4006 static void
4007 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4008 regex_t *regex)
4010 regmatch_t regmatch;
4011 struct got_pathlist_entry *pe;
4013 *have_match = 0;
4015 TAILQ_FOREACH(pe, changed_paths, entry) {
4016 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4017 *have_match = 1;
4018 break;
4023 static const struct got_error *
4024 match_patch(int *have_match, struct got_commit_object *commit,
4025 struct got_object_id *id, const char *path, int diff_context,
4026 struct got_repository *repo, regex_t *regex, FILE *f)
4028 const struct got_error *err = NULL;
4029 char *line = NULL;
4030 size_t linesize = 0;
4031 regmatch_t regmatch;
4033 *have_match = 0;
4035 err = got_opentemp_truncate(f);
4036 if (err)
4037 return err;
4039 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4040 if (err)
4041 goto done;
4043 if (fseeko(f, 0L, SEEK_SET) == -1) {
4044 err = got_error_from_errno("fseeko");
4045 goto done;
4048 while (getline(&line, &linesize, f) != -1) {
4049 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4050 *have_match = 1;
4051 break;
4054 done:
4055 free(line);
4056 return err;
4059 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4061 static const struct got_error*
4062 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4063 struct got_object_id *id, struct got_repository *repo,
4064 int local_only)
4066 static const struct got_error *err = NULL;
4067 struct got_reflist_entry *re;
4068 char *s;
4069 const char *name;
4071 *refs_str = NULL;
4073 TAILQ_FOREACH(re, refs, entry) {
4074 struct got_tag_object *tag = NULL;
4075 struct got_object_id *ref_id;
4076 int cmp;
4078 name = got_ref_get_name(re->ref);
4079 if (strcmp(name, GOT_REF_HEAD) == 0)
4080 continue;
4081 if (strncmp(name, "refs/", 5) == 0)
4082 name += 5;
4083 if (strncmp(name, "got/", 4) == 0)
4084 continue;
4085 if (strncmp(name, "heads/", 6) == 0)
4086 name += 6;
4087 if (strncmp(name, "remotes/", 8) == 0) {
4088 if (local_only)
4089 continue;
4090 name += 8;
4091 s = strstr(name, "/" GOT_REF_HEAD);
4092 if (s != NULL && s[strlen(s)] == '\0')
4093 continue;
4095 err = got_ref_resolve(&ref_id, repo, re->ref);
4096 if (err)
4097 break;
4098 if (strncmp(name, "tags/", 5) == 0) {
4099 err = got_object_open_as_tag(&tag, repo, ref_id);
4100 if (err) {
4101 if (err->code != GOT_ERR_OBJ_TYPE) {
4102 free(ref_id);
4103 break;
4105 /* Ref points at something other than a tag. */
4106 err = NULL;
4107 tag = NULL;
4110 cmp = got_object_id_cmp(tag ?
4111 got_object_tag_get_object_id(tag) : ref_id, id);
4112 free(ref_id);
4113 if (tag)
4114 got_object_tag_close(tag);
4115 if (cmp != 0)
4116 continue;
4117 s = *refs_str;
4118 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4119 s ? ", " : "", name) == -1) {
4120 err = got_error_from_errno("asprintf");
4121 free(s);
4122 *refs_str = NULL;
4123 break;
4125 free(s);
4128 return err;
4131 static const struct got_error *
4132 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4133 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4135 const struct got_error *err = NULL;
4136 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4137 char *comma, *s, *nl;
4138 struct got_reflist_head *refs;
4139 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4140 struct tm tm;
4141 time_t committer_time;
4143 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4144 if (refs) {
4145 err = build_refs_str(&ref_str, refs, id, repo, 1);
4146 if (err)
4147 return err;
4149 /* Display the first matching ref only. */
4150 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4151 *comma = '\0';
4154 if (ref_str == NULL) {
4155 err = got_object_id_str(&id_str, id);
4156 if (err)
4157 return err;
4160 committer_time = got_object_commit_get_committer_time(commit);
4161 if (gmtime_r(&committer_time, &tm) == NULL) {
4162 err = got_error_from_errno("gmtime_r");
4163 goto done;
4165 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4166 err = got_error(GOT_ERR_NO_SPACE);
4167 goto done;
4170 err = got_object_commit_get_logmsg(&logmsg0, commit);
4171 if (err)
4172 goto done;
4174 s = logmsg0;
4175 while (isspace((unsigned char)s[0]))
4176 s++;
4178 nl = strchr(s, '\n');
4179 if (nl) {
4180 *nl = '\0';
4183 if (ref_str)
4184 printf("%s%-7s %s\n", datebuf, ref_str, s);
4185 else
4186 printf("%s%.7s %s\n", datebuf, id_str, s);
4188 if (fflush(stdout) != 0 && err == NULL)
4189 err = got_error_from_errno("fflush");
4190 done:
4191 free(id_str);
4192 free(ref_str);
4193 free(logmsg0);
4194 return err;
4197 static const struct got_error *
4198 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4200 struct got_pathlist_entry *pe;
4202 if (header != NULL)
4203 printf("%s\n", header);
4205 TAILQ_FOREACH(pe, dsa->paths, entry) {
4206 struct got_diff_changed_path *cp = pe->data;
4207 int pad = dsa->max_path_len - pe->path_len + 1;
4209 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4210 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4212 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4213 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4214 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4216 if (fflush(stdout) != 0)
4217 return got_error_from_errno("fflush");
4219 return NULL;
4222 static const struct got_error *
4223 printfile(FILE *f)
4225 char buf[8192];
4226 size_t r;
4228 if (fseeko(f, 0L, SEEK_SET) == -1)
4229 return got_error_from_errno("fseek");
4231 for (;;) {
4232 r = fread(buf, 1, sizeof(buf), f);
4233 if (r == 0) {
4234 if (ferror(f))
4235 return got_error_from_errno("fread");
4236 if (feof(f))
4237 break;
4239 if (fwrite(buf, 1, r, stdout) != r)
4240 return got_ferror(stdout, GOT_ERR_IO);
4243 return NULL;
4246 static const struct got_error *
4247 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4248 struct got_repository *repo, const char *path,
4249 struct got_pathlist_head *changed_paths,
4250 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4251 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4252 const char *prefix)
4254 const struct got_error *err = NULL;
4255 FILE *f = NULL;
4256 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4257 char datebuf[26];
4258 time_t committer_time;
4259 const char *author, *committer;
4260 char *refs_str = NULL;
4262 err = got_object_id_str(&id_str, id);
4263 if (err)
4264 return err;
4266 if (custom_refs_str == NULL) {
4267 struct got_reflist_head *refs;
4268 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4269 if (refs) {
4270 err = build_refs_str(&refs_str, refs, id, repo, 0);
4271 if (err)
4272 goto done;
4276 printf(GOT_COMMIT_SEP_STR);
4277 if (custom_refs_str)
4278 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4279 custom_refs_str);
4280 else
4281 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4282 refs_str ? " (" : "", refs_str ? refs_str : "",
4283 refs_str ? ")" : "");
4284 free(id_str);
4285 id_str = NULL;
4286 free(refs_str);
4287 refs_str = NULL;
4288 printf("from: %s\n", got_object_commit_get_author(commit));
4289 author = got_object_commit_get_author(commit);
4290 committer = got_object_commit_get_committer(commit);
4291 if (strcmp(author, committer) != 0)
4292 printf("via: %s\n", committer);
4293 committer_time = got_object_commit_get_committer_time(commit);
4294 datestr = get_datestr(&committer_time, datebuf);
4295 if (datestr)
4296 printf("date: %s UTC\n", datestr);
4297 if (got_object_commit_get_nparents(commit) > 1) {
4298 const struct got_object_id_queue *parent_ids;
4299 struct got_object_qid *qid;
4300 int n = 1;
4301 parent_ids = got_object_commit_get_parent_ids(commit);
4302 STAILQ_FOREACH(qid, parent_ids, entry) {
4303 err = got_object_id_str(&id_str, &qid->id);
4304 if (err)
4305 goto done;
4306 printf("parent %d: %s\n", n++, id_str);
4307 free(id_str);
4308 id_str = NULL;
4312 err = got_object_commit_get_logmsg(&logmsg0, commit);
4313 if (err)
4314 goto done;
4316 logmsg = logmsg0;
4317 do {
4318 line = strsep(&logmsg, "\n");
4319 if (line)
4320 printf(" %s\n", line);
4321 } while (line);
4322 free(logmsg0);
4324 if (changed_paths && diffstat == NULL) {
4325 struct got_pathlist_entry *pe;
4327 TAILQ_FOREACH(pe, changed_paths, entry) {
4328 struct got_diff_changed_path *cp = pe->data;
4330 printf(" %c %s\n", cp->status, pe->path);
4332 printf("\n");
4334 if (show_patch) {
4335 if (diffstat) {
4336 f = got_opentemp();
4337 if (f == NULL) {
4338 err = got_error_from_errno("got_opentemp");
4339 goto done;
4343 err = print_patch(commit, id, path, diff_context, diffstat,
4344 repo, diffstat == NULL ? stdout : f);
4345 if (err)
4346 goto done;
4348 if (diffstat) {
4349 err = print_diffstat(diffstat, NULL);
4350 if (err)
4351 goto done;
4352 if (show_patch) {
4353 err = printfile(f);
4354 if (err)
4355 goto done;
4358 if (show_patch)
4359 printf("\n");
4361 if (fflush(stdout) != 0 && err == NULL)
4362 err = got_error_from_errno("fflush");
4363 done:
4364 if (f && fclose(f) == EOF && err == NULL)
4365 err = got_error_from_errno("fclose");
4366 free(id_str);
4367 free(refs_str);
4368 return err;
4371 static const struct got_error *
4372 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4373 struct got_repository *repo, const char *path, int show_changed_paths,
4374 int show_diffstat, int show_patch, const char *search_pattern,
4375 int diff_context, int limit, int log_branches, int reverse_display_order,
4376 struct got_reflist_object_id_map *refs_idmap, int one_line,
4377 FILE *tmpfile)
4379 const struct got_error *err;
4380 struct got_commit_graph *graph;
4381 regex_t regex;
4382 int have_match;
4383 struct got_object_id_queue reversed_commits;
4384 struct got_object_qid *qid;
4385 struct got_commit_object *commit;
4386 struct got_pathlist_head changed_paths;
4388 STAILQ_INIT(&reversed_commits);
4389 TAILQ_INIT(&changed_paths);
4391 if (search_pattern && regcomp(&regex, search_pattern,
4392 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4393 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4395 err = got_commit_graph_open(&graph, path, !log_branches);
4396 if (err)
4397 return err;
4398 err = got_commit_graph_iter_start(graph, root_id, repo,
4399 check_cancelled, NULL);
4400 if (err)
4401 goto done;
4402 for (;;) {
4403 struct got_object_id id;
4404 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4405 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4407 if (sigint_received || sigpipe_received)
4408 break;
4410 err = got_commit_graph_iter_next(&id, graph, repo,
4411 check_cancelled, NULL);
4412 if (err) {
4413 if (err->code == GOT_ERR_ITER_COMPLETED)
4414 err = NULL;
4415 break;
4418 err = got_object_open_as_commit(&commit, repo, &id);
4419 if (err)
4420 break;
4422 if ((show_changed_paths || (show_diffstat && !show_patch))
4423 && !reverse_display_order) {
4424 err = get_changed_paths(&changed_paths, commit, repo,
4425 show_diffstat ? &dsa : NULL);
4426 if (err)
4427 break;
4430 if (search_pattern) {
4431 err = match_commit(&have_match, &id, commit, &regex);
4432 if (err) {
4433 got_object_commit_close(commit);
4434 break;
4436 if (have_match == 0 && show_changed_paths)
4437 match_changed_paths(&have_match,
4438 &changed_paths, &regex);
4439 if (have_match == 0 && show_patch) {
4440 err = match_patch(&have_match, commit, &id,
4441 path, diff_context, repo, &regex, tmpfile);
4442 if (err)
4443 break;
4445 if (have_match == 0) {
4446 got_object_commit_close(commit);
4447 got_pathlist_free(&changed_paths,
4448 GOT_PATHLIST_FREE_ALL);
4449 continue;
4453 if (reverse_display_order) {
4454 err = got_object_qid_alloc(&qid, &id);
4455 if (err)
4456 break;
4457 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4458 got_object_commit_close(commit);
4459 } else {
4460 if (one_line)
4461 err = print_commit_oneline(commit, &id,
4462 repo, refs_idmap);
4463 else
4464 err = print_commit(commit, &id, repo, path,
4465 (show_changed_paths || show_diffstat) ?
4466 &changed_paths : NULL,
4467 show_diffstat ? &dsa : NULL, show_patch,
4468 diff_context, refs_idmap, NULL, NULL);
4469 got_object_commit_close(commit);
4470 if (err)
4471 break;
4473 if ((limit && --limit == 0) ||
4474 (end_id && got_object_id_cmp(&id, end_id) == 0))
4475 break;
4477 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4479 if (reverse_display_order) {
4480 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4481 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4482 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4484 err = got_object_open_as_commit(&commit, repo,
4485 &qid->id);
4486 if (err)
4487 break;
4488 if (show_changed_paths ||
4489 (show_diffstat && !show_patch)) {
4490 err = get_changed_paths(&changed_paths, commit,
4491 repo, show_diffstat ? &dsa : NULL);
4492 if (err)
4493 break;
4495 if (one_line)
4496 err = print_commit_oneline(commit, &qid->id,
4497 repo, refs_idmap);
4498 else
4499 err = print_commit(commit, &qid->id, repo, path,
4500 (show_changed_paths || show_diffstat) ?
4501 &changed_paths : NULL,
4502 show_diffstat ? &dsa : NULL, show_patch,
4503 diff_context, refs_idmap, NULL, NULL);
4504 got_object_commit_close(commit);
4505 if (err)
4506 break;
4507 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4510 done:
4511 while (!STAILQ_EMPTY(&reversed_commits)) {
4512 qid = STAILQ_FIRST(&reversed_commits);
4513 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4514 got_object_qid_free(qid);
4516 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4517 if (search_pattern)
4518 regfree(&regex);
4519 got_commit_graph_close(graph);
4520 return err;
4523 __dead static void
4524 usage_log(void)
4526 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4527 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4528 "[path]\n", getprogname());
4529 exit(1);
4532 static int
4533 get_default_log_limit(void)
4535 const char *got_default_log_limit;
4536 long long n;
4537 const char *errstr;
4539 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4540 if (got_default_log_limit == NULL)
4541 return 0;
4542 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4543 if (errstr != NULL)
4544 return 0;
4545 return n;
4548 static const struct got_error *
4549 cmd_log(int argc, char *argv[])
4551 const struct got_error *error;
4552 struct got_repository *repo = NULL;
4553 struct got_worktree *worktree = NULL;
4554 struct got_object_id *start_id = NULL, *end_id = NULL;
4555 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4556 const char *start_commit = NULL, *end_commit = NULL;
4557 const char *search_pattern = NULL;
4558 int diff_context = -1, ch;
4559 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4560 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4561 const char *errstr;
4562 struct got_reflist_head refs;
4563 struct got_reflist_object_id_map *refs_idmap = NULL;
4564 FILE *tmpfile = NULL;
4565 int *pack_fds = NULL;
4567 TAILQ_INIT(&refs);
4569 #ifndef PROFILE
4570 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4571 NULL)
4572 == -1)
4573 err(1, "pledge");
4574 #endif
4576 limit = get_default_log_limit();
4578 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4579 switch (ch) {
4580 case 'b':
4581 log_branches = 1;
4582 break;
4583 case 'C':
4584 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4585 &errstr);
4586 if (errstr != NULL)
4587 errx(1, "number of context lines is %s: %s",
4588 errstr, optarg);
4589 break;
4590 case 'c':
4591 start_commit = optarg;
4592 break;
4593 case 'd':
4594 show_diffstat = 1;
4595 break;
4596 case 'l':
4597 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4598 if (errstr != NULL)
4599 errx(1, "number of commits is %s: %s",
4600 errstr, optarg);
4601 break;
4602 case 'P':
4603 show_changed_paths = 1;
4604 break;
4605 case 'p':
4606 show_patch = 1;
4607 break;
4608 case 'R':
4609 reverse_display_order = 1;
4610 break;
4611 case 'r':
4612 repo_path = realpath(optarg, NULL);
4613 if (repo_path == NULL)
4614 return got_error_from_errno2("realpath",
4615 optarg);
4616 got_path_strip_trailing_slashes(repo_path);
4617 break;
4618 case 'S':
4619 search_pattern = optarg;
4620 break;
4621 case 's':
4622 one_line = 1;
4623 break;
4624 case 'x':
4625 end_commit = optarg;
4626 break;
4627 default:
4628 usage_log();
4629 /* NOTREACHED */
4633 argc -= optind;
4634 argv += optind;
4636 if (diff_context == -1)
4637 diff_context = 3;
4638 else if (!show_patch)
4639 errx(1, "-C requires -p");
4641 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4642 errx(1, "cannot use -s with -d, -p or -P");
4644 cwd = getcwd(NULL, 0);
4645 if (cwd == NULL) {
4646 error = got_error_from_errno("getcwd");
4647 goto done;
4650 error = got_repo_pack_fds_open(&pack_fds);
4651 if (error != NULL)
4652 goto done;
4654 if (repo_path == NULL) {
4655 error = got_worktree_open(&worktree, cwd);
4656 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4657 goto done;
4658 error = NULL;
4661 if (argc == 1) {
4662 if (worktree) {
4663 error = got_worktree_resolve_path(&path, worktree,
4664 argv[0]);
4665 if (error)
4666 goto done;
4667 } else {
4668 path = strdup(argv[0]);
4669 if (path == NULL) {
4670 error = got_error_from_errno("strdup");
4671 goto done;
4674 } else if (argc != 0)
4675 usage_log();
4677 if (repo_path == NULL) {
4678 repo_path = worktree ?
4679 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4681 if (repo_path == NULL) {
4682 error = got_error_from_errno("strdup");
4683 goto done;
4686 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4687 if (error != NULL)
4688 goto done;
4690 error = apply_unveil(got_repo_get_path(repo), 1,
4691 worktree ? got_worktree_get_root_path(worktree) : NULL);
4692 if (error)
4693 goto done;
4695 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4696 if (error)
4697 goto done;
4699 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4700 if (error)
4701 goto done;
4703 if (start_commit == NULL) {
4704 struct got_reference *head_ref;
4705 struct got_commit_object *commit = NULL;
4706 error = got_ref_open(&head_ref, repo,
4707 worktree ? got_worktree_get_head_ref_name(worktree)
4708 : GOT_REF_HEAD, 0);
4709 if (error != NULL)
4710 goto done;
4711 error = got_ref_resolve(&start_id, repo, head_ref);
4712 got_ref_close(head_ref);
4713 if (error != NULL)
4714 goto done;
4715 error = got_object_open_as_commit(&commit, repo,
4716 start_id);
4717 if (error != NULL)
4718 goto done;
4719 got_object_commit_close(commit);
4720 } else {
4721 error = got_repo_match_object_id(&start_id, NULL,
4722 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4723 if (error != NULL)
4724 goto done;
4726 if (end_commit != NULL) {
4727 error = got_repo_match_object_id(&end_id, NULL,
4728 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4729 if (error != NULL)
4730 goto done;
4733 if (worktree) {
4735 * If a path was specified on the command line it was resolved
4736 * to a path in the work tree above. Prepend the work tree's
4737 * path prefix to obtain the corresponding in-repository path.
4739 if (path) {
4740 const char *prefix;
4741 prefix = got_worktree_get_path_prefix(worktree);
4742 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4743 (path[0] != '\0') ? "/" : "", path) == -1) {
4744 error = got_error_from_errno("asprintf");
4745 goto done;
4748 } else
4749 error = got_repo_map_path(&in_repo_path, repo,
4750 path ? path : "");
4751 if (error != NULL)
4752 goto done;
4753 if (in_repo_path) {
4754 free(path);
4755 path = in_repo_path;
4758 if (worktree) {
4759 /* Release work tree lock. */
4760 got_worktree_close(worktree);
4761 worktree = NULL;
4764 if (search_pattern && show_patch) {
4765 tmpfile = got_opentemp();
4766 if (tmpfile == NULL) {
4767 error = got_error_from_errno("got_opentemp");
4768 goto done;
4772 error = print_commits(start_id, end_id, repo, path ? path : "",
4773 show_changed_paths, show_diffstat, show_patch, search_pattern,
4774 diff_context, limit, log_branches, reverse_display_order,
4775 refs_idmap, one_line, tmpfile);
4776 done:
4777 free(path);
4778 free(repo_path);
4779 free(cwd);
4780 if (worktree)
4781 got_worktree_close(worktree);
4782 if (repo) {
4783 const struct got_error *close_err = got_repo_close(repo);
4784 if (error == NULL)
4785 error = close_err;
4787 if (pack_fds) {
4788 const struct got_error *pack_err =
4789 got_repo_pack_fds_close(pack_fds);
4790 if (error == NULL)
4791 error = pack_err;
4793 if (refs_idmap)
4794 got_reflist_object_id_map_free(refs_idmap);
4795 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4796 error = got_error_from_errno("fclose");
4797 got_ref_list_free(&refs);
4798 return error;
4801 __dead static void
4802 usage_diff(void)
4804 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4805 "[-r repository-path] [object1 object2 | path ...]\n",
4806 getprogname());
4807 exit(1);
4810 struct print_diff_arg {
4811 struct got_repository *repo;
4812 struct got_worktree *worktree;
4813 struct got_diffstat_cb_arg *diffstat;
4814 int diff_context;
4815 const char *id_str;
4816 int header_shown;
4817 int diff_staged;
4818 enum got_diff_algorithm diff_algo;
4819 int ignore_whitespace;
4820 int force_text_diff;
4821 FILE *f1;
4822 FILE *f2;
4823 FILE *outfile;
4827 * Create a file which contains the target path of a symlink so we can feed
4828 * it as content to the diff engine.
4830 static const struct got_error *
4831 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4832 const char *abspath)
4834 const struct got_error *err = NULL;
4835 char target_path[PATH_MAX];
4836 ssize_t target_len, outlen;
4838 *fd = -1;
4840 if (dirfd != -1) {
4841 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4842 if (target_len == -1)
4843 return got_error_from_errno2("readlinkat", abspath);
4844 } else {
4845 target_len = readlink(abspath, target_path, PATH_MAX);
4846 if (target_len == -1)
4847 return got_error_from_errno2("readlink", abspath);
4850 *fd = got_opentempfd();
4851 if (*fd == -1)
4852 return got_error_from_errno("got_opentempfd");
4854 outlen = write(*fd, target_path, target_len);
4855 if (outlen == -1) {
4856 err = got_error_from_errno("got_opentempfd");
4857 goto done;
4860 if (lseek(*fd, 0, SEEK_SET) == -1) {
4861 err = got_error_from_errno2("lseek", abspath);
4862 goto done;
4864 done:
4865 if (err) {
4866 close(*fd);
4867 *fd = -1;
4869 return err;
4872 static const struct got_error *
4873 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4874 const char *path, struct got_object_id *blob_id,
4875 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4876 int dirfd, const char *de_name)
4878 struct print_diff_arg *a = arg;
4879 const struct got_error *err = NULL;
4880 struct got_blob_object *blob1 = NULL;
4881 int fd = -1, fd1 = -1, fd2 = -1;
4882 FILE *f2 = NULL;
4883 char *abspath = NULL, *label1 = NULL;
4884 struct stat sb;
4885 off_t size1 = 0;
4886 int f2_exists = 0;
4888 memset(&sb, 0, sizeof(sb));
4890 if (a->diff_staged) {
4891 if (staged_status != GOT_STATUS_MODIFY &&
4892 staged_status != GOT_STATUS_ADD &&
4893 staged_status != GOT_STATUS_DELETE)
4894 return NULL;
4895 } else {
4896 if (staged_status == GOT_STATUS_DELETE)
4897 return NULL;
4898 if (status == GOT_STATUS_NONEXISTENT)
4899 return got_error_set_errno(ENOENT, path);
4900 if (status != GOT_STATUS_MODIFY &&
4901 status != GOT_STATUS_ADD &&
4902 status != GOT_STATUS_DELETE &&
4903 status != GOT_STATUS_CONFLICT)
4904 return NULL;
4907 err = got_opentemp_truncate(a->f1);
4908 if (err)
4909 return got_error_from_errno("got_opentemp_truncate");
4910 err = got_opentemp_truncate(a->f2);
4911 if (err)
4912 return got_error_from_errno("got_opentemp_truncate");
4914 if (!a->header_shown) {
4915 if (fprintf(a->outfile, "diff %s%s\n",
4916 a->diff_staged ? "-s " : "",
4917 got_worktree_get_root_path(a->worktree)) < 0) {
4918 err = got_error_from_errno("fprintf");
4919 goto done;
4921 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4922 err = got_error_from_errno("fprintf");
4923 goto done;
4925 if (fprintf(a->outfile, "path + %s%s\n",
4926 got_worktree_get_root_path(a->worktree),
4927 a->diff_staged ? " (staged changes)" : "") < 0) {
4928 err = got_error_from_errno("fprintf");
4929 goto done;
4931 a->header_shown = 1;
4934 if (a->diff_staged) {
4935 const char *label1 = NULL, *label2 = NULL;
4936 switch (staged_status) {
4937 case GOT_STATUS_MODIFY:
4938 label1 = path;
4939 label2 = path;
4940 break;
4941 case GOT_STATUS_ADD:
4942 label2 = path;
4943 break;
4944 case GOT_STATUS_DELETE:
4945 label1 = path;
4946 break;
4947 default:
4948 return got_error(GOT_ERR_FILE_STATUS);
4950 fd1 = got_opentempfd();
4951 if (fd1 == -1) {
4952 err = got_error_from_errno("got_opentempfd");
4953 goto done;
4955 fd2 = got_opentempfd();
4956 if (fd2 == -1) {
4957 err = got_error_from_errno("got_opentempfd");
4958 goto done;
4960 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4961 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4962 a->diff_algo, a->diff_context, a->ignore_whitespace,
4963 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4964 goto done;
4967 fd1 = got_opentempfd();
4968 if (fd1 == -1) {
4969 err = got_error_from_errno("got_opentempfd");
4970 goto done;
4973 if (staged_status == GOT_STATUS_ADD ||
4974 staged_status == GOT_STATUS_MODIFY) {
4975 char *id_str;
4976 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4977 8192, fd1);
4978 if (err)
4979 goto done;
4980 err = got_object_id_str(&id_str, staged_blob_id);
4981 if (err)
4982 goto done;
4983 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4984 err = got_error_from_errno("asprintf");
4985 free(id_str);
4986 goto done;
4988 free(id_str);
4989 } else if (status != GOT_STATUS_ADD) {
4990 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4991 fd1);
4992 if (err)
4993 goto done;
4996 if (status != GOT_STATUS_DELETE) {
4997 if (asprintf(&abspath, "%s/%s",
4998 got_worktree_get_root_path(a->worktree), path) == -1) {
4999 err = got_error_from_errno("asprintf");
5000 goto done;
5003 if (dirfd != -1) {
5004 fd = openat(dirfd, de_name,
5005 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5006 if (fd == -1) {
5007 if (!got_err_open_nofollow_on_symlink()) {
5008 err = got_error_from_errno2("openat",
5009 abspath);
5010 goto done;
5012 err = get_symlink_target_file(&fd, dirfd,
5013 de_name, abspath);
5014 if (err)
5015 goto done;
5017 } else {
5018 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5019 if (fd == -1) {
5020 if (!got_err_open_nofollow_on_symlink()) {
5021 err = got_error_from_errno2("open",
5022 abspath);
5023 goto done;
5025 err = get_symlink_target_file(&fd, dirfd,
5026 de_name, abspath);
5027 if (err)
5028 goto done;
5031 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5032 err = got_error_from_errno2("fstatat", abspath);
5033 goto done;
5035 f2 = fdopen(fd, "r");
5036 if (f2 == NULL) {
5037 err = got_error_from_errno2("fdopen", abspath);
5038 goto done;
5040 fd = -1;
5041 f2_exists = 1;
5044 if (blob1) {
5045 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5046 a->f1, blob1);
5047 if (err)
5048 goto done;
5051 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5052 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5053 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5054 done:
5055 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5056 err = got_error_from_errno("close");
5057 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5058 err = got_error_from_errno("close");
5059 if (blob1)
5060 got_object_blob_close(blob1);
5061 if (fd != -1 && close(fd) == -1 && err == NULL)
5062 err = got_error_from_errno("close");
5063 if (f2 && fclose(f2) == EOF && err == NULL)
5064 err = got_error_from_errno("fclose");
5065 free(abspath);
5066 return err;
5069 static const struct got_error *
5070 cmd_diff(int argc, char *argv[])
5072 const struct got_error *error;
5073 struct got_repository *repo = NULL;
5074 struct got_worktree *worktree = NULL;
5075 char *cwd = NULL, *repo_path = NULL;
5076 const char *commit_args[2] = { NULL, NULL };
5077 int ncommit_args = 0;
5078 struct got_object_id *ids[2] = { NULL, NULL };
5079 char *labels[2] = { NULL, NULL };
5080 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5081 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5082 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5083 const char *errstr;
5084 struct got_reflist_head refs;
5085 struct got_pathlist_head diffstat_paths, paths;
5086 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5087 int fd1 = -1, fd2 = -1;
5088 int *pack_fds = NULL;
5089 struct got_diffstat_cb_arg dsa;
5091 memset(&dsa, 0, sizeof(dsa));
5093 TAILQ_INIT(&refs);
5094 TAILQ_INIT(&paths);
5095 TAILQ_INIT(&diffstat_paths);
5097 #ifndef PROFILE
5098 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5099 NULL) == -1)
5100 err(1, "pledge");
5101 #endif
5103 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5104 switch (ch) {
5105 case 'a':
5106 force_text_diff = 1;
5107 break;
5108 case 'C':
5109 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5110 &errstr);
5111 if (errstr != NULL)
5112 errx(1, "number of context lines is %s: %s",
5113 errstr, optarg);
5114 break;
5115 case 'c':
5116 if (ncommit_args >= 2)
5117 errx(1, "too many -c options used");
5118 commit_args[ncommit_args++] = optarg;
5119 break;
5120 case 'd':
5121 show_diffstat = 1;
5122 break;
5123 case 'P':
5124 force_path = 1;
5125 break;
5126 case 'r':
5127 repo_path = realpath(optarg, NULL);
5128 if (repo_path == NULL)
5129 return got_error_from_errno2("realpath",
5130 optarg);
5131 got_path_strip_trailing_slashes(repo_path);
5132 rflag = 1;
5133 break;
5134 case 's':
5135 diff_staged = 1;
5136 break;
5137 case 'w':
5138 ignore_whitespace = 1;
5139 break;
5140 default:
5141 usage_diff();
5142 /* NOTREACHED */
5146 argc -= optind;
5147 argv += optind;
5149 cwd = getcwd(NULL, 0);
5150 if (cwd == NULL) {
5151 error = got_error_from_errno("getcwd");
5152 goto done;
5155 error = got_repo_pack_fds_open(&pack_fds);
5156 if (error != NULL)
5157 goto done;
5159 if (repo_path == NULL) {
5160 error = got_worktree_open(&worktree, cwd);
5161 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5162 goto done;
5163 else
5164 error = NULL;
5165 if (worktree) {
5166 repo_path =
5167 strdup(got_worktree_get_repo_path(worktree));
5168 if (repo_path == NULL) {
5169 error = got_error_from_errno("strdup");
5170 goto done;
5172 } else {
5173 repo_path = strdup(cwd);
5174 if (repo_path == NULL) {
5175 error = got_error_from_errno("strdup");
5176 goto done;
5181 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5182 free(repo_path);
5183 if (error != NULL)
5184 goto done;
5186 if (show_diffstat) {
5187 dsa.paths = &diffstat_paths;
5188 dsa.force_text = force_text_diff;
5189 dsa.ignore_ws = ignore_whitespace;
5190 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5193 if (rflag || worktree == NULL || ncommit_args > 0) {
5194 if (force_path) {
5195 error = got_error_msg(GOT_ERR_NOT_IMPL,
5196 "-P option can only be used when diffing "
5197 "a work tree");
5198 goto done;
5200 if (diff_staged) {
5201 error = got_error_msg(GOT_ERR_NOT_IMPL,
5202 "-s option can only be used when diffing "
5203 "a work tree");
5204 goto done;
5208 error = apply_unveil(got_repo_get_path(repo), 1,
5209 worktree ? got_worktree_get_root_path(worktree) : NULL);
5210 if (error)
5211 goto done;
5213 if ((!force_path && argc == 2) || ncommit_args > 0) {
5214 int obj_type = (ncommit_args > 0 ?
5215 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5216 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5217 NULL);
5218 if (error)
5219 goto done;
5220 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5221 const char *arg;
5222 if (ncommit_args > 0)
5223 arg = commit_args[i];
5224 else
5225 arg = argv[i];
5226 error = got_repo_match_object_id(&ids[i], &labels[i],
5227 arg, obj_type, &refs, repo);
5228 if (error) {
5229 if (error->code != GOT_ERR_NOT_REF &&
5230 error->code != GOT_ERR_NO_OBJ)
5231 goto done;
5232 if (ncommit_args > 0)
5233 goto done;
5234 error = NULL;
5235 break;
5240 f1 = got_opentemp();
5241 if (f1 == NULL) {
5242 error = got_error_from_errno("got_opentemp");
5243 goto done;
5246 f2 = got_opentemp();
5247 if (f2 == NULL) {
5248 error = got_error_from_errno("got_opentemp");
5249 goto done;
5252 outfile = got_opentemp();
5253 if (outfile == NULL) {
5254 error = got_error_from_errno("got_opentemp");
5255 goto done;
5258 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5259 struct print_diff_arg arg;
5260 char *id_str;
5262 if (worktree == NULL) {
5263 if (argc == 2 && ids[0] == NULL) {
5264 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5265 goto done;
5266 } else if (argc == 2 && ids[1] == NULL) {
5267 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5268 goto done;
5269 } else if (argc > 0) {
5270 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5271 "%s", "specified paths cannot be resolved");
5272 goto done;
5273 } else {
5274 error = got_error(GOT_ERR_NOT_WORKTREE);
5275 goto done;
5279 error = get_worktree_paths_from_argv(&paths, argc, argv,
5280 worktree);
5281 if (error)
5282 goto done;
5284 error = got_object_id_str(&id_str,
5285 got_worktree_get_base_commit_id(worktree));
5286 if (error)
5287 goto done;
5288 arg.repo = repo;
5289 arg.worktree = worktree;
5290 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5291 arg.diff_context = diff_context;
5292 arg.id_str = id_str;
5293 arg.header_shown = 0;
5294 arg.diff_staged = diff_staged;
5295 arg.ignore_whitespace = ignore_whitespace;
5296 arg.force_text_diff = force_text_diff;
5297 arg.diffstat = show_diffstat ? &dsa : NULL;
5298 arg.f1 = f1;
5299 arg.f2 = f2;
5300 arg.outfile = outfile;
5302 error = got_worktree_status(worktree, &paths, repo, 0,
5303 print_diff, &arg, check_cancelled, NULL);
5304 free(id_str);
5305 if (error)
5306 goto done;
5308 if (show_diffstat && dsa.nfiles > 0) {
5309 char *header;
5311 if (asprintf(&header, "diffstat %s%s",
5312 diff_staged ? "-s " : "",
5313 got_worktree_get_root_path(worktree)) == -1) {
5314 error = got_error_from_errno("asprintf");
5315 goto done;
5318 error = print_diffstat(&dsa, header);
5319 free(header);
5320 if (error)
5321 goto done;
5324 error = printfile(outfile);
5325 goto done;
5328 if (ncommit_args == 1) {
5329 struct got_commit_object *commit;
5330 error = got_object_open_as_commit(&commit, repo, ids[0]);
5331 if (error)
5332 goto done;
5334 labels[1] = labels[0];
5335 ids[1] = ids[0];
5336 if (got_object_commit_get_nparents(commit) > 0) {
5337 const struct got_object_id_queue *pids;
5338 struct got_object_qid *pid;
5339 pids = got_object_commit_get_parent_ids(commit);
5340 pid = STAILQ_FIRST(pids);
5341 ids[0] = got_object_id_dup(&pid->id);
5342 if (ids[0] == NULL) {
5343 error = got_error_from_errno(
5344 "got_object_id_dup");
5345 got_object_commit_close(commit);
5346 goto done;
5348 error = got_object_id_str(&labels[0], ids[0]);
5349 if (error) {
5350 got_object_commit_close(commit);
5351 goto done;
5353 } else {
5354 ids[0] = NULL;
5355 labels[0] = strdup("/dev/null");
5356 if (labels[0] == NULL) {
5357 error = got_error_from_errno("strdup");
5358 got_object_commit_close(commit);
5359 goto done;
5363 got_object_commit_close(commit);
5366 if (ncommit_args == 0 && argc > 2) {
5367 error = got_error_msg(GOT_ERR_BAD_PATH,
5368 "path arguments cannot be used when diffing two objects");
5369 goto done;
5372 if (ids[0]) {
5373 error = got_object_get_type(&type1, repo, ids[0]);
5374 if (error)
5375 goto done;
5378 error = got_object_get_type(&type2, repo, ids[1]);
5379 if (error)
5380 goto done;
5381 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5382 error = got_error(GOT_ERR_OBJ_TYPE);
5383 goto done;
5385 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5386 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5387 "path arguments cannot be used when diffing blobs");
5388 goto done;
5391 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5392 char *in_repo_path;
5393 struct got_pathlist_entry *new;
5394 if (worktree) {
5395 const char *prefix;
5396 char *p;
5397 error = got_worktree_resolve_path(&p, worktree,
5398 argv[i]);
5399 if (error)
5400 goto done;
5401 prefix = got_worktree_get_path_prefix(worktree);
5402 while (prefix[0] == '/')
5403 prefix++;
5404 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5405 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5406 p) == -1) {
5407 error = got_error_from_errno("asprintf");
5408 free(p);
5409 goto done;
5411 free(p);
5412 } else {
5413 char *mapped_path, *s;
5414 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5415 if (error)
5416 goto done;
5417 s = mapped_path;
5418 while (s[0] == '/')
5419 s++;
5420 in_repo_path = strdup(s);
5421 if (in_repo_path == NULL) {
5422 error = got_error_from_errno("asprintf");
5423 free(mapped_path);
5424 goto done;
5426 free(mapped_path);
5429 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5430 if (error || new == NULL /* duplicate */)
5431 free(in_repo_path);
5432 if (error)
5433 goto done;
5436 if (worktree) {
5437 /* Release work tree lock. */
5438 got_worktree_close(worktree);
5439 worktree = NULL;
5442 fd1 = got_opentempfd();
5443 if (fd1 == -1) {
5444 error = got_error_from_errno("got_opentempfd");
5445 goto done;
5448 fd2 = got_opentempfd();
5449 if (fd2 == -1) {
5450 error = got_error_from_errno("got_opentempfd");
5451 goto done;
5454 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5455 case GOT_OBJ_TYPE_BLOB:
5456 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5457 fd1, fd2, ids[0], ids[1], NULL, NULL,
5458 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5459 ignore_whitespace, force_text_diff,
5460 show_diffstat ? &dsa : NULL, repo, outfile);
5461 break;
5462 case GOT_OBJ_TYPE_TREE:
5463 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5464 ids[0], ids[1], &paths, "", "",
5465 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5466 ignore_whitespace, force_text_diff,
5467 show_diffstat ? &dsa : NULL, repo, outfile);
5468 break;
5469 case GOT_OBJ_TYPE_COMMIT:
5470 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5471 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5472 fd1, fd2, ids[0], ids[1], &paths,
5473 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5474 ignore_whitespace, force_text_diff,
5475 show_diffstat ? &dsa : NULL, repo, outfile);
5476 break;
5477 default:
5478 error = got_error(GOT_ERR_OBJ_TYPE);
5480 if (error)
5481 goto done;
5483 if (show_diffstat && dsa.nfiles > 0) {
5484 char *header = NULL;
5486 if (asprintf(&header, "diffstat %s %s",
5487 labels[0], labels[1]) == -1) {
5488 error = got_error_from_errno("asprintf");
5489 goto done;
5492 error = print_diffstat(&dsa, header);
5493 free(header);
5494 if (error)
5495 goto done;
5498 error = printfile(outfile);
5500 done:
5501 free(labels[0]);
5502 free(labels[1]);
5503 free(ids[0]);
5504 free(ids[1]);
5505 if (worktree)
5506 got_worktree_close(worktree);
5507 if (repo) {
5508 const struct got_error *close_err = got_repo_close(repo);
5509 if (error == NULL)
5510 error = close_err;
5512 if (pack_fds) {
5513 const struct got_error *pack_err =
5514 got_repo_pack_fds_close(pack_fds);
5515 if (error == NULL)
5516 error = pack_err;
5518 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5519 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5520 got_ref_list_free(&refs);
5521 if (outfile && fclose(outfile) == EOF && error == NULL)
5522 error = got_error_from_errno("fclose");
5523 if (f1 && fclose(f1) == EOF && error == NULL)
5524 error = got_error_from_errno("fclose");
5525 if (f2 && fclose(f2) == EOF && error == NULL)
5526 error = got_error_from_errno("fclose");
5527 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5528 error = got_error_from_errno("close");
5529 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5530 error = got_error_from_errno("close");
5531 return error;
5534 __dead static void
5535 usage_blame(void)
5537 fprintf(stderr,
5538 "usage: %s blame [-c commit] [-r repository-path] path\n",
5539 getprogname());
5540 exit(1);
5543 struct blame_line {
5544 int annotated;
5545 char *id_str;
5546 char *committer;
5547 char datebuf[11]; /* YYYY-MM-DD + NUL */
5550 struct blame_cb_args {
5551 struct blame_line *lines;
5552 int nlines;
5553 int nlines_prec;
5554 int lineno_cur;
5555 off_t *line_offsets;
5556 FILE *f;
5557 struct got_repository *repo;
5560 static const struct got_error *
5561 blame_cb(void *arg, int nlines, int lineno,
5562 struct got_commit_object *commit, struct got_object_id *id)
5564 const struct got_error *err = NULL;
5565 struct blame_cb_args *a = arg;
5566 struct blame_line *bline;
5567 char *line = NULL;
5568 size_t linesize = 0;
5569 off_t offset;
5570 struct tm tm;
5571 time_t committer_time;
5573 if (nlines != a->nlines ||
5574 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5575 return got_error(GOT_ERR_RANGE);
5577 if (sigint_received)
5578 return got_error(GOT_ERR_ITER_COMPLETED);
5580 if (lineno == -1)
5581 return NULL; /* no change in this commit */
5583 /* Annotate this line. */
5584 bline = &a->lines[lineno - 1];
5585 if (bline->annotated)
5586 return NULL;
5587 err = got_object_id_str(&bline->id_str, id);
5588 if (err)
5589 return err;
5591 bline->committer = strdup(got_object_commit_get_committer(commit));
5592 if (bline->committer == NULL) {
5593 err = got_error_from_errno("strdup");
5594 goto done;
5597 committer_time = got_object_commit_get_committer_time(commit);
5598 if (gmtime_r(&committer_time, &tm) == NULL)
5599 return got_error_from_errno("gmtime_r");
5600 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5601 &tm) == 0) {
5602 err = got_error(GOT_ERR_NO_SPACE);
5603 goto done;
5605 bline->annotated = 1;
5607 /* Print lines annotated so far. */
5608 bline = &a->lines[a->lineno_cur - 1];
5609 if (!bline->annotated)
5610 goto done;
5612 offset = a->line_offsets[a->lineno_cur - 1];
5613 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5614 err = got_error_from_errno("fseeko");
5615 goto done;
5618 while (a->lineno_cur <= a->nlines && bline->annotated) {
5619 char *smallerthan, *at, *nl, *committer;
5620 size_t len;
5622 if (getline(&line, &linesize, a->f) == -1) {
5623 if (ferror(a->f))
5624 err = got_error_from_errno("getline");
5625 break;
5628 committer = bline->committer;
5629 smallerthan = strchr(committer, '<');
5630 if (smallerthan && smallerthan[1] != '\0')
5631 committer = smallerthan + 1;
5632 at = strchr(committer, '@');
5633 if (at)
5634 *at = '\0';
5635 len = strlen(committer);
5636 if (len >= 9)
5637 committer[8] = '\0';
5639 nl = strchr(line, '\n');
5640 if (nl)
5641 *nl = '\0';
5642 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5643 bline->id_str, bline->datebuf, committer, line);
5645 a->lineno_cur++;
5646 bline = &a->lines[a->lineno_cur - 1];
5648 done:
5649 free(line);
5650 return err;
5653 static const struct got_error *
5654 cmd_blame(int argc, char *argv[])
5656 const struct got_error *error;
5657 struct got_repository *repo = NULL;
5658 struct got_worktree *worktree = NULL;
5659 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5660 char *link_target = NULL;
5661 struct got_object_id *obj_id = NULL;
5662 struct got_object_id *commit_id = NULL;
5663 struct got_commit_object *commit = NULL;
5664 struct got_blob_object *blob = NULL;
5665 char *commit_id_str = NULL;
5666 struct blame_cb_args bca;
5667 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5668 off_t filesize;
5669 int *pack_fds = NULL;
5670 FILE *f1 = NULL, *f2 = NULL;
5672 fd1 = got_opentempfd();
5673 if (fd1 == -1)
5674 return got_error_from_errno("got_opentempfd");
5676 memset(&bca, 0, sizeof(bca));
5678 #ifndef PROFILE
5679 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5680 NULL) == -1)
5681 err(1, "pledge");
5682 #endif
5684 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5685 switch (ch) {
5686 case 'c':
5687 commit_id_str = optarg;
5688 break;
5689 case 'r':
5690 repo_path = realpath(optarg, NULL);
5691 if (repo_path == NULL)
5692 return got_error_from_errno2("realpath",
5693 optarg);
5694 got_path_strip_trailing_slashes(repo_path);
5695 break;
5696 default:
5697 usage_blame();
5698 /* NOTREACHED */
5702 argc -= optind;
5703 argv += optind;
5705 if (argc == 1)
5706 path = argv[0];
5707 else
5708 usage_blame();
5710 cwd = getcwd(NULL, 0);
5711 if (cwd == NULL) {
5712 error = got_error_from_errno("getcwd");
5713 goto done;
5716 error = got_repo_pack_fds_open(&pack_fds);
5717 if (error != NULL)
5718 goto done;
5720 if (repo_path == NULL) {
5721 error = got_worktree_open(&worktree, cwd);
5722 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5723 goto done;
5724 else
5725 error = NULL;
5726 if (worktree) {
5727 repo_path =
5728 strdup(got_worktree_get_repo_path(worktree));
5729 if (repo_path == NULL) {
5730 error = got_error_from_errno("strdup");
5731 if (error)
5732 goto done;
5734 } else {
5735 repo_path = strdup(cwd);
5736 if (repo_path == NULL) {
5737 error = got_error_from_errno("strdup");
5738 goto done;
5743 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5744 if (error != NULL)
5745 goto done;
5747 if (worktree) {
5748 const char *prefix = got_worktree_get_path_prefix(worktree);
5749 char *p;
5751 error = got_worktree_resolve_path(&p, worktree, path);
5752 if (error)
5753 goto done;
5754 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5755 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5756 p) == -1) {
5757 error = got_error_from_errno("asprintf");
5758 free(p);
5759 goto done;
5761 free(p);
5762 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5763 } else {
5764 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5765 if (error)
5766 goto done;
5767 error = got_repo_map_path(&in_repo_path, repo, path);
5769 if (error)
5770 goto done;
5772 if (commit_id_str == NULL) {
5773 struct got_reference *head_ref;
5774 error = got_ref_open(&head_ref, repo, worktree ?
5775 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5776 if (error != NULL)
5777 goto done;
5778 error = got_ref_resolve(&commit_id, repo, head_ref);
5779 got_ref_close(head_ref);
5780 if (error != NULL)
5781 goto done;
5782 } else {
5783 struct got_reflist_head refs;
5784 TAILQ_INIT(&refs);
5785 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5786 NULL);
5787 if (error)
5788 goto done;
5789 error = got_repo_match_object_id(&commit_id, NULL,
5790 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5791 got_ref_list_free(&refs);
5792 if (error)
5793 goto done;
5796 if (worktree) {
5797 /* Release work tree lock. */
5798 got_worktree_close(worktree);
5799 worktree = NULL;
5802 error = got_object_open_as_commit(&commit, repo, commit_id);
5803 if (error)
5804 goto done;
5806 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5807 commit, repo);
5808 if (error)
5809 goto done;
5811 error = got_object_id_by_path(&obj_id, repo, commit,
5812 link_target ? link_target : in_repo_path);
5813 if (error)
5814 goto done;
5816 error = got_object_get_type(&obj_type, repo, obj_id);
5817 if (error)
5818 goto done;
5820 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5821 error = got_error_path(link_target ? link_target : in_repo_path,
5822 GOT_ERR_OBJ_TYPE);
5823 goto done;
5826 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5827 if (error)
5828 goto done;
5829 bca.f = got_opentemp();
5830 if (bca.f == NULL) {
5831 error = got_error_from_errno("got_opentemp");
5832 goto done;
5834 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5835 &bca.line_offsets, bca.f, blob);
5836 if (error || bca.nlines == 0)
5837 goto done;
5839 /* Don't include \n at EOF in the blame line count. */
5840 if (bca.line_offsets[bca.nlines - 1] == filesize)
5841 bca.nlines--;
5843 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5844 if (bca.lines == NULL) {
5845 error = got_error_from_errno("calloc");
5846 goto done;
5848 bca.lineno_cur = 1;
5849 bca.nlines_prec = 0;
5850 i = bca.nlines;
5851 while (i > 0) {
5852 i /= 10;
5853 bca.nlines_prec++;
5855 bca.repo = repo;
5857 fd2 = got_opentempfd();
5858 if (fd2 == -1) {
5859 error = got_error_from_errno("got_opentempfd");
5860 goto done;
5862 fd3 = got_opentempfd();
5863 if (fd3 == -1) {
5864 error = got_error_from_errno("got_opentempfd");
5865 goto done;
5867 f1 = got_opentemp();
5868 if (f1 == NULL) {
5869 error = got_error_from_errno("got_opentemp");
5870 goto done;
5872 f2 = got_opentemp();
5873 if (f2 == NULL) {
5874 error = got_error_from_errno("got_opentemp");
5875 goto done;
5877 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5878 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5879 check_cancelled, NULL, fd2, fd3, f1, f2);
5880 done:
5881 free(in_repo_path);
5882 free(link_target);
5883 free(repo_path);
5884 free(cwd);
5885 free(commit_id);
5886 free(obj_id);
5887 if (commit)
5888 got_object_commit_close(commit);
5890 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5891 error = got_error_from_errno("close");
5892 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5893 error = got_error_from_errno("close");
5894 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5895 error = got_error_from_errno("close");
5896 if (f1 && fclose(f1) == EOF && error == NULL)
5897 error = got_error_from_errno("fclose");
5898 if (f2 && fclose(f2) == EOF && error == NULL)
5899 error = got_error_from_errno("fclose");
5901 if (blob)
5902 got_object_blob_close(blob);
5903 if (worktree)
5904 got_worktree_close(worktree);
5905 if (repo) {
5906 const struct got_error *close_err = got_repo_close(repo);
5907 if (error == NULL)
5908 error = close_err;
5910 if (pack_fds) {
5911 const struct got_error *pack_err =
5912 got_repo_pack_fds_close(pack_fds);
5913 if (error == NULL)
5914 error = pack_err;
5916 if (bca.lines) {
5917 for (i = 0; i < bca.nlines; i++) {
5918 struct blame_line *bline = &bca.lines[i];
5919 free(bline->id_str);
5920 free(bline->committer);
5922 free(bca.lines);
5924 free(bca.line_offsets);
5925 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5926 error = got_error_from_errno("fclose");
5927 return error;
5930 __dead static void
5931 usage_tree(void)
5933 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5934 "[path]\n", getprogname());
5935 exit(1);
5938 static const struct got_error *
5939 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5940 const char *root_path, struct got_repository *repo)
5942 const struct got_error *err = NULL;
5943 int is_root_path = (strcmp(path, root_path) == 0);
5944 const char *modestr = "";
5945 mode_t mode = got_tree_entry_get_mode(te);
5946 char *link_target = NULL;
5948 path += strlen(root_path);
5949 while (path[0] == '/')
5950 path++;
5952 if (got_object_tree_entry_is_submodule(te))
5953 modestr = "$";
5954 else if (S_ISLNK(mode)) {
5955 int i;
5957 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5958 if (err)
5959 return err;
5960 for (i = 0; i < strlen(link_target); i++) {
5961 if (!isprint((unsigned char)link_target[i]))
5962 link_target[i] = '?';
5965 modestr = "@";
5967 else if (S_ISDIR(mode))
5968 modestr = "/";
5969 else if (mode & S_IXUSR)
5970 modestr = "*";
5972 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5973 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5974 link_target ? " -> ": "", link_target ? link_target : "");
5976 free(link_target);
5977 return NULL;
5980 static const struct got_error *
5981 print_tree(const char *path, struct got_commit_object *commit,
5982 int show_ids, int recurse, const char *root_path,
5983 struct got_repository *repo)
5985 const struct got_error *err = NULL;
5986 struct got_object_id *tree_id = NULL;
5987 struct got_tree_object *tree = NULL;
5988 int nentries, i;
5990 err = got_object_id_by_path(&tree_id, repo, commit, path);
5991 if (err)
5992 goto done;
5994 err = got_object_open_as_tree(&tree, repo, tree_id);
5995 if (err)
5996 goto done;
5997 nentries = got_object_tree_get_nentries(tree);
5998 for (i = 0; i < nentries; i++) {
5999 struct got_tree_entry *te;
6000 char *id = NULL;
6002 if (sigint_received || sigpipe_received)
6003 break;
6005 te = got_object_tree_get_entry(tree, i);
6006 if (show_ids) {
6007 char *id_str;
6008 err = got_object_id_str(&id_str,
6009 got_tree_entry_get_id(te));
6010 if (err)
6011 goto done;
6012 if (asprintf(&id, "%s ", id_str) == -1) {
6013 err = got_error_from_errno("asprintf");
6014 free(id_str);
6015 goto done;
6017 free(id_str);
6019 err = print_entry(te, id, path, root_path, repo);
6020 free(id);
6021 if (err)
6022 goto done;
6024 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6025 char *child_path;
6026 if (asprintf(&child_path, "%s%s%s", path,
6027 path[0] == '/' && path[1] == '\0' ? "" : "/",
6028 got_tree_entry_get_name(te)) == -1) {
6029 err = got_error_from_errno("asprintf");
6030 goto done;
6032 err = print_tree(child_path, commit, show_ids, 1,
6033 root_path, repo);
6034 free(child_path);
6035 if (err)
6036 goto done;
6039 done:
6040 if (tree)
6041 got_object_tree_close(tree);
6042 free(tree_id);
6043 return err;
6046 static const struct got_error *
6047 cmd_tree(int argc, char *argv[])
6049 const struct got_error *error;
6050 struct got_repository *repo = NULL;
6051 struct got_worktree *worktree = NULL;
6052 const char *path, *refname = NULL;
6053 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6054 struct got_object_id *commit_id = NULL;
6055 struct got_commit_object *commit = NULL;
6056 char *commit_id_str = NULL;
6057 int show_ids = 0, recurse = 0;
6058 int ch;
6059 int *pack_fds = NULL;
6061 #ifndef PROFILE
6062 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6063 NULL) == -1)
6064 err(1, "pledge");
6065 #endif
6067 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6068 switch (ch) {
6069 case 'c':
6070 commit_id_str = optarg;
6071 break;
6072 case 'i':
6073 show_ids = 1;
6074 break;
6075 case 'R':
6076 recurse = 1;
6077 break;
6078 case 'r':
6079 repo_path = realpath(optarg, NULL);
6080 if (repo_path == NULL)
6081 return got_error_from_errno2("realpath",
6082 optarg);
6083 got_path_strip_trailing_slashes(repo_path);
6084 break;
6085 default:
6086 usage_tree();
6087 /* NOTREACHED */
6091 argc -= optind;
6092 argv += optind;
6094 if (argc == 1)
6095 path = argv[0];
6096 else if (argc > 1)
6097 usage_tree();
6098 else
6099 path = NULL;
6101 cwd = getcwd(NULL, 0);
6102 if (cwd == NULL) {
6103 error = got_error_from_errno("getcwd");
6104 goto done;
6107 error = got_repo_pack_fds_open(&pack_fds);
6108 if (error != NULL)
6109 goto done;
6111 if (repo_path == NULL) {
6112 error = got_worktree_open(&worktree, cwd);
6113 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6114 goto done;
6115 else
6116 error = NULL;
6117 if (worktree) {
6118 repo_path =
6119 strdup(got_worktree_get_repo_path(worktree));
6120 if (repo_path == NULL)
6121 error = got_error_from_errno("strdup");
6122 if (error)
6123 goto done;
6124 } else {
6125 repo_path = strdup(cwd);
6126 if (repo_path == NULL) {
6127 error = got_error_from_errno("strdup");
6128 goto done;
6133 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6134 if (error != NULL)
6135 goto done;
6137 if (worktree) {
6138 const char *prefix = got_worktree_get_path_prefix(worktree);
6139 char *p;
6141 if (path == NULL)
6142 path = "";
6143 error = got_worktree_resolve_path(&p, worktree, path);
6144 if (error)
6145 goto done;
6146 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6147 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6148 p) == -1) {
6149 error = got_error_from_errno("asprintf");
6150 free(p);
6151 goto done;
6153 free(p);
6154 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6155 if (error)
6156 goto done;
6157 } else {
6158 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6159 if (error)
6160 goto done;
6161 if (path == NULL)
6162 path = "/";
6163 error = got_repo_map_path(&in_repo_path, repo, path);
6164 if (error != NULL)
6165 goto done;
6168 if (commit_id_str == NULL) {
6169 struct got_reference *head_ref;
6170 if (worktree)
6171 refname = got_worktree_get_head_ref_name(worktree);
6172 else
6173 refname = GOT_REF_HEAD;
6174 error = got_ref_open(&head_ref, repo, refname, 0);
6175 if (error != NULL)
6176 goto done;
6177 error = got_ref_resolve(&commit_id, repo, head_ref);
6178 got_ref_close(head_ref);
6179 if (error != NULL)
6180 goto done;
6181 } else {
6182 struct got_reflist_head refs;
6183 TAILQ_INIT(&refs);
6184 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6185 NULL);
6186 if (error)
6187 goto done;
6188 error = got_repo_match_object_id(&commit_id, NULL,
6189 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6190 got_ref_list_free(&refs);
6191 if (error)
6192 goto done;
6195 if (worktree) {
6196 /* Release work tree lock. */
6197 got_worktree_close(worktree);
6198 worktree = NULL;
6201 error = got_object_open_as_commit(&commit, repo, commit_id);
6202 if (error)
6203 goto done;
6205 error = print_tree(in_repo_path, commit, show_ids, recurse,
6206 in_repo_path, repo);
6207 done:
6208 free(in_repo_path);
6209 free(repo_path);
6210 free(cwd);
6211 free(commit_id);
6212 if (commit)
6213 got_object_commit_close(commit);
6214 if (worktree)
6215 got_worktree_close(worktree);
6216 if (repo) {
6217 const struct got_error *close_err = got_repo_close(repo);
6218 if (error == NULL)
6219 error = close_err;
6221 if (pack_fds) {
6222 const struct got_error *pack_err =
6223 got_repo_pack_fds_close(pack_fds);
6224 if (error == NULL)
6225 error = pack_err;
6227 return error;
6230 __dead static void
6231 usage_status(void)
6233 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6234 "[-s status-codes] [path ...]\n", getprogname());
6235 exit(1);
6238 struct got_status_arg {
6239 char *status_codes;
6240 int suppress;
6243 static const struct got_error *
6244 print_status(void *arg, unsigned char status, unsigned char staged_status,
6245 const char *path, struct got_object_id *blob_id,
6246 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6247 int dirfd, const char *de_name)
6249 struct got_status_arg *st = arg;
6251 if (status == staged_status && (status == GOT_STATUS_DELETE))
6252 status = GOT_STATUS_NO_CHANGE;
6253 if (st != NULL && st->status_codes) {
6254 size_t ncodes = strlen(st->status_codes);
6255 int i, j = 0;
6257 for (i = 0; i < ncodes ; i++) {
6258 if (st->suppress) {
6259 if (status == st->status_codes[i] ||
6260 staged_status == st->status_codes[i]) {
6261 j++;
6262 continue;
6264 } else {
6265 if (status == st->status_codes[i] ||
6266 staged_status == st->status_codes[i])
6267 break;
6271 if (st->suppress && j == 0)
6272 goto print;
6274 if (i == ncodes)
6275 return NULL;
6277 print:
6278 printf("%c%c %s\n", status, staged_status, path);
6279 return NULL;
6282 static const struct got_error *
6283 cmd_status(int argc, char *argv[])
6285 const struct got_error *error = NULL;
6286 struct got_repository *repo = NULL;
6287 struct got_worktree *worktree = NULL;
6288 struct got_status_arg st;
6289 char *cwd = NULL;
6290 struct got_pathlist_head paths;
6291 int ch, i, no_ignores = 0;
6292 int *pack_fds = NULL;
6294 TAILQ_INIT(&paths);
6296 memset(&st, 0, sizeof(st));
6297 st.status_codes = NULL;
6298 st.suppress = 0;
6300 #ifndef PROFILE
6301 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6302 NULL) == -1)
6303 err(1, "pledge");
6304 #endif
6306 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6307 switch (ch) {
6308 case 'I':
6309 no_ignores = 1;
6310 break;
6311 case 'S':
6312 if (st.status_codes != NULL && st.suppress == 0)
6313 option_conflict('S', 's');
6314 st.suppress = 1;
6315 /* fallthrough */
6316 case 's':
6317 for (i = 0; i < strlen(optarg); i++) {
6318 switch (optarg[i]) {
6319 case GOT_STATUS_MODIFY:
6320 case GOT_STATUS_ADD:
6321 case GOT_STATUS_DELETE:
6322 case GOT_STATUS_CONFLICT:
6323 case GOT_STATUS_MISSING:
6324 case GOT_STATUS_OBSTRUCTED:
6325 case GOT_STATUS_UNVERSIONED:
6326 case GOT_STATUS_MODE_CHANGE:
6327 case GOT_STATUS_NONEXISTENT:
6328 break;
6329 default:
6330 errx(1, "invalid status code '%c'",
6331 optarg[i]);
6334 if (ch == 's' && st.suppress)
6335 option_conflict('s', 'S');
6336 st.status_codes = optarg;
6337 break;
6338 default:
6339 usage_status();
6340 /* NOTREACHED */
6344 argc -= optind;
6345 argv += optind;
6347 cwd = getcwd(NULL, 0);
6348 if (cwd == NULL) {
6349 error = got_error_from_errno("getcwd");
6350 goto done;
6353 error = got_repo_pack_fds_open(&pack_fds);
6354 if (error != NULL)
6355 goto done;
6357 error = got_worktree_open(&worktree, cwd);
6358 if (error) {
6359 if (error->code == GOT_ERR_NOT_WORKTREE)
6360 error = wrap_not_worktree_error(error, "status", cwd);
6361 goto done;
6364 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6365 NULL, pack_fds);
6366 if (error != NULL)
6367 goto done;
6369 error = apply_unveil(got_repo_get_path(repo), 1,
6370 got_worktree_get_root_path(worktree));
6371 if (error)
6372 goto done;
6374 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6375 if (error)
6376 goto done;
6378 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6379 print_status, &st, check_cancelled, NULL);
6380 done:
6381 if (pack_fds) {
6382 const struct got_error *pack_err =
6383 got_repo_pack_fds_close(pack_fds);
6384 if (error == NULL)
6385 error = pack_err;
6388 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6389 free(cwd);
6390 return error;
6393 __dead static void
6394 usage_ref(void)
6396 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6397 "[-s reference] [name]\n", getprogname());
6398 exit(1);
6401 static const struct got_error *
6402 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6404 static const struct got_error *err = NULL;
6405 struct got_reflist_head refs;
6406 struct got_reflist_entry *re;
6408 TAILQ_INIT(&refs);
6409 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6410 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6411 repo);
6412 if (err)
6413 return err;
6415 TAILQ_FOREACH(re, &refs, entry) {
6416 char *refstr;
6417 refstr = got_ref_to_str(re->ref);
6418 if (refstr == NULL) {
6419 err = got_error_from_errno("got_ref_to_str");
6420 break;
6422 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6423 free(refstr);
6426 got_ref_list_free(&refs);
6427 return err;
6430 static const struct got_error *
6431 delete_ref_by_name(struct got_repository *repo, const char *refname)
6433 const struct got_error *err;
6434 struct got_reference *ref;
6436 err = got_ref_open(&ref, repo, refname, 0);
6437 if (err)
6438 return err;
6440 err = delete_ref(repo, ref);
6441 got_ref_close(ref);
6442 return err;
6445 static const struct got_error *
6446 add_ref(struct got_repository *repo, const char *refname, const char *target)
6448 const struct got_error *err = NULL;
6449 struct got_object_id *id = NULL;
6450 struct got_reference *ref = NULL;
6451 struct got_reflist_head refs;
6454 * Don't let the user create a reference name with a leading '-'.
6455 * While technically a valid reference name, this case is usually
6456 * an unintended typo.
6458 if (refname[0] == '-')
6459 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6461 TAILQ_INIT(&refs);
6462 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6463 if (err)
6464 goto done;
6465 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6466 &refs, repo);
6467 got_ref_list_free(&refs);
6468 if (err)
6469 goto done;
6471 err = got_ref_alloc(&ref, refname, id);
6472 if (err)
6473 goto done;
6475 err = got_ref_write(ref, repo);
6476 done:
6477 if (ref)
6478 got_ref_close(ref);
6479 free(id);
6480 return err;
6483 static const struct got_error *
6484 add_symref(struct got_repository *repo, const char *refname, const char *target)
6486 const struct got_error *err = NULL;
6487 struct got_reference *ref = NULL;
6488 struct got_reference *target_ref = NULL;
6491 * Don't let the user create a reference name with a leading '-'.
6492 * While technically a valid reference name, this case is usually
6493 * an unintended typo.
6495 if (refname[0] == '-')
6496 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6498 err = got_ref_open(&target_ref, repo, target, 0);
6499 if (err)
6500 return err;
6502 err = got_ref_alloc_symref(&ref, refname, target_ref);
6503 if (err)
6504 goto done;
6506 err = got_ref_write(ref, repo);
6507 done:
6508 if (target_ref)
6509 got_ref_close(target_ref);
6510 if (ref)
6511 got_ref_close(ref);
6512 return err;
6515 static const struct got_error *
6516 cmd_ref(int argc, char *argv[])
6518 const struct got_error *error = NULL;
6519 struct got_repository *repo = NULL;
6520 struct got_worktree *worktree = NULL;
6521 char *cwd = NULL, *repo_path = NULL;
6522 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6523 const char *obj_arg = NULL, *symref_target= NULL;
6524 char *refname = NULL;
6525 int *pack_fds = NULL;
6527 #ifndef PROFILE
6528 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6529 "sendfd unveil", NULL) == -1)
6530 err(1, "pledge");
6531 #endif
6533 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6534 switch (ch) {
6535 case 'c':
6536 obj_arg = optarg;
6537 break;
6538 case 'd':
6539 do_delete = 1;
6540 break;
6541 case 'l':
6542 do_list = 1;
6543 break;
6544 case 'r':
6545 repo_path = realpath(optarg, NULL);
6546 if (repo_path == NULL)
6547 return got_error_from_errno2("realpath",
6548 optarg);
6549 got_path_strip_trailing_slashes(repo_path);
6550 break;
6551 case 's':
6552 symref_target = optarg;
6553 break;
6554 case 't':
6555 sort_by_time = 1;
6556 break;
6557 default:
6558 usage_ref();
6559 /* NOTREACHED */
6563 if (obj_arg && do_list)
6564 option_conflict('c', 'l');
6565 if (obj_arg && do_delete)
6566 option_conflict('c', 'd');
6567 if (obj_arg && symref_target)
6568 option_conflict('c', 's');
6569 if (symref_target && do_delete)
6570 option_conflict('s', 'd');
6571 if (symref_target && do_list)
6572 option_conflict('s', 'l');
6573 if (do_delete && do_list)
6574 option_conflict('d', 'l');
6575 if (sort_by_time && !do_list)
6576 errx(1, "-t option requires -l option");
6578 argc -= optind;
6579 argv += optind;
6581 if (do_list) {
6582 if (argc != 0 && argc != 1)
6583 usage_ref();
6584 if (argc == 1) {
6585 refname = strdup(argv[0]);
6586 if (refname == NULL) {
6587 error = got_error_from_errno("strdup");
6588 goto done;
6591 } else {
6592 if (argc != 1)
6593 usage_ref();
6594 refname = strdup(argv[0]);
6595 if (refname == NULL) {
6596 error = got_error_from_errno("strdup");
6597 goto done;
6601 if (refname)
6602 got_path_strip_trailing_slashes(refname);
6604 cwd = getcwd(NULL, 0);
6605 if (cwd == NULL) {
6606 error = got_error_from_errno("getcwd");
6607 goto done;
6610 error = got_repo_pack_fds_open(&pack_fds);
6611 if (error != NULL)
6612 goto done;
6614 if (repo_path == NULL) {
6615 error = got_worktree_open(&worktree, cwd);
6616 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6617 goto done;
6618 else
6619 error = NULL;
6620 if (worktree) {
6621 repo_path =
6622 strdup(got_worktree_get_repo_path(worktree));
6623 if (repo_path == NULL)
6624 error = got_error_from_errno("strdup");
6625 if (error)
6626 goto done;
6627 } else {
6628 repo_path = strdup(cwd);
6629 if (repo_path == NULL) {
6630 error = got_error_from_errno("strdup");
6631 goto done;
6636 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6637 if (error != NULL)
6638 goto done;
6640 #ifndef PROFILE
6641 if (do_list) {
6642 /* Remove "cpath" promise. */
6643 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6644 NULL) == -1)
6645 err(1, "pledge");
6647 #endif
6649 error = apply_unveil(got_repo_get_path(repo), do_list,
6650 worktree ? got_worktree_get_root_path(worktree) : NULL);
6651 if (error)
6652 goto done;
6654 if (do_list)
6655 error = list_refs(repo, refname, sort_by_time);
6656 else if (do_delete)
6657 error = delete_ref_by_name(repo, refname);
6658 else if (symref_target)
6659 error = add_symref(repo, refname, symref_target);
6660 else {
6661 if (obj_arg == NULL)
6662 usage_ref();
6663 error = add_ref(repo, refname, obj_arg);
6665 done:
6666 free(refname);
6667 if (repo) {
6668 const struct got_error *close_err = got_repo_close(repo);
6669 if (error == NULL)
6670 error = close_err;
6672 if (worktree)
6673 got_worktree_close(worktree);
6674 if (pack_fds) {
6675 const struct got_error *pack_err =
6676 got_repo_pack_fds_close(pack_fds);
6677 if (error == NULL)
6678 error = pack_err;
6680 free(cwd);
6681 free(repo_path);
6682 return error;
6685 __dead static void
6686 usage_branch(void)
6688 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6689 "[-r repository-path] [name]\n", getprogname());
6690 exit(1);
6693 static const struct got_error *
6694 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6695 struct got_reference *ref)
6697 const struct got_error *err = NULL;
6698 const char *refname, *marker = " ";
6699 char *refstr;
6701 refname = got_ref_get_name(ref);
6702 if (worktree && strcmp(refname,
6703 got_worktree_get_head_ref_name(worktree)) == 0) {
6704 struct got_object_id *id = NULL;
6706 err = got_ref_resolve(&id, repo, ref);
6707 if (err)
6708 return err;
6709 if (got_object_id_cmp(id,
6710 got_worktree_get_base_commit_id(worktree)) == 0)
6711 marker = "* ";
6712 else
6713 marker = "~ ";
6714 free(id);
6717 if (strncmp(refname, "refs/heads/", 11) == 0)
6718 refname += 11;
6719 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6720 refname += 18;
6721 if (strncmp(refname, "refs/remotes/", 13) == 0)
6722 refname += 13;
6724 refstr = got_ref_to_str(ref);
6725 if (refstr == NULL)
6726 return got_error_from_errno("got_ref_to_str");
6728 printf("%s%s: %s\n", marker, refname, refstr);
6729 free(refstr);
6730 return NULL;
6733 static const struct got_error *
6734 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6736 const char *refname;
6738 if (worktree == NULL)
6739 return got_error(GOT_ERR_NOT_WORKTREE);
6741 refname = got_worktree_get_head_ref_name(worktree);
6743 if (strncmp(refname, "refs/heads/", 11) == 0)
6744 refname += 11;
6745 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6746 refname += 18;
6748 printf("%s\n", refname);
6750 return NULL;
6753 static const struct got_error *
6754 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6755 int sort_by_time)
6757 static const struct got_error *err = NULL;
6758 struct got_reflist_head refs;
6759 struct got_reflist_entry *re;
6760 struct got_reference *temp_ref = NULL;
6761 int rebase_in_progress, histedit_in_progress;
6763 TAILQ_INIT(&refs);
6765 if (worktree) {
6766 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6767 worktree);
6768 if (err)
6769 return err;
6771 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6772 worktree);
6773 if (err)
6774 return err;
6776 if (rebase_in_progress || histedit_in_progress) {
6777 err = got_ref_open(&temp_ref, repo,
6778 got_worktree_get_head_ref_name(worktree), 0);
6779 if (err)
6780 return err;
6781 list_branch(repo, worktree, temp_ref);
6782 got_ref_close(temp_ref);
6786 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6787 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6788 repo);
6789 if (err)
6790 return err;
6792 TAILQ_FOREACH(re, &refs, entry)
6793 list_branch(repo, worktree, re->ref);
6795 got_ref_list_free(&refs);
6797 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6798 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6799 repo);
6800 if (err)
6801 return err;
6803 TAILQ_FOREACH(re, &refs, entry)
6804 list_branch(repo, worktree, re->ref);
6806 got_ref_list_free(&refs);
6808 return NULL;
6811 static const struct got_error *
6812 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6813 const char *branch_name)
6815 const struct got_error *err = NULL;
6816 struct got_reference *ref = NULL;
6817 char *refname, *remote_refname = NULL;
6819 if (strncmp(branch_name, "refs/", 5) == 0)
6820 branch_name += 5;
6821 if (strncmp(branch_name, "heads/", 6) == 0)
6822 branch_name += 6;
6823 else if (strncmp(branch_name, "remotes/", 8) == 0)
6824 branch_name += 8;
6826 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6827 return got_error_from_errno("asprintf");
6829 if (asprintf(&remote_refname, "refs/remotes/%s",
6830 branch_name) == -1) {
6831 err = got_error_from_errno("asprintf");
6832 goto done;
6835 err = got_ref_open(&ref, repo, refname, 0);
6836 if (err) {
6837 const struct got_error *err2;
6838 if (err->code != GOT_ERR_NOT_REF)
6839 goto done;
6841 * Keep 'err' intact such that if neither branch exists
6842 * we report "refs/heads" rather than "refs/remotes" in
6843 * our error message.
6845 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6846 if (err2)
6847 goto done;
6848 err = NULL;
6851 if (worktree &&
6852 strcmp(got_worktree_get_head_ref_name(worktree),
6853 got_ref_get_name(ref)) == 0) {
6854 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6855 "will not delete this work tree's current branch");
6856 goto done;
6859 err = delete_ref(repo, ref);
6860 done:
6861 if (ref)
6862 got_ref_close(ref);
6863 free(refname);
6864 free(remote_refname);
6865 return err;
6868 static const struct got_error *
6869 add_branch(struct got_repository *repo, const char *branch_name,
6870 struct got_object_id *base_commit_id)
6872 const struct got_error *err = NULL;
6873 struct got_reference *ref = NULL;
6874 char *refname = NULL;
6877 * Don't let the user create a branch name with a leading '-'.
6878 * While technically a valid reference name, this case is usually
6879 * an unintended typo.
6881 if (branch_name[0] == '-')
6882 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6884 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6885 branch_name += 11;
6887 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6888 err = got_error_from_errno("asprintf");
6889 goto done;
6892 err = got_ref_open(&ref, repo, refname, 0);
6893 if (err == NULL) {
6894 err = got_error(GOT_ERR_BRANCH_EXISTS);
6895 goto done;
6896 } else if (err->code != GOT_ERR_NOT_REF)
6897 goto done;
6899 err = got_ref_alloc(&ref, refname, base_commit_id);
6900 if (err)
6901 goto done;
6903 err = got_ref_write(ref, repo);
6904 done:
6905 if (ref)
6906 got_ref_close(ref);
6907 free(refname);
6908 return err;
6911 static const struct got_error *
6912 cmd_branch(int argc, char *argv[])
6914 const struct got_error *error = NULL;
6915 struct got_repository *repo = NULL;
6916 struct got_worktree *worktree = NULL;
6917 char *cwd = NULL, *repo_path = NULL;
6918 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6919 const char *delref = NULL, *commit_id_arg = NULL;
6920 struct got_reference *ref = NULL;
6921 struct got_pathlist_head paths;
6922 struct got_object_id *commit_id = NULL;
6923 char *commit_id_str = NULL;
6924 int *pack_fds = NULL;
6926 TAILQ_INIT(&paths);
6928 #ifndef PROFILE
6929 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6930 "sendfd unveil", NULL) == -1)
6931 err(1, "pledge");
6932 #endif
6934 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6935 switch (ch) {
6936 case 'c':
6937 commit_id_arg = optarg;
6938 break;
6939 case 'd':
6940 delref = optarg;
6941 break;
6942 case 'l':
6943 do_list = 1;
6944 break;
6945 case 'n':
6946 do_update = 0;
6947 break;
6948 case 'r':
6949 repo_path = realpath(optarg, NULL);
6950 if (repo_path == NULL)
6951 return got_error_from_errno2("realpath",
6952 optarg);
6953 got_path_strip_trailing_slashes(repo_path);
6954 break;
6955 case 't':
6956 sort_by_time = 1;
6957 break;
6958 default:
6959 usage_branch();
6960 /* NOTREACHED */
6964 if (do_list && delref)
6965 option_conflict('l', 'd');
6966 if (sort_by_time && !do_list)
6967 errx(1, "-t option requires -l option");
6969 argc -= optind;
6970 argv += optind;
6972 if (!do_list && !delref && argc == 0)
6973 do_show = 1;
6975 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6976 errx(1, "-c option can only be used when creating a branch");
6978 if (do_list || delref) {
6979 if (argc > 0)
6980 usage_branch();
6981 } else if (!do_show && argc != 1)
6982 usage_branch();
6984 cwd = getcwd(NULL, 0);
6985 if (cwd == NULL) {
6986 error = got_error_from_errno("getcwd");
6987 goto done;
6990 error = got_repo_pack_fds_open(&pack_fds);
6991 if (error != NULL)
6992 goto done;
6994 if (repo_path == NULL) {
6995 error = got_worktree_open(&worktree, cwd);
6996 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6997 goto done;
6998 else
6999 error = NULL;
7000 if (worktree) {
7001 repo_path =
7002 strdup(got_worktree_get_repo_path(worktree));
7003 if (repo_path == NULL)
7004 error = got_error_from_errno("strdup");
7005 if (error)
7006 goto done;
7007 } else {
7008 repo_path = strdup(cwd);
7009 if (repo_path == NULL) {
7010 error = got_error_from_errno("strdup");
7011 goto done;
7016 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7017 if (error != NULL)
7018 goto done;
7020 #ifndef PROFILE
7021 if (do_list || do_show) {
7022 /* Remove "cpath" promise. */
7023 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7024 NULL) == -1)
7025 err(1, "pledge");
7027 #endif
7029 error = apply_unveil(got_repo_get_path(repo), do_list,
7030 worktree ? got_worktree_get_root_path(worktree) : NULL);
7031 if (error)
7032 goto done;
7034 if (do_show)
7035 error = show_current_branch(repo, worktree);
7036 else if (do_list)
7037 error = list_branches(repo, worktree, sort_by_time);
7038 else if (delref)
7039 error = delete_branch(repo, worktree, delref);
7040 else {
7041 struct got_reflist_head refs;
7042 TAILQ_INIT(&refs);
7043 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7044 NULL);
7045 if (error)
7046 goto done;
7047 if (commit_id_arg == NULL)
7048 commit_id_arg = worktree ?
7049 got_worktree_get_head_ref_name(worktree) :
7050 GOT_REF_HEAD;
7051 error = got_repo_match_object_id(&commit_id, NULL,
7052 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7053 got_ref_list_free(&refs);
7054 if (error)
7055 goto done;
7056 error = add_branch(repo, argv[0], commit_id);
7057 if (error)
7058 goto done;
7059 if (worktree && do_update) {
7060 struct got_update_progress_arg upa;
7061 char *branch_refname = NULL;
7063 error = got_object_id_str(&commit_id_str, commit_id);
7064 if (error)
7065 goto done;
7066 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7067 worktree);
7068 if (error)
7069 goto done;
7070 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7071 == -1) {
7072 error = got_error_from_errno("asprintf");
7073 goto done;
7075 error = got_ref_open(&ref, repo, branch_refname, 0);
7076 free(branch_refname);
7077 if (error)
7078 goto done;
7079 error = switch_head_ref(ref, commit_id, worktree,
7080 repo);
7081 if (error)
7082 goto done;
7083 error = got_worktree_set_base_commit_id(worktree, repo,
7084 commit_id);
7085 if (error)
7086 goto done;
7087 memset(&upa, 0, sizeof(upa));
7088 error = got_worktree_checkout_files(worktree, &paths,
7089 repo, update_progress, &upa, check_cancelled,
7090 NULL);
7091 if (error)
7092 goto done;
7093 if (upa.did_something) {
7094 printf("Updated to %s: %s\n",
7095 got_worktree_get_head_ref_name(worktree),
7096 commit_id_str);
7098 print_update_progress_stats(&upa);
7101 done:
7102 if (ref)
7103 got_ref_close(ref);
7104 if (repo) {
7105 const struct got_error *close_err = got_repo_close(repo);
7106 if (error == NULL)
7107 error = close_err;
7109 if (worktree)
7110 got_worktree_close(worktree);
7111 if (pack_fds) {
7112 const struct got_error *pack_err =
7113 got_repo_pack_fds_close(pack_fds);
7114 if (error == NULL)
7115 error = pack_err;
7117 free(cwd);
7118 free(repo_path);
7119 free(commit_id);
7120 free(commit_id_str);
7121 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7122 return error;
7126 __dead static void
7127 usage_tag(void)
7129 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7130 "[-r repository-path] [-s signer-id] name\n", getprogname());
7131 exit(1);
7134 #if 0
7135 static const struct got_error *
7136 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7138 const struct got_error *err = NULL;
7139 struct got_reflist_entry *re, *se, *new;
7140 struct got_object_id *re_id, *se_id;
7141 struct got_tag_object *re_tag, *se_tag;
7142 time_t re_time, se_time;
7144 STAILQ_FOREACH(re, tags, entry) {
7145 se = STAILQ_FIRST(sorted);
7146 if (se == NULL) {
7147 err = got_reflist_entry_dup(&new, re);
7148 if (err)
7149 return err;
7150 STAILQ_INSERT_HEAD(sorted, new, entry);
7151 continue;
7152 } else {
7153 err = got_ref_resolve(&re_id, repo, re->ref);
7154 if (err)
7155 break;
7156 err = got_object_open_as_tag(&re_tag, repo, re_id);
7157 free(re_id);
7158 if (err)
7159 break;
7160 re_time = got_object_tag_get_tagger_time(re_tag);
7161 got_object_tag_close(re_tag);
7164 while (se) {
7165 err = got_ref_resolve(&se_id, repo, re->ref);
7166 if (err)
7167 break;
7168 err = got_object_open_as_tag(&se_tag, repo, se_id);
7169 free(se_id);
7170 if (err)
7171 break;
7172 se_time = got_object_tag_get_tagger_time(se_tag);
7173 got_object_tag_close(se_tag);
7175 if (se_time > re_time) {
7176 err = got_reflist_entry_dup(&new, re);
7177 if (err)
7178 return err;
7179 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7180 break;
7182 se = STAILQ_NEXT(se, entry);
7183 continue;
7186 done:
7187 return err;
7189 #endif
7191 static const struct got_error *
7192 get_tag_refname(char **refname, const char *tag_name)
7194 const struct got_error *err;
7196 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7197 *refname = strdup(tag_name);
7198 if (*refname == NULL)
7199 return got_error_from_errno("strdup");
7200 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7201 err = got_error_from_errno("asprintf");
7202 *refname = NULL;
7203 return err;
7206 return NULL;
7209 static const struct got_error *
7210 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7211 const char *allowed_signers, const char *revoked_signers, int verbosity)
7213 static const struct got_error *err = NULL;
7214 struct got_reflist_head refs;
7215 struct got_reflist_entry *re;
7216 char *wanted_refname = NULL;
7217 int bad_sigs = 0;
7219 TAILQ_INIT(&refs);
7221 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7222 if (err)
7223 return err;
7225 if (tag_name) {
7226 struct got_reference *ref;
7227 err = get_tag_refname(&wanted_refname, tag_name);
7228 if (err)
7229 goto done;
7230 /* Wanted tag reference should exist. */
7231 err = got_ref_open(&ref, repo, wanted_refname, 0);
7232 if (err)
7233 goto done;
7234 got_ref_close(ref);
7237 TAILQ_FOREACH(re, &refs, entry) {
7238 const char *refname;
7239 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7240 char datebuf[26];
7241 const char *tagger, *ssh_sig = NULL;
7242 char *sig_msg = NULL;
7243 time_t tagger_time;
7244 struct got_object_id *id;
7245 struct got_tag_object *tag;
7246 struct got_commit_object *commit = NULL;
7248 refname = got_ref_get_name(re->ref);
7249 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7250 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7251 continue;
7252 refname += 10;
7253 refstr = got_ref_to_str(re->ref);
7254 if (refstr == NULL) {
7255 err = got_error_from_errno("got_ref_to_str");
7256 break;
7259 err = got_ref_resolve(&id, repo, re->ref);
7260 if (err)
7261 break;
7262 err = got_object_open_as_tag(&tag, repo, id);
7263 if (err) {
7264 if (err->code != GOT_ERR_OBJ_TYPE) {
7265 free(id);
7266 break;
7268 /* "lightweight" tag */
7269 err = got_object_open_as_commit(&commit, repo, id);
7270 if (err) {
7271 free(id);
7272 break;
7274 tagger = got_object_commit_get_committer(commit);
7275 tagger_time =
7276 got_object_commit_get_committer_time(commit);
7277 err = got_object_id_str(&id_str, id);
7278 free(id);
7279 if (err)
7280 break;
7281 } else {
7282 free(id);
7283 tagger = got_object_tag_get_tagger(tag);
7284 tagger_time = got_object_tag_get_tagger_time(tag);
7285 err = got_object_id_str(&id_str,
7286 got_object_tag_get_object_id(tag));
7287 if (err)
7288 break;
7291 if (tag && verify_tags) {
7292 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7293 got_object_tag_get_message(tag));
7294 if (ssh_sig && allowed_signers == NULL) {
7295 err = got_error_msg(
7296 GOT_ERR_VERIFY_TAG_SIGNATURE,
7297 "SSH signature verification requires "
7298 "setting allowed_signers in "
7299 "got.conf(5)");
7300 break;
7304 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7305 free(refstr);
7306 printf("from: %s\n", tagger);
7307 datestr = get_datestr(&tagger_time, datebuf);
7308 if (datestr)
7309 printf("date: %s UTC\n", datestr);
7310 if (commit)
7311 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7312 else {
7313 switch (got_object_tag_get_object_type(tag)) {
7314 case GOT_OBJ_TYPE_BLOB:
7315 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7316 id_str);
7317 break;
7318 case GOT_OBJ_TYPE_TREE:
7319 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7320 id_str);
7321 break;
7322 case GOT_OBJ_TYPE_COMMIT:
7323 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7324 id_str);
7325 break;
7326 case GOT_OBJ_TYPE_TAG:
7327 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7328 id_str);
7329 break;
7330 default:
7331 break;
7334 free(id_str);
7336 if (ssh_sig) {
7337 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7338 allowed_signers, revoked_signers, verbosity);
7339 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7340 bad_sigs = 1;
7341 else if (err)
7342 break;
7343 printf("signature: %s", sig_msg);
7344 free(sig_msg);
7345 sig_msg = NULL;
7348 if (commit) {
7349 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7350 if (err)
7351 break;
7352 got_object_commit_close(commit);
7353 } else {
7354 tagmsg0 = strdup(got_object_tag_get_message(tag));
7355 got_object_tag_close(tag);
7356 if (tagmsg0 == NULL) {
7357 err = got_error_from_errno("strdup");
7358 break;
7362 tagmsg = tagmsg0;
7363 do {
7364 line = strsep(&tagmsg, "\n");
7365 if (line)
7366 printf(" %s\n", line);
7367 } while (line);
7368 free(tagmsg0);
7370 done:
7371 got_ref_list_free(&refs);
7372 free(wanted_refname);
7374 if (err == NULL && bad_sigs)
7375 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7376 return err;
7379 static const struct got_error *
7380 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7381 const char *tag_name, const char *repo_path)
7383 const struct got_error *err = NULL;
7384 char *template = NULL, *initial_content = NULL;
7385 char *editor = NULL;
7386 int initial_content_len;
7387 int fd = -1;
7389 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7390 err = got_error_from_errno("asprintf");
7391 goto done;
7394 initial_content_len = asprintf(&initial_content,
7395 "\n# tagging commit %s as %s\n",
7396 commit_id_str, tag_name);
7397 if (initial_content_len == -1) {
7398 err = got_error_from_errno("asprintf");
7399 goto done;
7402 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7403 if (err)
7404 goto done;
7406 if (write(fd, initial_content, initial_content_len) == -1) {
7407 err = got_error_from_errno2("write", *tagmsg_path);
7408 goto done;
7411 err = get_editor(&editor);
7412 if (err)
7413 goto done;
7414 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7415 initial_content_len, 1);
7416 done:
7417 free(initial_content);
7418 free(template);
7419 free(editor);
7421 if (fd != -1 && close(fd) == -1 && err == NULL)
7422 err = got_error_from_errno2("close", *tagmsg_path);
7424 if (err) {
7425 free(*tagmsg);
7426 *tagmsg = NULL;
7428 return err;
7431 static const struct got_error *
7432 add_tag(struct got_repository *repo, const char *tagger,
7433 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7434 const char *signer_id, int verbosity)
7436 const struct got_error *err = NULL;
7437 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7438 char *label = NULL, *commit_id_str = NULL;
7439 struct got_reference *ref = NULL;
7440 char *refname = NULL, *tagmsg = NULL;
7441 char *tagmsg_path = NULL, *tag_id_str = NULL;
7442 int preserve_tagmsg = 0;
7443 struct got_reflist_head refs;
7445 TAILQ_INIT(&refs);
7448 * Don't let the user create a tag name with a leading '-'.
7449 * While technically a valid reference name, this case is usually
7450 * an unintended typo.
7452 if (tag_name[0] == '-')
7453 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7455 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7456 if (err)
7457 goto done;
7459 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7460 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7461 if (err)
7462 goto done;
7464 err = got_object_id_str(&commit_id_str, commit_id);
7465 if (err)
7466 goto done;
7468 err = get_tag_refname(&refname, tag_name);
7469 if (err)
7470 goto done;
7471 if (strncmp("refs/tags/", tag_name, 10) == 0)
7472 tag_name += 10;
7474 err = got_ref_open(&ref, repo, refname, 0);
7475 if (err == NULL) {
7476 err = got_error(GOT_ERR_TAG_EXISTS);
7477 goto done;
7478 } else if (err->code != GOT_ERR_NOT_REF)
7479 goto done;
7481 if (tagmsg_arg == NULL) {
7482 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7483 tag_name, got_repo_get_path(repo));
7484 if (err) {
7485 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7486 tagmsg_path != NULL)
7487 preserve_tagmsg = 1;
7488 goto done;
7490 /* Editor is done; we can now apply unveil(2) */
7491 err = got_sigs_apply_unveil();
7492 if (err)
7493 goto done;
7494 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7495 if (err)
7496 goto done;
7499 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7500 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7501 verbosity);
7502 if (err) {
7503 if (tagmsg_path)
7504 preserve_tagmsg = 1;
7505 goto done;
7508 err = got_ref_alloc(&ref, refname, tag_id);
7509 if (err) {
7510 if (tagmsg_path)
7511 preserve_tagmsg = 1;
7512 goto done;
7515 err = got_ref_write(ref, repo);
7516 if (err) {
7517 if (tagmsg_path)
7518 preserve_tagmsg = 1;
7519 goto done;
7522 err = got_object_id_str(&tag_id_str, tag_id);
7523 if (err) {
7524 if (tagmsg_path)
7525 preserve_tagmsg = 1;
7526 goto done;
7528 printf("Created tag %s\n", tag_id_str);
7529 done:
7530 if (preserve_tagmsg) {
7531 fprintf(stderr, "%s: tag message preserved in %s\n",
7532 getprogname(), tagmsg_path);
7533 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7534 err = got_error_from_errno2("unlink", tagmsg_path);
7535 free(tag_id_str);
7536 if (ref)
7537 got_ref_close(ref);
7538 free(commit_id);
7539 free(commit_id_str);
7540 free(refname);
7541 free(tagmsg);
7542 free(tagmsg_path);
7543 got_ref_list_free(&refs);
7544 return err;
7547 static const struct got_error *
7548 cmd_tag(int argc, char *argv[])
7550 const struct got_error *error = NULL;
7551 struct got_repository *repo = NULL;
7552 struct got_worktree *worktree = NULL;
7553 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7554 char *gitconfig_path = NULL, *tagger = NULL;
7555 char *allowed_signers = NULL, *revoked_signers = NULL;
7556 const char *signer_id = NULL;
7557 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7558 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7559 int *pack_fds = NULL;
7561 #ifndef PROFILE
7562 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7563 "sendfd unveil", NULL) == -1)
7564 err(1, "pledge");
7565 #endif
7567 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7568 switch (ch) {
7569 case 'c':
7570 commit_id_arg = optarg;
7571 break;
7572 case 'l':
7573 do_list = 1;
7574 break;
7575 case 'm':
7576 tagmsg = optarg;
7577 break;
7578 case 'r':
7579 repo_path = realpath(optarg, NULL);
7580 if (repo_path == NULL) {
7581 error = got_error_from_errno2("realpath",
7582 optarg);
7583 goto done;
7585 got_path_strip_trailing_slashes(repo_path);
7586 break;
7587 case 's':
7588 signer_id = optarg;
7589 break;
7590 case 'V':
7591 verify_tags = 1;
7592 break;
7593 case 'v':
7594 if (verbosity < 0)
7595 verbosity = 0;
7596 else if (verbosity < 3)
7597 verbosity++;
7598 break;
7599 default:
7600 usage_tag();
7601 /* NOTREACHED */
7605 argc -= optind;
7606 argv += optind;
7608 if (do_list || verify_tags) {
7609 if (commit_id_arg != NULL)
7610 errx(1,
7611 "-c option can only be used when creating a tag");
7612 if (tagmsg) {
7613 if (do_list)
7614 option_conflict('l', 'm');
7615 else
7616 option_conflict('V', 'm');
7618 if (signer_id) {
7619 if (do_list)
7620 option_conflict('l', 's');
7621 else
7622 option_conflict('V', 's');
7624 if (argc > 1)
7625 usage_tag();
7626 } else if (argc != 1)
7627 usage_tag();
7629 if (argc == 1)
7630 tag_name = argv[0];
7632 cwd = getcwd(NULL, 0);
7633 if (cwd == NULL) {
7634 error = got_error_from_errno("getcwd");
7635 goto done;
7638 error = got_repo_pack_fds_open(&pack_fds);
7639 if (error != NULL)
7640 goto done;
7642 if (repo_path == NULL) {
7643 error = got_worktree_open(&worktree, cwd);
7644 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7645 goto done;
7646 else
7647 error = NULL;
7648 if (worktree) {
7649 repo_path =
7650 strdup(got_worktree_get_repo_path(worktree));
7651 if (repo_path == NULL)
7652 error = got_error_from_errno("strdup");
7653 if (error)
7654 goto done;
7655 } else {
7656 repo_path = strdup(cwd);
7657 if (repo_path == NULL) {
7658 error = got_error_from_errno("strdup");
7659 goto done;
7664 if (do_list || verify_tags) {
7665 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7666 if (error != NULL)
7667 goto done;
7668 error = get_allowed_signers(&allowed_signers, repo, worktree);
7669 if (error)
7670 goto done;
7671 error = get_revoked_signers(&revoked_signers, repo, worktree);
7672 if (error)
7673 goto done;
7674 if (worktree) {
7675 /* Release work tree lock. */
7676 got_worktree_close(worktree);
7677 worktree = NULL;
7681 * Remove "cpath" promise unless needed for signature tmpfile
7682 * creation.
7684 if (verify_tags)
7685 got_sigs_apply_unveil();
7686 else {
7687 #ifndef PROFILE
7688 if (pledge("stdio rpath wpath flock proc exec sendfd "
7689 "unveil", NULL) == -1)
7690 err(1, "pledge");
7691 #endif
7693 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7694 if (error)
7695 goto done;
7696 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7697 revoked_signers, verbosity);
7698 } else {
7699 error = get_gitconfig_path(&gitconfig_path);
7700 if (error)
7701 goto done;
7702 error = got_repo_open(&repo, repo_path, gitconfig_path,
7703 pack_fds);
7704 if (error != NULL)
7705 goto done;
7707 error = get_author(&tagger, repo, worktree);
7708 if (error)
7709 goto done;
7710 if (signer_id == NULL)
7711 signer_id = get_signer_id(repo, worktree);
7713 if (tagmsg) {
7714 if (signer_id) {
7715 error = got_sigs_apply_unveil();
7716 if (error)
7717 goto done;
7719 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7720 if (error)
7721 goto done;
7724 if (commit_id_arg == NULL) {
7725 struct got_reference *head_ref;
7726 struct got_object_id *commit_id;
7727 error = got_ref_open(&head_ref, repo,
7728 worktree ? got_worktree_get_head_ref_name(worktree)
7729 : GOT_REF_HEAD, 0);
7730 if (error)
7731 goto done;
7732 error = got_ref_resolve(&commit_id, repo, head_ref);
7733 got_ref_close(head_ref);
7734 if (error)
7735 goto done;
7736 error = got_object_id_str(&commit_id_str, commit_id);
7737 free(commit_id);
7738 if (error)
7739 goto done;
7742 if (worktree) {
7743 /* Release work tree lock. */
7744 got_worktree_close(worktree);
7745 worktree = NULL;
7748 error = add_tag(repo, tagger, tag_name,
7749 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7750 signer_id, verbosity);
7752 done:
7753 if (repo) {
7754 const struct got_error *close_err = got_repo_close(repo);
7755 if (error == NULL)
7756 error = close_err;
7758 if (worktree)
7759 got_worktree_close(worktree);
7760 if (pack_fds) {
7761 const struct got_error *pack_err =
7762 got_repo_pack_fds_close(pack_fds);
7763 if (error == NULL)
7764 error = pack_err;
7766 free(cwd);
7767 free(repo_path);
7768 free(gitconfig_path);
7769 free(commit_id_str);
7770 free(tagger);
7771 free(allowed_signers);
7772 free(revoked_signers);
7773 return error;
7776 __dead static void
7777 usage_add(void)
7779 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7780 exit(1);
7783 static const struct got_error *
7784 add_progress(void *arg, unsigned char status, const char *path)
7786 while (path[0] == '/')
7787 path++;
7788 printf("%c %s\n", status, path);
7789 return NULL;
7792 static const struct got_error *
7793 cmd_add(int argc, char *argv[])
7795 const struct got_error *error = NULL;
7796 struct got_repository *repo = NULL;
7797 struct got_worktree *worktree = NULL;
7798 char *cwd = NULL;
7799 struct got_pathlist_head paths;
7800 struct got_pathlist_entry *pe;
7801 int ch, can_recurse = 0, no_ignores = 0;
7802 int *pack_fds = NULL;
7804 TAILQ_INIT(&paths);
7806 #ifndef PROFILE
7807 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7808 NULL) == -1)
7809 err(1, "pledge");
7810 #endif
7812 while ((ch = getopt(argc, argv, "IR")) != -1) {
7813 switch (ch) {
7814 case 'I':
7815 no_ignores = 1;
7816 break;
7817 case 'R':
7818 can_recurse = 1;
7819 break;
7820 default:
7821 usage_add();
7822 /* NOTREACHED */
7826 argc -= optind;
7827 argv += optind;
7829 if (argc < 1)
7830 usage_add();
7832 cwd = getcwd(NULL, 0);
7833 if (cwd == NULL) {
7834 error = got_error_from_errno("getcwd");
7835 goto done;
7838 error = got_repo_pack_fds_open(&pack_fds);
7839 if (error != NULL)
7840 goto done;
7842 error = got_worktree_open(&worktree, cwd);
7843 if (error) {
7844 if (error->code == GOT_ERR_NOT_WORKTREE)
7845 error = wrap_not_worktree_error(error, "add", cwd);
7846 goto done;
7849 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7850 NULL, pack_fds);
7851 if (error != NULL)
7852 goto done;
7854 error = apply_unveil(got_repo_get_path(repo), 1,
7855 got_worktree_get_root_path(worktree));
7856 if (error)
7857 goto done;
7859 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7860 if (error)
7861 goto done;
7863 if (!can_recurse) {
7864 char *ondisk_path;
7865 struct stat sb;
7866 TAILQ_FOREACH(pe, &paths, entry) {
7867 if (asprintf(&ondisk_path, "%s/%s",
7868 got_worktree_get_root_path(worktree),
7869 pe->path) == -1) {
7870 error = got_error_from_errno("asprintf");
7871 goto done;
7873 if (lstat(ondisk_path, &sb) == -1) {
7874 if (errno == ENOENT) {
7875 free(ondisk_path);
7876 continue;
7878 error = got_error_from_errno2("lstat",
7879 ondisk_path);
7880 free(ondisk_path);
7881 goto done;
7883 free(ondisk_path);
7884 if (S_ISDIR(sb.st_mode)) {
7885 error = got_error_msg(GOT_ERR_BAD_PATH,
7886 "adding directories requires -R option");
7887 goto done;
7892 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7893 NULL, repo, no_ignores);
7894 done:
7895 if (repo) {
7896 const struct got_error *close_err = got_repo_close(repo);
7897 if (error == NULL)
7898 error = close_err;
7900 if (worktree)
7901 got_worktree_close(worktree);
7902 if (pack_fds) {
7903 const struct got_error *pack_err =
7904 got_repo_pack_fds_close(pack_fds);
7905 if (error == NULL)
7906 error = pack_err;
7908 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7909 free(cwd);
7910 return error;
7913 __dead static void
7914 usage_remove(void)
7916 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7917 getprogname());
7918 exit(1);
7921 static const struct got_error *
7922 print_remove_status(void *arg, unsigned char status,
7923 unsigned char staged_status, const char *path)
7925 while (path[0] == '/')
7926 path++;
7927 if (status == GOT_STATUS_NONEXISTENT)
7928 return NULL;
7929 if (status == staged_status && (status == GOT_STATUS_DELETE))
7930 status = GOT_STATUS_NO_CHANGE;
7931 printf("%c%c %s\n", status, staged_status, path);
7932 return NULL;
7935 static const struct got_error *
7936 cmd_remove(int argc, char *argv[])
7938 const struct got_error *error = NULL;
7939 struct got_worktree *worktree = NULL;
7940 struct got_repository *repo = NULL;
7941 const char *status_codes = NULL;
7942 char *cwd = NULL;
7943 struct got_pathlist_head paths;
7944 struct got_pathlist_entry *pe;
7945 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7946 int ignore_missing_paths = 0;
7947 int *pack_fds = NULL;
7949 TAILQ_INIT(&paths);
7951 #ifndef PROFILE
7952 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7953 NULL) == -1)
7954 err(1, "pledge");
7955 #endif
7957 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7958 switch (ch) {
7959 case 'f':
7960 delete_local_mods = 1;
7961 ignore_missing_paths = 1;
7962 break;
7963 case 'k':
7964 keep_on_disk = 1;
7965 break;
7966 case 'R':
7967 can_recurse = 1;
7968 break;
7969 case 's':
7970 for (i = 0; i < strlen(optarg); i++) {
7971 switch (optarg[i]) {
7972 case GOT_STATUS_MODIFY:
7973 delete_local_mods = 1;
7974 break;
7975 case GOT_STATUS_MISSING:
7976 ignore_missing_paths = 1;
7977 break;
7978 default:
7979 errx(1, "invalid status code '%c'",
7980 optarg[i]);
7983 status_codes = optarg;
7984 break;
7985 default:
7986 usage_remove();
7987 /* NOTREACHED */
7991 argc -= optind;
7992 argv += optind;
7994 if (argc < 1)
7995 usage_remove();
7997 cwd = getcwd(NULL, 0);
7998 if (cwd == NULL) {
7999 error = got_error_from_errno("getcwd");
8000 goto done;
8003 error = got_repo_pack_fds_open(&pack_fds);
8004 if (error != NULL)
8005 goto done;
8007 error = got_worktree_open(&worktree, cwd);
8008 if (error) {
8009 if (error->code == GOT_ERR_NOT_WORKTREE)
8010 error = wrap_not_worktree_error(error, "remove", cwd);
8011 goto done;
8014 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8015 NULL, pack_fds);
8016 if (error)
8017 goto done;
8019 error = apply_unveil(got_repo_get_path(repo), 1,
8020 got_worktree_get_root_path(worktree));
8021 if (error)
8022 goto done;
8024 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8025 if (error)
8026 goto done;
8028 if (!can_recurse) {
8029 char *ondisk_path;
8030 struct stat sb;
8031 TAILQ_FOREACH(pe, &paths, entry) {
8032 if (asprintf(&ondisk_path, "%s/%s",
8033 got_worktree_get_root_path(worktree),
8034 pe->path) == -1) {
8035 error = got_error_from_errno("asprintf");
8036 goto done;
8038 if (lstat(ondisk_path, &sb) == -1) {
8039 if (errno == ENOENT) {
8040 free(ondisk_path);
8041 continue;
8043 error = got_error_from_errno2("lstat",
8044 ondisk_path);
8045 free(ondisk_path);
8046 goto done;
8048 free(ondisk_path);
8049 if (S_ISDIR(sb.st_mode)) {
8050 error = got_error_msg(GOT_ERR_BAD_PATH,
8051 "removing directories requires -R option");
8052 goto done;
8057 error = got_worktree_schedule_delete(worktree, &paths,
8058 delete_local_mods, status_codes, print_remove_status, NULL,
8059 repo, keep_on_disk, ignore_missing_paths);
8060 done:
8061 if (repo) {
8062 const struct got_error *close_err = got_repo_close(repo);
8063 if (error == NULL)
8064 error = close_err;
8066 if (worktree)
8067 got_worktree_close(worktree);
8068 if (pack_fds) {
8069 const struct got_error *pack_err =
8070 got_repo_pack_fds_close(pack_fds);
8071 if (error == NULL)
8072 error = pack_err;
8074 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8075 free(cwd);
8076 return error;
8079 __dead static void
8080 usage_patch(void)
8082 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8083 "[patchfile]\n", getprogname());
8084 exit(1);
8087 static const struct got_error *
8088 patch_from_stdin(int *patchfd)
8090 const struct got_error *err = NULL;
8091 ssize_t r;
8092 char buf[BUFSIZ];
8093 sig_t sighup, sigint, sigquit;
8095 *patchfd = got_opentempfd();
8096 if (*patchfd == -1)
8097 return got_error_from_errno("got_opentempfd");
8099 sighup = signal(SIGHUP, SIG_DFL);
8100 sigint = signal(SIGINT, SIG_DFL);
8101 sigquit = signal(SIGQUIT, SIG_DFL);
8103 for (;;) {
8104 r = read(0, buf, sizeof(buf));
8105 if (r == -1) {
8106 err = got_error_from_errno("read");
8107 break;
8109 if (r == 0)
8110 break;
8111 if (write(*patchfd, buf, r) == -1) {
8112 err = got_error_from_errno("write");
8113 break;
8117 signal(SIGHUP, sighup);
8118 signal(SIGINT, sigint);
8119 signal(SIGQUIT, sigquit);
8121 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8122 err = got_error_from_errno("lseek");
8124 if (err != NULL) {
8125 close(*patchfd);
8126 *patchfd = -1;
8129 return err;
8132 static const struct got_error *
8133 patch_progress(void *arg, const char *old, const char *new,
8134 unsigned char status, const struct got_error *error, int old_from,
8135 int old_lines, int new_from, int new_lines, int offset,
8136 int ws_mangled, const struct got_error *hunk_err)
8138 const char *path = new == NULL ? old : new;
8140 while (*path == '/')
8141 path++;
8143 if (status != 0)
8144 printf("%c %s\n", status, path);
8146 if (error != NULL)
8147 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8149 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8150 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8151 old_lines, new_from, new_lines);
8152 if (hunk_err != NULL)
8153 printf("%s\n", hunk_err->msg);
8154 else if (offset != 0)
8155 printf("applied with offset %d\n", offset);
8156 else
8157 printf("hunk contains mangled whitespace\n");
8160 return NULL;
8163 static const struct got_error *
8164 cmd_patch(int argc, char *argv[])
8166 const struct got_error *error = NULL, *close_error = NULL;
8167 struct got_worktree *worktree = NULL;
8168 struct got_repository *repo = NULL;
8169 struct got_reflist_head refs;
8170 struct got_object_id *commit_id = NULL;
8171 const char *commit_id_str = NULL;
8172 struct stat sb;
8173 const char *errstr;
8174 char *cwd = NULL;
8175 int ch, nop = 0, strip = -1, reverse = 0;
8176 int patchfd;
8177 int *pack_fds = NULL;
8179 TAILQ_INIT(&refs);
8181 #ifndef PROFILE
8182 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8183 "unveil", NULL) == -1)
8184 err(1, "pledge");
8185 #endif
8187 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8188 switch (ch) {
8189 case 'c':
8190 commit_id_str = optarg;
8191 break;
8192 case 'n':
8193 nop = 1;
8194 break;
8195 case 'p':
8196 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8197 if (errstr != NULL)
8198 errx(1, "pathname strip count is %s: %s",
8199 errstr, optarg);
8200 break;
8201 case 'R':
8202 reverse = 1;
8203 break;
8204 default:
8205 usage_patch();
8206 /* NOTREACHED */
8210 argc -= optind;
8211 argv += optind;
8213 if (argc == 0) {
8214 error = patch_from_stdin(&patchfd);
8215 if (error)
8216 return error;
8217 } else if (argc == 1) {
8218 patchfd = open(argv[0], O_RDONLY);
8219 if (patchfd == -1) {
8220 error = got_error_from_errno2("open", argv[0]);
8221 return error;
8223 if (fstat(patchfd, &sb) == -1) {
8224 error = got_error_from_errno2("fstat", argv[0]);
8225 goto done;
8227 if (!S_ISREG(sb.st_mode)) {
8228 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8229 goto done;
8231 } else
8232 usage_patch();
8234 if ((cwd = getcwd(NULL, 0)) == NULL) {
8235 error = got_error_from_errno("getcwd");
8236 goto done;
8239 error = got_repo_pack_fds_open(&pack_fds);
8240 if (error != NULL)
8241 goto done;
8243 error = got_worktree_open(&worktree, cwd);
8244 if (error != NULL)
8245 goto done;
8247 const char *repo_path = got_worktree_get_repo_path(worktree);
8248 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8249 if (error != NULL)
8250 goto done;
8252 error = apply_unveil(got_repo_get_path(repo), 0,
8253 got_worktree_get_root_path(worktree));
8254 if (error != NULL)
8255 goto done;
8257 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8258 if (error)
8259 goto done;
8261 if (commit_id_str != NULL) {
8262 error = got_repo_match_object_id(&commit_id, NULL,
8263 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8264 if (error)
8265 goto done;
8268 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8269 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8271 done:
8272 got_ref_list_free(&refs);
8273 free(commit_id);
8274 if (repo) {
8275 close_error = got_repo_close(repo);
8276 if (error == NULL)
8277 error = close_error;
8279 if (worktree != NULL) {
8280 close_error = got_worktree_close(worktree);
8281 if (error == NULL)
8282 error = close_error;
8284 if (pack_fds) {
8285 const struct got_error *pack_err =
8286 got_repo_pack_fds_close(pack_fds);
8287 if (error == NULL)
8288 error = pack_err;
8290 free(cwd);
8291 return error;
8294 __dead static void
8295 usage_revert(void)
8297 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8298 getprogname());
8299 exit(1);
8302 static const struct got_error *
8303 revert_progress(void *arg, unsigned char status, const char *path)
8305 if (status == GOT_STATUS_UNVERSIONED)
8306 return NULL;
8308 while (path[0] == '/')
8309 path++;
8310 printf("%c %s\n", status, path);
8311 return NULL;
8314 struct choose_patch_arg {
8315 FILE *patch_script_file;
8316 const char *action;
8319 static const struct got_error *
8320 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8321 int nchanges, const char *action)
8323 const struct got_error *err;
8324 char *line = NULL;
8325 size_t linesize = 0;
8326 ssize_t linelen;
8328 switch (status) {
8329 case GOT_STATUS_ADD:
8330 printf("A %s\n%s this addition? [y/n] ", path, action);
8331 break;
8332 case GOT_STATUS_DELETE:
8333 printf("D %s\n%s this deletion? [y/n] ", path, action);
8334 break;
8335 case GOT_STATUS_MODIFY:
8336 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8337 return got_error_from_errno("fseek");
8338 printf(GOT_COMMIT_SEP_STR);
8339 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8340 printf("%s", line);
8341 if (linelen == -1 && ferror(patch_file)) {
8342 err = got_error_from_errno("getline");
8343 free(line);
8344 return err;
8346 free(line);
8347 printf(GOT_COMMIT_SEP_STR);
8348 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8349 path, n, nchanges, action);
8350 break;
8351 default:
8352 return got_error_path(path, GOT_ERR_FILE_STATUS);
8355 fflush(stdout);
8356 return NULL;
8359 static const struct got_error *
8360 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8361 FILE *patch_file, int n, int nchanges)
8363 const struct got_error *err = NULL;
8364 char *line = NULL;
8365 size_t linesize = 0;
8366 ssize_t linelen;
8367 int resp = ' ';
8368 struct choose_patch_arg *a = arg;
8370 *choice = GOT_PATCH_CHOICE_NONE;
8372 if (a->patch_script_file) {
8373 char *nl;
8374 err = show_change(status, path, patch_file, n, nchanges,
8375 a->action);
8376 if (err)
8377 return err;
8378 linelen = getline(&line, &linesize, a->patch_script_file);
8379 if (linelen == -1) {
8380 if (ferror(a->patch_script_file))
8381 return got_error_from_errno("getline");
8382 return NULL;
8384 nl = strchr(line, '\n');
8385 if (nl)
8386 *nl = '\0';
8387 if (strcmp(line, "y") == 0) {
8388 *choice = GOT_PATCH_CHOICE_YES;
8389 printf("y\n");
8390 } else if (strcmp(line, "n") == 0) {
8391 *choice = GOT_PATCH_CHOICE_NO;
8392 printf("n\n");
8393 } else if (strcmp(line, "q") == 0 &&
8394 status == GOT_STATUS_MODIFY) {
8395 *choice = GOT_PATCH_CHOICE_QUIT;
8396 printf("q\n");
8397 } else
8398 printf("invalid response '%s'\n", line);
8399 free(line);
8400 return NULL;
8403 while (resp != 'y' && resp != 'n' && resp != 'q') {
8404 err = show_change(status, path, patch_file, n, nchanges,
8405 a->action);
8406 if (err)
8407 return err;
8408 resp = getchar();
8409 if (resp == '\n')
8410 resp = getchar();
8411 if (status == GOT_STATUS_MODIFY) {
8412 if (resp != 'y' && resp != 'n' && resp != 'q') {
8413 printf("invalid response '%c'\n", resp);
8414 resp = ' ';
8416 } else if (resp != 'y' && resp != 'n') {
8417 printf("invalid response '%c'\n", resp);
8418 resp = ' ';
8422 if (resp == 'y')
8423 *choice = GOT_PATCH_CHOICE_YES;
8424 else if (resp == 'n')
8425 *choice = GOT_PATCH_CHOICE_NO;
8426 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8427 *choice = GOT_PATCH_CHOICE_QUIT;
8429 return NULL;
8432 struct wt_commitable_path_arg {
8433 struct got_pathlist_head *commit_paths;
8434 int *has_changes;
8438 * Shortcut work tree status callback to determine if the set of paths scanned
8439 * has at least one versioned path that is being modified and, if not NULL, is
8440 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8441 * soon as a path is passed with a status that satisfies this criteria.
8443 static const struct got_error *
8444 worktree_has_commitable_path(void *arg, unsigned char status,
8445 unsigned char staged_status, const char *path,
8446 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8447 struct got_object_id *commit_id, int dirfd, const char *de_name)
8449 struct wt_commitable_path_arg *a = arg;
8451 if (status == staged_status && (status == GOT_STATUS_DELETE))
8452 status = GOT_STATUS_NO_CHANGE;
8454 if (!(status == GOT_STATUS_NO_CHANGE ||
8455 status == GOT_STATUS_UNVERSIONED) ||
8456 staged_status != GOT_STATUS_NO_CHANGE) {
8457 if (a->commit_paths != NULL) {
8458 struct got_pathlist_entry *pe;
8460 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8461 if (strncmp(path, pe->path,
8462 pe->path_len) == 0) {
8463 *a->has_changes = 1;
8464 break;
8467 } else
8468 *a->has_changes = 1;
8470 if (*a->has_changes)
8471 return got_error(GOT_ERR_FILE_MODIFIED);
8474 return NULL;
8478 * Check that the changeset of the commit identified by id is
8479 * comprised of at least one modified path that is being committed.
8481 static const struct got_error *
8482 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8483 struct got_object_id *id, struct got_worktree *worktree,
8484 struct got_repository *repo)
8486 const struct got_error *err;
8487 struct got_pathlist_head paths;
8488 struct got_commit_object *commit = NULL, *pcommit = NULL;
8489 struct got_tree_object *tree = NULL, *ptree = NULL;
8490 struct got_object_qid *pid;
8492 TAILQ_INIT(&paths);
8494 err = got_object_open_as_commit(&commit, repo, id);
8495 if (err)
8496 goto done;
8498 err = got_object_open_as_tree(&tree, repo,
8499 got_object_commit_get_tree_id(commit));
8500 if (err)
8501 goto done;
8503 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8504 if (pid != NULL) {
8505 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8506 if (err)
8507 goto done;
8509 err = got_object_open_as_tree(&ptree, repo,
8510 got_object_commit_get_tree_id(pcommit));
8511 if (err)
8512 goto done;
8515 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8516 got_diff_tree_collect_changed_paths, &paths, 0);
8517 if (err)
8518 goto done;
8520 err = got_worktree_status(worktree, &paths, repo, 0,
8521 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8522 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8524 * At least one changed path in the referenced commit is
8525 * modified in the work tree, that's all we need to know!
8527 err = NULL;
8530 done:
8531 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8532 if (commit)
8533 got_object_commit_close(commit);
8534 if (pcommit)
8535 got_object_commit_close(pcommit);
8536 if (tree)
8537 got_object_tree_close(tree);
8538 if (ptree)
8539 got_object_tree_close(ptree);
8540 return err;
8544 * Remove any "logmsg" reference comprised entirely of paths that have
8545 * been reverted in this work tree. If any path in the logmsg ref changeset
8546 * remains in a changed state in the worktree, do not remove the reference.
8548 static const struct got_error *
8549 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8551 const struct got_error *err;
8552 struct got_reflist_head refs;
8553 struct got_reflist_entry *re;
8554 struct got_commit_object *commit = NULL;
8555 struct got_object_id *commit_id = NULL;
8556 struct wt_commitable_path_arg wcpa;
8557 char *uuidstr = NULL;
8559 TAILQ_INIT(&refs);
8561 err = got_worktree_get_uuid(&uuidstr, worktree);
8562 if (err)
8563 goto done;
8565 err = got_ref_list(&refs, repo, "refs/got/worktree",
8566 got_ref_cmp_by_name, repo);
8567 if (err)
8568 goto done;
8570 TAILQ_FOREACH(re, &refs, entry) {
8571 const char *refname;
8572 int has_changes = 0;
8574 refname = got_ref_get_name(re->ref);
8576 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8577 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8578 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8579 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8580 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8581 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8582 else
8583 continue;
8585 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8586 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8587 else
8588 continue;
8590 err = got_repo_match_object_id(&commit_id, NULL, refname,
8591 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8592 if (err)
8593 goto done;
8595 err = got_object_open_as_commit(&commit, repo, commit_id);
8596 if (err)
8597 goto done;
8599 wcpa.commit_paths = NULL;
8600 wcpa.has_changes = &has_changes;
8602 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8603 worktree, repo);
8604 if (err)
8605 goto done;
8607 if (!has_changes) {
8608 err = got_ref_delete(re->ref, repo);
8609 if (err)
8610 goto done;
8613 got_object_commit_close(commit);
8614 commit = NULL;
8615 free(commit_id);
8616 commit_id = NULL;
8619 done:
8620 free(uuidstr);
8621 free(commit_id);
8622 got_ref_list_free(&refs);
8623 if (commit)
8624 got_object_commit_close(commit);
8625 return err;
8628 static const struct got_error *
8629 cmd_revert(int argc, char *argv[])
8631 const struct got_error *error = NULL;
8632 struct got_worktree *worktree = NULL;
8633 struct got_repository *repo = NULL;
8634 char *cwd = NULL, *path = NULL;
8635 struct got_pathlist_head paths;
8636 struct got_pathlist_entry *pe;
8637 int ch, can_recurse = 0, pflag = 0;
8638 FILE *patch_script_file = NULL;
8639 const char *patch_script_path = NULL;
8640 struct choose_patch_arg cpa;
8641 int *pack_fds = NULL;
8643 TAILQ_INIT(&paths);
8645 #ifndef PROFILE
8646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8647 "unveil", NULL) == -1)
8648 err(1, "pledge");
8649 #endif
8651 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8652 switch (ch) {
8653 case 'F':
8654 patch_script_path = optarg;
8655 break;
8656 case 'p':
8657 pflag = 1;
8658 break;
8659 case 'R':
8660 can_recurse = 1;
8661 break;
8662 default:
8663 usage_revert();
8664 /* NOTREACHED */
8668 argc -= optind;
8669 argv += optind;
8671 if (argc < 1)
8672 usage_revert();
8673 if (patch_script_path && !pflag)
8674 errx(1, "-F option can only be used together with -p option");
8676 cwd = getcwd(NULL, 0);
8677 if (cwd == NULL) {
8678 error = got_error_from_errno("getcwd");
8679 goto done;
8682 error = got_repo_pack_fds_open(&pack_fds);
8683 if (error != NULL)
8684 goto done;
8686 error = got_worktree_open(&worktree, cwd);
8687 if (error) {
8688 if (error->code == GOT_ERR_NOT_WORKTREE)
8689 error = wrap_not_worktree_error(error, "revert", cwd);
8690 goto done;
8693 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8694 NULL, pack_fds);
8695 if (error != NULL)
8696 goto done;
8698 if (patch_script_path) {
8699 patch_script_file = fopen(patch_script_path, "re");
8700 if (patch_script_file == NULL) {
8701 error = got_error_from_errno2("fopen",
8702 patch_script_path);
8703 goto done;
8708 * XXX "c" perm needed on repo dir to delete merge references.
8710 error = apply_unveil(got_repo_get_path(repo), 0,
8711 got_worktree_get_root_path(worktree));
8712 if (error)
8713 goto done;
8715 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8716 if (error)
8717 goto done;
8719 if (!can_recurse) {
8720 char *ondisk_path;
8721 struct stat sb;
8722 TAILQ_FOREACH(pe, &paths, entry) {
8723 if (asprintf(&ondisk_path, "%s/%s",
8724 got_worktree_get_root_path(worktree),
8725 pe->path) == -1) {
8726 error = got_error_from_errno("asprintf");
8727 goto done;
8729 if (lstat(ondisk_path, &sb) == -1) {
8730 if (errno == ENOENT) {
8731 free(ondisk_path);
8732 continue;
8734 error = got_error_from_errno2("lstat",
8735 ondisk_path);
8736 free(ondisk_path);
8737 goto done;
8739 free(ondisk_path);
8740 if (S_ISDIR(sb.st_mode)) {
8741 error = got_error_msg(GOT_ERR_BAD_PATH,
8742 "reverting directories requires -R option");
8743 goto done;
8748 cpa.patch_script_file = patch_script_file;
8749 cpa.action = "revert";
8750 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8751 pflag ? choose_patch : NULL, &cpa, repo);
8753 error = rm_logmsg_ref(worktree, repo);
8754 done:
8755 if (patch_script_file && fclose(patch_script_file) == EOF &&
8756 error == NULL)
8757 error = got_error_from_errno2("fclose", patch_script_path);
8758 if (repo) {
8759 const struct got_error *close_err = got_repo_close(repo);
8760 if (error == NULL)
8761 error = close_err;
8763 if (worktree)
8764 got_worktree_close(worktree);
8765 if (pack_fds) {
8766 const struct got_error *pack_err =
8767 got_repo_pack_fds_close(pack_fds);
8768 if (error == NULL)
8769 error = pack_err;
8771 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8772 free(path);
8773 free(cwd);
8774 return error;
8777 __dead static void
8778 usage_commit(void)
8780 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8781 "[-m message] [path ...]\n", getprogname());
8782 exit(1);
8785 struct collect_commit_logmsg_arg {
8786 const char *cmdline_log;
8787 const char *prepared_log;
8788 const char *merged_log;
8789 int non_interactive;
8790 const char *editor;
8791 const char *worktree_path;
8792 const char *branch_name;
8793 const char *repo_path;
8794 char *logmsg_path;
8798 static const struct got_error *
8799 read_prepared_logmsg(char **logmsg, const char *path)
8801 const struct got_error *err = NULL;
8802 FILE *f = NULL;
8803 struct stat sb;
8804 size_t r;
8806 *logmsg = NULL;
8807 memset(&sb, 0, sizeof(sb));
8809 f = fopen(path, "re");
8810 if (f == NULL)
8811 return got_error_from_errno2("fopen", path);
8813 if (fstat(fileno(f), &sb) == -1) {
8814 err = got_error_from_errno2("fstat", path);
8815 goto done;
8817 if (sb.st_size == 0) {
8818 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8819 goto done;
8822 *logmsg = malloc(sb.st_size + 1);
8823 if (*logmsg == NULL) {
8824 err = got_error_from_errno("malloc");
8825 goto done;
8828 r = fread(*logmsg, 1, sb.st_size, f);
8829 if (r != sb.st_size) {
8830 if (ferror(f))
8831 err = got_error_from_errno2("fread", path);
8832 else
8833 err = got_error(GOT_ERR_IO);
8834 goto done;
8836 (*logmsg)[sb.st_size] = '\0';
8837 done:
8838 if (fclose(f) == EOF && err == NULL)
8839 err = got_error_from_errno2("fclose", path);
8840 if (err) {
8841 free(*logmsg);
8842 *logmsg = NULL;
8844 return err;
8847 static const struct got_error *
8848 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8849 const char *diff_path, char **logmsg, void *arg)
8851 char *initial_content = NULL;
8852 struct got_pathlist_entry *pe;
8853 const struct got_error *err = NULL;
8854 char *template = NULL;
8855 char *prepared_msg = NULL, *merged_msg = NULL;
8856 struct collect_commit_logmsg_arg *a = arg;
8857 int initial_content_len;
8858 int fd = -1;
8859 size_t len;
8861 /* if a message was specified on the command line, just use it */
8862 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8863 len = strlen(a->cmdline_log) + 1;
8864 *logmsg = malloc(len + 1);
8865 if (*logmsg == NULL)
8866 return got_error_from_errno("malloc");
8867 strlcpy(*logmsg, a->cmdline_log, len);
8868 return NULL;
8869 } else if (a->prepared_log != NULL && a->non_interactive)
8870 return read_prepared_logmsg(logmsg, a->prepared_log);
8872 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8873 return got_error_from_errno("asprintf");
8875 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8876 if (err)
8877 goto done;
8879 if (a->prepared_log) {
8880 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8881 if (err)
8882 goto done;
8883 } else if (a->merged_log) {
8884 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8885 if (err)
8886 goto done;
8889 initial_content_len = asprintf(&initial_content,
8890 "%s%s\n# changes to be committed on branch %s:\n",
8891 prepared_msg ? prepared_msg : "",
8892 merged_msg ? merged_msg : "", a->branch_name);
8893 if (initial_content_len == -1) {
8894 err = got_error_from_errno("asprintf");
8895 goto done;
8898 if (write(fd, initial_content, initial_content_len) == -1) {
8899 err = got_error_from_errno2("write", a->logmsg_path);
8900 goto done;
8903 TAILQ_FOREACH(pe, commitable_paths, entry) {
8904 struct got_commitable *ct = pe->data;
8905 dprintf(fd, "# %c %s\n",
8906 got_commitable_get_status(ct),
8907 got_commitable_get_path(ct));
8910 if (diff_path) {
8911 dprintf(fd, "# detailed changes can be viewed in %s\n",
8912 diff_path);
8915 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8916 initial_content_len, a->prepared_log ? 0 : 1);
8917 done:
8918 free(initial_content);
8919 free(template);
8920 free(prepared_msg);
8921 free(merged_msg);
8923 if (fd != -1 && close(fd) == -1 && err == NULL)
8924 err = got_error_from_errno2("close", a->logmsg_path);
8926 /* Editor is done; we can now apply unveil(2) */
8927 if (err == NULL)
8928 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8929 if (err) {
8930 free(*logmsg);
8931 *logmsg = NULL;
8933 return err;
8936 static const struct got_error *
8937 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8938 const char *type, int has_content)
8940 const struct got_error *err = NULL;
8941 char *logmsg = NULL;
8943 err = got_object_commit_get_logmsg(&logmsg, commit);
8944 if (err)
8945 return err;
8947 if (fprintf(f, "%s# log message of %s commit %s:%s",
8948 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8949 err = got_ferror(f, GOT_ERR_IO);
8951 free(logmsg);
8952 return err;
8956 * Lookup "logmsg" references of backed-out and cherrypicked commits
8957 * belonging to the current work tree. If found, and the worktree has
8958 * at least one modified file that was changed in the referenced commit,
8959 * add its log message to a new temporary file at *logmsg_path.
8960 * Add all refs found to matched_refs to be scheduled for removal on
8961 * successful commit.
8963 static const struct got_error *
8964 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8965 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8966 struct got_repository *repo)
8968 const struct got_error *err;
8969 struct got_commit_object *commit = NULL;
8970 struct got_object_id *id = NULL;
8971 struct got_reflist_head refs;
8972 struct got_reflist_entry *re, *re_match;
8973 FILE *f = NULL;
8974 char *uuidstr = NULL;
8975 int added_logmsg = 0;
8977 TAILQ_INIT(&refs);
8979 *logmsg_path = NULL;
8981 err = got_worktree_get_uuid(&uuidstr, worktree);
8982 if (err)
8983 goto done;
8985 err = got_ref_list(&refs, repo, "refs/got/worktree",
8986 got_ref_cmp_by_name, repo);
8987 if (err)
8988 goto done;
8990 TAILQ_FOREACH(re, &refs, entry) {
8991 const char *refname, *type;
8992 struct wt_commitable_path_arg wcpa;
8993 int add_logmsg = 0;
8995 refname = got_ref_get_name(re->ref);
8997 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8998 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8999 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9000 type = "cherrypicked";
9001 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9002 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9003 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9004 type = "backed-out";
9005 } else
9006 continue;
9008 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9009 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9010 else
9011 continue;
9013 err = got_repo_match_object_id(&id, NULL, refname,
9014 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9015 if (err)
9016 goto done;
9018 err = got_object_open_as_commit(&commit, repo, id);
9019 if (err)
9020 goto done;
9022 wcpa.commit_paths = paths;
9023 wcpa.has_changes = &add_logmsg;
9025 err = commit_path_changed_in_worktree(&wcpa, id,
9026 worktree, repo);
9027 if (err)
9028 goto done;
9030 if (add_logmsg) {
9031 if (f == NULL) {
9032 err = got_opentemp_named(logmsg_path, &f,
9033 "got-commit-logmsg", "");
9034 if (err)
9035 goto done;
9037 err = cat_logmsg(f, commit, refname, type,
9038 added_logmsg);
9039 if (err)
9040 goto done;
9041 if (!added_logmsg)
9042 ++added_logmsg;
9044 err = got_reflist_entry_dup(&re_match, re);
9045 if (err)
9046 goto done;
9047 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9050 got_object_commit_close(commit);
9051 commit = NULL;
9052 free(id);
9053 id = NULL;
9056 done:
9057 free(id);
9058 free(uuidstr);
9059 got_ref_list_free(&refs);
9060 if (commit)
9061 got_object_commit_close(commit);
9062 if (f && fclose(f) == EOF && err == NULL)
9063 err = got_error_from_errno("fclose");
9064 if (!added_logmsg) {
9065 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9066 err = got_error_from_errno2("unlink", *logmsg_path);
9067 *logmsg_path = NULL;
9069 return err;
9072 static const struct got_error *
9073 cmd_commit(int argc, char *argv[])
9075 const struct got_error *error = NULL;
9076 struct got_worktree *worktree = NULL;
9077 struct got_repository *repo = NULL;
9078 char *cwd = NULL, *id_str = NULL;
9079 struct got_object_id *id = NULL;
9080 const char *logmsg = NULL;
9081 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9082 struct collect_commit_logmsg_arg cl_arg;
9083 const char *author = NULL;
9084 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9085 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9086 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9087 int show_diff = 1, commit_conflicts = 0;
9088 struct got_pathlist_head paths;
9089 struct got_reflist_head refs;
9090 struct got_reflist_entry *re;
9091 int *pack_fds = NULL;
9093 TAILQ_INIT(&refs);
9094 TAILQ_INIT(&paths);
9095 cl_arg.logmsg_path = NULL;
9097 #ifndef PROFILE
9098 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9099 "unveil", NULL) == -1)
9100 err(1, "pledge");
9101 #endif
9103 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9104 switch (ch) {
9105 case 'A':
9106 author = optarg;
9107 error = valid_author(author);
9108 if (error)
9109 return error;
9110 break;
9111 case 'C':
9112 commit_conflicts = 1;
9113 break;
9114 case 'F':
9115 if (logmsg != NULL)
9116 option_conflict('F', 'm');
9117 prepared_logmsg = realpath(optarg, NULL);
9118 if (prepared_logmsg == NULL)
9119 return got_error_from_errno2("realpath",
9120 optarg);
9121 break;
9122 case 'm':
9123 if (prepared_logmsg)
9124 option_conflict('m', 'F');
9125 logmsg = optarg;
9126 break;
9127 case 'N':
9128 non_interactive = 1;
9129 break;
9130 case 'n':
9131 show_diff = 0;
9132 break;
9133 case 'S':
9134 allow_bad_symlinks = 1;
9135 break;
9136 default:
9137 usage_commit();
9138 /* NOTREACHED */
9142 argc -= optind;
9143 argv += optind;
9145 cwd = getcwd(NULL, 0);
9146 if (cwd == NULL) {
9147 error = got_error_from_errno("getcwd");
9148 goto done;
9151 error = got_repo_pack_fds_open(&pack_fds);
9152 if (error != NULL)
9153 goto done;
9155 error = got_worktree_open(&worktree, cwd);
9156 if (error) {
9157 if (error->code == GOT_ERR_NOT_WORKTREE)
9158 error = wrap_not_worktree_error(error, "commit", cwd);
9159 goto done;
9162 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9163 if (error)
9164 goto done;
9165 if (rebase_in_progress) {
9166 error = got_error(GOT_ERR_REBASING);
9167 goto done;
9170 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9171 worktree);
9172 if (error)
9173 goto done;
9175 error = get_gitconfig_path(&gitconfig_path);
9176 if (error)
9177 goto done;
9178 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9179 gitconfig_path, pack_fds);
9180 if (error != NULL)
9181 goto done;
9183 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9184 if (error)
9185 goto done;
9186 if (merge_in_progress) {
9187 error = got_error(GOT_ERR_MERGE_BUSY);
9188 goto done;
9191 error = get_author(&committer, repo, worktree);
9192 if (error)
9193 goto done;
9195 if (author == NULL)
9196 author = committer;
9199 * unveil(2) traverses exec(2); if an editor is used we have
9200 * to apply unveil after the log message has been written.
9202 if (logmsg == NULL || strlen(logmsg) == 0)
9203 error = get_editor(&editor);
9204 else
9205 error = apply_unveil(got_repo_get_path(repo), 0,
9206 got_worktree_get_root_path(worktree));
9207 if (error)
9208 goto done;
9210 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9211 if (error)
9212 goto done;
9214 if (prepared_logmsg == NULL) {
9215 error = lookup_logmsg_ref(&merged_logmsg,
9216 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9217 if (error)
9218 goto done;
9221 cl_arg.editor = editor;
9222 cl_arg.cmdline_log = logmsg;
9223 cl_arg.prepared_log = prepared_logmsg;
9224 cl_arg.merged_log = merged_logmsg;
9225 cl_arg.non_interactive = non_interactive;
9226 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9227 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9228 if (!histedit_in_progress) {
9229 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9230 error = got_error(GOT_ERR_COMMIT_BRANCH);
9231 goto done;
9233 cl_arg.branch_name += 11;
9235 cl_arg.repo_path = got_repo_get_path(repo);
9236 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9237 allow_bad_symlinks, show_diff, commit_conflicts,
9238 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9239 if (error) {
9240 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9241 cl_arg.logmsg_path != NULL)
9242 preserve_logmsg = 1;
9243 goto done;
9246 error = got_object_id_str(&id_str, id);
9247 if (error)
9248 goto done;
9249 printf("Created commit %s\n", id_str);
9251 TAILQ_FOREACH(re, &refs, entry) {
9252 error = got_ref_delete(re->ref, repo);
9253 if (error)
9254 goto done;
9257 done:
9258 if (preserve_logmsg) {
9259 fprintf(stderr, "%s: log message preserved in %s\n",
9260 getprogname(), cl_arg.logmsg_path);
9261 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9262 error == NULL)
9263 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9264 free(cl_arg.logmsg_path);
9265 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9266 error = got_error_from_errno2("unlink", merged_logmsg);
9267 free(merged_logmsg);
9268 if (repo) {
9269 const struct got_error *close_err = got_repo_close(repo);
9270 if (error == NULL)
9271 error = close_err;
9273 if (worktree)
9274 got_worktree_close(worktree);
9275 if (pack_fds) {
9276 const struct got_error *pack_err =
9277 got_repo_pack_fds_close(pack_fds);
9278 if (error == NULL)
9279 error = pack_err;
9281 got_ref_list_free(&refs);
9282 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9283 free(cwd);
9284 free(id_str);
9285 free(gitconfig_path);
9286 free(editor);
9287 free(committer);
9288 free(prepared_logmsg);
9289 return error;
9292 __dead static void
9293 usage_send(void)
9295 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9296 "[-r repository-path] [-t tag] [remote-repository]\n",
9297 getprogname());
9298 exit(1);
9301 static void
9302 print_load_info(int print_colored, int print_found, int print_trees,
9303 int ncolored, int nfound, int ntrees)
9305 if (print_colored) {
9306 printf("%d commit%s colored", ncolored,
9307 ncolored == 1 ? "" : "s");
9309 if (print_found) {
9310 printf("%s%d object%s found",
9311 ncolored > 0 ? "; " : "",
9312 nfound, nfound == 1 ? "" : "s");
9314 if (print_trees) {
9315 printf("; %d tree%s scanned", ntrees,
9316 ntrees == 1 ? "" : "s");
9320 struct got_send_progress_arg {
9321 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9322 int verbosity;
9323 int last_ncolored;
9324 int last_nfound;
9325 int last_ntrees;
9326 int loading_done;
9327 int last_ncommits;
9328 int last_nobj_total;
9329 int last_p_deltify;
9330 int last_p_written;
9331 int last_p_sent;
9332 int printed_something;
9333 int sent_something;
9334 struct got_pathlist_head *delete_branches;
9337 static const struct got_error *
9338 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9339 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9340 int nobj_written, off_t bytes_sent, const char *refname,
9341 const char *errmsg, int success)
9343 struct got_send_progress_arg *a = arg;
9344 char scaled_packsize[FMT_SCALED_STRSIZE];
9345 char scaled_sent[FMT_SCALED_STRSIZE];
9346 int p_deltify = 0, p_written = 0, p_sent = 0;
9347 int print_colored = 0, print_found = 0, print_trees = 0;
9348 int print_searching = 0, print_total = 0;
9349 int print_deltify = 0, print_written = 0, print_sent = 0;
9351 if (a->verbosity < 0)
9352 return NULL;
9354 if (refname) {
9355 const char *status = success ? "accepted" : "rejected";
9357 if (success) {
9358 struct got_pathlist_entry *pe;
9359 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9360 const char *branchname = pe->path;
9361 if (got_path_cmp(branchname, refname,
9362 strlen(branchname), strlen(refname)) == 0) {
9363 status = "deleted";
9364 a->sent_something = 1;
9365 break;
9370 if (a->printed_something)
9371 putchar('\n');
9372 printf("Server has %s %s", status, refname);
9373 if (errmsg)
9374 printf(": %s", errmsg);
9375 a->printed_something = 1;
9376 return NULL;
9379 if (a->last_ncolored != ncolored) {
9380 print_colored = 1;
9381 a->last_ncolored = ncolored;
9384 if (a->last_nfound != nfound) {
9385 print_colored = 1;
9386 print_found = 1;
9387 a->last_nfound = nfound;
9390 if (a->last_ntrees != ntrees) {
9391 print_colored = 1;
9392 print_found = 1;
9393 print_trees = 1;
9394 a->last_ntrees = ntrees;
9397 if ((print_colored || print_found || print_trees) &&
9398 !a->loading_done) {
9399 printf("\r");
9400 print_load_info(print_colored, print_found, print_trees,
9401 ncolored, nfound, ntrees);
9402 a->printed_something = 1;
9403 fflush(stdout);
9404 return NULL;
9405 } else if (!a->loading_done) {
9406 printf("\r");
9407 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9408 printf("\n");
9409 a->loading_done = 1;
9412 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9413 return got_error_from_errno("fmt_scaled");
9414 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9415 return got_error_from_errno("fmt_scaled");
9417 if (a->last_ncommits != ncommits) {
9418 print_searching = 1;
9419 a->last_ncommits = ncommits;
9422 if (a->last_nobj_total != nobj_total) {
9423 print_searching = 1;
9424 print_total = 1;
9425 a->last_nobj_total = nobj_total;
9428 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9429 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9430 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9431 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9432 return got_error(GOT_ERR_NO_SPACE);
9435 if (nobj_deltify > 0 || nobj_written > 0) {
9436 if (nobj_deltify > 0) {
9437 p_deltify = (nobj_deltify * 100) / nobj_total;
9438 if (p_deltify != a->last_p_deltify) {
9439 a->last_p_deltify = p_deltify;
9440 print_searching = 1;
9441 print_total = 1;
9442 print_deltify = 1;
9445 if (nobj_written > 0) {
9446 p_written = (nobj_written * 100) / nobj_total;
9447 if (p_written != a->last_p_written) {
9448 a->last_p_written = p_written;
9449 print_searching = 1;
9450 print_total = 1;
9451 print_deltify = 1;
9452 print_written = 1;
9457 if (bytes_sent > 0) {
9458 p_sent = (bytes_sent * 100) / packfile_size;
9459 if (p_sent != a->last_p_sent) {
9460 a->last_p_sent = p_sent;
9461 print_searching = 1;
9462 print_total = 1;
9463 print_deltify = 1;
9464 print_written = 1;
9465 print_sent = 1;
9467 a->sent_something = 1;
9470 if (print_searching || print_total || print_deltify || print_written ||
9471 print_sent)
9472 printf("\r");
9473 if (print_searching)
9474 printf("packing %d reference%s", ncommits,
9475 ncommits == 1 ? "" : "s");
9476 if (print_total)
9477 printf("; %d object%s", nobj_total,
9478 nobj_total == 1 ? "" : "s");
9479 if (print_deltify)
9480 printf("; deltify: %d%%", p_deltify);
9481 if (print_sent)
9482 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9483 scaled_packsize, p_sent);
9484 else if (print_written)
9485 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9486 scaled_packsize, p_written);
9487 if (print_searching || print_total || print_deltify ||
9488 print_written || print_sent) {
9489 a->printed_something = 1;
9490 fflush(stdout);
9492 return NULL;
9495 static const struct got_error *
9496 cmd_send(int argc, char *argv[])
9498 const struct got_error *error = NULL;
9499 char *cwd = NULL, *repo_path = NULL;
9500 const char *remote_name;
9501 char *proto = NULL, *host = NULL, *port = NULL;
9502 char *repo_name = NULL, *server_path = NULL;
9503 const struct got_remote_repo *remotes, *remote = NULL;
9504 int nremotes, nbranches = 0, ndelete_branches = 0;
9505 struct got_repository *repo = NULL;
9506 struct got_worktree *worktree = NULL;
9507 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9508 struct got_pathlist_head branches;
9509 struct got_pathlist_head tags;
9510 struct got_reflist_head all_branches;
9511 struct got_reflist_head all_tags;
9512 struct got_pathlist_head delete_args;
9513 struct got_pathlist_head delete_branches;
9514 struct got_reflist_entry *re;
9515 struct got_pathlist_entry *pe;
9516 int i, ch, sendfd = -1, sendstatus;
9517 pid_t sendpid = -1;
9518 struct got_send_progress_arg spa;
9519 int verbosity = 0, overwrite_refs = 0;
9520 int send_all_branches = 0, send_all_tags = 0;
9521 struct got_reference *ref = NULL;
9522 int *pack_fds = NULL;
9524 TAILQ_INIT(&branches);
9525 TAILQ_INIT(&tags);
9526 TAILQ_INIT(&all_branches);
9527 TAILQ_INIT(&all_tags);
9528 TAILQ_INIT(&delete_args);
9529 TAILQ_INIT(&delete_branches);
9531 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9532 switch (ch) {
9533 case 'a':
9534 send_all_branches = 1;
9535 break;
9536 case 'b':
9537 error = got_pathlist_append(&branches, optarg, NULL);
9538 if (error)
9539 return error;
9540 nbranches++;
9541 break;
9542 case 'd':
9543 error = got_pathlist_append(&delete_args, optarg, NULL);
9544 if (error)
9545 return error;
9546 break;
9547 case 'f':
9548 overwrite_refs = 1;
9549 break;
9550 case 'q':
9551 verbosity = -1;
9552 break;
9553 case 'r':
9554 repo_path = realpath(optarg, NULL);
9555 if (repo_path == NULL)
9556 return got_error_from_errno2("realpath",
9557 optarg);
9558 got_path_strip_trailing_slashes(repo_path);
9559 break;
9560 case 'T':
9561 send_all_tags = 1;
9562 break;
9563 case 't':
9564 error = got_pathlist_append(&tags, optarg, NULL);
9565 if (error)
9566 return error;
9567 break;
9568 case 'v':
9569 if (verbosity < 0)
9570 verbosity = 0;
9571 else if (verbosity < 3)
9572 verbosity++;
9573 break;
9574 default:
9575 usage_send();
9576 /* NOTREACHED */
9579 argc -= optind;
9580 argv += optind;
9582 if (send_all_branches && !TAILQ_EMPTY(&branches))
9583 option_conflict('a', 'b');
9584 if (send_all_tags && !TAILQ_EMPTY(&tags))
9585 option_conflict('T', 't');
9588 if (argc == 0)
9589 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9590 else if (argc == 1)
9591 remote_name = argv[0];
9592 else
9593 usage_send();
9595 cwd = getcwd(NULL, 0);
9596 if (cwd == NULL) {
9597 error = got_error_from_errno("getcwd");
9598 goto done;
9601 error = got_repo_pack_fds_open(&pack_fds);
9602 if (error != NULL)
9603 goto done;
9605 if (repo_path == NULL) {
9606 error = got_worktree_open(&worktree, cwd);
9607 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9608 goto done;
9609 else
9610 error = NULL;
9611 if (worktree) {
9612 repo_path =
9613 strdup(got_worktree_get_repo_path(worktree));
9614 if (repo_path == NULL)
9615 error = got_error_from_errno("strdup");
9616 if (error)
9617 goto done;
9618 } else {
9619 repo_path = strdup(cwd);
9620 if (repo_path == NULL) {
9621 error = got_error_from_errno("strdup");
9622 goto done;
9627 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9628 if (error)
9629 goto done;
9631 if (worktree) {
9632 worktree_conf = got_worktree_get_gotconfig(worktree);
9633 if (worktree_conf) {
9634 got_gotconfig_get_remotes(&nremotes, &remotes,
9635 worktree_conf);
9636 for (i = 0; i < nremotes; i++) {
9637 if (strcmp(remotes[i].name, remote_name) == 0) {
9638 remote = &remotes[i];
9639 break;
9644 if (remote == NULL) {
9645 repo_conf = got_repo_get_gotconfig(repo);
9646 if (repo_conf) {
9647 got_gotconfig_get_remotes(&nremotes, &remotes,
9648 repo_conf);
9649 for (i = 0; i < nremotes; i++) {
9650 if (strcmp(remotes[i].name, remote_name) == 0) {
9651 remote = &remotes[i];
9652 break;
9657 if (remote == NULL) {
9658 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9659 for (i = 0; i < nremotes; i++) {
9660 if (strcmp(remotes[i].name, remote_name) == 0) {
9661 remote = &remotes[i];
9662 break;
9666 if (remote == NULL) {
9667 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9668 goto done;
9671 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9672 &repo_name, remote->send_url);
9673 if (error)
9674 goto done;
9676 if (strcmp(proto, "git") == 0) {
9677 #ifndef PROFILE
9678 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9679 "sendfd dns inet unveil", NULL) == -1)
9680 err(1, "pledge");
9681 #endif
9682 } else if (strcmp(proto, "git+ssh") == 0 ||
9683 strcmp(proto, "ssh") == 0) {
9684 #ifndef PROFILE
9685 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9686 "sendfd unveil", NULL) == -1)
9687 err(1, "pledge");
9688 #endif
9689 } else if (strcmp(proto, "http") == 0 ||
9690 strcmp(proto, "git+http") == 0) {
9691 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9692 goto done;
9693 } else {
9694 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9695 goto done;
9698 error = got_dial_apply_unveil(proto);
9699 if (error)
9700 goto done;
9702 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9703 if (error)
9704 goto done;
9706 if (send_all_branches) {
9707 error = got_ref_list(&all_branches, repo, "refs/heads",
9708 got_ref_cmp_by_name, NULL);
9709 if (error)
9710 goto done;
9711 TAILQ_FOREACH(re, &all_branches, entry) {
9712 const char *branchname = got_ref_get_name(re->ref);
9713 error = got_pathlist_append(&branches,
9714 branchname, NULL);
9715 if (error)
9716 goto done;
9717 nbranches++;
9719 } else if (nbranches == 0) {
9720 for (i = 0; i < remote->nsend_branches; i++) {
9721 error = got_pathlist_append(&branches,
9722 remote->send_branches[i], NULL);
9723 if (error)
9724 goto done;
9728 if (send_all_tags) {
9729 error = got_ref_list(&all_tags, repo, "refs/tags",
9730 got_ref_cmp_by_name, NULL);
9731 if (error)
9732 goto done;
9733 TAILQ_FOREACH(re, &all_tags, entry) {
9734 const char *tagname = got_ref_get_name(re->ref);
9735 error = got_pathlist_append(&tags,
9736 tagname, NULL);
9737 if (error)
9738 goto done;
9743 * To prevent accidents only branches in refs/heads/ can be deleted
9744 * with 'got send -d'.
9745 * Deleting anything else requires local repository access or Git.
9747 TAILQ_FOREACH(pe, &delete_args, entry) {
9748 const char *branchname = pe->path;
9749 char *s;
9750 struct got_pathlist_entry *new;
9751 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9752 s = strdup(branchname);
9753 if (s == NULL) {
9754 error = got_error_from_errno("strdup");
9755 goto done;
9757 } else {
9758 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9759 error = got_error_from_errno("asprintf");
9760 goto done;
9763 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9764 if (error || new == NULL /* duplicate */)
9765 free(s);
9766 if (error)
9767 goto done;
9768 ndelete_branches++;
9771 if (nbranches == 0 && ndelete_branches == 0) {
9772 struct got_reference *head_ref;
9773 if (worktree)
9774 error = got_ref_open(&head_ref, repo,
9775 got_worktree_get_head_ref_name(worktree), 0);
9776 else
9777 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9778 if (error)
9779 goto done;
9780 if (got_ref_is_symbolic(head_ref)) {
9781 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9782 got_ref_close(head_ref);
9783 if (error)
9784 goto done;
9785 } else
9786 ref = head_ref;
9787 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9788 NULL);
9789 if (error)
9790 goto done;
9791 nbranches++;
9794 if (verbosity >= 0) {
9795 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9796 remote->name, proto, host,
9797 port ? ":" : "", port ? port : "",
9798 *server_path == '/' ? "" : "/", server_path);
9801 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9802 server_path, verbosity);
9803 if (error)
9804 goto done;
9806 memset(&spa, 0, sizeof(spa));
9807 spa.last_scaled_packsize[0] = '\0';
9808 spa.last_p_deltify = -1;
9809 spa.last_p_written = -1;
9810 spa.verbosity = verbosity;
9811 spa.delete_branches = &delete_branches;
9812 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9813 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9814 check_cancelled, NULL);
9815 if (spa.printed_something)
9816 putchar('\n');
9817 if (error)
9818 goto done;
9819 if (!spa.sent_something && verbosity >= 0)
9820 printf("Already up-to-date\n");
9821 done:
9822 if (sendpid > 0) {
9823 if (kill(sendpid, SIGTERM) == -1)
9824 error = got_error_from_errno("kill");
9825 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9826 error = got_error_from_errno("waitpid");
9828 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9829 error = got_error_from_errno("close");
9830 if (repo) {
9831 const struct got_error *close_err = got_repo_close(repo);
9832 if (error == NULL)
9833 error = close_err;
9835 if (worktree)
9836 got_worktree_close(worktree);
9837 if (pack_fds) {
9838 const struct got_error *pack_err =
9839 got_repo_pack_fds_close(pack_fds);
9840 if (error == NULL)
9841 error = pack_err;
9843 if (ref)
9844 got_ref_close(ref);
9845 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9846 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9847 got_ref_list_free(&all_branches);
9848 got_ref_list_free(&all_tags);
9849 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9850 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9851 free(cwd);
9852 free(repo_path);
9853 free(proto);
9854 free(host);
9855 free(port);
9856 free(server_path);
9857 free(repo_name);
9858 return error;
9862 * Print and if delete is set delete all ref_prefix references.
9863 * If wanted_ref is not NULL, only print or delete this reference.
9865 static const struct got_error *
9866 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9867 const char *wanted_ref, int delete, struct got_worktree *worktree,
9868 struct got_repository *repo)
9870 const struct got_error *err;
9871 struct got_pathlist_head paths;
9872 struct got_reflist_head refs;
9873 struct got_reflist_entry *re;
9874 struct got_reflist_object_id_map *refs_idmap = NULL;
9875 struct got_commit_object *commit = NULL;
9876 struct got_object_id *id = NULL;
9877 const char *header_prefix;
9878 char *uuidstr = NULL;
9879 int found = 0;
9881 TAILQ_INIT(&refs);
9882 TAILQ_INIT(&paths);
9884 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9885 if (err)
9886 goto done;
9888 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9889 if (err)
9890 goto done;
9892 if (worktree != NULL) {
9893 err = got_worktree_get_uuid(&uuidstr, worktree);
9894 if (err)
9895 goto done;
9898 if (wanted_ref) {
9899 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9900 wanted_ref += 11;
9903 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9904 header_prefix = "backout";
9905 else
9906 header_prefix = "cherrypick";
9908 TAILQ_FOREACH(re, &refs, entry) {
9909 const char *refname, *wt;
9911 refname = got_ref_get_name(re->ref);
9913 err = check_cancelled(NULL);
9914 if (err)
9915 goto done;
9917 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9918 refname += prefix_len + 1; /* skip '-' delimiter */
9919 else
9920 continue;
9922 wt = refname;
9924 if (worktree == NULL || strncmp(refname, uuidstr,
9925 GOT_WORKTREE_UUID_STRLEN) == 0)
9926 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9927 else
9928 continue;
9930 err = got_repo_match_object_id(&id, NULL, refname,
9931 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9932 if (err)
9933 goto done;
9935 err = got_object_open_as_commit(&commit, repo, id);
9936 if (err)
9937 goto done;
9939 if (wanted_ref)
9940 found = strncmp(wanted_ref, refname,
9941 strlen(wanted_ref)) == 0;
9942 if (wanted_ref && !found) {
9943 struct got_reflist_head *ci_refs;
9945 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9946 id);
9948 if (ci_refs) {
9949 char *refs_str = NULL;
9950 char const *r = NULL;
9952 err = build_refs_str(&refs_str, ci_refs, id,
9953 repo, 1);
9954 if (err)
9955 goto done;
9957 r = refs_str;
9958 while (r) {
9959 if (strncmp(r, wanted_ref,
9960 strlen(wanted_ref)) == 0) {
9961 found = 1;
9962 break;
9964 r = strchr(r, ' ');
9965 if (r)
9966 ++r;
9968 free(refs_str);
9972 if (wanted_ref == NULL || found) {
9973 if (delete) {
9974 err = got_ref_delete(re->ref, repo);
9975 if (err)
9976 goto done;
9977 printf("Deleted: ");
9978 err = print_commit_oneline(commit, id, repo,
9979 refs_idmap);
9980 } else {
9982 * Print paths modified by commit to help
9983 * associate commits with worktree changes.
9985 err = get_changed_paths(&paths, commit,
9986 repo, NULL);
9987 if (err)
9988 goto done;
9990 err = print_commit(commit, id, repo, NULL,
9991 &paths, NULL, 0, 0, refs_idmap, NULL,
9992 header_prefix);
9993 got_pathlist_free(&paths,
9994 GOT_PATHLIST_FREE_ALL);
9996 if (worktree == NULL)
9997 printf("work tree: %.*s\n\n",
9998 GOT_WORKTREE_UUID_STRLEN, wt);
10000 if (err || found)
10001 goto done;
10004 got_object_commit_close(commit);
10005 commit = NULL;
10006 free(id);
10007 id = NULL;
10010 if (wanted_ref != NULL && !found)
10011 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10013 done:
10014 free(id);
10015 free(uuidstr);
10016 got_ref_list_free(&refs);
10017 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10018 if (refs_idmap)
10019 got_reflist_object_id_map_free(refs_idmap);
10020 if (commit)
10021 got_object_commit_close(commit);
10022 return err;
10026 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10027 * identified by id for log messages to prepopulate the editor on commit.
10029 static const struct got_error *
10030 logmsg_ref(struct got_object_id *id, const char *prefix,
10031 struct got_worktree *worktree, struct got_repository *repo)
10033 const struct got_error *err = NULL;
10034 char *idstr, *ref = NULL, *refname = NULL;
10035 int histedit_in_progress;
10036 int rebase_in_progress, merge_in_progress;
10039 * Silenty refuse to create merge reference if any histedit, merge,
10040 * or rebase operation is in progress.
10042 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10043 worktree);
10044 if (err)
10045 return err;
10046 if (histedit_in_progress)
10047 return NULL;
10049 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10050 if (err)
10051 return err;
10052 if (rebase_in_progress)
10053 return NULL;
10055 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10056 repo);
10057 if (err)
10058 return err;
10059 if (merge_in_progress)
10060 return NULL;
10062 err = got_object_id_str(&idstr, id);
10063 if (err)
10064 return err;
10066 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10067 if (err)
10068 goto done;
10070 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10071 err = got_error_from_errno("asprintf");
10072 goto done;
10075 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10076 -1, repo);
10077 done:
10078 free(ref);
10079 free(idstr);
10080 free(refname);
10081 return err;
10084 __dead static void
10085 usage_cherrypick(void)
10087 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10088 getprogname());
10089 exit(1);
10092 static const struct got_error *
10093 cmd_cherrypick(int argc, char *argv[])
10095 const struct got_error *error = NULL;
10096 struct got_worktree *worktree = NULL;
10097 struct got_repository *repo = NULL;
10098 char *cwd = NULL, *commit_id_str = NULL;
10099 struct got_object_id *commit_id = NULL;
10100 struct got_commit_object *commit = NULL;
10101 struct got_object_qid *pid;
10102 int ch, list_refs = 0, remove_refs = 0;
10103 struct got_update_progress_arg upa;
10104 int *pack_fds = NULL;
10106 #ifndef PROFILE
10107 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10108 "unveil", NULL) == -1)
10109 err(1, "pledge");
10110 #endif
10112 while ((ch = getopt(argc, argv, "lX")) != -1) {
10113 switch (ch) {
10114 case 'l':
10115 list_refs = 1;
10116 break;
10117 case 'X':
10118 remove_refs = 1;
10119 break;
10120 default:
10121 usage_cherrypick();
10122 /* NOTREACHED */
10126 argc -= optind;
10127 argv += optind;
10129 if (list_refs || remove_refs) {
10130 if (argc != 0 && argc != 1)
10131 usage_cherrypick();
10132 } else if (argc != 1)
10133 usage_cherrypick();
10134 if (list_refs && remove_refs)
10135 option_conflict('l', 'X');
10137 cwd = getcwd(NULL, 0);
10138 if (cwd == NULL) {
10139 error = got_error_from_errno("getcwd");
10140 goto done;
10143 error = got_repo_pack_fds_open(&pack_fds);
10144 if (error != NULL)
10145 goto done;
10147 error = got_worktree_open(&worktree, cwd);
10148 if (error) {
10149 if (list_refs || remove_refs) {
10150 if (error->code != GOT_ERR_NOT_WORKTREE)
10151 goto done;
10152 } else {
10153 if (error->code == GOT_ERR_NOT_WORKTREE)
10154 error = wrap_not_worktree_error(error,
10155 "cherrypick", cwd);
10156 goto done;
10160 error = got_repo_open(&repo,
10161 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10162 NULL, pack_fds);
10163 if (error != NULL)
10164 goto done;
10166 error = apply_unveil(got_repo_get_path(repo), 0,
10167 worktree ? got_worktree_get_root_path(worktree) : NULL);
10168 if (error)
10169 goto done;
10171 if (list_refs || remove_refs) {
10172 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10173 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10174 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10175 goto done;
10178 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10179 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10180 if (error)
10181 goto done;
10182 error = got_object_id_str(&commit_id_str, commit_id);
10183 if (error)
10184 goto done;
10186 error = got_object_open_as_commit(&commit, repo, commit_id);
10187 if (error)
10188 goto done;
10189 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10190 memset(&upa, 0, sizeof(upa));
10191 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10192 commit_id, repo, update_progress, &upa, check_cancelled,
10193 NULL);
10194 if (error != NULL)
10195 goto done;
10197 if (upa.did_something) {
10198 error = logmsg_ref(commit_id,
10199 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10200 if (error)
10201 goto done;
10202 printf("Merged commit %s\n", commit_id_str);
10204 print_merge_progress_stats(&upa);
10205 done:
10206 free(cwd);
10207 if (commit)
10208 got_object_commit_close(commit);
10209 free(commit_id_str);
10210 if (worktree)
10211 got_worktree_close(worktree);
10212 if (repo) {
10213 const struct got_error *close_err = got_repo_close(repo);
10214 if (error == NULL)
10215 error = close_err;
10217 if (pack_fds) {
10218 const struct got_error *pack_err =
10219 got_repo_pack_fds_close(pack_fds);
10220 if (error == NULL)
10221 error = pack_err;
10224 return error;
10227 __dead static void
10228 usage_backout(void)
10230 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10231 exit(1);
10234 static const struct got_error *
10235 cmd_backout(int argc, char *argv[])
10237 const struct got_error *error = NULL;
10238 struct got_worktree *worktree = NULL;
10239 struct got_repository *repo = NULL;
10240 char *cwd = NULL, *commit_id_str = NULL;
10241 struct got_object_id *commit_id = NULL;
10242 struct got_commit_object *commit = NULL;
10243 struct got_object_qid *pid;
10244 int ch, list_refs = 0, remove_refs = 0;
10245 struct got_update_progress_arg upa;
10246 int *pack_fds = NULL;
10248 #ifndef PROFILE
10249 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10250 "unveil", NULL) == -1)
10251 err(1, "pledge");
10252 #endif
10254 while ((ch = getopt(argc, argv, "lX")) != -1) {
10255 switch (ch) {
10256 case 'l':
10257 list_refs = 1;
10258 break;
10259 case 'X':
10260 remove_refs = 1;
10261 break;
10262 default:
10263 usage_backout();
10264 /* NOTREACHED */
10268 argc -= optind;
10269 argv += optind;
10271 if (list_refs || remove_refs) {
10272 if (argc != 0 && argc != 1)
10273 usage_backout();
10274 } else if (argc != 1)
10275 usage_backout();
10276 if (list_refs && remove_refs)
10277 option_conflict('l', 'X');
10279 cwd = getcwd(NULL, 0);
10280 if (cwd == NULL) {
10281 error = got_error_from_errno("getcwd");
10282 goto done;
10285 error = got_repo_pack_fds_open(&pack_fds);
10286 if (error != NULL)
10287 goto done;
10289 error = got_worktree_open(&worktree, cwd);
10290 if (error) {
10291 if (list_refs || remove_refs) {
10292 if (error->code != GOT_ERR_NOT_WORKTREE)
10293 goto done;
10294 } else {
10295 if (error->code == GOT_ERR_NOT_WORKTREE)
10296 error = wrap_not_worktree_error(error,
10297 "backout", cwd);
10298 goto done;
10302 error = got_repo_open(&repo,
10303 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10304 NULL, pack_fds);
10305 if (error != NULL)
10306 goto done;
10308 error = apply_unveil(got_repo_get_path(repo), 0,
10309 worktree ? got_worktree_get_root_path(worktree) : NULL);
10310 if (error)
10311 goto done;
10313 if (list_refs || remove_refs) {
10314 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10315 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10316 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10317 goto done;
10320 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10321 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10322 if (error)
10323 goto done;
10324 error = got_object_id_str(&commit_id_str, commit_id);
10325 if (error)
10326 goto done;
10328 error = got_object_open_as_commit(&commit, repo, commit_id);
10329 if (error)
10330 goto done;
10331 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10332 if (pid == NULL) {
10333 error = got_error(GOT_ERR_ROOT_COMMIT);
10334 goto done;
10337 memset(&upa, 0, sizeof(upa));
10338 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10339 repo, update_progress, &upa, check_cancelled, NULL);
10340 if (error != NULL)
10341 goto done;
10343 if (upa.did_something) {
10344 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10345 worktree, repo);
10346 if (error)
10347 goto done;
10348 printf("Backed out commit %s\n", commit_id_str);
10350 print_merge_progress_stats(&upa);
10351 done:
10352 free(cwd);
10353 if (commit)
10354 got_object_commit_close(commit);
10355 free(commit_id_str);
10356 if (worktree)
10357 got_worktree_close(worktree);
10358 if (repo) {
10359 const struct got_error *close_err = got_repo_close(repo);
10360 if (error == NULL)
10361 error = close_err;
10363 if (pack_fds) {
10364 const struct got_error *pack_err =
10365 got_repo_pack_fds_close(pack_fds);
10366 if (error == NULL)
10367 error = pack_err;
10369 return error;
10372 __dead static void
10373 usage_rebase(void)
10375 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10376 exit(1);
10379 static void
10380 trim_logmsg(char *logmsg, int limit)
10382 char *nl;
10383 size_t len;
10385 len = strlen(logmsg);
10386 if (len > limit)
10387 len = limit;
10388 logmsg[len] = '\0';
10389 nl = strchr(logmsg, '\n');
10390 if (nl)
10391 *nl = '\0';
10394 static const struct got_error *
10395 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10397 const struct got_error *err;
10398 char *logmsg0 = NULL;
10399 const char *s;
10401 err = got_object_commit_get_logmsg(&logmsg0, commit);
10402 if (err)
10403 return err;
10405 s = logmsg0;
10406 while (isspace((unsigned char)s[0]))
10407 s++;
10409 *logmsg = strdup(s);
10410 if (*logmsg == NULL) {
10411 err = got_error_from_errno("strdup");
10412 goto done;
10415 trim_logmsg(*logmsg, limit);
10416 done:
10417 free(logmsg0);
10418 return err;
10421 static const struct got_error *
10422 show_rebase_merge_conflict(struct got_object_id *id,
10423 struct got_repository *repo)
10425 const struct got_error *err;
10426 struct got_commit_object *commit = NULL;
10427 char *id_str = NULL, *logmsg = NULL;
10429 err = got_object_open_as_commit(&commit, repo, id);
10430 if (err)
10431 return err;
10433 err = got_object_id_str(&id_str, id);
10434 if (err)
10435 goto done;
10437 id_str[12] = '\0';
10439 err = get_short_logmsg(&logmsg, 42, commit);
10440 if (err)
10441 goto done;
10443 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10444 done:
10445 free(id_str);
10446 got_object_commit_close(commit);
10447 free(logmsg);
10448 return err;
10451 static const struct got_error *
10452 show_rebase_progress(struct got_commit_object *commit,
10453 struct got_object_id *old_id, struct got_object_id *new_id)
10455 const struct got_error *err;
10456 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10458 err = got_object_id_str(&old_id_str, old_id);
10459 if (err)
10460 goto done;
10462 if (new_id) {
10463 err = got_object_id_str(&new_id_str, new_id);
10464 if (err)
10465 goto done;
10468 old_id_str[12] = '\0';
10469 if (new_id_str)
10470 new_id_str[12] = '\0';
10472 err = get_short_logmsg(&logmsg, 42, commit);
10473 if (err)
10474 goto done;
10476 printf("%s -> %s: %s\n", old_id_str,
10477 new_id_str ? new_id_str : "no-op change", logmsg);
10478 done:
10479 free(old_id_str);
10480 free(new_id_str);
10481 free(logmsg);
10482 return err;
10485 static const struct got_error *
10486 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10487 struct got_reference *branch, struct got_reference *tmp_branch,
10488 struct got_repository *repo, int create_backup)
10490 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10491 return got_worktree_rebase_complete(worktree, fileindex,
10492 tmp_branch, branch, repo, create_backup);
10495 static const struct got_error *
10496 rebase_commit(struct got_pathlist_head *merged_paths,
10497 struct got_worktree *worktree, struct got_fileindex *fileindex,
10498 struct got_reference *tmp_branch, const char *committer,
10499 struct got_object_id *commit_id, int allow_conflict,
10500 struct got_repository *repo)
10502 const struct got_error *error;
10503 struct got_commit_object *commit;
10504 struct got_object_id *new_commit_id;
10506 error = got_object_open_as_commit(&commit, repo, commit_id);
10507 if (error)
10508 return error;
10510 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10511 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10512 allow_conflict, repo);
10513 if (error) {
10514 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10515 goto done;
10516 error = show_rebase_progress(commit, commit_id, NULL);
10517 } else {
10518 error = show_rebase_progress(commit, commit_id, new_commit_id);
10519 free(new_commit_id);
10521 done:
10522 got_object_commit_close(commit);
10523 return error;
10526 struct check_path_prefix_arg {
10527 const char *path_prefix;
10528 size_t len;
10529 int errcode;
10532 static const struct got_error *
10533 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10534 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10535 struct got_object_id *id1, struct got_object_id *id2,
10536 const char *path1, const char *path2,
10537 mode_t mode1, mode_t mode2, struct got_repository *repo)
10539 struct check_path_prefix_arg *a = arg;
10541 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10542 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10543 return got_error(a->errcode);
10545 return NULL;
10548 static const struct got_error *
10549 check_path_prefix(struct got_object_id *parent_id,
10550 struct got_object_id *commit_id, const char *path_prefix,
10551 int errcode, struct got_repository *repo)
10553 const struct got_error *err;
10554 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10555 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10556 struct check_path_prefix_arg cpp_arg;
10558 if (got_path_is_root_dir(path_prefix))
10559 return NULL;
10561 err = got_object_open_as_commit(&commit, repo, commit_id);
10562 if (err)
10563 goto done;
10565 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10566 if (err)
10567 goto done;
10569 err = got_object_open_as_tree(&tree1, repo,
10570 got_object_commit_get_tree_id(parent_commit));
10571 if (err)
10572 goto done;
10574 err = got_object_open_as_tree(&tree2, repo,
10575 got_object_commit_get_tree_id(commit));
10576 if (err)
10577 goto done;
10579 cpp_arg.path_prefix = path_prefix;
10580 while (cpp_arg.path_prefix[0] == '/')
10581 cpp_arg.path_prefix++;
10582 cpp_arg.len = strlen(cpp_arg.path_prefix);
10583 cpp_arg.errcode = errcode;
10584 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10585 check_path_prefix_in_diff, &cpp_arg, 0);
10586 done:
10587 if (tree1)
10588 got_object_tree_close(tree1);
10589 if (tree2)
10590 got_object_tree_close(tree2);
10591 if (commit)
10592 got_object_commit_close(commit);
10593 if (parent_commit)
10594 got_object_commit_close(parent_commit);
10595 return err;
10598 static const struct got_error *
10599 collect_commits(struct got_object_id_queue *commits,
10600 struct got_object_id *initial_commit_id,
10601 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10602 const char *path_prefix, int path_prefix_errcode,
10603 struct got_repository *repo)
10605 const struct got_error *err = NULL;
10606 struct got_commit_graph *graph = NULL;
10607 struct got_object_id parent_id, commit_id;
10608 struct got_object_qid *qid;
10610 err = got_commit_graph_open(&graph, "/", 1);
10611 if (err)
10612 return err;
10614 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10615 check_cancelled, NULL);
10616 if (err)
10617 goto done;
10619 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10620 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10621 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10622 check_cancelled, NULL);
10623 if (err) {
10624 if (err->code == GOT_ERR_ITER_COMPLETED) {
10625 err = got_error_msg(GOT_ERR_ANCESTRY,
10626 "ran out of commits to rebase before "
10627 "youngest common ancestor commit has "
10628 "been reached?!?");
10630 goto done;
10631 } else {
10632 err = check_path_prefix(&parent_id, &commit_id,
10633 path_prefix, path_prefix_errcode, repo);
10634 if (err)
10635 goto done;
10637 err = got_object_qid_alloc(&qid, &commit_id);
10638 if (err)
10639 goto done;
10640 STAILQ_INSERT_HEAD(commits, qid, entry);
10642 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10645 done:
10646 got_commit_graph_close(graph);
10647 return err;
10650 static const struct got_error *
10651 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10653 const struct got_error *err = NULL;
10654 time_t committer_time;
10655 struct tm tm;
10656 char datebuf[11]; /* YYYY-MM-DD + NUL */
10657 char *author0 = NULL, *author, *smallerthan;
10658 char *logmsg0 = NULL, *logmsg, *newline;
10660 committer_time = got_object_commit_get_committer_time(commit);
10661 if (gmtime_r(&committer_time, &tm) == NULL)
10662 return got_error_from_errno("gmtime_r");
10663 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10664 return got_error(GOT_ERR_NO_SPACE);
10666 author0 = strdup(got_object_commit_get_author(commit));
10667 if (author0 == NULL)
10668 return got_error_from_errno("strdup");
10669 author = author0;
10670 smallerthan = strchr(author, '<');
10671 if (smallerthan && smallerthan[1] != '\0')
10672 author = smallerthan + 1;
10673 author[strcspn(author, "@>")] = '\0';
10675 err = got_object_commit_get_logmsg(&logmsg0, commit);
10676 if (err)
10677 goto done;
10678 logmsg = logmsg0;
10679 while (*logmsg == '\n')
10680 logmsg++;
10681 newline = strchr(logmsg, '\n');
10682 if (newline)
10683 *newline = '\0';
10685 if (asprintf(brief_str, "%s %s %s",
10686 datebuf, author, logmsg) == -1)
10687 err = got_error_from_errno("asprintf");
10688 done:
10689 free(author0);
10690 free(logmsg0);
10691 return err;
10694 static const struct got_error *
10695 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10696 struct got_repository *repo)
10698 const struct got_error *err;
10699 char *id_str;
10701 err = got_object_id_str(&id_str, id);
10702 if (err)
10703 return err;
10705 err = got_ref_delete(ref, repo);
10706 if (err)
10707 goto done;
10709 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10710 done:
10711 free(id_str);
10712 return err;
10715 static const struct got_error *
10716 print_backup_ref(const char *branch_name, const char *new_id_str,
10717 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10718 struct got_reflist_object_id_map *refs_idmap,
10719 struct got_repository *repo)
10721 const struct got_error *err = NULL;
10722 struct got_reflist_head *refs;
10723 char *refs_str = NULL;
10724 struct got_object_id *new_commit_id = NULL;
10725 struct got_commit_object *new_commit = NULL;
10726 char *new_commit_brief_str = NULL;
10727 struct got_object_id *yca_id = NULL;
10728 struct got_commit_object *yca_commit = NULL;
10729 char *yca_id_str = NULL, *yca_brief_str = NULL;
10730 char *custom_refs_str;
10732 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10733 return got_error_from_errno("asprintf");
10735 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10736 0, 0, refs_idmap, custom_refs_str, NULL);
10737 if (err)
10738 goto done;
10740 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10741 if (err)
10742 goto done;
10744 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10745 if (refs) {
10746 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10747 if (err)
10748 goto done;
10751 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10752 if (err)
10753 goto done;
10755 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10756 if (err)
10757 goto done;
10759 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10760 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10761 if (err)
10762 goto done;
10764 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10765 refs_str ? " (" : "", refs_str ? refs_str : "",
10766 refs_str ? ")" : "", new_commit_brief_str);
10767 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10768 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10769 free(refs_str);
10770 refs_str = NULL;
10772 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10773 if (err)
10774 goto done;
10776 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10777 if (err)
10778 goto done;
10780 err = got_object_id_str(&yca_id_str, yca_id);
10781 if (err)
10782 goto done;
10784 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10785 if (refs) {
10786 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10787 if (err)
10788 goto done;
10790 printf("history forked at %s%s%s%s\n %s\n",
10791 yca_id_str,
10792 refs_str ? " (" : "", refs_str ? refs_str : "",
10793 refs_str ? ")" : "", yca_brief_str);
10795 done:
10796 free(custom_refs_str);
10797 free(new_commit_id);
10798 free(refs_str);
10799 free(yca_id);
10800 free(yca_id_str);
10801 free(yca_brief_str);
10802 if (new_commit)
10803 got_object_commit_close(new_commit);
10804 if (yca_commit)
10805 got_object_commit_close(yca_commit);
10807 return err;
10810 static const struct got_error *
10811 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10812 struct got_repository *repo)
10814 const struct got_error *err;
10815 struct got_reflist_head refs;
10816 struct got_reflist_entry *re;
10817 char *uuidstr = NULL;
10818 static char msg[160];
10820 TAILQ_INIT(&refs);
10822 err = got_worktree_get_uuid(&uuidstr, worktree);
10823 if (err)
10824 goto done;
10826 err = got_ref_list(&refs, repo, "refs/got/worktree",
10827 got_ref_cmp_by_name, repo);
10828 if (err)
10829 goto done;
10831 TAILQ_FOREACH(re, &refs, entry) {
10832 const char *cmd, *refname, *type;
10834 refname = got_ref_get_name(re->ref);
10836 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10837 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10838 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10839 cmd = "cherrypick";
10840 type = "cherrypicked";
10841 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10842 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10843 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10844 cmd = "backout";
10845 type = "backed-out";
10846 } else
10847 continue;
10849 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10850 continue;
10852 snprintf(msg, sizeof(msg),
10853 "work tree has references created by %s commits which "
10854 "must be removed with 'got %s -X' before running the %s "
10855 "command", type, cmd, caller);
10856 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10857 goto done;
10860 done:
10861 free(uuidstr);
10862 got_ref_list_free(&refs);
10863 return err;
10866 static const struct got_error *
10867 process_backup_refs(const char *backup_ref_prefix,
10868 const char *wanted_branch_name,
10869 int delete, struct got_repository *repo)
10871 const struct got_error *err;
10872 struct got_reflist_head refs, backup_refs;
10873 struct got_reflist_entry *re;
10874 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10875 struct got_object_id *old_commit_id = NULL;
10876 char *branch_name = NULL;
10877 struct got_commit_object *old_commit = NULL;
10878 struct got_reflist_object_id_map *refs_idmap = NULL;
10879 int wanted_branch_found = 0;
10881 TAILQ_INIT(&refs);
10882 TAILQ_INIT(&backup_refs);
10884 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10885 if (err)
10886 return err;
10888 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10889 if (err)
10890 goto done;
10892 if (wanted_branch_name) {
10893 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10894 wanted_branch_name += 11;
10897 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10898 got_ref_cmp_by_commit_timestamp_descending, repo);
10899 if (err)
10900 goto done;
10902 TAILQ_FOREACH(re, &backup_refs, entry) {
10903 const char *refname = got_ref_get_name(re->ref);
10904 char *slash;
10906 err = check_cancelled(NULL);
10907 if (err)
10908 break;
10910 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10911 if (err)
10912 break;
10914 err = got_object_open_as_commit(&old_commit, repo,
10915 old_commit_id);
10916 if (err)
10917 break;
10919 if (strncmp(backup_ref_prefix, refname,
10920 backup_ref_prefix_len) == 0)
10921 refname += backup_ref_prefix_len;
10923 while (refname[0] == '/')
10924 refname++;
10926 branch_name = strdup(refname);
10927 if (branch_name == NULL) {
10928 err = got_error_from_errno("strdup");
10929 break;
10931 slash = strrchr(branch_name, '/');
10932 if (slash) {
10933 *slash = '\0';
10934 refname += strlen(branch_name) + 1;
10937 if (wanted_branch_name == NULL ||
10938 strcmp(wanted_branch_name, branch_name) == 0) {
10939 wanted_branch_found = 1;
10940 if (delete) {
10941 err = delete_backup_ref(re->ref,
10942 old_commit_id, repo);
10943 } else {
10944 err = print_backup_ref(branch_name, refname,
10945 old_commit_id, old_commit, refs_idmap,
10946 repo);
10948 if (err)
10949 break;
10952 free(old_commit_id);
10953 old_commit_id = NULL;
10954 free(branch_name);
10955 branch_name = NULL;
10956 got_object_commit_close(old_commit);
10957 old_commit = NULL;
10960 if (wanted_branch_name && !wanted_branch_found) {
10961 err = got_error_fmt(GOT_ERR_NOT_REF,
10962 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10964 done:
10965 if (refs_idmap)
10966 got_reflist_object_id_map_free(refs_idmap);
10967 got_ref_list_free(&refs);
10968 got_ref_list_free(&backup_refs);
10969 free(old_commit_id);
10970 free(branch_name);
10971 if (old_commit)
10972 got_object_commit_close(old_commit);
10973 return err;
10976 static const struct got_error *
10977 abort_progress(void *arg, unsigned char status, const char *path)
10980 * Unversioned files should not clutter progress output when
10981 * an operation is aborted.
10983 if (status == GOT_STATUS_UNVERSIONED)
10984 return NULL;
10986 return update_progress(arg, status, path);
10989 static const struct got_error *
10990 cmd_rebase(int argc, char *argv[])
10992 const struct got_error *error = NULL;
10993 struct got_worktree *worktree = NULL;
10994 struct got_repository *repo = NULL;
10995 struct got_fileindex *fileindex = NULL;
10996 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10997 struct got_reference *branch = NULL;
10998 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10999 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11000 struct got_object_id *resume_commit_id = NULL;
11001 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11002 struct got_object_id *head_commit_id = NULL;
11003 struct got_reference *head_ref = NULL;
11004 struct got_commit_object *commit = NULL;
11005 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11006 int histedit_in_progress = 0, merge_in_progress = 0;
11007 int create_backup = 1, list_backups = 0, delete_backups = 0;
11008 int allow_conflict = 0;
11009 struct got_object_id_queue commits;
11010 struct got_pathlist_head merged_paths;
11011 const struct got_object_id_queue *parent_ids;
11012 struct got_object_qid *qid, *pid;
11013 struct got_update_progress_arg upa;
11014 int *pack_fds = NULL;
11016 STAILQ_INIT(&commits);
11017 TAILQ_INIT(&merged_paths);
11018 memset(&upa, 0, sizeof(upa));
11020 #ifndef PROFILE
11021 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11022 "unveil", NULL) == -1)
11023 err(1, "pledge");
11024 #endif
11026 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11027 switch (ch) {
11028 case 'a':
11029 abort_rebase = 1;
11030 break;
11031 case 'C':
11032 allow_conflict = 1;
11033 break;
11034 case 'c':
11035 continue_rebase = 1;
11036 break;
11037 case 'l':
11038 list_backups = 1;
11039 break;
11040 case 'X':
11041 delete_backups = 1;
11042 break;
11043 default:
11044 usage_rebase();
11045 /* NOTREACHED */
11049 argc -= optind;
11050 argv += optind;
11052 if (list_backups) {
11053 if (abort_rebase)
11054 option_conflict('l', 'a');
11055 if (allow_conflict)
11056 option_conflict('l', 'C');
11057 if (continue_rebase)
11058 option_conflict('l', 'c');
11059 if (delete_backups)
11060 option_conflict('l', 'X');
11061 if (argc != 0 && argc != 1)
11062 usage_rebase();
11063 } else if (delete_backups) {
11064 if (abort_rebase)
11065 option_conflict('X', 'a');
11066 if (allow_conflict)
11067 option_conflict('X', 'C');
11068 if (continue_rebase)
11069 option_conflict('X', 'c');
11070 if (list_backups)
11071 option_conflict('l', 'X');
11072 if (argc != 0 && argc != 1)
11073 usage_rebase();
11074 } else if (allow_conflict) {
11075 if (abort_rebase)
11076 option_conflict('C', 'a');
11077 if (!continue_rebase)
11078 errx(1, "-C option requires -c");
11079 } else {
11080 if (abort_rebase && continue_rebase)
11081 usage_rebase();
11082 else if (abort_rebase || continue_rebase) {
11083 if (argc != 0)
11084 usage_rebase();
11085 } else if (argc != 1)
11086 usage_rebase();
11089 cwd = getcwd(NULL, 0);
11090 if (cwd == NULL) {
11091 error = got_error_from_errno("getcwd");
11092 goto done;
11095 error = got_repo_pack_fds_open(&pack_fds);
11096 if (error != NULL)
11097 goto done;
11099 error = got_worktree_open(&worktree, cwd);
11100 if (error) {
11101 if (list_backups || delete_backups) {
11102 if (error->code != GOT_ERR_NOT_WORKTREE)
11103 goto done;
11104 } else {
11105 if (error->code == GOT_ERR_NOT_WORKTREE)
11106 error = wrap_not_worktree_error(error,
11107 "rebase", cwd);
11108 goto done;
11112 error = get_gitconfig_path(&gitconfig_path);
11113 if (error)
11114 goto done;
11115 error = got_repo_open(&repo,
11116 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11117 gitconfig_path, pack_fds);
11118 if (error != NULL)
11119 goto done;
11121 if (worktree != NULL && !list_backups && !delete_backups) {
11122 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11123 if (error)
11124 goto done;
11127 error = get_author(&committer, repo, worktree);
11128 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11129 goto done;
11131 error = apply_unveil(got_repo_get_path(repo), 0,
11132 worktree ? got_worktree_get_root_path(worktree) : NULL);
11133 if (error)
11134 goto done;
11136 if (list_backups || delete_backups) {
11137 error = process_backup_refs(
11138 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11139 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11140 goto done; /* nothing else to do */
11143 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11144 worktree);
11145 if (error)
11146 goto done;
11147 if (histedit_in_progress) {
11148 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11149 goto done;
11152 error = got_worktree_merge_in_progress(&merge_in_progress,
11153 worktree, repo);
11154 if (error)
11155 goto done;
11156 if (merge_in_progress) {
11157 error = got_error(GOT_ERR_MERGE_BUSY);
11158 goto done;
11161 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11162 if (error)
11163 goto done;
11165 if (abort_rebase) {
11166 if (!rebase_in_progress) {
11167 error = got_error(GOT_ERR_NOT_REBASING);
11168 goto done;
11170 error = got_worktree_rebase_continue(&resume_commit_id,
11171 &new_base_branch, &tmp_branch, &branch, &fileindex,
11172 worktree, repo);
11173 if (error)
11174 goto done;
11175 printf("Switching work tree to %s\n",
11176 got_ref_get_symref_target(new_base_branch));
11177 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11178 new_base_branch, abort_progress, &upa);
11179 if (error)
11180 goto done;
11181 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11182 print_merge_progress_stats(&upa);
11183 goto done; /* nothing else to do */
11186 if (continue_rebase) {
11187 if (!rebase_in_progress) {
11188 error = got_error(GOT_ERR_NOT_REBASING);
11189 goto done;
11191 error = got_worktree_rebase_continue(&resume_commit_id,
11192 &new_base_branch, &tmp_branch, &branch, &fileindex,
11193 worktree, repo);
11194 if (error)
11195 goto done;
11197 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11198 committer, resume_commit_id, allow_conflict, repo);
11199 if (error)
11200 goto done;
11202 yca_id = got_object_id_dup(resume_commit_id);
11203 if (yca_id == NULL) {
11204 error = got_error_from_errno("got_object_id_dup");
11205 goto done;
11207 } else {
11208 error = got_ref_open(&branch, repo, argv[0], 0);
11209 if (error != NULL)
11210 goto done;
11211 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11212 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11213 "will not rebase a branch which lives outside "
11214 "the \"refs/heads/\" reference namespace");
11215 goto done;
11219 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11220 if (error)
11221 goto done;
11223 if (!continue_rebase) {
11224 struct got_object_id *base_commit_id;
11226 error = got_ref_open(&head_ref, repo,
11227 got_worktree_get_head_ref_name(worktree), 0);
11228 if (error)
11229 goto done;
11230 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11231 if (error)
11232 goto done;
11233 base_commit_id = got_worktree_get_base_commit_id(worktree);
11234 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11235 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11236 goto done;
11239 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11240 base_commit_id, branch_head_commit_id, 1, repo,
11241 check_cancelled, NULL);
11242 if (error) {
11243 if (error->code == GOT_ERR_ANCESTRY) {
11244 error = got_error_msg(GOT_ERR_ANCESTRY,
11245 "specified branch shares no common "
11246 "ancestry with work tree's branch");
11248 goto done;
11251 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11252 if (error) {
11253 if (error->code != GOT_ERR_ANCESTRY)
11254 goto done;
11255 error = NULL;
11256 } else {
11257 struct got_pathlist_head paths;
11258 printf("%s is already based on %s\n",
11259 got_ref_get_name(branch),
11260 got_worktree_get_head_ref_name(worktree));
11261 error = switch_head_ref(branch, branch_head_commit_id,
11262 worktree, repo);
11263 if (error)
11264 goto done;
11265 error = got_worktree_set_base_commit_id(worktree, repo,
11266 branch_head_commit_id);
11267 if (error)
11268 goto done;
11269 TAILQ_INIT(&paths);
11270 error = got_pathlist_append(&paths, "", NULL);
11271 if (error)
11272 goto done;
11273 error = got_worktree_checkout_files(worktree,
11274 &paths, repo, update_progress, &upa,
11275 check_cancelled, NULL);
11276 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11277 if (error)
11278 goto done;
11279 if (upa.did_something) {
11280 char *id_str;
11281 error = got_object_id_str(&id_str,
11282 branch_head_commit_id);
11283 if (error)
11284 goto done;
11285 printf("Updated to %s: %s\n",
11286 got_worktree_get_head_ref_name(worktree),
11287 id_str);
11288 free(id_str);
11289 } else
11290 printf("Already up-to-date\n");
11291 print_update_progress_stats(&upa);
11292 goto done;
11296 commit_id = branch_head_commit_id;
11297 error = got_object_open_as_commit(&commit, repo, commit_id);
11298 if (error)
11299 goto done;
11301 parent_ids = got_object_commit_get_parent_ids(commit);
11302 pid = STAILQ_FIRST(parent_ids);
11303 if (pid) {
11304 error = collect_commits(&commits, commit_id, &pid->id,
11305 yca_id, got_worktree_get_path_prefix(worktree),
11306 GOT_ERR_REBASE_PATH, repo);
11307 if (error)
11308 goto done;
11311 got_object_commit_close(commit);
11312 commit = NULL;
11314 if (!continue_rebase) {
11315 error = got_worktree_rebase_prepare(&new_base_branch,
11316 &tmp_branch, &fileindex, worktree, branch, repo);
11317 if (error)
11318 goto done;
11321 if (STAILQ_EMPTY(&commits)) {
11322 if (continue_rebase) {
11323 error = rebase_complete(worktree, fileindex,
11324 branch, tmp_branch, repo, create_backup);
11325 goto done;
11326 } else {
11327 /* Fast-forward the reference of the branch. */
11328 struct got_object_id *new_head_commit_id;
11329 char *id_str;
11330 error = got_ref_resolve(&new_head_commit_id, repo,
11331 new_base_branch);
11332 if (error)
11333 goto done;
11334 error = got_object_id_str(&id_str, new_head_commit_id);
11335 if (error)
11336 goto done;
11337 printf("Forwarding %s to commit %s\n",
11338 got_ref_get_name(branch), id_str);
11339 free(id_str);
11340 error = got_ref_change_ref(branch,
11341 new_head_commit_id);
11342 if (error)
11343 goto done;
11344 /* No backup needed since objects did not change. */
11345 create_backup = 0;
11349 pid = NULL;
11350 STAILQ_FOREACH(qid, &commits, entry) {
11352 commit_id = &qid->id;
11353 parent_id = pid ? &pid->id : yca_id;
11354 pid = qid;
11356 memset(&upa, 0, sizeof(upa));
11357 error = got_worktree_rebase_merge_files(&merged_paths,
11358 worktree, fileindex, parent_id, commit_id, repo,
11359 update_progress, &upa, check_cancelled, NULL);
11360 if (error)
11361 goto done;
11363 print_merge_progress_stats(&upa);
11364 if (upa.conflicts > 0 || upa.missing > 0 ||
11365 upa.not_deleted > 0 || upa.unversioned > 0) {
11366 if (upa.conflicts > 0) {
11367 error = show_rebase_merge_conflict(&qid->id,
11368 repo);
11369 if (error)
11370 goto done;
11372 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11373 break;
11376 error = rebase_commit(&merged_paths, worktree, fileindex,
11377 tmp_branch, committer, commit_id, 0, repo);
11378 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11379 if (error)
11380 goto done;
11383 if (upa.conflicts > 0 || upa.missing > 0 ||
11384 upa.not_deleted > 0 || upa.unversioned > 0) {
11385 error = got_worktree_rebase_postpone(worktree, fileindex);
11386 if (error)
11387 goto done;
11388 if (upa.conflicts > 0 && upa.missing == 0 &&
11389 upa.not_deleted == 0 && upa.unversioned == 0) {
11390 error = got_error_msg(GOT_ERR_CONFLICTS,
11391 "conflicts must be resolved before rebasing "
11392 "can continue");
11393 } else if (upa.conflicts > 0) {
11394 error = got_error_msg(GOT_ERR_CONFLICTS,
11395 "conflicts must be resolved before rebasing "
11396 "can continue; changes destined for some "
11397 "files were not yet merged and should be "
11398 "merged manually if required before the "
11399 "rebase operation is continued");
11400 } else {
11401 error = got_error_msg(GOT_ERR_CONFLICTS,
11402 "changes destined for some files were not "
11403 "yet merged and should be merged manually "
11404 "if required before the rebase operation "
11405 "is continued");
11407 } else
11408 error = rebase_complete(worktree, fileindex, branch,
11409 tmp_branch, repo, create_backup);
11410 done:
11411 free(cwd);
11412 free(committer);
11413 free(gitconfig_path);
11414 got_object_id_queue_free(&commits);
11415 free(branch_head_commit_id);
11416 free(resume_commit_id);
11417 free(head_commit_id);
11418 free(yca_id);
11419 if (commit)
11420 got_object_commit_close(commit);
11421 if (branch)
11422 got_ref_close(branch);
11423 if (new_base_branch)
11424 got_ref_close(new_base_branch);
11425 if (tmp_branch)
11426 got_ref_close(tmp_branch);
11427 if (head_ref)
11428 got_ref_close(head_ref);
11429 if (worktree)
11430 got_worktree_close(worktree);
11431 if (repo) {
11432 const struct got_error *close_err = got_repo_close(repo);
11433 if (error == NULL)
11434 error = close_err;
11436 if (pack_fds) {
11437 const struct got_error *pack_err =
11438 got_repo_pack_fds_close(pack_fds);
11439 if (error == NULL)
11440 error = pack_err;
11442 return error;
11445 __dead static void
11446 usage_histedit(void)
11448 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11449 "[branch]\n", getprogname());
11450 exit(1);
11453 #define GOT_HISTEDIT_PICK 'p'
11454 #define GOT_HISTEDIT_EDIT 'e'
11455 #define GOT_HISTEDIT_FOLD 'f'
11456 #define GOT_HISTEDIT_DROP 'd'
11457 #define GOT_HISTEDIT_MESG 'm'
11459 static const struct got_histedit_cmd {
11460 unsigned char code;
11461 const char *name;
11462 const char *desc;
11463 } got_histedit_cmds[] = {
11464 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11465 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11466 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11467 "be used" },
11468 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11469 { GOT_HISTEDIT_MESG, "mesg",
11470 "single-line log message for commit above (open editor if empty)" },
11473 struct got_histedit_list_entry {
11474 TAILQ_ENTRY(got_histedit_list_entry) entry;
11475 struct got_object_id *commit_id;
11476 const struct got_histedit_cmd *cmd;
11477 char *logmsg;
11479 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11481 static const struct got_error *
11482 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11483 FILE *f, struct got_repository *repo)
11485 const struct got_error *err = NULL;
11486 char *logmsg = NULL, *id_str = NULL;
11487 struct got_commit_object *commit = NULL;
11488 int n;
11490 err = got_object_open_as_commit(&commit, repo, commit_id);
11491 if (err)
11492 goto done;
11494 err = get_short_logmsg(&logmsg, 34, commit);
11495 if (err)
11496 goto done;
11498 err = got_object_id_str(&id_str, commit_id);
11499 if (err)
11500 goto done;
11502 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11503 if (n < 0)
11504 err = got_ferror(f, GOT_ERR_IO);
11505 done:
11506 if (commit)
11507 got_object_commit_close(commit);
11508 free(id_str);
11509 free(logmsg);
11510 return err;
11513 static const struct got_error *
11514 histedit_write_commit_list(struct got_object_id_queue *commits,
11515 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11516 int edit_only, struct got_repository *repo)
11518 const struct got_error *err = NULL;
11519 struct got_object_qid *qid;
11520 const char *histedit_cmd = NULL;
11522 if (STAILQ_EMPTY(commits))
11523 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11525 STAILQ_FOREACH(qid, commits, entry) {
11526 histedit_cmd = got_histedit_cmds[0].name;
11527 if (drop_only)
11528 histedit_cmd = "drop";
11529 else if (edit_only)
11530 histedit_cmd = "edit";
11531 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11532 histedit_cmd = "fold";
11533 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11534 if (err)
11535 break;
11536 if (edit_logmsg_only) {
11537 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11538 if (n < 0) {
11539 err = got_ferror(f, GOT_ERR_IO);
11540 break;
11545 return err;
11548 static const struct got_error *
11549 write_cmd_list(FILE *f, const char *branch_name,
11550 struct got_object_id_queue *commits)
11552 const struct got_error *err = NULL;
11553 size_t i;
11554 int n;
11555 char *id_str;
11556 struct got_object_qid *qid;
11558 qid = STAILQ_FIRST(commits);
11559 err = got_object_id_str(&id_str, &qid->id);
11560 if (err)
11561 return err;
11563 n = fprintf(f,
11564 "# Editing the history of branch '%s' starting at\n"
11565 "# commit %s\n"
11566 "# Commits will be processed in order from top to "
11567 "bottom of this file.\n", branch_name, id_str);
11568 if (n < 0) {
11569 err = got_ferror(f, GOT_ERR_IO);
11570 goto done;
11573 n = fprintf(f, "# Available histedit commands:\n");
11574 if (n < 0) {
11575 err = got_ferror(f, GOT_ERR_IO);
11576 goto done;
11579 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11580 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11581 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11582 cmd->desc);
11583 if (n < 0) {
11584 err = got_ferror(f, GOT_ERR_IO);
11585 break;
11588 done:
11589 free(id_str);
11590 return err;
11593 static const struct got_error *
11594 histedit_syntax_error(int lineno)
11596 static char msg[42];
11597 int ret;
11599 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11600 lineno);
11601 if (ret < 0 || (size_t)ret >= sizeof(msg))
11602 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11604 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11607 static const struct got_error *
11608 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11609 char *logmsg, struct got_repository *repo)
11611 const struct got_error *err;
11612 struct got_commit_object *folded_commit = NULL;
11613 char *id_str, *folded_logmsg = NULL;
11615 err = got_object_id_str(&id_str, hle->commit_id);
11616 if (err)
11617 return err;
11619 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11620 if (err)
11621 goto done;
11623 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11624 if (err)
11625 goto done;
11626 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11627 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11628 folded_logmsg) == -1) {
11629 err = got_error_from_errno("asprintf");
11631 done:
11632 if (folded_commit)
11633 got_object_commit_close(folded_commit);
11634 free(id_str);
11635 free(folded_logmsg);
11636 return err;
11639 static struct got_histedit_list_entry *
11640 get_folded_commits(struct got_histedit_list_entry *hle)
11642 struct got_histedit_list_entry *prev, *folded = NULL;
11644 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11645 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11646 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11647 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11648 folded = prev;
11649 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11652 return folded;
11655 static const struct got_error *
11656 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11657 struct got_repository *repo)
11659 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11660 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11661 const struct got_error *err = NULL;
11662 struct got_commit_object *commit = NULL;
11663 int logmsg_len;
11664 int fd;
11665 struct got_histedit_list_entry *folded = NULL;
11667 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11668 if (err)
11669 return err;
11671 folded = get_folded_commits(hle);
11672 if (folded) {
11673 while (folded != hle) {
11674 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11675 folded = TAILQ_NEXT(folded, entry);
11676 continue;
11678 err = append_folded_commit_msg(&new_msg, folded,
11679 logmsg, repo);
11680 if (err)
11681 goto done;
11682 free(logmsg);
11683 logmsg = new_msg;
11684 folded = TAILQ_NEXT(folded, entry);
11688 err = got_object_id_str(&id_str, hle->commit_id);
11689 if (err)
11690 goto done;
11691 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11692 if (err)
11693 goto done;
11694 logmsg_len = asprintf(&new_msg,
11695 "%s\n# original log message of commit %s: %s",
11696 logmsg ? logmsg : "", id_str, orig_logmsg);
11697 if (logmsg_len == -1) {
11698 err = got_error_from_errno("asprintf");
11699 goto done;
11701 free(logmsg);
11702 logmsg = new_msg;
11704 err = got_object_id_str(&id_str, hle->commit_id);
11705 if (err)
11706 goto done;
11708 err = got_opentemp_named_fd(&logmsg_path, &fd,
11709 GOT_TMPDIR_STR "/got-logmsg", "");
11710 if (err)
11711 goto done;
11713 write(fd, logmsg, logmsg_len);
11714 close(fd);
11716 err = get_editor(&editor);
11717 if (err)
11718 goto done;
11720 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11721 logmsg_len, 0);
11722 if (err) {
11723 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11724 goto done;
11725 err = NULL;
11726 hle->logmsg = strdup(new_msg);
11727 if (hle->logmsg == NULL)
11728 err = got_error_from_errno("strdup");
11730 done:
11731 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11732 err = got_error_from_errno2("unlink", logmsg_path);
11733 free(logmsg_path);
11734 free(logmsg);
11735 free(orig_logmsg);
11736 free(editor);
11737 if (commit)
11738 got_object_commit_close(commit);
11739 return err;
11742 static const struct got_error *
11743 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11744 FILE *f, struct got_repository *repo)
11746 const struct got_error *err = NULL;
11747 char *line = NULL, *p, *end;
11748 size_t i, linesize = 0;
11749 ssize_t linelen;
11750 int lineno = 0, lastcmd = -1;
11751 const struct got_histedit_cmd *cmd;
11752 struct got_object_id *commit_id = NULL;
11753 struct got_histedit_list_entry *hle = NULL;
11755 for (;;) {
11756 linelen = getline(&line, &linesize, f);
11757 if (linelen == -1) {
11758 const struct got_error *getline_err;
11759 if (feof(f))
11760 break;
11761 getline_err = got_error_from_errno("getline");
11762 err = got_ferror(f, getline_err->code);
11763 break;
11765 lineno++;
11766 p = line;
11767 while (isspace((unsigned char)p[0]))
11768 p++;
11769 if (p[0] == '#' || p[0] == '\0')
11770 continue;
11771 cmd = NULL;
11772 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11773 cmd = &got_histedit_cmds[i];
11774 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11775 isspace((unsigned char)p[strlen(cmd->name)])) {
11776 p += strlen(cmd->name);
11777 break;
11779 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11780 p++;
11781 break;
11784 if (i == nitems(got_histedit_cmds)) {
11785 err = histedit_syntax_error(lineno);
11786 break;
11788 while (isspace((unsigned char)p[0]))
11789 p++;
11790 if (cmd->code == GOT_HISTEDIT_MESG) {
11791 if (lastcmd != GOT_HISTEDIT_PICK &&
11792 lastcmd != GOT_HISTEDIT_EDIT) {
11793 err = got_error(GOT_ERR_HISTEDIT_CMD);
11794 break;
11796 if (p[0] == '\0') {
11797 err = histedit_edit_logmsg(hle, repo);
11798 if (err)
11799 break;
11800 } else {
11801 hle->logmsg = strdup(p);
11802 if (hle->logmsg == NULL) {
11803 err = got_error_from_errno("strdup");
11804 break;
11807 lastcmd = cmd->code;
11808 continue;
11809 } else {
11810 end = p;
11811 while (end[0] && !isspace((unsigned char)end[0]))
11812 end++;
11813 *end = '\0';
11815 err = got_object_resolve_id_str(&commit_id, repo, p);
11816 if (err) {
11817 /* override error code */
11818 err = histedit_syntax_error(lineno);
11819 break;
11822 hle = malloc(sizeof(*hle));
11823 if (hle == NULL) {
11824 err = got_error_from_errno("malloc");
11825 break;
11827 hle->cmd = cmd;
11828 hle->commit_id = commit_id;
11829 hle->logmsg = NULL;
11830 commit_id = NULL;
11831 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11832 lastcmd = cmd->code;
11835 free(line);
11836 free(commit_id);
11837 return err;
11840 static const struct got_error *
11841 histedit_check_script(struct got_histedit_list *histedit_cmds,
11842 struct got_object_id_queue *commits, struct got_repository *repo)
11844 const struct got_error *err = NULL;
11845 struct got_object_qid *qid;
11846 struct got_histedit_list_entry *hle;
11847 static char msg[92];
11848 char *id_str;
11850 if (TAILQ_EMPTY(histedit_cmds))
11851 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11852 "histedit script contains no commands");
11853 if (STAILQ_EMPTY(commits))
11854 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11856 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11857 struct got_histedit_list_entry *hle2;
11858 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11859 if (hle == hle2)
11860 continue;
11861 if (got_object_id_cmp(hle->commit_id,
11862 hle2->commit_id) != 0)
11863 continue;
11864 err = got_object_id_str(&id_str, hle->commit_id);
11865 if (err)
11866 return err;
11867 snprintf(msg, sizeof(msg), "commit %s is listed "
11868 "more than once in histedit script", id_str);
11869 free(id_str);
11870 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11874 STAILQ_FOREACH(qid, commits, entry) {
11875 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11876 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11877 break;
11879 if (hle == NULL) {
11880 err = got_object_id_str(&id_str, &qid->id);
11881 if (err)
11882 return err;
11883 snprintf(msg, sizeof(msg),
11884 "commit %s missing from histedit script", id_str);
11885 free(id_str);
11886 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11890 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11891 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11892 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11893 "last commit in histedit script cannot be folded");
11895 return NULL;
11898 static const struct got_error *
11899 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11900 const char *path, struct got_object_id_queue *commits,
11901 struct got_repository *repo)
11903 const struct got_error *err = NULL;
11904 char *editor;
11905 FILE *f = NULL;
11907 err = get_editor(&editor);
11908 if (err)
11909 return err;
11911 if (spawn_editor(editor, path) == -1) {
11912 err = got_error_from_errno("failed spawning editor");
11913 goto done;
11916 f = fopen(path, "re");
11917 if (f == NULL) {
11918 err = got_error_from_errno("fopen");
11919 goto done;
11921 err = histedit_parse_list(histedit_cmds, f, repo);
11922 if (err)
11923 goto done;
11925 err = histedit_check_script(histedit_cmds, commits, repo);
11926 done:
11927 if (f && fclose(f) == EOF && err == NULL)
11928 err = got_error_from_errno("fclose");
11929 free(editor);
11930 return err;
11933 static const struct got_error *
11934 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11935 struct got_object_id_queue *, const char *, const char *,
11936 struct got_repository *);
11938 static const struct got_error *
11939 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11940 struct got_object_id_queue *commits, const char *branch_name,
11941 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11942 struct got_repository *repo)
11944 const struct got_error *err;
11945 FILE *f = NULL;
11946 char *path = NULL;
11948 err = got_opentemp_named(&path, &f, "got-histedit", "");
11949 if (err)
11950 return err;
11952 err = write_cmd_list(f, branch_name, commits);
11953 if (err)
11954 goto done;
11956 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11957 fold_only, drop_only, edit_only, repo);
11958 if (err)
11959 goto done;
11961 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11962 rewind(f);
11963 err = histedit_parse_list(histedit_cmds, f, repo);
11964 } else {
11965 if (fclose(f) == EOF) {
11966 err = got_error_from_errno("fclose");
11967 goto done;
11969 f = NULL;
11970 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11971 if (err) {
11972 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11973 err->code != GOT_ERR_HISTEDIT_CMD)
11974 goto done;
11975 err = histedit_edit_list_retry(histedit_cmds, err,
11976 commits, path, branch_name, repo);
11979 done:
11980 if (f && fclose(f) == EOF && err == NULL)
11981 err = got_error_from_errno("fclose");
11982 if (path && unlink(path) != 0 && err == NULL)
11983 err = got_error_from_errno2("unlink", path);
11984 free(path);
11985 return err;
11988 static const struct got_error *
11989 histedit_save_list(struct got_histedit_list *histedit_cmds,
11990 struct got_worktree *worktree, struct got_repository *repo)
11992 const struct got_error *err = NULL;
11993 char *path = NULL;
11994 FILE *f = NULL;
11995 struct got_histedit_list_entry *hle;
11996 struct got_commit_object *commit = NULL;
11998 err = got_worktree_get_histedit_script_path(&path, worktree);
11999 if (err)
12000 return err;
12002 f = fopen(path, "we");
12003 if (f == NULL) {
12004 err = got_error_from_errno2("fopen", path);
12005 goto done;
12007 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12008 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12009 repo);
12010 if (err)
12011 break;
12013 if (hle->logmsg) {
12014 int n = fprintf(f, "%c %s\n",
12015 GOT_HISTEDIT_MESG, hle->logmsg);
12016 if (n < 0) {
12017 err = got_ferror(f, GOT_ERR_IO);
12018 break;
12022 done:
12023 if (f && fclose(f) == EOF && err == NULL)
12024 err = got_error_from_errno("fclose");
12025 free(path);
12026 if (commit)
12027 got_object_commit_close(commit);
12028 return err;
12031 static void
12032 histedit_free_list(struct got_histedit_list *histedit_cmds)
12034 struct got_histedit_list_entry *hle;
12036 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12037 TAILQ_REMOVE(histedit_cmds, hle, entry);
12038 free(hle);
12042 static const struct got_error *
12043 histedit_load_list(struct got_histedit_list *histedit_cmds,
12044 const char *path, struct got_repository *repo)
12046 const struct got_error *err = NULL;
12047 FILE *f = NULL;
12049 f = fopen(path, "re");
12050 if (f == NULL) {
12051 err = got_error_from_errno2("fopen", path);
12052 goto done;
12055 err = histedit_parse_list(histedit_cmds, f, repo);
12056 done:
12057 if (f && fclose(f) == EOF && err == NULL)
12058 err = got_error_from_errno("fclose");
12059 return err;
12062 static const struct got_error *
12063 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12064 const struct got_error *edit_err, struct got_object_id_queue *commits,
12065 const char *path, const char *branch_name, struct got_repository *repo)
12067 const struct got_error *err = NULL, *prev_err = edit_err;
12068 int resp = ' ';
12070 while (resp != 'c' && resp != 'r' && resp != 'a') {
12071 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12072 "or (a)bort: ", getprogname(), prev_err->msg);
12073 resp = getchar();
12074 if (resp == '\n')
12075 resp = getchar();
12076 if (resp == 'c') {
12077 histedit_free_list(histedit_cmds);
12078 err = histedit_run_editor(histedit_cmds, path, commits,
12079 repo);
12080 if (err) {
12081 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12082 err->code != GOT_ERR_HISTEDIT_CMD)
12083 break;
12084 prev_err = err;
12085 resp = ' ';
12086 continue;
12088 break;
12089 } else if (resp == 'r') {
12090 histedit_free_list(histedit_cmds);
12091 err = histedit_edit_script(histedit_cmds,
12092 commits, branch_name, 0, 0, 0, 0, repo);
12093 if (err) {
12094 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12095 err->code != GOT_ERR_HISTEDIT_CMD)
12096 break;
12097 prev_err = err;
12098 resp = ' ';
12099 continue;
12101 break;
12102 } else if (resp == 'a') {
12103 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12104 break;
12105 } else
12106 printf("invalid response '%c'\n", resp);
12109 return err;
12112 static const struct got_error *
12113 histedit_complete(struct got_worktree *worktree,
12114 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12115 struct got_reference *branch, struct got_repository *repo)
12117 printf("Switching work tree to %s\n",
12118 got_ref_get_symref_target(branch));
12119 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12120 branch, repo);
12123 static const struct got_error *
12124 show_histedit_progress(struct got_commit_object *commit,
12125 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12127 const struct got_error *err;
12128 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12130 err = got_object_id_str(&old_id_str, hle->commit_id);
12131 if (err)
12132 goto done;
12134 if (new_id) {
12135 err = got_object_id_str(&new_id_str, new_id);
12136 if (err)
12137 goto done;
12140 old_id_str[12] = '\0';
12141 if (new_id_str)
12142 new_id_str[12] = '\0';
12144 if (hle->logmsg) {
12145 logmsg = strdup(hle->logmsg);
12146 if (logmsg == NULL) {
12147 err = got_error_from_errno("strdup");
12148 goto done;
12150 trim_logmsg(logmsg, 42);
12151 } else {
12152 err = get_short_logmsg(&logmsg, 42, commit);
12153 if (err)
12154 goto done;
12157 switch (hle->cmd->code) {
12158 case GOT_HISTEDIT_PICK:
12159 case GOT_HISTEDIT_EDIT:
12160 printf("%s -> %s: %s\n", old_id_str,
12161 new_id_str ? new_id_str : "no-op change", logmsg);
12162 break;
12163 case GOT_HISTEDIT_DROP:
12164 case GOT_HISTEDIT_FOLD:
12165 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12166 logmsg);
12167 break;
12168 default:
12169 break;
12171 done:
12172 free(old_id_str);
12173 free(new_id_str);
12174 return err;
12177 static const struct got_error *
12178 histedit_commit(struct got_pathlist_head *merged_paths,
12179 struct got_worktree *worktree, struct got_fileindex *fileindex,
12180 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12181 const char *committer, int allow_conflict, struct got_repository *repo)
12183 const struct got_error *err;
12184 struct got_commit_object *commit;
12185 struct got_object_id *new_commit_id;
12187 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12188 && hle->logmsg == NULL) {
12189 err = histedit_edit_logmsg(hle, repo);
12190 if (err)
12191 return err;
12194 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12195 if (err)
12196 return err;
12198 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12199 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12200 hle->logmsg, allow_conflict, repo);
12201 if (err) {
12202 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12203 goto done;
12204 err = show_histedit_progress(commit, hle, NULL);
12205 } else {
12206 err = show_histedit_progress(commit, hle, new_commit_id);
12207 free(new_commit_id);
12209 done:
12210 got_object_commit_close(commit);
12211 return err;
12214 static const struct got_error *
12215 histedit_skip_commit(struct got_histedit_list_entry *hle,
12216 struct got_worktree *worktree, struct got_repository *repo)
12218 const struct got_error *error;
12219 struct got_commit_object *commit;
12221 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12222 repo);
12223 if (error)
12224 return error;
12226 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12227 if (error)
12228 return error;
12230 error = show_histedit_progress(commit, hle, NULL);
12231 got_object_commit_close(commit);
12232 return error;
12235 static const struct got_error *
12236 check_local_changes(void *arg, unsigned char status,
12237 unsigned char staged_status, const char *path,
12238 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12239 struct got_object_id *commit_id, int dirfd, const char *de_name)
12241 int *have_local_changes = arg;
12243 switch (status) {
12244 case GOT_STATUS_ADD:
12245 case GOT_STATUS_DELETE:
12246 case GOT_STATUS_MODIFY:
12247 case GOT_STATUS_CONFLICT:
12248 *have_local_changes = 1;
12249 return got_error(GOT_ERR_CANCELLED);
12250 default:
12251 break;
12254 switch (staged_status) {
12255 case GOT_STATUS_ADD:
12256 case GOT_STATUS_DELETE:
12257 case GOT_STATUS_MODIFY:
12258 *have_local_changes = 1;
12259 return got_error(GOT_ERR_CANCELLED);
12260 default:
12261 break;
12264 return NULL;
12267 static const struct got_error *
12268 cmd_histedit(int argc, char *argv[])
12270 const struct got_error *error = NULL;
12271 struct got_worktree *worktree = NULL;
12272 struct got_fileindex *fileindex = NULL;
12273 struct got_repository *repo = NULL;
12274 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12275 struct got_reference *branch = NULL;
12276 struct got_reference *tmp_branch = NULL;
12277 struct got_object_id *resume_commit_id = NULL;
12278 struct got_object_id *base_commit_id = NULL;
12279 struct got_object_id *head_commit_id = NULL;
12280 struct got_commit_object *commit = NULL;
12281 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12282 struct got_update_progress_arg upa;
12283 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12284 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12285 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12286 const char *edit_script_path = NULL;
12287 struct got_object_id_queue commits;
12288 struct got_pathlist_head merged_paths;
12289 const struct got_object_id_queue *parent_ids;
12290 struct got_object_qid *pid;
12291 struct got_histedit_list histedit_cmds;
12292 struct got_histedit_list_entry *hle;
12293 int *pack_fds = NULL;
12295 STAILQ_INIT(&commits);
12296 TAILQ_INIT(&histedit_cmds);
12297 TAILQ_INIT(&merged_paths);
12298 memset(&upa, 0, sizeof(upa));
12300 #ifndef PROFILE
12301 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12302 "unveil", NULL) == -1)
12303 err(1, "pledge");
12304 #endif
12306 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12307 switch (ch) {
12308 case 'a':
12309 abort_edit = 1;
12310 break;
12311 case 'C':
12312 allow_conflict = 1;
12313 break;
12314 case 'c':
12315 continue_edit = 1;
12316 break;
12317 case 'd':
12318 drop_only = 1;
12319 break;
12320 case 'e':
12321 edit_only = 1;
12322 break;
12323 case 'F':
12324 edit_script_path = optarg;
12325 break;
12326 case 'f':
12327 fold_only = 1;
12328 break;
12329 case 'l':
12330 list_backups = 1;
12331 break;
12332 case 'm':
12333 edit_logmsg_only = 1;
12334 break;
12335 case 'X':
12336 delete_backups = 1;
12337 break;
12338 default:
12339 usage_histedit();
12340 /* NOTREACHED */
12344 argc -= optind;
12345 argv += optind;
12347 if (abort_edit && allow_conflict)
12348 option_conflict('a', 'C');
12349 if (abort_edit && continue_edit)
12350 option_conflict('a', 'c');
12351 if (edit_script_path && allow_conflict)
12352 option_conflict('F', 'C');
12353 if (edit_script_path && edit_logmsg_only)
12354 option_conflict('F', 'm');
12355 if (abort_edit && edit_logmsg_only)
12356 option_conflict('a', 'm');
12357 if (edit_logmsg_only && allow_conflict)
12358 option_conflict('m', 'C');
12359 if (continue_edit && edit_logmsg_only)
12360 option_conflict('c', 'm');
12361 if (abort_edit && fold_only)
12362 option_conflict('a', 'f');
12363 if (fold_only && allow_conflict)
12364 option_conflict('f', 'C');
12365 if (continue_edit && fold_only)
12366 option_conflict('c', 'f');
12367 if (fold_only && edit_logmsg_only)
12368 option_conflict('f', 'm');
12369 if (edit_script_path && fold_only)
12370 option_conflict('F', 'f');
12371 if (abort_edit && edit_only)
12372 option_conflict('a', 'e');
12373 if (continue_edit && edit_only)
12374 option_conflict('c', 'e');
12375 if (edit_only && edit_logmsg_only)
12376 option_conflict('e', 'm');
12377 if (edit_script_path && edit_only)
12378 option_conflict('F', 'e');
12379 if (fold_only && edit_only)
12380 option_conflict('f', 'e');
12381 if (drop_only && abort_edit)
12382 option_conflict('d', 'a');
12383 if (drop_only && allow_conflict)
12384 option_conflict('d', 'C');
12385 if (drop_only && continue_edit)
12386 option_conflict('d', 'c');
12387 if (drop_only && edit_logmsg_only)
12388 option_conflict('d', 'm');
12389 if (drop_only && edit_only)
12390 option_conflict('d', 'e');
12391 if (drop_only && edit_script_path)
12392 option_conflict('d', 'F');
12393 if (drop_only && fold_only)
12394 option_conflict('d', 'f');
12395 if (list_backups) {
12396 if (abort_edit)
12397 option_conflict('l', 'a');
12398 if (allow_conflict)
12399 option_conflict('l', 'C');
12400 if (continue_edit)
12401 option_conflict('l', 'c');
12402 if (edit_script_path)
12403 option_conflict('l', 'F');
12404 if (edit_logmsg_only)
12405 option_conflict('l', 'm');
12406 if (drop_only)
12407 option_conflict('l', 'd');
12408 if (fold_only)
12409 option_conflict('l', 'f');
12410 if (edit_only)
12411 option_conflict('l', 'e');
12412 if (delete_backups)
12413 option_conflict('l', 'X');
12414 if (argc != 0 && argc != 1)
12415 usage_histedit();
12416 } else if (delete_backups) {
12417 if (abort_edit)
12418 option_conflict('X', 'a');
12419 if (allow_conflict)
12420 option_conflict('X', 'C');
12421 if (continue_edit)
12422 option_conflict('X', 'c');
12423 if (drop_only)
12424 option_conflict('X', 'd');
12425 if (edit_script_path)
12426 option_conflict('X', 'F');
12427 if (edit_logmsg_only)
12428 option_conflict('X', 'm');
12429 if (fold_only)
12430 option_conflict('X', 'f');
12431 if (edit_only)
12432 option_conflict('X', 'e');
12433 if (list_backups)
12434 option_conflict('X', 'l');
12435 if (argc != 0 && argc != 1)
12436 usage_histedit();
12437 } else if (allow_conflict && !continue_edit)
12438 errx(1, "-C option requires -c");
12439 else if (argc != 0)
12440 usage_histedit();
12443 * This command cannot apply unveil(2) in all cases because the
12444 * user may choose to run an editor to edit the histedit script
12445 * and to edit individual commit log messages.
12446 * unveil(2) traverses exec(2); if an editor is used we have to
12447 * apply unveil after edit script and log messages have been written.
12448 * XXX TODO: Make use of unveil(2) where possible.
12451 cwd = getcwd(NULL, 0);
12452 if (cwd == NULL) {
12453 error = got_error_from_errno("getcwd");
12454 goto done;
12457 error = got_repo_pack_fds_open(&pack_fds);
12458 if (error != NULL)
12459 goto done;
12461 error = got_worktree_open(&worktree, cwd);
12462 if (error) {
12463 if (list_backups || delete_backups) {
12464 if (error->code != GOT_ERR_NOT_WORKTREE)
12465 goto done;
12466 } else {
12467 if (error->code == GOT_ERR_NOT_WORKTREE)
12468 error = wrap_not_worktree_error(error,
12469 "histedit", cwd);
12470 goto done;
12474 if (list_backups || delete_backups) {
12475 error = got_repo_open(&repo,
12476 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12477 NULL, pack_fds);
12478 if (error != NULL)
12479 goto done;
12480 error = apply_unveil(got_repo_get_path(repo), 0,
12481 worktree ? got_worktree_get_root_path(worktree) : NULL);
12482 if (error)
12483 goto done;
12484 error = process_backup_refs(
12485 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12486 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12487 goto done; /* nothing else to do */
12490 error = get_gitconfig_path(&gitconfig_path);
12491 if (error)
12492 goto done;
12493 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12494 gitconfig_path, pack_fds);
12495 if (error != NULL)
12496 goto done;
12498 if (worktree != NULL && !list_backups && !delete_backups) {
12499 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12500 if (error)
12501 goto done;
12504 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12505 if (error)
12506 goto done;
12507 if (rebase_in_progress) {
12508 error = got_error(GOT_ERR_REBASING);
12509 goto done;
12512 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12513 repo);
12514 if (error)
12515 goto done;
12516 if (merge_in_progress) {
12517 error = got_error(GOT_ERR_MERGE_BUSY);
12518 goto done;
12521 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12522 if (error)
12523 goto done;
12525 if (edit_in_progress && edit_logmsg_only) {
12526 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12527 "histedit operation is in progress in this "
12528 "work tree and must be continued or aborted "
12529 "before the -m option can be used");
12530 goto done;
12532 if (edit_in_progress && drop_only) {
12533 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12534 "histedit operation is in progress in this "
12535 "work tree and must be continued or aborted "
12536 "before the -d option can be used");
12537 goto done;
12539 if (edit_in_progress && fold_only) {
12540 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12541 "histedit operation is in progress in this "
12542 "work tree and must be continued or aborted "
12543 "before the -f option can be used");
12544 goto done;
12546 if (edit_in_progress && edit_only) {
12547 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12548 "histedit operation is in progress in this "
12549 "work tree and must be continued or aborted "
12550 "before the -e option can be used");
12551 goto done;
12554 if (edit_in_progress && abort_edit) {
12555 error = got_worktree_histedit_continue(&resume_commit_id,
12556 &tmp_branch, &branch, &base_commit_id, &fileindex,
12557 worktree, repo);
12558 if (error)
12559 goto done;
12560 printf("Switching work tree to %s\n",
12561 got_ref_get_symref_target(branch));
12562 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12563 branch, base_commit_id, abort_progress, &upa);
12564 if (error)
12565 goto done;
12566 printf("Histedit of %s aborted\n",
12567 got_ref_get_symref_target(branch));
12568 print_merge_progress_stats(&upa);
12569 goto done; /* nothing else to do */
12570 } else if (abort_edit) {
12571 error = got_error(GOT_ERR_NOT_HISTEDIT);
12572 goto done;
12575 error = get_author(&committer, repo, worktree);
12576 if (error)
12577 goto done;
12579 if (continue_edit) {
12580 char *path;
12582 if (!edit_in_progress) {
12583 error = got_error(GOT_ERR_NOT_HISTEDIT);
12584 goto done;
12587 error = got_worktree_get_histedit_script_path(&path, worktree);
12588 if (error)
12589 goto done;
12591 error = histedit_load_list(&histedit_cmds, path, repo);
12592 free(path);
12593 if (error)
12594 goto done;
12596 error = got_worktree_histedit_continue(&resume_commit_id,
12597 &tmp_branch, &branch, &base_commit_id, &fileindex,
12598 worktree, repo);
12599 if (error)
12600 goto done;
12602 error = got_ref_resolve(&head_commit_id, repo, branch);
12603 if (error)
12604 goto done;
12606 error = got_object_open_as_commit(&commit, repo,
12607 head_commit_id);
12608 if (error)
12609 goto done;
12610 parent_ids = got_object_commit_get_parent_ids(commit);
12611 pid = STAILQ_FIRST(parent_ids);
12612 if (pid == NULL) {
12613 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12614 goto done;
12616 error = collect_commits(&commits, head_commit_id, &pid->id,
12617 base_commit_id, got_worktree_get_path_prefix(worktree),
12618 GOT_ERR_HISTEDIT_PATH, repo);
12619 got_object_commit_close(commit);
12620 commit = NULL;
12621 if (error)
12622 goto done;
12623 } else {
12624 if (edit_in_progress) {
12625 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12626 goto done;
12629 error = got_ref_open(&branch, repo,
12630 got_worktree_get_head_ref_name(worktree), 0);
12631 if (error != NULL)
12632 goto done;
12634 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12635 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12636 "will not edit commit history of a branch outside "
12637 "the \"refs/heads/\" reference namespace");
12638 goto done;
12641 error = got_ref_resolve(&head_commit_id, repo, branch);
12642 got_ref_close(branch);
12643 branch = NULL;
12644 if (error)
12645 goto done;
12647 error = got_object_open_as_commit(&commit, repo,
12648 head_commit_id);
12649 if (error)
12650 goto done;
12651 parent_ids = got_object_commit_get_parent_ids(commit);
12652 pid = STAILQ_FIRST(parent_ids);
12653 if (pid == NULL) {
12654 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12655 goto done;
12657 error = collect_commits(&commits, head_commit_id, &pid->id,
12658 got_worktree_get_base_commit_id(worktree),
12659 got_worktree_get_path_prefix(worktree),
12660 GOT_ERR_HISTEDIT_PATH, repo);
12661 got_object_commit_close(commit);
12662 commit = NULL;
12663 if (error)
12664 goto done;
12666 if (STAILQ_EMPTY(&commits)) {
12667 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12668 goto done;
12671 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12672 &base_commit_id, &fileindex, worktree, repo);
12673 if (error)
12674 goto done;
12676 if (edit_script_path) {
12677 error = histedit_load_list(&histedit_cmds,
12678 edit_script_path, repo);
12679 if (error) {
12680 got_worktree_histedit_abort(worktree, fileindex,
12681 repo, branch, base_commit_id,
12682 abort_progress, &upa);
12683 print_merge_progress_stats(&upa);
12684 goto done;
12686 } else {
12687 const char *branch_name;
12688 branch_name = got_ref_get_symref_target(branch);
12689 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12690 branch_name += 11;
12691 error = histedit_edit_script(&histedit_cmds, &commits,
12692 branch_name, edit_logmsg_only, fold_only,
12693 drop_only, edit_only, repo);
12694 if (error) {
12695 got_worktree_histedit_abort(worktree, fileindex,
12696 repo, branch, base_commit_id,
12697 abort_progress, &upa);
12698 print_merge_progress_stats(&upa);
12699 goto done;
12704 error = histedit_save_list(&histedit_cmds, worktree,
12705 repo);
12706 if (error) {
12707 got_worktree_histedit_abort(worktree, fileindex,
12708 repo, branch, base_commit_id,
12709 abort_progress, &upa);
12710 print_merge_progress_stats(&upa);
12711 goto done;
12716 error = histedit_check_script(&histedit_cmds, &commits, repo);
12717 if (error)
12718 goto done;
12720 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12721 if (resume_commit_id) {
12722 if (got_object_id_cmp(hle->commit_id,
12723 resume_commit_id) != 0)
12724 continue;
12726 resume_commit_id = NULL;
12727 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12728 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12729 error = histedit_skip_commit(hle, worktree,
12730 repo);
12731 if (error)
12732 goto done;
12733 } else {
12734 struct got_pathlist_head paths;
12735 int have_changes = 0;
12737 TAILQ_INIT(&paths);
12738 error = got_pathlist_append(&paths, "", NULL);
12739 if (error)
12740 goto done;
12741 error = got_worktree_status(worktree, &paths,
12742 repo, 0, check_local_changes, &have_changes,
12743 check_cancelled, NULL);
12744 got_pathlist_free(&paths,
12745 GOT_PATHLIST_FREE_NONE);
12746 if (error) {
12747 if (error->code != GOT_ERR_CANCELLED)
12748 goto done;
12749 if (sigint_received || sigpipe_received)
12750 goto done;
12752 if (have_changes) {
12753 error = histedit_commit(NULL, worktree,
12754 fileindex, tmp_branch, hle,
12755 committer, allow_conflict, repo);
12756 if (error)
12757 goto done;
12758 } else {
12759 error = got_object_open_as_commit(
12760 &commit, repo, hle->commit_id);
12761 if (error)
12762 goto done;
12763 error = show_histedit_progress(commit,
12764 hle, NULL);
12765 got_object_commit_close(commit);
12766 commit = NULL;
12767 if (error)
12768 goto done;
12771 continue;
12774 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12775 error = histedit_skip_commit(hle, worktree, repo);
12776 if (error)
12777 goto done;
12778 continue;
12781 error = got_object_open_as_commit(&commit, repo,
12782 hle->commit_id);
12783 if (error)
12784 goto done;
12785 parent_ids = got_object_commit_get_parent_ids(commit);
12786 pid = STAILQ_FIRST(parent_ids);
12788 error = got_worktree_histedit_merge_files(&merged_paths,
12789 worktree, fileindex, &pid->id, hle->commit_id, repo,
12790 update_progress, &upa, check_cancelled, NULL);
12791 if (error)
12792 goto done;
12793 got_object_commit_close(commit);
12794 commit = NULL;
12796 print_merge_progress_stats(&upa);
12797 if (upa.conflicts > 0 || upa.missing > 0 ||
12798 upa.not_deleted > 0 || upa.unversioned > 0) {
12799 if (upa.conflicts > 0) {
12800 error = show_rebase_merge_conflict(
12801 hle->commit_id, repo);
12802 if (error)
12803 goto done;
12805 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12806 break;
12809 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12810 char *id_str;
12811 error = got_object_id_str(&id_str, hle->commit_id);
12812 if (error)
12813 goto done;
12814 printf("Stopping histedit for amending commit %s\n",
12815 id_str);
12816 free(id_str);
12817 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12818 error = got_worktree_histedit_postpone(worktree,
12819 fileindex);
12820 goto done;
12823 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12824 error = histedit_skip_commit(hle, worktree, repo);
12825 if (error)
12826 goto done;
12827 continue;
12830 error = histedit_commit(&merged_paths, worktree, fileindex,
12831 tmp_branch, hle, committer, allow_conflict, repo);
12832 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12833 if (error)
12834 goto done;
12837 if (upa.conflicts > 0 || upa.missing > 0 ||
12838 upa.not_deleted > 0 || upa.unversioned > 0) {
12839 error = got_worktree_histedit_postpone(worktree, fileindex);
12840 if (error)
12841 goto done;
12842 if (upa.conflicts > 0 && upa.missing == 0 &&
12843 upa.not_deleted == 0 && upa.unversioned == 0) {
12844 error = got_error_msg(GOT_ERR_CONFLICTS,
12845 "conflicts must be resolved before histedit "
12846 "can continue");
12847 } else if (upa.conflicts > 0) {
12848 error = got_error_msg(GOT_ERR_CONFLICTS,
12849 "conflicts must be resolved before histedit "
12850 "can continue; changes destined for some "
12851 "files were not yet merged and should be "
12852 "merged manually if required before the "
12853 "histedit operation is continued");
12854 } else {
12855 error = got_error_msg(GOT_ERR_CONFLICTS,
12856 "changes destined for some files were not "
12857 "yet merged and should be merged manually "
12858 "if required before the histedit operation "
12859 "is continued");
12861 } else
12862 error = histedit_complete(worktree, fileindex, tmp_branch,
12863 branch, repo);
12864 done:
12865 free(cwd);
12866 free(committer);
12867 free(gitconfig_path);
12868 got_object_id_queue_free(&commits);
12869 histedit_free_list(&histedit_cmds);
12870 free(head_commit_id);
12871 free(base_commit_id);
12872 free(resume_commit_id);
12873 if (commit)
12874 got_object_commit_close(commit);
12875 if (branch)
12876 got_ref_close(branch);
12877 if (tmp_branch)
12878 got_ref_close(tmp_branch);
12879 if (worktree)
12880 got_worktree_close(worktree);
12881 if (repo) {
12882 const struct got_error *close_err = got_repo_close(repo);
12883 if (error == NULL)
12884 error = close_err;
12886 if (pack_fds) {
12887 const struct got_error *pack_err =
12888 got_repo_pack_fds_close(pack_fds);
12889 if (error == NULL)
12890 error = pack_err;
12892 return error;
12895 __dead static void
12896 usage_integrate(void)
12898 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12899 exit(1);
12902 static const struct got_error *
12903 cmd_integrate(int argc, char *argv[])
12905 const struct got_error *error = NULL;
12906 struct got_repository *repo = NULL;
12907 struct got_worktree *worktree = NULL;
12908 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12909 const char *branch_arg = NULL;
12910 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12911 struct got_fileindex *fileindex = NULL;
12912 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12913 int ch;
12914 struct got_update_progress_arg upa;
12915 int *pack_fds = NULL;
12917 #ifndef PROFILE
12918 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12919 "unveil", NULL) == -1)
12920 err(1, "pledge");
12921 #endif
12923 while ((ch = getopt(argc, argv, "")) != -1) {
12924 switch (ch) {
12925 default:
12926 usage_integrate();
12927 /* NOTREACHED */
12931 argc -= optind;
12932 argv += optind;
12934 if (argc != 1)
12935 usage_integrate();
12936 branch_arg = argv[0];
12938 cwd = getcwd(NULL, 0);
12939 if (cwd == NULL) {
12940 error = got_error_from_errno("getcwd");
12941 goto done;
12944 error = got_repo_pack_fds_open(&pack_fds);
12945 if (error != NULL)
12946 goto done;
12948 error = got_worktree_open(&worktree, cwd);
12949 if (error) {
12950 if (error->code == GOT_ERR_NOT_WORKTREE)
12951 error = wrap_not_worktree_error(error, "integrate",
12952 cwd);
12953 goto done;
12956 error = check_rebase_or_histedit_in_progress(worktree);
12957 if (error)
12958 goto done;
12960 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12961 NULL, pack_fds);
12962 if (error != NULL)
12963 goto done;
12965 error = apply_unveil(got_repo_get_path(repo), 0,
12966 got_worktree_get_root_path(worktree));
12967 if (error)
12968 goto done;
12970 error = check_merge_in_progress(worktree, repo);
12971 if (error)
12972 goto done;
12974 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12975 error = got_error_from_errno("asprintf");
12976 goto done;
12979 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12980 &base_branch_ref, worktree, refname, repo);
12981 if (error)
12982 goto done;
12984 refname = strdup(got_ref_get_name(branch_ref));
12985 if (refname == NULL) {
12986 error = got_error_from_errno("strdup");
12987 got_worktree_integrate_abort(worktree, fileindex, repo,
12988 branch_ref, base_branch_ref);
12989 goto done;
12991 base_refname = strdup(got_ref_get_name(base_branch_ref));
12992 if (base_refname == NULL) {
12993 error = got_error_from_errno("strdup");
12994 got_worktree_integrate_abort(worktree, fileindex, repo,
12995 branch_ref, base_branch_ref);
12996 goto done;
12998 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12999 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13000 got_worktree_integrate_abort(worktree, fileindex, repo,
13001 branch_ref, base_branch_ref);
13002 goto done;
13005 error = got_ref_resolve(&commit_id, repo, branch_ref);
13006 if (error)
13007 goto done;
13009 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13010 if (error)
13011 goto done;
13013 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13014 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13015 "specified branch has already been integrated");
13016 got_worktree_integrate_abort(worktree, fileindex, repo,
13017 branch_ref, base_branch_ref);
13018 goto done;
13021 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13022 if (error) {
13023 if (error->code == GOT_ERR_ANCESTRY)
13024 error = got_error(GOT_ERR_REBASE_REQUIRED);
13025 got_worktree_integrate_abort(worktree, fileindex, repo,
13026 branch_ref, base_branch_ref);
13027 goto done;
13030 memset(&upa, 0, sizeof(upa));
13031 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13032 branch_ref, base_branch_ref, update_progress, &upa,
13033 check_cancelled, NULL);
13034 if (error)
13035 goto done;
13037 printf("Integrated %s into %s\n", refname, base_refname);
13038 print_update_progress_stats(&upa);
13039 done:
13040 if (repo) {
13041 const struct got_error *close_err = got_repo_close(repo);
13042 if (error == NULL)
13043 error = close_err;
13045 if (worktree)
13046 got_worktree_close(worktree);
13047 if (pack_fds) {
13048 const struct got_error *pack_err =
13049 got_repo_pack_fds_close(pack_fds);
13050 if (error == NULL)
13051 error = pack_err;
13053 free(cwd);
13054 free(base_commit_id);
13055 free(commit_id);
13056 free(refname);
13057 free(base_refname);
13058 return error;
13061 __dead static void
13062 usage_merge(void)
13064 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13065 exit(1);
13068 static const struct got_error *
13069 cmd_merge(int argc, char *argv[])
13071 const struct got_error *error = NULL;
13072 struct got_worktree *worktree = NULL;
13073 struct got_repository *repo = NULL;
13074 struct got_fileindex *fileindex = NULL;
13075 char *cwd = NULL, *id_str = NULL, *author = NULL;
13076 char *gitconfig_path = NULL;
13077 struct got_reference *branch = NULL, *wt_branch = NULL;
13078 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13079 struct got_object_id *wt_branch_tip = NULL;
13080 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13081 int allow_conflict = 0, interrupt_merge = 0;
13082 struct got_update_progress_arg upa;
13083 struct got_object_id *merge_commit_id = NULL;
13084 char *branch_name = NULL;
13085 int *pack_fds = NULL;
13087 memset(&upa, 0, sizeof(upa));
13089 #ifndef PROFILE
13090 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13091 "unveil", NULL) == -1)
13092 err(1, "pledge");
13093 #endif
13095 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13096 switch (ch) {
13097 case 'a':
13098 abort_merge = 1;
13099 break;
13100 case 'C':
13101 allow_conflict = 1;
13102 case 'c':
13103 continue_merge = 1;
13104 break;
13105 case 'n':
13106 interrupt_merge = 1;
13107 break;
13108 default:
13109 usage_merge();
13110 /* NOTREACHED */
13114 argc -= optind;
13115 argv += optind;
13117 if (allow_conflict) {
13118 if (abort_merge)
13119 option_conflict('a', 'C');
13120 if (!continue_merge)
13121 errx(1, "-C option requires -c");
13123 if (abort_merge && continue_merge)
13124 option_conflict('a', 'c');
13125 if (abort_merge || continue_merge) {
13126 if (argc != 0)
13127 usage_merge();
13128 } else if (argc != 1)
13129 usage_merge();
13131 cwd = getcwd(NULL, 0);
13132 if (cwd == NULL) {
13133 error = got_error_from_errno("getcwd");
13134 goto done;
13137 error = got_repo_pack_fds_open(&pack_fds);
13138 if (error != NULL)
13139 goto done;
13141 error = got_worktree_open(&worktree, cwd);
13142 if (error) {
13143 if (error->code == GOT_ERR_NOT_WORKTREE)
13144 error = wrap_not_worktree_error(error,
13145 "merge", cwd);
13146 goto done;
13149 error = get_gitconfig_path(&gitconfig_path);
13150 if (error)
13151 goto done;
13152 error = got_repo_open(&repo,
13153 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13154 gitconfig_path, pack_fds);
13155 if (error != NULL)
13156 goto done;
13158 if (worktree != NULL) {
13159 error = worktree_has_logmsg_ref("merge", worktree, repo);
13160 if (error)
13161 goto done;
13164 error = apply_unveil(got_repo_get_path(repo), 0,
13165 worktree ? got_worktree_get_root_path(worktree) : NULL);
13166 if (error)
13167 goto done;
13169 error = check_rebase_or_histedit_in_progress(worktree);
13170 if (error)
13171 goto done;
13173 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13174 repo);
13175 if (error)
13176 goto done;
13178 if (abort_merge) {
13179 if (!merge_in_progress) {
13180 error = got_error(GOT_ERR_NOT_MERGING);
13181 goto done;
13183 error = got_worktree_merge_continue(&branch_name,
13184 &branch_tip, &fileindex, worktree, repo);
13185 if (error)
13186 goto done;
13187 error = got_worktree_merge_abort(worktree, fileindex, repo,
13188 abort_progress, &upa);
13189 if (error)
13190 goto done;
13191 printf("Merge of %s aborted\n", branch_name);
13192 goto done; /* nothing else to do */
13195 error = get_author(&author, repo, worktree);
13196 if (error)
13197 goto done;
13199 if (continue_merge) {
13200 if (!merge_in_progress) {
13201 error = got_error(GOT_ERR_NOT_MERGING);
13202 goto done;
13204 error = got_worktree_merge_continue(&branch_name,
13205 &branch_tip, &fileindex, worktree, repo);
13206 if (error)
13207 goto done;
13208 } else {
13209 error = got_ref_open(&branch, repo, argv[0], 0);
13210 if (error != NULL)
13211 goto done;
13212 branch_name = strdup(got_ref_get_name(branch));
13213 if (branch_name == NULL) {
13214 error = got_error_from_errno("strdup");
13215 goto done;
13217 error = got_ref_resolve(&branch_tip, repo, branch);
13218 if (error)
13219 goto done;
13222 error = got_ref_open(&wt_branch, repo,
13223 got_worktree_get_head_ref_name(worktree), 0);
13224 if (error)
13225 goto done;
13226 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13227 if (error)
13228 goto done;
13229 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13230 wt_branch_tip, branch_tip, 0, repo,
13231 check_cancelled, NULL);
13232 if (error && error->code != GOT_ERR_ANCESTRY)
13233 goto done;
13235 if (!continue_merge) {
13236 error = check_path_prefix(wt_branch_tip, branch_tip,
13237 got_worktree_get_path_prefix(worktree),
13238 GOT_ERR_MERGE_PATH, repo);
13239 if (error)
13240 goto done;
13241 if (yca_id) {
13242 error = check_same_branch(wt_branch_tip, branch,
13243 yca_id, repo);
13244 if (error) {
13245 if (error->code != GOT_ERR_ANCESTRY)
13246 goto done;
13247 error = NULL;
13248 } else {
13249 static char msg[512];
13250 snprintf(msg, sizeof(msg),
13251 "cannot create a merge commit because "
13252 "%s is based on %s; %s can be integrated "
13253 "with 'got integrate' instead", branch_name,
13254 got_worktree_get_head_ref_name(worktree),
13255 branch_name);
13256 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13257 goto done;
13260 error = got_worktree_merge_prepare(&fileindex, worktree,
13261 branch, repo);
13262 if (error)
13263 goto done;
13265 error = got_worktree_merge_branch(worktree, fileindex,
13266 yca_id, branch_tip, repo, update_progress, &upa,
13267 check_cancelled, NULL);
13268 if (error)
13269 goto done;
13270 print_merge_progress_stats(&upa);
13271 if (!upa.did_something) {
13272 error = got_worktree_merge_abort(worktree, fileindex,
13273 repo, abort_progress, &upa);
13274 if (error)
13275 goto done;
13276 printf("Already up-to-date\n");
13277 goto done;
13281 if (interrupt_merge) {
13282 error = got_worktree_merge_postpone(worktree, fileindex);
13283 if (error)
13284 goto done;
13285 printf("Merge of %s interrupted on request\n", branch_name);
13286 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13287 upa.not_deleted > 0 || upa.unversioned > 0) {
13288 error = got_worktree_merge_postpone(worktree, fileindex);
13289 if (error)
13290 goto done;
13291 if (upa.conflicts > 0 && upa.missing == 0 &&
13292 upa.not_deleted == 0 && upa.unversioned == 0) {
13293 error = got_error_msg(GOT_ERR_CONFLICTS,
13294 "conflicts must be resolved before merging "
13295 "can continue");
13296 } else if (upa.conflicts > 0) {
13297 error = got_error_msg(GOT_ERR_CONFLICTS,
13298 "conflicts must be resolved before merging "
13299 "can continue; changes destined for some "
13300 "files were not yet merged and "
13301 "should be merged manually if required before the "
13302 "merge operation is continued");
13303 } else {
13304 error = got_error_msg(GOT_ERR_CONFLICTS,
13305 "changes destined for some "
13306 "files were not yet merged and should be "
13307 "merged manually if required before the "
13308 "merge operation is continued");
13310 goto done;
13311 } else {
13312 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13313 fileindex, author, NULL, 1, branch_tip, branch_name,
13314 allow_conflict, repo, continue_merge ? print_status : NULL,
13315 NULL);
13316 if (error)
13317 goto done;
13318 error = got_worktree_merge_complete(worktree, fileindex, repo);
13319 if (error)
13320 goto done;
13321 error = got_object_id_str(&id_str, merge_commit_id);
13322 if (error)
13323 goto done;
13324 printf("Merged %s into %s: %s\n", branch_name,
13325 got_worktree_get_head_ref_name(worktree),
13326 id_str);
13329 done:
13330 free(gitconfig_path);
13331 free(id_str);
13332 free(merge_commit_id);
13333 free(author);
13334 free(branch_tip);
13335 free(branch_name);
13336 free(yca_id);
13337 if (branch)
13338 got_ref_close(branch);
13339 if (wt_branch)
13340 got_ref_close(wt_branch);
13341 if (worktree)
13342 got_worktree_close(worktree);
13343 if (repo) {
13344 const struct got_error *close_err = got_repo_close(repo);
13345 if (error == NULL)
13346 error = close_err;
13348 if (pack_fds) {
13349 const struct got_error *pack_err =
13350 got_repo_pack_fds_close(pack_fds);
13351 if (error == NULL)
13352 error = pack_err;
13354 return error;
13357 __dead static void
13358 usage_stage(void)
13360 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13361 "[path ...]\n", getprogname());
13362 exit(1);
13365 static const struct got_error *
13366 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13367 const char *path, struct got_object_id *blob_id,
13368 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13369 int dirfd, const char *de_name)
13371 const struct got_error *err = NULL;
13372 char *id_str = NULL;
13374 if (staged_status != GOT_STATUS_ADD &&
13375 staged_status != GOT_STATUS_MODIFY &&
13376 staged_status != GOT_STATUS_DELETE)
13377 return NULL;
13379 if (staged_status == GOT_STATUS_ADD ||
13380 staged_status == GOT_STATUS_MODIFY)
13381 err = got_object_id_str(&id_str, staged_blob_id);
13382 else
13383 err = got_object_id_str(&id_str, blob_id);
13384 if (err)
13385 return err;
13387 printf("%s %c %s\n", id_str, staged_status, path);
13388 free(id_str);
13389 return NULL;
13392 static const struct got_error *
13393 cmd_stage(int argc, char *argv[])
13395 const struct got_error *error = NULL;
13396 struct got_repository *repo = NULL;
13397 struct got_worktree *worktree = NULL;
13398 char *cwd = NULL;
13399 struct got_pathlist_head paths;
13400 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13401 FILE *patch_script_file = NULL;
13402 const char *patch_script_path = NULL;
13403 struct choose_patch_arg cpa;
13404 int *pack_fds = NULL;
13406 TAILQ_INIT(&paths);
13408 #ifndef PROFILE
13409 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13410 "unveil", NULL) == -1)
13411 err(1, "pledge");
13412 #endif
13414 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13415 switch (ch) {
13416 case 'F':
13417 patch_script_path = optarg;
13418 break;
13419 case 'l':
13420 list_stage = 1;
13421 break;
13422 case 'p':
13423 pflag = 1;
13424 break;
13425 case 'S':
13426 allow_bad_symlinks = 1;
13427 break;
13428 default:
13429 usage_stage();
13430 /* NOTREACHED */
13434 argc -= optind;
13435 argv += optind;
13437 if (list_stage && (pflag || patch_script_path))
13438 errx(1, "-l option cannot be used with other options");
13439 if (patch_script_path && !pflag)
13440 errx(1, "-F option can only be used together with -p option");
13442 cwd = getcwd(NULL, 0);
13443 if (cwd == NULL) {
13444 error = got_error_from_errno("getcwd");
13445 goto done;
13448 error = got_repo_pack_fds_open(&pack_fds);
13449 if (error != NULL)
13450 goto done;
13452 error = got_worktree_open(&worktree, cwd);
13453 if (error) {
13454 if (error->code == GOT_ERR_NOT_WORKTREE)
13455 error = wrap_not_worktree_error(error, "stage", cwd);
13456 goto done;
13459 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13460 NULL, pack_fds);
13461 if (error != NULL)
13462 goto done;
13464 if (patch_script_path) {
13465 patch_script_file = fopen(patch_script_path, "re");
13466 if (patch_script_file == NULL) {
13467 error = got_error_from_errno2("fopen",
13468 patch_script_path);
13469 goto done;
13472 error = apply_unveil(got_repo_get_path(repo), 0,
13473 got_worktree_get_root_path(worktree));
13474 if (error)
13475 goto done;
13477 error = check_merge_in_progress(worktree, repo);
13478 if (error)
13479 goto done;
13481 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13482 if (error)
13483 goto done;
13485 if (list_stage)
13486 error = got_worktree_status(worktree, &paths, repo, 0,
13487 print_stage, NULL, check_cancelled, NULL);
13488 else {
13489 cpa.patch_script_file = patch_script_file;
13490 cpa.action = "stage";
13491 error = got_worktree_stage(worktree, &paths,
13492 pflag ? NULL : print_status, NULL,
13493 pflag ? choose_patch : NULL, &cpa,
13494 allow_bad_symlinks, repo);
13496 done:
13497 if (patch_script_file && fclose(patch_script_file) == EOF &&
13498 error == NULL)
13499 error = got_error_from_errno2("fclose", patch_script_path);
13500 if (repo) {
13501 const struct got_error *close_err = got_repo_close(repo);
13502 if (error == NULL)
13503 error = close_err;
13505 if (worktree)
13506 got_worktree_close(worktree);
13507 if (pack_fds) {
13508 const struct got_error *pack_err =
13509 got_repo_pack_fds_close(pack_fds);
13510 if (error == NULL)
13511 error = pack_err;
13513 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13514 free(cwd);
13515 return error;
13518 __dead static void
13519 usage_unstage(void)
13521 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13522 "[path ...]\n", getprogname());
13523 exit(1);
13527 static const struct got_error *
13528 cmd_unstage(int argc, char *argv[])
13530 const struct got_error *error = NULL;
13531 struct got_repository *repo = NULL;
13532 struct got_worktree *worktree = NULL;
13533 char *cwd = NULL;
13534 struct got_pathlist_head paths;
13535 int ch, pflag = 0;
13536 struct got_update_progress_arg upa;
13537 FILE *patch_script_file = NULL;
13538 const char *patch_script_path = NULL;
13539 struct choose_patch_arg cpa;
13540 int *pack_fds = NULL;
13542 TAILQ_INIT(&paths);
13544 #ifndef PROFILE
13545 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13546 "unveil", NULL) == -1)
13547 err(1, "pledge");
13548 #endif
13550 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13551 switch (ch) {
13552 case 'F':
13553 patch_script_path = optarg;
13554 break;
13555 case 'p':
13556 pflag = 1;
13557 break;
13558 default:
13559 usage_unstage();
13560 /* NOTREACHED */
13564 argc -= optind;
13565 argv += optind;
13567 if (patch_script_path && !pflag)
13568 errx(1, "-F option can only be used together with -p option");
13570 cwd = getcwd(NULL, 0);
13571 if (cwd == NULL) {
13572 error = got_error_from_errno("getcwd");
13573 goto done;
13576 error = got_repo_pack_fds_open(&pack_fds);
13577 if (error != NULL)
13578 goto done;
13580 error = got_worktree_open(&worktree, cwd);
13581 if (error) {
13582 if (error->code == GOT_ERR_NOT_WORKTREE)
13583 error = wrap_not_worktree_error(error, "unstage", cwd);
13584 goto done;
13587 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13588 NULL, pack_fds);
13589 if (error != NULL)
13590 goto done;
13592 if (patch_script_path) {
13593 patch_script_file = fopen(patch_script_path, "re");
13594 if (patch_script_file == NULL) {
13595 error = got_error_from_errno2("fopen",
13596 patch_script_path);
13597 goto done;
13601 error = apply_unveil(got_repo_get_path(repo), 0,
13602 got_worktree_get_root_path(worktree));
13603 if (error)
13604 goto done;
13606 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13607 if (error)
13608 goto done;
13610 cpa.patch_script_file = patch_script_file;
13611 cpa.action = "unstage";
13612 memset(&upa, 0, sizeof(upa));
13613 error = got_worktree_unstage(worktree, &paths, update_progress,
13614 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13615 if (!error)
13616 print_merge_progress_stats(&upa);
13617 done:
13618 if (patch_script_file && fclose(patch_script_file) == EOF &&
13619 error == NULL)
13620 error = got_error_from_errno2("fclose", patch_script_path);
13621 if (repo) {
13622 const struct got_error *close_err = got_repo_close(repo);
13623 if (error == NULL)
13624 error = close_err;
13626 if (worktree)
13627 got_worktree_close(worktree);
13628 if (pack_fds) {
13629 const struct got_error *pack_err =
13630 got_repo_pack_fds_close(pack_fds);
13631 if (error == NULL)
13632 error = pack_err;
13634 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13635 free(cwd);
13636 return error;
13639 __dead static void
13640 usage_cat(void)
13642 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13643 "arg ...\n", getprogname());
13644 exit(1);
13647 static const struct got_error *
13648 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13650 const struct got_error *err;
13651 struct got_blob_object *blob;
13652 int fd = -1;
13654 fd = got_opentempfd();
13655 if (fd == -1)
13656 return got_error_from_errno("got_opentempfd");
13658 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13659 if (err)
13660 goto done;
13662 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13663 done:
13664 if (fd != -1 && close(fd) == -1 && err == NULL)
13665 err = got_error_from_errno("close");
13666 if (blob)
13667 got_object_blob_close(blob);
13668 return err;
13671 static const struct got_error *
13672 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13674 const struct got_error *err;
13675 struct got_tree_object *tree;
13676 int nentries, i;
13678 err = got_object_open_as_tree(&tree, repo, id);
13679 if (err)
13680 return err;
13682 nentries = got_object_tree_get_nentries(tree);
13683 for (i = 0; i < nentries; i++) {
13684 struct got_tree_entry *te;
13685 char *id_str;
13686 if (sigint_received || sigpipe_received)
13687 break;
13688 te = got_object_tree_get_entry(tree, i);
13689 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13690 if (err)
13691 break;
13692 fprintf(outfile, "%s %.7o %s\n", id_str,
13693 got_tree_entry_get_mode(te),
13694 got_tree_entry_get_name(te));
13695 free(id_str);
13698 got_object_tree_close(tree);
13699 return err;
13702 static const struct got_error *
13703 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13705 const struct got_error *err;
13706 struct got_commit_object *commit;
13707 const struct got_object_id_queue *parent_ids;
13708 struct got_object_qid *pid;
13709 char *id_str = NULL;
13710 const char *logmsg = NULL;
13711 char gmtoff[6];
13713 err = got_object_open_as_commit(&commit, repo, id);
13714 if (err)
13715 return err;
13717 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13718 if (err)
13719 goto done;
13721 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13722 parent_ids = got_object_commit_get_parent_ids(commit);
13723 fprintf(outfile, "numparents %d\n",
13724 got_object_commit_get_nparents(commit));
13725 STAILQ_FOREACH(pid, parent_ids, entry) {
13726 char *pid_str;
13727 err = got_object_id_str(&pid_str, &pid->id);
13728 if (err)
13729 goto done;
13730 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13731 free(pid_str);
13733 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13734 got_object_commit_get_author_gmtoff(commit));
13735 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13736 got_object_commit_get_author(commit),
13737 (long long)got_object_commit_get_author_time(commit),
13738 gmtoff);
13740 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13741 got_object_commit_get_committer_gmtoff(commit));
13742 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13743 got_object_commit_get_committer(commit),
13744 (long long)got_object_commit_get_committer_time(commit),
13745 gmtoff);
13747 logmsg = got_object_commit_get_logmsg_raw(commit);
13748 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13749 fprintf(outfile, "%s", logmsg);
13750 done:
13751 free(id_str);
13752 got_object_commit_close(commit);
13753 return err;
13756 static const struct got_error *
13757 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13759 const struct got_error *err;
13760 struct got_tag_object *tag;
13761 char *id_str = NULL;
13762 const char *tagmsg = NULL;
13763 char gmtoff[6];
13765 err = got_object_open_as_tag(&tag, repo, id);
13766 if (err)
13767 return err;
13769 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13770 if (err)
13771 goto done;
13773 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13775 switch (got_object_tag_get_object_type(tag)) {
13776 case GOT_OBJ_TYPE_BLOB:
13777 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13778 GOT_OBJ_LABEL_BLOB);
13779 break;
13780 case GOT_OBJ_TYPE_TREE:
13781 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13782 GOT_OBJ_LABEL_TREE);
13783 break;
13784 case GOT_OBJ_TYPE_COMMIT:
13785 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13786 GOT_OBJ_LABEL_COMMIT);
13787 break;
13788 case GOT_OBJ_TYPE_TAG:
13789 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13790 GOT_OBJ_LABEL_TAG);
13791 break;
13792 default:
13793 break;
13796 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13797 got_object_tag_get_name(tag));
13799 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13800 got_object_tag_get_tagger_gmtoff(tag));
13801 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13802 got_object_tag_get_tagger(tag),
13803 (long long)got_object_tag_get_tagger_time(tag),
13804 gmtoff);
13806 tagmsg = got_object_tag_get_message(tag);
13807 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13808 fprintf(outfile, "%s", tagmsg);
13809 done:
13810 free(id_str);
13811 got_object_tag_close(tag);
13812 return err;
13815 static const struct got_error *
13816 cmd_cat(int argc, char *argv[])
13818 const struct got_error *error;
13819 struct got_repository *repo = NULL;
13820 struct got_worktree *worktree = NULL;
13821 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13822 const char *commit_id_str = NULL;
13823 struct got_object_id *id = NULL, *commit_id = NULL;
13824 struct got_commit_object *commit = NULL;
13825 int ch, obj_type, i, force_path = 0;
13826 struct got_reflist_head refs;
13827 int *pack_fds = NULL;
13829 TAILQ_INIT(&refs);
13831 #ifndef PROFILE
13832 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13833 NULL) == -1)
13834 err(1, "pledge");
13835 #endif
13837 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13838 switch (ch) {
13839 case 'c':
13840 commit_id_str = optarg;
13841 break;
13842 case 'P':
13843 force_path = 1;
13844 break;
13845 case 'r':
13846 repo_path = realpath(optarg, NULL);
13847 if (repo_path == NULL)
13848 return got_error_from_errno2("realpath",
13849 optarg);
13850 got_path_strip_trailing_slashes(repo_path);
13851 break;
13852 default:
13853 usage_cat();
13854 /* NOTREACHED */
13858 argc -= optind;
13859 argv += optind;
13861 cwd = getcwd(NULL, 0);
13862 if (cwd == NULL) {
13863 error = got_error_from_errno("getcwd");
13864 goto done;
13867 error = got_repo_pack_fds_open(&pack_fds);
13868 if (error != NULL)
13869 goto done;
13871 if (repo_path == NULL) {
13872 error = got_worktree_open(&worktree, cwd);
13873 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13874 goto done;
13875 if (worktree) {
13876 repo_path = strdup(
13877 got_worktree_get_repo_path(worktree));
13878 if (repo_path == NULL) {
13879 error = got_error_from_errno("strdup");
13880 goto done;
13883 /* Release work tree lock. */
13884 got_worktree_close(worktree);
13885 worktree = NULL;
13889 if (repo_path == NULL) {
13890 repo_path = strdup(cwd);
13891 if (repo_path == NULL)
13892 return got_error_from_errno("strdup");
13895 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13896 free(repo_path);
13897 if (error != NULL)
13898 goto done;
13900 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13901 if (error)
13902 goto done;
13904 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13905 if (error)
13906 goto done;
13908 if (commit_id_str == NULL)
13909 commit_id_str = GOT_REF_HEAD;
13910 error = got_repo_match_object_id(&commit_id, NULL,
13911 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13912 if (error)
13913 goto done;
13915 error = got_object_open_as_commit(&commit, repo, commit_id);
13916 if (error)
13917 goto done;
13919 for (i = 0; i < argc; i++) {
13920 if (force_path) {
13921 error = got_object_id_by_path(&id, repo, commit,
13922 argv[i]);
13923 if (error)
13924 break;
13925 } else {
13926 error = got_repo_match_object_id(&id, &label, argv[i],
13927 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13928 repo);
13929 if (error) {
13930 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13931 error->code != GOT_ERR_NOT_REF)
13932 break;
13933 error = got_object_id_by_path(&id, repo,
13934 commit, argv[i]);
13935 if (error)
13936 break;
13940 error = got_object_get_type(&obj_type, repo, id);
13941 if (error)
13942 break;
13944 switch (obj_type) {
13945 case GOT_OBJ_TYPE_BLOB:
13946 error = cat_blob(id, repo, stdout);
13947 break;
13948 case GOT_OBJ_TYPE_TREE:
13949 error = cat_tree(id, repo, stdout);
13950 break;
13951 case GOT_OBJ_TYPE_COMMIT:
13952 error = cat_commit(id, repo, stdout);
13953 break;
13954 case GOT_OBJ_TYPE_TAG:
13955 error = cat_tag(id, repo, stdout);
13956 break;
13957 default:
13958 error = got_error(GOT_ERR_OBJ_TYPE);
13959 break;
13961 if (error)
13962 break;
13963 free(label);
13964 label = NULL;
13965 free(id);
13966 id = NULL;
13968 done:
13969 free(label);
13970 free(id);
13971 free(commit_id);
13972 if (commit)
13973 got_object_commit_close(commit);
13974 if (worktree)
13975 got_worktree_close(worktree);
13976 if (repo) {
13977 const struct got_error *close_err = got_repo_close(repo);
13978 if (error == NULL)
13979 error = close_err;
13981 if (pack_fds) {
13982 const struct got_error *pack_err =
13983 got_repo_pack_fds_close(pack_fds);
13984 if (error == NULL)
13985 error = pack_err;
13988 got_ref_list_free(&refs);
13989 return error;
13992 __dead static void
13993 usage_info(void)
13995 fprintf(stderr, "usage: %s info [path ...]\n",
13996 getprogname());
13997 exit(1);
14000 static const struct got_error *
14001 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14002 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14003 struct got_object_id *commit_id)
14005 const struct got_error *err = NULL;
14006 char *id_str = NULL;
14007 char datebuf[128];
14008 struct tm mytm, *tm;
14009 struct got_pathlist_head *paths = arg;
14010 struct got_pathlist_entry *pe;
14013 * Clear error indication from any of the path arguments which
14014 * would cause this file index entry to be displayed.
14016 TAILQ_FOREACH(pe, paths, entry) {
14017 if (got_path_cmp(path, pe->path, strlen(path),
14018 pe->path_len) == 0 ||
14019 got_path_is_child(path, pe->path, pe->path_len))
14020 pe->data = NULL; /* no error */
14023 printf(GOT_COMMIT_SEP_STR);
14024 if (S_ISLNK(mode))
14025 printf("symlink: %s\n", path);
14026 else if (S_ISREG(mode)) {
14027 printf("file: %s\n", path);
14028 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14029 } else if (S_ISDIR(mode))
14030 printf("directory: %s\n", path);
14031 else
14032 printf("something: %s\n", path);
14034 tm = localtime_r(&mtime, &mytm);
14035 if (tm == NULL)
14036 return NULL;
14037 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14038 return got_error(GOT_ERR_NO_SPACE);
14039 printf("timestamp: %s\n", datebuf);
14041 if (blob_id) {
14042 err = got_object_id_str(&id_str, blob_id);
14043 if (err)
14044 return err;
14045 printf("based on blob: %s\n", id_str);
14046 free(id_str);
14049 if (staged_blob_id) {
14050 err = got_object_id_str(&id_str, staged_blob_id);
14051 if (err)
14052 return err;
14053 printf("based on staged blob: %s\n", id_str);
14054 free(id_str);
14057 if (commit_id) {
14058 err = got_object_id_str(&id_str, commit_id);
14059 if (err)
14060 return err;
14061 printf("based on commit: %s\n", id_str);
14062 free(id_str);
14065 return NULL;
14068 static const struct got_error *
14069 cmd_info(int argc, char *argv[])
14071 const struct got_error *error = NULL;
14072 struct got_worktree *worktree = NULL;
14073 char *cwd = NULL, *id_str = NULL;
14074 struct got_pathlist_head paths;
14075 char *uuidstr = NULL;
14076 int ch, show_files = 0;
14078 TAILQ_INIT(&paths);
14080 #ifndef PROFILE
14081 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14082 NULL) == -1)
14083 err(1, "pledge");
14084 #endif
14086 while ((ch = getopt(argc, argv, "")) != -1) {
14087 switch (ch) {
14088 default:
14089 usage_info();
14090 /* NOTREACHED */
14094 argc -= optind;
14095 argv += optind;
14097 cwd = getcwd(NULL, 0);
14098 if (cwd == NULL) {
14099 error = got_error_from_errno("getcwd");
14100 goto done;
14103 error = got_worktree_open(&worktree, cwd);
14104 if (error) {
14105 if (error->code == GOT_ERR_NOT_WORKTREE)
14106 error = wrap_not_worktree_error(error, "info", cwd);
14107 goto done;
14110 #ifndef PROFILE
14111 /* Remove "wpath cpath proc exec sendfd" promises. */
14112 if (pledge("stdio rpath flock unveil", NULL) == -1)
14113 err(1, "pledge");
14114 #endif
14115 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14116 if (error)
14117 goto done;
14119 if (argc >= 1) {
14120 error = get_worktree_paths_from_argv(&paths, argc, argv,
14121 worktree);
14122 if (error)
14123 goto done;
14124 show_files = 1;
14127 error = got_object_id_str(&id_str,
14128 got_worktree_get_base_commit_id(worktree));
14129 if (error)
14130 goto done;
14132 error = got_worktree_get_uuid(&uuidstr, worktree);
14133 if (error)
14134 goto done;
14136 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14137 printf("work tree base commit: %s\n", id_str);
14138 printf("work tree path prefix: %s\n",
14139 got_worktree_get_path_prefix(worktree));
14140 printf("work tree branch reference: %s\n",
14141 got_worktree_get_head_ref_name(worktree));
14142 printf("work tree UUID: %s\n", uuidstr);
14143 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14145 if (show_files) {
14146 struct got_pathlist_entry *pe;
14147 TAILQ_FOREACH(pe, &paths, entry) {
14148 if (pe->path_len == 0)
14149 continue;
14151 * Assume this path will fail. This will be corrected
14152 * in print_path_info() in case the path does suceeed.
14154 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14156 error = got_worktree_path_info(worktree, &paths,
14157 print_path_info, &paths, check_cancelled, NULL);
14158 if (error)
14159 goto done;
14160 TAILQ_FOREACH(pe, &paths, entry) {
14161 if (pe->data != NULL) {
14162 const struct got_error *perr;
14164 perr = pe->data;
14165 error = got_error_fmt(perr->code, "%s",
14166 pe->path);
14167 break;
14171 done:
14172 if (worktree)
14173 got_worktree_close(worktree);
14174 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14175 free(cwd);
14176 free(id_str);
14177 free(uuidstr);
14178 return error;